feat(nestjs): migrate to NestJS

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

View File

@@ -0,0 +1,100 @@
import { CreateBill } from './commands/CreateBill.service';
import { EditBillService } from './commands/EditBill.service';
import { GetBill } from './queries/GetBill';
import { DeleteBill } from './commands/DeleteBill.service';
import { IBillDTO, IBillEditDTO, IBillsFilter } from './Bills.types';
import { GetDueBills } from './queries/GetDueBills.service';
import { OpenBillService } from './commands/OpenBill.service';
import { Injectable } from '@nestjs/common';
import { GetBillsService } from './queries/GetBills.service';
import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
// import { GetBillPayments } from './queries/GetBillPayments';
// import { GetBills } from './queries/GetBills';
@Injectable()
export class BillsApplication {
constructor(
private createBillService: CreateBill,
private editBillService: EditBillService,
private getBillService: GetBill,
private deleteBillService: DeleteBill,
private getDueBillsService: GetDueBills,
private openBillService: OpenBillService,
private getBillsService: GetBillsService,
// private getBillPaymentsService: GetBillPayments,
) {}
/**
* Creates a new bill with associated GL entries.
* @param {IBillDTO} billDTO
* @returns
*/
public createBill(billDTO: CreateBillDto) {
return this.createBillService.createBill(billDTO);
}
/**
* Edits the given bill with associated GL entries.
* @param {number} billId
* @param {IBillEditDTO} billDTO
* @returns
*/
public editBill(billId: number, billDTO: EditBillDto) {
return this.editBillService.editBill(billId, billDTO);
}
/**
* Deletes the given bill with associated GL entries.
* @param {number} billId - Bill id.
* @returns {Promise<void>}
*/
public deleteBill(billId: number) {
return this.deleteBillService.deleteBill(billId);
}
/**
* Retrieve bills data table list.
* @param {IBillsFilter} billsFilter -
*/
public getBills(filterDTO: IBillsFilter) {
return this.getBillsService.getBills(filterDTO);
}
/**
* Retrieves the given bill details.
* @param {number} billId
* @returns
*/
public getBill(billId: number) {
return this.getBillService.getBill(billId);
}
/**
* Open the given bill.
* @param {number} tenantId
* @param {number} billId
* @returns {Promise<void>}
*/
public openBill(billId: number): Promise<void> {
return this.openBillService.openBill(billId);
}
/**
* Retrieves due bills of the given vendor.
* @param {number} tenantId
* @param {number} vendorId
* @returns
*/
public getDueBills(vendorId?: number) {
return this.getDueBillsService.getDueBills(vendorId);
}
/**
* Retrieve the specific bill associated payment transactions.
* @param {number} tenantId
* @param {number} billId
*/
// public getBillPayments(billId: number) {
// return this.getBillPaymentsService.getBillPayments(billId);
// }
}

View File

@@ -0,0 +1,123 @@
export const ERRORS = {
BILL_NOT_FOUND: 'BILL_NOT_FOUND',
BILL_VENDOR_NOT_FOUND: 'BILL_VENDOR_NOT_FOUND',
BILL_ITEMS_NOT_PURCHASABLE: 'BILL_ITEMS_NOT_PURCHASABLE',
BILL_NUMBER_EXISTS: 'BILL_NUMBER_EXISTS',
BILL_ITEMS_NOT_FOUND: 'BILL_ITEMS_NOT_FOUND',
BILL_ENTRIES_IDS_NOT_FOUND: 'BILL_ENTRIES_IDS_NOT_FOUND',
NOT_PURCHASE_ABLE_ITEMS: 'NOT_PURCHASE_ABLE_ITEMS',
BILL_ALREADY_OPEN: 'BILL_ALREADY_OPEN',
BILL_NO_IS_REQUIRED: 'BILL_NO_IS_REQUIRED',
BILL_HAS_ASSOCIATED_PAYMENT_ENTRIES: 'BILL_HAS_ASSOCIATED_PAYMENT_ENTRIES',
VENDOR_HAS_BILLS: 'VENDOR_HAS_BILLS',
BILL_HAS_ASSOCIATED_LANDED_COSTS: 'BILL_HAS_ASSOCIATED_LANDED_COSTS',
BILL_ENTRIES_ALLOCATED_COST_COULD_DELETED:
'BILL_ENTRIES_ALLOCATED_COST_COULD_DELETED',
LOCATED_COST_ENTRIES_SHOULD_BIGGE_THAN_NEW_ENTRIES:
'LOCATED_COST_ENTRIES_SHOULD_BIGGE_THAN_NEW_ENTRIES',
LANDED_COST_ENTRIES_SHOULD_BE_INVENTORY_ITEMS:
'LANDED_COST_ENTRIES_SHOULD_BE_INVENTORY_ITEMS',
BILL_HAS_APPLIED_TO_VENDOR_CREDIT: 'BILL_HAS_APPLIED_TO_VENDOR_CREDIT',
BILL_AMOUNT_SMALLER_THAN_PAID_AMOUNT: 'BILL_AMOUNT_SMALLER_THAN_PAID_AMOUNT',
};
export const DEFAULT_VIEW_COLUMNS = [];
export const DEFAULT_VIEWS = [
{
name: 'Draft',
slug: 'draft',
rolesLogicExpression: '1',
roles: [
{ index: 1, fieldKey: 'status', comparator: 'equals', value: 'draft' },
],
columns: DEFAULT_VIEW_COLUMNS,
},
{
name: 'Opened',
slug: 'opened',
rolesLogicExpression: '1',
roles: [
{ index: 1, fieldKey: 'status', comparator: 'equals', value: 'opened' },
],
columns: DEFAULT_VIEW_COLUMNS,
},
{
name: 'Unpaid',
slug: 'unpaid',
rolesLogicExpression: '1',
roles: [
{ index: 1, fieldKey: 'status', comparator: 'equals', value: 'unpaid' },
],
columns: DEFAULT_VIEW_COLUMNS,
},
{
name: 'Overdue',
slug: 'overdue',
rolesLogicExpression: '1',
roles: [
{ index: 1, fieldKey: 'status', comparator: 'equals', value: 'overdue' },
],
columns: DEFAULT_VIEW_COLUMNS,
},
{
name: 'Partially paid',
slug: 'partially-paid',
rolesLogicExpression: '1',
roles: [
{
index: 1,
fieldKey: 'status',
comparator: 'equals',
value: 'partially-paid',
},
],
columns: DEFAULT_VIEW_COLUMNS,
},
];
export const BillsSampleData = [
{
'Bill No.': 'B-101',
'Reference No.': 'REF0',
Date: '2024-01-01',
'Due Date': '2024-03-01',
Vendor: 'Gabriel Kovacek',
'Exchange Rate': 1,
Note: 'Vel in sit sint.',
Open: 'T',
Item: 'VonRueden, Ruecker and Hettinger',
Quantity: 100,
Rate: 100,
'Line Description': 'Id a vel quis vel aut.',
},
{
'Bill No.': 'B-102',
'Reference No.': 'REF0',
Date: '2024-01-01',
'Due Date': '2024-03-01',
Vendor: 'Gabriel Kovacek',
'Exchange Rate': 1,
Note: 'Quia ut dolorem qui sint velit.',
Open: 'T',
Item: 'Thompson - Reichert',
Quantity: 200,
Rate: 50,
'Line Description':
'Nesciunt in adipisci quia ab reiciendis nam sed saepe consequatur.',
},
{
'Bill No.': 'B-103',
'Reference No.': 'REF0',
Date: '2024-01-01',
'Due Date': '2024-03-01',
Vendor: 'Gabriel Kovacek',
'Exchange Rate': 1,
Note: 'Dolore aut voluptatem minus pariatur alias pariatur.',
Open: 'T',
Item: 'VonRueden, Ruecker and Hettinger',
Quantity: 100,
Rate: 100,
'Line Description': 'Quam eligendi provident.',
},
];

