feat(nestjs): migrate to NestJS

This commit is contained in:
Ahmed Bouhuolia
2025-04-07 11:51:24 +02:00
parent f068218a16
commit 55fcc908ef
3779 changed files with 631 additions and 195332 deletions

View File

@@ -0,0 +1,83 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { BillPaymentsApplication } from './BillPaymentsApplication.service';
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
import {
CreateBillPaymentDto,
EditBillPaymentDto,
} from './dtos/BillPayment.dto';
@Controller('bill-payments')
@ApiTags('bill-payments')
export class BillPaymentsController {
constructor(private billPaymentsApplication: BillPaymentsApplication) {}
@Post()
@ApiOperation({ summary: 'Create a new bill payment.' })
public createBillPayment(@Body() billPaymentDTO: CreateBillPaymentDto) {
return this.billPaymentsApplication.createBillPayment(billPaymentDTO);
}
@Delete(':billPaymentId')
@ApiOperation({ summary: 'Delete the given bill payment.' })
@ApiParam({
name: 'billPaymentId',
required: true,
type: Number,
description: 'The bill payment id',
})
public deleteBillPayment(@Param('billPaymentId') billPaymentId: string) {
return this.billPaymentsApplication.deleteBillPayment(
Number(billPaymentId),
);
}
@Put(':billPaymentId')
@ApiOperation({ summary: 'Edit the given bill payment.' })
@ApiParam({
name: 'billPaymentId',
required: true,
type: Number,
description: 'The bill payment id',
})
public editBillPayment(
@Param('billPaymentId') billPaymentId: string,
@Body() billPaymentDTO: EditBillPaymentDto,
) {
return this.billPaymentsApplication.editBillPayment(
Number(billPaymentId),
billPaymentDTO,
);
}
@Get(':billPaymentId')
@ApiOperation({ summary: 'Retrieves the bill payment details.' })
@ApiParam({
name: 'billPaymentId',
required: true,
type: Number,
description: 'The bill payment id',
})
public getBillPayment(@Param('billPaymentId') billPaymentId: string) {
return this.billPaymentsApplication.getBillPayment(Number(billPaymentId));
}
@Get(':billPaymentId/bills')
@ApiOperation({ summary: 'Retrieves the bills of the given bill payment.' })
@ApiParam({
name: 'billPaymentId',
required: true,
type: Number,
description: 'The bill payment id',
})
public getPaymentBills(@Param('billPaymentId') billPaymentId: string) {
return this.billPaymentsApplication.getPaymentBills(Number(billPaymentId));
}
}

View File

@@ -0,0 +1,41 @@
import { Module } from '@nestjs/common';
import { BillPaymentsApplication } from './BillPaymentsApplication.service';
import { CreateBillPaymentService } from './commands/CreateBillPayment.service';
import { EditBillPayment } from './commands/EditBillPayment.service';
import { GetBillPayment } from './queries/GetBillPayment.service';
import { DeleteBillPayment } from './commands/DeleteBillPayment.service';
import { BillPaymentBillSync } from './commands/BillPaymentBillSync.service';
import { GetPaymentBills } from './queries/GetPaymentBills.service';
import { BillPaymentValidators } from './commands/BillPaymentValidators.service';
import { CommandBillPaymentDTOTransformer } from './commands/CommandBillPaymentDTOTransformer.service';
import { TenancyContext } from '../Tenancy/TenancyContext.service';
import { BranchTransactionDTOTransformer } from '../Branches/integrations/BranchTransactionDTOTransform';
import { BranchesSettingsService } from '../Branches/BranchesSettings';
import { BillPaymentsController } from './BillPayments.controller';
import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries';
import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module';
@Module({
imports: [LedgerModule, AccountsModule],
providers: [
BillPaymentsApplication,
CreateBillPaymentService,
EditBillPayment,
GetBillPayment,
DeleteBillPayment,
BillPaymentBillSync,
GetPaymentBills,
BillPaymentValidators,
CommandBillPaymentDTOTransformer,
BranchTransactionDTOTransformer,
BranchesSettingsService,
TenancyContext,
BillPaymentGLEntries,
BillPaymentGLEntriesSubscriber,
],
exports: [BillPaymentValidators, CreateBillPaymentService],
controllers: [BillPaymentsController],
})
export class BillPaymentsModule {}

View File

@@ -0,0 +1,84 @@
import { Injectable } from '@nestjs/common';
import { CreateBillPaymentService } from './commands/CreateBillPayment.service';
import { DeleteBillPayment } from './commands/DeleteBillPayment.service';
import { EditBillPayment } from './commands/EditBillPayment.service';
// import { GetBillPayments } from './GetBillPayments';
import { GetBillPayment } from './queries/GetBillPayment.service';
import { GetPaymentBills } from './queries/GetPaymentBills.service';
import { GetBillPayments } from '../Bills/queries/GetBillPayments';
import { CreateBillPaymentDto, EditBillPaymentDto } from './dtos/BillPayment.dto';
/**
* Bill payments application.
* @service
*/
@Injectable()
export class BillPaymentsApplication {
constructor(
private createBillPaymentService: CreateBillPaymentService,
private editBillPaymentService: EditBillPayment,
private deleteBillPaymentService: DeleteBillPayment,
private getBillPaymentService: GetBillPayment,
private getPaymentBillsService: GetPaymentBills,
// private getBillPaymentsService: GetBillPayments,
) {}
/**
* Creates a bill payment with associated GL entries.
* @param {IBillPaymentDTO} billPaymentDTO
* @returns {Promise<IBillPayment>}
*/
public createBillPayment(billPaymentDTO: CreateBillPaymentDto) {
return this.createBillPaymentService.createBillPayment(billPaymentDTO);
}
/**
* Delets the given bill payment with associated GL entries.
* @param {number} billPaymentId
*/
public deleteBillPayment(billPaymentId: number) {
return this.deleteBillPaymentService.deleteBillPayment(billPaymentId);
}
/**
* Edits the given bill payment with associated GL entries.
* @param {number} billPaymentId - The given bill payment id.
* @param {IBillPaymentDTO} billPaymentDTO - The given bill payment DTO.
* @returns {Promise<IBillPayment>}
*/
public editBillPayment(
billPaymentId: number,
billPaymentDTO: EditBillPaymentDto,
) {
return this.editBillPaymentService.editBillPayment(
billPaymentId,
billPaymentDTO,
);
}
/**
* Retrieves bill payments list.
* @param {number} tenantId
* @param filterDTO
* @returns
*/
// public getBillPayments(filterDTO: IBillPaymentsFilter) {
// return this.getBillPaymentsService.getBillPayments(filterDTO);
// }
/**
* Retrieve specific bill payment.
* @param {number} billPyamentId - The given bill payment id.
*/
public getBillPayment(billPyamentId: number) {
return this.getBillPaymentService.getBillPayment(billPyamentId);
}
/**
* Retrieve payment made associated bills.
* @param {number} billPaymentId - The given bill payment id.
*/
public getPaymentBills(billPaymentId: number) {
return this.getPaymentBillsService.getPaymentBills(billPaymentId);
}
}

View File

