99 lines
2.9 KiB
JavaScript
99 lines
2.9 KiB
JavaScript
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
const loggable = require('vn-loopback/util/log');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('cloneWithEntries', {
|
|
description: 'Clone travel',
|
|
accessType: 'WRITE',
|
|
accepts: [{
|
|
arg: 'id',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'The original travel id',
|
|
http: {source: 'path'}
|
|
}],
|
|
returns: {
|
|
type: 'object',
|
|
description: 'The new cloned travel id',
|
|
root: true,
|
|
},
|
|
http: {
|
|
path: `/:id/cloneWithEntries`,
|
|
verb: 'post'
|
|
}
|
|
});
|
|
|
|
Self.cloneWithEntries = async(ctx, id) => {
|
|
const userId = ctx.req.accessToken.userId;
|
|
const conn = Self.dataSource.connector;
|
|
const models = Self.app.models;
|
|
const travel = await Self.findById(id, {
|
|
fields: [
|
|
'id',
|
|
'shipped',
|
|
'landed',
|
|
'warehouseInFk',
|
|
'warehouseOutFk',
|
|
'agencyModeFk',
|
|
'ref'
|
|
]
|
|
});
|
|
const started = Date.vnNew();
|
|
const ended = Date.vnNew();
|
|
|
|
if (!travel)
|
|
throw new UserError('Travel not found');
|
|
|
|
let stmts = [];
|
|
let stmt;
|
|
|
|
stmt = new ParameterizedSQL(
|
|
`CALL travel_cloneWithEntries(?, ?, ?, ?, ?, ?, ?, @vTravelFk)`, [
|
|
id,
|
|
started,
|
|
ended,
|
|
travel.warehouseOutFk,
|
|
travel.warehouseInFk,
|
|
travel.ref,
|
|
travel.agencyModeFk
|
|
]
|
|
);
|
|
stmts.push(stmt);
|
|
const newTravelIndex = stmts.push('SELECT @vTravelFk AS id') - 1;
|
|
|
|
const sql = ParameterizedSQL.join(stmts, ';');
|
|
const result = await conn.executeStmt(sql);
|
|
const [lastInsert] = result[newTravelIndex];
|
|
|
|
if (!lastInsert.id)
|
|
throw new UserError('Unable to clone this travel');
|
|
|
|
const newTravel = await Self.findById(lastInsert.id, {
|
|
fields: [
|
|
'id',
|
|
'shipped',
|
|
'landed',
|
|
'warehouseInFk',
|
|
'warehouseOutFk',
|
|
'agencyModeFk',
|
|
'ref'
|
|
]
|
|
});
|
|
|
|
const oldProperties = await loggable.translateValues(Self, travel);
|
|
const newProperties = await loggable.translateValues(Self, newTravel);
|
|
await models.TravelLog.create({
|
|
originFk: newTravel.id,
|
|
userFk: userId,
|
|
action: 'insert',
|
|
changedModel: 'Travel',
|
|
changedModelId: newTravel.id,
|
|
oldInstance: oldProperties,
|
|
newInstance: newProperties
|
|
});
|
|
|
|
return newTravel.id;
|
|
};
|
|
};
|