View File

@@ -0,0 +1,92 @@
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
import {
Controller,
Post,
Body,
Put,
Param,
Delete,
Get,
Query,
} from '@nestjs/common';
import { BillsApplication } from './Bills.application';
import { IBillsFilter } from './Bills.types';
import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
@Controller('bills')
@ApiTags('bills')
export class BillsController {
constructor(private billsApplication: BillsApplication) {}
@Post()
@ApiOperation({ summary: 'Create a new bill.' })
createBill(@Body() billDTO: CreateBillDto) {
return this.billsApplication.createBill(billDTO);
}
@Put(':id')
@ApiOperation({ summary: 'Edit the given bill.' })
@ApiParam({
name: 'id',
required: true,
type: Number,
description: 'The bill id',
})
editBill(@Param('id') billId: number, @Body() billDTO: EditBillDto) {
return this.billsApplication.editBill(billId, billDTO);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete the given bill.' })
@ApiParam({
name: 'id',
required: true,
type: Number,
description: 'The bill id',
})
deleteBill(@Param('id') billId: number) {
return this.billsApplication.deleteBill(billId);
}
@Get()
@ApiOperation({ summary: 'Retrieves the bills.' })
@ApiParam({
name: 'id',
required: true,
type: Number,
description: 'The bill id',
})
getBills(@Query() filterDTO: IBillsFilter) {
return this.billsApplication.getBills(filterDTO);
}
@Get(':id')
@ApiOperation({ summary: 'Retrieves the bill details.' })
@ApiParam({
name: 'id',
required: true,
type: Number,
description: 'The bill id',
})
getBill(@Param('id') billId: number) {
return this.billsApplication.getBill(billId);
}
@Post(':id/open')
@ApiOperation({ summary: 'Open the given bill.' })
@ApiParam({
name: 'id',
required: true,
type: Number,
description: 'The bill id',
})
openBill(@Param('id') billId: number) {
return this.billsApplication.openBill(billId);
}
@Get('due')
@ApiOperation({ summary: 'Retrieves the due bills.' })
getDueBills(@Body('vendorId') vendorId?: number) {
return this.billsApplication.getDueBills(vendorId);
}
}

View File

@@ -0,0 +1,63 @@
import { Module } from '@nestjs/common';
import { BillsApplication } from './Bills.application';
import { CreateBill } from './commands/CreateBill.service';
import { DeleteBill } from './commands/DeleteBill.service';
import { GetBill } from './queries/GetBill';
import { BillDTOTransformer } from './commands/BillDTOTransformer.service';
import { EditBillService } from './commands/EditBill.service';
import { GetDueBills } from './queries/GetDueBills.service';
import { OpenBillService } from './commands/OpenBill.service';
import { BillsValidators } from './commands/BillsValidators.service';
import { ItemsEntriesService } from '../Items/ItemsEntries.service';
import { BranchTransactionDTOTransformer } from '../Branches/integrations/BranchTransactionDTOTransform';
import { BranchesSettingsService } from '../Branches/BranchesSettings';
import { WarehouseTransactionDTOTransform } from '../Warehouses/Integrations/WarehouseTransactionDTOTransform';
import { WarehousesSettings } from '../Warehouses/WarehousesSettings';
import { ItemEntriesTaxTransactions } from '../TaxRates/ItemEntriesTaxTransactions.service';
import { TenancyContext } from '../Tenancy/TenancyContext.service';
import { BillsController } from './Bills.controller';
import { BillLandedCostsModule } from '../BillLandedCosts/BillLandedCosts.module';
import { BillGLEntriesSubscriber } from './subscribers/BillGLEntriesSubscriber';
import { BillGLEntries } from './commands/BillsGLEntries';
import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module';
import { BillWriteInventoryTransactionsSubscriber } from './subscribers/BillWriteInventoryTransactionsSubscriber';
import { BillInventoryTransactions } from './commands/BillInventoryTransactions';
import { GetBillsService } from './queries/GetBills.service';
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
import { InventoryCostModule } from '../InventoryCost/InventoryCost.module';
@Module({
imports: [
BillLandedCostsModule,
LedgerModule,
AccountsModule,
DynamicListModule,
InventoryCostModule,
],
providers: [
TenancyContext,
BillsApplication,
BranchTransactionDTOTransformer,
WarehouseTransactionDTOTransform,
WarehousesSettings,
ItemEntriesTaxTransactions,
BranchesSettingsService,
CreateBill,
EditBillService,
GetDueBills,
OpenBillService,
GetBill,
GetBillsService,
DeleteBill,
BillDTOTransformer,
BillsValidators,
BillGLEntries,
ItemsEntriesService,
BillGLEntriesSubscriber,
BillInventoryTransactions,
BillWriteInventoryTransactionsSubscriber,
],
controllers: [BillsController],
})
export class BillsModule {}

View File

@@ -0,0 +1,108 @@
import { Knex } from 'knex';
import { IItemEntryDTO } from '../TransactionItemEntry/ItemEntry.types';
import { AttachmentLinkDTO } from '../Attachments/Attachments.types';
import { Bill } from './models/Bill';
import { IDynamicListFilter } from '../DynamicListing/DynamicFilter/DynamicFilter.types';
import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
export interface IBillDTO {
vendorId: number;
billNumber: string;
billDate: Date;
dueDate: Date;
referenceNo: string;
status: string;
note: string;
amount: number;
paymentAmount: number;
exchangeRate?: number;
open: boolean;
entries: IItemEntryDTO[];
branchId?: number;
warehouseId?: number;
projectId?: number;
isInclusiveTax?: boolean;
attachments?: AttachmentLinkDTO[];
}
export interface IBillEditDTO {
vendorId: number;
billNumber: string;
billDate: Date;
dueDate: Date;
referenceNo: string;
status: string;
note: string;
amount: number;
paymentAmount: number;
open: boolean;
entries: IItemEntryDTO[];
branchId?: number;
warehouseId?: number;
projectId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IBillsFilter extends IDynamicListFilter {
stringifiedFilterRoles?: string;
page: number;
pageSize: number;
filterQuery?: (q: any) => void;
}
export interface IBillCreatedPayload {
bill: Bill;
billDTO: CreateBillDto;
trx?: Knex.Transaction;
}
export interface IBillCreatingPayload {
billDTO: CreateBillDto;
trx: Knex.Transaction;
}
export interface IBillEditingPayload {
oldBill: Bill;
billDTO: EditBillDto;
trx: Knex.Transaction;
}
export interface IBillEditedPayload {
oldBill: Bill;
bill: Bill;
billDTO: EditBillDto;
trx?: Knex.Transaction;
}
export interface IBIllEventDeletedPayload {
// tenantId: number;
billId: number;
oldBill: Bill;
trx: Knex.Transaction;
}
export interface IBillEventDeletingPayload {
// tenantId: number;
oldBill: Bill;
trx: Knex.Transaction;
}
export enum BillAction {
Create = 'Create',
Edit = 'Edit',
Delete = 'Delete',
View = 'View',
NotifyBySms = 'NotifyBySms',
}
export interface IBillOpeningPayload {
trx: Knex.Transaction;
// tenantId: number;
oldBill: Bill;
}
export interface IBillOpenedPayload {
bill: Bill;
oldBill: Bill;
trx?: Knex.Transaction;
// tenantId: number;
}

View File

@@ -0,0 +1,152 @@
import { Inject, Injectable } from '@nestjs/common';
import { omit, sumBy } from 'lodash';
import * as moment from 'moment';
import * as R from 'ramda';
import * as composeAsync from 'async/compose';
import { formatDateFields } from '@/utils/format-date-fields';
import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations/BranchTransactionDTOTransform';
import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform';
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
import { Item } from '@/modules/Items/models/Item';
import { Vendor } from '@/modules/Vendors/models/Vendor';
import { ItemEntriesTaxTransactions } from '@/modules/TaxRates/ItemEntriesTaxTransactions.service';
import { IBillDTO } from '../Bills.types';
import { Bill } from '../models/Bill';
import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index';
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { CreateBillDto } from '../dtos/Bill.dto';
@Injectable()
export class BillDTOTransformer {
constructor(
private branchDTOTransform: BranchTransactionDTOTransformer,
private warehouseDTOTransform: WarehouseTransactionDTOTransform,
private taxDTOTransformer: ItemEntriesTaxTransactions,
private tenancyContext: TenancyContext,
@Inject(ItemEntry.name)
private itemEntryModel: TenantModelProxy<typeof ItemEntry>,
@Inject(Item.name) private itemModel: TenantModelProxy<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 {CreateBillDto} billDTO
* @returns {number}
*/
private getBillLandedCostAmount(billDTO: CreateBillDto): number {
const costEntries = billDTO.entries.filter((entry) => entry.landedCost);
// return this.getBillEntriesTotal(costEntries);
return 0;
}
/**
* Converts create bill DTO to model.
* @param {IBillDTO} billDTO
* @param {IBill} oldBill
* @returns {IBill}
*/
public async billDTOToModel(
billDTO: CreateBillDto,
vendor: Vendor,
oldBill?: Bill,
): Promise<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,
};
const asyncDto = await composeAsync(
this.branchDTOTransform.transformDTO<Bill>,
this.warehouseDTOTransform.transformDTO<Bill>,
)(initialDTO);
return R.compose(
// Associates tax amount withheld to the model.
this.taxDTOTransformer.assocTaxAmountWithheldFromEntries,
)(asyncDto) as Bill;
}
/**
* 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,
}),
};
});
};
}
}

View File

@@ -0,0 +1,75 @@
// @ts-nocheck
import { Knex } from 'knex';
import { Bill } from '../models/Bill';
import { Inject, Injectable } from '@nestjs/common';
import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service';
import { InventoryTransactionsService } from '@/modules/InventoryCost/commands/InventoryTransactions.service';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class BillInventoryTransactions {
constructor(
private readonly itemsEntriesService: ItemsEntriesService,
private readonly inventoryTransactionsService: InventoryTransactionsService,
@Inject(Bill.name)
private readonly bill: TenantModelProxy<typeof Bill>,
) {}
/**
* Records the inventory transactions from the given bill input.
* @param {number} billId - Bill id.
* @return {Promise<void>}
*/
public async recordInventoryTransactions(
billId: number,
override?: boolean,
trx?: Knex.Transaction,
): Promise<void> {
// Retireve bill with assocaited entries and allocated cost entries.
const bill = await this.bill()
.query(trx)
.findById(billId)
.withGraphFetched('entries.allocatedCostEntries');
// Loads the inventory items entries of the given sale invoice.
const inventoryEntries =
await this.itemsEntriesService.filterInventoryEntries(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.inventoryTransactionsService.recordInventoryTransactionsFromItemsEntries(
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(
billId: number,
trx?: Knex.Transaction,
) {
// Deletes the inventory transactions by the given reference id and type.
await this.inventoryTransactionsService.deleteInventoryTransactions(
billId,
'Bill',
trx,
);
}
}

View File

@@ -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
// );
// };
// }

View File

@@ -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
// );
// };
// }

View File

@@ -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);
// }
// }

View File

@@ -0,0 +1,242 @@
import { sumBy } from 'lodash';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
import { Bill } from '../models/Bill';
import { AccountNormal } from '@/modules/Accounts/Accounts.types';
import { Ledger } from '@/modules/Ledger/Ledger';
import { BillLandedCost } from '@/modules/BillLandedCosts/models/BillLandedCost';
export class BillGL {
private bill: Bill;
private payableAccountId: number;
private taxPayableAccountId: number;
private purchaseDiscountAccountId: number;
private otherExpensesAccountId: number;
constructor(bill: Bill) {
this.bill = bill;
}
setPayableAccountId(payableAccountId: number) {
this.payableAccountId = payableAccountId;
return this;
}
setTaxPayableAccountId(taxPayableAccountId: number) {
this.taxPayableAccountId = taxPayableAccountId;
return this;
}
setPurchaseDiscountAccountId(purchaseDiscountAccountId: number) {
this.purchaseDiscountAccountId = purchaseDiscountAccountId;
return this;
}
setOtherExpensesAccountId(otherExpensesAccountId: number) {
this.otherExpensesAccountId = otherExpensesAccountId;
return this;
}
/**
* Retrieves the bill common entry.
* @returns {ILedgerEntry}
*/
private get billCommonEntry() {
return {
debit: 0,
credit: 0,
currencyCode: this.bill.currencyCode,
exchangeRate: this.bill.exchangeRate || 1,
transactionId: this.bill.id,
transactionType: 'Bill',
date: moment(this.bill.billDate).format('YYYY-MM-DD'),
userId: this.bill.userId,
referenceNumber: this.bill.referenceNo,
transactionNumber: this.bill.billNumber,
branchId: this.bill.branchId,
projectId: this.bill.projectId,
createdAt: this.bill.createdAt,
};
}
/**
* Retrieves the bill item inventory/cost entry.
* @param {ItemEntry} entry -
* @param {number} index -
*/
private getBillItemEntry(entry: ItemEntry, index: number): ILedgerEntry {
const commonJournalMeta = this.billCommonEntry;
const totalLocal = this.bill.exchangeRate * entry.totalExcludingTax;
const landedCostAmount = sumBy(entry.allocatedCostEntries, 'cost');
return {
...commonJournalMeta,
debit: totalLocal + landedCostAmount,
accountId:
['inventory'].indexOf(entry.item.type) !== -1
? entry.item.inventoryAccountId
: entry.costAccountId,
index: index + 1,
indexGroup: 10,
itemId: entry.itemId,
accountNormal: AccountNormal.DEBIT,
};
}
/**
* Retrieves the bill landed cost entry.
* @param {BillLandedCost} landedCost - Landed cost
* @param {number} index - Index
*/
private getBillLandedCostEntry(
landedCost: BillLandedCost,
index: number,
): ILedgerEntry {
const commonJournalMeta = this.billCommonEntry;
return {
...commonJournalMeta,
credit: landedCost.amount,
accountId: landedCost.costAccountId,
accountNormal: AccountNormal.DEBIT,
index: 1,
indexGroup: 20,
};
}
/**
* Retrieves the bill payable entry.
* @returns {ILedgerEntry}
*/
private get billPayableEntry(): ILedgerEntry {
const commonJournalMeta = this.billCommonEntry;
return {
...commonJournalMeta,
credit: this.bill.totalLocal,
accountId: this.payableAccountId,
contactId: this.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(entry: ItemEntry, index: number): ILedgerEntry {
const commonJournalMeta = this.billCommonEntry;
return {
...commonJournalMeta,
debit: entry.taxAmount,
index,
indexGroup: 30,
accountId: this.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 = () => {
// // Retrieves the non-zero tax entries.
// const nonZeroTaxEntries = this.itemsEntriesService.getNonZeroEntries(
// this.bill.entries,
// );
// const transformTaxEntry = this.getBillTaxEntry(
// this.bill,
// this.taxPayableAccountId,
// );
// return nonZeroTaxEntries.map(transformTaxEntry);
// };
/**
* Retrieves the purchase discount GL entry.
* @returns {ILedgerEntry}
*/
private get purchaseDiscountEntry(): ILedgerEntry {
const commonEntry = this.billCommonEntry;
return {
...commonEntry,
credit: this.bill.discountAmountLocal,
accountId: this.purchaseDiscountAccountId,
accountNormal: AccountNormal.DEBIT,
index: 1,
indexGroup: 40,
};
}
/**
* Retrieves the purchase other charges GL entry.
* @returns {ILedgerEntry}
*/
private get adjustmentEntry(): ILedgerEntry {
const commonEntry = this.billCommonEntry;
const adjustmentAmount = Math.abs(this.bill.adjustmentLocal);
return {
...commonEntry,
debit: this.bill.adjustmentLocal > 0 ? adjustmentAmount : 0,
credit: this.bill.adjustmentLocal < 0 ? adjustmentAmount : 0,
accountId: this.otherExpensesAccountId,
accountNormal: AccountNormal.DEBIT,
index: 1,
indexGroup: 40,
};
}
/**
* Retrieves the given bill GL entries.
* @returns {ILedgerEntry[]}
*/
private getBillGLEntries = (): ILedgerEntry[] => {
const payableEntry = this.billPayableEntry;
const itemsEntries = this.bill.entries.map((entry, index) =>
this.getBillItemEntry(entry, index),
);
const landedCostEntries = this.bill.locatedLandedCosts.map(
(landedCost, index) => this.getBillLandedCostEntry(landedCost, index),
);
// Allocate cost entries journal entries.
return [
payableEntry,
...itemsEntries,
...landedCostEntries,
this.purchaseDiscountEntry,
this.adjustmentEntry,
];
};
/**
* Retrieves the given bill ledger.
* @returns {Ledger}
*/
public getBillLedger = () => {
const entries = this.getBillGLEntries();
return new Ledger(entries);
};
}

View File

@@ -0,0 +1,100 @@
import { Knex } from 'knex';
import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service';
import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository';
import { Bill } from '../models/Bill';
import { Inject, Injectable } from '@nestjs/common';
import { BillGL } from './BillsGL';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class BillGLEntries {
/**
* @param {LedgerStorageService} ledgerStorage - Ledger storage service.
* @param {AccountRepository} accountRepository - Account repository.
* @param {typeof Bill} billModel - Bill model.
*/
constructor(
private readonly ledgerStorage: LedgerStorageService,
private readonly accountRepository: AccountRepository,
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<typeof Bill>,
) {}
/**
* Creates bill GL entries.
* @param {number} billId - Bill id.
* @param {Knex.Transaction} trx - Knex transaction.
*/
public writeBillGLEntries = async (
billId: number,
trx?: Knex.Transaction,
) => {
// Retrieves bill with associated entries and landed costs.
const bill = await this.billModel()
.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 this.accountRepository.findOrCreateAccountsPayable(
bill.currencyCode,
{},
trx,
);
// Find or create tax payable account.
const taxPayableAccount =
await this.accountRepository.findOrCreateTaxPayable({}, trx);
// Find or create other expenses account.
const otherExpensesAccount =
await this.accountRepository.findOrCreateOtherExpensesAccount({}, trx);
// Find or create purchase discount account.
const purchaseDiscountAccount =
await this.accountRepository.findOrCreatePurchaseDiscountAccount({}, trx);
// Retrieves the bill ledger.
const billLedger = new BillGL(bill)
.setPayableAccountId(APAccount.id)
.setTaxPayableAccountId(taxPayableAccount.id)
.setPurchaseDiscountAccountId(purchaseDiscountAccount.id)
.setOtherExpensesAccountId(otherExpensesAccount.id)
.getBillLedger();
// Commit the GL enties on the storage.
await this.ledgerStorage.commit(billLedger, trx);
};
/**
* Reverts the given bill GL entries.
* @param {number} tenantId
* @param {number} billId
* @param {Knex.Transaction} trx
*/
public revertBillGLEntries = async (
billId: number,
trx?: Knex.Transaction,
) => {
await this.ledgerStorage.deleteByReference(billId, 'Bill', trx);
};
/**
* Rewrites the given bill GL entries.
* @param {number} tenantId
* @param {number} billId
* @param {Knex.Transaction} trx
*/
public rewriteBillGLEntries = async (
billId: number,
trx?: Knex.Transaction,
) => {
// Reverts the bill GL entries.
await this.revertBillGLEntries(billId, trx);
// Writes the bill GL entries.
await this.writeBillGLEntries(billId, trx);
};
}

View File

@@ -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;
// }
// }

View File

@@ -0,0 +1,175 @@
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';
import { VendorCreditAppliedBill } from '@/modules/VendorCreditsApplyBills/models/VendorCreditAppliedBill';
import { transformToMap } from '@/utils/transform-to-key';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { ItemEntryDto } from '@/modules/TransactionItemEntry/dto/ItemEntry.dto';
import { BillEntryDto } from '../dtos/Bill.dto';
@Injectable()
export class BillsValidators {
constructor(
@Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>,
@Inject(BillPaymentEntry.name)
private billPaymentEntryModel: TenantModelProxy<typeof BillPaymentEntry>,
@Inject(BillLandedCost.name)
private billLandedCostModel: TenantModelProxy<typeof BillLandedCost>,
@Inject(VendorCreditAppliedBill.name)
private vendorCreditAppliedBillModel: TenantModelProxy<
typeof VendorCreditAppliedBill
>,
@Inject(Item.name) private itemModel: TenantModelProxy<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: BillEntryDto[],
) {
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);
}
}
}

View File

@@ -0,0 +1,99 @@
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';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { CreateBillDto } from '../dtos/Bill.dto';
@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: TenantModelProxy<typeof Bill>,
@Inject(Vendor.name)
private vendorModel: TenantModelProxy<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: CreateBillDto,
trx?: Knex.Transaction,
): Promise<Bill> {
// Retrieves the given bill vendor or throw not found error.
const vendor = await this.vendorModel()
.query()
.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)
.upsertGraphAndFetch(billObj);
// Triggers `onBillCreated` event.
await this.eventPublisher.emitAsync(events.bill.onCreated, {
bill,
billDTO,
trx,
} as IBillCreatedPayload);
return bill;
}, trx);
}
}

View File

@@ -0,0 +1,80 @@
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/TransactionItemEntry/models/ItemEntry';
import { Bill } from '../models/Bill';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class DeleteBill {
constructor(
private readonly validators: BillsValidators,
private readonly uow: UnitOfWork,
private readonly eventPublisher: EventEmitter2,
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<typeof Bill>,
@Inject(ItemEntry.name)
private readonly itemEntryModel: TenantModelProxy<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 this.itemEntryModel()
.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);
});
}
}

