96 lines
2.8 KiB
JavaScript
96 lines
2.8 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethodCtx('invoiceClient', {
|
|
description: 'Make a invoice of a client',
|
|
accessType: 'WRITE',
|
|
accepts: [
|
|
{
|
|
arg: 'clientId',
|
|
type: 'number',
|
|
description: 'The client id to invoice',
|
|
required: true
|
|
}, {
|
|
arg: 'addressId',
|
|
type: 'number',
|
|
description: 'The address id to invoice',
|
|
required: true
|
|
}, {
|
|
arg: 'invoiceDate',
|
|
type: 'date',
|
|
description: 'The invoice date',
|
|
required: true
|
|
}, {
|
|
arg: 'maxShipped',
|
|
type: 'date',
|
|
description: 'The maximum shipped date',
|
|
required: true
|
|
}, {
|
|
arg: 'companyFk',
|
|
type: 'number',
|
|
description: 'The company id to invoice',
|
|
required: true
|
|
}
|
|
],
|
|
returns: {
|
|
type: 'number',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: '/invoiceClient',
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.invoiceClient = async(ctx, options) => {
|
|
const args = ctx.args;
|
|
const models = Self.app.models;
|
|
options = typeof options == 'object'
|
|
? Object.assign({}, options) : {};
|
|
options.userId = ctx.req.accessToken.userId;
|
|
|
|
let tx;
|
|
if (!options.transaction)
|
|
tx = options.transaction = await Self.beginTransaction({});
|
|
|
|
const minShipped = Date.vnNew();
|
|
minShipped.setFullYear(args.maxShipped.getFullYear() - 1);
|
|
|
|
try {
|
|
const client = await models.Client.findById(args.clientId, {
|
|
fields: ['id', 'hasToInvoiceByAddress']
|
|
}, options);
|
|
|
|
if (client.hasToInvoiceByAddress) {
|
|
await Self.rawSql('CALL ticketToInvoiceByAddress(?, ?, ?, ?)', [
|
|
minShipped,
|
|
args.maxShipped,
|
|
args.addressId,
|
|
args.companyFk
|
|
], options);
|
|
} else {
|
|
await Self.rawSql('CALL invoiceFromClient(?, ?, ?)', [
|
|
args.maxShipped,
|
|
client.id,
|
|
args.companyFk
|
|
], options);
|
|
}
|
|
|
|
const invoiceType = 'G';
|
|
const invoiceId = await models.Ticket.makeInvoice(
|
|
ctx,
|
|
invoiceType,
|
|
args.companyFk,
|
|
args.invoiceDate,
|
|
null,
|
|
options
|
|
);
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return invoiceId;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|