salix/modules/item/back/methods/item-shelving/upsertItem.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-01-30 13:00:08 +00:00
module.exports = Self => {
2024-02-19 10:18:05 +00:00
Self.remoteMethodCtx('upsertItem', {
2024-01-30 13:00:08 +00:00
description: 'Add a record or update it if it already exists.',
accessType: 'WRITE',
accepts: [{
arg: 'shelvingFk',
type: 'string',
required: true,
},
{
arg: 'items',
type: ['number'],
required: true,
description: 'array of item foreign keys'
},
{
arg: 'warehouseFk',
type: 'number',
required: true
}],
http: {
2024-02-19 10:18:05 +00:00
path: `/upsertItem`,
2024-01-30 13:00:08 +00:00
verb: 'POST'
}
});
2024-02-19 10:18:05 +00:00
Self.upsertItem = async(ctx, shelvingFk, items, warehouseFk, options) => {
2024-01-30 15:05:56 +00:00
const myOptions = {userId: ctx.req.accessToken.userId};
2024-01-30 13:00:08 +00:00
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const discardItems = new Set();
const itemCounts = items.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
2024-01-30 13:00:08 +00:00
try {
for (let item of items) {
if (!discardItems.has(item)) {
let quantity = itemCounts[item];
discardItems.add(item);
2024-01-30 13:00:08 +00:00
await Self.rawSql('CALL vn.itemShelving_add(?, ?, ?, NULL, NULL, NULL, ?)',
[shelvingFk, item, quantity, warehouseFk], myOptions
2024-01-30 13:00:08 +00:00
);
}
}
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};