@@ -0,0 +1,75 @@
// import { Inject, Service } from 'typedi';
// import * as R from 'ramda';
// import {
// IBillPayment,
// IBillPaymentsFilter,
// IPaginationMeta,
// IFilterMeta,
// } from '@/interfaces';
// import { BillPaymentTransformer } from './queries/BillPaymentTransformer';
// import DynamicListingService from '@/services/DynamicListing/DynamicListService';
// import HasTenancyService from '@/services/Tenancy/TenancyService';
// import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
// @Service()
// export class GetBillPayments {
// @Inject()
// private tenancy: HasTenancyService;
// @Inject()
// private dynamicListService: DynamicListingService;
// @Inject()
// private transformer: TransformerInjectable;
// /**
// * Retrieve bill payment paginted and filterable list.
// * @param {number} tenantId
// * @param {IBillPaymentsFilter} billPaymentsFilter
// */
// public async getBillPayments(
// tenantId: number,
// filterDTO: IBillPaymentsFilter
// ): Promise<{
// billPayments: IBillPayment[];
// pagination: IPaginationMeta;
// filterMeta: IFilterMeta;
// }> {
// const { BillPayment } = this.tenancy.models(tenantId);
// // Parses filter DTO.
// const filter = this.parseListFilterDTO(filterDTO);
// // Dynamic list service.
// const dynamicList = await this.dynamicListService.dynamicList(
// tenantId,
// BillPayment,
// filter
// );
// const { results, pagination } = await BillPayment.query()
// .onBuild((builder) => {
// builder.withGraphFetched('vendor');
// builder.withGraphFetched('paymentAccount');
// dynamicList.buildQuery()(builder);
// filter?.filterQuery && filter?.filterQuery(builder);
// })
// .pagination(filter.page - 1, filter.pageSize);
// // Transformes the bill payments models to POJO.
// const billPayments = await this.transformer.transform(
// tenantId,
// results,
// new BillPaymentTransformer()
// );
// return {
// billPayments,
// pagination,
// filterMeta: dynamicList.getResponseMeta(),
// };
// }
// private parseListFilterDTO(filterDTO) {
// return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
// }
// }

View File

