mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 22:00:31 +00:00
refactor: wip to nestjs
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import { omit, sumBy } from 'lodash';
|
||||
import moment from 'moment';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import * as R from 'ramda';
|
||||
import { formatDateFields } from '@/utils/format-date-fields';
|
||||
import composeAsync from 'async/compose';
|
||||
import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations/BranchTransactionDTOTransform';
|
||||
import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform';
|
||||
import { ItemEntry } from '@/modules/Items/models/ItemEntry';
|
||||
import { Item } from '@/modules/Items/models/Item';
|
||||
import { ItemEntriesTaxTransactions } from '@/modules/TaxRates/ItemEntriesTaxTransactions.service';
|
||||
import { IBillDTO } from '../Bills.types';
|
||||
import { Vendor } from '@/modules/Vendors/models/Vendor';
|
||||
import { Bill } from '../models/Bill';
|
||||
import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index';
|
||||
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
|
||||
|
||||
@Injectable()
|
||||
export class BillDTOTransformer {
|
||||
constructor(
|
||||
private branchDTOTransform: BranchTransactionDTOTransformer,
|
||||
private warehouseDTOTransform: WarehouseTransactionDTOTransform,
|
||||
private taxDTOTransformer: ItemEntriesTaxTransactions,
|
||||
private tenancyContext: TenancyContext,
|
||||
|
||||
@Inject(ItemEntry) private itemEntryModel: typeof ItemEntry,
|
||||
@Inject(Item) private itemModel: typeof Item,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve the bill entries total.
|
||||
* @param {IItemEntry[]} entries
|
||||
* @returns {number}
|
||||
*/
|
||||
private getBillEntriesTotal(entries: ItemEntry[]): number {
|
||||
return sumBy(entries, (e) => this.itemEntryModel.calcAmount(e));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the bill landed cost amount.
|
||||
* @param {IBillDTO} billDTO
|
||||
* @returns {number}
|
||||
*/
|
||||
private getBillLandedCostAmount(billDTO: IBillDTO): number {
|
||||
const costEntries = billDTO.entries.filter((entry) => entry.landedCost);
|
||||
|
||||
return this.getBillEntriesTotal(costEntries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts create bill DTO to model.
|
||||
* @param {IBillDTO} billDTO
|
||||
* @param {IBill} oldBill
|
||||
* @returns {IBill}
|
||||
*/
|
||||
public async billDTOToModel(
|
||||
billDTO: IBillDTO,
|
||||
vendor: Vendor,
|
||||
oldBill?: Bill,
|
||||
) {
|
||||
const amount = sumBy(billDTO.entries, (e) =>
|
||||
this.itemEntryModel.calcAmount(e),
|
||||
);
|
||||
// Retrieve the landed cost amount from landed cost entries.
|
||||
const landedCostAmount = this.getBillLandedCostAmount(billDTO);
|
||||
|
||||
// Retrieve the authorized user.
|
||||
const authorizedUser = await this.tenancyContext.getSystemUser();
|
||||
|
||||
// Bill number from DTO or frprom auto-increment.
|
||||
const billNumber = billDTO.billNumber || oldBill?.billNumber;
|
||||
|
||||
const initialEntries = billDTO.entries.map((entry) => ({
|
||||
referenceType: 'Bill',
|
||||
isInclusiveTax: billDTO.isInclusiveTax,
|
||||
...omit(entry, ['amount']),
|
||||
}));
|
||||
const asyncEntries = await composeAsync(
|
||||
// Associate tax rate from tax id to entries.
|
||||
this.taxDTOTransformer.assocTaxRateFromTaxIdToEntries,
|
||||
// Associate tax rate id from tax code to entries.
|
||||
this.taxDTOTransformer.assocTaxRateIdFromCodeToEntries,
|
||||
// Sets the default cost account to the bill entries.
|
||||
this.setBillEntriesDefaultAccounts(),
|
||||
)(initialEntries);
|
||||
|
||||
const entries = R.compose(
|
||||
// Remove tax code from entries.
|
||||
R.map(R.omit(['taxCode'])),
|
||||
// Associate the default index to each item entry line.
|
||||
assocItemEntriesDefaultIndex,
|
||||
)(asyncEntries);
|
||||
|
||||
const initialDTO = {
|
||||
...formatDateFields(omit(billDTO, ['open', 'entries', 'attachments']), [
|
||||
'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(
|
||||
// Associates tax amount withheld to the model.
|
||||
this.taxDTOTransformer.assocTaxAmountWithheldFromEntries,
|
||||
this.branchDTOTransform.transformDTO,
|
||||
this.warehouseDTOTransform.transformDTO,
|
||||
)(initialDTO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default cost account to the bill entries.
|
||||
*/
|
||||
private setBillEntriesDefaultAccounts() {
|
||||
return async (entries: ItemEntry[]) => {
|
||||
const entriesItemsIds = entries.map((e) => e.itemId);
|
||||
const items = await this.itemModel.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,
|
||||
}),
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
288
packages/server-nest/src/modules/Bills/commands/BillGLEntries.ts
Normal file
288
packages/server-nest/src/modules/Bills/commands/BillGLEntries.ts
Normal file
@@ -0,0 +1,288 @@
|
||||
// import moment from 'moment';
|
||||
// import { sumBy } from 'lodash';
|
||||
// import { Knex } from 'knex';
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import * as R from 'ramda';
|
||||
// import { AccountNormal, IBill, IItemEntry, ILedgerEntry } from '@/interfaces';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
// import Ledger from '@/services/Accounting/Ledger';
|
||||
// import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
// import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
|
||||
// @Service()
|
||||
// export class BillGLEntries {
|
||||
// @Inject()
|
||||
// private tenancy: HasTenancyService;
|
||||
|
||||
// @Inject()
|
||||
// private ledgerStorage: LedgerStorageService;
|
||||
|
||||
// @Inject()
|
||||
// private itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
// /**
|
||||
// * Creates bill GL entries.
|
||||
// * @param {number} tenantId -
|
||||
// * @param {number} billId -
|
||||
// * @param {Knex.Transaction} trx -
|
||||
// */
|
||||
// public writeBillGLEntries = async (
|
||||
// tenantId: number,
|
||||
// billId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
// const { Bill } = this.tenancy.models(tenantId);
|
||||
|
||||
// // Retrieves bill with associated entries and landed costs.
|
||||
// const bill = await Bill.query(trx)
|
||||
// .findById(billId)
|
||||
// .withGraphFetched('entries.item')
|
||||
// .withGraphFetched('entries.allocatedCostEntries')
|
||||
// .withGraphFetched('locatedLandedCosts.allocateEntries');
|
||||
|
||||
// // Finds or create a A/P account based on the given currency.
|
||||
// const APAccount = await accountRepository.findOrCreateAccountsPayable(
|
||||
// bill.currencyCode,
|
||||
// {},
|
||||
// trx
|
||||
// );
|
||||
// // Find or create tax payable account.
|
||||
// const taxPayableAccount = await accountRepository.findOrCreateTaxPayable(
|
||||
// {},
|
||||
// trx
|
||||
// );
|
||||
// const billLedger = this.getBillLedger(
|
||||
// bill,
|
||||
// APAccount.id,
|
||||
// taxPayableAccount.id
|
||||
// );
|
||||
// // Commit the GL enties on the storage.
|
||||
// await this.ledgerStorage.commit(tenantId, billLedger, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Reverts the given bill GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} billId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public revertBillGLEntries = async (
|
||||
// tenantId: number,
|
||||
// billId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// await this.ledgerStorage.deleteByReference(tenantId, billId, 'Bill', trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Rewrites the given bill GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} billId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public rewriteBillGLEntries = async (
|
||||
// tenantId: number,
|
||||
// billId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// // Reverts the bill GL entries.
|
||||
// await this.revertBillGLEntries(tenantId, billId, trx);
|
||||
|
||||
// // Writes the bill GL entries.
|
||||
// await this.writeBillGLEntries(tenantId, billId, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the bill common entry.
|
||||
// * @param {IBill} bill
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getBillCommonEntry = (bill: IBill) => {
|
||||
// return {
|
||||
// debit: 0,
|
||||
// credit: 0,
|
||||
// currencyCode: bill.currencyCode,
|
||||
// exchangeRate: bill.exchangeRate || 1,
|
||||
|
||||
// transactionId: bill.id,
|
||||
// transactionType: 'Bill',
|
||||
|
||||
// date: moment(bill.billDate).format('YYYY-MM-DD'),
|
||||
// userId: bill.userId,
|
||||
|
||||
// referenceNumber: bill.referenceNo,
|
||||
// transactionNumber: bill.billNumber,
|
||||
|
||||
// branchId: bill.branchId,
|
||||
// projectId: bill.projectId,
|
||||
|
||||
// createdAt: bill.createdAt,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the bill item inventory/cost entry.
|
||||
// * @param {IBill} bill -
|
||||
// * @param {IItemEntry} entry -
|
||||
// * @param {number} index -
|
||||
// */
|
||||
// private getBillItemEntry = R.curry(
|
||||
// (bill: IBill, entry: IItemEntry, index: number): ILedgerEntry => {
|
||||
// const commonJournalMeta = this.getBillCommonEntry(bill);
|
||||
|
||||
// const localAmount = bill.exchangeRate * entry.amountExludingTax;
|
||||
// const landedCostAmount = sumBy(entry.allocatedCostEntries, 'cost');
|
||||
|
||||
// return {
|
||||
// ...commonJournalMeta,
|
||||
// debit: localAmount + landedCostAmount,
|
||||
// accountId:
|
||||
// ['inventory'].indexOf(entry.item.type) !== -1
|
||||
// ? entry.item.inventoryAccountId
|
||||
// : entry.costAccountId,
|
||||
// index: index + 1,
|
||||
// indexGroup: 10,
|
||||
// itemId: entry.itemId,
|
||||
// itemQuantity: entry.quantity,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// };
|
||||
// }
|
||||
// );
|
||||
|
||||
// /**
|
||||
// * Retrieves the bill landed cost entry.
|
||||
// * @param {IBill} bill -
|
||||
// * @param {} landedCost -
|
||||
// * @param {number} index -
|
||||
// */
|
||||
// private getBillLandedCostEntry = R.curry(
|
||||
// (bill: IBill, landedCost, index: number): ILedgerEntry => {
|
||||
// const commonJournalMeta = this.getBillCommonEntry(bill);
|
||||
|
||||
// return {
|
||||
// ...commonJournalMeta,
|
||||
// credit: landedCost.amount,
|
||||
// accountId: landedCost.costAccountId,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// index: 1,
|
||||
// indexGroup: 20,
|
||||
// };
|
||||
// }
|
||||
// );
|
||||
|
||||
// /**
|
||||
// * Retrieves the bill payable entry.
|
||||
// * @param {number} payableAccountId
|
||||
// * @param {IBill} bill
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getBillPayableEntry = (
|
||||
// payableAccountId: number,
|
||||
// bill: IBill
|
||||
// ): ILedgerEntry => {
|
||||
// const commonJournalMeta = this.getBillCommonEntry(bill);
|
||||
|
||||
// return {
|
||||
// ...commonJournalMeta,
|
||||
// credit: bill.totalLocal,
|
||||
// accountId: payableAccountId,
|
||||
// contactId: bill.vendorId,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// index: 1,
|
||||
// indexGroup: 5,
|
||||
// };
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the bill tax GL entry.
|
||||
// * @param {IBill} bill -
|
||||
// * @param {number} taxPayableAccountId -
|
||||
// * @param {IItemEntry} entry -
|
||||
// * @param {number} index -
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getBillTaxEntry = R.curry(
|
||||
// (
|
||||
// bill: IBill,
|
||||
// taxPayableAccountId: number,
|
||||
// entry: IItemEntry,
|
||||
// index: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonJournalMeta = this.getBillCommonEntry(bill);
|
||||
|
||||
// return {
|
||||
// ...commonJournalMeta,
|
||||
// debit: entry.taxAmount,
|
||||
// index,
|
||||
// indexGroup: 30,
|
||||
// accountId: taxPayableAccountId,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// taxRateId: entry.taxRateId,
|
||||
// taxRate: entry.taxRate,
|
||||
// };
|
||||
// }
|
||||
// );
|
||||
|
||||
// /**
|
||||
// * Retrieves the bill tax GL entries.
|
||||
// * @param {IBill} bill
|
||||
// * @param {number} taxPayableAccountId
|
||||
// * @returns {ILedgerEntry[]}
|
||||
// */
|
||||
// private getBillTaxEntries = (bill: IBill, taxPayableAccountId: number) => {
|
||||
// // Retrieves the non-zero tax entries.
|
||||
// const nonZeroTaxEntries = this.itemsEntriesService.getNonZeroEntries(
|
||||
// bill.entries
|
||||
// );
|
||||
// const transformTaxEntry = this.getBillTaxEntry(bill, taxPayableAccountId);
|
||||
|
||||
// return nonZeroTaxEntries.map(transformTaxEntry);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the given bill GL entries.
|
||||
// * @param {IBill} bill
|
||||
// * @param {number} payableAccountId
|
||||
// * @returns {ILedgerEntry[]}
|
||||
// */
|
||||
// private getBillGLEntries = (
|
||||
// bill: IBill,
|
||||
// payableAccountId: number,
|
||||
// taxPayableAccountId: number
|
||||
// ): ILedgerEntry[] => {
|
||||
// const payableEntry = this.getBillPayableEntry(payableAccountId, bill);
|
||||
|
||||
// const itemEntryTransformer = this.getBillItemEntry(bill);
|
||||
// const landedCostTransformer = this.getBillLandedCostEntry(bill);
|
||||
|
||||
// const itemsEntries = bill.entries.map(itemEntryTransformer);
|
||||
// const landedCostEntries = bill.locatedLandedCosts.map(
|
||||
// landedCostTransformer
|
||||
// );
|
||||
// const taxEntries = this.getBillTaxEntries(bill, taxPayableAccountId);
|
||||
|
||||
// // Allocate cost entries journal entries.
|
||||
// return [payableEntry, ...itemsEntries, ...landedCostEntries, ...taxEntries];
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Retrieves the given bill ledger.
|
||||
// * @param {IBill} bill
|
||||
// * @param {number} payableAccountId
|
||||
// * @returns {Ledger}
|
||||
// */
|
||||
// private getBillLedger = (
|
||||
// bill: IBill,
|
||||
// payableAccountId: number,
|
||||
// taxPayableAccountId: number
|
||||
// ) => {
|
||||
// const entries = this.getBillGLEntries(
|
||||
// bill,
|
||||
// payableAccountId,
|
||||
// taxPayableAccountId
|
||||
// );
|
||||
|
||||
// return new Ledger(entries);
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,75 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import events from '@/subscribers/events';
|
||||
// import {
|
||||
// IBillCreatedPayload,
|
||||
// IBillEditedPayload,
|
||||
// IBIllEventDeletedPayload,
|
||||
// IBillOpenedPayload,
|
||||
// } from '@/interfaces';
|
||||
// import { BillGLEntries } from './BillGLEntries';
|
||||
|
||||
// @Service()
|
||||
// export class BillGLEntriesSubscriber {
|
||||
// @Inject()
|
||||
// private billGLEntries: BillGLEntries;
|
||||
|
||||
// /**
|
||||
// * Attaches events with handles.
|
||||
// */
|
||||
// public attach(bus) {
|
||||
// bus.subscribe(
|
||||
// events.bill.onCreated,
|
||||
// this.handlerWriteJournalEntriesOnCreate
|
||||
// );
|
||||
// bus.subscribe(
|
||||
// events.bill.onOpened,
|
||||
// this.handlerWriteJournalEntriesOnCreate
|
||||
// );
|
||||
// bus.subscribe(
|
||||
// events.bill.onEdited,
|
||||
// this.handleOverwriteJournalEntriesOnEdit
|
||||
// );
|
||||
// bus.subscribe(events.bill.onDeleted, this.handlerDeleteJournalEntries);
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Handles writing journal entries once bill created.
|
||||
// * @param {IBillCreatedPayload} payload -
|
||||
// */
|
||||
// private handlerWriteJournalEntriesOnCreate = async ({
|
||||
// tenantId,
|
||||
// bill,
|
||||
// trx,
|
||||
// }: IBillCreatedPayload | IBillOpenedPayload) => {
|
||||
// if (!bill.openedAt) return null;
|
||||
|
||||
// await this.billGLEntries.writeBillGLEntries(tenantId, bill.id, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Handles the overwriting journal entries once bill edited.
|
||||
// * @param {IBillEditedPayload} payload -
|
||||
// */
|
||||
// private handleOverwriteJournalEntriesOnEdit = async ({
|
||||
// tenantId,
|
||||
// billId,
|
||||
// bill,
|
||||
// trx,
|
||||
// }: IBillEditedPayload) => {
|
||||
// if (!bill.openedAt) return null;
|
||||
|
||||
// await this.billGLEntries.rewriteBillGLEntries(tenantId, billId, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Handles revert journal entries on bill deleted.
|
||||
// * @param {IBIllEventDeletedPayload} payload -
|
||||
// */
|
||||
// private handlerDeleteJournalEntries = async ({
|
||||
// tenantId,
|
||||
// billId,
|
||||
// trx,
|
||||
// }: IBIllEventDeletedPayload) => {
|
||||
// await this.billGLEntries.revertBillGLEntries(tenantId, billId, trx);
|
||||
// };
|
||||
// }
|
||||
@@ -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
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,76 @@
|
||||
// import { Knex } from 'knex';
|
||||
// import async from 'async';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { BillPaymentGLEntries } from '../BillPayments/BillPaymentGLEntries';
|
||||
|
||||
// @Service()
|
||||
// export class BillPaymentsGLEntriesRewrite {
|
||||
// @Inject()
|
||||
// public tenancy: HasTenancyService;
|
||||
|
||||
// @Inject()
|
||||
// public paymentGLEntries: BillPaymentGLEntries;
|
||||
|
||||
// /**
|
||||
// * Rewrites payments GL entries that associated to the given bill.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} billId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public rewriteBillPaymentsGLEntries = async (
|
||||
// tenantId: number,
|
||||
// billId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// const { BillPaymentEntry } = this.tenancy.models(tenantId);
|
||||
|
||||
// const billPaymentEntries = await BillPaymentEntry.query().where(
|
||||
// 'billId',
|
||||
// billId
|
||||
// );
|
||||
// const paymentsIds = billPaymentEntries.map((e) => e.billPaymentId);
|
||||
|
||||
// await this.rewritePaymentsGLEntriesQueue(tenantId, paymentsIds, trx);
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Rewrites the payments GL entries under async queue.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number[]} paymentsIds
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public rewritePaymentsGLEntriesQueue = async (
|
||||
// tenantId: number,
|
||||
// paymentsIds: number[],
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// // Initiate a new queue for accounts balance mutation.
|
||||
// const rewritePaymentGL = async.queue(this.rewritePaymentsGLEntriesTask, 10);
|
||||
|
||||
// paymentsIds.forEach((paymentId: number) => {
|
||||
// rewritePaymentGL.push({ paymentId, trx, tenantId });
|
||||
// });
|
||||
// //
|
||||
// if (paymentsIds.length > 0) await rewritePaymentGL.drain();
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Rewrites the payments GL entries task.
|
||||
// * @param {number} tenantId -
|
||||
// * @param {number} paymentId -
|
||||
// * @param {Knex.Transaction} trx -
|
||||
// * @returns {Promise<void>}
|
||||
// */
|
||||
// public rewritePaymentsGLEntriesTask = async ({
|
||||
// tenantId,
|
||||
// paymentId,
|
||||
// trx,
|
||||
// }) => {
|
||||
// await this.paymentGLEntries.rewritePaymentGLEntries(
|
||||
// tenantId,
|
||||
// paymentId,
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,36 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import events from '@/subscribers/events';
|
||||
// import { IBillEditedPayload } from '@/interfaces';
|
||||
// import { BillPaymentsGLEntriesRewrite } from './BillPaymentsGLEntriesRewrite';
|
||||
|
||||
// @Service()
|
||||
// export class BillPaymentsGLEntriesRewriteSubscriber {
|
||||
// @Inject()
|
||||
// private billPaymentGLEntriesRewrite: BillPaymentsGLEntriesRewrite;
|
||||
|
||||
// /**
|
||||
// * Attaches events with handles.
|
||||
// */
|
||||
// public attach(bus) {
|
||||
// bus.subscribe(
|
||||
// events.bill.onEdited,
|
||||
// this.handlerRewritePaymentsGLOnBillEdited
|
||||
// );
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Handles writing journal entries once bill created.
|
||||
// * @param {IBillCreatedPayload} payload -
|
||||
// */
|
||||
// private handlerRewritePaymentsGLOnBillEdited = async ({
|
||||
// tenantId,
|
||||
// billId,
|
||||
// trx,
|
||||
// }: IBillEditedPayload) => {
|
||||
// await this.billPaymentGLEntriesRewrite.rewriteBillPaymentsGLEntries(
|
||||
// tenantId,
|
||||
// billId,
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
// }
|
||||
@@ -0,0 +1,37 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { IBillsFilter } from '@/interfaces';
|
||||
// import { Exportable } from '@/services/Export/Exportable';
|
||||
// import { BillsApplication } from '../Bills.application';
|
||||
// import { EXPORT_SIZE_LIMIT } from '@/services/Export/constants';
|
||||
// import Objection from 'objection';
|
||||
|
||||
// @Service()
|
||||
// export class BillsExportable extends Exportable {
|
||||
// @Inject()
|
||||
// private billsApplication: BillsApplication;
|
||||
|
||||
// /**
|
||||
// * Retrieves the accounts data to exportable sheet.
|
||||
// * @param {number} tenantId
|
||||
// * @returns
|
||||
// */
|
||||
// public exportable(tenantId: number, query: IBillsFilter) {
|
||||
// const filterQuery = (query) => {
|
||||
// query.withGraphFetched('branch');
|
||||
// query.withGraphFetched('warehouse');
|
||||
// };
|
||||
// const parsedQuery = {
|
||||
// sortOrder: 'desc',
|
||||
// columnSortBy: 'created_at',
|
||||
// ...query,
|
||||
// page: 1,
|
||||
// pageSize: EXPORT_SIZE_LIMIT,
|
||||
// filterQuery,
|
||||
// } as IBillsFilter;
|
||||
|
||||
// return this.billsApplication
|
||||
// .getBills(tenantId, parsedQuery)
|
||||
// .then((output) => output.bills);
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,46 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { Importable } from '@/services/Import/Importable';
|
||||
// import { CreateBill } from './CreateBill.service';
|
||||
// import { IBillDTO } from '@/interfaces';
|
||||
// import { BillsSampleData } from '../Bills.constants';
|
||||
|
||||
// @Service()
|
||||
// export class BillsImportable extends Importable {
|
||||
// @Inject()
|
||||
// private createBillService: CreateBill;
|
||||
|
||||
// /**
|
||||
// * Importing to account service.
|
||||
// * @param {number} tenantId
|
||||
// * @param {IAccountCreateDTO} createAccountDTO
|
||||
// * @returns
|
||||
// */
|
||||
// public importable(
|
||||
// tenantId: number,
|
||||
// createAccountDTO: IBillDTO,
|
||||
// trx?: Knex.Transaction
|
||||
// ) {
|
||||
// return this.createBillService.createBill(
|
||||
// tenantId,
|
||||
// createAccountDTO,
|
||||
// {},
|
||||
// trx
|
||||
// );
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Concurrrency controlling of the importing process.
|
||||
// * @returns {number}
|
||||
// */
|
||||
// public get concurrency() {
|
||||
// return 1;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Retrieves the sample data that used to download accounts sample sheet.
|
||||
// */
|
||||
// public sampleData(): any[] {
|
||||
// return BillsSampleData;
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { ERRORS } from '../Bills.constants';
|
||||
import { Bill } from '../models/Bill';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
import { IItemEntryDTO } from '@/modules/TransactionItemEntry/ItemEntry.types';
|
||||
import { Item } from '@/modules/Items/models/Item';
|
||||
import { BillPaymentEntry } from '@/modules/BillPayments/models/BillPaymentEntry';
|
||||
import { BillLandedCost } from '@/modules/BillLandedCosts/models/BillLandedCost';
|
||||
|
||||
@Injectable()
|
||||
export class BillsValidators {
|
||||
constructor(
|
||||
@Inject(Bill.name) private billModel: typeof Bill,
|
||||
|
||||
@Inject(BillPaymentEntry.name)
|
||||
private billPaymentEntryModel: typeof BillPaymentEntry,
|
||||
|
||||
@Inject(BillLandedCost.name)
|
||||
private billLandedCostModel: typeof BillLandedCost,
|
||||
|
||||
@Inject(VendorCreditAppliedBill.name)
|
||||
private vendorCreditAppliedBillModel: typeof VendorCreditAppliedBill,
|
||||
|
||||
@Inject(Item.name) private itemModel: typeof Item,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 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 amount is bigger than paid amount.
|
||||
* @param {number} billAmount
|
||||
* @param {number} paidAmount
|
||||
*/
|
||||
public validateBillAmountBiggerPaidAmount(
|
||||
billAmount: number,
|
||||
paidAmount: number,
|
||||
) {
|
||||
if (billAmount < paidAmount) {
|
||||
throw new ServiceError(ERRORS.BILL_AMOUNT_SMALLER_THAN_PAID_AMOUNT);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill number existance.
|
||||
*/
|
||||
public async validateBillNumberExists(
|
||||
billNumber: string,
|
||||
notBillId?: number,
|
||||
) {
|
||||
const foundBills = await this.billModel
|
||||
.query()
|
||||
.where('bill_number', billNumber)
|
||||
.onBuild((builder) => {
|
||||
if (notBillId) {
|
||||
builder.whereNot('id', notBillId);
|
||||
}
|
||||
});
|
||||
|
||||
if (foundBills.length > 0) {
|
||||
throw new ServiceError(
|
||||
ERRORS.BILL_NUMBER_EXISTS,
|
||||
'The bill number is not unique.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the bill has no payment entries.
|
||||
* @param {number} billId - Bill id.
|
||||
*/
|
||||
public async validateBillHasNoEntries(billId: number) {
|
||||
// Retrieve the bill associate payment made entries.
|
||||
const entries = await this.billPaymentEntryModel
|
||||
.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} billId
|
||||
*/
|
||||
public async validateBillHasNoLandedCost(billId: number) {
|
||||
const billLandedCosts = await this.billLandedCostModel
|
||||
.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 {IItemEntryDTO[]} newEntriesDTO -
|
||||
*/
|
||||
public async validateCostEntriesShouldBeInventoryItems(
|
||||
newEntriesDTO: IItemEntryDTO[],
|
||||
) {
|
||||
const entriesItemsIds = newEntriesDTO.map((e) => e.itemId);
|
||||
const entriesItems = await this.itemModel
|
||||
.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} billId
|
||||
*/
|
||||
public validateBillHasNoAppliedToCredit = async (billId: number) => {
|
||||
const appliedTransactions = await this.vendorCreditAppliedBillModel
|
||||
.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} vendorId - Vendor id.
|
||||
*/
|
||||
public async validateVendorHasNoBills(vendorId: number) {
|
||||
const bills = await this.billModel.query().where('vendor_id', vendorId);
|
||||
|
||||
if (bills.length > 0) {
|
||||
throw new ServiceError(ERRORS.VENDOR_HAS_BILLS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import {
|
||||
IBillDTO,
|
||||
IBillCreatedPayload,
|
||||
IBillCreatingPayload,
|
||||
} from '../Bills.types';
|
||||
import { BillDTOTransformer } from './BillDTOTransformer.service';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { BillsValidators } from './BillsValidators.service';
|
||||
import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service';
|
||||
import { Bill } from '../models/Bill';
|
||||
import { Vendor } from '@/modules/Vendors/models/Vendor';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class CreateBill {
|
||||
constructor(
|
||||
private uow: UnitOfWork,
|
||||
private eventPublisher: EventEmitter2,
|
||||
private validators: BillsValidators,
|
||||
private itemsEntriesService: ItemsEntriesService,
|
||||
private transformerDTO: BillDTOTransformer,
|
||||
|
||||
@Inject(Bill.name)
|
||||
private billModel: typeof Bill,
|
||||
|
||||
@Inject(Vendor.name)
|
||||
private contactModel: typeof Vendor,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 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 {IBillDTO} billDTO -
|
||||
* @return {Promise<IBill>}
|
||||
*/
|
||||
public async createBill(
|
||||
billDTO: IBillDTO,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<Bill> {
|
||||
// Retrieves the given bill vendor or throw not found error.
|
||||
const vendor = await this.contactModel
|
||||
.query()
|
||||
.modify('vendor')
|
||||
.findById(billDTO.vendorId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate the bill number uniqiness on the storage.
|
||||
await this.validators.validateBillNumberExists(billDTO.billNumber);
|
||||
|
||||
// Validate items IDs existance.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(billDTO.entries);
|
||||
|
||||
// Validate non-purchasable items.
|
||||
await this.itemsEntriesService.validateNonPurchasableEntriesItems(
|
||||
billDTO.entries,
|
||||
);
|
||||
// Validates the cost entries should be with inventory items.
|
||||
await this.validators.validateCostEntriesShouldBeInventoryItems(
|
||||
billDTO.entries,
|
||||
);
|
||||
// Transform the bill DTO to model object.
|
||||
const billObj = await this.transformerDTO.billDTOToModel(
|
||||
billDTO,
|
||||
vendor,
|
||||
);
|
||||
|
||||
// Write new bill transaction with associated transactions under UOW env.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onCreating, {
|
||||
trx,
|
||||
billDTO,
|
||||
} as IBillCreatingPayload);
|
||||
|
||||
// Inserts the bill graph object to the storage.
|
||||
const bill = await this.billModel.query(trx).upsertGraph(billObj);
|
||||
|
||||
// Triggers `onBillCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onCreated, {
|
||||
bill,
|
||||
billId: bill.id,
|
||||
billDTO,
|
||||
trx,
|
||||
} as IBillCreatedPayload);
|
||||
|
||||
return bill;
|
||||
}, trx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { events } from '@/common/events/events';
|
||||
import {
|
||||
IBIllEventDeletedPayload,
|
||||
IBillEventDeletingPayload,
|
||||
} from '../Bills.types';
|
||||
import { BillsValidators } from './BillsValidators.service';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { ItemEntry } from '@/modules/Items/models/ItemEntry';
|
||||
import { Bill } from '../models/Bill';
|
||||
|
||||
@Injectable()
|
||||
export class DeleteBill {
|
||||
constructor(
|
||||
private readonly validators: BillsValidators,
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
@Inject(Bill.name) private readonly billModel: typeof Bill,
|
||||
@Inject(ItemEntry.name) private readonly itemEntryModel: typeof ItemEntry,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Deletes the bill with associated entries.
|
||||
* @param {number} billId
|
||||
* @return {void}
|
||||
*/
|
||||
public async deleteBill(billId: number) {
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await this.billModel
|
||||
.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Validates the bill existence.
|
||||
this.validators.validateBillExistance(oldBill);
|
||||
|
||||
// Validate the given bill has no associated landed cost transactions.
|
||||
await this.validators.validateBillHasNoLandedCost(billId);
|
||||
|
||||
// Validate the purchase bill has no associated payments transactions.
|
||||
await this.validators.validateBillHasNoEntries(billId);
|
||||
|
||||
// Validate the given bill has no associated reconciled with vendor credits.
|
||||
await this.validators.validateBillHasNoAppliedToCredit(billId);
|
||||
|
||||
// Deletes bill transaction with associated transactions under
|
||||
// unit-of-work environment.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillDeleting` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onDeleting, {
|
||||
trx,
|
||||
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, {
|
||||
billId,
|
||||
oldBill,
|
||||
trx,
|
||||
} as IBIllEventDeletedPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
IBillEditDTO,
|
||||
IBillEditedPayload,
|
||||
IBillEditingPayload,
|
||||
} from '../Bills.types';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { BillsValidators } from './BillsValidators.service';
|
||||
import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { BillDTOTransformer } from './BillDTOTransformer.service';
|
||||
import { Bill } from '../models/Bill';
|
||||
import { events } from '@/common/events/events';
|
||||
import { Vendor } from '@/modules/Vendors/models/Vendor';
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class EditBillService {
|
||||
constructor(
|
||||
private validators: BillsValidators,
|
||||
private itemsEntriesService: ItemsEntriesService,
|
||||
private uow: UnitOfWork,
|
||||
private eventPublisher: EventEmitter2,
|
||||
private entriesService: ItemEntries,
|
||||
private transformerDTO: BillDTOTransformer,
|
||||
@Inject(Bill.name) private billModel: typeof Bill,
|
||||
@Inject(Vendor.name) private contactModel: typeof Vendor,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 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 {Integer} billId - The given bill id.
|
||||
* @param {IBillEditDTO} billDTO - The given new bill details.
|
||||
* @return {Promise<IBill>}
|
||||
*/
|
||||
public async editBill(
|
||||
billId: number,
|
||||
billDTO: IBillEditDTO,
|
||||
): Promise<Bill> {
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await this.billModel
|
||||
.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Validate bill existance.
|
||||
this.validators.validateBillExistance(oldBill);
|
||||
|
||||
// Retrieve vendor details or throw not found service error.
|
||||
const vendor = await this.contactModel
|
||||
.query()
|
||||
.findById(billDTO.vendorId)
|
||||
.modify('vendor')
|
||||
.throwIfNotFound();
|
||||
|
||||
// Validate bill number uniqiness on the storage.
|
||||
if (billDTO.billNumber) {
|
||||
await this.validators.validateBillNumberExists(
|
||||
billDTO.billNumber,
|
||||
billId
|
||||
);
|
||||
}
|
||||
// Validate the entries ids existance.
|
||||
await this.itemsEntriesService.validateEntriesIdsExistance(
|
||||
billId,
|
||||
'Bill',
|
||||
billDTO.entries
|
||||
);
|
||||
// Validate the items ids existance on the storage.
|
||||
await this.itemsEntriesService.validateItemsIdsExistance(
|
||||
billDTO.entries
|
||||
);
|
||||
// Accept the purchasable items only.
|
||||
await this.itemsEntriesService.validateNonPurchasableEntriesItems(
|
||||
billDTO.entries
|
||||
);
|
||||
|
||||
// Transforms the bill DTO to model object.
|
||||
const billObj = await this.transformerDTO.billDTOToModel(
|
||||
billDTO,
|
||||
vendor,
|
||||
oldBill
|
||||
);
|
||||
// Validate bill total amount should be bigger than paid amount.
|
||||
this.validators.validateBillAmountBiggerPaidAmount(
|
||||
billObj.amount,
|
||||
oldBill.paymentAmount
|
||||
);
|
||||
// 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(async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBillEditing` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onEditing, {
|
||||
oldBill,
|
||||
billDTO,
|
||||
trx,
|
||||
} as IBillEditingPayload);
|
||||
|
||||
// Update the bill transaction.
|
||||
const bill = await this.billModel.query(trx).upsertGraphAndFetch({
|
||||
id: billId,
|
||||
...billObj,
|
||||
});
|
||||
// Triggers event `onBillEdited`.
|
||||
await this.eventPublisher.emitAsync(events.bill.onEdited, {
|
||||
oldBill,
|
||||
bill,
|
||||
billDTO,
|
||||
trx,
|
||||
} as IBillEditedPayload);
|
||||
|
||||
return bill;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import moment from 'moment';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { ERRORS } from '../Bills.constants';
|
||||
import { BillsValidators } from './BillsValidators.service';
|
||||
import { IBillOpenedPayload, IBillOpeningPayload } from '../Bills.types';
|
||||
import { Bill } from '../models/Bill';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class OpenBillService {
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly validators: BillsValidators,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
|
||||
@Inject(Bill.name)
|
||||
private readonly billModel: typeof Bill,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Mark the bill as open.
|
||||
* @param {number} billId - Bill id.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async openBill(billId: number): Promise<void> {
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await this.billModel
|
||||
.query()
|
||||
.findById(billId)
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Validates the bill existence.
|
||||
this.validators.validateBillExistance(oldBill);
|
||||
|
||||
if (oldBill.isOpen) {
|
||||
throw new ServiceError(ERRORS.BILL_ALREADY_OPEN);
|
||||
}
|
||||
|
||||
return this.uow.withTransaction(async (trx) => {
|
||||
// Triggers `onBillCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onOpening, {
|
||||
oldBill,
|
||||
trx,
|
||||
} as IBillOpeningPayload);
|
||||
|
||||
// Save the bill opened at on the storage.
|
||||
const bill = await this.billModel
|
||||
.query(trx)
|
||||
.patchAndFetchById(billId, {
|
||||
openedAt: moment().toMySqlDateTime(),
|
||||
})
|
||||
.withGraphFetched('entries');
|
||||
|
||||
// Triggers `onBillCreating` event.
|
||||
await this.eventPublisher.emitAsync(events.bill.onOpened, {
|
||||
bill,
|
||||
oldBill,
|
||||
trx,
|
||||
} as IBillOpenedPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user