View File

@@ -0,0 +1,135 @@
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';
import { Knex } from 'knex';
import { TransactionLandedCostEntriesService } from '@/modules/BillLandedCosts/TransactionLandedCostEntries.service';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { EditBillDto } from '../dtos/Bill.dto';
@Injectable()
export class EditBillService {
constructor(
private validators: BillsValidators,
private itemsEntriesService: ItemsEntriesService,
private uow: UnitOfWork,
private eventPublisher: EventEmitter2,
private transactionLandedCostEntries: TransactionLandedCostEntriesService,
private transformerDTO: BillDTOTransformer,
@Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>,
@Inject(Vendor.name) private contactModel: TenantModelProxy<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: EditBillDto): 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.transactionLandedCostEntries.validateLandedCostEntriesNotDeleted(
oldBill.entries,
billObj.entries,
);
// Validate new landed cost entries should be bigger than new entries.
await this.transactionLandedCostEntries.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;
});
}
}

View File

@@ -0,0 +1,66 @@
import * as 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';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class OpenBillService {
constructor(
private readonly uow: UnitOfWork,
private readonly validators: BillsValidators,
private readonly eventPublisher: EventEmitter2,
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<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);
});
}
}

View File

@@ -0,0 +1,107 @@
import { ItemEntryDto } from '@/modules/TransactionItemEntry/dto/ItemEntry.dto';
import { Type } from 'class-transformer';
import {
ArrayMinSize,
IsArray,
IsBoolean,
IsDate,
IsEnum,
IsInt,
IsNumber,
IsOptional,
IsPositive,
IsString,
Min,
MinLength,
ValidateNested,
} from 'class-validator';
enum DiscountType {
Percentage = 'percentage',
Amount = 'amount',
}
export class BillEntryDto extends ItemEntryDto {
@IsOptional()
@IsBoolean()
landedCost?: boolean;
}
class AttachmentDto {
@IsString()
key: string;
}
export class CommandBillDto {
@IsString()
billNumber: string;
@IsOptional()
@IsString()
referenceNo?: string;
@IsDate()
@Type(() => Date)
billDate: Date;
@IsOptional()
@IsDate()
@Type(() => Date)
dueDate?: Date;
@IsInt()
vendorId: number;
@IsOptional()
@IsNumber()
@IsPositive()
exchangeRate?: number;
@IsOptional()
@IsInt()
warehouseId?: number;
@IsOptional()
@IsInt()
branchId?: number;
@IsOptional()
@IsInt()
projectId?: number;
@IsOptional()
@IsString()
note?: string;
@IsBoolean()
open: boolean = false;
@IsBoolean()
isInclusiveTax: boolean = false;
@IsArray()
@ValidateNested({ each: true })
@Type(() => BillEntryDto)
@ArrayMinSize(1)
entries: BillEntryDto[];
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => AttachmentDto)
attachments?: AttachmentDto[];
@IsEnum(DiscountType)
discountType: DiscountType = DiscountType.Amount;
@IsOptional()
@IsNumber()
discount?: number;
@IsOptional()
@IsNumber()
adjustment?: number;
}
export class CreateBillDto extends CommandBillDto {}
export class EditBillDto extends CommandBillDto {}