@@ -0,0 +1,51 @@
import { Inject, Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { Bill } from '../../Bills/models/Bill';
import { entriesAmountDiff } from '@/utils/entries-amount-diff';
import Objection, { ModelObject } from 'objection';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { BillPaymentEntryDto } from '../dtos/BillPayment.dto';
import { BillPaymentEntry } from '../models/BillPaymentEntry';
@Injectable()
export class BillPaymentBillSync {
constructor(
@Inject(Bill.name)
private readonly bill: TenantModelProxy<typeof Bill>,
) {}
/**
* Saves bills payment amount changes different.
* @param {number} tenantId -
* @param {IBillPaymentEntryDTO[]} paymentMadeEntries -
* @param {IBillPaymentEntryDTO[]} oldPaymentMadeEntries -
*/
public async saveChangeBillsPaymentAmount(
paymentMadeEntries: BillPaymentEntryDto[],
oldPaymentMadeEntries?: ModelObject<BillPaymentEntry>[],
trx?: Knex.Transaction,
): Promise<void> {
const opers: Objection.QueryBuilder<Bill, Bill[]>[] = [];
const diffEntries = entriesAmountDiff(
paymentMadeEntries,
oldPaymentMadeEntries,
'paymentAmount',
'billId',
);
diffEntries.forEach(
(diffEntry: { paymentAmount: number; billId: number }) => {
if (diffEntry.paymentAmount === 0) {
return;
}
const oper = this.bill().changePaymentAmount(
diffEntry.billId,
diffEntry.paymentAmount,
trx,
);
opers.push(oper);
},
);
await Promise.all(opers);
}
}

View File

@@ -0,0 +1,34 @@
// import { Inject, Service } from 'typedi';
// import { Exportable } from '@/services/Export/Exportable';
// import { BillPaymentsApplication } from './BillPaymentsApplication';
// import { EXPORT_SIZE_LIMIT } from '@/services/Export/constants';
// @Service()
// export class BillPaymentExportable extends Exportable {
// @Inject()
// private billPaymentsApplication: BillPaymentsApplication;
// /**
// * Retrieves the accounts data to exportable sheet.
// * @param {number} tenantId
// * @returns
// */
// public exportable(tenantId: number, query: any) {
// const filterQuery = (builder) => {
// builder.withGraphFetched('entries.bill');
// builder.withGraphFetched('branch');
// };
// const parsedQuery = {
// sortOrder: 'desc',
// columnSortBy: 'created_at',
// ...query,
// page: 1,
// pageSize: EXPORT_SIZE_LIMIT,
// filterQuery
// } as any;
// return this.billPaymentsApplication
// .getBillPayments(tenantId, parsedQuery)
// .then((output) => output.billPayments);
// }
// }

View File

@@ -0,0 +1,191 @@
import { sumBy } from 'lodash';
import { BillPayment } from '../models/BillPayment';
import { AccountNormal } from '@/interfaces/Account';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { Ledger } from '@/modules/Ledger/Ledger';
export class BillPaymentGL {
private billPayment: BillPayment;
private APAccountId: number;
private gainLossAccountId: number;
private baseCurrency: string;
constructor(billPayment: BillPayment) {
this.billPayment = billPayment;
}
/**
* Sets the A/P account ID.
* @param {number} APAccountId -
* @returns {BillPaymentGL}
*/
setAPAccountId(APAccountId: number) {
this.APAccountId = APAccountId;
return this;
}
/**
* Sets the gain/loss account ID.
* @param {number} gainLossAccountId -
* @returns {BillPaymentGL}
*/
setGainLossAccountId(gainLossAccountId: number) {
this.gainLossAccountId = gainLossAccountId;
return this;
}
/**
* Sets the base currency.
* @param {string} baseCurrency -
* @returns {BillPaymentGL}
*/
setBaseCurrency(baseCurrency: string) {
this.baseCurrency = baseCurrency;
return this;
}
/**
* Retrieves the payment common entry.
*/
private get paymentCommonEntry() {
const formattedDate = moment(this.billPayment.paymentDate).format(
'YYYY-MM-DD',
);
return {
debit: 0,
credit: 0,
exchangeRate: this.billPayment.exchangeRate,
currencyCode: this.billPayment.currencyCode,
transactionId: this.billPayment.id,
transactionType: 'BillPayment',
transactionNumber: this.billPayment.paymentNumber,
referenceNumber: this.billPayment.reference,
date: formattedDate,
createdAt: this.billPayment.createdAt,
branchId: this.billPayment.branchId,
};
}
/**
* Calculates the payment total exchange gain/loss.
* @param {IBillPayment} paymentReceive - Payment receive with entries.
* @returns {number}
*/
private get paymentExGainOrLoss(): number {
return sumBy(this.billPayment.entries, (entry) => {
const paymentLocalAmount =
entry.paymentAmount * this.billPayment.exchangeRate;
const invoicePayment = entry.paymentAmount * entry.bill.exchangeRate;
return invoicePayment - paymentLocalAmount;
});
}
/**
* Retrieves the payment exchange gain/loss entries.
* @returns {ILedgerEntry[]}
*/
private get paymentExGainOrLossEntries(): ILedgerEntry[] {
const commonEntry = this.paymentCommonEntry;
const totalExGainOrLoss = this.paymentExGainOrLoss;
const absExGainOrLoss = Math.abs(totalExGainOrLoss);
return totalExGainOrLoss
? [
{
...commonEntry,
currencyCode: this.baseCurrency,
exchangeRate: 1,
credit: totalExGainOrLoss > 0 ? absExGainOrLoss : 0,
debit: totalExGainOrLoss < 0 ? absExGainOrLoss : 0,
accountId: this.gainLossAccountId,
index: 2,
indexGroup: 20,
accountNormal: AccountNormal.DEBIT,
},
{
...commonEntry,
currencyCode: this.baseCurrency,
exchangeRate: 1,
debit: totalExGainOrLoss > 0 ? absExGainOrLoss : 0,
credit: totalExGainOrLoss < 0 ? absExGainOrLoss : 0,
accountId: this.APAccountId,
index: 3,
accountNormal: AccountNormal.DEBIT,
},
]
: [];
}
/**
* Retrieves the payment deposit GL entry.
* @param {IBillPayment} billPayment
* @returns {ILedgerEntry}
*/
private get paymentGLEntry(): ILedgerEntry {
const commonEntry = this.paymentCommonEntry;
return {
...commonEntry,
credit: this.billPayment.localAmount,
accountId: this.billPayment.paymentAccountId,
accountNormal: AccountNormal.DEBIT,
index: 2,
};
}
/**
* Retrieves the payment GL payable entry.
* @returns {ILedgerEntry}
*/
private get paymentGLPayableEntry(): ILedgerEntry {
const commonEntry = this.paymentCommonEntry;
return {
...commonEntry,
exchangeRate: this.billPayment.exchangeRate,
debit: this.billPayment.localAmount,
contactId: this.billPayment.vendorId,
accountId: this.APAccountId,
accountNormal: AccountNormal.CREDIT,
index: 1,
};
}
/**
* Retrieves the payment GL entries.
* @param {IBillPayment} billPayment
* @param {number} APAccountId
* @returns {ILedgerEntry[]}
*/
private get paymentGLEntries(): ILedgerEntry[] {
// Retrieves the payment deposit entry.
const paymentEntry = this.paymentGLEntry;
// Retrieves the payment debit A/R entry.
const payableEntry = this.paymentGLPayableEntry;
// Retrieves the exchange gain/loss entries.
const exGainLossEntries = this.paymentExGainOrLossEntries;
return [paymentEntry, payableEntry, ...exGainLossEntries];
};
/**
* Retrieves the bill payment ledger.
* @param {IBillPayment} billPayment
* @param {number} APAccountId
* @returns {Ledger}
*/
public getBillPaymentLedger(): Ledger {
const entries = this.paymentGLEntries;
return new Ledger(entries);
}
}

View File

@@ -0,0 +1,99 @@
import { Knex } from 'knex';
import { BillPaymentGL } from './BillPaymentGL';
import { Inject, Injectable } from '@nestjs/common';
import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service';
import { Account } from '@/modules/Accounts/models/Account.model';
import { BillPayment } from '../models/BillPayment';
import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository';
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class BillPaymentGLEntries {
constructor(
private readonly ledgerStorage: LedgerStorageService,
private readonly accountRepository: AccountRepository,
private readonly tenancyContext: TenancyContext,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
@Inject(Account.name)
private readonly accountModel: TenantModelProxy<typeof Account>,
) {}
/**
* Creates a bill payment GL entries.
* @param {number} billPaymentId - Bill payment id.
* @param {Knex.Transaction} trx - Knex transaction.
*/
public writePaymentGLEntries = async (
billPaymentId: number,
trx?: Knex.Transaction,
): Promise<void> => {
// Retrieves the bill payment details with associated entries.
const payment = await this.billPaymentModel()
.query(trx)
.findById(billPaymentId)
.withGraphFetched('entries.bill');
// Retrieves the given tenant metadata.
const tenantMeta = await this.tenancyContext.getTenantMetadata();
// Finds or creates a new A/P account of the given currency.
const APAccount = await this.accountRepository.findOrCreateAccountsPayable(
payment.currencyCode,
{},
trx,
);
// Exchange gain or loss account.
const EXGainLossAccount = await this.accountModel()
.query(trx)
.modify('findBySlug', 'exchange-grain-loss')
.first();
// Retrieves the bill payment ledger.
const ledger = new BillPaymentGL(payment)
.setAPAccountId(APAccount.id)
.setGainLossAccountId(EXGainLossAccount.id)
.setBaseCurrency(tenantMeta.baseCurrency)
.getBillPaymentLedger();
// Commits the ledger on the storage.
await this.ledgerStorage.commit(ledger, trx);
};
/**
* Rewrites the bill payment GL entries.
* @param {number} tenantId
* @param {number} billPaymentId
* @param {Knex.Transaction} trx
*/
public rewritePaymentGLEntries = async (
billPaymentId: number,
trx?: Knex.Transaction,
): Promise<void> => {
// Revert payment GL entries.
await this.revertPaymentGLEntries(billPaymentId, trx);
// Write payment GL entries.
await this.writePaymentGLEntries(billPaymentId, trx);
};
/**
* Reverts the bill payment GL entries.
* @param {number} tenantId
* @param {number} billPaymentId
* @param {Knex.Transaction} trx
*/
public revertPaymentGLEntries = async (
billPaymentId: number,
trx?: Knex.Transaction,
): Promise<void> => {
await this.ledgerStorage.deleteByReference(
billPaymentId,
'BillPayment',
trx,
);
};
}

View File

@@ -0,0 +1,258 @@
import { Inject, Injectable } from '@nestjs/common';
import { sumBy, difference } from 'lodash';
import { ERRORS } from '../constants';
import { Bill } from '../../Bills/models/Bill';
import { BillPayment } from '../models/BillPayment';
import { BillPaymentEntry } from '../models/BillPaymentEntry';
import { ServiceError } from '../../Items/ServiceError';
import { ACCOUNT_TYPE } from '@/constants/accounts';
import { Account } from '../../Accounts/models/Account.model';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import {
BillPaymentEntryDto,
EditBillPaymentDto,
} from '../dtos/BillPayment.dto';
@Injectable()
export class BillPaymentValidators {
constructor(
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<typeof Bill>,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
@Inject(BillPaymentEntry.name)
private readonly billPaymentEntryModel: TenantModelProxy<
typeof BillPaymentEntry
>,
@Inject(Account.name)
private readonly accountModel: TenantModelProxy<typeof Account>,
) {}
/**
* Validates the bill payment existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
public async getPaymentMadeOrThrowError(paymentMadeId: number) {
const billPayment = await this.billPaymentModel()
.query()
.withGraphFetched('entries')
.findById(paymentMadeId);
if (!billPayment) {
throw new ServiceError(ERRORS.PAYMENT_MADE_NOT_FOUND);
}
return billPayment;
}
/**
* Validates the payment account.
* @param {number} tenantId -
* @param {number} paymentAccountId
* @return {Promise<IAccountType>}
*/
public async getPaymentAccountOrThrowError(paymentAccountId: number) {
const paymentAccount = await this.accountModel()
.query()
.findById(paymentAccountId);
if (!paymentAccount) {
throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_FOUND);
}
// Validate the payment account type.
if (
!paymentAccount.isAccountType([
ACCOUNT_TYPE.BANK,
ACCOUNT_TYPE.CASH,
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
])
) {
throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE);
}
return paymentAccount;
}
/**
* Validates the payment number uniqness.
* @param {number} tenantId -
* @param {string} paymentMadeNumber -
* @return {Promise<IBillPayment>}
*/
public async validatePaymentNumber(
paymentMadeNumber: string,
notPaymentMadeId?: number,
) {
const foundBillPayment = await this.billPaymentModel()
.query()
.onBuild((builder: any) => {
builder.findOne('payment_number', paymentMadeNumber);
if (notPaymentMadeId) {
builder.whereNot('id', notPaymentMadeId);
}
});
if (foundBillPayment) {
throw new ServiceError(ERRORS.BILL_PAYMENT_NUMBER_NOT_UNQIUE);
}
return foundBillPayment;
}
/**
* Validate whether the entries bills ids exist on the storage.
*/
public async validateBillsExistance(
billPaymentEntries: { billId: number }[],
vendorId: number,
) {
const entriesBillsIds = billPaymentEntries.map((e: any) => e.billId);
const storedBills = await this.billModel()
.query()
.whereIn('id', entriesBillsIds)
.where('vendor_id', vendorId);
const storedBillsIds = storedBills.map((t: Bill) => t.id);
const notFoundBillsIds = difference(entriesBillsIds, storedBillsIds);
if (notFoundBillsIds.length > 0) {
throw new ServiceError(ERRORS.BILL_ENTRIES_IDS_NOT_FOUND);
}
// Validate the not opened bills.
const notOpenedBills = storedBills.filter((bill) => !bill.openedAt);
if (notOpenedBills.length > 0) {
throw new ServiceError(ERRORS.BILLS_NOT_OPENED_YET, null, {
notOpenedBills,
});
}
return storedBills;
}
/**
* Validate wether the payment amount bigger than the payable amount.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {void}
*/
public async validateBillsDueAmount(
billPaymentEntries: BillPaymentEntryDto[],
oldPaymentEntries: BillPaymentEntry[] = [],
) {
const billsIds = billPaymentEntries.map(
(entry: BillPaymentEntryDto) => entry.billId,
);
const storedBills = await this.billModel().query().whereIn('id', billsIds);
const storedBillsMap = new Map(
storedBills.map((bill) => {
const oldEntries = oldPaymentEntries.filter(
(entry) => entry.billId === bill.id,
);
const oldPaymentAmount = sumBy(oldEntries, 'paymentAmount') || 0;
return [
bill.id,
{ ...bill, dueAmount: bill.dueAmount + oldPaymentAmount },
];
}),
);
interface invalidPaymentAmountError {
index: number;
due_amount: number;
}
const hasWrongPaymentAmount: invalidPaymentAmountError[] = [];
billPaymentEntries.forEach((entry: BillPaymentEntryDto, index: number) => {
const entryBill = storedBillsMap.get(entry.billId);
const { dueAmount } = entryBill;
if (dueAmount < entry.paymentAmount) {
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
}
});
if (hasWrongPaymentAmount.length > 0) {
throw new ServiceError(ERRORS.INVALID_BILL_PAYMENT_AMOUNT);
}
}
/**
* Validate the payment receive entries IDs existance.
* @param {Request} req
* @param {Response} res
* @return {Response}
*/
public async validateEntriesIdsExistance(
billPaymentId: number,
billPaymentEntries: BillPaymentEntry[],
) {
const entriesIds = billPaymentEntries
.filter((entry: any) => entry.id)
.map((entry: any) => entry.id);
const storedEntries = await this.billPaymentEntryModel()
.query()
.where('bill_payment_id', billPaymentId);
const storedEntriesIds = storedEntries.map((entry: any) => entry.id);
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
if (notFoundEntriesIds.length > 0) {
throw new ServiceError(ERRORS.BILL_PAYMENT_ENTRIES_NOT_FOUND);
}
}
/**
* * Validate the payment vendor whether modified.
* @param {string} billPaymentNo
*/
public validateVendorNotModified(
billPaymentDTO: EditBillPaymentDto,
oldBillPayment: BillPayment,
) {
if (billPaymentDTO.vendorId !== oldBillPayment.vendorId) {
throw new ServiceError(ERRORS.PAYMENT_NUMBER_SHOULD_NOT_MODIFY);
}
}
/**
* Validates the payment account currency code. The deposit account curreny
* should be equals the customer currency code or the base currency.
* @param {string} paymentAccountCurrency
* @param {string} customerCurrency
* @param {string} baseCurrency
* @throws {ServiceError(ERRORS.WITHDRAWAL_ACCOUNT_CURRENCY_INVALID)}
*/
public validateWithdrawalAccountCurrency = (
paymentAccountCurrency: string,
customerCurrency: string,
baseCurrency: string,
) => {
if (
paymentAccountCurrency !== customerCurrency &&
paymentAccountCurrency !== baseCurrency
) {
throw new ServiceError(ERRORS.WITHDRAWAL_ACCOUNT_CURRENCY_INVALID);
}
};
/**
* Validates the given vendor has no associated payments.
* @param {number} tenantId
* @param {number} vendorId
*/
public async validateVendorHasNoPayments(vendorId: number) {
const payments = await this.billPaymentModel()
.query()
.where('vendor_id', vendorId);
if (payments.length > 0) {
throw new ServiceError(ERRORS.VENDOR_HAS_PAYMENTS);
}
}
}

