mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 22:00:31 +00:00
add server to monorepo.
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
import moment from 'moment';
|
||||
import { sumBy } from 'lodash';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { Knex } from 'knex';
|
||||
import { AccountNormal, IBillPayment, ILedgerEntry } from '@/interfaces';
|
||||
import Ledger from '@/services/Accounting/Ledger';
|
||||
import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { TenantMetadata } from '@/system/models';
|
||||
|
||||
@Service()
|
||||
export class BillPaymentGLEntries {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private ledgerStorage: LedgerStorageService;
|
||||
|
||||
/**
|
||||
* Creates a bill payment GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPaymentId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public writePaymentGLEntries = async (
|
||||
tenantId: number,
|
||||
billPaymentId: number,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> => {
|
||||
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
const { BillPayment, Account } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieves the bill payment details with associated entries.
|
||||
const payment = await BillPayment.query(trx)
|
||||
.findById(billPaymentId)
|
||||
.withGraphFetched('entries.bill');
|
||||
|
||||
// Retrieves the given tenant metadata.
|
||||
const tenantMeta = await TenantMetadata.query().findOne({ tenantId });
|
||||
|
||||
// Finds or creates a new A/P account of the given currency.
|
||||
const APAccount = await accountRepository.findOrCreateAccountsPayable(
|
||||
payment.currencyCode,
|
||||
{},
|
||||
trx
|
||||
);
|
||||
// Exchange gain or loss account.
|
||||
const EXGainLossAccount = await Account.query(trx).modify(
|
||||
'findBySlug',
|
||||
'exchange-grain-loss'
|
||||
);
|
||||
// Retrieves the bill payment ledger.
|
||||
const ledger = this.getBillPaymentLedger(
|
||||
payment,
|
||||
APAccount.id,
|
||||
EXGainLossAccount.id,
|
||||
tenantMeta.baseCurrency
|
||||
);
|
||||
// Commits the ledger on the storage.
|
||||
await this.ledgerStorage.commit(tenantId, ledger, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Rewrites the bill payment GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPaymentId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public rewritePaymentGLEntries = async (
|
||||
tenantId: number,
|
||||
billPaymentId: number,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> => {
|
||||
// Revert payment GL entries.
|
||||
await this.revertPaymentGLEntries(tenantId, billPaymentId, trx);
|
||||
|
||||
// Write payment GL entries.
|
||||
await this.writePaymentGLEntries(tenantId, billPaymentId, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts the bill payment GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPaymentId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public revertPaymentGLEntries = async (
|
||||
tenantId: number,
|
||||
billPaymentId: number,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> => {
|
||||
await this.ledgerStorage.deleteByReference(
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
'BillPayment',
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the payment common entry.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @returns {}
|
||||
*/
|
||||
private getPaymentCommonEntry = (billPayment: IBillPayment) => {
|
||||
const formattedDate = moment(billPayment.paymentDate).format('YYYY-MM-DD');
|
||||
|
||||
return {
|
||||
debit: 0,
|
||||
credit: 0,
|
||||
|
||||
exchangeRate: billPayment.exchangeRate,
|
||||
currencyCode: billPayment.currencyCode,
|
||||
|
||||
transactionId: billPayment.id,
|
||||
transactionType: 'BillPayment',
|
||||
|
||||
transactionNumber: billPayment.paymentNumber,
|
||||
referenceNumber: billPayment.reference,
|
||||
|
||||
date: formattedDate,
|
||||
createdAt: billPayment.createdAt,
|
||||
|
||||
branchId: billPayment.branchId,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculates the payment total exchange gain/loss.
|
||||
* @param {IBillPayment} paymentReceive - Payment receive with entries.
|
||||
* @returns {number}
|
||||
*/
|
||||
private getPaymentExGainOrLoss = (billPayment: IBillPayment): number => {
|
||||
return sumBy(billPayment.entries, (entry) => {
|
||||
const paymentLocalAmount = entry.paymentAmount * billPayment.exchangeRate;
|
||||
const invoicePayment = entry.paymentAmount * entry.bill.exchangeRate;
|
||||
|
||||
return invoicePayment - paymentLocalAmount;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the payment exchange gain/loss entries.
|
||||
* @param {IBillPayment} billPayment -
|
||||
* @param {number} APAccountId -
|
||||
* @param {number} gainLossAccountId -
|
||||
* @param {string} baseCurrency -
|
||||
* @returns {ILedgerEntry[]}
|
||||
*/
|
||||
private getPaymentExGainOrLossEntries = (
|
||||
billPayment: IBillPayment,
|
||||
APAccountId: number,
|
||||
gainLossAccountId: number,
|
||||
baseCurrency: string
|
||||
): ILedgerEntry[] => {
|
||||
const commonEntry = this.getPaymentCommonEntry(billPayment);
|
||||
const totalExGainOrLoss = this.getPaymentExGainOrLoss(billPayment);
|
||||
const absExGainOrLoss = Math.abs(totalExGainOrLoss);
|
||||
|
||||
return totalExGainOrLoss
|
||||
? [
|
||||
{
|
||||
...commonEntry,
|
||||
currencyCode: baseCurrency,
|
||||
exchangeRate: 1,
|
||||
credit: totalExGainOrLoss > 0 ? absExGainOrLoss : 0,
|
||||
debit: totalExGainOrLoss < 0 ? absExGainOrLoss : 0,
|
||||
accountId: gainLossAccountId,
|
||||
index: 2,
|
||||
indexGroup: 20,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
},
|
||||
{
|
||||
...commonEntry,
|
||||
currencyCode: baseCurrency,
|
||||
exchangeRate: 1,
|
||||
debit: totalExGainOrLoss > 0 ? absExGainOrLoss : 0,
|
||||
credit: totalExGainOrLoss < 0 ? absExGainOrLoss : 0,
|
||||
accountId: APAccountId,
|
||||
index: 3,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the payment deposit GL entry.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
private getPaymentGLEntry = (billPayment: IBillPayment): ILedgerEntry => {
|
||||
const commonEntry = this.getPaymentCommonEntry(billPayment);
|
||||
|
||||
return {
|
||||
...commonEntry,
|
||||
credit: billPayment.localAmount,
|
||||
accountId: billPayment.paymentAccountId,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
index: 2,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the payment GL payable entry.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @param {number} APAccountId
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
private getPaymentGLPayableEntry = (
|
||||
billPayment: IBillPayment,
|
||||
APAccountId: number
|
||||
): ILedgerEntry => {
|
||||
const commonEntry = this.getPaymentCommonEntry(billPayment);
|
||||
|
||||
return {
|
||||
...commonEntry,
|
||||
exchangeRate: billPayment.exchangeRate,
|
||||
debit: billPayment.localAmount,
|
||||
contactId: billPayment.vendorId,
|
||||
accountId: APAccountId,
|
||||
accountNormal: AccountNormal.CREDIT,
|
||||
index: 1,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the payment GL entries.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @param {number} APAccountId
|
||||
* @returns {ILedgerEntry[]}
|
||||
*/
|
||||
private getPaymentGLEntries = (
|
||||
billPayment: IBillPayment,
|
||||
APAccountId: number,
|
||||
gainLossAccountId: number,
|
||||
baseCurrency: string
|
||||
): ILedgerEntry[] => {
|
||||
// Retrieves the payment deposit entry.
|
||||
const paymentEntry = this.getPaymentGLEntry(billPayment);
|
||||
|
||||
// Retrieves the payment debit A/R entry.
|
||||
const payableEntry = this.getPaymentGLPayableEntry(
|
||||
billPayment,
|
||||
APAccountId
|
||||
);
|
||||
// Retrieves the exchange gain/loss entries.
|
||||
const exGainLossEntries = this.getPaymentExGainOrLossEntries(
|
||||
billPayment,
|
||||
APAccountId,
|
||||
gainLossAccountId,
|
||||
baseCurrency
|
||||
);
|
||||
return [paymentEntry, payableEntry, ...exGainLossEntries];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the bill payment ledger.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @param {number} APAccountId
|
||||
* @returns {Ledger}
|
||||
*/
|
||||
private getBillPaymentLedger = (
|
||||
billPayment: IBillPayment,
|
||||
APAccountId: number,
|
||||
gainLossAccountId: number,
|
||||
baseCurrency: string
|
||||
): Ledger => {
|
||||
const entries = this.getPaymentGLEntries(
|
||||
billPayment,
|
||||
APAccountId,
|
||||
gainLossAccountId,
|
||||
baseCurrency
|
||||
);
|
||||
return new Ledger(entries);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IBillPaymentEventCreatedPayload,
|
||||
IBillPaymentEventDeletedPayload,
|
||||
IBillPaymentEventEditedPayload,
|
||||
} from '@/interfaces';
|
||||
import { BillPaymentGLEntries } from './BillPaymentGLEntries';
|
||||
|
||||
@Service()
|
||||
export class PaymentWriteGLEntriesSubscriber {
|
||||
@Inject()
|
||||
private billPaymentGLEntries: BillPaymentGLEntries;
|
||||
|
||||
/**
|
||||
* Attaches events with handles.
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(events.billPayment.onCreated, this.handleWriteJournalEntries);
|
||||
bus.subscribe(
|
||||
events.billPayment.onEdited,
|
||||
this.handleRewriteJournalEntriesOncePaymentEdited
|
||||
);
|
||||
bus.subscribe(
|
||||
events.billPayment.onDeleted,
|
||||
this.handleRevertJournalEntries
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle bill payment writing journal entries once created.
|
||||
*/
|
||||
private handleWriteJournalEntries = async ({
|
||||
tenantId,
|
||||
billPayment,
|
||||
trx,
|
||||
}: IBillPaymentEventCreatedPayload) => {
|
||||
// Records the journal transactions after bills payment
|
||||
// and change diff acoount balance.
|
||||
await this.billPaymentGLEntries.writePaymentGLEntries(
|
||||
tenantId,
|
||||
billPayment.id,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle bill payment re-writing journal entries once the payment transaction be edited.
|
||||
*/
|
||||
private handleRewriteJournalEntriesOncePaymentEdited = async ({
|
||||
tenantId,
|
||||
billPayment,
|
||||
trx,
|
||||
}: IBillPaymentEventEditedPayload) => {
|
||||
await this.billPaymentGLEntries.rewritePaymentGLEntries(
|
||||
tenantId,
|
||||
billPayment.id,
|
||||
trx
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts journal entries once bill payment deleted.
|
||||
*/
|
||||
private handleRevertJournalEntries = async ({
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
trx,
|
||||
}: IBillPaymentEventDeletedPayload) => {
|
||||
await this.billPaymentGLEntries.revertPaymentGLEntries(
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
trx
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
import { formatNumber } from 'utils';
|
||||
|
||||
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 formatNumber(entry.paymentAmount, {
|
||||
currencyCode: entry.payment.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted bill payment date.
|
||||
* @param entry
|
||||
* @returns
|
||||
*/
|
||||
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,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { IBillPayment } from '@/interfaces';
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
import { formatNumber } from 'utils';
|
||||
|
||||
export class BillPaymentTransformer extends Transformer {
|
||||
/**
|
||||
* Include these attributes to sale invoice object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['formattedPaymentDate', 'formattedAmount'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted invoice date.
|
||||
* @param {IBill} invoice
|
||||
* @returns {String}
|
||||
*/
|
||||
protected formattedPaymentDate = (billPayment: IBillPayment): string => {
|
||||
return this.formatDate(billPayment.paymentDate);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve formatted bill amount.
|
||||
* @param {IBill} invoice
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedAmount = (billPayment: IBillPayment): string => {
|
||||
return formatNumber(billPayment.amount, {
|
||||
currencyCode: billPayment.currencyCode,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { sumBy, difference } from 'lodash';
|
||||
import * as R from 'ramda';
|
||||
import { Knex } from 'knex';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IBill,
|
||||
IBillPaymentDTO,
|
||||
IBillPaymentEntryDTO,
|
||||
IBillPayment,
|
||||
IBillPaymentsFilter,
|
||||
IPaginationMeta,
|
||||
IFilterMeta,
|
||||
IBillPaymentEntry,
|
||||
IBillPaymentEventCreatedPayload,
|
||||
IBillPaymentEventEditedPayload,
|
||||
IBillPaymentEventDeletedPayload,
|
||||
IBillPaymentCreatingPayload,
|
||||
IBillPaymentEditingPayload,
|
||||
IBillPaymentDeletingPayload,
|
||||
IVendor,
|
||||
} from '@/interfaces';
|
||||
import JournalPosterService from '@/services/Sales/JournalPosterService';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import { entriesAmountDiff, formatDateFields } from 'utils';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { ACCOUNT_TYPE } from '@/data/AccountTypes';
|
||||
import { BillPaymentTransformer } from './BillPaymentTransformer';
|
||||
import { ERRORS } from './constants';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { BranchTransactionDTOTransform } from '@/services/Branches/Integrations/BranchTransactionDTOTransform';
|
||||
import { TenantMetadata } from '@/system/models';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
|
||||
/**
|
||||
* Bill payments service.
|
||||
* @service
|
||||
*/
|
||||
@Service('BillPayments')
|
||||
export default class BillPaymentsService implements IBillPaymentsService {
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
journalService: JournalPosterService;
|
||||
|
||||
@Inject()
|
||||
dynamicListService: DynamicListingService;
|
||||
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
@Inject()
|
||||
uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private branchDTOTransform: BranchTransactionDTOTransform;
|
||||
|
||||
/**
|
||||
* Validates the bill payment existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
private async getPaymentMadeOrThrowError(
|
||||
tenantid: number,
|
||||
paymentMadeId: number
|
||||
) {
|
||||
const { BillPayment } = this.tenancy.models(tenantid);
|
||||
const billPayment = await BillPayment.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>}
|
||||
*/
|
||||
private async getPaymentAccountOrThrowError(
|
||||
tenantId: number,
|
||||
paymentAccountId: number
|
||||
) {
|
||||
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
|
||||
const paymentAccount = await accountRepository.findOneById(
|
||||
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>}
|
||||
*/
|
||||
private async validatePaymentNumber(
|
||||
tenantId: number,
|
||||
paymentMadeNumber: string,
|
||||
notPaymentMadeId?: number
|
||||
) {
|
||||
const { BillPayment } = this.tenancy.models(tenantId);
|
||||
|
||||
const foundBillPayment = await BillPayment.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.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
public async validateBillsExistance(
|
||||
tenantId: number,
|
||||
billPaymentEntries: { billId: number }[],
|
||||
vendorId: number
|
||||
) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
const entriesBillsIds = billPaymentEntries.map((e: any) => e.billId);
|
||||
|
||||
const storedBills = await Bill.query()
|
||||
.whereIn('id', entriesBillsIds)
|
||||
.where('vendor_id', vendorId);
|
||||
|
||||
const storedBillsIds = storedBills.map((t: IBill) => 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}
|
||||
*/
|
||||
private async validateBillsDueAmount(
|
||||
tenantId: number,
|
||||
billPaymentEntries: IBillPaymentEntryDTO[],
|
||||
oldPaymentEntries: IBillPaymentEntry[] = []
|
||||
) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
const billsIds = billPaymentEntries.map(
|
||||
(entry: IBillPaymentEntryDTO) => entry.billId
|
||||
);
|
||||
|
||||
const storedBills = await Bill.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: IBillPaymentEntryDTO, 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}
|
||||
*/
|
||||
private async validateEntriesIdsExistance(
|
||||
tenantId: number,
|
||||
billPaymentId: number,
|
||||
billPaymentEntries: IBillPaymentEntry[]
|
||||
) {
|
||||
const { BillPaymentEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
const entriesIds = billPaymentEntries
|
||||
.filter((entry: any) => entry.id)
|
||||
.map((entry: any) => entry.id);
|
||||
|
||||
const storedEntries = await BillPaymentEntry.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
|
||||
*/
|
||||
private validateVendorNotModified(
|
||||
billPaymentDTO: IBillPaymentDTO,
|
||||
oldBillPayment: IBillPayment
|
||||
) {
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Transforms create/edit DTO to model.
|
||||
* @param {number} tenantId
|
||||
* @param {IBillPaymentDTO} billPaymentDTO - Bill payment.
|
||||
* @param {IBillPayment} oldBillPayment - Old bill payment.
|
||||
* @return {Promise<IBillPayment>}
|
||||
*/
|
||||
async transformDTOToModel(
|
||||
tenantId: number,
|
||||
billPaymentDTO: IBillPaymentDTO,
|
||||
vendor: IVendor,
|
||||
oldBillPayment?: IBillPayment
|
||||
): Promise<IBillPayment> {
|
||||
const initialDTO = {
|
||||
...formatDateFields(billPaymentDTO, ['paymentDate']),
|
||||
amount: sumBy(billPaymentDTO.entries, 'paymentAmount'),
|
||||
currencyCode: vendor.currencyCode,
|
||||
exchangeRate: billPaymentDTO.exchangeRate || 1,
|
||||
entries: billPaymentDTO.entries,
|
||||
};
|
||||
return R.compose(
|
||||
this.branchDTOTransform.transformDTO<IBillPayment>(tenantId)
|
||||
)(initialDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(
|
||||
tenantId: number,
|
||||
billPaymentDTO: IBillPaymentDTO
|
||||
): Promise<IBillPayment> {
|
||||
const { BillPayment, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
const tenantMeta = await TenantMetadata.query().findOne({ tenantId });
|
||||
|
||||
// Retrieves the payment vendor or throw not found error.
|
||||
const vendor = await Contact.query()
|
||||
.findById(billPaymentDTO.vendorId)
|
||||
.modify('vendor')
|
||||
.throwIfNotFound();
|
||||
|
||||
// Transform create DTO to model object.
|
||||
const billPaymentObj = await this.transformDTOToModel(
|
||||
tenantId,
|
||||
billPaymentDTO,
|
||||
vendor
|
||||
);
|
||||
// Validate the payment account existance and type.
|
||||
const paymentAccount = await this.getPaymentAccountOrThrowError(
|
||||
tenantId,
|
||||
billPaymentObj.paymentAccountId
|
||||
);
|
||||
// Validate the payment number uniquiness.
|
||||
if (billPaymentObj.paymentNumber) {
|
||||
await this.validatePaymentNumber(tenantId, billPaymentObj.paymentNumber);
|
||||
}
|
||||
// Validates the bills existance and associated to the given vendor.
|
||||
await this.validateBillsExistance(
|
||||
tenantId,
|
||||
billPaymentObj.entries,
|
||||
billPaymentDTO.vendorId
|
||||
);
|
||||
// Validates the bills due payment amount.
|
||||
await this.validateBillsDueAmount(tenantId, billPaymentObj.entries);
|
||||
|
||||
// Validates the withdrawal account currency code.
|
||||
this.validateWithdrawalAccountCurrency(
|
||||
paymentAccount.currencyCode,
|
||||
vendor.currencyCode,
|
||||
tenantMeta.baseCurrency
|
||||
);
|
||||
// Writes bill payment transacation with associated transactions
|
||||
// under unit-of-work envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillPaymentCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onCreating, {
|
||||
tenantId,
|
||||
billPaymentDTO,
|
||||
trx,
|
||||
} as IBillPaymentCreatingPayload);
|
||||
|
||||
// Writes the bill payment graph to the storage.
|
||||
const billPayment = await BillPayment.query(trx).insertGraphAndFetch({
|
||||
...billPaymentObj,
|
||||
});
|
||||
|
||||
// Triggers `onBillPaymentCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onCreated, {
|
||||
tenantId,
|
||||
billPayment,
|
||||
billPaymentId: billPayment.id,
|
||||
trx,
|
||||
} as IBillPaymentEventCreatedPayload);
|
||||
|
||||
return billPayment;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {number} tenantId - Tenant id
|
||||
* @param {Integer} billPaymentId
|
||||
* @param {BillPaymentDTO} billPayment
|
||||
* @param {IBillPayment} oldBillPayment
|
||||
*/
|
||||
public async editBillPayment(
|
||||
tenantId: number,
|
||||
billPaymentId: number,
|
||||
billPaymentDTO
|
||||
): Promise<IBillPayment> {
|
||||
const { BillPayment, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
const tenantMeta = await TenantMetadata.query().findOne({ tenantId });
|
||||
|
||||
//
|
||||
const oldBillPayment = await this.getPaymentMadeOrThrowError(
|
||||
tenantId,
|
||||
billPaymentId
|
||||
);
|
||||
|
||||
//
|
||||
const vendor = await Contact.query()
|
||||
.modify('vendor')
|
||||
.findById(billPaymentDTO.vendorId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Transform bill payment DTO to model object.
|
||||
const billPaymentObj = await this.transformDTOToModel(
|
||||
tenantId,
|
||||
billPaymentDTO,
|
||||
vendor,
|
||||
oldBillPayment
|
||||
);
|
||||
// Validate vendor not modified.
|
||||
this.validateVendorNotModified(billPaymentDTO, oldBillPayment);
|
||||
|
||||
// Validate the payment account existance and type.
|
||||
const paymentAccount = await this.getPaymentAccountOrThrowError(
|
||||
tenantId,
|
||||
billPaymentObj.paymentAccountId
|
||||
);
|
||||
// Validate the items entries IDs existance on the storage.
|
||||
await this.validateEntriesIdsExistance(
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
billPaymentObj.entries
|
||||
);
|
||||
// Validate the bills existance and associated to the given vendor.
|
||||
await this.validateBillsExistance(
|
||||
tenantId,
|
||||
billPaymentObj.entries,
|
||||
billPaymentDTO.vendorId
|
||||
);
|
||||
// Validates the bills due payment amount.
|
||||
await this.validateBillsDueAmount(
|
||||
tenantId,
|
||||
billPaymentObj.entries,
|
||||
oldBillPayment.entries
|
||||
);
|
||||
// Validate the payment number uniquiness.
|
||||
if (billPaymentObj.paymentNumber) {
|
||||
await this.validatePaymentNumber(
|
||||
tenantId,
|
||||
billPaymentObj.paymentNumber,
|
||||
billPaymentId
|
||||
);
|
||||
}
|
||||
// Validates the withdrawal account currency code.
|
||||
this.validateWithdrawalAccountCurrency(
|
||||
paymentAccount.currencyCode,
|
||||
vendor.currencyCode,
|
||||
tenantMeta.baseCurrency
|
||||
);
|
||||
// Edits the bill transactions with associated transactions
|
||||
// under unit-of-work envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillPaymentEditing` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onEditing, {
|
||||
tenantId,
|
||||
oldBillPayment,
|
||||
billPaymentDTO,
|
||||
trx,
|
||||
} as IBillPaymentEditingPayload);
|
||||
|
||||
// Deletes the bill payment transaction graph from the storage.
|
||||
const billPayment = await BillPayment.query(trx).upsertGraphAndFetch({
|
||||
id: billPaymentId,
|
||||
...billPaymentObj,
|
||||
});
|
||||
// Triggers `onBillPaymentEdited` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onEdited, {
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
billPayment,
|
||||
oldBillPayment,
|
||||
trx,
|
||||
} as IBillPaymentEventEditedPayload);
|
||||
|
||||
return billPayment;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the bill payment and associated transactions.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {Integer} billPaymentId - The given bill payment id.
|
||||
* @return {Promise}
|
||||
*/
|
||||
public async deleteBillPayment(tenantId: number, billPaymentId: number) {
|
||||
const { BillPayment, BillPaymentEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the bill payment or throw not found service error.
|
||||
const oldBillPayment = await this.getPaymentMadeOrThrowError(
|
||||
tenantId,
|
||||
billPaymentId
|
||||
);
|
||||
// Deletes the bill transactions with associated transactions under
|
||||
// unit-of-work envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillPaymentDeleting` payload.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onDeleting, {
|
||||
tenantId,
|
||||
trx,
|
||||
oldBillPayment,
|
||||
} as IBillPaymentDeletingPayload);
|
||||
|
||||
// Deletes the bill payment assocaited entries.
|
||||
await BillPaymentEntry.query(trx)
|
||||
.where('bill_payment_id', billPaymentId)
|
||||
.delete();
|
||||
|
||||
// Deletes the bill payment transaction.
|
||||
await BillPayment.query(trx).where('id', billPaymentId).delete();
|
||||
|
||||
// Triggers `onBillPaymentDeleted` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onDeleted, {
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
oldBillPayment,
|
||||
trx,
|
||||
} as IBillPaymentEventDeletedPayload);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment made associated bills.
|
||||
* @param {number} tenantId -
|
||||
* @param {number} billPaymentId -
|
||||
*/
|
||||
public async getPaymentBills(tenantId: number, billPaymentId: number) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const billPayment = await this.getPaymentMadeOrThrowError(
|
||||
tenantId,
|
||||
billPaymentId
|
||||
);
|
||||
const paymentBillsIds = billPayment.entries.map((entry) => entry.id);
|
||||
|
||||
const bills = await Bill.query().whereIn('id', paymentBillsIds);
|
||||
|
||||
return bills;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve bill payment.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPyamentId
|
||||
* @return {Promise<IBillPayment>}
|
||||
*/
|
||||
public async getBillPayment(
|
||||
tenantId: number,
|
||||
billPyamentId: number
|
||||
): Promise<IBillPayment> {
|
||||
const { BillPayment } = this.tenancy.models(tenantId);
|
||||
|
||||
const billPayment = await BillPayment.query()
|
||||
.withGraphFetched('entries.bill')
|
||||
.withGraphFetched('vendor')
|
||||
.withGraphFetched('paymentAccount')
|
||||
.withGraphFetched('transactions')
|
||||
.withGraphFetched('branch')
|
||||
.findById(billPyamentId);
|
||||
|
||||
if (!billPayment) {
|
||||
throw new ServiceError(ERRORS.PAYMENT_MADE_NOT_FOUND);
|
||||
}
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
billPayment,
|
||||
new BillPaymentTransformer()
|
||||
);
|
||||
}
|
||||
|
||||
private parseListFilterDTO(filterDTO) {
|
||||
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve bill payment paginted and filterable list.
|
||||
* @param {number} tenantId
|
||||
* @param {IBillPaymentsFilter} billPaymentsFilter
|
||||
*/
|
||||
public async listBillPayments(
|
||||
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);
|
||||
})
|
||||
.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(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves bills payment amount changes different.
|
||||
* @param {number} tenantId -
|
||||
* @param {IBillPaymentEntryDTO[]} paymentMadeEntries -
|
||||
* @param {IBillPaymentEntryDTO[]} oldPaymentMadeEntries -
|
||||
*/
|
||||
public async saveChangeBillsPaymentAmount(
|
||||
tenantId: number,
|
||||
paymentMadeEntries: IBillPaymentEntryDTO[],
|
||||
oldPaymentMadeEntries?: IBillPaymentEntryDTO[],
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
const opers: Promise<void>[] = [];
|
||||
|
||||
const diffEntries = entriesAmountDiff(
|
||||
paymentMadeEntries,
|
||||
oldPaymentMadeEntries,
|
||||
'paymentAmount',
|
||||
'billId'
|
||||
);
|
||||
diffEntries.forEach(
|
||||
(diffEntry: { paymentAmount: number; billId: number }) => {
|
||||
if (diffEntry.paymentAmount === 0) {
|
||||
return;
|
||||
}
|
||||
const oper = Bill.changePaymentAmount(
|
||||
diffEntry.billId,
|
||||
diffEntry.paymentAmount,
|
||||
trx
|
||||
);
|
||||
opers.push(oper);
|
||||
}
|
||||
);
|
||||
await Promise.all(opers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the given vendor has no associated payments.
|
||||
* @param {number} tenantId
|
||||
* @param {number} vendorId
|
||||
*/
|
||||
public async validateVendorHasNoPayments(tenantId: number, vendorId: number) {
|
||||
const { BillPayment } = this.tenancy.models(tenantId);
|
||||
|
||||
const payments = await BillPayment.query().where('vendor_id', vendorId);
|
||||
|
||||
if (payments.length > 0) {
|
||||
throw new ServiceError(ERRORS.VENDOR_HAS_PAYMENTS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { omit } from 'lodash';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { IBill, IBillPayment, IBillReceivePageEntry } from '@/interfaces';
|
||||
import { ERRORS } from './constants';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
|
||||
/**
|
||||
* Bill payments edit and create pages services.
|
||||
*/
|
||||
@Service()
|
||||
export default class BillPaymentsPages {
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
/**
|
||||
* Retrieve bill payment with associated metadata.
|
||||
* @param {number} billPaymentId - The bill payment id.
|
||||
* @return {object}
|
||||
*/
|
||||
public async getBillPaymentEditPage(
|
||||
tenantId: number,
|
||||
billPaymentId: number
|
||||
): Promise<{
|
||||
billPayment: Omit<IBillPayment, 'entries'>;
|
||||
entries: IBillReceivePageEntry[];
|
||||
}> {
|
||||
const { BillPayment, Bill } = this.tenancy.models(tenantId);
|
||||
const billPayment = await BillPayment.query()
|
||||
.findById(billPaymentId)
|
||||
.withGraphFetched('entries.bill');
|
||||
|
||||
// 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(
|
||||
tenantId: number,
|
||||
vendorId: number
|
||||
): Promise<IBillReceivePageEntry[]> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve all payable bills that assocaited to the payment made transaction.
|
||||
const payableBills = await Bill.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 {ISaleInvoice[]} invoices - Invoices.
|
||||
* @return {IPaymentReceiveEditPageEntry}
|
||||
*/
|
||||
private mapBillToPageEntry(bill: IBill): 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,17 @@
|
||||
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 = [];
|
||||
Reference in New Issue
Block a user