salix/modules/zone/back/methods/zone/clone.js

83 lines
2.4 KiB
JavaScript

module.exports = Self => {
Self.remoteMethod('clone', {
description: 'Clone zone and all its properties including geolocations',
accessType: 'WRITE',
accepts: {
arg: 'id',
type: 'number',
required: true,
description: 'Zone id',
http: {source: 'path'}
},
returns: {
root: true,
type: 'object'
},
http: {
path: '/:id/clone',
verb: 'POST'
}
});
Self.clone = async(id, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
// Find original zone
const zone = await models.Zone.findOne({
fields: [
'name',
'hour',
'agencyModeFk',
'travelingDays',
'price',
'bonus',
'isVolumetric'],
where: {id}
}, myOptions);
// Find all original included geolocations
const includedGeo = await models.ZoneIncluded.find({
fields: ['geoFk', 'isIncluded'],
where: {zoneFk: id}
}, myOptions);
// Find all original selected days
const calendarDays = await models.ZoneEvent.find({
fields: {id: false},
where: {zoneFk: id}
}, myOptions);
const newZone = await Self.create(zone, myOptions);
const newIncludedGeo = includedGeo.map(included => {
included.zoneFk = newZone.id;
return included;
});
const newCalendarDays = calendarDays.map(day => {
day.zoneFk = newZone.id;
return day;
});
await models.ZoneIncluded.create(newIncludedGeo, myOptions);
await models.ZoneEvent.create(newCalendarDays, myOptions);
if (tx) await tx.commit();
return newZone;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};