View File

@@ -0,0 +1,45 @@
// import { Inject, Service } from 'typedi';
// import { Knex } from 'knex';
// import { IBillPaymentDTO } from '@/interfaces';
// import { CreateBillPayment } from './CreateBillPayment';
// import { Importable } from '@/services/Import/Importable';
// import { BillsPaymentsSampleData } from './constants';
// @Service()
// export class BillPaymentsImportable extends Importable {
// @Inject()
// private createBillPaymentService: CreateBillPayment;
// /**
// * Importing to account service.
// * @param {number} tenantId
// * @param {IAccountCreateDTO} createAccountDTO
// * @returns
// */
// public importable(
// tenantId: number,
// billPaymentDTO: IBillPaymentDTO,
// trx?: Knex.Transaction
// ) {
// return this.createBillPaymentService.createBillPayment(
// tenantId,
// billPaymentDTO,
// 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 BillsPaymentsSampleData;
// }
// }

View File

@@ -0,0 +1,106 @@
import { omit } from 'lodash';
import { ERRORS } from '../constants';
import { Inject, Injectable } from '@nestjs/common';
import { Bill } from '../../Bills/models/Bill';
import { BillPayment } from '../models/BillPayment';
import { IBillReceivePageEntry } from '../types/BillPayments.types';
import { ServiceError } from '../../Items/ServiceError';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export default class BillPaymentsPages {
/**
* @param {TenantModelProxy<typeof Bill>} billModel - Bill model.
* @param {TenantModelProxy<typeof BillPayment>} billPaymentModel - Bill payment model.
*/
constructor(
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<typeof Bill>,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {}
/**
* Retrieve bill payment with associated metadata.
* @param {number} billPaymentId - The bill payment id.
* @return {object}
*/
public async getBillPaymentEditPage(billPaymentId: number): Promise<{
billPayment: Omit<BillPayment, 'entries'>;
entries: IBillReceivePageEntry[];
}> {
const billPayment = await this.billPaymentModel()
.query()
.findById(billPaymentId)
.withGraphFetched('entries.bill')
.withGraphFetched('attachments');
// Throw not found the bill payment.
if (!billPayment) {
throw new ServiceError(ERRORS.PAYMENT_MADE_NOT_FOUND);
}
const paymentEntries = billPayment.entries.map((entry) => ({
...this.mapBillToPageEntry(entry.bill),
dueAmount: entry.bill.dueAmount + entry.paymentAmount,
paymentAmount: entry.paymentAmount,
}));
const resPayableBills = await Bill.query()
.modify('opened')
.modify('dueBills')
.where('vendor_id', billPayment.vendorId)
.whereNotIn(
'id',
billPayment.entries.map((e) => e.billId),
)
.orderBy('bill_date', 'ASC');
// Mapping the payable bills to entries.
const restPayableEntries = resPayableBills.map(this.mapBillToPageEntry);
const entries = [...paymentEntries, ...restPayableEntries];
return {
billPayment: omit(billPayment, ['entries']),
entries,
};
}
/**
* Retrieve the payable entries of the new page once vendor be selected.
* @param {number} tenantId
* @param {number} vendorId
*/
public async getNewPageEntries(
vendorId: number,
): Promise<IBillReceivePageEntry[]> {
// Retrieve all payable bills that associated to the payment made transaction.
const payableBills = await this.billModel()
.query()
.modify('opened')
.modify('dueBills')
.where('vendor_id', vendorId)
.orderBy('bill_date', 'ASC');
return payableBills.map(this.mapBillToPageEntry);
}
/**
* Retrive edit page invoices entries from the given sale invoices models.
* @param {Bill} bill - Bill.
* @return {IBillReceivePageEntry}
*/
private mapBillToPageEntry(bill: Bill): IBillReceivePageEntry {
return {
entryType: 'invoice',
billId: bill.id,
billNo: bill.billNumber,
amount: bill.amount,
dueAmount: bill.dueAmount,
totalPaymentAmount: bill.paymentAmount,
paymentAmount: bill.paymentAmount,
currencyCode: bill.currencyCode,
date: bill.billDate,
};
}
}

View File

@@ -0,0 +1,54 @@
import { Injectable } from '@nestjs/common';
import * as R from 'ramda';
import { omit, sumBy } from 'lodash';
import { formatDateFields } from '@/utils/format-date-fields';
import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index';
import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations/BranchTransactionDTOTransform';
import { Vendor } from '@/modules/Vendors/models/Vendor';
import { BillPayment } from '../models/BillPayment';
import {
CreateBillPaymentDto,
EditBillPaymentDto,
} from '../dtos/BillPayment.dto';
@Injectable()
export class CommandBillPaymentDTOTransformer {
constructor(
private readonly branchDTOTransform: BranchTransactionDTOTransformer,
) {}
/**
* Transforms create/edit DTO to model.
* @param {number} tenantId
* @param {IBillPaymentDTO} billPaymentDTO - Bill payment.
* @param {IBillPayment} oldBillPayment - Old bill payment.
* @return {Promise<IBillPayment>}
*/
public async transformDTOToModel(
billPaymentDTO: CreateBillPaymentDto | EditBillPaymentDto,
vendor: Vendor,
oldBillPayment?: BillPayment,
): Promise<BillPayment> {
const amount =
billPaymentDTO.amount ?? sumBy(billPaymentDTO.entries, 'paymentAmount');
// Associate the default index to each item entry.
const entries = R.compose(
// Associate the default index to payment entries.
assocItemEntriesDefaultIndex,
)(billPaymentDTO.entries);
const initialDTO = {
...formatDateFields(omit(billPaymentDTO, ['attachments']), [
'paymentDate',
]),
amount,
currencyCode: vendor.currencyCode,
exchangeRate: billPaymentDTO.exchangeRate || 1,
entries,
};
return R.compose(this.branchDTOTransform.transformDTO<BillPayment>)(
initialDTO,
);
}
}

View File

@@ -0,0 +1,122 @@
import { Knex } from 'knex';
import {
IBillPaymentEventCreatedPayload,
IBillPaymentCreatingPayload,
} from '../types/BillPayments.types';
import { Inject, Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service';
import { BillPaymentValidators } from './BillPaymentValidators.service';
import { CommandBillPaymentDTOTransformer } from './CommandBillPaymentDTOTransformer.service';
import { events } from '@/common/events/events';
import { TenancyContext } from '../../Tenancy/TenancyContext.service';
import { BillPayment } from '../models/BillPayment';
import { Vendor } from '../../Vendors/models/Vendor';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { CreateBillPaymentDto } from '../dtos/BillPayment.dto';
@Injectable()
export class CreateBillPaymentService {
/**
* @param {UnitOfWork} uow - Unit of work service.
* @param {EventEmitter2} eventPublisher - Event emitter service.
* @param {BillPaymentValidators} validators - Bill payment validators service.
* @param {CommandBillPaymentDTOTransformer} commandTransformerDTO - Command bill payment DTO transformer service.
* @param {TenancyContext} tenancyContext - Tenancy context service.
* @param {TenantModelProxy<typeof Vendor>} vendorModel - Vendor model.
* @param {TenantModelProxy<typeof BillPayment>} billPaymentModel - Bill payment model.
*/
constructor(
private uow: UnitOfWork,
private eventPublisher: EventEmitter2,
private validators: BillPaymentValidators,
private commandTransformerDTO: CommandBillPaymentDTOTransformer,
private tenancyContext: TenancyContext,
@Inject(Vendor.name)
private readonly vendorModel: TenantModelProxy<typeof Vendor>,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {}
/**
* Creates a new bill payment transcations and store it to the storage
* with associated bills entries and journal transactions.
* ------
* Precedures:-
* ------
* - Records the bill payment transaction.
* - Records the bill payment associated entries.
* - Increment the payment amount of the given vendor bills.
* - Decrement the vendor balance.
* - Records payment journal entries.
* ------
* @param {number} tenantId - Tenant id.
* @param {BillPaymentDTO} billPayment - Bill payment object.
*/
public async createBillPayment(
billPaymentDTO: CreateBillPaymentDto,
trx?: Knex.Transaction,
): Promise<BillPayment> {
const tenantMeta = await this.tenancyContext.getTenant(true);
// Retrieves the payment vendor or throw not found error.
const vendor = await this.vendorModel()
.query()
.findById(billPaymentDTO.vendorId)
.throwIfNotFound();
// Transform create DTO to model object.
const billPaymentObj = await this.commandTransformerDTO.transformDTOToModel(
billPaymentDTO,
vendor,
);
// Validate the payment account existance and type.
const paymentAccount = await this.validators.getPaymentAccountOrThrowError(
billPaymentObj.paymentAccountId,
);
// Validate the payment number uniquiness.
if (billPaymentObj.paymentNumber) {
await this.validators.validatePaymentNumber(billPaymentObj.paymentNumber);
}
// Validates the bills existance and associated to the given vendor.
await this.validators.validateBillsExistance(
billPaymentObj.entries,
billPaymentDTO.vendorId,
);
// Validates the bills due payment amount.
await this.validators.validateBillsDueAmount(billPaymentObj.entries);
// Validates the withdrawal account currency code.
this.validators.validateWithdrawalAccountCurrency(
paymentAccount.currencyCode,
vendor.currencyCode,
tenantMeta.metadata.baseCurrency,
);
// Writes bill payment transacation with associated transactions
// under unit-of-work envirement.
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
// Triggers `onBillPaymentCreating` event.
await this.eventPublisher.emitAsync(events.billPayment.onCreating, {
billPaymentDTO,
trx,
} as IBillPaymentCreatingPayload);
// Writes the bill payment graph to the storage.
const billPayment = await this.billPaymentModel()
.query(trx)
.insertGraphAndFetch({
...billPaymentObj,
});
// Triggers `onBillPaymentCreated` event.
await this.eventPublisher.emitAsync(events.billPayment.onCreated, {
billPayment,
billPaymentId: billPayment.id,
billPaymentDTO,
trx,
} as IBillPaymentEventCreatedPayload);
return billPayment;
}, trx);
}
}

View File

@@ -0,0 +1,77 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import {
IBillPaymentDeletingPayload,
IBillPaymentEventDeletedPayload,
} from '../types/BillPayments.types';
import { BillPayment } from '../models/BillPayment';
import { BillPaymentEntry } from '../models/BillPaymentEntry';
import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class DeleteBillPayment {
/**
* @param {EventPublisher} eventPublisher - Event publisher.
* @param {UnitOfWork} uow - Unit of work.
* @param {typeof BillPayment} billPaymentModel - Bill payment model.
* @param {typeof BillPaymentEntry} billPaymentEntryModel - Bill payment entry model.
*/
constructor(
private readonly eventEmitter: EventEmitter2,
private readonly uow: UnitOfWork,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
@Inject(BillPaymentEntry.name)
private readonly billPaymentEntryModel: TenantModelProxy<
typeof BillPaymentEntry
>,
) {}
/**
* Deletes the bill payment and associated transactions.
* @param {Integer} billPaymentId - The given bill payment id.
* @return {Promise}
*/
public async deleteBillPayment(billPaymentId: number) {
// Retrieve the bill payment or throw not found service error.
const oldBillPayment = await this.billPaymentModel()
.query()
.withGraphFetched('entries')
.findById(billPaymentId)
.throwIfNotFound();
// Deletes the bill transactions with associated transactions under
// unit-of-work environment.
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
// Triggers `onBillPaymentDeleting` payload.
await this.eventEmitter.emitAsync(events.billPayment.onDeleting, {
oldBillPayment,
trx,
} as IBillPaymentDeletingPayload);
// Deletes the bill payment associated entries.
await this.billPaymentEntryModel()
.query(trx)
.where('bill_payment_id', billPaymentId)
.delete();
// Deletes the bill payment transaction.
await this.billPaymentModel()
.query(trx)
.where('id', billPaymentId)
.delete();
// Triggers `onBillPaymentDeleted` event.
await this.eventEmitter.emitAsync(events.billPayment.onDeleted, {
billPaymentId,
oldBillPayment,
trx,
} as IBillPaymentEventDeletedPayload);
});
}
}

