const Component = require(`${appPath}/core/component`); const Report = require(`${appPath}/core/report`); const reportHeader = new Component('report-header'); const reportFooter = new Component('report-footer'); const invoiceIncoterms = new Report('invoice-incoterms'); module.exports = { name: 'invoice', async serverPrefetch() { this.invoice = await this.fetchInvoice(this.refFk); this.client = await this.fetchClient(this.refFk); this.taxes = await this.fetchTaxes(this.refFk); this.intrastat = await this.fetchIntrastat(this.refFk); this.rectified = await this.fetchRectified(this.refFk); this.hasIncoterms = await this.fetchHasIncoterms(this.refFk); const tickets = await this.fetchTickets(this.refFk); const sales = await this.fetchSales(this.refFk); const map = new Map(); for (let ticket of tickets) { ticket.sales = []; map.set(ticket.id, ticket); } for (let sale of sales) { const ticket = map.get(sale.ticketFk); if (ticket) ticket.sales.push(sale); } this.tickets = tickets; if (!this.invoice) throw new Error('Something went wrong'); }, data() { return {totalBalance: 0.00}; }, computed: { ticketsId() { const tickets = this.tickets.map(ticket => ticket.id); return tickets.join(', '); }, botanical() { let phytosanitary = []; for (let ticket of this.tickets) { for (let sale of ticket.sales) { if (sale.botanical) phytosanitary.push(sale.botanical); } } return phytosanitary.filter((item, index) => phytosanitary.indexOf(item) == index ).join(', '); }, taxTotal() { const base = this.sumTotal(this.taxes, 'base'); const vat = this.sumTotal(this.taxes, 'vat'); return base + vat; } }, methods: { fetchInvoice(refFk) { return this.findOneFromDef('invoice', [refFk]); }, fetchClient(refFk) { return this.findOneFromDef('client', [refFk]); }, fetchTickets(refFk) { return this.rawSqlFromDef('tickets', [refFk]); }, fetchSales(refFk) { return this.rawSqlFromDef('sales', [refFk, refFk]); }, fetchTaxes(refFk) { return this.rawSqlFromDef(`taxes`, [refFk]); }, fetchIntrastat(refFk) { return this.rawSqlFromDef(`intrastat`, [refFk, refFk, refFk]); }, fetchRectified(refFk) { return this.rawSqlFromDef(`rectified`, [refFk]); }, fetchHasIncoterms(refFk) { return this.findValueFromDef(`hasIncoterms`, [refFk]); }, saleImport(sale) { const price = sale.quantity * sale.price; return price * (1 - sale.discount / 100); }, ticketSubtotal(ticket) { let subTotal = 0.00; for (let sale of ticket.sales) subTotal += this.saleImport(sale); return subTotal; }, sumTotal(rows, prop) { let total = 0.00; for (let row of rows) total += parseFloat(row[prop]); return total; } }, components: { 'report-header': reportHeader.build(), 'report-footer': reportFooter.build(), 'invoice-incoterms': invoiceIncoterms.build() }, props: { refFk: { type: String } } };