View File

@@ -0,0 +1,659 @@
import { Model, raw, mixin } from 'objection';
import { castArray, difference, defaultTo } from 'lodash';
import * as moment from 'moment';
import * as R from 'ramda';
// import TenantModel from 'models/TenantModel';
// import BillSettings from './Bill.Settings';
// import ModelSetting from './ModelSetting';
// import CustomViewBaseModel from './CustomViewBaseModel';
// import { DEFAULT_VIEWS } from '@/services/Purchases/Bills/constants';
// import ModelSearchable from './ModelSearchable';
import { BaseModel, PaginationQueryBuilderType } from '@/models/Model';
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
import { BillLandedCost } from '@/modules/BillLandedCosts/models/BillLandedCost';
import { DiscountType } from '@/common/types/Discount';
import type { Knex, QueryBuilder } from 'knex';
import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel';
export class Bill extends TenantBaseModel {
public amount: number;
public paymentAmount: number;
public landedCostAmount: number;
public allocatedCostAmount: number;
public isInclusiveTax: boolean;
public taxAmountWithheld: number;
public exchangeRate: number;
public vendorId: number;
public billNumber: string;
public billDate: Date;
public dueDate: Date;
public referenceNo: string;
public status: string;
public note: string;
public currencyCode: string;
public creditedAmount: number;
public invLotNumber: string;
public invoicedAmount: number;
public openedAt: Date | string;
public userId: number;
public discountType: DiscountType;
public discount: number;
public adjustment: number;
public branchId: number;
public warehouseId: number;
public projectId: number;
public createdAt: Date;
public updatedAt: Date | null;
public entries?: ItemEntry[];
public locatedLandedCosts?: BillLandedCost[];
/**
* Timestamps columns.
*/
get timestamps() {
return ['createdAt', 'updatedAt'];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [
'balance',
'dueAmount',
'isOpen',
'isPartiallyPaid',
'isFullyPaid',
'isPaid',
'remainingDays',
'overdueDays',
'isOverdue',
'unallocatedCostAmount',
'localAmount',
'localAllocatedCostAmount',
'billableAmount',
'amountLocal',
'discountAmount',
'discountAmountLocal',
'discountPercentage',
'adjustmentLocal',
'subtotal',
'subtotalLocal',
'subtotalExludingTax',
'taxAmountWithheldLocal',
'total',
'totalLocal',
];
}
/**
* Invoice amount in base currency.
* @returns {number}
*/
get amountLocal(): number {
return this.amount * this.exchangeRate;
}
/**
* Subtotal. (Tax inclusive) if the tax inclusive is enabled.
* @returns {number}
*/
get subtotal(): number {
return this.amount;
}
/**
* Subtotal in base currency. (Tax inclusive) if the tax inclusive is enabled.
* @returns {number}
*/
get subtotalLocal(): number {
return this.amountLocal;
}
/**
* Sale invoice amount excluding tax.
* @returns {number}
*/
get subtotalExcludingTax(): number {
return this.isInclusiveTax
? this.subtotal - this.taxAmountWithheld
: this.subtotal;
}
/**
* Tax amount withheld in base currency.
* @returns {number}
*/
get taxAmountWithheldLocal(): number {
return this.taxAmountWithheld * this.exchangeRate;
}
/**
* Discount amount.
* @returns {number}
*/
get discountAmount(): number {
return this.discountType === DiscountType.Amount
? this.discount
: this.subtotal * (this.discount / 100);
}
/**
* Discount amount in local currency.
* @returns {number | null}
*/
get discountAmountLocal(): number | null {
return this.discountAmount ? this.discountAmount * this.exchangeRate : null;
}
/**
/**
* Discount percentage.
* @returns {number | null}
*/
get discountPercentage(): number | null {
return this.discountType === DiscountType.Percentage ? this.discount : null;
}
/**
* Adjustment amount in local currency.
* @returns {number | null}
*/
get adjustmentLocal(): number | null {
return this.adjustment ? this.adjustment * this.exchangeRate : null;
}
/**
* Invoice total. (Tax included)
* @returns {number}
*/
get total(): number {
const adjustmentAmount = defaultTo(this.adjustment, 0);
return R.compose(
R.add(adjustmentAmount),
R.subtract(R.__, this.discountAmount),
R.when(R.always(this.isInclusiveTax), R.add(this.taxAmountWithheld)),
)(this.subtotal);
}
/**
* Invoice total in local currency. (Tax included)
* @returns {number}
*/
get totalLocal(): number {
return this.total * this.exchangeRate;
}
/**
* Invoice amount in organization base currency.
* @deprecated
* @returns {number}
*/
get localAmount(): number {
return this.amountLocal;
}
/**
* Retrieves the local allocated cost amount.
* @returns {number}
*/
get localAllocatedCostAmount(): number {
return this.allocatedCostAmount * this.exchangeRate;
}
/**
* Retrieves the local landed cost amount.
* @returns {number}
*/
get localLandedCostAmount(): number {
return this.landedCostAmount * this.exchangeRate;
}
/**
* Retrieves the local unallocated cost amount.
* @returns {number}
*/
get localUnallocatedCostAmount(): number {
return this.unallocatedCostAmount * this.exchangeRate;
}
/**
* Retrieve the balance of bill.
* @return {number}
*/
get balance(): number {
return this.paymentAmount + this.creditedAmount;
}
/**
* Due amount of the given.
* @return {number}
*/
get dueAmount(): number {
return Math.max(this.total - this.balance, 0);
}
/**
* Detarmine whether the bill is open.
* @return {boolean}
*/
get isOpen(): boolean {
return !!this.openedAt;
}
/**
* Deetarmine whether the bill paid partially.
* @return {boolean}
*/
get isPartiallyPaid(): boolean {
return this.dueAmount !== this.total && this.dueAmount > 0;
}
/**
* Deetarmine whether the bill paid fully.
* @return {boolean}
*/
get isFullyPaid(): boolean {
return this.dueAmount === 0;
}
/**
* Detarmines whether the bill paid fully or partially.
* @return {boolean}
*/
get isPaid(): boolean {
return this.isPartiallyPaid || this.isFullyPaid;
}
/**
* Retrieve the remaining days in number
* @return {number|null}
*/
get remainingDays(): number | null {
const currentMoment = moment();
const dueDateMoment = moment(this.dueDate);
return Math.max(dueDateMoment.diff(currentMoment, 'days'), 0);
}
/**
* Retrieve the overdue days in number.
* @return {number|null}
*/
get overdueDays(): number | null {
const currentMoment = moment();
const dueDateMoment = moment(this.dueDate);
return Math.max(currentMoment.diff(dueDateMoment, 'days'), 0);
}
/**
* Detarmines the due date is over.
* @return {boolean}
*/
get isOverdue(): boolean {
return this.overdueDays > 0;
}
/**
* Retrieve the unallocated cost amount.
* @return {number}
*/
get unallocatedCostAmount(): number {
return Math.max(this.landedCostAmount - this.allocatedCostAmount, 0);
}
/**
* Retrieves the calculated amount which have not been invoiced.
*/
get billableAmount(): number {
return Math.max(this.total - this.invoicedAmount, 0);
}
/**
* Table name
*/
static get tableName() {
return 'bills';
}
/**
* Model modifiers.
*/
static get modifiers() {
return {
/**
* Filters the bills in draft status.
*/
draft(query) {
query.where('opened_at', null);
},
/**
* Filters the opened bills.
*/
published(query) {
query.whereNot('openedAt', null);
},
/**
* Filters the opened bills.
*/
opened(query) {
query.whereNot('opened_at', null);
},
/**
* Filters the unpaid bills.
*/
unpaid(query) {
query.where('payment_amount', 0);
},
/**
* Filters the due bills.
*/
dueBills(query) {
query.where(
raw(`COALESCE(AMOUNT, 0) -
COALESCE(PAYMENT_AMOUNT, 0) -
COALESCE(CREDITED_AMOUNT, 0) > 0
`),
);
},
/**
* Filters the overdue bills.
*/
overdue(query) {
query.where('due_date', '<', moment().format('YYYY-MM-DD'));
},
/**
* Filters the not overdue invoices.
*/
notOverdue(query, asDate = moment().format('YYYY-MM-DD')) {
query.where('due_date', '>=', asDate);
},
/**
* Filters the partially paid bills.
*/
partiallyPaid(query) {
query.whereNot('payment_amount', 0);
query.whereNot(raw('`PAYMENT_AMOUNT` = `AMOUNT`'));
},
/**
* Filters the paid bills.
*/
paid(query) {
query.where(raw('`PAYMENT_AMOUNT` = `AMOUNT`'));
},
/**
* Filters the bills from the given date.
*/
fromDate(query, fromDate) {
query.where('bill_date', '<=', fromDate);
},
/**
* Sort the bills by full-payment bills.
*/
sortByStatus(query, order) {
query.orderByRaw(`PAYMENT_AMOUNT = AMOUNT ${order}`);
},
/**
* Status filter.
*/
statusFilter(query, filterType) {
switch (filterType) {
case 'draft':
query.modify('draft');
break;
case 'delivered':
query.modify('delivered');
break;
case 'unpaid':
query.modify('unpaid');
break;
case 'overdue':
default:
query.modify('overdue');
break;
case 'partially-paid':
query.modify('partiallyPaid');
break;
case 'paid':
query.modify('paid');
break;
}
},
/**
* Filters by branches.
*/
filterByBranches(query, branchesIds) {
const formattedBranchesIds = castArray(branchesIds);
query.whereIn('branchId', formattedBranchesIds);
},
dueBillsFromDate(query, asDate = moment().format('YYYY-MM-DD')) {
query.modify('dueBills');
query.modify('notOverdue');
query.modify('fromDate', asDate);
},
overdueBillsFromDate(query, asDate = moment().format('YYYY-MM-DD')) {
query.modify('dueBills');
query.modify('overdue', asDate);
query.modify('fromDate', asDate);
},
/**
*
*/
billable(query) {
query.where(raw('AMOUNT > INVOICED_AMOUNT'));
},
};
}
/**
* Bill model settings.
*/
// static get meta() {
// return BillSettings;
// }
/**
* Relationship mapping.
*/
static get relationMappings() {
const { Vendor } = require('../../Vendors/models/Vendor');
const {
ItemEntry,
} = require('../../TransactionItemEntry/models/ItemEntry');
const {
BillLandedCost,
} = require('../../BillLandedCosts/models/BillLandedCost');
const { Branch } = require('../../Branches/models/Branch.model');
const { Warehouse } = require('../../Warehouses/models/Warehouse.model');
const { TaxRateModel } = require('../../TaxRates/models/TaxRate.model');
const {
TaxRateTransaction,
} = require('../../TaxRates/models/TaxRateTransaction.model');
const { Document } = require('../../ChromiumlyTenancy/models/Document');
// const { MatchedBankTransaction } = require('models/MatchedBankTransaction');
return {
vendor: {
relation: Model.BelongsToOneRelation,
modelClass: Vendor,
join: {
from: 'bills.vendorId',
to: 'contacts.id',
},
filter(query) {
query.where('contact_service', 'vendor');
},
},
entries: {
relation: Model.HasManyRelation,
modelClass: ItemEntry,
join: {
from: 'bills.id',
to: 'items_entries.referenceId',
},
filter(builder) {
builder.where('reference_type', 'Bill');
builder.orderBy('index', 'ASC');
},
},
locatedLandedCosts: {
relation: Model.HasManyRelation,
modelClass: BillLandedCost,
join: {
from: 'bills.id',
to: 'bill_located_costs.billId',
},
},
/**
* Bill may belongs to associated branch.
*/
branch: {
relation: Model.BelongsToOneRelation,
modelClass: Branch,
join: {
from: 'bills.branchId',
to: 'branches.id',
},
},
/**
* Bill may has associated warehouse.
*/
warehouse: {
relation: Model.BelongsToOneRelation,
modelClass: Warehouse,
join: {
from: 'bills.warehouseId',
to: 'warehouses.id',
},
},
/**
* Bill may has associated tax rate transactions.
*/
taxes: {
relation: Model.HasManyRelation,
modelClass: TaxRateTransaction,
join: {
from: 'bills.id',
to: 'tax_rate_transactions.referenceId',
},
filter(builder) {
builder.where('reference_type', 'Bill');
},
},
/**
* Bill may has many attached attachments.
*/
attachments: {
relation: Model.ManyToManyRelation,
modelClass: Document,
join: {
from: 'bills.id',
through: {
from: 'document_links.modelId',
to: 'document_links.documentId',
},
to: 'documents.id',
},
filter(query) {
query.where('model_ref', 'Bill');
},
},
/**
* Bill may belongs to matched bank transaction.
*/
// matchedBankTransaction: {
// relation: Model.HasManyRelation,
// modelClass: MatchedBankTransaction,
// join: {
// from: 'bills.id',
// to: 'matched_bank_transactions.referenceId',
// },
// filter(query) {
// query.where('reference_type', 'Bill');
// },
// },
};
}
/**
* Retrieve the not found bills ids as array that associated to the given vendor.
* @param {Array} billsIds
* @param {number} vendorId -
* @return {Array}
*/
static async getNotFoundBills(billsIds, vendorId) {
const storedBills = await this.query().onBuild((builder) => {
builder.whereIn('id', billsIds);
if (vendorId) {
builder.where('vendor_id', vendorId);
}
});
const storedBillsIds = storedBills.map((t) => t.id);
const notFoundBillsIds = difference(billsIds, storedBillsIds);
return notFoundBillsIds;
}
static changePaymentAmount(
billId: number,
amount: number,
trx: Knex.Transaction,
) {
const changeMethod = amount > 0 ? 'increment' : 'decrement';
return this.query(trx)
.where('id', billId)
[changeMethod]('payment_amount', Math.abs(amount));
}
/**
* Retrieve the default custom views, roles and columns.
*/
// static get defaultViews() {
// return DEFAULT_VIEWS;
// }
/**
* Model search attributes.
*/
static get searchRoles() {
return [
{ fieldKey: 'bill_number', comparator: 'contains' },
{ condition: 'or', fieldKey: 'reference_no', comparator: 'contains' },
{ condition: 'or', fieldKey: 'amount', comparator: 'equals' },
];
}
/**
* Prevents mutate base currency since the model is not empty.
*/
static get preventMutateBaseCurrency() {
return true;
}
}