View File

@@ -0,0 +1,137 @@
import { Inject, Injectable } from '@nestjs/common';
import { BillPaymentValidators } from './BillPaymentValidators.service';
import {
IBillPaymentEditingPayload,
IBillPaymentEventEditedPayload,
} from '../types/BillPayments.types';
import { Knex } from 'knex';
import { BillPayment } from '../models/BillPayment';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
import { CommandBillPaymentDTOTransformer } from './CommandBillPaymentDTOTransformer.service';
import { Vendor } from '@/modules/Vendors/models/Vendor';
import { events } from '@/common/events/events';
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { EditBillPaymentDto } from '../dtos/BillPayment.dto';
@Injectable()
export class EditBillPayment {
constructor(
private readonly validators: BillPaymentValidators,
private readonly eventPublisher: EventEmitter2,
private readonly uow: UnitOfWork,
private readonly transformer: CommandBillPaymentDTOTransformer,
private readonly tenancyContext: TenancyContext,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
@Inject(Vendor.name)
private readonly vendorModel: TenantModelProxy<typeof Vendor>,
) {}
/**
* Edits the details of the given bill payment.
*
* Preceducres:
* ------
* - Update the bill payment transaction.
* - Insert the new bill payment entries that have no ids.
* - Update the bill paymeny entries that have ids.
* - Delete the bill payment entries that not presented.
* - Re-insert the journal transactions and update the diff accounts balance.
* - Update the diff vendor balance.
* - Update the diff bill payment amount.
* ------
* @param {Integer} billPaymentId
* @param {EditBillPaymentDto} billPayment
* @param {BillPayment} oldBillPayment
*/
public async editBillPayment(
billPaymentId: number,
billPaymentDTO: EditBillPaymentDto,
): Promise<BillPayment> {
const tenantMeta = await this.tenancyContext.getTenant(true);
const oldBillPayment = await this.billPaymentModel()
.query()
.findById(billPaymentId)
.withGraphFetched('entries')
.throwIfNotFound();
const vendor = await this.vendorModel()
.query()
.findById(billPaymentDTO.vendorId)
.throwIfNotFound();
const billPaymentObj = await this.transformer.transformDTOToModel(
billPaymentDTO,
vendor,
oldBillPayment,
);
// Validate vendor not modified.
this.validators.validateVendorNotModified(billPaymentDTO, oldBillPayment);
// Validate the payment account existance and type.
const paymentAccount = await this.validators.getPaymentAccountOrThrowError(
billPaymentObj.paymentAccountId,
);
// Validate the items entries IDs existance on the storage.
await this.validators.validateEntriesIdsExistance(
billPaymentId,
billPaymentObj.entries,
);
// Validate the bills existance and associated to the given vendor.
await this.validators.validateBillsExistance(
billPaymentObj.entries,
billPaymentDTO.vendorId,
);
// Validates the bills due payment amount.
await this.validators.validateBillsDueAmount(
billPaymentObj.entries,
oldBillPayment.entries,
);
// Validate the payment number uniquiness.
if (billPaymentObj.paymentNumber) {
await this.validators.validatePaymentNumber(
billPaymentObj.paymentNumber,
billPaymentId,
);
}
// Validates the withdrawal account currency code.
this.validators.validateWithdrawalAccountCurrency(
paymentAccount.currencyCode,
vendor.currencyCode,
tenantMeta.metadata.baseCurrency,
);
// Edits the bill transactions with associated transactions
// under unit-of-work envirement.
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
// Triggers `onBillPaymentEditing` event.
await this.eventPublisher.emitAsync(events.billPayment.onEditing, {
oldBillPayment,
billPaymentDTO,
trx,
} as IBillPaymentEditingPayload);
// Edits the bill payment transaction graph on the storage.
const billPayment = await this.billPaymentModel()
.query(trx)
.upsertGraphAndFetch({
id: billPaymentId,
...billPaymentObj,
});
// Triggers `onBillPaymentEdited` event.
await this.eventPublisher.emitAsync(events.billPayment.onEdited, {
billPaymentId,
billPayment,
oldBillPayment,
billPaymentDTO,
trx,
} as IBillPaymentEventEditedPayload);
return billPayment;
});
}
}

