import { Inject, Injectable } from '@nestjs/common'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice'; import { GetCreditNote } from '../../CreditNotes/queries/GetCreditNote.service'; import { CreditNoteWithInvoicesToApplyTransformer } from './CreditNoteWithInvoicesToApplyTransformer'; import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNoteAssociatedInvoicesToApply { /** * @param {TransformerInjectable} transformer - Transformer service. * @param {GetCreditNote} getCreditNote - Get credit note service. * @param {typeof SaleInvoice} saleInvoiceModel - Sale invoice model. */ constructor( private transformer: TransformerInjectable, private getCreditNote: GetCreditNote, @Inject(SaleInvoice.name) private saleInvoiceModel: TenantModelProxy, ) {} /** * Retrieve credit note associated invoices to apply. * @param {number} creditNoteId * @returns {Promise} */ public async getCreditAssociatedInvoicesToApply( creditNoteId: number, ): Promise { // Retrieve credit note or throw not found service error. const creditNote = await this.getCreditNote.getCreditNote(creditNoteId); // Retrieves the published due invoices that associated to the given customer. const saleInvoices = await this.saleInvoiceModel() .query() .where('customerId', creditNote.customerId) .modify('dueInvoices') .modify('published'); // Transforms the sale invoices models to POJO. return this.transformer.transform( saleInvoices, new CreditNoteWithInvoicesToApplyTransformer(), ); } }