View File

@@ -0,0 +1,217 @@
import { Transformer } from '@/modules/Transformer/Transformer';
import { Bill } from '../models/Bill';
import { AttachmentTransformer } from '@/modules/Attachments/Attachment.transformer';
import { ItemEntryTransformer } from '@/modules/TransactionItemEntry/ItemEntry.transformer';
import { SaleInvoiceTaxEntryTransformer } from '@/modules/SaleInvoices/queries/SaleInvoiceTaxEntry.transformer';
export class BillTransformer extends Transformer {
/**
* Include these attributes to sale bill object.
* @returns {Array}
*/
public includeAttributes = (): string[] => {
return [
'formattedBillDate',
'formattedDueDate',
'formattedCreatedAt',
'formattedAmount',
'formattedPaymentAmount',
'formattedBalance',
'formattedDueAmount',
'formattedExchangeRate',
'subtotalFormatted',
'subtotalLocalFormatted',
'subtotalExcludingTaxFormatted',
'taxAmountWithheldLocalFormatted',
'totalFormatted',
'totalLocalFormatted',
'taxes',
'entries',
'attachments',
];
};
/**
* Excluded attributes.
* @returns {string[]}
*/
public excludeAttributes = (): string[] => {
return ['amount', 'amountLocal', 'localAmount'];
};
/**
* Retrieve formatted bill date.
* @param {IBill} bill
* @returns {String}
*/
protected formattedBillDate = (bill: Bill): string => {
return this.formatDate(bill.billDate);
};
/**
* Retrieve formatted bill date.
* @param {IBill} bill
* @returns {String}
*/
protected formattedDueDate = (bill: Bill): string => {
return this.formatDate(bill.dueDate);
};
/**
* Retrieve the formatted created at date.
* @param {IBill} bill
* @returns {string}
*/
protected formattedCreatedAt = (bill: Bill): string => {
return this.formatDate(bill.createdAt);
};
/**
* Retrieve formatted bill amount.
* @param {IBill} bill
* @returns {string}
*/
protected formattedAmount = (bill: Bill): string => {
return this.formatNumber(bill.amount, { currencyCode: bill.currencyCode });
};
/**
* Retrieve formatted bill amount.
* @param {IBill} bill
* @returns {string}
*/
protected formattedPaymentAmount = (bill: Bill): string => {
return this.formatNumber(bill.paymentAmount, {
currencyCode: bill.currencyCode,
});
};
/**
* Retrieve formatted bill amount.
* @param {IBill} bill
* @returns {string}
*/
protected formattedDueAmount = (bill: Bill): string => {
return this.formatNumber(bill.dueAmount, {
currencyCode: bill.currencyCode,
});
};
/**
* Retrieve formatted bill balance.
* @param {IBill} bill
* @returns {string}
*/
protected formattedBalance = (bill: Bill): string => {
return this.formatNumber(bill.balance, { currencyCode: bill.currencyCode });
};
/**
* Retrieve the formatted exchange rate.
* @param {IBill} bill
* @returns {string}
*/
protected formattedExchangeRate = (bill: Bill): string => {
return this.formatNumber(bill.exchangeRate, {
currencyCode: this.context.organization.baseCurrency,
});
};
/**
* Retrieves the formatted subtotal.
* @param {IBill} bill
* @returns {string}
*/
protected subtotalFormatted = (bill: Bill): string => {
return this.formatNumber(bill.subtotal, {
currencyCode: bill.currencyCode,
});
};
/**
* Retrieves the local subtotal formatted.
* @param {IBill} bill
* @returns {string}
*/
protected subtotalLocalFormatted = (bill: Bill): string => {
return this.formatNumber(bill.subtotalLocal, {
currencyCode: this.context.organization.baseCurrency,
});
};
/**
* Retrieves the formatted subtotal tax excluded.
* @param {IBill} bill
* @returns {string}
*/
protected subtotalExcludingTaxFormatted = (bill: Bill): string => {
return this.formatNumber(bill.subtotalExcludingTax, {
currencyCode: bill.currencyCode,
});
};
/**
* Retrieves the local formatted tax amount withheld
* @param {IBill} bill
* @returns {string}
*/
protected taxAmountWithheldLocalFormatted = (bill: Bill): string => {
return this.formatNumber(bill.taxAmountWithheldLocal, {
currencyCode: this.context.organization.baseCurrency,
});
};
/**
* Retrieves the total formatted.
* @param {IBill} bill
* @returns {string}
*/
protected totalFormatted = (bill: Bill): string => {
return this.formatNumber(bill.total, {
currencyCode: bill.currencyCode,
});
};
/**
* Retrieves the local total formatted.
* @param {IBill} bill
* @returns {string}
*/
protected totalLocalFormatted = (bill: Bill): string => {
return this.formatNumber(bill.totalLocal, {
currencyCode: this.context.organization.baseCurrency,
});
};
/**
* Retrieve the taxes lines of bill.
* @param {Bill} bill
*/
// protected taxes = (bill: Bill) => {
// return this.item(bill.taxes, new SaleInvoiceTaxEntryTransformer(), {
// subtotal: bill.subtotal,
// isInclusiveTax: bill.isInclusiveTax,
// currencyCode: bill.currencyCode,
// });
// };
/**
* Retrieves the entries of the bill.
* @param {Bill} credit
* @returns {}
*/
// protected entries = (bill: Bill) => {
// return this.item(bill.entries, new ItemEntryTransformer(), {
// currencyCode: bill.currencyCode,
// });
// };
/**
* Retrieves the bill attachments.
* @param {ISaleInvoice} invoice
* @returns
*/
// protected attachments = (bill: Bill) => {
// return this.item(bill.attachments, new AttachmentTransformer());
// };
}