View File

@@ -0,0 +1,50 @@
export const ERRORS = {
BILL_VENDOR_NOT_FOUND: 'VENDOR_NOT_FOUND',
PAYMENT_MADE_NOT_FOUND: 'PAYMENT_MADE_NOT_FOUND',
BILL_PAYMENT_NUMBER_NOT_UNQIUE: 'BILL_PAYMENT_NUMBER_NOT_UNQIUE',
PAYMENT_ACCOUNT_NOT_FOUND: 'PAYMENT_ACCOUNT_NOT_FOUND',
PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE:
'PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE',
BILL_ENTRIES_IDS_NOT_FOUND: 'BILL_ENTRIES_IDS_NOT_FOUND',
BILL_PAYMENT_ENTRIES_NOT_FOUND: 'BILL_PAYMENT_ENTRIES_NOT_FOUND',
INVALID_BILL_PAYMENT_AMOUNT: 'INVALID_BILL_PAYMENT_AMOUNT',
PAYMENT_NUMBER_SHOULD_NOT_MODIFY: 'PAYMENT_NUMBER_SHOULD_NOT_MODIFY',
BILLS_NOT_OPENED_YET: 'BILLS_NOT_OPENED_YET',
VENDOR_HAS_PAYMENTS: 'VENDOR_HAS_PAYMENTS',
WITHDRAWAL_ACCOUNT_CURRENCY_INVALID: 'WITHDRAWAL_ACCOUNT_CURRENCY_INVALID',
};
export const DEFAULT_VIEWS = [];
export const BillsPaymentsSampleData = [
{
'Payment Date': '2024-03-01',
Vendor: 'Gabriel Kovacek',
'Payment No.': 'P-10001',
'Reference No.': 'REF-1',
'Payment Account': 'Petty Cash',
Statement: 'Vel et dolorem architecto veniam.',
'Bill No': 'B-120',
'Payment Amount': 100,
},
{
'Payment Date': '2024-03-02',
Vendor: 'Gabriel Kovacek',
'Payment No.': 'P-10002',
'Reference No.': 'REF-2',
'Payment Account': 'Petty Cash',
Statement: 'Id est molestias.',
'Bill No': 'B-121',
'Payment Amount': 100,
},
{
'Payment Date': '2024-03-03',
Vendor: 'Gabriel Kovacek',
'Payment No.': 'P-10003',
'Reference No.': 'REF-3',
'Payment Account': 'Petty Cash',
Statement: 'Quam cupiditate at nihil dicta dignissimos non fugit illo.',
'Bill No': 'B-122',
'Payment Amount': 100,
},
];

View File

@@ -0,0 +1,120 @@
import { Type } from 'class-transformer';
import {
IsArray,
IsDate,
IsNotEmpty,
IsNumber,
IsOptional,
IsString,
ValidateNested,
} from 'class-validator';
import { AttachmentLinkDto } from '@/modules/Attachments/dtos/Attachment.dto';
import { ApiProperty } from '@nestjs/swagger';
export class BillPaymentEntryDto {
@IsNumber()
billId: number;
@IsNumber()
paymentAmount: number;
}
export class CommandBillPaymentDTO {
@IsNumber()
@IsNotEmpty()
@ApiProperty({
description: 'The id of the vendor',
example: 1,
})
vendorId: number;
@IsNumber()
@IsOptional()
@ApiProperty({
description: 'The amount of the bill payment',
example: 100,
})
amount?: number;
@IsNumber()
@IsNotEmpty()
@ApiProperty({
description: 'The id of the payment account',
example: 1,
})
paymentAccountId: number;
@IsString()
@IsOptional()
@ApiProperty({
description: 'The payment number of the bill payment',
example: '123456',
})
paymentNumber?: string;
@IsDate()
@Type(() => Date)
@ApiProperty({
description: 'The payment date of the bill payment',
example: '2021-01-01',
})
paymentDate: Date | string;
@IsNumber()
@IsOptional()
@ApiProperty({
description: 'The exchange rate of the bill payment',
example: 1,
})
exchangeRate?: number;
@IsString()
@IsOptional()
@ApiProperty({
description: 'The statement of the bill payment',
example: '123456',
})
statement?: string;
@IsString()
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => BillPaymentEntryDto)
@ApiProperty({
description: 'The entries of the bill payment',
example: [
{
billId: 1,
paymentAmount: 100,
},
],
})
entries: BillPaymentEntryDto[];
@IsNumber()
@IsOptional()
@ApiProperty({
description: 'The id of the branch',
example: 1,
})
branchId?: number;
@IsArray()
@IsOptional()
@ValidateNested({ each: true })
@Type(() => AttachmentLinkDto)
@ApiProperty({
description: 'The attachments of the bill payment',
example: [
{
id: 1,
type: 'bill',
},
],
})
attachments?: AttachmentLinkDto[];
}
export class CreateBillPaymentDto extends CommandBillPaymentDTO {}
export class EditBillPaymentDto extends CommandBillPaymentDTO {}

