diff --git a/src/api/order/content-types/order/lifecycles.ts b/src/api/order/content-types/order/lifecycles.ts new file mode 100644 index 0000000..8a46394 --- /dev/null +++ b/src/api/order/content-types/order/lifecycles.ts @@ -0,0 +1,76 @@ +const ERR_INVALID_TIME = 'Некорректное время'; +const ERR_OVERLAPPING_TIME = 'Время пересекается с другими заказами'; + +function timeToDate(time: string) { + return new Date(`1970-01-01T${time}Z`); +} + +export default { + async beforeCreate(event) { + const { data } = event.params; + const { time_start, time_end, date } = data; + + if (!time_start || !time_end) { + throw new Error(ERR_INVALID_TIME); + } + + if (timeToDate(time_start) >= timeToDate(time_end)) { + throw new Error(ERR_INVALID_TIME); + } + + const overlappingEntities = await strapi.db + .query('api::order.order') + .findMany({ + where: { + date, + documentId: { $ne: data.documentId }, + time_start: { $lt: time_end }, + time_end: { $gt: time_start }, + }, + }); + + if (overlappingEntities.length > 0) { + throw new Error(ERR_OVERLAPPING_TIME); + } + }, + 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(ERR_INVALID_TIME); + } + + if (timeToDate(time_start) >= timeToDate(time_end)) { + throw new Error(ERR_INVALID_TIME); + } + + const existingEntity = await strapi.db.query('api::order.order').findOne({ + where: { id: entityId }, + select: ['date', 'documentId'], + }); + + if (!existingEntity) { + throw new Error('Запись не найдена'); + } + + const { date, documentId } = existingEntity; + + const overlappingEntities = await strapi.db + .query('api::order.order') + .findMany({ + where: { + date, + id: { $ne: entityId }, + documentId: { $ne: documentId }, + time_start: { $lt: time_end }, + time_end: { $gt: time_start }, + }, + }); + + if (overlappingEntities.length > 0) { + throw new Error(ERR_OVERLAPPING_TIME); + } + }, +};