mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-19 14:20:31 +00:00
refactor: wip to nestjs
This commit is contained in:
105
packages/server-nest/src/modules/Bills/Bills.application.ts
Normal file
105
packages/server-nest/src/modules/Bills/Bills.application.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
|
||||
import { CreateBill } from './commands/CreateBill.service';
|
||||
import { EditBillService } from './commands/EditBill.service';
|
||||
import { GetBill } from './queries/GetBill';
|
||||
// import { GetBills } from './queries/GetBills';
|
||||
import { DeleteBill } from './commands/DeleteBill.service';
|
||||
import {
|
||||
IBillDTO,
|
||||
IBillEditDTO,
|
||||
} from './Bills.types';
|
||||
import { GetDueBills } from './queries/GetDueBills.service';
|
||||
import { OpenBillService } from './commands/OpenBill.service';
|
||||
import { GetBillPayments } from './queries/GetBillPayments';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class BillsApplication {
|
||||
constructor(
|
||||
private createBillService: CreateBill,
|
||||
private editBillService: EditBillService,
|
||||
private getBillService: GetBill,
|
||||
// private getBillsService: GetBills,
|
||||
private deleteBillService: DeleteBill,
|
||||
private getDueBillsService: GetDueBills,
|
||||
private openBillService: OpenBillService,
|
||||
private getBillPaymentsService: GetBillPayments,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Creates a new bill with associated GL entries.
|
||||
* @param {IBillDTO} billDTO
|
||||
* @returns
|
||||
*/
|
||||
public createBill(billDTO: IBillDTO) {
|
||||
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: IBillEditDTO) {
|
||||
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 {number} tenantId -
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
123
packages/server-nest/src/modules/Bills/Bills.constants.ts
Normal file
123
packages/server-nest/src/modules/Bills/Bills.constants.ts
Normal 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.',
|
||||
},
|
||||
];
|
||||
17
packages/server-nest/src/modules/Bills/Bills.module.ts
Normal file
17
packages/server-nest/src/modules/Bills/Bills.module.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
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';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
BillsApplication,
|
||||
CreateBill,
|
||||
GetBill,
|
||||
DeleteBill,
|
||||
BillDTOTransformer,
|
||||
],
|
||||
})
|
||||
export class BillsModule {}
|
||||
112
packages/server-nest/src/modules/Bills/Bills.types.ts
Normal file
112
packages/server-nest/src/modules/Bills/Bills.types.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { Knex } from 'knex';
|
||||
import { IItemEntryDTO } from '../TransactionItemEntry/ItemEntry.types';
|
||||
import { AttachmentLinkDTO } from '../Attachments/Attachments.types';
|
||||
import { Bill } from './models/Bill';
|
||||
|
||||
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 IDynamicListFilterDTO {
|
||||
// stringifiedFilterRoles?: string;
|
||||
// page: number;
|
||||
// pageSize: number;
|
||||
// filterQuery?: (q: any) => void;
|
||||
// }
|
||||
|
||||
export interface IBillCreatedPayload {
|
||||
// tenantId: number;
|
||||
bill: Bill;
|
||||
billDTO: IBillDTO;
|
||||
billId: number;
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IBillCreatingPayload {
|
||||
// tenantId: number;
|
||||
billDTO: IBillDTO;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IBillEditingPayload {
|
||||
// tenantId: number;
|
||||
oldBill: Bill;
|
||||
billDTO: IBillEditDTO;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
export interface IBillEditedPayload {
|
||||
// tenantId: number;
|
||||
// billId: number;
|
||||
oldBill: Bill;
|
||||
bill: Bill;
|
||||
billDTO: IBillDTO;
|
||||
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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
585
packages/server-nest/src/modules/Bills/models/Bill.ts
Normal file
585
packages/server-nest/src/modules/Bills/models/Bill.ts
Normal file
@@ -0,0 +1,585 @@
|
||||
import { Model, raw, mixin } from 'objection';
|
||||
import { castArray, difference } from 'lodash';
|
||||
import moment from 'moment';
|
||||
// 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 } from '@/models/Model';
|
||||
|
||||
export class Bill extends BaseModel{
|
||||
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 createdAt: Date;
|
||||
public updatedAt: Date | null;
|
||||
|
||||
/**
|
||||
* 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',
|
||||
'subtotal',
|
||||
'subtotalLocal',
|
||||
'subtotalExcludingTax',
|
||||
'taxAmountWithheldLocal',
|
||||
'total',
|
||||
'totalLocal',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoice amount in base currency.
|
||||
* @returns {number}
|
||||
*/
|
||||
get amountLocal() {
|
||||
return this.amount * this.exchangeRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtotal. (Tax inclusive) if the tax inclusive is enabled.
|
||||
* @returns {number}
|
||||
*/
|
||||
get subtotal() {
|
||||
return this.amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtotal in base currency. (Tax inclusive) if the tax inclusive is enabled.
|
||||
* @returns {number}
|
||||
*/
|
||||
get subtotalLocal() {
|
||||
return this.amountLocal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sale invoice amount excluding tax.
|
||||
* @returns {number}
|
||||
*/
|
||||
get subtotalExcludingTax() {
|
||||
return this.isInclusiveTax
|
||||
? this.subtotal - this.taxAmountWithheld
|
||||
: this.subtotal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tax amount withheld in base currency.
|
||||
* @returns {number}
|
||||
*/
|
||||
get taxAmountWithheldLocal() {
|
||||
return this.taxAmountWithheld * this.exchangeRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoice total. (Tax included)
|
||||
* @returns {number}
|
||||
*/
|
||||
get total() {
|
||||
return this.isInclusiveTax
|
||||
? this.subtotal
|
||||
: this.subtotal + this.taxAmountWithheld;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoice total in local currency. (Tax included)
|
||||
* @returns {number}
|
||||
*/
|
||||
get totalLocal() {
|
||||
return this.total * this.exchangeRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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'));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoice amount in organization base currency.
|
||||
* @deprecated
|
||||
* @returns {number}
|
||||
*/
|
||||
get localAmount() {
|
||||
return this.amountLocal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the local allocated cost amount.
|
||||
* @returns {number}
|
||||
*/
|
||||
get localAllocatedCostAmount() {
|
||||
return this.allocatedCostAmount * this.exchangeRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the local landed cost amount.
|
||||
* @returns {number}
|
||||
*/
|
||||
get localLandedCostAmount() {
|
||||
return this.landedCostAmount * this.exchangeRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the local unallocated cost amount.
|
||||
* @returns {number}
|
||||
*/
|
||||
get localUnallocatedCostAmount() {
|
||||
return this.unallocatedCostAmount * this.exchangeRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the balance of bill.
|
||||
* @return {number}
|
||||
*/
|
||||
get balance() {
|
||||
return this.paymentAmount + this.creditedAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Due amount of the given.
|
||||
* @return {number}
|
||||
*/
|
||||
get dueAmount() {
|
||||
return Math.max(this.total - this.balance, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detarmine whether the bill is open.
|
||||
* @return {boolean}
|
||||
*/
|
||||
get isOpen() {
|
||||
return !!this.openedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deetarmine whether the bill paid partially.
|
||||
* @return {boolean}
|
||||
*/
|
||||
get isPartiallyPaid() {
|
||||
return this.dueAmount !== this.total && this.dueAmount > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deetarmine whether the bill paid fully.
|
||||
* @return {boolean}
|
||||
*/
|
||||
get isFullyPaid() {
|
||||
return this.dueAmount === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detarmines whether the bill paid fully or partially.
|
||||
* @return {boolean}
|
||||
*/
|
||||
get isPaid() {
|
||||
return this.isPartiallyPaid || this.isFullyPaid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the remaining days in number
|
||||
* @return {number|null}
|
||||
*/
|
||||
get remainingDays() {
|
||||
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() {
|
||||
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() {
|
||||
return this.overdueDays > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the unallocated cost amount.
|
||||
* @return {number}
|
||||
*/
|
||||
get unallocatedCostAmount() {
|
||||
return Math.max(this.landedCostAmount - this.allocatedCostAmount, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the calculated amount which have not been invoiced.
|
||||
*/
|
||||
get billableAmount() {
|
||||
return Math.max(this.total - this.invoicedAmount, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bill model settings.
|
||||
*/
|
||||
// static get meta() {
|
||||
// return BillSettings;
|
||||
// }
|
||||
|
||||
/**
|
||||
* Relationship mapping.
|
||||
*/
|
||||
static get relationMappings() {
|
||||
const Vendor = require('models/Vendor');
|
||||
const ItemEntry = require('models/ItemEntry');
|
||||
const BillLandedCost = require('models/BillLandedCost');
|
||||
const Branch = require('models/Branch');
|
||||
const Warehouse = require('models/Warehouse');
|
||||
const TaxRateTransaction = require('models/TaxRateTransaction');
|
||||
const Document = require('models/Document');
|
||||
const { MatchedBankTransaction } = require('models/MatchedBankTransaction');
|
||||
|
||||
return {
|
||||
vendor: {
|
||||
relation: Model.BelongsToOneRelation,
|
||||
modelClass: Vendor.default,
|
||||
join: {
|
||||
from: 'bills.vendorId',
|
||||
to: 'contacts.id',
|
||||
},
|
||||
filter(query) {
|
||||
query.where('contact_service', 'vendor');
|
||||
},
|
||||
},
|
||||
|
||||
entries: {
|
||||
relation: Model.HasManyRelation,
|
||||
modelClass: ItemEntry.default,
|
||||
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.default,
|
||||
join: {
|
||||
from: 'bills.id',
|
||||
to: 'bill_located_costs.billId',
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Bill may belongs to associated branch.
|
||||
*/
|
||||
branch: {
|
||||
relation: Model.BelongsToOneRelation,
|
||||
modelClass: Branch.default,
|
||||
join: {
|
||||
from: 'bills.branchId',
|
||||
to: 'branches.id',
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Bill may has associated warehouse.
|
||||
*/
|
||||
warehouse: {
|
||||
relation: Model.BelongsToOneRelation,
|
||||
modelClass: Warehouse.default,
|
||||
join: {
|
||||
from: 'bills.warehouseId',
|
||||
to: 'warehouses.id',
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Bill may has associated tax rate transactions.
|
||||
*/
|
||||
taxes: {
|
||||
relation: Model.HasManyRelation,
|
||||
modelClass: TaxRateTransaction.default,
|
||||
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.default,
|
||||
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, amount, trx) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
// };
|
||||
}
|
||||
38
packages/server-nest/src/modules/Bills/queries/GetBill.ts
Normal file
38
packages/server-nest/src/modules/Bills/queries/GetBill.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class GetBill {
|
||||
constructor(
|
||||
@Inject(Bill.name) private billModel: 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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
);
|
||||
};
|
||||
}
|
||||
72
packages/server-nest/src/modules/Bills/queries/GetBills.ts
Normal file
72
packages/server-nest/src/modules/Bills/queries/GetBills.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
// import { Injectable } from '@nestjs/common';
|
||||
// import * as R from 'ramda';
|
||||
// import {
|
||||
// IBill,
|
||||
// IBillsFilter,
|
||||
// IFilterMeta,
|
||||
// IPaginationMeta,
|
||||
// } from '@/interfaces';
|
||||
// import { BillTransformer } from './Bill.transformer';
|
||||
// import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
|
||||
// // import { DynamicListingService } from '@/modules/DynamicListing/DynamicListService';
|
||||
|
||||
// @Injectable()
|
||||
// export class GetBills {
|
||||
// constructor(
|
||||
// private transformer: TransformerInjectable,
|
||||
// private dynamicListService: DynamicListingService,
|
||||
// ) {}
|
||||
|
||||
// /**
|
||||
// * Retrieve bills data table list.
|
||||
// * @param {number} tenantId -
|
||||
// * @param {IBillsFilter} billsFilter -
|
||||
// */
|
||||
// public async getBills(
|
||||
// tenantId: number,
|
||||
// filterDTO: IBillsFilter,
|
||||
// ): Promise<{
|
||||
// bills: IBill;
|
||||
// pagination: IPaginationMeta;
|
||||
// filterMeta: IFilterMeta;
|
||||
// }> {
|
||||
// // Parses bills list filter DTO.
|
||||
// const filter = this.parseListFilterDTO(filterDTO);
|
||||
|
||||
// // Dynamic list service.
|
||||
// const dynamicFilter = await this.dynamicListService.dynamicList(
|
||||
// tenantId,
|
||||
// Bill,
|
||||
// filter,
|
||||
// );
|
||||
// const { results, pagination } = await Bill.query()
|
||||
// .onBuild((builder) => {
|
||||
// builder.withGraphFetched('vendor');
|
||||
// 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 PurchaseInvoiceTransformer(),
|
||||
// );
|
||||
// return {
|
||||
// bills,
|
||||
// pagination,
|
||||
// filterMeta: dynamicFilter.getResponseMeta(),
|
||||
// };
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Parses bills list filter DTO.
|
||||
// * @param filterDTO -
|
||||
// */
|
||||
// private parseListFilterDTO(filterDTO) {
|
||||
// return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Bill } from '../models/Bill';
|
||||
|
||||
@Injectable()
|
||||
export class GetDueBills {
|
||||
constructor(private billModel: 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user