order: lifecycle checks
This commit is contained in:
parent
797da91b8e
commit
f434f0e208
76
src/api/order/content-types/order/lifecycles.ts
Normal file
76
src/api/order/content-types/order/lifecycles.ts
Normal 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);
|
||||
}
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user