mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 05:40:31 +00:00
feat(nestjs): migrate to NestJS
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
// }
|
||||
// }
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
// }
|
||||
// }
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user