const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { Self.remoteMethodCtx('canBeInvoiced', { description: 'Whether the ticket can or not be invoiced', accessType: 'READ', accepts: [ { arg: 'ticketsIds', description: 'The tickets id', type: ['number'], required: true } ], returns: { arg: 'data', type: 'boolean', root: true }, http: { path: `/canBeInvoiced`, verb: 'get' } }); Self.canBeInvoiced = async(ctx, ticketsIds, options) => { const myOptions = {}; const $t = ctx.req.__; // $translate if (typeof options == 'object') Object.assign(myOptions, options); const tickets = await Self.find({ where: { id: {inq: ticketsIds} }, fields: ['id', 'refFk', 'shipped', 'totalWithVat', 'companyFk'] }, myOptions); const [firstTicket] = tickets; const companyFk = firstTicket.companyFk; const query = `SELECT COUNT(*) isSpanishCompany FROM supplier s JOIN country c ON c.id = s.countryFk AND c.code = 'ES' WHERE s.id = ?`; const [supplierCompany] = await Self.rawSql(query, [companyFk], options); const isSpanishCompany = supplierCompany?.isSpanishCompany; const [result] = await Self.rawSql('SELECT hasAnyNegativeBase() AS base', null, options); const hasAnyNegativeBase = result?.base && isSpanishCompany; if (hasAnyNegativeBase) throw new UserError($t('Negative basis of tickets', {ticketsIds: ticketsIds})); const today = Date.vnNew(); tickets.some(ticket => { const shipped = new Date(ticket.shipped); const shippingInFuture = shipped.getTime() > today.getTime(); if (shippingInFuture) throw new UserError(`Can't invoice to future`); const isInvoiced = ticket.refFk; if (isInvoiced) throw new UserError(`This ticket is already invoiced`); const priceZero = ticket.totalWithVat == 0; if (ticketsIds.length == 1 && priceZero) throw new UserError(`A ticket with an amount of zero can't be invoiced`); }); return true; }; };