mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 05:40:31 +00:00
refactor: migrate credit note and vendor credit services to nestjs
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CreateCreditNoteService } from './commands/CreateCreditNote.service';
|
||||
import { CreateRefundCreditNoteService } from './commands/CreateRefundCreditNote.service';
|
||||
import { DeleteCreditNoteService } from './commands/DeleteCreditNote.service';
|
||||
import { EditCreditNoteService } from './commands/EditCreditNote.service';
|
||||
import { OpenCreditNoteService } from './commands/OpenCreditNote.service';
|
||||
import { GetCreditNotePdf } from './queries/GetCreditNotePdf.serivce';
|
||||
import {
|
||||
ICreditNoteEditDTO,
|
||||
ICreditNoteNewDTO,
|
||||
ICreditNoteRefundDTO,
|
||||
} from './types/CreditNotes.types';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteApplication {
|
||||
constructor(
|
||||
private createCreditNoteService: CreateCreditNoteService,
|
||||
private createRefundCreditNoteService: CreateRefundCreditNoteService,
|
||||
private editCreditNoteService: EditCreditNoteService,
|
||||
private openCreditNoteService: OpenCreditNoteService,
|
||||
private deleteCreditNoteService: DeleteCreditNoteService,
|
||||
private getCreditNotePdfService: GetCreditNotePdf,
|
||||
) {}
|
||||
|
||||
createCreditNote(creditNoteDTO: ICreditNoteNewDTO) {
|
||||
return this.createCreditNoteService.creditCreditNote(creditNoteDTO);
|
||||
}
|
||||
|
||||
editCreditNote(creditNoteId: number, creditNoteDTO: ICreditNoteEditDTO) {
|
||||
return this.editCreditNoteService.editCreditNote(
|
||||
creditNoteId,
|
||||
creditNoteDTO,
|
||||
);
|
||||
}
|
||||
|
||||
openCreditNote(creditNoteId: number) {
|
||||
return this.openCreditNoteService.openCreditNote(creditNoteId);
|
||||
}
|
||||
|
||||
deleteCreditNote(creditNoteId: number) {
|
||||
return this.deleteCreditNoteService.deleteCreditNote(creditNoteId);
|
||||
}
|
||||
|
||||
createRefundCreditNote(
|
||||
creditNoteId: number,
|
||||
creditNoteDTO: ICreditNoteRefundDTO,
|
||||
) {
|
||||
return this.createRefundCreditNoteService.createCreditNoteRefund(
|
||||
creditNoteId,
|
||||
creditNoteDTO,
|
||||
);
|
||||
}
|
||||
|
||||
getCreditNotePdf(creditNoteId: number) {
|
||||
return this.getCreditNotePdfService.getCreditNotePdf(creditNoteId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Body, Controller, Delete, Param, Post, Put } from '@nestjs/common';
|
||||
import { CreditNoteApplication } from './CreditNoteApplication.service';
|
||||
import {
|
||||
ICreditNoteEditDTO,
|
||||
ICreditNoteNewDTO,
|
||||
ICreditNoteRefundDTO,
|
||||
} from './types/CreditNotes.types';
|
||||
|
||||
@Controller('credit-notes')
|
||||
export class CreditNotesController {
|
||||
/**
|
||||
* @param {CreditNoteApplication} creditNoteApplication - The credit note application service.
|
||||
*/
|
||||
constructor(private creditNoteApplication: CreditNoteApplication) {}
|
||||
|
||||
@Post()
|
||||
createCreditNote(@Body() creditNoteDTO: ICreditNoteNewDTO) {
|
||||
return this.creditNoteApplication.createCreditNote(creditNoteDTO);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
editCreditNote(
|
||||
@Param('id') creditNoteId: number,
|
||||
@Body() creditNoteDTO: ICreditNoteEditDTO,
|
||||
) {
|
||||
return this.creditNoteApplication.editCreditNote(
|
||||
creditNoteId,
|
||||
creditNoteDTO,
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':id/open')
|
||||
openCreditNote(@Param('id') creditNoteId: number) {
|
||||
return this.creditNoteApplication.openCreditNote(creditNoteId);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
deleteCreditNote(@Param('id') creditNoteId: number) {
|
||||
return this.creditNoteApplication.deleteCreditNote(creditNoteId);
|
||||
}
|
||||
|
||||
@Post(':id/refund')
|
||||
createRefundCreditNote(
|
||||
@Param('id') creditNoteId: number,
|
||||
@Body() creditNoteDTO: ICreditNoteRefundDTO,
|
||||
) {
|
||||
return this.creditNoteApplication.createRefundCreditNote(
|
||||
creditNoteId,
|
||||
creditNoteDTO,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CreateCreditNoteService } from './commands/CreateCreditNote.service';
|
||||
import { CommandCreditNoteDTOTransform } from './commands/CommandCreditNoteDTOTransform.service';
|
||||
import { CreateRefundCreditNoteService } from './commands/CreateRefundCreditNote.service';
|
||||
import { EditCreditNoteService } from './commands/EditCreditNote.service';
|
||||
import { OpenCreditNoteService } from './commands/OpenCreditNote.service';
|
||||
import { DeleteCreditNoteService } from './commands/DeleteCreditNote.service';
|
||||
import { CreditNoteApplySyncCredit } from './commands/CreditNoteApplySyncCredit.service';
|
||||
import { DeleteCustomerLinkedCreditNoteService } from './commands/DeleteCustomerLinkedCreditNote.service';
|
||||
import { CreditNoteAutoIncrementService } from './commands/CreditNoteAutoIncrement.service';
|
||||
import { CreditNoteApplication } from './CreditNoteApplication.service';
|
||||
import { CreditNotesController } from './CreditNotes.controller';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
CreateCreditNoteService,
|
||||
CommandCreditNoteDTOTransform,
|
||||
CreateRefundCreditNoteService,
|
||||
EditCreditNoteService,
|
||||
OpenCreditNoteService,
|
||||
DeleteCreditNoteService,
|
||||
CreditNoteApplySyncCredit,
|
||||
DeleteCustomerLinkedCreditNoteService,
|
||||
CreditNoteAutoIncrementService,
|
||||
CreditNoteApplication
|
||||
],
|
||||
controllers: [CreditNotesController],
|
||||
})
|
||||
export class CreditNotesModule {}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import BaseCreditNotes from '../CreditNotes';
|
||||
import { ISaleInvoice } from '@/interfaces';
|
||||
import { CreditNoteWithInvoicesToApplyTransformer } from './commands/CreditNoteWithInvoicesToApplyTransformer';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
|
||||
@Service()
|
||||
export default class GetCreditNoteAssociatedInvoicesToApply extends BaseCreditNotes {
|
||||
@Inject()
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
/**
|
||||
* Retrieve credit note associated invoices to apply.
|
||||
* @param {number} tenantId
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<ISaleInvoice[]>}
|
||||
*/
|
||||
public getCreditAssociatedInvoicesToApply = async (
|
||||
tenantId: number,
|
||||
creditNoteId: number
|
||||
): Promise<ISaleInvoice[]> => {
|
||||
const { SaleInvoice } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retireve credit note or throw not found service error.
|
||||
const creditNote = await this.getCreditNoteOrThrowError(
|
||||
tenantId,
|
||||
creditNoteId
|
||||
);
|
||||
// Retrieves the published due invoices that associated to the given customer.
|
||||
const saleInvoices = await SaleInvoice.query()
|
||||
.where('customerId', creditNote.customerId)
|
||||
.modify('dueInvoices')
|
||||
.modify('published');
|
||||
|
||||
// Transformes the sale invoices models to POJO.
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
saleInvoices,
|
||||
new CreditNoteWithInvoicesToApplyTransformer()
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import moment from 'moment';
|
||||
import { omit } from 'lodash';
|
||||
import * as R from 'ramda';
|
||||
import composeAsync from 'async/compose';
|
||||
import { ERRORS } from '../constants';
|
||||
import {
|
||||
ICreditNote,
|
||||
ICreditNoteEditDTO,
|
||||
ICreditNoteEntryNewDTO,
|
||||
ICreditNoteNewDTO,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service';
|
||||
import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations/BranchTransactionDTOTransform';
|
||||
import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform';
|
||||
import { BrandingTemplateDTOTransformer } from '../../PdfTemplate/BrandingTemplateDTOTransformer';
|
||||
import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index';
|
||||
import { CreditNoteAutoIncrementService } from './CreditNoteAutoIncrement.service';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
|
||||
@Injectable()
|
||||
export class CommandCreditNoteDTOTransform {
|
||||
/**
|
||||
* @param {ItemsEntriesService} itemsEntriesService - The items entries service.
|
||||
* @param {BranchTransactionDTOTransformer} branchDTOTransform - The branch transaction DTO transformer.
|
||||
* @param {WarehouseTransactionDTOTransform} warehouseDTOTransform - The warehouse transaction DTO transformer.
|
||||
* @param {BrandingTemplateDTOTransformer} brandingTemplatesTransformer - The branding template DTO transformer.
|
||||
* @param {CreditNoteAutoIncrementService} creditNoteAutoIncrement - The credit note auto increment service.
|
||||
*/
|
||||
constructor(
|
||||
private readonly itemsEntriesService: ItemsEntriesService,
|
||||
private readonly branchDTOTransform: BranchTransactionDTOTransformer,
|
||||
private readonly warehouseDTOTransform: WarehouseTransactionDTOTransform,
|
||||
private readonly brandingTemplatesTransformer: BrandingTemplateDTOTransformer,
|
||||
private readonly creditNoteAutoIncrement: CreditNoteAutoIncrementService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Transformes the credit/edit DTO to model.
|
||||
* @param {ICreditNoteNewDTO | ICreditNoteEditDTO} creditNoteDTO
|
||||
* @param {string} customerCurrencyCode -
|
||||
*/
|
||||
public transformCreateEditDTOToModel = async (
|
||||
creditNoteDTO: ICreditNoteNewDTO | ICreditNoteEditDTO,
|
||||
customerCurrencyCode: string,
|
||||
oldCreditNote?: CreditNote,
|
||||
): Promise<CreditNote> => {
|
||||
// Retrieve the total amount of the given items entries.
|
||||
const amount = this.itemsEntriesService.getTotalItemsEntries(
|
||||
creditNoteDTO.entries,
|
||||
);
|
||||
const entries = R.compose(
|
||||
// Associate the default index to each item entry.
|
||||
assocItemEntriesDefaultIndex,
|
||||
|
||||
// Associate the reference type to credit note entries.
|
||||
R.map((entry: ICreditNoteEntryNewDTO) => ({
|
||||
...entry,
|
||||
referenceType: 'CreditNote',
|
||||
})),
|
||||
)(creditNoteDTO.entries);
|
||||
|
||||
// Retreive the next credit note number.
|
||||
const autoNextNumber = this.creditNoteAutoIncrement.getNextCreditNumber();
|
||||
|
||||
// Detarmines the credit note number.
|
||||
const creditNoteNumber =
|
||||
creditNoteDTO.creditNoteNumber ||
|
||||
oldCreditNote?.creditNoteNumber ||
|
||||
autoNextNumber;
|
||||
|
||||
const initialDTO = {
|
||||
...omit(creditNoteDTO, ['open', 'attachments']),
|
||||
creditNoteNumber,
|
||||
amount,
|
||||
currencyCode: customerCurrencyCode,
|
||||
exchangeRate: creditNoteDTO.exchangeRate || 1,
|
||||
entries,
|
||||
...(creditNoteDTO.open &&
|
||||
!oldCreditNote?.openedAt && {
|
||||
openedAt: moment().toMySqlDateTime(),
|
||||
}),
|
||||
refundedAmount: 0,
|
||||
invoicesAmount: 0,
|
||||
};
|
||||
const initialAsyncDTO = await composeAsync(
|
||||
// Assigns the default branding template id to the invoice DTO.
|
||||
this.brandingTemplatesTransformer.assocDefaultBrandingTemplate(
|
||||
'CreditNote',
|
||||
),
|
||||
)(initialDTO);
|
||||
|
||||
return R.compose(
|
||||
this.branchDTOTransform.transformDTO<ICreditNote>,
|
||||
this.warehouseDTOTransform.transformDTO<ICreditNote>,
|
||||
)(initialAsyncDTO);
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the credit note remaining amount.
|
||||
* @param {ICreditNote} creditNote
|
||||
* @param {number} amount
|
||||
*/
|
||||
public validateCreditRemainingAmount = (
|
||||
creditNote: CreditNote,
|
||||
amount: number,
|
||||
) => {
|
||||
if (creditNote.creditsRemaining < amount) {
|
||||
throw new ServiceError(ERRORS.CREDIT_NOTE_HAS_NO_REMAINING_AMOUNT);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
ICreditNoteCreatedPayload,
|
||||
ICreditNoteCreatingPayload,
|
||||
ICreditNoteNewDTO,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { Contact } from '../../Contacts/models/Contact';
|
||||
import { CommandCreditNoteDTOTransform } from './CommandCreditNoteDTOTransform.service';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class CreateCreditNoteService {
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly itemsEntriesService: ItemsEntriesService,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
private readonly contactModel: typeof Contact,
|
||||
private readonly commandCreditNoteDTOTransform: CommandCreditNoteDTOTransform,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Creates a new credit note.
|
||||
* @param creditNoteDTO
|
||||
*/
|
||||
public creditCreditNote = async (
|
||||
creditNoteDTO: ICreditNoteNewDTO,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// Triggers `onCreditNoteCreate` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onCreate, {
|
||||
creditNoteDTO,
|
||||
});
|
||||
// Validate customer existance.
|
||||
const customer = await this.contactModel
|
||||
.query()
|
||||
.modify('customer')
|
||||
.findById(creditNoteDTO.customerId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate items ids existance.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
creditNoteDTO.entries,
|
||||
);
|
||||
// Validate items should be sellable items.
|
||||
await this.itemsEntriesService.validateNonSellableEntriesItems(
|
||||
creditNoteDTO.entries,
|
||||
);
|
||||
// Transformes the given DTO to storage layer data.
|
||||
const creditNoteModel =
|
||||
await this.commandCreditNoteDTOTransform.transformCreateEditDTOToModel(
|
||||
creditNoteDTO,
|
||||
customer.currencyCode,
|
||||
);
|
||||
// Creates a new credit card transactions under unit-of-work envirement.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onCreditNoteCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onCreating, {
|
||||
creditNoteDTO,
|
||||
trx,
|
||||
} as ICreditNoteCreatingPayload);
|
||||
|
||||
// Upsert the credit note graph.
|
||||
const creditNote = await this.creditNoteModel.query(trx).upsertGraph({
|
||||
...creditNoteModel,
|
||||
});
|
||||
// Triggers `onCreditNoteCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onCreated, {
|
||||
creditNoteDTO,
|
||||
creditNote,
|
||||
creditNoteId: creditNote.id,
|
||||
trx,
|
||||
} as ICreditNoteCreatedPayload);
|
||||
|
||||
return creditNote;
|
||||
}, trx);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import {
|
||||
ICreditNoteRefundDTO,
|
||||
IRefundCreditNoteCreatedPayload,
|
||||
IRefundCreditNoteCreatingPayload,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { Account } from '@/modules/Accounts/models/Account.model';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { RefundCreditNote } from '../models/RefundCreditNote';
|
||||
import { events } from '@/common/events/events';
|
||||
import { CommandCreditNoteDTOTransform } from './CommandCreditNoteDTOTransform.service';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
|
||||
@Injectable()
|
||||
export class CreateRefundCreditNoteService {
|
||||
/**
|
||||
* @param {UnitOfWork} uow - The unit of work service.
|
||||
* @param {EventEmitter2} eventPublisher - The event emitter service.
|
||||
* @param {CommandCreditNoteDTOTransform} commandCreditNoteDTOTransform - The command credit note DTO transform service.
|
||||
* @param {typeof RefundCreditNote} refundCreditNoteModel - The refund credit note model.
|
||||
* @param {typeof Account} accountModel - The account model.
|
||||
* @param {typeof CreditNote} creditNoteModel - The credit note model.
|
||||
*/
|
||||
constructor(
|
||||
private uow: UnitOfWork,
|
||||
private eventPublisher: EventEmitter2,
|
||||
private commandCreditNoteDTOTransform: CommandCreditNoteDTOTransform,
|
||||
|
||||
@Inject(RefundCreditNote.name)
|
||||
private refundCreditNoteModel: typeof RefundCreditNote,
|
||||
|
||||
@Inject(Account.name) private accountModel: typeof Account,
|
||||
@Inject(CreditNote.name) private creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the credit note graph.
|
||||
* @param {number} creditNoteId
|
||||
* @param {ICreditNoteRefundDTO} newCreditNoteDTO
|
||||
* @returns {Promise<IRefundCreditNote>}
|
||||
*/
|
||||
public async createCreditNoteRefund(
|
||||
creditNoteId: number,
|
||||
newCreditNoteDTO: ICreditNoteRefundDTO,
|
||||
): Promise<RefundCreditNote> {
|
||||
// Retrieve the credit note or throw not found service error.
|
||||
const creditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Retrieve the withdrawal account or throw not found service error.
|
||||
const fromAccount = await this.accountModel
|
||||
.query()
|
||||
.findById(newCreditNoteDTO.fromAccountId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate the credit note remaining amount.
|
||||
this.commandCreditNoteDTOTransform?.validateCreditRemainingAmount(
|
||||
creditNote,
|
||||
newCreditNoteDTO.amount,
|
||||
);
|
||||
// Validate the refund withdrawal account type.
|
||||
this.commandCreditNoteDTOTransform.validateRefundWithdrawwalAccountType(
|
||||
fromAccount,
|
||||
);
|
||||
// Creates a refund credit note transaction.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onCreditNoteRefundCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onRefundCreating, {
|
||||
trx,
|
||||
creditNote,
|
||||
newCreditNoteDTO,
|
||||
} as IRefundCreditNoteCreatingPayload);
|
||||
|
||||
// Stores the refund credit note graph to the storage layer.
|
||||
const refundCreditNote = await this.refundCreditNoteModel
|
||||
.query(trx)
|
||||
.insertAndFetch({
|
||||
...this.transformDTOToModel(creditNote, newCreditNoteDTO),
|
||||
});
|
||||
|
||||
// Triggers `onCreditNoteRefundCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onRefundCreated, {
|
||||
trx,
|
||||
refundCreditNote,
|
||||
creditNote,
|
||||
} as IRefundCreditNoteCreatedPayload);
|
||||
|
||||
return refundCreditNote;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes the refund credit note DTO to model.
|
||||
* @param {number} creditNoteId
|
||||
* @param {ICreditNoteRefundDTO} creditNoteDTO
|
||||
* @returns {ICreditNote}
|
||||
*/
|
||||
private transformDTOToModel = (
|
||||
creditNote: CreditNote,
|
||||
creditNoteDTO: ICreditNoteRefundDTO,
|
||||
): RefundCreditNote => {
|
||||
return {
|
||||
creditNoteId: creditNote.id,
|
||||
currencyCode: creditNote.currencyCode,
|
||||
...creditNoteDTO,
|
||||
exchangeRate: creditNoteDTO.exchangeRate || 1,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteApplySyncCredit {
|
||||
constructor(
|
||||
@Inject(CreditNote.name)
|
||||
private creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Increment credit note invoiced amount.
|
||||
* @param {number} creditNoteId
|
||||
* @param {number} invoicesAppliedAmount
|
||||
* @param {Knex.Transaction} [trx]
|
||||
*/
|
||||
public async incrementCreditNoteInvoicedAmount(
|
||||
creditNoteId: number,
|
||||
invoicesAppliedAmount: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
await this.creditNoteModel
|
||||
.query(trx)
|
||||
.findById(creditNoteId)
|
||||
.increment('invoicesAmount', invoicesAppliedAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement credit note invoiced amount.
|
||||
* @param {number} creditNoteId
|
||||
* @param {number} invoicesAppliedAmount
|
||||
* @param {Knex.Transaction} [trx]
|
||||
*/
|
||||
public async decrementCreditNoteInvoicedAmount(
|
||||
creditNoteId: number,
|
||||
invoicesAppliedAmount: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
await this.creditNoteModel
|
||||
.query(trx)
|
||||
.findById(creditNoteId)
|
||||
.decrement('invoicesAmount', invoicesAppliedAmount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import Bluebird from 'bluebird';
|
||||
import { ICreditNoteAppliedToInvoice } from '../types/CreditNotes.types';
|
||||
import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteApplySyncInvoicesCreditedAmount {
|
||||
constructor(
|
||||
@Inject(SaleInvoice.name)
|
||||
private readonly saleInvoiceModel: typeof SaleInvoice,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Increment invoices credited amount.
|
||||
* @param {ICreditNoteAppliedToInvoice[]} creditNoteAppliedInvoices -
|
||||
* @param {Knex.Transaction} trx -
|
||||
*/
|
||||
public incrementInvoicesCreditedAmount = async (
|
||||
creditNoteAppliedInvoices: ICreditNoteAppliedToInvoice[],
|
||||
trx?: Knex.Transaction
|
||||
) => {
|
||||
await Bluebird.each(
|
||||
creditNoteAppliedInvoices,
|
||||
(creditNoteAppliedInvoice: ICreditNoteAppliedToInvoice) => {
|
||||
return this.saleInvoiceModel.query(trx)
|
||||
.where('id', creditNoteAppliedInvoice.invoiceId)
|
||||
.increment('creditedAmount', creditNoteAppliedInvoice.amount);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} invoicesIds
|
||||
* @param {number} amount -
|
||||
* @param {Knex.Transaction} knex -
|
||||
*/
|
||||
public decrementInvoiceCreditedAmount = async (
|
||||
invoiceId: number,
|
||||
amount: number,
|
||||
trx?: Knex.Transaction
|
||||
) => {
|
||||
await this.saleInvoiceModel.query(trx)
|
||||
.findById(invoiceId)
|
||||
.decrement('creditedAmount', amount);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { sumBy } from 'lodash';
|
||||
import {
|
||||
ICreditNoteAppliedToInvoice,
|
||||
ICreditNoteAppliedToInvoiceModel,
|
||||
IApplyCreditToInvoicesDTO,
|
||||
IApplyCreditToInvoicesCreatedPayload,
|
||||
ICreditNote,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { ERRORS } from '../constants';
|
||||
import { PaymentReceivedValidators } from '@/modules/PaymentReceived/commands/PaymentReceivedValidators.service';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice';
|
||||
import { events } from '@/common/events/events';
|
||||
import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteApplyToInvoices {
|
||||
/**
|
||||
* @param {PaymentReceivedValidators} paymentReceiveValidators - The payment received validators service.
|
||||
* @param {UnitOfWork} uow - The unit of work service.
|
||||
* @param {EventEmitter2} eventPublisher - The event emitter service.
|
||||
* @param {typeof CreditNoteAppliedInvoice} creditNoteAppliedInvoiceModel - The credit note applied invoice model.
|
||||
*/
|
||||
constructor(
|
||||
private readonly paymentReceiveValidators: PaymentReceivedValidators,
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
|
||||
@Inject(CreditNoteAppliedInvoice.name)
|
||||
private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Apply credit note to the given invoices.
|
||||
* @param {number} creditNoteId
|
||||
* @param {IApplyCreditToInvoicesDTO} applyCreditToInvoicesDTO
|
||||
*/
|
||||
public async applyCreditNoteToInvoices(
|
||||
creditNoteId: number,
|
||||
applyCreditToInvoicesDTO: IApplyCreditToInvoicesDTO,
|
||||
): Promise<ICreditNoteAppliedToInvoice[]> {
|
||||
// Saves the credit note or throw not found service error.
|
||||
const creditNote = await this.getCreditNoteOrThrowError(creditNoteId);
|
||||
|
||||
// Retrieve the applied invoices that associated to the credit note customer.
|
||||
const appliedInvoicesEntries =
|
||||
await this.paymentReceiveValidators.validateInvoicesIDsExistance(
|
||||
creditNote.customerId,
|
||||
applyCreditToInvoicesDTO.entries,
|
||||
);
|
||||
|
||||
// Transformes apply DTO to model.
|
||||
const creditNoteAppliedModel = this.transformApplyDTOToModel(
|
||||
applyCreditToInvoicesDTO,
|
||||
creditNote,
|
||||
);
|
||||
|
||||
// Validate invoices has remaining amount to apply.
|
||||
this.validateInvoicesRemainingAmount(
|
||||
appliedInvoicesEntries,
|
||||
creditNoteAppliedModel.amount,
|
||||
);
|
||||
// Validate the credit note remaining amount.
|
||||
this.validateCreditRemainingAmount(
|
||||
creditNote,
|
||||
creditNoteAppliedModel.amount,
|
||||
);
|
||||
|
||||
// Creates credit note apply to invoice transaction.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Saves the credit note apply to invoice graph to the storage layer.
|
||||
const creditNoteAppliedInvoices = await this.creditNoteAppliedInvoiceModel
|
||||
.query()
|
||||
.insertGraph(creditNoteAppliedModel.entries);
|
||||
|
||||
// Triggers `onCreditNoteApplyToInvoiceCreated` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.creditNote.onApplyToInvoicesCreated,
|
||||
{
|
||||
creditNote,
|
||||
creditNoteAppliedInvoices,
|
||||
trx,
|
||||
} as IApplyCreditToInvoicesCreatedPayload,
|
||||
);
|
||||
|
||||
return creditNoteAppliedInvoices;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes apply DTO to model.
|
||||
* @param {IApplyCreditToInvoicesDTO} applyDTO
|
||||
* @param {ICreditNote} creditNote
|
||||
* @returns
|
||||
*/
|
||||
private transformApplyDTOToModel = (
|
||||
applyDTO: IApplyCreditToInvoicesDTO,
|
||||
creditNote: ICreditNote,
|
||||
): ICreditNoteAppliedToInvoiceModel => {
|
||||
const entries = applyDTO.entries.map((entry) => ({
|
||||
invoiceId: entry.invoiceId,
|
||||
amount: entry.amount,
|
||||
creditNoteId: creditNote.id,
|
||||
}));
|
||||
return {
|
||||
amount: sumBy(entries, 'amount'),
|
||||
entries,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the invoice remaining amount.
|
||||
* @param {ISaleInvoice[]} invoices
|
||||
* @param {number} amount
|
||||
*/
|
||||
private validateInvoicesRemainingAmount = (
|
||||
invoices: SaleInvoice[],
|
||||
amount: number,
|
||||
) => {
|
||||
const invalidInvoices = invoices.filter(
|
||||
(invoice) => invoice.dueAmount < amount,
|
||||
);
|
||||
if (invalidInvoices.length > 0) {
|
||||
throw new ServiceError(ERRORS.INVOICES_HAS_NO_REMAINING_AMOUNT);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { AutoIncrementOrdersService } from '@/modules/AutoIncrementOrders/AutoIncrementOrders.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteAutoIncrementService {
|
||||
constructor(
|
||||
private readonly autoIncrementOrdersService: AutoIncrementOrdersService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the next unique credit number.
|
||||
* @return {string}
|
||||
*/
|
||||
public getNextCreditNumber(): string {
|
||||
return this.autoIncrementOrdersService.getNextTransactionNumber(
|
||||
'credit_note',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the credit note serial next number.
|
||||
*/
|
||||
public incrementSerialNumber() {
|
||||
return this.autoIncrementOrdersService.incrementSettingsNextNumber(
|
||||
'credit_note',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import * as R from 'ramda';
|
||||
// import {
|
||||
// AccountNormal,
|
||||
// IItemEntry,
|
||||
// ILedgerEntry,
|
||||
// ICreditNote,
|
||||
// ILedger,
|
||||
// ICreditNoteGLCommonEntry,
|
||||
// } from '@/interfaces';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
// import Ledger from '@/services/Accounting/Ledger';
|
||||
// import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
// import { SaleReceipt } from '@/models';
|
||||
|
||||
// @Service()
|
||||
// export default class CreditNoteGLEntries {
|
||||
// @Inject()
|
||||
// private tenancy: HasTenancyService;
|
||||
|
||||
// @Inject()
|
||||
// private ledgerStorage: LedgerStorageService;
|
||||
|
||||
// /**
|
||||
// * Retrieves the credit note GL.
|
||||
// * @param {ICreditNote} creditNote
|
||||
// * @param {number} receivableAccount
|
||||
// * @returns {Ledger}
|
||||
// */
|
||||
// private getCreditNoteGLedger = (
|
||||
// creditNote: ICreditNote,
|
||||
// receivableAccount: number,
|
||||
// discountAccount: number,
|
||||
// adjustmentAccount: number
|
||||
// ): Ledger => {
|
||||
// const ledgerEntries = this.getCreditNoteGLEntries(
|
||||
// creditNote,
|
||||
// receivableAccount,
|
||||
// discountAccount,
|
||||
// adjustmentAccount
|
||||
// );
|
||||
// return new Ledger(ledgerEntries);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Saves credit note GL entries.
|
||||
// * @param {number} tenantId -
|
||||
// * @param {ICreditNote} creditNote - Credit note model.
|
||||
// * @param {number} payableAccount - Payable account id.
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public saveCreditNoteGLEntries = async (
|
||||
// tenantId: number,
|
||||
// creditNote: ICreditNote,
|
||||
// payableAccount: number,
|
||||
// discountAccount: number,
|
||||
// adjustmentAccount: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// const ledger = this.getCreditNoteGLedger(
|
||||
// creditNote,
|
||||
// payableAccount,
|
||||
// discountAccount,
|
||||
// adjustmentAccount
|
||||
// );
|
||||
|
||||
// await this.ledgerStorage.commit(tenantId, ledger, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Reverts the credit note associated GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} vendorCreditId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public revertVendorCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// creditNoteId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// await this.ledgerStorage.deleteByReference(
|
||||
// tenantId,
|
||||
// creditNoteId,
|
||||
// 'CreditNote',
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Writes vendor credit associated GL entries.
|
||||
// * @param {number} tenantId - Tenant id.
|
||||
// * @param {number} creditNoteId - Credit note id.
|
||||
// * @param {Knex.Transaction} trx - Knex transactions.
|
||||
// */
|
||||
// public createVendorCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// creditNoteId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// const { CreditNote } = this.tenancy.models(tenantId);
|
||||
// const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
|
||||
// // Retrieve the credit note with associated entries and items.
|
||||
// const creditNoteWithItems = await CreditNote.query(trx)
|
||||
// .findById(creditNoteId)
|
||||
// .withGraphFetched('entries.item');
|
||||
|
||||
// // Retreive the the `accounts receivable` account based on the given currency.
|
||||
// const ARAccount = await accountRepository.findOrCreateAccountReceivable(
|
||||
// creditNoteWithItems.currencyCode
|
||||
// );
|
||||
// const discountAccount = await accountRepository.findOrCreateDiscountAccount(
|
||||
// {}
|
||||
// );
|
||||
// const adjustmentAccount =
|
||||
// await accountRepository.findOrCreateOtherChargesAccount({});
|
||||
// // Saves the credit note GL entries.
|
||||
// await this.saveCreditNoteGLEntries(
|
||||
// tenantId,
|
||||
// creditNoteWithItems,
|
||||
// ARAccount.id,
|
||||
// discountAccount.id,
|
||||
// adjustmentAccount.id,
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Edits vendor credit associated GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} creditNoteId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public editVendorCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// creditNoteId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// // Reverts vendor credit GL entries.
|
||||
// await this.revertVendorCreditGLEntries(tenantId, creditNoteId, trx);
|
||||
|
||||
// // Creates vendor credit Gl entries.
|
||||
// await this.createVendorCreditGLEntries(tenantId, creditNoteId, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieve the credit note common entry.
|
||||
// * @param {ICreditNote} creditNote -
|
||||
// * @returns {ICreditNoteGLCommonEntry}
|
||||
// */
|
||||
// private getCreditNoteCommonEntry = (
|
||||
// creditNote: ICreditNote
|
||||
// ): ICreditNoteGLCommonEntry => {
|
||||
// return {
|
||||
// date: creditNote.creditNoteDate,
|
||||
// userId: creditNote.userId,
|
||||
// currencyCode: creditNote.currencyCode,
|
||||
// exchangeRate: creditNote.exchangeRate,
|
||||
|
||||
// transactionType: 'CreditNote',
|
||||
// transactionId: creditNote.id,
|
||||
|
||||
// transactionNumber: creditNote.creditNoteNumber,
|
||||
// referenceNumber: creditNote.referenceNo,
|
||||
|
||||
// createdAt: creditNote.createdAt,
|
||||
// indexGroup: 10,
|
||||
|
||||
// credit: 0,
|
||||
// debit: 0,
|
||||
|
||||
// branchId: creditNote.branchId,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the creidt note A/R entry.
|
||||
// * @param {ICreditNote} creditNote -
|
||||
// * @param {number} ARAccountId -
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getCreditNoteAREntry = (
|
||||
// creditNote: ICreditNote,
|
||||
// ARAccountId: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getCreditNoteCommonEntry(creditNote);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// credit: creditNote.totalLocal,
|
||||
// accountId: ARAccountId,
|
||||
// contactId: creditNote.customerId,
|
||||
// index: 1,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieve the credit note item entry.
|
||||
// * @param {ICreditNote} creditNote
|
||||
// * @param {IItemEntry} entry
|
||||
// * @param {number} index
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getCreditNoteItemEntry = R.curry(
|
||||
// (
|
||||
// creditNote: ICreditNote,
|
||||
// entry: IItemEntry,
|
||||
// index: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getCreditNoteCommonEntry(creditNote);
|
||||
// const totalLocal = entry.totalExcludingTax * creditNote.exchangeRate;
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// debit: totalLocal,
|
||||
// accountId: entry.sellAccountId || entry.item.sellAccountId,
|
||||
// note: entry.description,
|
||||
// index: index + 2,
|
||||
// itemId: entry.itemId,
|
||||
// itemQuantity: entry.quantity,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// };
|
||||
// }
|
||||
// );
|
||||
|
||||
// /**
|
||||
// * Retrieves the credit note discount entry.
|
||||
// * @param {ICreditNote} creditNote
|
||||
// * @param {number} discountAccountId
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getDiscountEntry = (
|
||||
// creditNote: ICreditNote,
|
||||
// discountAccountId: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getCreditNoteCommonEntry(creditNote);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// credit: creditNote.discountAmountLocal,
|
||||
// accountId: discountAccountId,
|
||||
// index: 1,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the credit note adjustment entry.
|
||||
// * @param {ICreditNote} creditNote
|
||||
// * @param {number} adjustmentAccountId
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getAdjustmentEntry = (
|
||||
// creditNote: ICreditNote,
|
||||
// adjustmentAccountId: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getCreditNoteCommonEntry(creditNote);
|
||||
// const adjustmentAmount = Math.abs(creditNote.adjustmentLocal);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// credit: creditNote.adjustmentLocal < 0 ? adjustmentAmount : 0,
|
||||
// debit: creditNote.adjustmentLocal > 0 ? adjustmentAmount : 0,
|
||||
// accountId: adjustmentAccountId,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// index: 1,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieve the credit note GL entries.
|
||||
// * @param {ICreditNote} creditNote - Credit note.
|
||||
// * @param {IAccount} receivableAccount - Receviable account.
|
||||
// * @returns {ILedgerEntry[]} - Ledger entries.
|
||||
// */
|
||||
// public getCreditNoteGLEntries = (
|
||||
// creditNote: ICreditNote,
|
||||
// ARAccountId: number,
|
||||
// discountAccountId: number,
|
||||
// adjustmentAccountId: number
|
||||
// ): ILedgerEntry[] => {
|
||||
// const AREntry = this.getCreditNoteAREntry(creditNote, ARAccountId);
|
||||
|
||||
// const getItemEntry = this.getCreditNoteItemEntry(creditNote);
|
||||
// const itemsEntries = creditNote.entries.map(getItemEntry);
|
||||
|
||||
// const discountEntry = this.getDiscountEntry(creditNote, discountAccountId);
|
||||
// const adjustmentEntry = this.getAdjustmentEntry(
|
||||
// creditNote,
|
||||
// adjustmentAccountId
|
||||
// );
|
||||
|
||||
// return [AREntry, discountEntry, adjustmentEntry, ...itemsEntries];
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Transformer } from "@/modules/Transformer/Transformer";
|
||||
|
||||
export class CreditNoteWithInvoicesToApplyTransformer extends Transformer {
|
||||
/**
|
||||
* Include these attributes to sale invoice object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return [
|
||||
'formattedInvoiceDate',
|
||||
'formattedDueDate',
|
||||
'formattedAmount',
|
||||
'formattedDueAmount',
|
||||
'formattedPaymentAmount',
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted invoice date.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns {String}
|
||||
*/
|
||||
protected formattedInvoiceDate = (invoice): string => {
|
||||
return this.formatDate(invoice.invoiceDate);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted due date.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedDueDate = (invoice): string => {
|
||||
return this.formatDate(invoice.dueDate);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted invoice amount.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedAmount = (invoice): string => {
|
||||
return this.formatNumber(invoice.balance, {
|
||||
currencyCode: invoice.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted invoice due amount.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedDueAmount = (invoice): string => {
|
||||
return this.formatNumber(invoice.dueAmount, {
|
||||
currencyCode: invoice.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted payment amount.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedPaymentAmount = (invoice): string => {
|
||||
return this.formatNumber(invoice.paymentAmount, {
|
||||
currencyCode: invoice.currencyCode,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { ICreditNotesQueryDTO } from '@/interfaces';
|
||||
// import { Exportable } from '@/services/Export/Exportable';
|
||||
// import ListCreditNotes from '../ListCreditNotes';
|
||||
|
||||
// @Service()
|
||||
// export class CreditNotesExportable extends Exportable {
|
||||
// @Inject()
|
||||
// private getCreditNotes: ListCreditNotes;
|
||||
|
||||
// /**
|
||||
// * Retrieves the accounts data to exportable sheet.
|
||||
// * @param {number} tenantId -
|
||||
// * @param {IVendorCreditsQueryDTO} query -
|
||||
// * @returns {}
|
||||
// */
|
||||
// public exportable(tenantId: number, query: ICreditNotesQueryDTO) {
|
||||
// const filterQuery = (query) => {
|
||||
// query.withGraphFetched('branch');
|
||||
// query.withGraphFetched('warehouse');
|
||||
// };
|
||||
// const parsedQuery = {
|
||||
// sortOrder: 'desc',
|
||||
// columnSortBy: 'created_at',
|
||||
// ...query,
|
||||
// page: 1,
|
||||
// pageSize: 12000,
|
||||
// filterQuery,
|
||||
// } as ICreditNotesQueryDTO;
|
||||
|
||||
// return this.getCreditNotes
|
||||
// .getCreditNotesList(tenantId, parsedQuery)
|
||||
// .then((output) => output.creditNotes);
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,44 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { ICreditNoteNewDTO } from '@/interfaces';
|
||||
// import { Importable } from '../Import/Importable';
|
||||
// import CreateCreditNote from './commands/CreateCreditNote.service';
|
||||
|
||||
// @Service()
|
||||
// export class CreditNotesImportable extends Importable {
|
||||
// @Inject()
|
||||
// private createCreditNoteImportable: CreateCreditNote;
|
||||
|
||||
// /**
|
||||
// * Importing to account service.
|
||||
// * @param {number} tenantId
|
||||
// * @param {IAccountCreateDTO} createAccountDTO
|
||||
// * @returns
|
||||
// */
|
||||
// public importable(
|
||||
// tenantId: number,
|
||||
// createAccountDTO: ICreditNoteNewDTO,
|
||||
// trx?: Knex.Transaction
|
||||
// ) {
|
||||
// return this.createCreditNoteImportable.newCreditNote(
|
||||
// tenantId,
|
||||
// createAccountDTO,
|
||||
// trx
|
||||
// );
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Concurrrency controlling of the importing process.
|
||||
// * @returns {number}
|
||||
// */
|
||||
// public get concurrency() {
|
||||
// return 1;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Retrieves the sample data that used to download accounts sample sheet.
|
||||
// */
|
||||
// public sampleData(): any[] {
|
||||
// return [];
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,90 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { ICreditNote } from '@/interfaces';
|
||||
// import InventoryService from '@/services/Inventory/Inventory';
|
||||
// import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
|
||||
// @Service()
|
||||
// export default class CreditNoteInventoryTransactions {
|
||||
// @Inject()
|
||||
// inventoryService: InventoryService;
|
||||
|
||||
// @Inject()
|
||||
// itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
// /**
|
||||
// * Creates credit note inventory transactions.
|
||||
// * @param {number} tenantId
|
||||
// * @param {ICreditNote} creditNote
|
||||
// */
|
||||
// public createInventoryTransactions = async (
|
||||
// tenantId: number,
|
||||
// creditNote: ICreditNote,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// // Loads the inventory items entries of the given sale invoice.
|
||||
// const inventoryEntries =
|
||||
// await this.itemsEntriesService.filterInventoryEntries(
|
||||
// tenantId,
|
||||
// creditNote.entries
|
||||
// );
|
||||
// const transaction = {
|
||||
// transactionId: creditNote.id,
|
||||
// transactionType: 'CreditNote',
|
||||
// transactionNumber: creditNote.creditNoteNumber,
|
||||
// exchangeRate: creditNote.exchangeRate,
|
||||
// date: creditNote.creditNoteDate,
|
||||
// direction: 'IN',
|
||||
// entries: inventoryEntries,
|
||||
// createdAt: creditNote.createdAt,
|
||||
// warehouseId: creditNote.warehouseId,
|
||||
// };
|
||||
// // Writes inventory tranactions.
|
||||
// await this.inventoryService.recordInventoryTransactionsFromItemsEntries(
|
||||
// tenantId,
|
||||
// transaction,
|
||||
// false,
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Edits vendor credit associated inventory transactions.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} creditNoteId
|
||||
// * @param {ICreditNote} creditNote
|
||||
// * @param {Knex.Transactions} trx
|
||||
// */
|
||||
// public editInventoryTransactions = async (
|
||||
// tenantId: number,
|
||||
// creditNoteId: number,
|
||||
// creditNote: ICreditNote,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// // Deletes inventory transactions.
|
||||
// await this.deleteInventoryTransactions(tenantId, creditNoteId, trx);
|
||||
|
||||
// // Re-write inventory transactions.
|
||||
// await this.createInventoryTransactions(tenantId, creditNote, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Deletes credit note associated inventory transactions.
|
||||
// * @param {number} tenantId - Tenant id.
|
||||
// * @param {number} creditNoteId - Credit note id.
|
||||
// * @param {Knex.Transaction} trx -
|
||||
// */
|
||||
// public deleteInventoryTransactions = async (
|
||||
// tenantId: number,
|
||||
// creditNoteId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// // Deletes the inventory transactions by the given reference id and type.
|
||||
// await this.inventoryService.deleteInventoryTransactions(
|
||||
// tenantId,
|
||||
// creditNoteId,
|
||||
// 'CreditNote',
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,124 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import {
|
||||
ICreditNoteDeletedPayload,
|
||||
ICreditNoteDeletingPayload,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { ERRORS } from '../constants';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice';
|
||||
import {
|
||||
RefundCreditNote as RefundCreditNoteModel,
|
||||
} from '../models/RefundCreditNote';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { ItemEntry } from '@/modules/Items/models/ItemEntry';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class DeleteCreditNoteService {
|
||||
/**
|
||||
* @param {UnitOfWork} uow - Unit of work.
|
||||
* @param {EventEmitter2} eventPublisher - Event emitter.
|
||||
* @param {typeof CreditNote} creditNoteModel - Credit note model.
|
||||
* @param {typeof ItemEntry} itemEntryModel - Item entry model.
|
||||
* @param {typeof CreditNoteAppliedInvoice} creditNoteAppliedInvoiceModel - Credit note applied invoice model.
|
||||
* @param {typeof RefundCreditNote} refundCreditNoteModel - Refund credit note model.
|
||||
*/
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
|
||||
@Inject(ItemEntry.name)
|
||||
private readonly itemEntryModel: typeof ItemEntry,
|
||||
|
||||
@Inject(CreditNoteAppliedInvoice.name)
|
||||
private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice,
|
||||
|
||||
@Inject(RefundCreditNoteModel.name)
|
||||
private readonly refundCreditNoteModel: typeof RefundCreditNoteModel,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Deletes the given credit note transactions.
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async deleteCreditNote(creditNoteId: number): Promise<void> {
|
||||
// Retrieve the credit note or throw not found service error.
|
||||
const oldCreditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate credit note has no refund transactions.
|
||||
await this.validateCreditNoteHasNoRefundTransactions(creditNoteId);
|
||||
|
||||
// Validate credit note has no applied invoices transactions.
|
||||
await this.validateCreditNoteHasNoApplyInvoiceTransactions(creditNoteId);
|
||||
|
||||
// Deletes the credit note transactions under unit-of-work transaction.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onCreditNoteDeleting` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onDeleting, {
|
||||
trx,
|
||||
oldCreditNote,
|
||||
} as ICreditNoteDeletingPayload);
|
||||
|
||||
// Deletes the associated credit note entries.
|
||||
await this.itemEntryModel
|
||||
.query(trx)
|
||||
.where('reference_id', creditNoteId)
|
||||
.where('reference_type', 'CreditNote')
|
||||
.delete();
|
||||
|
||||
// Deletes the credit note transaction.
|
||||
await this.creditNoteModel.query(trx).findById(creditNoteId).delete();
|
||||
|
||||
// Triggers `onCreditNoteDeleted` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onDeleted, {
|
||||
oldCreditNote,
|
||||
creditNoteId,
|
||||
trx,
|
||||
} as ICreditNoteDeletedPayload);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates credit note has no associated refund transactions.
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private async validateCreditNoteHasNoRefundTransactions(
|
||||
creditNoteId: number,
|
||||
): Promise<void> {
|
||||
const refundTransactions = await this.refundCreditNoteModel
|
||||
.query()
|
||||
.where('creditNoteId', creditNoteId);
|
||||
|
||||
if (refundTransactions.length > 0) {
|
||||
throw new ServiceError(ERRORS.CREDIT_NOTE_HAS_REFUNDS_TRANSACTIONS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate credit note has no associated applied invoices transactions.
|
||||
* @param {number} creditNoteId - Credit note id.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private async validateCreditNoteHasNoApplyInvoiceTransactions(
|
||||
creditNoteId: number,
|
||||
): Promise<void> {
|
||||
const appliedTransactions = await this.creditNoteAppliedInvoiceModel
|
||||
.query()
|
||||
.where('creditNoteId', creditNoteId);
|
||||
|
||||
if (appliedTransactions.length > 0) {
|
||||
throw new ServiceError(ERRORS.CREDIT_NOTE_HAS_APPLIED_INVOICES);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { IApplyCreditToInvoicesDeletedPayload } from '../types/CreditNotes.types';
|
||||
import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { events } from '@/common/events/events';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { ERRORS } from '../constants';
|
||||
|
||||
@Injectable()
|
||||
export default class DeleteCreditNoteApplyToInvoices {
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice,
|
||||
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Apply credit note to the given invoices.
|
||||
* @param {number} creditNoteId
|
||||
* @param {IApplyCreditToInvoicesDTO} applyCreditToInvoicesDTO
|
||||
*/
|
||||
public deleteApplyCreditNoteToInvoices = async (
|
||||
applyCreditToInvoicesId: number,
|
||||
): Promise<void> => {
|
||||
const creditNoteAppliedToInvoice = await this.creditNoteAppliedInvoiceModel
|
||||
.query()
|
||||
.findById(applyCreditToInvoicesId);
|
||||
|
||||
if (!creditNoteAppliedToInvoice) {
|
||||
throw new ServiceError(ERRORS.CREDIT_NOTE_APPLY_TO_INVOICES_NOT_FOUND);
|
||||
}
|
||||
// Retrieve the credit note or throw not found service error.
|
||||
const creditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteAppliedToInvoice.creditNoteId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Creates credit note apply to invoice transaction.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Delete credit note applied to invoices.
|
||||
await this.creditNoteAppliedInvoiceModel
|
||||
.query(trx)
|
||||
.findById(applyCreditToInvoicesId)
|
||||
.delete();
|
||||
|
||||
// Triggers `onCreditNoteApplyToInvoiceDeleted` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.creditNote.onApplyToInvoicesDeleted,
|
||||
{
|
||||
creditNote,
|
||||
creditNoteAppliedToInvoice,
|
||||
trx,
|
||||
} as IApplyCreditToInvoicesDeletedPayload,
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { ERRORS } from '../constants';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
|
||||
@Injectable()
|
||||
export class DeleteCustomerLinkedCreditNoteService {
|
||||
constructor(
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Validate the given customer has no linked credit note transactions.
|
||||
* @param {number} customerId - The customer identifier.
|
||||
*/
|
||||
public async validateCustomerHasNoCreditTransaction(customerId: number) {
|
||||
const associatedCredits = await this.creditNoteModel
|
||||
.query()
|
||||
.where('customerId', customerId);
|
||||
|
||||
if (associatedCredits.length > 0) {
|
||||
throw new ServiceError(ERRORS.CUSTOMER_HAS_LINKED_CREDIT_NOTES);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { Knex } from 'knex';
|
||||
import {
|
||||
IRefundCreditNoteDeletedPayload,
|
||||
IRefundCreditNoteDeletingPayload,
|
||||
IRefundVendorCreditDeletedPayload,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { RefundCreditNote } from '../models/RefundCreditNote';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export default class DeleteRefundCreditNote {
|
||||
/**
|
||||
* @param {UnitOfWork} uow
|
||||
* @param {EventEmitter2} eventPublisher
|
||||
* @param {typeof RefundCreditNoteModel} refundCreditNoteModel
|
||||
*/
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
|
||||
@Inject(RefundCreditNote.name)
|
||||
private readonly refundCreditNoteModel: typeof RefundCreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the credit note graph.
|
||||
* @param {number} refundCreditId
|
||||
* @returns
|
||||
*/
|
||||
public deleteCreditNoteRefund = async (refundCreditId: number) => {
|
||||
// Retrieve the old credit note or throw not found service error.
|
||||
const oldRefundCredit = await this.refundCreditNoteModel
|
||||
.query()
|
||||
.findById(refundCreditId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Triggers `onCreditNoteRefundDeleted` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onRefundDelete, {
|
||||
refundCreditId,
|
||||
oldRefundCredit,
|
||||
} as IRefundCreditNoteDeletedPayload);
|
||||
|
||||
// Deletes refund credit note transactions with associated entries.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
const eventPayload = {
|
||||
trx,
|
||||
refundCreditId,
|
||||
oldRefundCredit,
|
||||
} as IRefundCreditNoteDeletedPayload | IRefundCreditNoteDeletingPayload;
|
||||
|
||||
// Triggers `onCreditNoteRefundDeleting` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.creditNote.onRefundDeleting,
|
||||
eventPayload,
|
||||
);
|
||||
|
||||
// Deletes the refund credit note graph from the storage.
|
||||
await this.refundCreditNoteModel
|
||||
.query(trx)
|
||||
.findById(refundCreditId)
|
||||
.delete();
|
||||
|
||||
// Triggers `onCreditNoteRefundDeleted` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.creditNote.onRefundDeleted,
|
||||
eventPayload as IRefundVendorCreditDeletedPayload,
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
ICreditNoteEditDTO,
|
||||
ICreditNoteEditedPayload,
|
||||
ICreditNoteEditingPayload,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { Knex } from 'knex';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { Contact } from '../../Contacts/models/Contact';
|
||||
import { ItemsEntriesService } from '../../Items/ItemsEntries.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { events } from '@/common/events/events';
|
||||
import { CommandCreditNoteDTOTransform } from './CommandCreditNoteDTOTransform.service';
|
||||
|
||||
@Injectable()
|
||||
export class EditCreditNoteService {
|
||||
/**
|
||||
* @param {typeof CreditNote} creditNoteModel - The credit note model.
|
||||
* @param {typeof Contact} contactModel - The contact model.
|
||||
* @param {CommandCreditNoteDTOTransform} commandCreditNoteDTOTransform - The command credit note DTO transform service.
|
||||
* @param {ItemsEntriesService} itemsEntriesService - The items entries service.
|
||||
* @param {EventEmitter2} eventPublisher - The event publisher.
|
||||
* @param {UnitOfWork} uow - The unit of work.
|
||||
*/
|
||||
constructor(
|
||||
@Inject(CreditNote.name) private creditNoteModel: typeof CreditNote,
|
||||
@Inject(Contact.name) private contactModel: typeof Contact,
|
||||
private commandCreditNoteDTOTransform: CommandCreditNoteDTOTransform,
|
||||
private itemsEntriesService: ItemsEntriesService,
|
||||
private eventPublisher: EventEmitter2,
|
||||
private uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Edits the given credit note.
|
||||
* @param {ICreditNoteEditDTO} creditNoteEditDTO -
|
||||
*/
|
||||
public async editCreditNote(
|
||||
creditNoteId: number,
|
||||
creditNoteEditDTO: ICreditNoteEditDTO,
|
||||
) {
|
||||
// Retrieve the sale invoice or throw not found service error.
|
||||
const oldCreditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate customer existance.
|
||||
const customer = await this.contactModel
|
||||
.query()
|
||||
.findById(creditNoteEditDTO.customerId);
|
||||
|
||||
// Validate items ids existance.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
creditNoteEditDTO.entries,
|
||||
);
|
||||
// Validate non-sellable entries items.
|
||||
await this.itemsEntriesService.validateNonSellableEntriesItems(
|
||||
creditNoteEditDTO.entries,
|
||||
);
|
||||
// Validate the items entries existance.
|
||||
await this.itemsEntriesService.validateEntriesIdsExistance(
|
||||
creditNoteId,
|
||||
'CreditNote',
|
||||
creditNoteEditDTO.entries,
|
||||
);
|
||||
// Transformes the given DTO to storage layer data.
|
||||
const creditNoteModel =
|
||||
await this.commandCreditNoteDTOTransform.transformCreateEditDTOToModel(
|
||||
creditNoteEditDTO,
|
||||
customer.currencyCode,
|
||||
oldCreditNote,
|
||||
);
|
||||
// Sales the credit note transactions with associated entries.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onCreditNoteEditing` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onEditing, {
|
||||
creditNoteEditDTO,
|
||||
oldCreditNote,
|
||||
trx,
|
||||
} as ICreditNoteEditingPayload);
|
||||
|
||||
// Saves the credit note graph to the storage.
|
||||
const creditNote = await this.creditNoteModel.query(trx).upsertGraph({
|
||||
id: creditNoteId,
|
||||
...creditNoteModel,
|
||||
});
|
||||
// Triggers `onCreditNoteEdited` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onEdited, {
|
||||
trx,
|
||||
oldCreditNote,
|
||||
creditNoteId,
|
||||
creditNote,
|
||||
creditNoteEditDTO,
|
||||
} as ICreditNoteEditedPayload);
|
||||
|
||||
return creditNote;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
ICreditNoteOpenedPayload,
|
||||
ICreditNoteOpeningPayload,
|
||||
} from '../types/CreditNotes.types';
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { ERRORS } from '../constants';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { events } from '@/common/events/events';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
|
||||
@Injectable()
|
||||
export class OpenCreditNoteService {
|
||||
/**
|
||||
* @param {EventEmitter2} eventPublisher - The event publisher.
|
||||
* @param {UnitOfWork} uow - The unit of work.
|
||||
* @param {typeof CreditNote} creditNoteModel - The credit note model.
|
||||
*/
|
||||
constructor(
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
private readonly uow: UnitOfWork,
|
||||
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Opens the given credit note.
|
||||
* @param {number} creditNoteId -
|
||||
* @returns {Promise<CreditNote>}
|
||||
*/
|
||||
public openCreditNote = async (creditNoteId: number): Promise<CreditNote> => {
|
||||
// Retrieve the sale invoice or throw not found service error.
|
||||
const oldCreditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Throw service error if the credit note is already open.
|
||||
this.throwErrorIfAlreadyOpen(oldCreditNote);
|
||||
|
||||
// Triggers `onCreditNoteOpen` event.
|
||||
this.eventPublisher.emitAsync(events.creditNote.onOpen, {
|
||||
creditNoteId,
|
||||
oldCreditNote,
|
||||
});
|
||||
// Sales the credit note transactions with associated entries.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
const eventPayload = {
|
||||
creditNoteId,
|
||||
oldCreditNote,
|
||||
trx,
|
||||
} as ICreditNoteOpeningPayload;
|
||||
|
||||
// Triggers `onCreditNoteOpening` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.creditNote.onOpening,
|
||||
eventPayload,
|
||||
);
|
||||
// Saves the credit note graph to the storage.
|
||||
const creditNote = await this.creditNoteModel
|
||||
.query(trx)
|
||||
.findById(creditNoteId)
|
||||
.update({
|
||||
openedAt: new Date(),
|
||||
});
|
||||
// Triggers `onCreditNoteOpened` event.
|
||||
await this.eventPublisher.emitAsync(events.creditNote.onOpened, {
|
||||
...eventPayload,
|
||||
creditNote,
|
||||
} as ICreditNoteOpenedPayload);
|
||||
|
||||
return creditNote;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param creditNote
|
||||
*/
|
||||
public throwErrorIfAlreadyOpen = (creditNote) => {
|
||||
if (creditNote.openedAt) {
|
||||
throw new ServiceError(ERRORS.CREDIT_NOTE_ALREADY_OPENED);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { ERRORS } from '../constants';
|
||||
import { RefundCreditNote } from '../models/RefundCreditNote';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
import { Account } from '@/modules/Accounts/models/Account.model';
|
||||
|
||||
@Injectable()
|
||||
export class RefundCreditNoteService {
|
||||
/**
|
||||
* @param {typeof RefundCreditNote} refundCreditNoteModel - The refund credit note model.
|
||||
*/
|
||||
constructor(
|
||||
@Inject(RefundCreditNote.name)
|
||||
private readonly refundCreditNoteModel: typeof RefundCreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the credit note graph.
|
||||
* @param {number} refundCreditId
|
||||
* @returns {Promise<RefundCreditNote>}
|
||||
*/
|
||||
public getCreditNoteRefundOrThrowError = async (
|
||||
refundCreditId: number,
|
||||
): Promise<RefundCreditNote> => {
|
||||
const refundCreditNote = await this.refundCreditNoteModel
|
||||
.query()
|
||||
.findById(refundCreditId);
|
||||
if (!refundCreditNote) {
|
||||
throw new ServiceError(ERRORS.REFUND_CREDIT_NOTE_NOT_FOUND);
|
||||
}
|
||||
return refundCreditNote;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the refund account type.
|
||||
* @param {Account} account
|
||||
*/
|
||||
public validateRefundWithdrawwalAccountType = (account: Account): void => {
|
||||
const supportedTypes = ['bank', 'cash', 'fixed-asset'];
|
||||
|
||||
if (supportedTypes.indexOf(account.accountType) === -1) {
|
||||
throw new ServiceError(ERRORS.ACCOUNT_INVALID_TYPE);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { AccountNormal, ILedgerEntry, IRefundCreditNote } from '@/interfaces';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
// import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
// import Ledger from '@/services/Accounting/Ledger';
|
||||
|
||||
// @Service()
|
||||
// export default class RefundCreditNoteGLEntries {
|
||||
// @Inject()
|
||||
// ledgerStorage: LedgerStorageService;
|
||||
|
||||
// @Inject()
|
||||
// tenancy: HasTenancyService;
|
||||
|
||||
// /**
|
||||
// * Retrieves the refund credit common GL entry.
|
||||
// * @param {IRefundCreditNote} refundCreditNote
|
||||
// * @returns
|
||||
// */
|
||||
// private getRefundCreditCommonGLEntry = (
|
||||
// refundCreditNote: IRefundCreditNote
|
||||
// ) => {
|
||||
// return {
|
||||
// currencyCode: refundCreditNote.currencyCode,
|
||||
// exchangeRate: refundCreditNote.exchangeRate,
|
||||
|
||||
// transactionType: 'RefundCreditNote',
|
||||
// transactionId: refundCreditNote.id,
|
||||
// date: refundCreditNote.date,
|
||||
// userId: refundCreditNote.userId,
|
||||
|
||||
// referenceNumber: refundCreditNote.referenceNo,
|
||||
|
||||
// createdAt: refundCreditNote.createdAt,
|
||||
// indexGroup: 10,
|
||||
|
||||
// credit: 0,
|
||||
// debit: 0,
|
||||
|
||||
// note: refundCreditNote.description,
|
||||
// branchId: refundCreditNote.branchId,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the refudn credit receivable GL entry.
|
||||
// * @param {IRefundCreditNote} refundCreditNote
|
||||
// * @param {number} ARAccountId
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getRefundCreditGLReceivableEntry = (
|
||||
// refundCreditNote: IRefundCreditNote,
|
||||
// ARAccountId: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getRefundCreditCommonGLEntry(refundCreditNote);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// debit: refundCreditNote.amount,
|
||||
// accountId: ARAccountId,
|
||||
// contactId: refundCreditNote.creditNote.customerId,
|
||||
// index: 1,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the refund credit withdrawal GL entry.
|
||||
// * @param {number} refundCreditNote
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getRefundCreditGLWithdrawalEntry = (
|
||||
// refundCreditNote: IRefundCreditNote
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getRefundCreditCommonGLEntry(refundCreditNote);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// credit: refundCreditNote.amount,
|
||||
// accountId: refundCreditNote.fromAccountId,
|
||||
// index: 2,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieve the refund credit note GL entries.
|
||||
// * @param {IRefundCreditNote} refundCreditNote
|
||||
// * @param {number} receivableAccount
|
||||
// * @returns {ILedgerEntry[]}
|
||||
// */
|
||||
// public getRefundCreditGLEntries(
|
||||
// refundCreditNote: IRefundCreditNote,
|
||||
// ARAccountId: number
|
||||
// ): ILedgerEntry[] {
|
||||
// const receivableEntry = this.getRefundCreditGLReceivableEntry(
|
||||
// refundCreditNote,
|
||||
// ARAccountId
|
||||
// );
|
||||
// const withdrawalEntry =
|
||||
// this.getRefundCreditGLWithdrawalEntry(refundCreditNote);
|
||||
|
||||
// return [receivableEntry, withdrawalEntry];
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Creates refund credit GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {IRefundCreditNote} refundCreditNote
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public createRefundCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// refundCreditNoteId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// const { Account, RefundCreditNote } = this.tenancy.models(tenantId);
|
||||
|
||||
// // Retrieve the refund with associated credit note.
|
||||
// const refundCreditNote = await RefundCreditNote.query(trx)
|
||||
// .findById(refundCreditNoteId)
|
||||
// .withGraphFetched('creditNote');
|
||||
|
||||
// // Receivable account A/R.
|
||||
// const receivableAccount = await Account.query().findOne(
|
||||
// 'slug',
|
||||
// 'accounts-receivable'
|
||||
// );
|
||||
// // Retrieve refund credit GL entries.
|
||||
// const refundGLEntries = this.getRefundCreditGLEntries(
|
||||
// refundCreditNote,
|
||||
// receivableAccount.id
|
||||
// );
|
||||
// const ledger = new Ledger(refundGLEntries);
|
||||
|
||||
// // Saves refund ledger entries.
|
||||
// await this.ledgerStorage.commit(tenantId, ledger, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Reverts refund credit note GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} refundCreditNoteId
|
||||
// * @param {number} receivableAccount
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public revertRefundCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// refundCreditNoteId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// await this.ledgerStorage.deleteByReference(
|
||||
// tenantId,
|
||||
// refundCreditNoteId,
|
||||
// 'RefundCreditNote',
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
|
||||
@Injectable()
|
||||
export class RefundSyncCreditNoteBalance {
|
||||
/**
|
||||
* @param {typeof CreditNote} creditNoteModel - The credit note model.
|
||||
*/
|
||||
constructor(
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Increments the refund amount of the credit note.
|
||||
* @param {number} creditNoteId - The credit note ID.
|
||||
* @param {number} amount - The amount to increment.
|
||||
* @param {Knex.Transaction} trx - The knex transaction.
|
||||
*/
|
||||
public incrementCreditNoteRefundAmount = async (
|
||||
creditNoteId: number,
|
||||
amount: number,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> => {
|
||||
await this.creditNoteModel
|
||||
.query(trx)
|
||||
.findById(creditNoteId)
|
||||
.increment('refunded_amount', amount);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrements the refund amount of the credit note.
|
||||
* @param {number} creditNoteId - The credit note ID.
|
||||
* @param {number} amount - The amount to decrement.
|
||||
* @param {Knex.Transaction} trx - The knex transaction.
|
||||
*/
|
||||
public decrementCreditNoteRefundAmount = async (
|
||||
creditNoteId: number,
|
||||
amount: number,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> => {
|
||||
await this.creditNoteModel
|
||||
.query(trx)
|
||||
.findById(creditNoteId)
|
||||
.decrement('refunded_amount', amount);
|
||||
};
|
||||
}
|
||||
132
packages/server-nest/src/modules/CreditNotes/constants.ts
Normal file
132
packages/server-nest/src/modules/CreditNotes/constants.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
export const ERRORS = {
|
||||
CREDIT_NOTE_NOT_FOUND: 'CREDIT_NOTE_NOT_FOUND',
|
||||
REFUND_CREDIT_NOTE_NOT_FOUND: 'REFUND_CREDIT_NOTE_NOT_FOUND',
|
||||
CREDIT_NOTE_ALREADY_OPENED: 'CREDIT_NOTE_ALREADY_OPENED',
|
||||
ACCOUNT_INVALID_TYPE: 'ACCOUNT_INVALID_TYPE',
|
||||
CREDIT_NOTE_HAS_NO_REMAINING_AMOUNT: 'CREDIT_NOTE_HAS_NO_REMAINING_AMOUNT',
|
||||
INVOICES_HAS_NO_REMAINING_AMOUNT: 'INVOICES_HAS_NO_REMAINING_AMOUNT',
|
||||
CREDIT_NOTE_APPLY_TO_INVOICES_NOT_FOUND:
|
||||
'CREDIT_NOTE_APPLY_TO_INVOICES_NOT_FOUND',
|
||||
CREDIT_NOTE_HAS_REFUNDS_TRANSACTIONS: 'CREDIT_NOTE_HAS_REFUNDS_TRANSACTIONS',
|
||||
CREDIT_NOTE_HAS_APPLIED_INVOICES: 'CREDIT_NOTE_HAS_APPLIED_INVOICES',
|
||||
CUSTOMER_HAS_LINKED_CREDIT_NOTES: 'CUSTOMER_HAS_LINKED_CREDIT_NOTES',
|
||||
};
|
||||
|
||||
export const DEFAULT_VIEW_COLUMNS = [];
|
||||
export const DEFAULT_VIEWS = [
|
||||
{
|
||||
name: 'credit_note.view.draft',
|
||||
slug: 'draft',
|
||||
rolesLogicExpression: '1',
|
||||
roles: [
|
||||
{ index: 1, fieldKey: 'status', comparator: 'equals', value: 'draft' },
|
||||
],
|
||||
columns: DEFAULT_VIEW_COLUMNS,
|
||||
},
|
||||
{
|
||||
name: 'credit_note.view.published',
|
||||
slug: 'published',
|
||||
rolesLogicExpression: '1',
|
||||
roles: [
|
||||
{
|
||||
index: 1,
|
||||
fieldKey: 'status',
|
||||
comparator: 'equals',
|
||||
value: 'published',
|
||||
},
|
||||
],
|
||||
columns: DEFAULT_VIEW_COLUMNS,
|
||||
},
|
||||
{
|
||||
name: 'credit_note.view.open',
|
||||
slug: 'open',
|
||||
rolesLogicExpression: '1',
|
||||
roles: [
|
||||
{
|
||||
index: 1,
|
||||
fieldKey: 'status',
|
||||
comparator: 'equals',
|
||||
value: 'open',
|
||||
},
|
||||
],
|
||||
columns: DEFAULT_VIEW_COLUMNS,
|
||||
},
|
||||
{
|
||||
name: 'credit_note.view.closed',
|
||||
slug: 'closed',
|
||||
rolesLogicExpression: '1',
|
||||
roles: [
|
||||
{
|
||||
index: 1,
|
||||
fieldKey: 'status',
|
||||
comparator: 'equals',
|
||||
value: 'closed',
|
||||
},
|
||||
],
|
||||
columns: DEFAULT_VIEW_COLUMNS,
|
||||
},
|
||||
];
|
||||
|
||||
export const defaultCreditNoteBrandingAttributes = {
|
||||
// # Colors
|
||||
primaryColor: '',
|
||||
secondaryColor: '',
|
||||
|
||||
// # Company logo
|
||||
showCompanyLogo: true,
|
||||
companyLogoKey: '',
|
||||
companyLogoUri: '',
|
||||
|
||||
// # Company name
|
||||
companyName: 'Bigcapital Technology, Inc.',
|
||||
|
||||
// # Customer address
|
||||
showCustomerAddress: true,
|
||||
customerAddress: '',
|
||||
|
||||
// # Company address
|
||||
showCompanyAddress: true,
|
||||
companyAddress: '',
|
||||
billedToLabel: 'Billed To',
|
||||
|
||||
// Total
|
||||
total: '$1000.00',
|
||||
totalLabel: 'Total',
|
||||
showTotal: true,
|
||||
|
||||
// Subtotal
|
||||
subtotal: '1000/00',
|
||||
subtotalLabel: 'Subtotal',
|
||||
showSubtotal: true,
|
||||
|
||||
// Customer note
|
||||
showCustomerNote: true,
|
||||
customerNote:
|
||||
'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.',
|
||||
customerNoteLabel: 'Customer Note',
|
||||
|
||||
// Terms & conditions
|
||||
showTermsConditions: true,
|
||||
termsConditions:
|
||||
'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.',
|
||||
termsConditionsLabel: 'Terms & Conditions',
|
||||
|
||||
lines: [
|
||||
{
|
||||
item: 'Simply dummy text',
|
||||
description: 'Simply dummy text of the printing and typesetting',
|
||||
rate: '1',
|
||||
quantity: '1000',
|
||||
total: '$1000.00',
|
||||
},
|
||||
],
|
||||
// Credit note number.
|
||||
showCreditNoteNumber: true,
|
||||
creditNoteNumberLabel: 'Credit Note Number',
|
||||
creditNoteNumebr: '346D3D40-0001',
|
||||
|
||||
// Credit note date.
|
||||
creditNoteDate: 'September 3, 2024',
|
||||
showCreditNoteDate: true,
|
||||
creditNoteDateLabel: 'Credit Note Date',
|
||||
};
|
||||
@@ -4,8 +4,17 @@ import { mixin, Model } from 'objection';
|
||||
// import CustomViewBaseModel from './CustomViewBaseModel';
|
||||
// import ModelSearchable from './ModelSearchable';
|
||||
import { BaseModel } from '@/models/Model';
|
||||
import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
|
||||
import { CreditNote } from './CreditNote';
|
||||
|
||||
export class CreditNoteAppliedInvoice extends BaseModel {
|
||||
public amount: number;
|
||||
public creditNoteId: number;
|
||||
public invoiceId: number;
|
||||
|
||||
public saleInvoice!: SaleInvoice;
|
||||
public creditNote!: CreditNote;
|
||||
|
||||
/**
|
||||
* Table name
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Model, mixin } from 'objection';
|
||||
// import TenantModel from 'models/TenantModel';
|
||||
// import ModelSetting from './ModelSetting';
|
||||
// import CustomViewBaseModel from './CustomViewBaseModel';
|
||||
// import ModelSearchable from './ModelSearchable';
|
||||
import { BaseModel } from '@/models/Model';
|
||||
|
||||
export class RefundCreditNote extends BaseModel{
|
||||
date: Date;
|
||||
referenceNo: string;
|
||||
amount: number;
|
||||
currencyCode: string;
|
||||
exchangeRate: number;
|
||||
fromAccountId: number;
|
||||
description: string;
|
||||
creditNoteId: number;
|
||||
|
||||
userId?: number;
|
||||
branchId?: number;
|
||||
|
||||
createdAt?: Date | null;
|
||||
|
||||
/**
|
||||
* Table name.
|
||||
*/
|
||||
static get tableName() {
|
||||
return 'refund_credit_note_transactions';
|
||||
}
|
||||
|
||||
/**
|
||||
* Timestamps columns.
|
||||
*/
|
||||
get timestamps() {
|
||||
return ['created_at', 'updated_at'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Relationship mapping.
|
||||
*/
|
||||
static get relationMappings() {
|
||||
const { Account } = require('../../Accounts/models/Account.model');
|
||||
const { CreditNote } = require('../../CreditNotes/models/CreditNote');
|
||||
|
||||
return {
|
||||
fromAccount: {
|
||||
relation: Model.BelongsToOneRelation,
|
||||
modelClass: Account,
|
||||
join: {
|
||||
from: 'refund_credit_note_transactions.fromAccountId',
|
||||
to: 'accounts.id',
|
||||
},
|
||||
},
|
||||
creditNote: {
|
||||
relation: Model.BelongsToOneRelation,
|
||||
modelClass: CreditNote,
|
||||
join: {
|
||||
from: 'refund_credit_note_transactions.creditNoteId',
|
||||
to: 'credit_notes.id',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Transformer } from '../../Transformer/Transformer';
|
||||
import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice';
|
||||
|
||||
export class CreditNoteAppliedInvoiceTransformer extends Transformer {
|
||||
/**
|
||||
* Includeded attributes.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return [
|
||||
'formttedAmount',
|
||||
'creditNoteNumber',
|
||||
'creditNoteDate',
|
||||
'invoiceNumber',
|
||||
'invoiceReferenceNo',
|
||||
'formattedCreditNoteDate',
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclude attributes.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
public excludeAttributes = (): string[] => {
|
||||
return ['saleInvoice', 'creditNote'];
|
||||
};
|
||||
|
||||
public formttedAmount = (item: CreditNoteAppliedInvoice) => {
|
||||
return this.formatNumber(item.amount, {
|
||||
currencyCode: item.creditNote.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
public creditNoteNumber = (item: CreditNoteAppliedInvoice) => {
|
||||
return item.creditNote.creditNoteNumber;
|
||||
};
|
||||
|
||||
public creditNoteDate = (item: CreditNoteAppliedInvoice) => {
|
||||
return item.creditNote.creditNoteDate;
|
||||
};
|
||||
|
||||
public invoiceNumber = (item: CreditNoteAppliedInvoice) => {
|
||||
return item.saleInvoice.invoiceNo;
|
||||
};
|
||||
|
||||
public invoiceReferenceNo = (item: CreditNoteAppliedInvoice) => {
|
||||
return item.saleInvoice.referenceNo;
|
||||
};
|
||||
|
||||
public formattedCreditNoteDate = (item: CreditNoteAppliedInvoice) => {
|
||||
return this.formatDate(item.creditNote.creditNoteDate);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { defaultCreditNoteBrandingAttributes } from '../constants';
|
||||
import { GetPdfTemplateService } from '../../PdfTemplate/queries/GetPdfTemplate.service';
|
||||
import { GetOrganizationBrandingAttributesService } from '../../PdfTemplate/queries/GetOrganizationBrandingAttributes.service';
|
||||
import { mergePdfTemplateWithDefaultAttributes } from '../../SaleInvoices/utils';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteBrandingTemplate {
|
||||
constructor(
|
||||
private getPdfTemplateService: GetPdfTemplateService,
|
||||
private getOrgBrandingAttributes: GetOrganizationBrandingAttributesService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieves the credit note branding template.
|
||||
* @param {number} templateId
|
||||
* @returns {}
|
||||
*/
|
||||
public async getCreditNoteBrandingTemplate(templateId: number) {
|
||||
const template =
|
||||
await this.getPdfTemplateService.getPdfTemplate(templateId);
|
||||
|
||||
// Retrieves the organization branding attributes.
|
||||
const commonOrgBrandingAttrs =
|
||||
await this.getOrgBrandingAttributes.getOrganizationBrandingAttributes();
|
||||
|
||||
// Merges the default branding attributes with common organization branding attrs.
|
||||
const organizationBrandingAttrs = {
|
||||
...defaultCreditNoteBrandingAttributes,
|
||||
...commonOrgBrandingAttrs,
|
||||
};
|
||||
const brandingTemplateAttrs = {
|
||||
...template.attributes,
|
||||
companyLogoUri: template.companyLogoUri,
|
||||
};
|
||||
const attributes = mergePdfTemplateWithDefaultAttributes(
|
||||
brandingTemplateAttrs,
|
||||
organizationBrandingAttrs,
|
||||
);
|
||||
return {
|
||||
...template,
|
||||
attributes,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { AttachmentTransformer } from "@/modules/Attachments/Attachment.transformer";
|
||||
import { ItemEntryTransformer } from "@/modules/TransactionItemEntry/ItemEntry.transformer";
|
||||
import { Transformer } from "@/modules/Transformer/Transformer";
|
||||
|
||||
export class CreditNoteTransformer extends Transformer {
|
||||
/**
|
||||
* Include these attributes to sale credit note object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return [
|
||||
'formattedCreditsRemaining',
|
||||
'formattedCreditNoteDate',
|
||||
'formattedCreatedAt',
|
||||
'formattedCreatedAt',
|
||||
'formattedAmount',
|
||||
'formattedCreditsUsed',
|
||||
'formattedSubtotal',
|
||||
|
||||
'discountAmountFormatted',
|
||||
'discountAmountLocalFormatted',
|
||||
|
||||
'discountPercentageFormatted',
|
||||
|
||||
'adjustmentFormatted',
|
||||
'adjustmentLocalFormatted',
|
||||
|
||||
'totalFormatted',
|
||||
'totalLocalFormatted',
|
||||
|
||||
'entries',
|
||||
'attachments',
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted credit note date.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {String}
|
||||
*/
|
||||
protected formattedCreditNoteDate = (credit): string => {
|
||||
return this.formatDate(credit.creditNoteDate);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted created at date.
|
||||
* @param credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedCreatedAt = (credit): string => {
|
||||
return this.formatDate(credit.createdAt);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted invoice amount.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedAmount = (credit): string => {
|
||||
return this.formatNumber(credit.amount, {
|
||||
currencyCode: credit.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted credits remaining.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedCreditsRemaining = (credit) => {
|
||||
return this.formatNumber(credit.creditsRemaining, {
|
||||
currencyCode: credit.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted credits used.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedCreditsUsed = (credit) => {
|
||||
return this.formatNumber(credit.creditsUsed, {
|
||||
currencyCode: credit.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted subtotal.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedSubtotal = (credit): string => {
|
||||
return this.formatNumber(credit.amount, { money: false });
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves formatted discount amount.
|
||||
* @param credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected discountAmountFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.discountAmount, {
|
||||
currencyCode: credit.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted discount amount in local currency.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected discountAmountLocalFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.discountAmountLocal, {
|
||||
currencyCode: credit.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves formatted discount percentage.
|
||||
* @param credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected discountPercentageFormatted = (credit): string => {
|
||||
return credit.discountPercentage ? `${credit.discountPercentage}%` : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves formatted adjustment amount.
|
||||
* @param credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected adjustmentFormatted = (credit): string => {
|
||||
return this.formatMoney(credit.adjustment, {
|
||||
currencyCode: credit.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted adjustment amount in local currency.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected adjustmentLocalFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.adjustmentLocal, {
|
||||
currencyCode: this.context.organization.baseCurrency,
|
||||
excerptZero: true,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted total.
|
||||
* @param credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected totalFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.total, {
|
||||
currencyCode: credit.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted total in local currency.
|
||||
* @param credit
|
||||
* @returns {string}
|
||||
*/
|
||||
protected totalLocalFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.totalLocal, {
|
||||
currencyCode: credit.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the entries of the credit note.
|
||||
* @param {ICreditNote} credit
|
||||
* @returns {}
|
||||
*/
|
||||
protected entries = (credit) => {
|
||||
return this.item(credit.entries, new ItemEntryTransformer(), {
|
||||
currencyCode: credit.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the credit note attachments.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns
|
||||
*/
|
||||
protected attachments = (creditNote) => {
|
||||
return this.item(creditNote.attachments, new AttachmentTransformer());
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
|
||||
import { ERRORS } from '../constants';
|
||||
import { CreditNoteTransformer } from './CreditNoteTransformer';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
|
||||
@Injectable()
|
||||
export class GetCreditNote {
|
||||
constructor(
|
||||
private readonly transformer: TransformerInjectable,
|
||||
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the credit note graph.
|
||||
* @param {number} tenantId
|
||||
* @param {number} creditNoteId
|
||||
* @returns
|
||||
*/
|
||||
public async getCreditNote(creditNoteId: number) {
|
||||
// Retrieve the vendor credit model graph.
|
||||
const creditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteId)
|
||||
.withGraphFetched('entries.item')
|
||||
.withGraphFetched('customer')
|
||||
.withGraphFetched('branch')
|
||||
.withGraphFetched('attachments');
|
||||
|
||||
if (!creditNote) {
|
||||
throw new ServiceError(ERRORS.CREDIT_NOTE_NOT_FOUND);
|
||||
}
|
||||
// Transforms the credit note model to POJO.
|
||||
return this.transformer.transform(creditNote, new CreditNoteTransformer());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CreditNoteAppliedInvoiceTransformer } from './CreditNoteAppliedInvoiceTransformer';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service';
|
||||
import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice';
|
||||
|
||||
@Injectable()
|
||||
export class GetCreditNoteAssociatedAppliedInvoices {
|
||||
constructor(
|
||||
private readonly transformer: TransformerInjectable,
|
||||
private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice,
|
||||
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve credit note associated invoices to apply.
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<CreditNoteAppliedInvoice[]>}
|
||||
*/
|
||||
public async getCreditAssociatedAppliedInvoices(
|
||||
creditNoteId: number
|
||||
): Promise<CreditNoteAppliedInvoice[]> {
|
||||
// Retrieve credit note or throw not found service error.
|
||||
const creditNote = await this.creditNoteModel.query()
|
||||
.findById(creditNoteId)
|
||||
.throwIfNotFound();
|
||||
|
||||
const appliedToInvoices = await this.creditNoteAppliedInvoiceModel.query()
|
||||
.where('credit_note_id', creditNoteId)
|
||||
.withGraphFetched('saleInvoice')
|
||||
.withGraphFetched('creditNote');
|
||||
|
||||
// Transforms credit note applied to invoices.
|
||||
return this.transformer.transform(
|
||||
appliedToInvoices,
|
||||
new CreditNoteAppliedInvoiceTransformer()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CreditNoteWithInvoicesToApplyTransformer } from '../commands/CreditNoteWithInvoicesToApplyTransformer';
|
||||
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
|
||||
import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
|
||||
import { GetCreditNote } from './GetCreditNote.service';
|
||||
|
||||
@Injectable()
|
||||
export class GetCreditNoteAssociatedInvoicesToApply {
|
||||
constructor(
|
||||
private transformer: TransformerInjectable,
|
||||
private getCreditNote: GetCreditNote,
|
||||
|
||||
@Inject(SaleInvoice.name)
|
||||
private saleInvoiceModel: typeof SaleInvoice,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve credit note associated invoices to apply.
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<ISaleInvoice[]>}
|
||||
*/
|
||||
public async getCreditAssociatedInvoicesToApply(
|
||||
creditNoteId: number,
|
||||
): Promise<SaleInvoice[]> {
|
||||
// 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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { GetCreditNote } from './GetCreditNote.service';
|
||||
import { CreditNoteBrandingTemplate } from './CreditNoteBrandingTemplate.service';
|
||||
import { transformCreditNoteToPdfTemplate } from '../utils';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service';
|
||||
import { TemplateInjectable } from '@/modules/TemplateInjectable/TemplateInjectable.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate';
|
||||
import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class GetCreditNotePdf {
|
||||
constructor(
|
||||
private readonly chromiumlyTenancy: ChromiumlyTenancy,
|
||||
private readonly templateInjectable: TemplateInjectable,
|
||||
private readonly getCreditNoteService: GetCreditNote,
|
||||
private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
|
||||
@Inject(CreditNote.name)
|
||||
private readonly creditNoteModel: typeof CreditNote,
|
||||
|
||||
@Inject(PdfTemplateModel.name)
|
||||
private readonly pdfTemplateModel: typeof PdfTemplateModel,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieves sale invoice pdf content.
|
||||
* @param {number} creditNoteId - Credit note id.
|
||||
* @returns {Promise<[Buffer, string]>}
|
||||
*/
|
||||
public async getCreditNotePdf(
|
||||
creditNoteId: number,
|
||||
): Promise<[Buffer, string]> {
|
||||
const brandingAttributes =
|
||||
await this.getCreditNoteBrandingAttributes(creditNoteId);
|
||||
const htmlContent = await this.templateInjectable.render(
|
||||
'modules/credit-note-standard',
|
||||
brandingAttributes,
|
||||
);
|
||||
const filename = await this.getCreditNoteFilename(creditNoteId);
|
||||
|
||||
const document =
|
||||
await this.chromiumlyTenancy.convertHtmlContent(htmlContent);
|
||||
const eventPayload = { creditNoteId };
|
||||
|
||||
// Triggers the `onCreditNotePdfViewed` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.creditNote.onPdfViewed,
|
||||
eventPayload,
|
||||
);
|
||||
return [document, filename];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the filename pdf document of the given credit note.
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
public async getCreditNoteFilename(creditNoteId: number): Promise<string> {
|
||||
const creditNote = await this.creditNoteModel
|
||||
.query()
|
||||
.findById(creditNoteId);
|
||||
return `Credit-${creditNote.creditNoteNumber}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves credit note branding attributes.
|
||||
* @param {number} creditNoteId - The ID of the credit note.
|
||||
* @returns {Promise<CreditNotePdfTemplateAttributes>} The credit note branding attributes.
|
||||
*/
|
||||
public async getCreditNoteBrandingAttributes(
|
||||
creditNoteId: number,
|
||||
): Promise<CreditNotePdfTemplateAttributes> {
|
||||
const creditNote =
|
||||
await this.getCreditNoteService.getCreditNote(creditNoteId);
|
||||
|
||||
// Retrieve the invoice template id of not found get the default template id.
|
||||
const templateId =
|
||||
creditNote.pdfTemplateId ??
|
||||
(
|
||||
await this.pdfTemplateModel.query().findOne({
|
||||
resource: 'CreditNote',
|
||||
default: true,
|
||||
})
|
||||
)?.id;
|
||||
// Retrieves the credit note branding template.
|
||||
const brandingTemplate =
|
||||
await this.creditNoteBrandingTemplate.getCreditNoteBrandingTemplate(
|
||||
templateId,
|
||||
);
|
||||
return {
|
||||
...brandingTemplate.attributes,
|
||||
...transformCreditNoteToPdfTemplate(creditNote),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import RefundCreditNoteTransformer from './RefundCreditNoteTransformer';
|
||||
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
|
||||
import { RefundCreditNote } from '../models/RefundCreditNote';
|
||||
import { IRefundCreditNotePOJO } from '../types/CreditNotes.types';
|
||||
|
||||
@Injectable()
|
||||
export class ListCreditNoteRefunds {
|
||||
constructor(
|
||||
private readonly transformer: TransformerInjectable,
|
||||
|
||||
@Inject(RefundCreditNote.name)
|
||||
private readonly refundCreditNoteModel: typeof RefundCreditNote,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the credit note graph.
|
||||
* @param {number} creditNoteId
|
||||
* @returns {Promise<IRefundCreditNotePOJO[]>}
|
||||
*/
|
||||
public async getCreditNoteRefunds(
|
||||
creditNoteId: number,
|
||||
): Promise<IRefundCreditNotePOJO[]> {
|
||||
// Retrieve refund credit notes associated to the given credit note.
|
||||
const refundCreditTransactions = await this.refundCreditNoteModel
|
||||
.query()
|
||||
.where('creditNoteId', creditNoteId)
|
||||
.withGraphFetched('creditNote')
|
||||
.withGraphFetched('fromAccount');
|
||||
|
||||
// Transforms refund credit note models to POJO objects.
|
||||
return this.transformer.transform(
|
||||
refundCreditTransactions,
|
||||
new RefundCreditNoteTransformer(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { ICreditNoteState } from '../types/CreditNotes.types';
|
||||
import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate';
|
||||
|
||||
@Injectable()
|
||||
export class GetCreditNoteState {
|
||||
constructor(
|
||||
@Inject(PdfTemplateModel.name)
|
||||
private pdfTemplateModel: typeof PdfTemplateModel,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieves the create/edit initial state of the payment received.
|
||||
* @return {Promise<ICreditNoteState>}
|
||||
*/
|
||||
public async getCreditNoteState(): Promise<ICreditNoteState> {
|
||||
const defaultPdfTemplate = await this.pdfTemplateModel.query()
|
||||
.findOne({ resource: 'CreditNote' })
|
||||
.modify('default');
|
||||
|
||||
return {
|
||||
defaultTemplateId: defaultPdfTemplate?.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// import { Service, Inject } from 'typedi';
|
||||
// import * as R from 'ramda';
|
||||
// import { ICreditNotesQueryDTO } from '@/interfaces';
|
||||
// import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
// import BaseCreditNotes from './commands/CommandCreditNoteDTOTransform.service';
|
||||
// import { CreditNoteTransformer } from './queries/CreditNoteTransformer';
|
||||
// import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
|
||||
// @Service()
|
||||
// export default class ListCreditNotes extends BaseCreditNotes {
|
||||
// @Inject()
|
||||
// private dynamicListService: DynamicListingService;
|
||||
|
||||
// @Inject()
|
||||
// private transformer: TransformerInjectable;
|
||||
|
||||
// /**
|
||||
// * Parses the sale invoice list filter DTO.
|
||||
// * @param filterDTO
|
||||
// * @returns
|
||||
// */
|
||||
// private parseListFilterDTO = (filterDTO) => {
|
||||
// return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the paginated and filterable credit notes list.
|
||||
// * @param {number} tenantId -
|
||||
// * @param {ICreditNotesQueryDTO} creditNotesQuery -
|
||||
// */
|
||||
// public getCreditNotesList = async (
|
||||
// tenantId: number,
|
||||
// creditNotesQuery: ICreditNotesQueryDTO
|
||||
// ) => {
|
||||
// const { CreditNote } = this.tenancy.models(tenantId);
|
||||
|
||||
// // Parses stringified filter roles.
|
||||
// const filter = this.parseListFilterDTO(creditNotesQuery);
|
||||
|
||||
// // Dynamic list service.
|
||||
// const dynamicFilter = await this.dynamicListService.dynamicList(
|
||||
// tenantId,
|
||||
// CreditNote,
|
||||
// filter
|
||||
// );
|
||||
// const { results, pagination } = await CreditNote.query()
|
||||
// .onBuild((builder) => {
|
||||
// builder.withGraphFetched('entries.item');
|
||||
// builder.withGraphFetched('customer');
|
||||
// dynamicFilter.buildQuery()(builder);
|
||||
// creditNotesQuery?.filterQuery && creditNotesQuery?.filterQuery(builder);
|
||||
// })
|
||||
// .pagination(filter.page - 1, filter.pageSize);
|
||||
|
||||
// // Transforomes the credit notes to POJO.
|
||||
// const creditNotes = await this.transformer.transform(
|
||||
// tenantId,
|
||||
// results,
|
||||
// new CreditNoteTransformer()
|
||||
// );
|
||||
|
||||
// return {
|
||||
// creditNotes,
|
||||
// pagination,
|
||||
// filterMeta: dynamicFilter.getResponseMeta(),
|
||||
// };
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { IRefundCreditNote } from '../types/CreditNotes.types';
|
||||
import { RefundCreditNote } from '../models/RefundCreditNote';
|
||||
import { RefundCreditNoteTransformer } from './RefundCreditNoteTransformer';
|
||||
|
||||
@Injectable()
|
||||
export class GetRefundCreditNoteTransaction {
|
||||
/**
|
||||
* @param {RefundCreditNoteTransformer} transformer
|
||||
* @param {typeof RefundCreditNote} refundCreditNoteModel
|
||||
*/
|
||||
constructor(
|
||||
private readonly transformer: RefundCreditNoteTransformer,
|
||||
|
||||
@Inject(RefundCreditNote.name)
|
||||
private readonly refundCreditNoteModel: typeof RefundCreditNote,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve credit note associated invoices to apply.
|
||||
* @param {number} refundCreditId
|
||||
* @returns {Promise<IRefundCreditNote>}
|
||||
*/
|
||||
public async getRefundCreditTransaction(
|
||||
refundCreditId: number
|
||||
): Promise<IRefundCreditNote> {
|
||||
const refundCreditNote = await this.refundCreditNoteModel
|
||||
.query()
|
||||
.findById(refundCreditId)
|
||||
.withGraphFetched('fromAccount')
|
||||
.withGraphFetched('creditNote')
|
||||
.throwIfNotFound();
|
||||
|
||||
return this.transformer.transform(refundCreditNote);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Transformer } from "@/modules/Transformer/Transformer";
|
||||
|
||||
export class RefundCreditNoteTransformer extends Transformer{
|
||||
/**
|
||||
* Includeded attributes.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['formttedAmount', 'formattedDate'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Formatted amount.
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formttedAmount = (item) => {
|
||||
return this.formatNumber(item.amount, {
|
||||
currencyCode: item.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Formatted date.
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedDate = (item) => {
|
||||
return this.formatDate(item.date);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { sumBy } from 'lodash';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IApplyCreditToInvoicesCreatedPayload,
|
||||
IApplyCreditToInvoicesDeletedPayload,
|
||||
} from '@/interfaces';
|
||||
import CreditNoteApplySyncCredit from '../commands/CreditNoteApplySyncCredit.service';
|
||||
|
||||
@Service()
|
||||
export default class CreditNoteApplySyncCreditSubscriber {
|
||||
@Inject()
|
||||
syncInvoicedAmountWithCredit: CreditNoteApplySyncCredit;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param bus
|
||||
*/
|
||||
attach(bus) {
|
||||
bus.subscribe(
|
||||
events.creditNote.onApplyToInvoicesCreated,
|
||||
this.incrementCreditedAmountOnceApplyToInvoicesCreated
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onApplyToInvoicesDeleted,
|
||||
this.decrementCreditedAmountOnceApplyToInvoicesDeleted
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment credited amount of credit note transaction once the transaction created.
|
||||
* @param {IApplyCreditToInvoicesCreatedPayload} payload -
|
||||
*/
|
||||
private incrementCreditedAmountOnceApplyToInvoicesCreated = async ({
|
||||
trx,
|
||||
creditNote,
|
||||
tenantId,
|
||||
creditNoteAppliedInvoices,
|
||||
}: IApplyCreditToInvoicesCreatedPayload) => {
|
||||
const totalCredited = sumBy(creditNoteAppliedInvoices, 'amount');
|
||||
|
||||
await this.syncInvoicedAmountWithCredit.incrementCreditNoteInvoicedAmount(
|
||||
tenantId,
|
||||
creditNote.id,
|
||||
totalCredited,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrement credited amount of credit note transaction once the transaction deleted.
|
||||
* @param {IApplyCreditToInvoicesDeletedPayload} payload -
|
||||
*/
|
||||
private decrementCreditedAmountOnceApplyToInvoicesDeleted = async ({
|
||||
tenantId,
|
||||
creditNote,
|
||||
creditNoteAppliedToInvoice,
|
||||
trx,
|
||||
}: IApplyCreditToInvoicesDeletedPayload) => {
|
||||
await this.syncInvoicedAmountWithCredit.decrementCreditNoteInvoicedAmount(
|
||||
tenantId,
|
||||
creditNote.id,
|
||||
creditNoteAppliedToInvoice.amount,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IApplyCreditToInvoicesCreatedPayload,
|
||||
IApplyCreditToInvoicesDeletedPayload,
|
||||
} from '@/interfaces';
|
||||
import CreditNoteApplySyncInvoicesCreditedAmount from '../commands/CreditNoteApplySyncInvoices.service';
|
||||
|
||||
@Service()
|
||||
export default class CreditNoteApplySyncInvoicesCreditedAmountSubscriber {
|
||||
@Inject()
|
||||
private syncInvoicesWithCreditNote: CreditNoteApplySyncInvoicesCreditedAmount;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.creditNote.onApplyToInvoicesCreated,
|
||||
this.incrementAppliedInvoicesOnceCreditCreated
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onApplyToInvoicesDeleted,
|
||||
this.decrementAppliedInvoicesOnceCreditDeleted
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment invoices credited amount once the credit note apply to invoices transaction
|
||||
* @param {IApplyCreditToInvoicesCreatedPayload} payload -
|
||||
*/
|
||||
private incrementAppliedInvoicesOnceCreditCreated = async ({
|
||||
trx,
|
||||
tenantId,
|
||||
creditNoteAppliedInvoices,
|
||||
}: IApplyCreditToInvoicesCreatedPayload) => {
|
||||
await this.syncInvoicesWithCreditNote.incrementInvoicesCreditedAmount(
|
||||
tenantId,
|
||||
creditNoteAppliedInvoices,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {IApplyCreditToInvoicesDeletedPayload} payload -
|
||||
*/
|
||||
private decrementAppliedInvoicesOnceCreditDeleted = async ({
|
||||
trx,
|
||||
creditNoteAppliedToInvoice,
|
||||
tenantId,
|
||||
}: IApplyCreditToInvoicesDeletedPayload) => {
|
||||
// Decrement invoice credited amount.
|
||||
await this.syncInvoicesWithCreditNote.decrementInvoiceCreditedAmount(
|
||||
tenantId,
|
||||
creditNoteAppliedToInvoice.invoiceId,
|
||||
creditNoteAppliedToInvoice.amount,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import BaseCreditNotes from '../commands/CommandCreditNoteDTOTransform.service';
|
||||
import { ICreditNoteCreatedPayload } from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export default class CreditNoteAutoSerialSubscriber {
|
||||
@Inject()
|
||||
creditNotesService: BaseCreditNotes;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.creditNote.onCreated,
|
||||
this.autoSerialIncrementOnceCreated
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto serial increment once credit note created.
|
||||
* @param {ICreditNoteCreatedPayload} payload -
|
||||
*/
|
||||
private autoSerialIncrementOnceCreated = async ({
|
||||
tenantId,
|
||||
}: ICreditNoteCreatedPayload) => {
|
||||
await this.creditNotesService.incrementSerialNumber(tenantId);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
ICreditNoteCreatedPayload,
|
||||
ICreditNoteDeletedPayload,
|
||||
ICreditNoteEditedPayload,
|
||||
ICreditNoteOpenedPayload,
|
||||
} from '@/interfaces';
|
||||
import CreditNoteGLEntries from '../commands/CreditNoteGLEntries';
|
||||
|
||||
@Service()
|
||||
export default class CreditNoteGLEntriesSubscriber {
|
||||
@Inject()
|
||||
private creditNoteGLEntries: CreditNoteGLEntries;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
* @param bus
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.creditNote.onCreated,
|
||||
this.writeGlEntriesOnceCreditNoteCreated
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onOpened,
|
||||
this.writeGLEntriesOnceCreditNoteOpened
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onEdited,
|
||||
this.editVendorCreditGLEntriesOnceEdited
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onDeleted,
|
||||
this.revertGLEntriesOnceCreditNoteDeleted
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the GL entries once the credit note transaction created or open.
|
||||
* @private
|
||||
* @param {ICreditNoteCreatedPayload|ICreditNoteOpenedPayload} payload -
|
||||
*/
|
||||
private writeGlEntriesOnceCreditNoteCreated = async ({
|
||||
tenantId,
|
||||
creditNote,
|
||||
creditNoteId,
|
||||
trx,
|
||||
}: ICreditNoteCreatedPayload | ICreditNoteOpenedPayload) => {
|
||||
// Can't continue if the credit note is not published yet.
|
||||
if (!creditNote.isPublished) return;
|
||||
|
||||
await this.creditNoteGLEntries.createVendorCreditGLEntries(
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes the GL entries once the vendor credit transaction opened.
|
||||
* @param {ICreditNoteOpenedPayload} payload
|
||||
*/
|
||||
private writeGLEntriesOnceCreditNoteOpened = async ({
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
trx,
|
||||
}: ICreditNoteOpenedPayload) => {
|
||||
await this.creditNoteGLEntries.createVendorCreditGLEntries(
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts GL entries once credit note deleted.
|
||||
*/
|
||||
private revertGLEntriesOnceCreditNoteDeleted = async ({
|
||||
tenantId,
|
||||
oldCreditNote,
|
||||
creditNoteId,
|
||||
trx,
|
||||
}: ICreditNoteDeletedPayload) => {
|
||||
// Can't continue if the credit note is not published yet.
|
||||
if (!oldCreditNote.isPublished) return;
|
||||
|
||||
await this.creditNoteGLEntries.revertVendorCreditGLEntries(
|
||||
tenantId,
|
||||
creditNoteId
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Edits vendor credit associated GL entries once the transaction edited.
|
||||
* @param {ICreditNoteEditedPayload} payload -
|
||||
*/
|
||||
private editVendorCreditGLEntriesOnceEdited = async ({
|
||||
tenantId,
|
||||
creditNote,
|
||||
creditNoteId,
|
||||
trx,
|
||||
}: ICreditNoteEditedPayload) => {
|
||||
// Can't continue if the credit note is not published yet.
|
||||
if (!creditNote.isPublished) return;
|
||||
|
||||
await this.creditNoteGLEntries.editVendorCreditGLEntries(
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import CreditNoteInventoryTransactions from '../commands/CreditNotesInventoryTransactions';
|
||||
import {
|
||||
ICreditNoteCreatedPayload,
|
||||
ICreditNoteDeletedPayload,
|
||||
ICreditNoteEditedPayload,
|
||||
} from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export default class CreditNoteInventoryTransactionsSubscriber {
|
||||
@Inject()
|
||||
inventoryTransactions: CreditNoteInventoryTransactions;
|
||||
|
||||
/**
|
||||
* Attaches events with publisher.
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.creditNote.onCreated,
|
||||
this.writeInventoryTranscationsOnceCreated
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onEdited,
|
||||
this.rewriteInventoryTransactionsOnceEdited
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onDeleted,
|
||||
this.revertInventoryTransactionsOnceDeleted
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onOpened,
|
||||
this.writeInventoryTranscationsOnceCreated
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes inventory transactions once credit note created.
|
||||
* @param {ICreditNoteCreatedPayload} payload -
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public writeInventoryTranscationsOnceCreated = async ({
|
||||
tenantId,
|
||||
creditNote,
|
||||
trx,
|
||||
}: ICreditNoteCreatedPayload) => {
|
||||
// Can't continue if the credit note is open yet.
|
||||
if (!creditNote.isOpen) return;
|
||||
|
||||
await this.inventoryTransactions.createInventoryTransactions(
|
||||
tenantId,
|
||||
creditNote,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Rewrites inventory transactions once credit note edited.
|
||||
* @param {ICreditNoteEditedPayload} payload -
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public rewriteInventoryTransactionsOnceEdited = async ({
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
creditNote,
|
||||
trx,
|
||||
}: ICreditNoteEditedPayload) => {
|
||||
// Can't continue if the credit note is open yet.
|
||||
if (!creditNote.isOpen) return;
|
||||
|
||||
await this.inventoryTransactions.editInventoryTransactions(
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
creditNote,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts inventory transactions once credit note deleted.
|
||||
* @param {ICreditNoteDeletedPayload} payload -
|
||||
*/
|
||||
public revertInventoryTransactionsOnceDeleted = async ({
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
oldCreditNote,
|
||||
trx,
|
||||
}: ICreditNoteDeletedPayload) => {
|
||||
// Can't continue if the credit note is open yet.
|
||||
if (!oldCreditNote.isOpen) return;
|
||||
|
||||
await this.inventoryTransactions.deleteInventoryTransactions(
|
||||
tenantId,
|
||||
creditNoteId,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import events from '@/subscribers/events';
|
||||
import { ICustomerDeletingPayload } from '@/interfaces';
|
||||
import DeleteCustomerLinkedCreidtNote from '../commands/DeleteCustomerLinkedCreditNote.service';
|
||||
|
||||
const ERRORS = {
|
||||
CUSTOMER_HAS_TRANSACTIONS: 'CUSTOMER_HAS_TRANSACTIONS',
|
||||
};
|
||||
|
||||
@Service()
|
||||
export default class DeleteCustomerLinkedCreditSubscriber {
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
deleteCustomerLinkedCredit: DeleteCustomerLinkedCreidtNote;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
* @param bus
|
||||
*/
|
||||
public attach = (bus) => {
|
||||
bus.subscribe(
|
||||
events.customers.onDeleting,
|
||||
this.validateCustomerHasNoLinkedCreditsOnDeleting
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate vendor has no associated credit transaction once the vendor deleting.
|
||||
* @param {IVendorEventDeletingPayload} payload -
|
||||
*/
|
||||
public validateCustomerHasNoLinkedCreditsOnDeleting = async ({
|
||||
tenantId,
|
||||
customerId,
|
||||
}: ICustomerDeletingPayload) => {
|
||||
try {
|
||||
await this.deleteCustomerLinkedCredit.validateCustomerHasNoCreditTransaction(
|
||||
tenantId,
|
||||
customerId
|
||||
);
|
||||
} catch (error) {
|
||||
throw new ServiceError(ERRORS.CUSTOMER_HAS_TRANSACTIONS);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import RefundCreditNoteGLEntries from '../commands/RefundCreditNoteGLEntries';
|
||||
import {
|
||||
IRefundCreditNoteCreatedPayload,
|
||||
IRefundCreditNoteDeletedPayload,
|
||||
} from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export default class RefundCreditNoteGLEntriesSubscriber {
|
||||
@Inject()
|
||||
refundCreditGLEntries: RefundCreditNoteGLEntries;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
*/
|
||||
public attach = (bus) => {
|
||||
bus.subscribe(
|
||||
events.creditNote.onRefundCreated,
|
||||
this.writeRefundCreditGLEntriesOnceCreated
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onRefundDeleted,
|
||||
this.revertRefundCreditGLEntriesOnceDeleted
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes refund credit note GL entries once the transaction created.
|
||||
* @param {IRefundCreditNoteCreatedPayload} payload -
|
||||
*/
|
||||
private writeRefundCreditGLEntriesOnceCreated = async ({
|
||||
trx,
|
||||
refundCreditNote,
|
||||
creditNote,
|
||||
tenantId,
|
||||
}: IRefundCreditNoteCreatedPayload) => {
|
||||
await this.refundCreditGLEntries.createRefundCreditGLEntries(
|
||||
tenantId,
|
||||
refundCreditNote.id,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts refund credit note GL entries once the transaction deleted.
|
||||
* @param {IRefundCreditNoteDeletedPayload} payload -
|
||||
*/
|
||||
private revertRefundCreditGLEntriesOnceDeleted = async ({
|
||||
trx,
|
||||
refundCreditId,
|
||||
oldRefundCredit,
|
||||
tenantId,
|
||||
}: IRefundCreditNoteDeletedPayload) => {
|
||||
await this.refundCreditGLEntries.revertRefundCreditGLEntries(
|
||||
tenantId,
|
||||
refundCreditId,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import {
|
||||
IRefundCreditNoteCreatedPayload,
|
||||
IRefundCreditNoteDeletedPayload,
|
||||
} from '@/interfaces';
|
||||
import events from '@/subscribers/events';
|
||||
import RefundSyncCreditNoteBalance from '../commands/RefundSyncCreditNoteBalance';
|
||||
|
||||
@Service()
|
||||
export default class RefundSyncCreditNoteBalanceSubscriber {
|
||||
@Inject()
|
||||
refundSyncCreditBalance: RefundSyncCreditNoteBalance;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
*/
|
||||
attach(bus) {
|
||||
bus.subscribe(
|
||||
events.creditNote.onRefundCreated,
|
||||
this.incrementRefundedAmountOnceRefundCreated
|
||||
);
|
||||
bus.subscribe(
|
||||
events.creditNote.onRefundDeleted,
|
||||
this.decrementRefundedAmountOnceRefundDeleted
|
||||
);
|
||||
return bus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment credit note refunded amount once associated refund transaction created.
|
||||
* @param {IRefundCreditNoteCreatedPayload} payload -
|
||||
*/
|
||||
private incrementRefundedAmountOnceRefundCreated = async ({
|
||||
trx,
|
||||
refundCreditNote,
|
||||
tenantId,
|
||||
}: IRefundCreditNoteCreatedPayload) => {
|
||||
await this.refundSyncCreditBalance.incrementCreditNoteRefundAmount(
|
||||
tenantId,
|
||||
refundCreditNote.creditNoteId,
|
||||
refundCreditNote.amount,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrement credit note refunded amount once associated refuned transaction deleted.
|
||||
* @param {IRefundCreditNoteDeletedPayload} payload -
|
||||
*/
|
||||
private decrementRefundedAmountOnceRefundDeleted = async ({
|
||||
trx,
|
||||
oldRefundCredit,
|
||||
tenantId,
|
||||
}: IRefundCreditNoteDeletedPayload) => {
|
||||
await this.refundSyncCreditBalance.decrementCreditNoteRefundAmount(
|
||||
tenantId,
|
||||
oldRefundCredit.creditNoteId,
|
||||
oldRefundCredit.amount,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import { Knex } from 'knex';
|
||||
import { DiscountType, IDynamicListFilter, IItemEntry } from '@/interfaces';
|
||||
import { ILedgerEntry } from './Ledger';
|
||||
import { AttachmentLinkDTO } from './Attachments';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { RefundCreditNote } from '../models/RefundCreditNote';
|
||||
|
||||
export interface ICreditNoteEntryNewDTO {
|
||||
index?: number;
|
||||
itemId: number;
|
||||
rate: number;
|
||||
quantity: number;
|
||||
discount: number;
|
||||
description: string;
|
||||
warehouseId?: number;
|
||||
}
|
||||
export interface ICreditNoteNewDTO {
|
||||
customerId: number;
|
||||
exchangeRate?: number;
|
||||
creditNoteDate: Date;
|
||||
creditNoteNumber: string;
|
||||
note: string;
|
||||
open: boolean;
|
||||
entries: ICreditNoteEntryNewDTO[];
|
||||
branchId?: number;
|
||||
warehouseId?: number;
|
||||
attachments?: AttachmentLinkDTO[];
|
||||
discount?: number;
|
||||
discountType?: DiscountType;
|
||||
adjustment?: number;
|
||||
}
|
||||
|
||||
export interface ICreditNoteEditDTO {
|
||||
customerId: number;
|
||||
exchangeRate?: number;
|
||||
creditNoteDate: Date;
|
||||
creditNoteNumber: string;
|
||||
note: string;
|
||||
open: boolean;
|
||||
entries: ICreditNoteEntryNewDTO[];
|
||||
branchId?: number;
|
||||
warehouseId?: number;
|
||||
attachments?: AttachmentLinkDTO[];
|
||||
}
|
||||
|
||||
export interface ICreditNoteEntry extends IItemEntry {}
|
||||
|
||||
export interface ICreditNote {
|
||||
id?: number;
|
||||
customerId: number;
|
||||
amount: number;
|
||||
refundedAmount: number;
|
||||
currencyCode: string;
|
||||
exchangeRate: number;
|
||||
creditNoteDate: Date;
|
||||
creditNoteNumber: string;
|
||||
referenceNo?: string;
|
||||
// note?: string;
|
||||
openedAt: Date | null;
|
||||
entries: ICreditNoteEntry[];
|
||||
isOpen: boolean;
|
||||
isClosed: boolean;
|
||||
isDraft: boolean;
|
||||
isPublished: boolean;
|
||||
creditsRemaining: number;
|
||||
localAmount?: number;
|
||||
branchId?: number;
|
||||
warehouseId: number;
|
||||
createdAt?: Date;
|
||||
termsConditions: string;
|
||||
note: string;
|
||||
}
|
||||
|
||||
export enum CreditNoteAction {
|
||||
Create = 'Create',
|
||||
Edit = 'Edit',
|
||||
Delete = 'Delete',
|
||||
View = 'View',
|
||||
Refund = 'Refund',
|
||||
}
|
||||
|
||||
export interface ICreditNoteDeletingPayload {
|
||||
tenantId: number;
|
||||
oldCreditNote: CreditNote;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICreditNoteDeletedPayload {
|
||||
tenantId: number;
|
||||
oldCreditNote: CreditNote;
|
||||
creditNoteId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICreditNoteEditingPayload {
|
||||
trx: Knex.Transaction;
|
||||
oldCreditNote: CreditNote;
|
||||
creditNoteEditDTO: ICreditNoteEditDTO;
|
||||
tenantId: number;
|
||||
}
|
||||
|
||||
export interface ICreditNoteEditedPayload {
|
||||
trx: Knex.Transaction;
|
||||
oldCreditNote: CreditNote;
|
||||
// creditNoteId: number;
|
||||
creditNote: CreditNote;
|
||||
creditNoteEditDTO: ICreditNoteEditDTO;
|
||||
// tenantId: number;
|
||||
}
|
||||
|
||||
export interface ICreditNoteCreatedPayload {
|
||||
// tenantId: number;
|
||||
creditNoteDTO: ICreditNoteNewDTO;
|
||||
creditNote: CreditNote;
|
||||
// creditNoteId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICreditNoteCreatingPayload {
|
||||
// tenantId: number;
|
||||
creditNoteDTO: ICreditNoteNewDTO;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICreditNoteOpeningPayload {
|
||||
tenantId: number;
|
||||
creditNoteId: number;
|
||||
oldCreditNote: CreditNote;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICreditNoteOpenedPayload {
|
||||
// tenantId: number;
|
||||
creditNote: CreditNote;
|
||||
// creditNoteId: number;
|
||||
oldCreditNote: CreditNote;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICreditNotesQueryDTO {
|
||||
filterQuery?: (query: any) => void;
|
||||
}
|
||||
|
||||
export interface ICreditNotesQueryDTO extends IDynamicListFilter {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
searchKeyword?: string;
|
||||
}
|
||||
|
||||
export interface ICreditNoteRefundDTO {
|
||||
fromAccountId: number;
|
||||
amount: number;
|
||||
exchangeRate?: number;
|
||||
referenceNo: string;
|
||||
description: string;
|
||||
date: Date;
|
||||
branchId?: number;
|
||||
}
|
||||
|
||||
export interface ICreditNoteApplyInvoiceDTO {
|
||||
entries: { invoiceId: number; amount: number }[];
|
||||
}
|
||||
export interface IRefundCreditNotePOJO {
|
||||
formattedAmount: string;
|
||||
}
|
||||
|
||||
export interface IRefundCreditNoteDeletedPayload {
|
||||
trx: Knex.Transaction;
|
||||
refundCreditId: number;
|
||||
oldRefundCredit: RefundCreditNote;
|
||||
tenantId: number;
|
||||
}
|
||||
|
||||
export interface IRefundCreditNoteDeletingPayload {
|
||||
trx: Knex.Transaction;
|
||||
refundCreditId: number;
|
||||
oldRefundCredit: RefundCreditNote;
|
||||
// tenantId: number;
|
||||
}
|
||||
|
||||
export interface IRefundCreditNoteCreatingPayload {
|
||||
trx: Knex.Transaction;
|
||||
creditNote: CreditNote;
|
||||
newCreditNoteDTO: ICreditNoteRefundDTO;
|
||||
// tenantId: number;
|
||||
}
|
||||
|
||||
export interface IRefundCreditNoteCreatedPayload {
|
||||
trx: Knex.Transaction;
|
||||
refundCreditNote: RefundCreditNote;
|
||||
creditNote: CreditNote;
|
||||
// tenantId: number;
|
||||
}
|
||||
|
||||
export interface IRefundCreditNoteOpenedPayload {
|
||||
// tenantId: number;
|
||||
creditNoteId: number;
|
||||
oldCreditNote: CreditNote;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IApplyCreditToInvoiceEntryDTO {
|
||||
amount: number;
|
||||
invoiceId: number;
|
||||
}
|
||||
|
||||
export interface IApplyCreditToInvoicesDTO {
|
||||
entries: IApplyCreditToInvoiceEntryDTO[];
|
||||
}
|
||||
|
||||
export interface IApplyCreditToInvoicesCreatedPayload {
|
||||
trx: Knex.Transaction;
|
||||
creditNote: ICreditNote;
|
||||
creditNoteAppliedInvoices: ICreditNoteAppliedToInvoice[];
|
||||
// tenantId: number;
|
||||
}
|
||||
export interface IApplyCreditToInvoicesDeletedPayload {
|
||||
trx: Knex.Transaction;
|
||||
creditNote: ICreditNote;
|
||||
creditNoteAppliedToInvoice: ICreditNoteAppliedToInvoice;
|
||||
// tenantId: number;
|
||||
}
|
||||
|
||||
export interface ICreditNoteAppliedToInvoice {
|
||||
invoiceId: number;
|
||||
amount: number;
|
||||
creditNoteId: number;
|
||||
}
|
||||
export interface ICreditNoteAppliedToInvoiceModel {
|
||||
amount: number;
|
||||
entries: ICreditNoteAppliedToInvoice[];
|
||||
}
|
||||
|
||||
export type ICreditNoteGLCommonEntry = Pick<
|
||||
ILedgerEntry,
|
||||
| 'date'
|
||||
| 'userId'
|
||||
| 'currencyCode'
|
||||
| 'exchangeRate'
|
||||
| 'transactionType'
|
||||
| 'transactionId'
|
||||
| 'transactionNumber'
|
||||
| 'referenceNumber'
|
||||
| 'createdAt'
|
||||
| 'indexGroup'
|
||||
| 'credit'
|
||||
| 'debit'
|
||||
| 'branchId'
|
||||
>;
|
||||
|
||||
export interface CreditNotePdfTemplateAttributes {
|
||||
// # Primary color
|
||||
primaryColor: string;
|
||||
secondaryColor: string;
|
||||
|
||||
// # Company logo
|
||||
showCompanyLogo: boolean;
|
||||
companyLogo: string;
|
||||
|
||||
// # Company name
|
||||
companyName: string;
|
||||
|
||||
// # Customer Address
|
||||
showCustomerAddress: boolean;
|
||||
customerAddress: string;
|
||||
|
||||
// # Company address
|
||||
showCompanyAddress: boolean;
|
||||
companyAddress: string;
|
||||
billedToLabel: string;
|
||||
|
||||
total: string;
|
||||
totalLabel: string;
|
||||
showTotal: boolean;
|
||||
|
||||
subtotal: string;
|
||||
subtotalLabel: string;
|
||||
showSubtotal: boolean;
|
||||
|
||||
showCustomerNote: boolean;
|
||||
customerNote: string;
|
||||
customerNoteLabel: string;
|
||||
|
||||
showTermsConditions: boolean;
|
||||
termsConditions: string;
|
||||
termsConditionsLabel: string;
|
||||
|
||||
lines: Array<{
|
||||
item: string;
|
||||
description: string;
|
||||
rate: string;
|
||||
quantity: string;
|
||||
total: string;
|
||||
}>;
|
||||
|
||||
showCreditNoteNumber: boolean;
|
||||
creditNoteNumberLabel: string;
|
||||
creditNoteNumebr: string;
|
||||
|
||||
creditNoteDate: string;
|
||||
showCreditNoteDate: boolean;
|
||||
creditNoteDateLabel: string;
|
||||
}
|
||||
|
||||
export interface ICreditNoteState {
|
||||
defaultTemplateId: number;
|
||||
}
|
||||
25
packages/server-nest/src/modules/CreditNotes/utils.ts
Normal file
25
packages/server-nest/src/modules/CreditNotes/utils.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { CreditNotePdfTemplateAttributes, ICreditNote } from '@/interfaces';
|
||||
import { contactAddressTextFormat } from '@/utils/address-text-format';
|
||||
|
||||
export const transformCreditNoteToPdfTemplate = (
|
||||
creditNote: ICreditNote
|
||||
): Partial<CreditNotePdfTemplateAttributes> => {
|
||||
return {
|
||||
creditNoteDate: creditNote.formattedCreditNoteDate,
|
||||
creditNoteNumebr: creditNote.creditNoteNumber,
|
||||
|
||||
total: creditNote.formattedAmount,
|
||||
subtotal: creditNote.formattedSubtotal,
|
||||
|
||||
lines: creditNote.entries?.map((entry) => ({
|
||||
item: entry.item.name,
|
||||
description: entry.description,
|
||||
rate: entry.rateFormatted,
|
||||
quantity: entry.quantityFormatted,
|
||||
total: entry.totalFormatted,
|
||||
})),
|
||||
customerNote: creditNote.note,
|
||||
termsConditions: creditNote.termsConditions,
|
||||
customerAddress: contactAddressTextFormat(creditNote.customer),
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user