98 lines
3.0 KiB
JavaScript
98 lines
3.0 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethodCtx('clientsToInvoice', {
|
|
description: 'Get the clients to make global invoicing',
|
|
accessType: 'WRITE',
|
|
accepts: [
|
|
{
|
|
arg: 'clientId',
|
|
type: 'number',
|
|
description: 'The client id'
|
|
}, {
|
|
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: 'Object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: '/clientsToInvoice',
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.clientsToInvoice = async(ctx, clientId, invoiceDate, maxShipped, companyFk, options) => {
|
|
let tx;
|
|
const myOptions = {userId: ctx.req.accessToken.userId};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
try {
|
|
// Packaging liquidation
|
|
const vIsAllInvoiceable = false;
|
|
await Self.rawSql('CALL ticketPackaging_add(?, ?, ?, ?)', [
|
|
clientId,
|
|
invoiceDate,
|
|
companyFk,
|
|
vIsAllInvoiceable
|
|
], myOptions);
|
|
|
|
const minShipped = Date.vnNew();
|
|
minShipped.setFullYear(maxShipped.getFullYear() - 1);
|
|
|
|
const query = `
|
|
SELECT c.id clientId,
|
|
c.name clientName,
|
|
a.id,
|
|
a.nickname
|
|
FROM ticket t
|
|
JOIN address a ON a.id = t.addressFk
|
|
JOIN client c ON c.id = t.clientFk
|
|
WHERE t.refFk IS NULL
|
|
AND t.shipped BETWEEN ? AND util.dayEnd(?)
|
|
AND (t.clientFk = ? OR ? IS NULL )
|
|
AND t.companyFk = ?
|
|
AND c.hasToInvoice
|
|
AND c.isTaxDataChecked
|
|
AND c.isActive
|
|
AND NOT t.isDeleted
|
|
GROUP BY c.id, IF(c.hasToInvoiceByAddress, a.id, TRUE)
|
|
HAVING SUM(t.totalWithVat) > 0;`;
|
|
|
|
const addresses = await Self.rawSql(query, [
|
|
minShipped,
|
|
maxShipped,
|
|
clientId,
|
|
clientId,
|
|
companyFk
|
|
], myOptions);
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return addresses;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|