salix/modules/claim/back/methods/claim/createFromSales.js

117 lines
3.7 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('createFromSales', {
description: 'Create a claim',
accepts: [
{
arg: 'ticketId',
type: 'number',
required: true,
description: 'The origin ticket id'
},
{
arg: 'sales',
type: ['object'],
required: true,
description: 'The claimed sales'
}
],
returns: {
type: 'object',
root: true
},
http: {
path: `/createFromSales`,
verb: 'post'
}
});
Self.createFromSales = async(ctx, ticketId, sales, options) => {
const $t = ctx.req.__; // $translate
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const userId = ctx.req.accessToken.userId;
try {
const ticket = await models.Ticket.findById(ticketId, {
include: {
relation: 'client',
scope: {
include: {
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
}
}
}
}, myOptions);
const landedPlusWeek = new Date(ticket.landed);
landedPlusWeek.setDate(landedPlusWeek.getDate() + 7);
const isClaimable = landedPlusWeek >= Date.vnNew();
const canCreateClaimAfterDeadline =
await models.ACL.checkAccessAcl(ctx, 'Claim', 'createAfterDeadline', 'WRITE');
if (ticket.isDeleted)
throw new UserError(`You can't create a claim for a removed ticket`);
if (!isClaimable && !canCreateClaimAfterDeadline)
throw new UserError(`You can't create a claim from a ticket delivered more than seven days ago`);
const newClaim = await Self.create({
ticketFk: ticketId,
clientFk: ticket.clientFk,
ticketCreated: ticket.shipped,
workerFk: userId
}, myOptions);
let changesMade = '';
const promises = [];
for (const sale of sales) {
const newClaimBeginning = models.ClaimBeginning.create({
saleFk: sale.id,
claimFk: newClaim.id,
}, myOptions);
promises.push(newClaimBeginning);
changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`;
}
await Promise.all(promises);
const salesPerson = ticket.client().salesPersonUser();
if (salesPerson) {
const url = await Self.app.models.Url.getUrl();
const message = $t('Created claim', {
claimId: newClaim.id,
ticketId: ticketId,
ticketUrl: `${url}ticket/${ticketId}/sale`,
claimUrl: `${url}claim/${newClaim.id}/summary`,
changes: changesMade
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message);
}
if (tx) await tx.commit();
return newClaim;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};