View File

@@ -0,0 +1,185 @@
import { Model, mixin } from 'objection';
// import TenantModel from 'models/TenantModel';
// import ModelSetting from './ModelSetting';
// import BillPaymentSettings from './BillPayment.Settings';
// import CustomViewBaseModel from './CustomViewBaseModel';
// import { DEFAULT_VIEWS } from '@/services/Sales/PaymentReceived/constants';
// import ModelSearchable from './ModelSearchable';
import { BaseModel } from '@/models/Model';
import { BillPaymentEntry } from './BillPaymentEntry';
import { Vendor } from '@/modules/Vendors/models/Vendor';
import { Document } from '@/modules/ChromiumlyTenancy/models/Document';
export class BillPayment extends BaseModel{
vendorId: number;
amount: number;
currencyCode: string;
paymentAccountId: number;
paymentNumber: string;
paymentDate: string;
paymentMethod: string;
reference: string;
userId: number;
statement: string;
exchangeRate: number;
createdAt?: Date;
updatedAt?: Date;
branchId?: number;
entries?: BillPaymentEntry[];
vendor?: Vendor;
attachments?: Document[];
/**
* Table name
*/
static get tableName() {
return 'bills_payments';
}
/**
* Timestamps columns.
*/
get timestamps() {
return ['createdAt', 'updatedAt'];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return ['localAmount'];
}
/**
* Payment amount in local currency.
* @returns {number}
*/
get localAmount() {
return this.amount * this.exchangeRate;
}
/**
* Model settings.
*/
// static get meta() {
// return BillPaymentSettings;
// }
/**
* Relationship mapping.
*/
// static get relationMappings() {
// const BillPaymentEntry = require('models/BillPaymentEntry');
// const AccountTransaction = require('models/AccountTransaction');
// const Vendor = require('models/Vendor');
// const Account = require('models/Account');
// const Branch = require('models/Branch');
// const Document = require('models/Document');
// return {
// entries: {
// relation: Model.HasManyRelation,
// modelClass: BillPaymentEntry.default,
// join: {
// from: 'bills_payments.id',
// to: 'bills_payments_entries.billPaymentId',
// },
// filter: (query) => {
// query.orderBy('index', 'ASC');
// },
// },
// vendor: {
// relation: Model.BelongsToOneRelation,
// modelClass: Vendor.default,
// join: {
// from: 'bills_payments.vendorId',
// to: 'contacts.id',
// },
// filter(query) {
// query.where('contact_service', 'vendor');
// },
// },
// paymentAccount: {
// relation: Model.BelongsToOneRelation,
// modelClass: Account.default,
// join: {
// from: 'bills_payments.paymentAccountId',
// to: 'accounts.id',
// },
// },
// transactions: {
// relation: Model.HasManyRelation,
// modelClass: AccountTransaction.default,
// join: {
// from: 'bills_payments.id',
// to: 'accounts_transactions.referenceId',
// },
// filter(builder) {
// builder.where('reference_type', 'BillPayment');
// },
// },
// /**
// * Bill payment may belongs to branch.
// */
// branch: {
// relation: Model.BelongsToOneRelation,
// modelClass: Branch.default,
// join: {
// from: 'bills_payments.branchId',
// to: 'branches.id',
// },
// },
// /**
// * Bill payment may has many attached attachments.
// */
// attachments: {
// relation: Model.ManyToManyRelation,
// modelClass: Document.default,
// join: {
// from: 'bills_payments.id',
// through: {
// from: 'document_links.modelId',
// to: 'document_links.documentId',
// },
// to: 'documents.id',
// },
// filter(query) {
// query.where('model_ref', 'BillPayment');
// },
// },
// };
// }
/**
* Retrieve the default custom views, roles and columns.
*/
// static get defaultViews() {
// return DEFAULT_VIEWS;
// }
/**
* Model search attributes.
*/
static get searchRoles() {
return [
{ fieldKey: 'payment_number', comparator: 'contains' },
{ condition: 'or', fieldKey: 'reference_no', comparator: 'contains' },
{ condition: 'or', fieldKey: 'amount', comparator: 'equals' },
];
}
/**
* Prevents mutate base currency since the model is not empty.
*/
static get preventMutateBaseCurrency() {
return true;
}
}

View File

@@ -0,0 +1,56 @@
import { Model } from 'objection';
// import TenantModel from 'models/TenantModel';
import { BaseModel } from '@/models/Model';
import { Bill } from '@/modules/Bills/models/Bill';
import { BillPayment } from './BillPayment';
export class BillPaymentEntry extends BaseModel {
public billPaymentId: number;
public billId: number;
public paymentAmount: number;
public index: number;
bill?: Bill;
payment?: BillPayment;
/**
* Table name
*/
static get tableName() {
return 'bills_payments_entries';
}
/**
* Timestamps columns.
*/
get timestamps() {
return [];
}
/**
* Relationship mapping.
*/
static get relationMappings() {
const { Bill } = require('../../Bills/models/Bill');
const { BillPayment } = require('../../BillPayments/models/BillPayment');
return {
payment: {
relation: Model.BelongsToOneRelation,
modelClass: BillPayment,
join: {
from: 'bills_payments_entries.billPaymentId',
to: 'bills_payments.id',
},
},
bill: {
relation: Model.BelongsToOneRelation,
modelClass: Bill,
join: {
from: 'bills_payments_entries.billId',
to: 'bills.id',
},
},
};
}
}

View File

@@ -0,0 +1,27 @@
import { BillTransformer } from "../../Bills/queries/Bill.transformer";
import { Transformer } from "../../Transformer/Transformer";
export class BillPaymentEntryTransformer extends Transformer{
/**
* Include these attributes to bill payment object.
* @returns {Array}
*/
public includeAttributes = (): string[] => {
return ['paymentAmountFormatted', 'bill'];
};
/**
* Retreives the bill.
*/
protected bill = (entry) => {
return this.item(entry.bill, new BillTransformer());
};
/**
* Retreives the payment amount formatted.
* @returns {string}
*/
protected paymentAmountFormatted(entry) {
return this.formatNumber(entry.paymentAmount, { money: false });
}
}

View File

