import { Entity } from "./entity"; import { Pagamento } from "./pagamento"; import { Caixa } from "./caixa"; import { chain } from 'lodash'; export class Venda extends Entity { caixa: Caixa; pagamentos: Array; troco:number; constructor(json?: any, generateId?: boolean) { super(json, generateId); json = json || {}; this.pagamentos = (json.pagamentos || []).map(i => new Pagamento(i)); this.caixa = typeof json.caixa === 'object' && new Caixa(json.caixa) || json.caixa; this.troco = json.troco || 0.0; } toJson() { this.pagamentos = chain(this.pagamentos) .groupBy('modalidade') .map((value, key) => { if (key == 'DINHEIRO') return value.reduce((total, obj) => { total.modalidade = obj.modalidade; total.troco += obj.troco; total.valor += obj.valor; return total; }); return value; }) .flatten() .value() .map((pagamento: Pagamento) => Object.assign(pagamento, { valor: pagamento.valor - pagamento.troco, modalidade: pagamento.modalidade, parcelas: 1, forma_pagamento: pagamento.forma_pagamento, troco : pagamento.troco }) ); return { pagamentos: this.pagamentos, caixa: this.caixa && this.caixa._id }; } }