salix/modules/agency/back/methods/zone/editPrices.js

82 lines
2.0 KiB
JavaScript

const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
Self.remoteMethod('editPrices', {
description: 'Changes the price and bonus of a delivery day',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'Number',
description: 'The zone id',
http: {source: 'path'}
},
{
arg: 'delivered',
type: 'Date',
required: true,
},
{
arg: 'price',
type: 'Number',
required: true,
},
{
arg: 'bonus',
type: 'Number',
required: true,
},
{
arg: 'option',
type: 'String',
required: true,
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/:id/editPrices`,
verb: 'POST'
}
});
Self.editPrices = async(id, delivered, price, bonus, option) => {
const models = Self.app.models;
let filter = {
where: {
zoneFk: id
}
};
let where;
let shouldPropagate = true;
if (option == 'Only this day') {
shouldPropagate = false;
where = {delivered};
} else if (option == 'From this day') {
where = {
delivered: {
gte: delivered
}
};
}
filter = mergeFilters(filter, {where});
const days = await models.ZoneCalendar.find(filter);
const areAllFromSameZone = days.every(day => day.zoneFk === id);
if (!areAllFromSameZone)
throw new UserError('All delivery days must belong to the same zone');
if (shouldPropagate) {
const zone = await models.Zone.findById(id);
zone.updateAttributes({price, bonus});
}
return models.ZoneCalendar.updateAll(filter.where, {price, bonus});
};
};