View File

@@ -0,0 +1,37 @@
import { Inject, Injectable } from '@nestjs/common';
import { BillsValidators } from '../commands/BillsValidators.service';
import { BillTransformer } from './Bill.transformer';
import { Bill } from '../models/Bill';
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class GetBill {
constructor(
@Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>,
private transformer: TransformerInjectable,
private validators: BillsValidators,
) {}
/**
* Retrieve the given bill details with associated items entries.
* @param {Integer} billId - Specific bill.
* @returns {Promise<IBill>}
*/
public async getBill(billId: number): Promise<Bill> {
const bill = await this.billModel()
.query()
.findById(billId)
.withGraphFetched('vendor')
.withGraphFetched('entries.item')
.withGraphFetched('branch')
.withGraphFetched('taxes.taxRate')
.withGraphFetched('attachments');
// Validates the bill existence.
this.validators.validateBillExistance(bill);
return this.transformer.transform(bill, new BillTransformer());
}
}

View File

@@ -0,0 +1,32 @@
import { Inject, Injectable } from '@nestjs/common';
import { BillPaymentEntry } from '@/modules/BillPayments/models/BillPaymentEntry';
import { BillPaymentTransactionTransformer } from '@/modules/BillPayments/queries/BillPaymentTransactionTransformer';
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
@Injectable()
export class GetBillPayments {
constructor(
@Inject(BillPaymentEntry.name)
private billPaymentEntryModel: typeof BillPaymentEntry,
private transformer: TransformerInjectable,
) {}
/**
* Retrieve the specific bill associated payment transactions.
* @param {number} billId
* @returns {}
*/
public getBillPayments = async (billId: number) => {
const billsEntries = await this.billPaymentEntryModel
.query()
.where('billId', billId)
.withGraphJoined('payment.paymentAccount')
.withGraphJoined('bill')
.orderBy('payment:paymentDate', 'ASC');
return this.transformer.transform(
billsEntries,
new BillPaymentTransactionTransformer(),
);
};
}

