100 lines
2.9 KiB
JavaScript
100 lines
2.9 KiB
JavaScript
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
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, options) => {
|
|
const conn = Self.dataSource.connector;
|
|
let tx;
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
try {
|
|
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, myOptions);
|
|
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'
|
|
]
|
|
}, myOptions);
|
|
|
|
if (tx) await tx.commit();
|
|
return newTravel.id;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|