salix/modules/entry/back/methods/entry/editLatestBuys.js

92 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-08-26 14:33:47 +00:00
module.exports = Self => {
Self.remoteMethod('editLatestBuys', {
2020-08-27 15:54:43 +00:00
description: 'Updates a column for one or more buys',
2020-08-26 14:33:47 +00:00
accessType: 'WRITE',
accepts: [{
2020-09-02 11:09:30 +00:00
arg: 'field',
type: 'String',
required: true,
description: `the column to edit`
},
{
arg: 'newValue',
type: 'Any',
2020-08-26 14:33:47 +00:00
required: true,
2020-09-02 11:09:30 +00:00
description: `The new value to save`
2020-08-26 14:33:47 +00:00
},
{
arg: 'lines',
2020-08-26 14:33:47 +00:00
type: ['Object'],
required: true,
description: `the buys which will be modified`
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/editLatestBuys`,
verb: 'POST'
}
});
Self.editLatestBuys = async(field, newValue, lines, options) => {
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
2020-08-26 14:33:47 +00:00
let modelName;
let identifier;
2020-08-27 15:54:43 +00:00
2020-09-02 11:09:30 +00:00
switch (field) {
2020-08-26 14:33:47 +00:00
case 'size':
case 'density':
case 'description':
case 'packingOut':
2020-08-26 14:33:47 +00:00
modelName = 'Item';
identifier = 'itemFk';
break;
case 'packing':
case 'grouping':
case 'groupingMode':
case 'packageValue':
case 'weight':
modelName = 'Buy';
identifier = 'id';
}
const models = Self.app.models;
const model = models[modelName];
try {
const promises = [];
2020-08-26 14:33:47 +00:00
const targets = lines.map(line => {
return line[identifier];
2020-08-26 14:33:47 +00:00
});
const value = {};
2020-09-02 11:09:30 +00:00
value[field] = newValue;
2020-08-26 14:33:47 +00:00
for (let target of targets)
promises.push(model.upsertWithWhere({id: target}, value, myOptions));
const result = await Promise.all(promises);
if (tx) await tx.commit();
2020-08-26 14:33:47 +00:00
return result;
} catch (e) {
if (tx) await tx.rollback();
throw e;
2020-08-26 14:33:47 +00:00
}
};
};