salix/modules/route/back/methods/roadmap/clone.js

77 lines
2.2 KiB
JavaScript
Raw Normal View History

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('clone', {
description: 'Clones the selected routes',
accessType: 'WRITE',
accepts: [
{
arg: 'ids',
type: ['number'],
required: true,
description: 'The routes ids to clone'
},
{
arg: 'etd',
type: 'date',
required: true,
description: 'The estimated time of departure for all roadmaps'
}
],
returns: {
type: ['Object'],
root: true
},
http: {
path: `/clone`,
verb: 'POST'
}
});
Self.clone = async(ids, etd) => {
const tx = await Self.beginTransaction({});
try {
const models = Self.app.models;
const options = {transaction: tx};
const originalRoadmaps = await models.Roadmap.find({
where: {id: {inq: ids}},
fields: [
'id',
'name',
'supplierFk',
2024-05-24 13:14:20 +00:00
'etd'],
include: [{
2024-05-24 13:14:20 +00:00
relation: 'roadmapStop',
scope: {
2024-05-24 13:14:20 +00:00
fields: ['roadmapFk', 'addressFk', 'eta', 'description']
}
}]
}, options);
if (ids.length != originalRoadmaps.length)
throw new UserError(`The amount of roadmaps found don't match`);
for (const roadmap of originalRoadmaps) {
roadmap.id = undefined;
roadmap.etd = etd;
const clone = await models.Roadmap.create(roadmap, options);
2024-05-16 08:20:08 +00:00
const roadmapStops = roadmap.roadmapStop();
roadmapStops.map(roadmapStop => {
roadmapStop.roadmapFk = clone.id;
return roadmapStop;
});
2024-05-20 11:27:38 +00:00
await models.RoadmapStop.create(roadmapStops, options);
}
await tx.commit();
return true;
} catch (e) {
await tx.rollback();
throw e;
}
};
};