diff --git a/src/api/order/content-types/order/lifecycles.ts b/src/api/order/content-types/order/lifecycles.ts index 3b97168..580920c 100644 --- a/src/api/order/content-types/order/lifecycles.ts +++ b/src/api/order/content-types/order/lifecycles.ts @@ -1,21 +1,23 @@ const ERR_INVALID_TIME = 'Некорректное время'; const ERR_OVERLAPPING_TIME = 'Время пересекается с другими заказами'; +const ERR_INACTIVE_CLIENT = 'Клиент не активен'; +const ERR_INACTIVE_MASTER = 'Мастер не активен'; function timeToDate(time: string) { return new Date(`1970-01-01T${time}Z`); } -function extractSlotId(slotField: any): number | null { - if (typeof slotField === 'number') { - return slotField; +function extractId(input: any): number | null { + if (typeof input === 'number') { + return input; } - if (slotField?.id) { - return slotField.id; + if (input?.id) { + return input.id; } - if (slotField?.set?.[0]?.id) { - return slotField.set[0].id; + if (input?.set?.[0]?.id) { + return input.set[0].id; } return null; @@ -24,9 +26,10 @@ function extractSlotId(slotField: any): number | null { export default { async beforeCreate(event) { const { data } = event.params; - const { time_start, time_end } = data; + const { time_start, time_end, client } = data; + const clientId = extractId(client); - const slotId = extractSlotId(data.slot); + const slotId = extractId(data.slot); if (!time_start || !time_end) { throw new Error(ERR_INVALID_TIME); @@ -36,6 +39,34 @@ export default { throw new Error(ERR_INVALID_TIME); } + const isClientActive = await strapi.db + .query('api::customer.customer') + .findOne({ + where: { + id: clientId, + active: true, + }, + }); + + if (!isClientActive) { + throw new Error(ERR_INACTIVE_CLIENT); + } + + const slot = await strapi.db.query('api::slot.slot').findOne({ + where: { + id: slotId, + }, + populate: ['master'], + }); + + const master = slot.master; + + const isMasterActive = master.active && master.role === 'master'; + + if (!isMasterActive) { + throw new Error(ERR_INACTIVE_MASTER); + } + const overlappingEntities = await strapi.db .query('api::order.order') .findMany({ @@ -46,6 +77,9 @@ export default { slot: { id: { $ne: slotId }, }, + state: { + $notIn: ['cancelled', 'completed'], + }, }, populate: ['slot'], });