View File

@@ -0,0 +1,68 @@
import { Inject, Injectable } from '@nestjs/common';
import * as R from 'ramda';
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service';
import { Bill } from '../models/Bill';
import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model';
import { BillTransformer } from './Bill.transformer';
import { IBillsFilter } from '../Bills.types';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class GetBillsService {
constructor(
private transformer: TransformerInjectable,
private dynamicListService: DynamicListService,
@Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>,
) {}
/**
* Retrieve bills data table list.
* @param {IBillsFilter} billsFilter -
*/
public async getBills(filterDTO: IBillsFilter): Promise<{
bills: Bill;
pagination: IPaginationMeta;
filterMeta: IFilterMeta;
}> {
// Parses bills list filter DTO.
const filter = this.parseListFilterDTO(filterDTO);
// Dynamic list service.
const dynamicFilter = await this.dynamicListService.dynamicList(
this.billModel(),
filter,
);
const { results, pagination } = await this.billModel()
.query()
.onBuild((builder) => {
builder.withGraphFetched('vendor');
builder.withGraphFetched('entries.item');
dynamicFilter.buildQuery()(builder);
// Filter query.
filterDTO?.filterQuery && filterDTO?.filterQuery(builder);
})
.pagination(filter.page - 1, filter.pageSize);
// Tranform the bills to POJO.
const bills = await this.transformer.transform(
results,
new BillTransformer(),
);
return {
bills,
pagination,
filterMeta: dynamicFilter.getResponseMeta(),
};
}
/**
* Parses bills list filter DTO.
* @param filterDTO -
*/
private parseListFilterDTO(filterDTO) {
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
}
}

