mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 04:40:32 +00:00
refactor: split the services to multiple service classes (#202)
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { Knex } from 'knex';
|
||||
import { IBillPaymentEntryDTO } from '@/interfaces';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { entriesAmountDiff } from '@/utils';
|
||||
|
||||
@Service()
|
||||
export class BillPaymentBillSync {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export class BillPaymentGLEntries {
|
||||
|
||||
/**
|
||||
* Retrieves the payment common entry.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @param {IBillPayment} billPayment
|
||||
* @returns {}
|
||||
*/
|
||||
private getPaymentCommonEntry = (billPayment: IBillPayment) => {
|
||||
|
||||
@@ -24,7 +24,7 @@ export class BillPaymentTransactionTransformer extends Transformer {
|
||||
/**
|
||||
* Retrieve formatted bill payment date.
|
||||
* @param entry
|
||||
* @returns
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedPaymentDate = (entry): string => {
|
||||
return this.formatDate(entry.payment.paymentDate);
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { sumBy, difference } from 'lodash';
|
||||
import {
|
||||
IBill,
|
||||
IBillPaymentDTO,
|
||||
IBillPaymentEntryDTO,
|
||||
IBillPayment,
|
||||
IBillPaymentEntry,
|
||||
} from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { ACCOUNT_TYPE } from '@/data/AccountTypes';
|
||||
import { BillPayment } from '@/models';
|
||||
import { ERRORS } from './constants';
|
||||
|
||||
@Service()
|
||||
export class BillPaymentValidators {
|
||||
@Inject()
|
||||
private tenancy: TenancyService;
|
||||
|
||||
/**
|
||||
* Validates the payment existance.
|
||||
* @param {BillPayment | undefined | null} payment
|
||||
* @throws {ServiceError(ERRORS.PAYMENT_MADE_NOT_FOUND)}
|
||||
*/
|
||||
public async validateBillPaymentExistance(
|
||||
payment: BillPayment | undefined | null
|
||||
) {
|
||||
if (!payment) {
|
||||
throw new ServiceError(ERRORS.PAYMENT_MADE_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill payment existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
public 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>}
|
||||
*/
|
||||
public 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>}
|
||||
*/
|
||||
public 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}
|
||||
*/
|
||||
public 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}
|
||||
*/
|
||||
public 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
|
||||
*/
|
||||
public 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);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,713 +0,0 @@
|
||||
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,109 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IBillPaymentDTO, IBillPayment } from '@/interfaces';
|
||||
import { CreateBillPayment } from './CreateBillPayment';
|
||||
import { DeleteBillPayment } from './DeleteBillPayment';
|
||||
import { EditBillPayment } from './EditBillPayment';
|
||||
import { GetBillPayments } from './GetBillPayments';
|
||||
import { GetBillPayment } from './GetBillPayment';
|
||||
import { GetPaymentBills } from './GetPaymentBills';
|
||||
|
||||
/**
|
||||
* Bill payments application.
|
||||
* @service
|
||||
*/
|
||||
@Service()
|
||||
export class BillPaymentsApplication {
|
||||
@Inject()
|
||||
private createBillPaymentService: CreateBillPayment;
|
||||
|
||||
@Inject()
|
||||
private deleteBillPaymentService: DeleteBillPayment;
|
||||
|
||||
@Inject()
|
||||
private editBillPaymentService: EditBillPayment;
|
||||
|
||||
@Inject()
|
||||
private getBillPaymentsService: GetBillPayments;
|
||||
|
||||
@Inject()
|
||||
private getBillPaymentService: GetBillPayment;
|
||||
|
||||
@Inject()
|
||||
private getPaymentBillsService: GetPaymentBills;
|
||||
|
||||
/**
|
||||
* Creates a bill payment with associated GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {IBillPaymentDTO} billPaymentDTO
|
||||
* @returns {Promise<IBillPayment>}
|
||||
*/
|
||||
public createBillPayment(
|
||||
tenantId: number,
|
||||
billPaymentDTO: IBillPaymentDTO
|
||||
): Promise<IBillPayment> {
|
||||
return this.createBillPaymentService.createBillPayment(
|
||||
tenantId,
|
||||
billPaymentDTO
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delets the given bill payment with associated GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPaymentId
|
||||
*/
|
||||
public deleteBillPayment(tenantId: number, billPaymentId: number) {
|
||||
return this.deleteBillPaymentService.deleteBillPayment(
|
||||
tenantId,
|
||||
billPaymentId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits the given bill payment with associated GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPaymentId
|
||||
* @param billPaymentDTO
|
||||
* @returns {Promise<IBillPayment>}
|
||||
*/
|
||||
public editBillPayment(
|
||||
tenantId: number,
|
||||
billPaymentId: number,
|
||||
billPaymentDTO
|
||||
): Promise<IBillPayment> {
|
||||
return this.editBillPaymentService.editBillPayment(
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
billPaymentDTO
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves bill payments list.
|
||||
* @param {number} tenantId
|
||||
* @param filterDTO
|
||||
* @returns
|
||||
*/
|
||||
public getBillPayments(tenantId: number, filterDTO: IBillPaymentsFilter) {
|
||||
return this.getBillPaymentsService.getBillPayments(tenantId, filterDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve specific bill payment.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billPyamentId
|
||||
* @returns
|
||||
*/
|
||||
public getBillPayment(tenantId: number, billPyamentId: number) {
|
||||
return this.getBillPaymentService.getBillPayment(tenantId, billPyamentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment made associated bills.
|
||||
* @param {number} tenantId -
|
||||
* @param {number} billPaymentId -
|
||||
*/
|
||||
public getPaymentBills(tenantId: number, billPaymentId: number) {
|
||||
return this.getPaymentBillsService.getPaymentBills(tenantId, billPaymentId);
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,10 @@ 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;
|
||||
private tenancy: TenancyService;
|
||||
|
||||
/**
|
||||
* Retrieve bill payment with associated metadata.
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import * as R from 'ramda';
|
||||
import { sumBy } from 'lodash';
|
||||
import { IBillPayment, IBillPaymentDTO, IVendor } from '@/interfaces';
|
||||
import { BranchTransactionDTOTransform } from '@/services/Branches/Integrations/BranchTransactionDTOTransform';
|
||||
import { formatDateFields } from '@/utils';
|
||||
|
||||
@Service()
|
||||
export class CommandBillPaymentDTOTransformer {
|
||||
@Inject()
|
||||
private branchDTOTransform: BranchTransactionDTOTransform;
|
||||
|
||||
/**
|
||||
* 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(
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { Knex } from 'knex';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IBillPaymentDTO,
|
||||
IBillPayment,
|
||||
IBillPaymentEventCreatedPayload,
|
||||
IBillPaymentCreatingPayload,
|
||||
} from '@/interfaces';
|
||||
import { TenantMetadata } from '@/system/models';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { BillPaymentValidators } from './BillPaymentValidators';
|
||||
import { CommandBillPaymentDTOTransformer } from './CommandBillPaymentDTOTransformer';
|
||||
|
||||
@Service()
|
||||
export class CreateBillPayment {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private validators: BillPaymentValidators;
|
||||
|
||||
@Inject()
|
||||
private commandTransformerDTO: CommandBillPaymentDTOTransformer;
|
||||
|
||||
/**
|
||||
* 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.commandTransformerDTO.transformDTOToModel(
|
||||
tenantId,
|
||||
billPaymentDTO,
|
||||
vendor
|
||||
);
|
||||
// Validate the payment account existance and type.
|
||||
const paymentAccount = await this.validators.getPaymentAccountOrThrowError(
|
||||
tenantId,
|
||||
billPaymentObj.paymentAccountId
|
||||
);
|
||||
// Validate the payment number uniquiness.
|
||||
if (billPaymentObj.paymentNumber) {
|
||||
await this.validators.validatePaymentNumber(
|
||||
tenantId,
|
||||
billPaymentObj.paymentNumber
|
||||
);
|
||||
}
|
||||
// Validates the bills existance and associated to the given vendor.
|
||||
await this.validators.validateBillsExistance(
|
||||
tenantId,
|
||||
billPaymentObj.entries,
|
||||
billPaymentDTO.vendorId
|
||||
);
|
||||
// Validates the bills due payment amount.
|
||||
await this.validators.validateBillsDueAmount(
|
||||
tenantId,
|
||||
billPaymentObj.entries
|
||||
);
|
||||
// Validates the withdrawal account currency code.
|
||||
this.validators.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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Knex } from 'knex';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { BillPaymentValidators } from './BillPaymentValidators';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import {
|
||||
IBillPaymentDeletingPayload,
|
||||
IBillPaymentEventDeletedPayload,
|
||||
} from '@/interfaces';
|
||||
import events from '@/subscribers/events';
|
||||
|
||||
@Service()
|
||||
export class DeleteBillPayment {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private validators: BillPaymentValidators;
|
||||
|
||||
/**
|
||||
* 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 BillPayment.query()
|
||||
.withGraphFetched('entries')
|
||||
.findById(billPaymentId);
|
||||
|
||||
// Validates the bill payment existance.
|
||||
this.validators.validateBillPaymentExistance(oldBillPayment);
|
||||
|
||||
// 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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { BillPaymentValidators } from './BillPaymentValidators';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import {
|
||||
IBillPayment,
|
||||
IBillPaymentEditingPayload,
|
||||
IBillPaymentEventEditedPayload,
|
||||
} from '@/interfaces';
|
||||
import events from '@/subscribers/events';
|
||||
import { Knex } from 'knex';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { CommandBillPaymentDTOTransformer } from './CommandBillPaymentDTOTransformer';
|
||||
import { TenantMetadata } from '@/system/models';
|
||||
|
||||
@Service()
|
||||
export class EditBillPayment {
|
||||
@Inject()
|
||||
private validators: BillPaymentValidators;
|
||||
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private transformer: CommandBillPaymentDTOTransformer;
|
||||
|
||||
/**
|
||||
* 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 BillPayment.query().findById(billPaymentId);
|
||||
|
||||
// Validates the bill payment existance.
|
||||
this.validators.validateBillPaymentExistance(oldBillPayment);
|
||||
|
||||
//
|
||||
const vendor = await Contact.query()
|
||||
.modify('vendor')
|
||||
.findById(billPaymentDTO.vendorId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Transform bill payment DTO to model object.
|
||||
const billPaymentObj = await this.transformer.transformDTOToModel(
|
||||
tenantId,
|
||||
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(
|
||||
tenantId,
|
||||
billPaymentObj.paymentAccountId
|
||||
);
|
||||
// Validate the items entries IDs existance on the storage.
|
||||
await this.validators.validateEntriesIdsExistance(
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
billPaymentObj.entries
|
||||
);
|
||||
// Validate the bills existance and associated to the given vendor.
|
||||
await this.validators.validateBillsExistance(
|
||||
tenantId,
|
||||
billPaymentObj.entries,
|
||||
billPaymentDTO.vendorId
|
||||
);
|
||||
// Validates the bills due payment amount.
|
||||
await this.validators.validateBillsDueAmount(
|
||||
tenantId,
|
||||
billPaymentObj.entries,
|
||||
oldBillPayment.entries
|
||||
);
|
||||
// Validate the payment number uniquiness.
|
||||
if (billPaymentObj.paymentNumber) {
|
||||
await this.validators.validatePaymentNumber(
|
||||
tenantId,
|
||||
billPaymentObj.paymentNumber,
|
||||
billPaymentId
|
||||
);
|
||||
}
|
||||
// Validates the withdrawal account currency code.
|
||||
this.validators.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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { IBillPayment } from '@/interfaces';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ERRORS } from './constants';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { BillPaymentTransformer } from './BillPaymentTransformer';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
import { BillsValidators } from '../Bills/BillsValidators';
|
||||
import { BillPaymentValidators } from './BillPaymentValidators';
|
||||
|
||||
@Service()
|
||||
export class GetBillPayment {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
@Inject()
|
||||
private validators: BillPaymentValidators;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
// Validates the bill payment existance.
|
||||
this.validators.validateBillPaymentExistance(billPayment);
|
||||
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
billPayment,
|
||||
new BillPaymentTransformer()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
IBillPayment,
|
||||
IBillPaymentsFilter,
|
||||
IPaginationMeta,
|
||||
IFilterMeta,
|
||||
} from '@/interfaces';
|
||||
import { BillPaymentTransformer } from './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);
|
||||
})
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { BillPaymentValidators } from './BillPaymentValidators';
|
||||
|
||||
@Service()
|
||||
export class GetPaymentBills {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private validators: BillPaymentValidators;
|
||||
|
||||
/**
|
||||
* Retrieve payment made associated bills.
|
||||
* @param {number} tenantId -
|
||||
* @param {number} billPaymentId -
|
||||
*/
|
||||
public async getPaymentBills(tenantId: number, billPaymentId: number) {
|
||||
const { Bill, BillPayment } = this.tenancy.models(tenantId);
|
||||
|
||||
const billPayment = await BillPayment.query().findById(billPaymentId);
|
||||
|
||||
// Validates the bill payment existance.
|
||||
this.validators.validateBillPaymentExistance(billPayment);
|
||||
|
||||
const paymentBillsIds = billPayment.entries.map((entry) => entry.id);
|
||||
|
||||
const bills = await Bill.query().whereIn('id', paymentBillsIds);
|
||||
|
||||
return bills;
|
||||
}
|
||||
}
|
||||
@@ -1,751 +0,0 @@
|
||||
import { omit, sumBy } from 'lodash';
|
||||
import moment from 'moment';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import * as R from 'ramda';
|
||||
import { Knex } from 'knex';
|
||||
import composeAsync from 'async/compose';
|
||||
import events from '@/subscribers/events';
|
||||
import InventoryService from '@/services/Inventory/Inventory';
|
||||
import SalesInvoicesCost from '@/services/Sales/SalesInvoicesCost';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import { formatDateFields, transformToMap } from 'utils';
|
||||
import {
|
||||
IBillDTO,
|
||||
IBill,
|
||||
ISystemUser,
|
||||
IBillEditDTO,
|
||||
IPaginationMeta,
|
||||
IFilterMeta,
|
||||
IBillsFilter,
|
||||
IBillsService,
|
||||
IItemEntry,
|
||||
IItemEntryDTO,
|
||||
IBillCreatedPayload,
|
||||
IBillEditedPayload,
|
||||
IBIllEventDeletedPayload,
|
||||
IBillEventDeletingPayload,
|
||||
IBillEditingPayload,
|
||||
IBillCreatingPayload,
|
||||
IVendor,
|
||||
} from '@/interfaces';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
import JournalPosterService from '@/services/Sales/JournalPosterService';
|
||||
import { ERRORS } from './constants';
|
||||
import EntriesService from '@/services/Entries';
|
||||
import { PurchaseInvoiceTransformer } from './PurchaseInvoices/PurchaseInvoiceTransformer';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { BranchTransactionDTOTransform } from '@/services/Branches/Integrations/BranchTransactionDTOTransform';
|
||||
import { WarehouseTransactionDTOTransform } from '@/services/Warehouses/Integrations/WarehouseTransactionDTOTransform';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
|
||||
/**
|
||||
* Vendor bills services.
|
||||
* @service
|
||||
*/
|
||||
@Service('Bills')
|
||||
export default class BillsService
|
||||
extends SalesInvoicesCost
|
||||
implements IBillsService
|
||||
{
|
||||
@Inject()
|
||||
inventoryService: InventoryService;
|
||||
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
|
||||
@Inject()
|
||||
dynamicListService: DynamicListingService;
|
||||
|
||||
@Inject()
|
||||
itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
@Inject()
|
||||
journalPosterService: JournalPosterService;
|
||||
|
||||
@Inject()
|
||||
entriesService: EntriesService;
|
||||
|
||||
@Inject()
|
||||
transformer: TransformerInjectable;
|
||||
|
||||
@Inject()
|
||||
uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private branchDTOTransform: BranchTransactionDTOTransform;
|
||||
|
||||
@Inject()
|
||||
private warehouseDTOTransform: WarehouseTransactionDTOTransform;
|
||||
|
||||
/**
|
||||
* Validates the given bill existance.
|
||||
* @async
|
||||
* @param {number} tenantId -
|
||||
* @param {number} billId -
|
||||
*/
|
||||
public async getBillOrThrowError(tenantId: number, billId: number) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const foundBill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
if (!foundBill) {
|
||||
throw new ServiceError(ERRORS.BILL_NOT_FOUND);
|
||||
}
|
||||
return foundBill;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill number existance.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
private async validateBillNumberExists(
|
||||
tenantId: number,
|
||||
billNumber: string,
|
||||
notBillId?: number
|
||||
) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
const foundBills = await Bill.query()
|
||||
.where('bill_number', billNumber)
|
||||
.onBuild((builder) => {
|
||||
if (notBillId) {
|
||||
builder.whereNot('id', notBillId);
|
||||
}
|
||||
});
|
||||
|
||||
if (foundBills.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_NUMBER_EXISTS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the bill has no payment entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId - Bill id.
|
||||
*/
|
||||
private async validateBillHasNoEntries(tenantId, billId: number) {
|
||||
const { BillPaymentEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retireve the bill associate payment made entries.
|
||||
const entries = await BillPaymentEntry.query().where('bill_id', billId);
|
||||
|
||||
if (entries.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_HAS_ASSOCIATED_PAYMENT_ENTRIES);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the bill number require.
|
||||
* @param {string} billNo -
|
||||
*/
|
||||
private validateBillNoRequire(billNo: string) {
|
||||
if (!billNo) {
|
||||
throw new ServiceError(ERRORS.BILL_NO_IS_REQUIRED);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate bill transaction has no associated allocated landed cost transactions.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
*/
|
||||
private async validateBillHasNoLandedCost(tenantId: number, billId: number) {
|
||||
const { BillLandedCost } = this.tenancy.models(tenantId);
|
||||
|
||||
const billLandedCosts = await BillLandedCost.query().where(
|
||||
'billId',
|
||||
billId
|
||||
);
|
||||
if (billLandedCosts.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_HAS_ASSOCIATED_LANDED_COSTS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate transaction entries that have landed cost type should not be
|
||||
* inventory items.
|
||||
* @param {number} tenantId -
|
||||
* @param {IItemEntryDTO[]} newEntriesDTO -
|
||||
*/
|
||||
public async validateCostEntriesShouldBeInventoryItems(
|
||||
tenantId: number,
|
||||
newEntriesDTO: IItemEntryDTO[]
|
||||
) {
|
||||
const { Item } = this.tenancy.models(tenantId);
|
||||
|
||||
const entriesItemsIds = newEntriesDTO.map((e) => e.itemId);
|
||||
const entriesItems = await Item.query().whereIn('id', entriesItemsIds);
|
||||
|
||||
const entriesItemsById = transformToMap(entriesItems, 'id');
|
||||
|
||||
// Filter the landed cost entries that not associated with inventory item.
|
||||
const nonInventoryHasCost = newEntriesDTO.filter((entry) => {
|
||||
const item = entriesItemsById.get(entry.itemId);
|
||||
|
||||
return entry.landedCost && item.type !== 'inventory';
|
||||
});
|
||||
if (nonInventoryHasCost.length > 0) {
|
||||
throw new ServiceError(
|
||||
ERRORS.LANDED_COST_ENTRIES_SHOULD_BE_INVENTORY_ITEMS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default cost account to the bill entries.
|
||||
*/
|
||||
private setBillEntriesDefaultAccounts(tenantId: number) {
|
||||
return async (entries: IItemEntry[]) => {
|
||||
const { Item } = this.tenancy.models(tenantId);
|
||||
|
||||
const entriesItemsIds = entries.map((e) => e.itemId);
|
||||
const items = await Item.query().whereIn('id', entriesItemsIds);
|
||||
|
||||
return entries.map((entry) => {
|
||||
const item = items.find((i) => i.id === entry.itemId);
|
||||
|
||||
return {
|
||||
...entry,
|
||||
...(item.type !== 'inventory' && {
|
||||
costAccountId: entry.costAccountId || item.costAccountId,
|
||||
}),
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the bill entries total.
|
||||
* @param {IItemEntry[]} entries
|
||||
* @returns {number}
|
||||
*/
|
||||
private getBillEntriesTotal(tenantId: number, entries: IItemEntry[]): number {
|
||||
const { ItemEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
return sumBy(entries, (e) => ItemEntry.calcAmount(e));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the bill landed cost amount.
|
||||
* @param {IBillDTO} billDTO
|
||||
* @returns {number}
|
||||
*/
|
||||
private getBillLandedCostAmount(tenantId: number, billDTO: IBillDTO): number {
|
||||
const costEntries = billDTO.entries.filter((entry) => entry.landedCost);
|
||||
|
||||
return this.getBillEntriesTotal(tenantId, costEntries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts create bill DTO to model.
|
||||
* @param {number} tenantId
|
||||
* @param {IBillDTO} billDTO
|
||||
* @param {IBill} oldBill
|
||||
* @returns {IBill}
|
||||
*/
|
||||
private async billDTOToModel(
|
||||
tenantId: number,
|
||||
billDTO: IBillDTO,
|
||||
vendor: IVendor,
|
||||
authorizedUser: ISystemUser,
|
||||
oldBill?: IBill
|
||||
) {
|
||||
const { ItemEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
const amount = sumBy(billDTO.entries, (e) => ItemEntry.calcAmount(e));
|
||||
|
||||
// Retrieve the landed cost amount from landed cost entries.
|
||||
const landedCostAmount = this.getBillLandedCostAmount(tenantId, billDTO);
|
||||
|
||||
// Bill number from DTO or from auto-increment.
|
||||
const billNumber = billDTO.billNumber || oldBill?.billNumber;
|
||||
|
||||
const initialEntries = billDTO.entries.map((entry) => ({
|
||||
reference_type: 'Bill',
|
||||
...omit(entry, ['amount']),
|
||||
}));
|
||||
const entries = await composeAsync(
|
||||
// Sets the default cost account to the bill entries.
|
||||
this.setBillEntriesDefaultAccounts(tenantId)
|
||||
)(initialEntries);
|
||||
|
||||
const initialDTO = {
|
||||
...formatDateFields(omit(billDTO, ['open', 'entries']), [
|
||||
'billDate',
|
||||
'dueDate',
|
||||
]),
|
||||
amount,
|
||||
landedCostAmount,
|
||||
currencyCode: vendor.currencyCode,
|
||||
exchangeRate: billDTO.exchangeRate || 1,
|
||||
billNumber,
|
||||
entries,
|
||||
// Avoid rewrite the open date in edit mode when already opened.
|
||||
...(billDTO.open &&
|
||||
!oldBill?.openedAt && {
|
||||
openedAt: moment().toMySqlDateTime(),
|
||||
}),
|
||||
userId: authorizedUser.id,
|
||||
};
|
||||
return R.compose(
|
||||
this.branchDTOTransform.transformDTO(tenantId),
|
||||
this.warehouseDTOTransform.transformDTO(tenantId)
|
||||
)(initialDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new bill and stored it to the storage.
|
||||
* ----
|
||||
* Precedures.
|
||||
* ----
|
||||
* - Insert bill transactions to the storage.
|
||||
* - Insert bill entries to the storage.
|
||||
* - Increment the given vendor id.
|
||||
* - Record bill journal transactions on the given accounts.
|
||||
* - Record bill items inventory transactions.
|
||||
* ----
|
||||
* @param {number} tenantId - The given tenant id.
|
||||
* @param {IBillDTO} billDTO -
|
||||
* @return {Promise<IBill>}
|
||||
*/
|
||||
public async createBill(
|
||||
tenantId: number,
|
||||
billDTO: IBillDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<IBill> {
|
||||
const { Bill, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieves the given bill vendor or throw not found error.
|
||||
const vendor = await Contact.query()
|
||||
.modify('vendor')
|
||||
.findById(billDTO.vendorId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate the bill number uniqiness on the storage.
|
||||
await this.validateBillNumberExists(tenantId, billDTO.billNumber);
|
||||
|
||||
// Validate items IDs existance.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Validate non-purchasable items.
|
||||
await this.itemsEntriesService.validateNonPurchasableEntriesItems(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Validates the cost entries should be with inventory items.
|
||||
await this.validateCostEntriesShouldBeInventoryItems(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Transform the bill DTO to model object.
|
||||
const billObj = await this.billDTOToModel(
|
||||
tenantId,
|
||||
billDTO,
|
||||
vendor,
|
||||
authorizedUser
|
||||
);
|
||||
// Write new bill transaction with associated transactions under UOW env.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onCreating, {
|
||||
trx,
|
||||
billDTO,
|
||||
tenantId,
|
||||
} as IBillCreatingPayload);
|
||||
|
||||
// Inserts the bill graph object to the storage.
|
||||
const bill = await Bill.query(trx).upsertGraph(billObj);
|
||||
|
||||
// Triggers `onBillCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onCreated, {
|
||||
tenantId,
|
||||
bill,
|
||||
billId: bill.id,
|
||||
trx,
|
||||
} as IBillCreatedPayload);
|
||||
|
||||
return bill;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits details of the given bill id with associated entries.
|
||||
*
|
||||
* Precedures:
|
||||
* -------
|
||||
* - Update the bill transaction on the storage.
|
||||
* - Update the bill entries on the storage and insert the not have id and delete
|
||||
* once that not presented.
|
||||
* - Increment the diff amount on the given vendor id.
|
||||
* - Re-write the inventory transactions.
|
||||
* - Re-write the bill journal transactions.
|
||||
* ------
|
||||
* @param {number} tenantId - The given tenant id.
|
||||
* @param {Integer} billId - The given bill id.
|
||||
* @param {IBillEditDTO} billDTO - The given new bill details.
|
||||
* @return {Promise<IBill>}
|
||||
*/
|
||||
public async editBill(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
billDTO: IBillEditDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<IBill> {
|
||||
const { Bill, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
const oldBill = await this.getBillOrThrowError(tenantId, billId);
|
||||
|
||||
// Retrieve vendor details or throw not found service error.
|
||||
const vendor = await Contact.query()
|
||||
.findById(billDTO.vendorId)
|
||||
.modify('vendor')
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate bill number uniqiness on the storage.
|
||||
if (billDTO.billNumber) {
|
||||
await this.validateBillNumberExists(tenantId, billDTO.billNumber, billId);
|
||||
}
|
||||
// Validate the entries ids existance.
|
||||
await this.itemsEntriesService.validateEntriesIdsExistance(
|
||||
tenantId,
|
||||
billId,
|
||||
'Bill',
|
||||
billDTO.entries
|
||||
);
|
||||
// Validate the items ids existance on the storage.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Accept the purchasable items only.
|
||||
await this.itemsEntriesService.validateNonPurchasableEntriesItems(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Transforms the bill DTO to model object.
|
||||
const billObj = await this.billDTOToModel(
|
||||
tenantId,
|
||||
billDTO,
|
||||
vendor,
|
||||
authorizedUser,
|
||||
oldBill
|
||||
);
|
||||
// Validate landed cost entries that have allocated cost could not be deleted.
|
||||
await this.entriesService.validateLandedCostEntriesNotDeleted(
|
||||
oldBill.entries,
|
||||
billObj.entries
|
||||
);
|
||||
// Validate new landed cost entries should be bigger than new entries.
|
||||
await this.entriesService.validateLocatedCostEntriesSmallerThanNewEntries(
|
||||
oldBill.entries,
|
||||
billObj.entries
|
||||
);
|
||||
// Edits bill transactions and associated transactions under UOW envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillEditing` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onEditing, {
|
||||
trx,
|
||||
tenantId,
|
||||
oldBill,
|
||||
billDTO,
|
||||
} as IBillEditingPayload);
|
||||
|
||||
// Update the bill transaction.
|
||||
const bill = await Bill.query(trx).upsertGraph({
|
||||
id: billId,
|
||||
...billObj,
|
||||
});
|
||||
// Triggers event `onBillEdited`.
|
||||
await this.eventPublisher.emitAsync(events.bill.onEdited, {
|
||||
tenantId,
|
||||
billId,
|
||||
oldBill,
|
||||
bill,
|
||||
trx,
|
||||
} as IBillEditedPayload);
|
||||
|
||||
return bill;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the bill with associated entries.
|
||||
* @param {Integer} billId
|
||||
* @return {void}
|
||||
*/
|
||||
public async deleteBill(tenantId: number, billId: number) {
|
||||
const { ItemEntry, Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await this.getBillOrThrowError(tenantId, billId);
|
||||
|
||||
// Validate the givne bill has no associated landed cost transactions.
|
||||
await this.validateBillHasNoLandedCost(tenantId, billId);
|
||||
|
||||
// Validate the purchase bill has no assocaited payments transactions.
|
||||
await this.validateBillHasNoEntries(tenantId, billId);
|
||||
|
||||
// Validate the given bill has no associated reconciled with vendor credits.
|
||||
await this.validateBillHasNoAppliedToCredit(tenantId, billId);
|
||||
|
||||
// Deletes bill transaction with associated transactions under
|
||||
// unit-of-work envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillDeleting` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onDeleting, {
|
||||
trx,
|
||||
tenantId,
|
||||
oldBill,
|
||||
} as IBillEventDeletingPayload);
|
||||
|
||||
// Delete all associated bill entries.
|
||||
await ItemEntry.query(trx)
|
||||
.where('reference_type', 'Bill')
|
||||
.where('reference_id', billId)
|
||||
.delete();
|
||||
|
||||
// Delete the bill transaction.
|
||||
await Bill.query(trx).findById(billId).delete();
|
||||
|
||||
// Triggers `onBillDeleted` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onDeleted, {
|
||||
tenantId,
|
||||
billId,
|
||||
oldBill,
|
||||
trx,
|
||||
} as IBIllEventDeletedPayload);
|
||||
});
|
||||
}
|
||||
|
||||
validateBillHasNoAppliedToCredit = async (
|
||||
tenantId: number,
|
||||
billId: number
|
||||
) => {
|
||||
const { VendorCreditAppliedBill } = this.tenancy.models(tenantId);
|
||||
|
||||
const appliedTransactions = await VendorCreditAppliedBill.query().where(
|
||||
'billId',
|
||||
billId
|
||||
);
|
||||
if (appliedTransactions.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_HAS_APPLIED_TO_VENDOR_CREDIT);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses bills list filter DTO.
|
||||
* @param filterDTO -
|
||||
*/
|
||||
private parseListFilterDTO(filterDTO) {
|
||||
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve bills data table list.
|
||||
* @param {number} tenantId -
|
||||
* @param {IBillsFilter} billsFilter -
|
||||
*/
|
||||
public async getBills(
|
||||
tenantId: number,
|
||||
filterDTO: IBillsFilter
|
||||
): Promise<{
|
||||
bills: IBill;
|
||||
pagination: IPaginationMeta;
|
||||
filterMeta: IFilterMeta;
|
||||
}> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Parses bills list filter DTO.
|
||||
const filter = this.parseListFilterDTO(filterDTO);
|
||||
|
||||
// Dynamic list service.
|
||||
const dynamicFilter = await this.dynamicListService.dynamicList(
|
||||
tenantId,
|
||||
Bill,
|
||||
filter
|
||||
);
|
||||
const { results, pagination } = await Bill.query()
|
||||
.onBuild((builder) => {
|
||||
builder.withGraphFetched('vendor');
|
||||
dynamicFilter.buildQuery()(builder);
|
||||
})
|
||||
.pagination(filter.page - 1, filter.pageSize);
|
||||
|
||||
// Tranform the bills to POJO.
|
||||
const bills = await this.transformer.transform(
|
||||
tenantId,
|
||||
results,
|
||||
new PurchaseInvoiceTransformer()
|
||||
);
|
||||
return {
|
||||
bills,
|
||||
pagination,
|
||||
filterMeta: dynamicFilter.getResponseMeta(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all due bills or for specific given vendor id.
|
||||
* @param {number} tenantId -
|
||||
* @param {number} vendorId -
|
||||
*/
|
||||
public async getDueBills(
|
||||
tenantId: number,
|
||||
vendorId?: number
|
||||
): Promise<IBill[]> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const dueBills = await Bill.query().onBuild((query) => {
|
||||
query.orderBy('bill_date', 'DESC');
|
||||
query.modify('dueBills');
|
||||
|
||||
if (vendorId) {
|
||||
query.where('vendor_id', vendorId);
|
||||
}
|
||||
});
|
||||
return dueBills;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the given bill details with associated items entries.
|
||||
* @param {Integer} billId - Specific bill.
|
||||
* @returns {Promise<IBill>}
|
||||
*/
|
||||
public async getBill(tenantId: number, billId: number): Promise<IBill> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const bill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('vendor')
|
||||
.withGraphFetched('entries.item')
|
||||
.withGraphFetched('branch');
|
||||
|
||||
if (!bill) {
|
||||
throw new ServiceError(ERRORS.BILL_NOT_FOUND);
|
||||
}
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
bill,
|
||||
new PurchaseInvoiceTransformer()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the bill as open.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
*/
|
||||
public async openBill(tenantId: number, billId: number): Promise<void> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await this.getBillOrThrowError(tenantId, billId);
|
||||
|
||||
if (oldBill.isOpen) {
|
||||
throw new ServiceError(ERRORS.BILL_ALREADY_OPEN);
|
||||
}
|
||||
//
|
||||
return this.uow.withTransaction(tenantId, async (trx) => {
|
||||
// Record the bill opened at on the storage.
|
||||
await Bill.query(trx).findById(billId).patch({
|
||||
openedAt: moment().toMySqlDateTime(),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the inventory transactions from the given bill input.
|
||||
* @param {Bill} bill - Bill model object.
|
||||
* @param {number} billId - Bill id.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async recordInventoryTransactions(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
override?: boolean,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retireve bill with assocaited entries and allocated cost entries.
|
||||
const bill = await Bill.query(trx)
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries.allocatedCostEntries');
|
||||
|
||||
// Loads the inventory items entries of the given sale invoice.
|
||||
const inventoryEntries =
|
||||
await this.itemsEntriesService.filterInventoryEntries(
|
||||
tenantId,
|
||||
bill.entries
|
||||
);
|
||||
const transaction = {
|
||||
transactionId: bill.id,
|
||||
transactionType: 'Bill',
|
||||
exchangeRate: bill.exchangeRate,
|
||||
|
||||
date: bill.billDate,
|
||||
direction: 'IN',
|
||||
entries: inventoryEntries,
|
||||
createdAt: bill.createdAt,
|
||||
|
||||
warehouseId: bill.warehouseId,
|
||||
};
|
||||
await this.inventoryService.recordInventoryTransactionsFromItemsEntries(
|
||||
tenantId,
|
||||
transaction,
|
||||
override,
|
||||
trx
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverts the inventory transactions of the given bill id.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} billId - Bill id.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async revertInventoryTransactions(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
trx?: Knex.Transaction
|
||||
) {
|
||||
// Deletes the inventory transactions by the given reference id and type.
|
||||
await this.inventoryService.deleteInventoryTransactions(
|
||||
tenantId,
|
||||
billId,
|
||||
'Bill',
|
||||
trx
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the given vendor has no associated bills transactions.
|
||||
* @param {number} tenantId
|
||||
* @param {number} vendorId - Vendor id.
|
||||
*/
|
||||
public async validateVendorHasNoBills(tenantId: number, vendorId: number) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const bills = await Bill.query().where('vendor_id', vendorId);
|
||||
|
||||
if (bills.length > 0) {
|
||||
throw new ServiceError(ERRORS.VENDOR_HAS_BILLS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { omit, sumBy } from 'lodash';
|
||||
import moment from 'moment';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import * as R from 'ramda';
|
||||
import composeAsync from 'async/compose';
|
||||
import { formatDateFields } from 'utils';
|
||||
import {
|
||||
IBillDTO,
|
||||
IBill,
|
||||
ISystemUser,
|
||||
IVendor,
|
||||
IItemEntry,
|
||||
} from '@/interfaces';
|
||||
import { BranchTransactionDTOTransform } from '@/services/Branches/Integrations/BranchTransactionDTOTransform';
|
||||
import { WarehouseTransactionDTOTransform } from '@/services/Warehouses/Integrations/WarehouseTransactionDTOTransform';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
@Service()
|
||||
export class BillDTOTransformer {
|
||||
@Inject()
|
||||
private branchDTOTransform: BranchTransactionDTOTransform;
|
||||
|
||||
@Inject()
|
||||
private warehouseDTOTransform: WarehouseTransactionDTOTransform;
|
||||
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Retrieve the bill entries total.
|
||||
* @param {IItemEntry[]} entries
|
||||
* @returns {number}
|
||||
*/
|
||||
private getBillEntriesTotal(tenantId: number, entries: IItemEntry[]): number {
|
||||
const { ItemEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
return sumBy(entries, (e) => ItemEntry.calcAmount(e));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the bill landed cost amount.
|
||||
* @param {IBillDTO} billDTO
|
||||
* @returns {number}
|
||||
*/
|
||||
private getBillLandedCostAmount(tenantId: number, billDTO: IBillDTO): number {
|
||||
const costEntries = billDTO.entries.filter((entry) => entry.landedCost);
|
||||
|
||||
return this.getBillEntriesTotal(tenantId, costEntries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts create bill DTO to model.
|
||||
* @param {number} tenantId
|
||||
* @param {IBillDTO} billDTO
|
||||
* @param {IBill} oldBill
|
||||
* @returns {IBill}
|
||||
*/
|
||||
public async billDTOToModel(
|
||||
tenantId: number,
|
||||
billDTO: IBillDTO,
|
||||
vendor: IVendor,
|
||||
authorizedUser: ISystemUser,
|
||||
oldBill?: IBill
|
||||
) {
|
||||
const { ItemEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
const amount = sumBy(billDTO.entries, (e) => ItemEntry.calcAmount(e));
|
||||
|
||||
// Retrieve the landed cost amount from landed cost entries.
|
||||
const landedCostAmount = this.getBillLandedCostAmount(tenantId, billDTO);
|
||||
|
||||
// Bill number from DTO or from auto-increment.
|
||||
const billNumber = billDTO.billNumber || oldBill?.billNumber;
|
||||
|
||||
const initialEntries = billDTO.entries.map((entry) => ({
|
||||
reference_type: 'Bill',
|
||||
...omit(entry, ['amount']),
|
||||
}));
|
||||
const entries = await composeAsync(
|
||||
// Sets the default cost account to the bill entries.
|
||||
this.setBillEntriesDefaultAccounts(tenantId)
|
||||
)(initialEntries);
|
||||
|
||||
const initialDTO = {
|
||||
...formatDateFields(omit(billDTO, ['open', 'entries']), [
|
||||
'billDate',
|
||||
'dueDate',
|
||||
]),
|
||||
amount,
|
||||
landedCostAmount,
|
||||
currencyCode: vendor.currencyCode,
|
||||
exchangeRate: billDTO.exchangeRate || 1,
|
||||
billNumber,
|
||||
entries,
|
||||
// Avoid rewrite the open date in edit mode when already opened.
|
||||
...(billDTO.open &&
|
||||
!oldBill?.openedAt && {
|
||||
openedAt: moment().toMySqlDateTime(),
|
||||
}),
|
||||
userId: authorizedUser.id,
|
||||
};
|
||||
return R.compose(
|
||||
this.branchDTOTransform.transformDTO(tenantId),
|
||||
this.warehouseDTOTransform.transformDTO(tenantId)
|
||||
)(initialDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default cost account to the bill entries.
|
||||
*/
|
||||
private setBillEntriesDefaultAccounts(tenantId: number) {
|
||||
return async (entries: IItemEntry[]) => {
|
||||
const { Item } = this.tenancy.models(tenantId);
|
||||
|
||||
const entriesItemsIds = entries.map((e) => e.itemId);
|
||||
const items = await Item.query().whereIn('id', entriesItemsIds);
|
||||
|
||||
return entries.map((entry) => {
|
||||
const item = items.find((i) => i.id === entry.itemId);
|
||||
|
||||
return {
|
||||
...entry,
|
||||
...(item.type !== 'inventory' && {
|
||||
costAccountId: entry.costAccountId || item.costAccountId,
|
||||
}),
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import events from '@/subscribers/events';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import BillsService from '@/services/Purchases/Bills';
|
||||
import {
|
||||
IBillCreatedPayload,
|
||||
IBillEditedPayload,
|
||||
@@ -12,15 +10,12 @@ import { BillGLEntries } from './BillGLEntries';
|
||||
@Service()
|
||||
export class BillGLEntriesSubscriber {
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
billGLEntries: BillGLEntries;
|
||||
private billGLEntries: BillGLEntries;
|
||||
|
||||
/**
|
||||
* Attachs events with handles.
|
||||
*/
|
||||
attach(bus) {
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.bill.onCreated,
|
||||
this.handlerWriteJournalEntriesOnCreate
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import InventoryService from '@/services/Inventory/Inventory';
|
||||
import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
@Service()
|
||||
export class BillInventoryTransactions {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
@Inject()
|
||||
private inventoryService: InventoryService;
|
||||
|
||||
/**
|
||||
* Records the inventory transactions from the given bill input.
|
||||
* @param {Bill} bill - Bill model object.
|
||||
* @param {number} billId - Bill id.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async recordInventoryTransactions(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
override?: boolean,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retireve bill with assocaited entries and allocated cost entries.
|
||||
const bill = await Bill.query(trx)
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries.allocatedCostEntries');
|
||||
|
||||
// Loads the inventory items entries of the given sale invoice.
|
||||
const inventoryEntries =
|
||||
await this.itemsEntriesService.filterInventoryEntries(
|
||||
tenantId,
|
||||
bill.entries
|
||||
);
|
||||
const transaction = {
|
||||
transactionId: bill.id,
|
||||
transactionType: 'Bill',
|
||||
exchangeRate: bill.exchangeRate,
|
||||
|
||||
date: bill.billDate,
|
||||
direction: 'IN',
|
||||
entries: inventoryEntries,
|
||||
createdAt: bill.createdAt,
|
||||
|
||||
warehouseId: bill.warehouseId,
|
||||
};
|
||||
await this.inventoryService.recordInventoryTransactionsFromItemsEntries(
|
||||
tenantId,
|
||||
transaction,
|
||||
override,
|
||||
trx
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverts the inventory transactions of the given bill id.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} billId - Bill id.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async revertInventoryTransactions(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
trx?: Knex.Transaction
|
||||
) {
|
||||
// Deletes the inventory transactions by the given reference id and type.
|
||||
await this.inventoryService.deleteInventoryTransactions(
|
||||
tenantId,
|
||||
billId,
|
||||
'Bill',
|
||||
trx
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export class BillPaymentsGLEntriesRewriteSubscriber {
|
||||
/**
|
||||
* Attachs events with handles.
|
||||
*/
|
||||
attach(bus) {
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.bill.onEdited,
|
||||
this.handlerRewritePaymentsGLOnBillEdited
|
||||
|
||||
147
packages/server/src/services/Purchases/Bills/BillsApplication.ts
Normal file
147
packages/server/src/services/Purchases/Bills/BillsApplication.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { CreateBill } from './CreateBill';
|
||||
import { EditBill } from './EditBill';
|
||||
import { GetBill } from './GetBill';
|
||||
import { GetBills } from './GetBills';
|
||||
import { DeleteBill } from './DeleteBill';
|
||||
import {
|
||||
IBill,
|
||||
IBillDTO,
|
||||
IBillEditDTO,
|
||||
IBillsFilter,
|
||||
IFilterMeta,
|
||||
IPaginationMeta,
|
||||
ISystemUser,
|
||||
} from '@/interfaces';
|
||||
import { GetDueBills } from './GetDueBills';
|
||||
import { OpenBill } from './OpenBill';
|
||||
import { GetBillPayments } from './GetBillPayments';
|
||||
|
||||
@Service()
|
||||
export class BillsApplication {
|
||||
@Inject()
|
||||
private createBillService: CreateBill;
|
||||
|
||||
@Inject()
|
||||
private editBillService: EditBill;
|
||||
|
||||
@Inject()
|
||||
private getBillService: GetBill;
|
||||
|
||||
@Inject()
|
||||
private getBillsService: GetBills;
|
||||
|
||||
@Inject()
|
||||
private deleteBillService: DeleteBill;
|
||||
|
||||
@Inject()
|
||||
private getDueBillsService: GetDueBills;
|
||||
|
||||
@Inject()
|
||||
private openBillService: OpenBill;
|
||||
|
||||
@Inject()
|
||||
private getBillPaymentsService: GetBillPayments;
|
||||
|
||||
/**
|
||||
* Creates a new bill with associated GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {IBillDTO} billDTO
|
||||
* @param {ISystemUser} authorizedUser
|
||||
* @returns
|
||||
*/
|
||||
public createBill(
|
||||
tenantId: number,
|
||||
billDTO: IBillDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<IBill> {
|
||||
return this.createBillService.createBill(tenantId, billDTO, authorizedUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits the given bill with associated GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
* @param {IBillEditDTO} billDTO
|
||||
* @param {ISystemUser} authorizedUser
|
||||
* @returns
|
||||
*/
|
||||
public editBill(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
billDTO: IBillEditDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<IBill> {
|
||||
return this.editBillService.editBill(
|
||||
tenantId,
|
||||
billId,
|
||||
billDTO,
|
||||
authorizedUser
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the given bill with associated GL entries.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public deleteBill(tenantId: number, billId: number) {
|
||||
return this.deleteBillService.deleteBill(tenantId, billId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve bills data table list.
|
||||
* @param {number} tenantId -
|
||||
* @param {IBillsFilter} billsFilter -
|
||||
*/
|
||||
public getBills(
|
||||
tenantId: number,
|
||||
filterDTO: IBillsFilter
|
||||
): Promise<{
|
||||
bills: IBill;
|
||||
pagination: IPaginationMeta;
|
||||
filterMeta: IFilterMeta;
|
||||
}> {
|
||||
return this.getBillsService.getBills(tenantId, filterDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the given bill details.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
* @returns
|
||||
*/
|
||||
public getBill(tenantId: number, billId: number): Promise<IBill> {
|
||||
return this.getBillService.getBill(tenantId, billId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the given bill.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public openBill(tenantId: number, billId: number): Promise<void> {
|
||||
return this.openBillService.openBill(tenantId, billId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves due bills of the given vendor.
|
||||
* @param {number} tenantId
|
||||
* @param {number} vendorId
|
||||
* @returns
|
||||
*/
|
||||
public getDueBills(tenantId: number, vendorId?: number) {
|
||||
return this.getDueBillsService.getDueBills(tenantId, vendorId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the specific bill associated payment transactions.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
*/
|
||||
public getBillPayments = async (tenantId: number, billId: number) => {
|
||||
return this.getBillPaymentsService.getBillPayments(tenantId, billId);
|
||||
};
|
||||
}
|
||||
154
packages/server/src/services/Purchases/Bills/BillsValidators.ts
Normal file
154
packages/server/src/services/Purchases/Bills/BillsValidators.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ERRORS } from './constants';
|
||||
import { IItemEntryDTO } from '@/interfaces';
|
||||
import { transformToMap } from '@/utils';
|
||||
import { Bill } from '@/models';
|
||||
|
||||
@Service()
|
||||
export class BillsValidators {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Validates the bill existance.
|
||||
* @param {Bill | undefined | null} bill
|
||||
*/
|
||||
public validateBillExistance(bill: Bill | undefined | null) {
|
||||
if (!bill) {
|
||||
throw new ServiceError(ERRORS.BILL_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill number existance.
|
||||
*/
|
||||
public async validateBillNumberExists(
|
||||
tenantId: number,
|
||||
billNumber: string,
|
||||
notBillId?: number
|
||||
) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
const foundBills = await Bill.query()
|
||||
.where('bill_number', billNumber)
|
||||
.onBuild((builder) => {
|
||||
if (notBillId) {
|
||||
builder.whereNot('id', notBillId);
|
||||
}
|
||||
});
|
||||
|
||||
if (foundBills.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_NUMBER_EXISTS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the bill has no payment entries.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} billId - Bill id.
|
||||
*/
|
||||
public async validateBillHasNoEntries(tenantId, billId: number) {
|
||||
const { BillPaymentEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retireve the bill associate payment made entries.
|
||||
const entries = await BillPaymentEntry.query().where('bill_id', billId);
|
||||
|
||||
if (entries.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_HAS_ASSOCIATED_PAYMENT_ENTRIES);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the bill number require.
|
||||
* @param {string} billNo -
|
||||
*/
|
||||
public validateBillNoRequire(billNo: string) {
|
||||
if (!billNo) {
|
||||
throw new ServiceError(ERRORS.BILL_NO_IS_REQUIRED);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate bill transaction has no associated allocated landed cost transactions.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
*/
|
||||
public async validateBillHasNoLandedCost(tenantId: number, billId: number) {
|
||||
const { BillLandedCost } = this.tenancy.models(tenantId);
|
||||
|
||||
const billLandedCosts = await BillLandedCost.query().where(
|
||||
'billId',
|
||||
billId
|
||||
);
|
||||
if (billLandedCosts.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_HAS_ASSOCIATED_LANDED_COSTS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate transaction entries that have landed cost type should not be
|
||||
* inventory items.
|
||||
* @param {number} tenantId -
|
||||
* @param {IItemEntryDTO[]} newEntriesDTO -
|
||||
*/
|
||||
public async validateCostEntriesShouldBeInventoryItems(
|
||||
tenantId: number,
|
||||
newEntriesDTO: IItemEntryDTO[]
|
||||
) {
|
||||
const { Item } = this.tenancy.models(tenantId);
|
||||
|
||||
const entriesItemsIds = newEntriesDTO.map((e) => e.itemId);
|
||||
const entriesItems = await Item.query().whereIn('id', entriesItemsIds);
|
||||
|
||||
const entriesItemsById = transformToMap(entriesItems, 'id');
|
||||
|
||||
// Filter the landed cost entries that not associated with inventory item.
|
||||
const nonInventoryHasCost = newEntriesDTO.filter((entry) => {
|
||||
const item = entriesItemsById.get(entry.itemId);
|
||||
|
||||
return entry.landedCost && item.type !== 'inventory';
|
||||
});
|
||||
if (nonInventoryHasCost.length > 0) {
|
||||
throw new ServiceError(
|
||||
ERRORS.LANDED_COST_ENTRIES_SHOULD_BE_INVENTORY_ITEMS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
*/
|
||||
public validateBillHasNoAppliedToCredit = async (
|
||||
tenantId: number,
|
||||
billId: number
|
||||
) => {
|
||||
const { VendorCreditAppliedBill } = this.tenancy.models(tenantId);
|
||||
|
||||
const appliedTransactions = await VendorCreditAppliedBill.query().where(
|
||||
'billId',
|
||||
billId
|
||||
);
|
||||
if (appliedTransactions.length > 0) {
|
||||
throw new ServiceError(ERRORS.BILL_HAS_APPLIED_TO_VENDOR_CREDIT);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the given vendor has no associated bills transactions.
|
||||
* @param {number} tenantId
|
||||
* @param {number} vendorId - Vendor id.
|
||||
*/
|
||||
public async validateVendorHasNoBills(tenantId: number, vendorId: number) {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const bills = await Bill.query().where('vendor_id', vendorId);
|
||||
|
||||
if (bills.length > 0) {
|
||||
throw new ServiceError(ERRORS.VENDOR_HAS_BILLS);
|
||||
}
|
||||
}
|
||||
}
|
||||
116
packages/server/src/services/Purchases/Bills/CreateBill.ts
Normal file
116
packages/server/src/services/Purchases/Bills/CreateBill.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { Knex } from 'knex';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IBillDTO,
|
||||
IBill,
|
||||
ISystemUser,
|
||||
IBillCreatedPayload,
|
||||
IBillCreatingPayload,
|
||||
} from '@/interfaces';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { BillsValidators } from './BillsValidators';
|
||||
import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
import { BillDTOTransformer } from './BillDTOTransformer';
|
||||
|
||||
@Service()
|
||||
export class CreateBill {
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private validators: BillsValidators;
|
||||
|
||||
@Inject()
|
||||
private itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
@Inject()
|
||||
private transformerDTO: BillDTOTransformer;
|
||||
|
||||
/**
|
||||
* Creates a new bill and stored it to the storage.
|
||||
* ----
|
||||
* Precedures.
|
||||
* ----
|
||||
* - Insert bill transactions to the storage.
|
||||
* - Insert bill entries to the storage.
|
||||
* - Increment the given vendor id.
|
||||
* - Record bill journal transactions on the given accounts.
|
||||
* - Record bill items inventory transactions.
|
||||
* ----
|
||||
* @param {number} tenantId - The given tenant id.
|
||||
* @param {IBillDTO} billDTO -
|
||||
* @return {Promise<IBill>}
|
||||
*/
|
||||
public async createBill(
|
||||
tenantId: number,
|
||||
billDTO: IBillDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<IBill> {
|
||||
const { Bill, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieves the given bill vendor or throw not found error.
|
||||
const vendor = await Contact.query()
|
||||
.modify('vendor')
|
||||
.findById(billDTO.vendorId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate the bill number uniqiness on the storage.
|
||||
await this.validators.validateBillNumberExists(
|
||||
tenantId,
|
||||
billDTO.billNumber
|
||||
);
|
||||
// Validate items IDs existance.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Validate non-purchasable items.
|
||||
await this.itemsEntriesService.validateNonPurchasableEntriesItems(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Validates the cost entries should be with inventory items.
|
||||
await this.validators.validateCostEntriesShouldBeInventoryItems(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Transform the bill DTO to model object.
|
||||
const billObj = await this.transformerDTO.billDTOToModel(
|
||||
tenantId,
|
||||
billDTO,
|
||||
vendor,
|
||||
authorizedUser
|
||||
);
|
||||
// Write new bill transaction with associated transactions under UOW env.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onCreating, {
|
||||
trx,
|
||||
billDTO,
|
||||
tenantId,
|
||||
} as IBillCreatingPayload);
|
||||
|
||||
// Inserts the bill graph object to the storage.
|
||||
const bill = await Bill.query(trx).upsertGraph(billObj);
|
||||
|
||||
// Triggers `onBillCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onCreated, {
|
||||
tenantId,
|
||||
bill,
|
||||
billId: bill.id,
|
||||
trx,
|
||||
} as IBillCreatedPayload);
|
||||
|
||||
return bill;
|
||||
});
|
||||
}
|
||||
}
|
||||
80
packages/server/src/services/Purchases/Bills/DeleteBill.ts
Normal file
80
packages/server/src/services/Purchases/Bills/DeleteBill.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { Knex } from 'knex';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
IBIllEventDeletedPayload,
|
||||
IBillEventDeletingPayload,
|
||||
} from '@/interfaces';
|
||||
import { BillsValidators } from './BillsValidators';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
@Service()
|
||||
export class DeleteBill {
|
||||
@Inject()
|
||||
private validators: BillsValidators;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Deletes the bill with associated entries.
|
||||
* @param {number} billId
|
||||
* @return {void}
|
||||
*/
|
||||
public async deleteBill(tenantId: number, billId: number) {
|
||||
const { ItemEntry, Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Validates the bill existance.
|
||||
this.validators.validateBillExistance(oldBill);
|
||||
|
||||
// Validate the givne bill has no associated landed cost transactions.
|
||||
await this.validators.validateBillHasNoLandedCost(tenantId, billId);
|
||||
|
||||
// Validate the purchase bill has no assocaited payments transactions.
|
||||
await this.validators.validateBillHasNoEntries(tenantId, billId);
|
||||
|
||||
// Validate the given bill has no associated reconciled with vendor credits.
|
||||
await this.validators.validateBillHasNoAppliedToCredit(tenantId, billId);
|
||||
|
||||
// Deletes bill transaction with associated transactions under
|
||||
// unit-of-work envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillDeleting` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onDeleting, {
|
||||
trx,
|
||||
tenantId,
|
||||
oldBill,
|
||||
} as IBillEventDeletingPayload);
|
||||
|
||||
// Delete all associated bill entries.
|
||||
await ItemEntry.query(trx)
|
||||
.where('reference_type', 'Bill')
|
||||
.where('reference_id', billId)
|
||||
.delete();
|
||||
|
||||
// Delete the bill transaction.
|
||||
await Bill.query(trx).findById(billId).delete();
|
||||
|
||||
// Triggers `onBillDeleted` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onDeleted, {
|
||||
tenantId,
|
||||
billId,
|
||||
oldBill,
|
||||
trx,
|
||||
} as IBIllEventDeletedPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
151
packages/server/src/services/Purchases/Bills/EditBill.ts
Normal file
151
packages/server/src/services/Purchases/Bills/EditBill.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import {
|
||||
IBill,
|
||||
IBillEditDTO,
|
||||
IBillEditedPayload,
|
||||
IBillEditingPayload,
|
||||
ISystemUser,
|
||||
} from '@/interfaces';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { BillsValidators } from './BillsValidators';
|
||||
import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { Knex } from 'knex';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import events from '@/subscribers/events';
|
||||
import EntriesService from '@/services/Entries';
|
||||
import { BillDTOTransformer } from './BillDTOTransformer';
|
||||
|
||||
@Service()
|
||||
export class EditBill {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private validators: BillsValidators;
|
||||
|
||||
@Inject()
|
||||
private itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private entriesService: EntriesService;
|
||||
|
||||
@Inject()
|
||||
private transformerDTO: BillDTOTransformer;
|
||||
|
||||
/**
|
||||
* Edits details of the given bill id with associated entries.
|
||||
*
|
||||
* Precedures:
|
||||
* -------
|
||||
* - Update the bill transaction on the storage.
|
||||
* - Update the bill entries on the storage and insert the not have id and delete
|
||||
* once that not presented.
|
||||
* - Increment the diff amount on the given vendor id.
|
||||
* - Re-write the inventory transactions.
|
||||
* - Re-write the bill journal transactions.
|
||||
* ------
|
||||
* @param {number} tenantId - The given tenant id.
|
||||
* @param {Integer} billId - The given bill id.
|
||||
* @param {IBillEditDTO} billDTO - The given new bill details.
|
||||
* @return {Promise<IBill>}
|
||||
*/
|
||||
public async editBill(
|
||||
tenantId: number,
|
||||
billId: number,
|
||||
billDTO: IBillEditDTO,
|
||||
authorizedUser: ISystemUser
|
||||
): Promise<IBill> {
|
||||
const { Bill, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Validate bill existance.
|
||||
this.validators.validateBillExistance(oldBill);
|
||||
|
||||
// Retrieve vendor details or throw not found service error.
|
||||
const vendor = await Contact.query()
|
||||
.findById(billDTO.vendorId)
|
||||
.modify('vendor')
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate bill number uniqiness on the storage.
|
||||
if (billDTO.billNumber) {
|
||||
await this.validators.validateBillNumberExists(
|
||||
tenantId,
|
||||
billDTO.billNumber,
|
||||
billId
|
||||
);
|
||||
}
|
||||
// Validate the entries ids existance.
|
||||
await this.itemsEntriesService.validateEntriesIdsExistance(
|
||||
tenantId,
|
||||
billId,
|
||||
'Bill',
|
||||
billDTO.entries
|
||||
);
|
||||
// Validate the items ids existance on the storage.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Accept the purchasable items only.
|
||||
await this.itemsEntriesService.validateNonPurchasableEntriesItems(
|
||||
tenantId,
|
||||
billDTO.entries
|
||||
);
|
||||
// Transforms the bill DTO to model object.
|
||||
const billObj = await this.transformerDTO.billDTOToModel(
|
||||
tenantId,
|
||||
billDTO,
|
||||
vendor,
|
||||
authorizedUser,
|
||||
oldBill
|
||||
);
|
||||
// Validate landed cost entries that have allocated cost could not be deleted.
|
||||
await this.entriesService.validateLandedCostEntriesNotDeleted(
|
||||
oldBill.entries,
|
||||
billObj.entries
|
||||
);
|
||||
// Validate new landed cost entries should be bigger than new entries.
|
||||
await this.entriesService.validateLocatedCostEntriesSmallerThanNewEntries(
|
||||
oldBill.entries,
|
||||
billObj.entries
|
||||
);
|
||||
// Edits bill transactions and associated transactions under UOW envirement.
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillEditing` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onEditing, {
|
||||
trx,
|
||||
tenantId,
|
||||
oldBill,
|
||||
billDTO,
|
||||
} as IBillEditingPayload);
|
||||
|
||||
// Update the bill transaction.
|
||||
const bill = await Bill.query(trx).upsertGraph({
|
||||
id: billId,
|
||||
...billObj,
|
||||
});
|
||||
// Triggers event `onBillEdited`.
|
||||
await this.eventPublisher.emitAsync(events.bill.onEdited, {
|
||||
tenantId,
|
||||
billId,
|
||||
oldBill,
|
||||
bill,
|
||||
trx,
|
||||
} as IBillEditedPayload);
|
||||
|
||||
return bill;
|
||||
});
|
||||
}
|
||||
}
|
||||
42
packages/server/src/services/Purchases/Bills/GetBill.ts
Normal file
42
packages/server/src/services/Purchases/Bills/GetBill.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
import { IBill } from '@/interfaces';
|
||||
import { BillsValidators } from './BillsValidators';
|
||||
import { PurchaseInvoiceTransformer } from './PurchaseInvoiceTransformer';
|
||||
|
||||
@Service()
|
||||
export class GetBill {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
@Inject()
|
||||
private validators: BillsValidators;
|
||||
|
||||
/**
|
||||
* Retrieve the given bill details with associated items entries.
|
||||
* @param {Integer} billId - Specific bill.
|
||||
* @returns {Promise<IBill>}
|
||||
*/
|
||||
public async getBill(tenantId: number, billId: number): Promise<IBill> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const bill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('vendor')
|
||||
.withGraphFetched('entries.item')
|
||||
.withGraphFetched('branch');
|
||||
|
||||
// Validates the bill existance.
|
||||
this.validators.validateBillExistance(bill);
|
||||
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
bill,
|
||||
new PurchaseInvoiceTransformer()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { BillPaymentTransactionTransformer } from './BillPayments/BillPaymentTransactionTransformer';
|
||||
import { BillPaymentTransactionTransformer } from '../BillPayments/BillPaymentTransactionTransformer';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
|
||||
@Service()
|
||||
export default class BillPaymentsService {
|
||||
export class GetBillPayments {
|
||||
@Inject()
|
||||
private tenancy: TenancyService;
|
||||
|
||||
76
packages/server/src/services/Purchases/Bills/GetBills.ts
Normal file
76
packages/server/src/services/Purchases/Bills/GetBills.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
IBill,
|
||||
IBillsFilter,
|
||||
IFilterMeta,
|
||||
IPaginationMeta,
|
||||
} from '@/interfaces';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { PurchaseInvoiceTransformer } from './PurchaseInvoiceTransformer';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
|
||||
@Service()
|
||||
export class GetBills {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
@Inject()
|
||||
private dynamicListService: DynamicListingService;
|
||||
|
||||
/**
|
||||
* Retrieve bills data table list.
|
||||
* @param {number} tenantId -
|
||||
* @param {IBillsFilter} billsFilter -
|
||||
*/
|
||||
public async getBills(
|
||||
tenantId: number,
|
||||
filterDTO: IBillsFilter
|
||||
): Promise<{
|
||||
bills: IBill;
|
||||
pagination: IPaginationMeta;
|
||||
filterMeta: IFilterMeta;
|
||||
}> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Parses bills list filter DTO.
|
||||
const filter = this.parseListFilterDTO(filterDTO);
|
||||
|
||||
// Dynamic list service.
|
||||
const dynamicFilter = await this.dynamicListService.dynamicList(
|
||||
tenantId,
|
||||
Bill,
|
||||
filter
|
||||
);
|
||||
const { results, pagination } = await Bill.query()
|
||||
.onBuild((builder) => {
|
||||
builder.withGraphFetched('vendor');
|
||||
dynamicFilter.buildQuery()(builder);
|
||||
})
|
||||
.pagination(filter.page - 1, filter.pageSize);
|
||||
|
||||
// Tranform the bills to POJO.
|
||||
const bills = await this.transformer.transform(
|
||||
tenantId,
|
||||
results,
|
||||
new PurchaseInvoiceTransformer()
|
||||
);
|
||||
return {
|
||||
bills,
|
||||
pagination,
|
||||
filterMeta: dynamicFilter.getResponseMeta(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses bills list filter DTO.
|
||||
* @param filterDTO -
|
||||
*/
|
||||
private parseListFilterDTO(filterDTO) {
|
||||
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
|
||||
}
|
||||
}
|
||||
32
packages/server/src/services/Purchases/Bills/GetDueBills.ts
Normal file
32
packages/server/src/services/Purchases/Bills/GetDueBills.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { IBill } from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export class GetDueBills {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Retrieve all due bills or for specific given vendor id.
|
||||
* @param {number} tenantId -
|
||||
* @param {number} vendorId -
|
||||
*/
|
||||
public async getDueBills(
|
||||
tenantId: number,
|
||||
vendorId?: number
|
||||
): Promise<IBill[]> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
const dueBills = await Bill.query().onBuild((query) => {
|
||||
query.orderBy('bill_date', 'DESC');
|
||||
query.modify('dueBills');
|
||||
|
||||
if (vendorId) {
|
||||
query.where('vendor_id', vendorId);
|
||||
}
|
||||
});
|
||||
return dueBills;
|
||||
}
|
||||
}
|
||||
46
packages/server/src/services/Purchases/Bills/OpenBill.ts
Normal file
46
packages/server/src/services/Purchases/Bills/OpenBill.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import moment from 'moment';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { ERRORS } from './constants';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { BillsValidators } from './BillsValidators';
|
||||
|
||||
@Service()
|
||||
export class OpenBill {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
private validators: BillsValidators;
|
||||
|
||||
/**
|
||||
* Mark the bill as open.
|
||||
* @param {number} tenantId
|
||||
* @param {number} billId
|
||||
*/
|
||||
public async openBill(tenantId: number, billId: number): Promise<void> {
|
||||
const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Validates the bill existance.
|
||||
this.validators.validateBillExistance(oldBill);
|
||||
|
||||
if (oldBill.isOpen) {
|
||||
throw new ServiceError(ERRORS.BILL_ALREADY_OPEN);
|
||||
}
|
||||
return this.uow.withTransaction(tenantId, async (trx) => {
|
||||
// Record the bill opened at on the storage.
|
||||
await Bill.query(trx).findById(billId).patch({
|
||||
openedAt: moment().toMySqlDateTime(),
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -41,13 +41,16 @@ export default class AllocateLandedCost extends BaseLandedCostService {
|
||||
allocateCostDTO: ILandedCostDTO,
|
||||
billId: number
|
||||
): Promise<IBillLandedCost> => {
|
||||
const { BillLandedCost } = this.tenancy.models(tenantId);
|
||||
const { BillLandedCost, Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve total cost of allocated items.
|
||||
const amount = this.getAllocateItemsCostTotal(allocateCostDTO);
|
||||
|
||||
// Retrieve the purchase invoice or throw not found error.
|
||||
const bill = await this.billsService.getBillOrThrowError(tenantId, billId);
|
||||
const bill = await Bill.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries')
|
||||
.throwIfNotFound();
|
||||
|
||||
// Retrieve landed cost transaction or throw not found service error.
|
||||
const costTransaction = await this.getLandedCostOrThrowError(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { difference, sumBy } from 'lodash';
|
||||
import BillsService from '../Bills';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import {
|
||||
IItemEntry,
|
||||
@@ -13,14 +12,10 @@ import {
|
||||
} from '@/interfaces';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import TransactionLandedCost from './TransctionLandedCost';
|
||||
import { ERRORS } from './utils';
|
||||
import { CONFIG } from './utils';
|
||||
import { ERRORS, CONFIG } from './utils';
|
||||
|
||||
@Service()
|
||||
export default class BaseLandedCostService {
|
||||
@Inject()
|
||||
public billsService: BillsService;
|
||||
|
||||
@Inject()
|
||||
public tenancy: HasTenancyService;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import LandedCostSyncCostTransactions from './LandedCostSyncCostTransactions';
|
||||
@Service()
|
||||
export default class LandedCostSyncCostTransactionsSubscriber {
|
||||
@Inject()
|
||||
landedCostSyncCostTransaction: LandedCostSyncCostTransactions;
|
||||
private landedCostSyncCostTransaction: LandedCostSyncCostTransactions;
|
||||
|
||||
/**
|
||||
* Attaches events with handlers.
|
||||
|
||||
@@ -9,20 +9,12 @@ import {
|
||||
ILandedCostTransactionEntryDOJO,
|
||||
} from '@/interfaces';
|
||||
import TransactionLandedCost from './TransctionLandedCost';
|
||||
import BillsService from '../Bills';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { formatNumber } from 'utils';
|
||||
|
||||
@Service()
|
||||
export default class LandedCostTranasctions {
|
||||
@Inject()
|
||||
transactionLandedCost: TransactionLandedCost;
|
||||
|
||||
@Inject()
|
||||
billsService: BillsService;
|
||||
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private transactionLandedCost: TransactionLandedCost;
|
||||
|
||||
/**
|
||||
* Retrieve the landed costs based on the given query.
|
||||
|
||||
@@ -16,13 +16,13 @@ import { ERRORS } from './utils';
|
||||
@Service()
|
||||
export default class TransactionLandedCost {
|
||||
@Inject()
|
||||
billLandedCost: BillLandedCost;
|
||||
private billLandedCost: BillLandedCost;
|
||||
|
||||
@Inject()
|
||||
expenseLandedCost: ExpenseLandedCost;
|
||||
private expenseLandedCost: ExpenseLandedCost;
|
||||
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Retrieve the cost transaction code model.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import Knex from 'knex';
|
||||
import { Knex } from 'knex';
|
||||
import { sumBy } from 'lodash';
|
||||
import {
|
||||
IVendorCredit,
|
||||
@@ -9,27 +9,27 @@ import {
|
||||
IBill,
|
||||
} from '@/interfaces';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import PaymentReceiveService from '@/services/Sales/PaymentReceives/PaymentsReceives';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import events from '@/subscribers/events';
|
||||
import VendorCredit from '../BaseVendorCredit';
|
||||
import BillPaymentsService from '@/services/Purchases/BillPayments/BillPayments';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { BillPaymentValidators } from '../../BillPayments/BillPaymentValidators';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { ERRORS } from '../constants';
|
||||
|
||||
@Service()
|
||||
export default class ApplyVendorCreditToBills extends VendorCredit {
|
||||
@Inject('PaymentReceives')
|
||||
paymentReceive: PaymentReceiveService;
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
uow: UnitOfWork;
|
||||
private uow: UnitOfWork;
|
||||
|
||||
@Inject()
|
||||
eventPublisher: EventPublisher;
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
billPayment: BillPaymentsService;
|
||||
private billPaymentValidators: BillPaymentValidators;
|
||||
|
||||
/**
|
||||
* Apply credit note to the given invoices.
|
||||
@@ -55,11 +55,12 @@ export default class ApplyVendorCreditToBills extends VendorCredit {
|
||||
vendorCredit
|
||||
);
|
||||
// Validate bills entries existance.
|
||||
const appliedBills = await this.billPayment.validateBillsExistance(
|
||||
tenantId,
|
||||
vendorCreditAppliedModel.entries,
|
||||
vendorCredit.vendorId
|
||||
);
|
||||
const appliedBills =
|
||||
await this.billPaymentValidators.validateBillsExistance(
|
||||
tenantId,
|
||||
vendorCreditAppliedModel.entries,
|
||||
vendorCredit.vendorId
|
||||
);
|
||||
// Validate bills has remaining amount to apply.
|
||||
this.validateBillsRemainingAmount(
|
||||
appliedBills,
|
||||
|
||||
Reference in New Issue
Block a user