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

99 lines
2.6 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('editLatestBuys', {
description: 'Updates a column for one or more buys',
accessType: 'WRITE',
accepts: [{
arg: 'field',
type: 'string',
required: true,
description: `the column to edit`
},
{
arg: 'newValue',
type: 'any',
required: true,
description: `The new value to save`
},
{
arg: 'lines',
type: ['object'],
required: true,
description: `the buys which will be modified`
},
{
arg: 'filter',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string'
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/editLatestBuys`,
verb: 'POST'
}
});
Self.editLatestBuys = async(ctx, field, newValue, lines, filter, options) => {
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
let modelName;
let identifier;
switch (field) {
case 'size':
case 'density':
case 'description':
case 'packingOut':
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 = [];
const value = {};
value[field] = newValue;
if (filter) {
ctx.args.filter = {where: filter, limit: null};
lines = await models.Buy.latestBuysFilter(ctx, null, myOptions);
}
const targets = lines.map(line => {
return line[identifier];
});
for (let target of targets)
promises.push(model.upsertWithWhere({id: target}, value, myOptions));
const result = await Promise.all(promises);
if (tx) await tx.commit();
return result;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};