109 lines
3.3 KiB
JavaScript
109 lines
3.3 KiB
JavaScript
let UserError = require('vn-loopback/util/user-error');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('confirm', {
|
|
description: '',
|
|
accessType: 'WRITE',
|
|
accepts: [{
|
|
arg: 'id',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'The request ID',
|
|
}, {
|
|
arg: 'itemFk',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'The requested item ID',
|
|
}, {
|
|
arg: 'quantity',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'The requested item quantity',
|
|
}],
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/:id/confirm`,
|
|
verb: 'post'
|
|
}
|
|
});
|
|
|
|
Self.confirm = async(ctx, options) => {
|
|
const userId = ctx.req.accessToken.userId;
|
|
const models = Self.app.models;
|
|
const $t = ctx.req.__; // $translate
|
|
const myOptions = {userId};
|
|
let tx;
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
try {
|
|
const item = await models.Item.findById(ctx.args.itemFk, null, myOptions);
|
|
if (!item)
|
|
throw new UserError(`That item doesn't exists`);
|
|
|
|
const request = await models.TicketRequest.findById(ctx.args.id, {
|
|
include: {relation: 'ticket'}
|
|
}, myOptions);
|
|
|
|
const itemStock = await models.Item.getVisibleAvailable(
|
|
ctx.args.itemFk,
|
|
request.ticket().warehouseFk,
|
|
request.ticket().shipped,
|
|
myOptions
|
|
);
|
|
|
|
const isAvailable = itemStock.available > 0;
|
|
|
|
if (!isAvailable)
|
|
throw new UserError(`This item is not available`);
|
|
|
|
if (request.saleFk)
|
|
throw new UserError(`This request already contains a sale`);
|
|
|
|
const sale = await models.Sale.create({
|
|
ticketFk: request.ticketFk,
|
|
itemFk: ctx.args.itemFk,
|
|
quantity: ctx.args.quantity,
|
|
concept: item.name
|
|
}, myOptions);
|
|
await request.updateAttributes({
|
|
saleFk: sale.id,
|
|
itemFk: sale.itemFk,
|
|
isOk: true
|
|
}, myOptions);
|
|
|
|
const query = `CALL vn.sale_calculateComponent(?, NULL)`;
|
|
await Self.rawSql(query, [sale.id], myOptions);
|
|
|
|
const origin = ctx.req.headers.origin;
|
|
const requesterId = request.requesterFk;
|
|
|
|
const message = $t('Bought units from buy request', {
|
|
quantity: sale.quantity,
|
|
concept: sale.concept,
|
|
itemId: sale.itemFk,
|
|
ticketId: sale.ticketFk,
|
|
url: `${origin}/#!/ticket/${sale.ticketFk}/summary`,
|
|
urlItem: `${origin}/#!/item/${sale.itemFk}/summary`
|
|
});
|
|
await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions);
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return sale;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|