View File

@@ -0,0 +1,28 @@
import { Inject, Injectable } from '@nestjs/common';
import { Bill } from '../models/Bill';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
@Injectable()
export class GetDueBills {
constructor(
@Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>,
) {}
/**
* Retrieve all due bills or for specific given vendor id.
* @param {number} vendorId -
*/
public async getDueBills(vendorId?: number): Promise<Bill[]> {
const dueBills = await this.billModel()
.query()
.onBuild((query) => {
query.orderBy('bill_date', 'DESC');
query.modify('dueBills');
if (vendorId) {
query.where('vendor_id', vendorId);
}
});
return dueBills;
}
}

View File

@@ -0,0 +1,59 @@
import { Injectable } from '@nestjs/common';
import {
IBillCreatedPayload,
IBillEditedPayload,
IBIllEventDeletedPayload,
IBillOpenedPayload,
} from '../Bills.types';
import { BillGLEntries } from '../commands/BillsGLEntries';
import { events } from '@/common/events/events';
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class BillGLEntriesSubscriber {
/**
* @param {BillGLEntries} billGLEntries - Bill GL entries command.
*/
constructor(private billGLEntries: BillGLEntries) {}
/**
* Handles writing journal entries once bill created.
* @param {IBillCreatedPayload} payload -
*/
@OnEvent(events.bill.onCreated)
@OnEvent(events.bill.onOpened)
public async handlerWriteJournalEntriesOnCreate({
bill,
trx,
}: IBillCreatedPayload | IBillOpenedPayload) {
if (!bill.openedAt) return null;
await this.billGLEntries.writeBillGLEntries(bill.id, trx);
};
/**
* Handles the overwriting journal entries once bill edited.
* @param {IBillEditedPayload} payload -
*/
@OnEvent(events.bill.onEdited)
public async handleOverwriteJournalEntriesOnEdit({
bill,
trx,
}: IBillEditedPayload) {
if (!bill.openedAt) return null;
await this.billGLEntries.rewriteBillGLEntries(bill.id, trx);
};
/**
* Handles revert journal entries on bill deleted.
* @param {IBIllEventDeletedPayload} payload -
*/
@OnEvent(events.bill.onDeleted)
public async handlerDeleteJournalEntries({
oldBill,
trx,
}: IBIllEventDeletedPayload) {
await this.billGLEntries.revertBillGLEntries(oldBill.id, trx);
};
}

View File

@@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common';
import {
IBillCreatedPayload,
IBillEditedPayload,
IBIllEventDeletedPayload,
IBillOpenedPayload,
} from '../Bills.types';
import { BillInventoryTransactions } from '../commands/BillInventoryTransactions';
import { events } from '@/common/events/events';
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class BillWriteInventoryTransactionsSubscriber {
constructor(private readonly billsInventory: BillInventoryTransactions) {}
/**
* Handles writing the inventory transactions once bill created.
* @param {IBillCreatedPayload | IBillOpenedPayload} payload -
*/
@OnEvent(events.bill.onCreated)
@OnEvent(events.bill.onOpened)
public async handleWritingInventoryTransactions({
bill,
trx,
}: IBillCreatedPayload | IBillOpenedPayload) {
// Can't continue if the bill is not opened yet.
if (!bill.openedAt) return null;
await this.billsInventory.recordInventoryTransactions(bill.id, false, trx);
}
/**
* Handles the overwriting the inventory transactions once bill edited.
* @param {IBillEditedPayload} payload -
*/
@OnEvent(events.bill.onEdited)
public async handleOverwritingInventoryTransactions({
bill,
trx,
}: IBillEditedPayload) {
// Can't continue if the bill is not opened yet.
if (!bill.openedAt) return null;
await this.billsInventory.recordInventoryTransactions(bill.id, true, trx);
};
/**
* Handles the reverting the inventory transactions once the bill deleted.
* @param {IBIllEventDeletedPayload} payload -
*/
@OnEvent(events.bill.onDeleted)
public async handleRevertInventoryTransactions({
billId,
trx,
}: IBIllEventDeletedPayload) {
await this.billsInventory.revertInventoryTransactions(billId, trx);
}
}