113 lines
3.4 KiB
JavaScript
113 lines
3.4 KiB
JavaScript
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('addSale', {
|
|
description: 'Inserts a new sale for the current ticket',
|
|
accessType: 'WRITE',
|
|
accepts: [{
|
|
arg: 'id',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'The ticket id',
|
|
http: {source: 'path'}
|
|
},
|
|
{
|
|
arg: 'itemId',
|
|
type: 'number',
|
|
required: true
|
|
},
|
|
{
|
|
arg: 'quantity',
|
|
type: 'number',
|
|
required: true
|
|
}],
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/:id/addSale`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.addSale = async(ctx, id, itemId, quantity, options) => {
|
|
const $t = ctx.req.__; // $translate
|
|
const models = Self.app.models;
|
|
const myOptions = {};
|
|
let tx;
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
try {
|
|
const isEditable = await models.Ticket.isEditable(ctx, id, myOptions);
|
|
if (!isEditable)
|
|
throw new UserError(`The sales of this ticket can't be modified`);
|
|
|
|
const item = await models.Item.findById(itemId, null, myOptions);
|
|
const ticket = await models.Ticket.findById(id, {
|
|
include: {
|
|
relation: 'client',
|
|
scope: {
|
|
include: {
|
|
relation: 'salesPersonUser',
|
|
scope: {
|
|
fields: ['id', 'name']
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}, myOptions);
|
|
|
|
const itemInfo = await models.Item.getVisibleAvailable(itemId, ticket.warehouseFk, ticket.shipped, myOptions);
|
|
|
|
const isPackaging = item.family == 'EMB';
|
|
if (!isPackaging && itemInfo.available < quantity)
|
|
throw new UserError(`This item is not available`);
|
|
|
|
const newSale = await models.Sale.create({
|
|
ticketFk: id,
|
|
itemFk: item.id,
|
|
concept: item.name,
|
|
quantity: quantity
|
|
}, myOptions);
|
|
|
|
await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions);
|
|
|
|
const sale = await models.Sale.findById(newSale.id, {
|
|
include: {
|
|
relation: 'item'
|
|
}
|
|
}, myOptions);
|
|
|
|
const addition = `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`;
|
|
|
|
const salesPerson = ticket.client().salesPersonUser();
|
|
if (salesPerson) {
|
|
const origin = ctx.req.headers.origin;
|
|
|
|
const message = $t('Added sale to ticket', {
|
|
ticketId: id,
|
|
ticketUrl: `${origin}/#!/ticket/${id}/sale`,
|
|
addition: addition
|
|
});
|
|
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message);
|
|
}
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return sale;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|