@@ -0,0 +1,60 @@
import { Transformer } from '@/modules/Transformer/Transformer';
export class BillPaymentTransactionTransformer extends Transformer {
/**
* Include these attributes to sale credit note object.
* @returns {Array}
*/
public includeAttributes = (): string[] => {
return ['formattedPaymentAmount', 'formattedPaymentDate'];
};
/**
* Retrieve formatted bill payment amount.
* @param {ICreditNote} credit
* @returns {string}
*/
protected formattedPaymentAmount = (entry): string => {
return this.formatNumber(entry.paymentAmount, {
currencyCode: entry.payment.currencyCode,
});
};
/**
* Retrieve formatted bill payment date.
* @param entry
* @returns {string}
*/
protected formattedPaymentDate = (entry): string => {
return this.formatDate(entry.payment.paymentDate);
};
/**
*
* @param entry
* @returns
*/
public transform = (entry) => {
return {
billId: entry.billId,
billPaymentId: entry.billPaymentId,
paymentDate: entry.payment.paymentDate,
formattedPaymentDate: entry.formattedPaymentDate,
paymentAmount: entry.paymentAmount,
formattedPaymentAmount: entry.formattedPaymentAmount,
currencyCode: entry.payment.currencyCode,
paymentNumber: entry.payment.paymentNumber,
paymentReferenceNo: entry.payment.reference,
billNumber: entry.bill.billNumber,
billReferenceNo: entry.bill.referenceNo,
paymentAccountId: entry.payment.paymentAccountId,
paymentAccountName: entry.payment.paymentAccount.name,
paymentAccountSlug: entry.payment.paymentAccount.slug,
};
};
}

View File

@@ -0,0 +1,65 @@
import { BillPaymentEntryTransformer } from './BillPaymentEntry.transformer';
import { Transformer } from '@/modules/Transformer/Transformer';
import { BillPayment } from '../models/BillPayment';
import { AttachmentTransformer } from '@/modules/Attachments/Attachment.transformer';
export class BillPaymentTransformer extends Transformer {
/**
* Include these attributes to sale invoice object.
* @returns {Array}
*/
public includeAttributes = (): string[] => {
return [
'formattedPaymentDate',
'formattedCreatedAt',
'formattedAmount',
'entries',
'attachments',
];
};
/**
* Retrieve formatted invoice date.
* @param {IBill} invoice
* @returns {String}
*/
protected formattedPaymentDate = (billPayment: BillPayment): string => {
return this.formatDate(billPayment.paymentDate);
};
/**
* Retrieve formatted created at date.
* @param {IBillPayment} billPayment
* @returns {string}
*/
protected formattedCreatedAt = (billPayment: BillPayment): string => {
return this.formatDate(billPayment.createdAt);
};
/**
* Retrieve formatted bill amount.
* @param {IBill} invoice
* @returns {string}
*/
protected formattedAmount = (billPayment: BillPayment): string => {
return this.formatNumber(billPayment.amount, {
currencyCode: billPayment.currencyCode,
});
};
/**
* Retreives the bill payment entries.
*/
protected entries = (billPayment: BillPayment) => {
return this.item(billPayment.entries, new BillPaymentEntryTransformer());
};
/**
* Retrieves the bill attachments.
* @param {ISaleInvoice} invoice
* @returns
*/
protected attachments = (billPayment: BillPayment) => {
return this.item(billPayment.attachments, new AttachmentTransformer());
};
}

View File

@@ -0,0 +1,38 @@
import { Inject, Injectable } from '@nestjs/common';
import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service';
import { BillPayment } from '../models/BillPayment';
import { BillPaymentTransformer } from './BillPaymentTransformer';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class GetBillPayment {
constructor(
private readonly transformer: TransformerInjectable,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {}
/**
* Retrieves bill payment.
* @param {number} billPyamentId
* @return {Promise<BillPayment>}
*/
public async getBillPayment(billPyamentId: number): Promise<BillPayment> {
const billPayment = await this.billPaymentModel()
.query()
.withGraphFetched('entries.bill')
.withGraphFetched('vendor')
.withGraphFetched('paymentAccount')
.withGraphFetched('transactions')
.withGraphFetched('branch')
.withGraphFetched('attachments')
.findById(billPyamentId)
.throwIfNotFound();
return this.transformer.transform(
billPayment,
new BillPaymentTransformer(),
);
}
}

View File

@@ -0,0 +1,36 @@
import { Inject, Injectable } from '@nestjs/common';
import { Bill } from '@/modules/Bills/models/Bill';
import { BillPayment } from '../models/BillPayment';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class GetPaymentBills {
/**
* @param {typeof Bill} billModel
* @param {typeof BillPayment} billPaymentModel
*/
constructor(
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<typeof Bill>,
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {}
/**
* Retrieve payment made associated bills.
* @param {number} billPaymentId - Bill payment id.
*/
public async getPaymentBills(billPaymentId: number) {
const billPayment = await this.billPaymentModel()
.query()
.findById(billPaymentId)
.throwIfNotFound();
const paymentBillsIds = billPayment.entries.map((entry) => entry.id);
const bills = await this.billModel().query().whereIn('id', paymentBillsIds);
return bills;
}
}

View File

@@ -0,0 +1,60 @@
import {
IBillPaymentEventCreatedPayload,
IBillPaymentEventDeletedPayload,
IBillPaymentEventEditedPayload,
} from '../types/BillPayments.types';
import { BillPaymentGLEntries } from '../commands/BillPaymentGLEntries';
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
@Injectable()
export class BillPaymentGLEntriesSubscriber {
constructor(
private readonly billPaymentGLEntries: BillPaymentGLEntries,
) {}
/**
* Handle bill payment writing journal entries once created.
*/
@OnEvent(events.billPayment.onCreated)
private async handleWriteJournalEntries({
billPayment,
trx,
}: IBillPaymentEventCreatedPayload) {
// Records the journal transactions after bills payment
// and change diff account balance.
await this.billPaymentGLEntries.writePaymentGLEntries(
billPayment.id,
trx
);
};
/**
* Handle bill payment re-writing journal entries once the payment transaction be edited.
*/
@OnEvent(events.billPayment.onEdited)
private async handleRewriteJournalEntriesOncePaymentEdited({
billPayment,
trx,
}: IBillPaymentEventEditedPayload) {
await this.billPaymentGLEntries.rewritePaymentGLEntries(
billPayment.id,
trx
);
};
/**
* Reverts journal entries once bill payment deleted.
*/
@OnEvent(events.billPayment.onDeleted)
private async handleRevertJournalEntries({
billPaymentId,
trx,
}: IBillPaymentEventDeletedPayload) {
await this.billPaymentGLEntries.revertPaymentGLEntries(
billPaymentId,
trx
);
};
}

View File

@@ -0,0 +1,64 @@
import { Knex } from 'knex';
import { BillPayment } from '../models/BillPayment';
import { AttachmentLinkDTO } from '@/modules/Attachments/Attachments.types';
import { CreateBillPaymentDto, EditBillPaymentDto } from '../dtos/BillPayment.dto';
export interface IBillReceivePageEntry {
billId: number;
entryType: string;
billNo: string;
dueAmount: number;
amount: number;
totalPaymentAmount: number;
paymentAmount: number;
currencyCode: string;
date: Date | string;
}
export interface IBillPaymentEventCreatedPayload {
billPayment: BillPayment;
billPaymentDTO: CreateBillPaymentDto;
billPaymentId: number;
trx: Knex.Transaction;
}
export interface IBillPaymentCreatingPayload {
billPaymentDTO: CreateBillPaymentDto;
trx: Knex.Transaction;
}
export interface IBillPaymentEditingPayload {
billPaymentDTO: EditBillPaymentDto;
oldBillPayment: BillPayment;
trx: Knex.Transaction;
}
export interface IBillPaymentEventEditedPayload {
billPaymentId: number;
billPayment: BillPayment;
oldBillPayment: BillPayment;
billPaymentDTO: EditBillPaymentDto;
trx: Knex.Transaction;
}
export interface IBillPaymentEventDeletedPayload {
billPaymentId: number;
oldBillPayment: BillPayment;
trx: Knex.Transaction;
}
export interface IBillPaymentDeletingPayload {
oldBillPayment: BillPayment;
trx: Knex.Transaction;
}
export interface IBillPaymentPublishingPayload {
oldBillPayment: BillPayment;
trx: Knex.Transaction;
}
export enum IPaymentMadeAction {
Create = 'Create',
Edit = 'Edit',
Delete = 'Delete',
View = 'View',
}