diff --git a/src/api/slot/content-types/slot/lifecycles.ts b/src/api/slot/content-types/slot/lifecycles.ts new file mode 100644 index 0000000..8602199 --- /dev/null +++ b/src/api/slot/content-types/slot/lifecycles.ts @@ -0,0 +1,49 @@ +export default { + async beforeUpdate(event) { + const { data, where } = event.params; + const { id: entityId } = where; + const { time_start, time_end } = data; + + if (!time_start || !time_end) { + throw new Error('Не указано время начала или окончания'); + } + + const startTime = new Date(`1970-01-01T${time_start}Z`); + const endTime = new Date(`1970-01-01T${time_end}Z`); + + if (startTime >= endTime) { + throw new Error('Время начала должно быть раньше времени окончания'); + } + + const existingEntity = await strapi.db.query('api::slot.slot').findOne({ + where: { id: entityId }, + select: ['date', 'documentId'], + }); + + if (!existingEntity) { + throw new Error('Запись не найдена'); + } + + const { date, documentId } = existingEntity; + + const overlappingEntities = await strapi.db + .query('api::slot.slot') + .findMany({ + where: { + date, + id: { $ne: entityId }, + documentId: { $ne: documentId }, + time_start: { $lt: time_end }, + time_end: { $gt: time_start }, + }, + }); + + console.log('🔍 Пересечения:', overlappingEntities); + + if (overlappingEntities.length > 0) { + throw new Error( + 'Выбранное время пересекается с существующими бронированиями', + ); + } + }, +};