order: lifecycle checks

This commit is contained in:
vchikalkin 2025-05-09 18:48:49 +03:00
parent 797da91b8e
commit f434f0e208

View File

@ -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);
}
},
};