From 5c0bb52b592882354e359c7647a645375ee1e0e8 Mon Sep 17 00:00:00 2001 From: Ahmed Bouhuolia Date: Sat, 15 Feb 2025 23:52:12 +0200 Subject: [PATCH] refactor: tenant proxy providers --- packages/server-nest/package.json | 2 +- .../server-nest/src/interfaces/Account.ts | 4 - packages/server-nest/src/interfaces/Tenant.ts | 4 + .../src/modules/Accounts/Accounts.module.ts | 3 +- .../Accounts/ActivateAccount.service.ts | 7 +- .../CommandAccountValidators.service.ts | 7 +- .../modules/Accounts/CreateAccount.service.ts | 11 ++- .../modules/Accounts/DeleteAccount.service.ts | 11 ++- .../modules/Accounts/EditAccount.service.ts | 7 +- .../modules/Accounts/GetAccount.service.ts | 5 +- .../GetAccountTransactions.service.ts | 11 ++- .../modules/Accounts/GetAccounts.service.ts | 15 +-- .../server-nest/src/modules/App/App.module.ts | 10 +- .../src/modules/BankRules/BankRules.module.ts | 5 +- .../commands/DeleteBankRule.service.ts | 14 ++- .../commands/EditBankRule.service.ts | 22 +++-- .../BankRules/queries/GetBankRule.service.ts | 11 +-- .../BankRules/queries/GetBankRules.service.ts | 10 +- .../commands/DisconnectBankAccount.service.ts | 17 +++- .../commands/PauseBankAccountFeeds.service.ts | 13 ++- .../commands/RefreshBankAccount.service.ts | 6 +- .../ResumeBankAccountFeeds.service.ts | 12 ++- .../queries/GetBankAccountSummary.ts | 91 +++++++++++-------- ...ategorizedTransactionsOnAccountDeleting.ts | 23 ++--- .../DisconnectPlaidItemOnAccountDeleted.ts | 17 ++-- .../commands/CategorizeCashflowTransaction.ts | 18 ++-- .../CategorizeTransactionAsExpense.ts | 9 +- .../CreateUncategorizedTransaction.service.ts | 55 +++++------ ...UncategorizeCashflowTransaction.service.ts | 13 ++- .../UncategorizedTransactionsImportable.ts | 7 +- .../BankingMatching/BankingMatching.module.ts | 2 +- .../commands/MatchTransactions.ts | 7 +- .../UnmatchMatchedTransaction.service.ts | 7 +- .../ValidateTransactionsMatched.service.ts | 13 ++- ...crementUncategorizedTransactionsOnMatch.ts | 27 +++--- .../queries/GetMatchedTransactions.service.ts | 21 +++-- .../GetMatchedTransactionsByBills.service.ts | 43 +++++---- .../GetMatchedTransactionsByCashflow.ts | 9 +- .../GetMatchedTransactionsByExpenses.ts | 47 +++++----- ...etMatchedTransactionsByInvoices.service.ts | 75 ++++++++------- ...hedTransactionsByManualJournals.service.ts | 47 +++++----- .../queries/GetMatchedTransactionsByType.ts | 17 ++-- .../BankingPlaid/BankingPlaid.module.ts | 8 +- .../modules/BankingPlaid/command/PlaidItem.ts | 16 +++- .../BankingPlaid/command/PlaidSyncDB.ts | 21 +++-- .../command/PlaidUpdateTransactions.ts | 6 +- .../BankingTransactionsRegonize.module.ts | 7 +- .../commands/RecognizeTranasctions.service.ts | 37 +++++--- ...etAutofillCategorizeTransaction.service.ts | 14 ++- .../BankingTransactions.module.ts | 2 +- .../commands/CreateBankTransaction.service.ts | 11 ++- .../DeleteCashflowTransaction.service.ts | 13 ++- ...PendingUncategorizedTransaction.service.ts | 9 +- ...teDeleteBankAccountTransactions.service.ts | 7 +- .../GetRecognizedTransaction.service.ts | 14 +-- .../ExcludeBankTransaction.service.ts | 9 +- .../UnexcludeBankTransaction.service.ts | 9 +- .../queries/GetExcludedBankTransactions.ts | 11 ++- ...rementUncategorizedTransactionOnExclude.ts | 25 +++-- .../commands/BillPaymentBillSync.service.ts | 5 +- .../commands/BillPaymentGLEntries.ts | 14 +-- .../commands/BillPaymentValidators.service.ts | 26 +++--- .../commands/BillPaymentsPages.service.ts | 13 +-- .../commands/CreateBillPayment.service.ts | 13 +-- .../commands/DeleteBillPayment.service.ts | 13 ++- .../commands/EditBillPayment.service.ts | 11 ++- .../queries/GetBillPayment.service.ts | 5 +- .../queries/GetPaymentBills.service.ts | 9 +- .../commands/BillDTOTransformer.service.ts | 14 ++- .../commands/BillInventoryTransactions.ts | 6 +- .../modules/Bills/commands/BillsGLEntries.ts | 5 +- .../Bills/commands/BillsValidators.service.ts | 26 +++--- .../Bills/commands/CreateBill.service.ts | 11 ++- .../Bills/commands/DeleteBill.service.ts | 14 ++- .../Bills/commands/EditBill.service.ts | 44 +++++---- .../Bills/commands/OpenBill.service.ts | 7 +- .../src/modules/Bills/queries/GetBill.ts | 10 +- .../modules/Bills/queries/GetBills.service.ts | 7 +- .../Bills/queries/GetDueBills.service.ts | 20 ++-- .../ActivateBranchesFeature.service.ts | 3 +- .../BranchCommandValidator.service.ts | 9 +- .../Branches/commands/CreateBranch.service.ts | 12 ++- .../Branches/commands/DeleteBranch.service.ts | 15 +-- .../Branches/commands/EditBranch.service.ts | 7 +- .../commands/MarkBranchAsPrimary.service.ts | 9 +- .../Branches/queries/GetBranch.service.ts | 5 +- .../Branches/queries/GetBranches.service.ts | 5 +- .../ChromiumlyHtmlConvert.service.ts | 11 ++- .../CreateRefundCreditNote.service.ts | 22 +++-- .../DeleteRefundCreditNote.service.ts | 9 +- .../commands/RefundCreditNote.service.ts | 9 +- .../commands/RefundSyncCreditNoteBalance.ts | 13 +-- .../queries/GetCreditNoteRefunds.service.ts | 7 +- .../GetRefundCreditNoteTransaction.service.ts | 12 ++- .../commands/CreateCreditNote.service.ts | 15 +-- .../commands/CreditNoteGLEntries.ts | 3 +- .../commands/DeleteCreditNote.service.ts | 27 +++--- .../commands/EditCreditNote.service.ts | 22 +++-- .../commands/OpenCreditNote.service.ts | 7 +- .../queries/GetCreditNote.service.ts | 7 +- .../queries/GetCreditNotePdf.serivce.ts | 11 ++- .../queries/GetCreditNoteState.service.ts | 6 +- .../queries/GetCreditNotes.service.ts | 12 ++- .../CreditNoteApplySyncCredit.service.ts | 7 +- .../CreditNoteApplySyncInvoices.service.ts | 19 ++-- .../CreditNoteApplyToInvoices.service.ts | 16 ++-- ...DeleteCreditNoteApplyToInvoices.service.ts | 20 ++-- .../DeleteCustomerLinkedCreditNote.service.ts | 5 +- ...itNoteAssociatedAppliedInvoices.service.ts | 16 ++-- ...itNoteAssociatedInvoicesToApply.service.ts | 5 +- .../commands/ActivateCustomer.service.ts | 7 +- .../commands/CreateCustomer.service.ts | 11 ++- .../commands/CreateEditCustomerDTO.service.ts | 2 +- .../commands/DeleteCustomer.service.ts | 19 ++-- .../commands/EditCustomer.service.ts | 11 ++- .../EditOpeningBalanceCustomer.service.ts | 9 +- .../Customers/queries/GetCustomer.service.ts | 13 ++- .../Customers/queries/GetCustomers.service.ts | 8 +- .../src/modules/Expenses/Expenses.module.ts | 5 +- .../commands/CreateExpense.service.ts | 11 ++- .../commands/DeleteExpense.service.ts | 16 ++-- .../Expenses/commands/EditExpense.service.ts | 14 +-- .../commands/PublishExpense.service.ts | 9 +- .../Expenses/queries/GetExpense.service.ts | 5 +- .../Expenses/queries/GetExpenses.service.ts | 18 ++-- .../subscribers/ExpenseGLEntries.service.ts | 7 +- .../CashFlowStatement/CashFlowRepository.ts | 71 ++++++++------- .../CashFlowStatement/CashFlowTable.ts | 4 +- .../CustomerBalanceSummaryRepository.ts | 15 +-- .../PurchasesByItems.service.ts | 23 +++-- .../SalesByItems/SalesByItemsService.ts | 29 +++--- .../TransactionsByCustomersRepository.ts | 38 ++++---- .../TransactionsByReferenceRepository.ts | 9 +- .../TransactionsByVendorRepository.ts | 29 +++--- .../TrialBalanceSheetRepository.ts | 29 +++--- .../InventoryAdjustments.module.ts | 2 +- .../CreateQuickInventoryAdjustment.service.ts | 15 +-- .../DeleteInventoryAdjustment.service.ts | 15 ++- .../PublishInventoryAdjustment.service.ts | 11 ++- .../ledger/InventoryAdjustmentsGLEntries.ts | 8 +- .../queries/GetInventoryAdjustment.service.ts | 7 +- .../GetInventoryAdjustments.service.ts | 9 +- .../InventoryCost/InventoryCost.module.ts | 3 +- .../InventoryCost/InventoryCostMethod.ts | 15 ++- .../InventoryItemsQuantitySync.service.ts | 6 +- .../ItemCategories/ItemCategory.interfaces.ts | 2 +- .../ItemCategories/ItemCategory.module.ts | 2 +- .../CommandItemCategoryValidator.service.ts | 17 ++-- .../commands/CreateItemCategory.service.ts | 11 ++- .../commands/DeleteItemCategory.service.ts | 11 ++- .../commands/EditItemCategory.service.ts | 6 +- .../queries/GetItemCategories.service.ts | 20 ++-- .../queries/GetItemCategory.service.ts | 5 +- .../src/modules/Items/ActivateItem.service.ts | 10 +- .../src/modules/Items/CreateItem.service.ts | 11 ++- .../src/modules/Items/DeleteItem.service.ts | 13 +-- .../src/modules/Items/EditItem.service.ts | 7 +- .../src/modules/Items/GetItem.service.ts | 6 +- .../src/modules/Items/GetItems.service.ts | 6 +- .../modules/Items/InactivateItem.service.ts | 10 +- .../modules/Items/ItemTransactions.service.ts | 15 ++- .../modules/Items/ItemValidator.service.ts | 65 ++++++++----- .../src/modules/Items/ItemsEntries.service.ts | 30 +++--- .../Ledger/LedgerContactStorage.service.ts | 9 +- .../Ledger/LedgerEntriesStorage.service.ts | 14 ++- .../modules/Ledger/LedgerStorage.service.ts | 7 +- .../Ledger/LedgerStorageRevert.service.ts | 11 ++- .../Ledger/LedgetAccountStorage.service.ts | 14 +-- .../CommandManualJournalValidators.service.ts | 35 +++---- .../commands/CreateManualJournal.service.ts | 10 +- .../commands/DeleteManualJournal.service.ts | 14 ++- .../commands/EditManualJournal.service.ts | 15 +-- .../commands/ManualJournalGLEntries.ts | 5 +- .../commands/PublishManualJournal.service.ts | 17 ++-- .../queries/GetManualJournal.service.ts | 5 +- .../queries/GetManualJournals.service.ts | 7 +- .../commands/CreatePaymentReceived.serivce.ts | 9 +- .../commands/DeletePaymentReceived.service.ts | 13 ++- .../commands/EditPaymentReceived.service.ts | 13 ++- .../commands/PaymentReceivedDTOTransformer.ts | 22 +++-- .../PaymentReceivedInvoiceSync.service.ts | 11 ++- .../PaymentReceivedMailNotification.ts | 7 +- .../PaymentReceivedValidators.service.ts | 81 +++++++++-------- .../queries/GetPaymentReceived.service.ts | 12 ++- .../GetPaymentReceivedInvoices.service.ts | 9 +- .../queries/GetPaymentReceivedPdf.service.ts | 9 +- .../GetPaymentReceivedState.service.ts | 5 +- .../queries/GetPaymentsReceived.service.ts | 7 +- .../queries/PaymentsReceivedPages.service.ts | 11 ++- .../BrandingTemplateDTOTransformer.ts | 7 +- .../AssignPdfTemplateDefault.service.ts | 57 ++++++------ .../commands/CreatePdfTemplate.service.ts | 7 +- .../commands/DeletePdfTemplate.service.ts | 10 +- .../commands/EditPdfTemplate.service.ts | 13 ++- .../queries/GetPdfTemplate.service.ts | 12 ++- .../queries/GetPdfTemplates.service.ts | 20 ++-- .../commands/ApproveSaleEstimate.service.ts | 8 +- .../commands/ConvetSaleEstimate.service.ts | 14 +-- .../commands/CreateSaleEstimate.service.ts | 13 ++- .../commands/DeleteSaleEstimate.service.ts | 14 ++- .../commands/DeliverSaleEstimate.service.ts | 8 +- .../commands/EditSaleEstimate.service.ts | 11 ++- .../commands/RejectSaleEstimate.service.ts | 18 ++-- .../SaleEstimateDTOTransformer.service.ts | 22 +++-- .../SaleEstimateValidators.service.ts | 7 +- .../commands/SendSaleEstimateMail.ts | 6 +- .../UnlinkConvertedSaleEstimate.service.ts | 8 +- .../queries/GetSaleEstimate.service.ts | 11 ++- .../queries/GetSaleEstimatePdf.ts | 18 ++-- .../queries/GetSaleEstimateState.service.ts | 5 +- .../queries/GetSaleEstimates.service.ts | 16 ++-- .../modules/SaleInvoices/SaleInvoice.types.ts | 9 +- .../SaleInvoices/SaleInvoices.controller.ts | 8 +- .../SaleInvoices/SaleInvoices.module.ts | 2 +- ...ommandSaleInvoiceDTOTransformer.service.ts | 4 +- .../CommandSaleInvoiceValidators.service.ts | 7 +- .../commands/CreateSaleInvoice.service.ts | 18 ++-- .../commands/DeleteSaleInvoice.service.ts | 17 ++-- .../commands/DeliverSaleInvoice.service.ts | 8 +- .../commands/EditSaleInvoice.service.ts | 14 +-- .../GenerateInvoicePaymentLink.service.ts | 23 +++-- .../SendInvoiceInvoiceMailCommon.service.ts | 6 +- .../commands/SendSaleInvoiceMail.ts | 16 +++- .../commands/WriteoffSaleInvoice.service.ts | 9 +- .../writeoff/SaleInvoiceWriteoffGLStorage.ts | 9 +- .../SaleInvoices/ledger/InvoiceGLEntries.ts | 5 +- .../SendSaleInvoiceMail.processor.ts | 13 ++- .../queries/GetInvoicePayments.service.ts | 7 +- .../queries/GetSaleInvoice.service.ts | 5 +- .../GetSaleInvoiceMailState.service.ts | 5 +- .../queries/GetSaleInvoiceState.service.ts | 5 +- .../queries/GetSaleInvoicesPayable.service.ts | 5 +- .../queries/SaleInvoicePdf.service.ts | 9 +- .../commands/CloseSaleReceipt.service.ts | 11 ++- .../commands/CreateSaleReceipt.service.ts | 15 +-- .../commands/DeleteSaleReceipt.service.ts | 11 ++- .../commands/EditSaleReceipt.service.ts | 11 ++- .../SaleReceiptDTOTransformer.service.ts | 5 +- .../commands/SaleReceiptMailNotification.ts | 19 +++- .../commands/SaleReceiptValidators.service.ts | 20 ++-- .../ledger/SaleReceiptGLEntries.ts | 20 ++-- .../queries/GetSaleReceipt.service.ts | 6 +- .../queries/GetSaleReceiptState.service.ts | 5 +- .../queries/GetSaleReceipts.service.ts | 5 +- .../queries/SaleReceiptsPdf.service.ts | 11 ++- .../SaleReceipts/types/SaleReceipts.types.ts | 11 ++- .../CreateStripeAccountService.ts | 7 +- .../StripePayment/ExchangeStripeOauthToken.ts | 7 +- .../subscribers/SeedStripeAccounts.ts | 11 ++- .../subscribers/StripeWebhooksSubscriber.ts | 7 +- .../interceptors/Subscription.guard.ts | 7 +- .../modules/System/models/TenantBaseModel.ts | 2 + .../ItemEntriesTaxTransactions.service.ts | 64 +++++++------ .../commands/ActivateTaxRate.service.ts | 7 +- .../CommandTaxRatesValidator.service.ts | 7 +- .../commands/CreateTaxRate.service.ts | 45 +++++---- .../commands/DeleteTaxRate.service.ts | 7 +- .../TaxRates/commands/EditTaxRate.service.ts | 42 +++++---- .../TaxRates/commands/InactivateTaxRate.ts | 7 +- .../TaxRates/queries/GetTaxRate.service.ts | 10 +- .../TaxRates/queries/GetTaxRates.service.ts | 6 +- .../Tenancy/TenancyDB/TenancyDB.module.ts | 28 +++--- .../Tenancy/TenancyModels/Tenancy.module.ts | 24 ++--- .../commands/CreateVendorCredit.service.ts | 10 +- .../commands/DeleteVendorCredit.service.ts | 26 ++++-- .../commands/EditVendorCredit.service.ts | 11 ++- .../commands/OpenVendorCredit.service.ts | 8 +- .../commands/VendorCreditGLEntries.ts | 7 +- .../queries/GetVendorCredit.service.ts | 5 +- .../queries/GetVendorCredits.service.ts | 5 +- .../ApplyVendorCreditSyncBills.service.ts | 7 +- .../ApplyVendorCreditSyncInvoiced.service.ts | 15 +-- .../ApplyVendorCreditToBills.service.ts | 15 +-- .../DeleteApplyVendorCreditToBill.service.ts | 15 +-- .../GetAppliedBillsToVendorCredit.service.ts | 11 ++- .../GetVendorCreditToApplyBills.service.ts | 12 ++- .../CreateRefundVendorCredit.service.ts | 15 +-- .../DeleteRefundVendorCredit.service.ts | 9 +- .../RefundSyncCreditRefundedAmount.service.ts | 7 +- .../RefundSyncVendorCreditBalance.service.ts | 11 ++- .../commands/RefundVendorCredit.service.ts | 11 ++- .../queries/GetRefundVendorCredit.service.ts | 11 ++- .../queries/GetRefundVendorCredits.service.ts | 11 ++- .../commands/ActivateVendor.service.ts | 7 +- .../Vendors/commands/CreateVendor.service.ts | 11 ++- .../Vendors/commands/DeleteVendor.service.ts | 7 +- .../EditOpeningBalanceVendor.service.ts | 7 +- .../Vendors/commands/EditVendor.service.ts | 8 +- .../src/modules/Vendors/queries/GetVendor.ts | 6 +- .../Vendors/queries/GetVendors.service.ts | 7 +- .../Warehouses/Items/GetItemWarehouses.ts | 11 ++- .../modules/Warehouses/Warehouses.module.ts | 4 +- .../commands/CreateWarehouse.service.ts | 13 ++- .../commands/DeleteItemWarehousesQuantity.ts | 7 +- .../commands/DeleteWarehouse.service.ts | 7 +- .../commands/EditWarehouse.service.ts | 5 +- .../commands/WarehouseMarkPrimary.service.ts | 13 +-- .../commands/WarehouseValidator.service.ts | 11 ++- .../Warehouses/queries/GetWarehouse.ts | 5 +- .../Warehouses/queries/GetWarehouses.ts | 5 +- .../src/services/Items/ItemsEntriesService.ts | 41 ++++----- pnpm-lock.yaml | 14 +-- 302 files changed, 2396 insertions(+), 1677 deletions(-) create mode 100644 packages/server-nest/src/interfaces/Tenant.ts diff --git a/packages/server-nest/package.json b/packages/server-nest/package.json index d99359c1f..0dd77ccbe 100644 --- a/packages/server-nest/package.json +++ b/packages/server-nest/package.json @@ -62,7 +62,7 @@ "moment": "^2.30.1", "mysql": "^2.18.1", "mysql2": "^3.11.3", - "nestjs-cls": "^4.4.1", + "nestjs-cls": "^5.2.0", "nestjs-i18n": "^10.4.9", "nodemailer": "^6.3.0", "object-hash": "^2.0.3", diff --git a/packages/server-nest/src/interfaces/Account.ts b/packages/server-nest/src/interfaces/Account.ts index 5124f7967..9fb905e3f 100644 --- a/packages/server-nest/src/interfaces/Account.ts +++ b/packages/server-nest/src/interfaces/Account.ts @@ -117,26 +117,22 @@ export interface IAccountsTypesService { } export interface IAccountEventCreatingPayload { - tenantId: number; accountDTO: any; trx: Knex.Transaction; } export interface IAccountEventCreatedPayload { - tenantId: number; account: IAccount; accountId: number; trx: Knex.Transaction; } export interface IAccountEventEditedPayload { - tenantId: number; account: IAccount; oldAccount: IAccount; trx: Knex.Transaction; } export interface IAccountEventDeletedPayload { - tenantId: number; accountId: number; oldAccount: IAccount; trx: Knex.Transaction; diff --git a/packages/server-nest/src/interfaces/Tenant.ts b/packages/server-nest/src/interfaces/Tenant.ts new file mode 100644 index 000000000..b99d9bdfa --- /dev/null +++ b/packages/server-nest/src/interfaces/Tenant.ts @@ -0,0 +1,4 @@ +export interface TenantJobPayload { + organizationId: string; + userId: number; +} diff --git a/packages/server-nest/src/modules/Accounts/Accounts.module.ts b/packages/server-nest/src/modules/Accounts/Accounts.module.ts index 7b54096d7..7ed6c4f12 100644 --- a/packages/server-nest/src/modules/Accounts/Accounts.module.ts +++ b/packages/server-nest/src/modules/Accounts/Accounts.module.ts @@ -22,7 +22,7 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module'; const models = [RegisterTenancyModel(BankAccount)]; @Module({ - imports: [TenancyDatabaseModule, DynamicListModule], + imports: [TenancyDatabaseModule, DynamicListModule, ...models], controllers: [AccountsController], providers: [ AccountsApplication, @@ -38,7 +38,6 @@ const models = [RegisterTenancyModel(BankAccount)]; GetAccountTypesService, GetAccountTransactionsService, GetAccountsService, - ...models, ], exports: [AccountRepository, CreateAccountService, ...models], }) diff --git a/packages/server-nest/src/modules/Accounts/ActivateAccount.service.ts b/packages/server-nest/src/modules/Accounts/ActivateAccount.service.ts index a18b98255..d08602938 100644 --- a/packages/server-nest/src/modules/Accounts/ActivateAccount.service.ts +++ b/packages/server-nest/src/modules/Accounts/ActivateAccount.service.ts @@ -6,16 +6,17 @@ import { AccountRepository } from './repositories/Account.repository'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ActivateAccount { constructor( private readonly eventEmitter: EventEmitter2, private readonly uow: UnitOfWork, + private readonly accountRepository: AccountRepository, @Inject(Account.name) - private readonly accountModel: typeof Account, - private readonly accountRepository: AccountRepository, + private readonly accountModel: TenantModelProxy, ) {} /** @@ -25,7 +26,7 @@ export class ActivateAccount { */ public activateAccount = async (accountId: number, activate?: boolean) => { // Retrieve the given account or throw not found error. - const oldAccount = await this.accountModel + const oldAccount = await this.accountModel() .query() .findById(accountId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/Accounts/CommandAccountValidators.service.ts b/packages/server-nest/src/modules/Accounts/CommandAccountValidators.service.ts index 4d08ce8d4..882954995 100644 --- a/packages/server-nest/src/modules/Accounts/CommandAccountValidators.service.ts +++ b/packages/server-nest/src/modules/Accounts/CommandAccountValidators.service.ts @@ -9,12 +9,13 @@ import { AccountRepository } from './repositories/Account.repository'; import { AccountTypesUtils } from './utils/AccountType.utils'; import { CreateAccountDTO } from './CreateAccount.dto'; import { EditAccountDTO } from './EditAccount.dto'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable({ scope: Scope.REQUEST }) export class CommandAccountValidators { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, private readonly accountRepository: AccountRepository, ) {} @@ -66,7 +67,7 @@ export class CommandAccountValidators { accountId: number, notAccountId?: number, ) { - const parentAccount = await this.accountModel + const parentAccount = await this.accountModel() .query() .findById(accountId) .onBuild((query) => { @@ -89,7 +90,7 @@ export class CommandAccountValidators { accountCode: string, notAccountId?: number, ) { - const account = await this.accountModel + const account = await this.accountModel() .query() .where('code', accountCode) .onBuild((query) => { diff --git a/packages/server-nest/src/modules/Accounts/CreateAccount.service.ts b/packages/server-nest/src/modules/Accounts/CreateAccount.service.ts index fb4ed6b97..732bc64a5 100644 --- a/packages/server-nest/src/modules/Accounts/CreateAccount.service.ts +++ b/packages/server-nest/src/modules/Accounts/CreateAccount.service.ts @@ -14,12 +14,13 @@ import { TenancyContext } from '../Tenancy/TenancyContext.service'; import { events } from '@/common/events/events'; import { CreateAccountDTO } from './CreateAccount.dto'; import { PartialModelObject } from 'objection'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class CreateAccountService { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, private readonly eventEmitter: EventEmitter2, private readonly uow: UnitOfWork, private readonly validator: CommandAccountValidators, @@ -121,9 +122,11 @@ export class CreateAccountService { } as IAccountEventCreatingPayload); // Inserts account to the storage. - const account = await this.accountModel.query().insert({ - ...accountInputModel, - }); + const account = await this.accountModel() + .query() + .insert({ + ...accountInputModel, + }); // Triggers `onAccountCreated` event. await this.eventEmitter.emitAsync(events.accounts.onCreated, { account, diff --git a/packages/server-nest/src/modules/Accounts/DeleteAccount.service.ts b/packages/server-nest/src/modules/Accounts/DeleteAccount.service.ts index 9479d6ea1..40f3978bd 100644 --- a/packages/server-nest/src/modules/Accounts/DeleteAccount.service.ts +++ b/packages/server-nest/src/modules/Accounts/DeleteAccount.service.ts @@ -7,11 +7,14 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { IAccountEventDeletedPayload } from './Accounts.types'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class DeleteAccount { constructor( - @Inject(Account.name) private accountModel: typeof Account, + @Inject(Account.name) + private accountModel: TenantModelProxy, + private eventEmitter: EventEmitter2, private uow: UnitOfWork, private validator: CommandAccountValidators, @@ -38,7 +41,7 @@ export class DeleteAccount { ? parentAccountId : [parentAccountId]; - await this.accountModel + await this.accountModel() .query(trx) .whereIn('parent_account_id', accountsIds) .patch({ parentAccountId: null }); @@ -50,7 +53,7 @@ export class DeleteAccount { */ public deleteAccount = async (accountId: number): Promise => { // Retrieve account or not found service error. - const oldAccount = await this.accountModel.query().findById(accountId); + const oldAccount = await this.accountModel().query().findById(accountId); // Authorize before delete account. await this.authorize(accountId, oldAccount); @@ -67,7 +70,7 @@ export class DeleteAccount { await this.unassociateChildrenAccountsFromParent(accountId, trx); // Deletes account by the given id. - await this.accountModel.query(trx).deleteById(accountId); + await this.accountModel().query(trx).deleteById(accountId); // Triggers `onAccountDeleted` event. await this.eventEmitter.emitAsync(events.accounts.onDeleted, { diff --git a/packages/server-nest/src/modules/Accounts/EditAccount.service.ts b/packages/server-nest/src/modules/Accounts/EditAccount.service.ts index 3b5386381..330f72496 100644 --- a/packages/server-nest/src/modules/Accounts/EditAccount.service.ts +++ b/packages/server-nest/src/modules/Accounts/EditAccount.service.ts @@ -6,6 +6,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { EditAccountDTO } from './EditAccount.dto'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class EditAccount { @@ -15,7 +16,7 @@ export class EditAccount { private readonly validator: CommandAccountValidators, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) {} /** @@ -66,7 +67,7 @@ export class EditAccount { accountDTO: EditAccountDTO, ): Promise { // Retrieve the old account or throw not found service error. - const oldAccount = await this.accountModel + const oldAccount = await this.accountModel() .query() .findById(accountId) .throwIfNotFound(); @@ -82,7 +83,7 @@ export class EditAccount { accountDTO, }); // Update the account on the storage. - const account = await this.accountModel + const account = await this.accountModel() .query(trx) .findById(accountId) .updateAndFetch({ ...accountDTO }); diff --git a/packages/server-nest/src/modules/Accounts/GetAccount.service.ts b/packages/server-nest/src/modules/Accounts/GetAccount.service.ts index 23cbceb18..3f2c3b56b 100644 --- a/packages/server-nest/src/modules/Accounts/GetAccount.service.ts +++ b/packages/server-nest/src/modules/Accounts/GetAccount.service.ts @@ -5,12 +5,13 @@ import { AccountRepository } from './repositories/Account.repository'; import { TransformerInjectable } from '../Transformer/TransformerInjectable.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class GetAccount { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, private readonly accountRepository: AccountRepository, private readonly transformer: TransformerInjectable, private readonly eventEmitter: EventEmitter2, @@ -22,7 +23,7 @@ export class GetAccount { */ public getAccount = async (accountId: number) => { // Find the given account or throw not found error. - const account = await this.accountModel + const account = await this.accountModel() .query() .findById(accountId) .withGraphFetched('plaidItem') diff --git a/packages/server-nest/src/modules/Accounts/GetAccountTransactions.service.ts b/packages/server-nest/src/modules/Accounts/GetAccountTransactions.service.ts index bb92df38c..24e4bab22 100644 --- a/packages/server-nest/src/modules/Accounts/GetAccountTransactions.service.ts +++ b/packages/server-nest/src/modules/Accounts/GetAccountTransactions.service.ts @@ -7,6 +7,7 @@ import { AccountTransaction } from './models/AccountTransaction.model'; import { Account } from './models/Account.model'; import { Inject, Injectable } from '@nestjs/common'; import { TransformerInjectable } from '../Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class GetAccountTransactionsService { @@ -14,10 +15,12 @@ export class GetAccountTransactionsService { private readonly transformer: TransformerInjectable, @Inject(AccountTransaction.name) - private readonly accountTransaction: typeof AccountTransaction, + private readonly accountTransaction: TenantModelProxy< + typeof AccountTransaction + >, @Inject(Account.name) - private readonly account: typeof Account, + private readonly account: TenantModelProxy, ) {} /** @@ -29,9 +32,9 @@ export class GetAccountTransactionsService { ): Promise => { // Retrieve the given account or throw not found error. if (filter.accountId) { - await this.account.query().findById(filter.accountId).throwIfNotFound(); + await this.account().query().findById(filter.accountId).throwIfNotFound(); } - const transactions = await this.accountTransaction + const transactions = await this.accountTransaction() .query() .onBuild((query) => { query.orderBy('date', 'DESC'); diff --git a/packages/server-nest/src/modules/Accounts/GetAccounts.service.ts b/packages/server-nest/src/modules/Accounts/GetAccounts.service.ts index b029cef20..d2741712a 100644 --- a/packages/server-nest/src/modules/Accounts/GetAccounts.service.ts +++ b/packages/server-nest/src/modules/Accounts/GetAccounts.service.ts @@ -7,6 +7,7 @@ import { TransformerInjectable } from '../Transformer/TransformerInjectable.serv import { Account } from './models/Account.model'; import { AccountRepository } from './repositories/Account.repository'; import { IFilterMeta } from '@/interfaces/Model'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class GetAccountsService { @@ -16,7 +17,7 @@ export class GetAccountsService { private readonly accountRepository: AccountRepository, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) {} /** @@ -32,14 +33,16 @@ export class GetAccountsService { // Dynamic list service. const dynamicList = await this.dynamicListService.dynamicList( - this.accountModel, + this.accountModel(), filter, ); // Retrieve accounts model based on the given query. - const accounts = await this.accountModel.query().onBuild((builder) => { - dynamicList.buildQuery()(builder); - builder.modify('inactiveMode', filter.inactiveMode); - }); + const accounts = await this.accountModel() + .query() + .onBuild((builder) => { + dynamicList.buildQuery()(builder); + builder.modify('inactiveMode', filter.inactiveMode); + }); const accountsGraph = await this.accountRepository.getDependencyGraph(); // Retrieves the transformed accounts collection. diff --git a/packages/server-nest/src/modules/App/App.module.ts b/packages/server-nest/src/modules/App/App.module.ts index 2efa6e7f1..48eb37bd1 100644 --- a/packages/server-nest/src/modules/App/App.module.ts +++ b/packages/server-nest/src/modules/App/App.module.ts @@ -117,6 +117,8 @@ import { StripePaymentModule } from '../StripePayment/StripePayment.module'; cls.set('organizationId', req.headers['organization-id']); cls.set('userId', 1); }, + generateId: true, + saveReq: true, }, }), TenancyDatabaseModule, @@ -152,13 +154,13 @@ import { StripePaymentModule } from '../StripePayment/StripePayment.module'; BankingTransactionsModule, BankingTransactionsExcludeModule, BankingTransactionsRegonizeModule, - BankingMatchingModule, - TransactionsLockingModule, - SettingsModule, + // BankingMatchingModule, + // TransactionsLockingModule, + // SettingsModule, InventoryAdjustmentsModule, PostHogModule, EventTrackerModule, - FinancialStatementsModule, + // FinancialStatementsModule, StripePaymentModule, ], controllers: [AppController], diff --git a/packages/server-nest/src/modules/BankRules/BankRules.module.ts b/packages/server-nest/src/modules/BankRules/BankRules.module.ts index bfba0146e..5b2fcc0de 100644 --- a/packages/server-nest/src/modules/BankRules/BankRules.module.ts +++ b/packages/server-nest/src/modules/BankRules/BankRules.module.ts @@ -20,9 +20,8 @@ const models = [ @Module({ controllers: [BankRulesController], - imports: [forwardRef(() => BankingTransactionsRegonizeModule)], + imports: [forwardRef(() => BankingTransactionsRegonizeModule), ...models], providers: [ - ...models, CreateBankRuleService, EditBankRuleService, DeleteBankRuleService, @@ -30,7 +29,7 @@ const models = [ GetBankRuleService, GetBankRulesService, BankRulesApplication, - UnlinkBankRuleOnDeleteBankRuleSubscriber + UnlinkBankRuleOnDeleteBankRuleSubscriber, ], exports: [...models, DeleteBankRuleService, DeleteBankRulesService], }) diff --git a/packages/server-nest/src/modules/BankRules/commands/DeleteBankRule.service.ts b/packages/server-nest/src/modules/BankRules/commands/DeleteBankRule.service.ts index da880ac2f..7f51c1379 100644 --- a/packages/server-nest/src/modules/BankRules/commands/DeleteBankRule.service.ts +++ b/packages/server-nest/src/modules/BankRules/commands/DeleteBankRule.service.ts @@ -9,13 +9,16 @@ import { BankRuleCondition } from '../models/BankRuleCondition'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteBankRuleService { constructor( - @Inject(BankRule.name) private bankRuleModel: typeof BankRule, + @Inject(BankRule.name) + private bankRuleModel: TenantModelProxy, + @Inject(BankRuleCondition.name) - private bankRuleConditionModel: typeof BankRuleCondition, + private bankRuleConditionModel: TenantModelProxy, private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, @@ -30,7 +33,7 @@ export class DeleteBankRuleService { ruleId: number, trx?: Knex.Transaction, ): Promise { - const oldBankRule = await this.bankRuleModel + const oldBankRule = await this.bankRuleModel() .query() .findById(ruleId) .throwIfNotFound(); @@ -43,11 +46,12 @@ export class DeleteBankRuleService { trx, } as IBankRuleEventDeletingPayload); - await this.bankRuleConditionModel + await this.bankRuleConditionModel() .query(trx) .where('ruleId', ruleId) .delete(); - await this.bankRuleModel.query(trx).findById(ruleId).delete(); + + await this.bankRuleModel().query(trx).findById(ruleId).delete(); // Triggers `onBankRuleDeleted` event. await this.eventPublisher.emitAsync(events.bankRules.onDeleted, { diff --git a/packages/server-nest/src/modules/BankRules/commands/EditBankRule.service.ts b/packages/server-nest/src/modules/BankRules/commands/EditBankRule.service.ts index b1ce8654b..1becf17d2 100644 --- a/packages/server-nest/src/modules/BankRules/commands/EditBankRule.service.ts +++ b/packages/server-nest/src/modules/BankRules/commands/EditBankRule.service.ts @@ -8,6 +8,7 @@ import { BankRule } from '../models/BankRule'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditBankRuleService { @@ -15,7 +16,8 @@ export class EditBankRuleService { private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, - @Inject(BankRule.name) private bankRuleModel: typeof BankRule, + @Inject(BankRule.name) + private bankRuleModel: TenantModelProxy, ) {} /** @@ -34,11 +36,9 @@ export class EditBankRuleService { * @param {number} ruleId - * @param {IEditBankRuleDTO} editBankDTO */ - public async editBankRule( - ruleId: number, - editRuleDTO: IEditBankRuleDTO - ) { - const oldBankRule = await this.bankRuleModel.query() + public async editBankRule(ruleId: number, editRuleDTO: IEditBankRuleDTO) { + const oldBankRule = await this.bankRuleModel() + .query() .findById(ruleId) .withGraphFetched('conditions') .throwIfNotFound(); @@ -55,10 +55,12 @@ export class EditBankRuleService { } as IBankRuleEventEditingPayload); // Updates the given bank rule. - const bankRule = await this.bankRuleModel.query(trx).upsertGraphAndFetch({ - ...tranformDTO, - id: ruleId, - }); + const bankRule = await this.bankRuleModel() + .query(trx) + .upsertGraphAndFetch({ + ...tranformDTO, + id: ruleId, + }); // Triggers `onBankRuleEdited` event. await this.eventPublisher.emitAsync(events.bankRules.onEdited, { oldBankRule, diff --git a/packages/server-nest/src/modules/BankRules/queries/GetBankRule.service.ts b/packages/server-nest/src/modules/BankRules/queries/GetBankRule.service.ts index 49181e729..4fc2cf514 100644 --- a/packages/server-nest/src/modules/BankRules/queries/GetBankRule.service.ts +++ b/packages/server-nest/src/modules/BankRules/queries/GetBankRule.service.ts @@ -3,11 +3,13 @@ import { GetBankRuleTransformer } from './GetBankRuleTransformer'; import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service'; import { BankRule } from '../models/BankRule'; import { GetBankRulesTransformer } from './GetBankRulesTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetBankRuleService { constructor( - @Inject(BankRule.name) private bankRuleModel: typeof BankRule, + @Inject(BankRule.name) + private bankRuleModel: TenantModelProxy, private transformer: TransformerInjectable, ) {} @@ -17,15 +19,12 @@ export class GetBankRuleService { * @returns {Promise} */ async getBankRule(ruleId: number): Promise { - const bankRule = await this.bankRuleModel + const bankRule = await this.bankRuleModel() .query() .findById(ruleId) .withGraphFetched('conditions') .withGraphFetched('assignAccount'); - return this.transformer.transform( - bankRule, - new GetBankRulesTransformer() - ); + return this.transformer.transform(bankRule, new GetBankRulesTransformer()); } } diff --git a/packages/server-nest/src/modules/BankRules/queries/GetBankRules.service.ts b/packages/server-nest/src/modules/BankRules/queries/GetBankRules.service.ts index 2dbec718a..5d4ce4280 100644 --- a/packages/server-nest/src/modules/BankRules/queries/GetBankRules.service.ts +++ b/packages/server-nest/src/modules/BankRules/queries/GetBankRules.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { GetBankRulesTransformer } from './GetBankRulesTransformer'; import { BankRule } from '../models/BankRule'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetBankRulesService { @@ -9,7 +10,7 @@ export class GetBankRulesService { private transformer: TransformerInjectable, @Inject(BankRule.name) - private bankRuleModel: typeof BankRule, + private bankRuleModel: TenantModelProxy, ) {} /** @@ -17,14 +18,11 @@ export class GetBankRulesService { * @returns {Promise} */ public async getBankRules(): Promise { - const bankRule = await this.bankRuleModel + const bankRule = await this.bankRuleModel() .query() .withGraphFetched('conditions') .withGraphFetched('assignAccount'); - return this.transformer.transform( - bankRule, - new GetBankRulesTransformer() - ); + return this.transformer.transform(bankRule, new GetBankRulesTransformer()); } } diff --git a/packages/server-nest/src/modules/BankingAccounts/commands/DisconnectBankAccount.service.ts b/packages/server-nest/src/modules/BankingAccounts/commands/DisconnectBankAccount.service.ts index 214ef4661..2f656594e 100644 --- a/packages/server-nest/src/modules/BankingAccounts/commands/DisconnectBankAccount.service.ts +++ b/packages/server-nest/src/modules/BankingAccounts/commands/DisconnectBankAccount.service.ts @@ -14,6 +14,7 @@ import { ServiceError } from '@/modules/Items/ServiceError'; import { events } from '@/common/events/events'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { PLAID_CLIENT } from '@/modules/Plaid/Plaid.module'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DisconnectBankAccountService { @@ -21,9 +22,12 @@ export class DisconnectBankAccountService { private eventPublisher: EventEmitter2, private uow: UnitOfWork, - @Inject(Account.name) private accountModel: typeof Account, - @Inject(PlaidItem.name) private plaidItemModel: typeof PlaidItem, @Inject(PLAID_CLIENT) private plaidClient: PlaidApi, + @Inject(Account.name) + private accountModel: TenantModelProxy, + + @Inject(PlaidItem.name) + private plaidItemModel: TenantModelProxy, ) {} /** @@ -33,7 +37,7 @@ export class DisconnectBankAccountService { */ public async disconnectBankAccount(bankAccountId: number) { // Retrieve the bank account or throw not found error. - const account = await this.accountModel + const account = await this.accountModel() .query() .findById(bankAccountId) .whereIn('account_type', [ACCOUNT_TYPE.CASH, ACCOUNT_TYPE.BANK]) @@ -52,10 +56,13 @@ export class DisconnectBankAccountService { } as IBankAccountDisconnectingEventPayload); // Remove the Plaid item from the system. - await this.plaidItemModel.query(trx).findById(account.plaidItemId).delete(); + await this.plaidItemModel() + .query(trx) + .findById(account.plaidItemId) + .delete(); // Remove the plaid item association to the bank account. - await this.accountModel.query(trx).findById(bankAccountId).patch({ + await this.accountModel().query(trx).findById(bankAccountId).patch({ plaidAccountId: null, plaidItemId: null, isFeedsActive: false, diff --git a/packages/server-nest/src/modules/BankingAccounts/commands/PauseBankAccountFeeds.service.ts b/packages/server-nest/src/modules/BankingAccounts/commands/PauseBankAccountFeeds.service.ts index 45867bf64..bb1a45843 100644 --- a/packages/server-nest/src/modules/BankingAccounts/commands/PauseBankAccountFeeds.service.ts +++ b/packages/server-nest/src/modules/BankingAccounts/commands/PauseBankAccountFeeds.service.ts @@ -5,23 +5,26 @@ import { ServiceError } from '@/modules/Items/ServiceError'; import { Account } from '@/modules/Accounts/models/Account.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { PlaidItem } from '@/modules/BankingPlaid/models/PlaidItem'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PauseBankAccountFeeds { constructor( - @Inject(Account.name) private accountModel: typeof Account, - @Inject(PlaidItem.name) private plaidItemModel: typeof PlaidItem, + @Inject(Account.name) + private accountModel: TenantModelProxy, + @Inject(PlaidItem.name) + private plaidItemModel: TenantModelProxy, private uow: UnitOfWork, ) {} /** - * Pauses the bankfeed syncing of the given bank account. + * Pauses the bank feed syncing of the given bank account. * @param {number} bankAccountId * @returns {Promise} */ public async pauseBankAccountFeeds(bankAccountId: number) { - const oldAccount = await this.accountModel + const oldAccount = await this.accountModel() .query() .findById(bankAccountId) .withGraphFetched('plaidItem') @@ -36,7 +39,7 @@ export class PauseBankAccountFeeds { throw new ServiceError(ERRORS.BANK_ACCOUNT_FEEDS_ALREADY_PAUSED); } return this.uow.withTransaction(async (trx: Knex.Transaction) => { - await this.plaidItemModel + await this.plaidItemModel() .query(trx) .findById(oldAccount.plaidItem.id) .patch({ diff --git a/packages/server-nest/src/modules/BankingAccounts/commands/RefreshBankAccount.service.ts b/packages/server-nest/src/modules/BankingAccounts/commands/RefreshBankAccount.service.ts index 4bf063707..f230db815 100644 --- a/packages/server-nest/src/modules/BankingAccounts/commands/RefreshBankAccount.service.ts +++ b/packages/server-nest/src/modules/BankingAccounts/commands/RefreshBankAccount.service.ts @@ -4,12 +4,14 @@ import { Account } from '@/modules/Accounts/models/Account.model'; import { ServiceError } from '@/modules/Items/ServiceError'; import { PLAID_CLIENT } from '@/modules/Plaid/Plaid.module'; import { ERRORS } from '../types/BankAccounts.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RefreshBankAccountService { constructor( @Inject(PLAID_CLIENT) private plaidClient: PlaidApi, - @Inject(Account.name) private readonly accountModel: typeof Account, + @Inject(Account.name) + private readonly accountModel: TenantModelProxy, ) {} /** @@ -18,7 +20,7 @@ export class RefreshBankAccountService { * @returns {Promise} */ public async refreshBankAccount(bankAccountId: number) { - const bankAccount = await this.accountModel + const bankAccount = await this.accountModel() .query() .findById(bankAccountId) .withGraphFetched('plaidItem') diff --git a/packages/server-nest/src/modules/BankingAccounts/commands/ResumeBankAccountFeeds.service.ts b/packages/server-nest/src/modules/BankingAccounts/commands/ResumeBankAccountFeeds.service.ts index 8009dd8f4..e5f9b7343 100644 --- a/packages/server-nest/src/modules/BankingAccounts/commands/ResumeBankAccountFeeds.service.ts +++ b/packages/server-nest/src/modules/BankingAccounts/commands/ResumeBankAccountFeeds.service.ts @@ -5,12 +5,16 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { PlaidItem } from '@/modules/BankingPlaid/models/PlaidItem'; import { Account } from '@/modules/Accounts/models/Account.model'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ResumeBankAccountFeedsService { constructor( - @Inject(Account.name) private accountModel: typeof Account, - @Inject(PlaidItem.name) private plaidItemModel: typeof PlaidItem, + @Inject(Account.name) + private accountModel: TenantModelProxy, + + @Inject(PlaidItem.name) + private plaidItemModel: TenantModelProxy, private uow: UnitOfWork, ) {} @@ -21,7 +25,7 @@ export class ResumeBankAccountFeedsService { * @returns {Promise} */ public async resumeBankAccountFeeds(bankAccountId: number) { - const oldAccount = await this.accountModel + const oldAccount = await this.accountModel() .query() .findById(bankAccountId) .withGraphFetched('plaidItem'); @@ -35,7 +39,7 @@ export class ResumeBankAccountFeedsService { throw new ServiceError(ERRORS.BANK_ACCOUNT_FEEDS_ALREADY_RESUMED); } return this.uow.withTransaction(async (trx: Knex.Transaction) => { - await this.plaidItemModel + await this.plaidItemModel() .query(trx) .findById(oldAccount.plaidItem.id) .patch({ diff --git a/packages/server-nest/src/modules/BankingAccounts/queries/GetBankAccountSummary.ts b/packages/server-nest/src/modules/BankingAccounts/queries/GetBankAccountSummary.ts index f71ce5439..545e4f461 100644 --- a/packages/server-nest/src/modules/BankingAccounts/queries/GetBankAccountSummary.ts +++ b/packages/server-nest/src/modules/BankingAccounts/queries/GetBankAccountSummary.ts @@ -2,15 +2,18 @@ import { Inject, Injectable } from '@nestjs/common'; import { Account } from '@/modules/Accounts/models/Account.model'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { BaseModel } from '@/models/Model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetBankAccountSummary { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -19,7 +22,7 @@ export class GetBankAccountSummary { * @returns {Promise} */ public async getBankAccountSummary(bankAccountId: number) { - const bankAccount = await this.accountModel + const bankAccount = await this.accountModel() .query() .findById(bankAccountId) .throwIfNotFound(); @@ -41,60 +44,68 @@ export class GetBankAccountSummary { // Retrieves the uncategorized transactions count of the given bank account. const uncategorizedTranasctionsCount = - await this.uncategorizedBankTransactionModel.query().onBuild((q) => { - commonQuery(q); + await this.uncategorizedBankTransactionModel() + .query() + .onBuild((q) => { + commonQuery(q); - // Only the not matched bank transactions. - q.withGraphJoined('matchedBankTransactions'); - q.whereNull('matchedBankTransactions.id'); + // Only the not matched bank transactions. + q.withGraphJoined('matchedBankTransactions'); + q.whereNull('matchedBankTransactions.id'); - // Exclude the pending transactions. - q.modify('notPending'); + // Exclude the pending transactions. + q.modify('notPending'); - // Count the results. - q.count('uncategorized_cashflow_transactions.id as total'); - q.first(); - }); + // Count the results. + q.count('uncategorized_cashflow_transactions.id as total'); + q.first(); + }); // Retrives the recognized transactions count. const recognizedTransactionsCount = - await this.uncategorizedBankTransactionModel.query().onBuild((q) => { - commonQuery(q); + await this.uncategorizedBankTransactionModel() + .query() + .onBuild((q) => { + commonQuery(q); - q.withGraphJoined('recognizedTransaction'); - q.whereNotNull('recognizedTransaction.id'); + q.withGraphJoined('recognizedTransaction'); + q.whereNotNull('recognizedTransaction.id'); - // Exclude the pending transactions. - q.modify('notPending'); + // Exclude the pending transactions. + q.modify('notPending'); - // Count the results. - q.count('uncategorized_cashflow_transactions.id as total'); - q.first(); - }); + // Count the results. + q.count('uncategorized_cashflow_transactions.id as total'); + q.first(); + }); // Retrieves excluded transactions count. const excludedTransactionsCount = - await this.uncategorizedBankTransactionModel.query().onBuild((q) => { - q.where('accountId', bankAccountId); - q.modify('excluded'); + await this.uncategorizedBankTransactionModel() + .query() + .onBuild((q) => { + q.where('accountId', bankAccountId); + q.modify('excluded'); - // Exclude the pending transactions. - q.modify('notPending'); + // Exclude the pending transactions. + q.modify('notPending'); - // Count the results. - q.count('uncategorized_cashflow_transactions.id as total'); - q.first(); - }); + // Count the results. + q.count('uncategorized_cashflow_transactions.id as total'); + q.first(); + }); // Retrieves the pending transactions count. const pendingTransactionsCount = - await this.uncategorizedBankTransactionModel.query().onBuild((q) => { - q.where('accountId', bankAccountId); - q.modify('pending'); + await this.uncategorizedBankTransactionModel() + .query() + .onBuild((q) => { + q.where('accountId', bankAccountId); + q.modify('pending'); - // Count the results. - q.count('uncategorized_cashflow_transactions.id as total'); - q.first(); - }); + // Count the results. + q.count('uncategorized_cashflow_transactions.id as total'); + q.first(); + }); const totalUncategorizedTransactions = // @ts-ignore diff --git a/packages/server-nest/src/modules/BankingAccounts/subscribers/DeleteUncategorizedTransactionsOnAccountDeleting.ts b/packages/server-nest/src/modules/BankingAccounts/subscribers/DeleteUncategorizedTransactionsOnAccountDeleting.ts index c4ec04fa9..768b0af95 100644 --- a/packages/server-nest/src/modules/BankingAccounts/subscribers/DeleteUncategorizedTransactionsOnAccountDeleting.ts +++ b/packages/server-nest/src/modules/BankingAccounts/subscribers/DeleteUncategorizedTransactionsOnAccountDeleting.ts @@ -6,6 +6,7 @@ import { RevertRecognizedTransactionsService } from '@/modules/BankingTranasctio import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { DeleteBankRulesService } from '@/modules/BankRules/commands/DeleteBankRules.service'; import { BankRule } from '@/modules/BankRules/models/BankRule'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteUncategorizedTransactionsOnAccountDeleting { @@ -13,9 +14,13 @@ export class DeleteUncategorizedTransactionsOnAccountDeleting { private readonly deleteBankRules: DeleteBankRulesService, private readonly revertRecognizedTransactins: RevertRecognizedTransactionsService, - @Inject(BankRule.name) private bankRuleModel: typeof BankRule, + @Inject(BankRule.name) + private bankRuleModel: TenantModelProxy, + @Inject(UncategorizedBankTransaction.name) - private uncategorizedCashflowTransactionModel: typeof UncategorizedBankTransaction, + private uncategorizedCashflowTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -28,10 +33,9 @@ export class DeleteUncategorizedTransactionsOnAccountDeleting { oldAccount, trx, }: IAccountEventDeletePayload) { - const foundAssociatedRules = await this.bankRuleModel.query(trx).where( - 'applyIfAccountId', - oldAccount.id, - ); + const foundAssociatedRules = await this.bankRuleModel() + .query(trx) + .where('applyIfAccountId', oldAccount.id); const foundAssociatedRulesIds = foundAssociatedRules.map((rule) => rule.id); // Revert the recognized transactions of the given bank rules. @@ -41,15 +45,12 @@ export class DeleteUncategorizedTransactionsOnAccountDeleting { trx, ); // Delete the associated uncategorized transactions. - await this.uncategorizedCashflowTransactionModel + await this.uncategorizedCashflowTransactionModel() .query(trx) .where('accountId', oldAccount.id) .delete(); // Delete the given bank rules. - await this.deleteBankRules.deleteBankRules( - foundAssociatedRulesIds, - trx, - ); + await this.deleteBankRules.deleteBankRules(foundAssociatedRulesIds, trx); } } diff --git a/packages/server-nest/src/modules/BankingAccounts/subscribers/DisconnectPlaidItemOnAccountDeleted.ts b/packages/server-nest/src/modules/BankingAccounts/subscribers/DisconnectPlaidItemOnAccountDeleted.ts index 7c4bcf1e7..a4891b349 100644 --- a/packages/server-nest/src/modules/BankingAccounts/subscribers/DisconnectPlaidItemOnAccountDeleted.ts +++ b/packages/server-nest/src/modules/BankingAccounts/subscribers/DisconnectPlaidItemOnAccountDeleted.ts @@ -6,14 +6,20 @@ import { PlaidItem } from '@/modules/BankingPlaid/models/PlaidItem'; import { Account } from '@/modules/Accounts/models/Account.model'; import { PlaidApi } from 'plaid'; import { PLAID_CLIENT } from '@/modules/Plaid/Plaid.module'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DisconnectPlaidItemOnAccountDeleted { constructor( @Inject(PLAID_CLIENT) private plaidClient: PlaidApi, - @Inject(PlaidItem.name) private plaidItemModel: typeof PlaidItem, - @Inject(Account.name) private accountModel: typeof Account, + + @Inject(PlaidItem.name) + private plaidItemModel: TenantModelProxy, + + @Inject(Account.name) + private accountModel: TenantModelProxy, ) {} + /** * Deletes Plaid item from the system and Plaid once the account deleted. * @param {IAccountEventDeletedPayload} payload @@ -21,7 +27,6 @@ export class DisconnectPlaidItemOnAccountDeleted { */ @OnEvent(events.accounts.onDeleted) public async handleDisconnectPlaidItemOnAccountDelete({ - tenantId, oldAccount, trx, }: IAccountEventDeletedPayload) { @@ -29,11 +34,11 @@ export class DisconnectPlaidItemOnAccountDeleted { if (!oldAccount.plaidItemId) return; // Retrieves the Plaid item that associated to the deleted account. - const oldPlaidItem = await this.plaidItemModel + const oldPlaidItem = await this.plaidItemModel() .query(trx) .findOne('plaidItemId', oldAccount.plaidItemId); // Unlink the Plaid item from all account before deleting it. - await this.accountModel + await this.accountModel() .query(trx) .where('plaidItemId', oldAccount.plaidItemId) .patch({ @@ -41,7 +46,7 @@ export class DisconnectPlaidItemOnAccountDeleted { plaidItemId: null, }); // Remove the Plaid item from the system. - await this.plaidItemModel + await this.plaidItemModel() .query(trx) .findOne('plaidItemId', oldAccount.plaidItemId) .delete(); diff --git a/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeCashflowTransaction.ts b/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeCashflowTransaction.ts index cc564c27d..c4a4c1513 100644 --- a/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeCashflowTransaction.ts +++ b/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeCashflowTransaction.ts @@ -16,6 +16,7 @@ import { CreateBankTransactionService } from '../../BankingTransactions/commands import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CategorizeCashflowTransaction { @@ -26,7 +27,9 @@ export class CategorizeCashflowTransaction { private readonly createBankTransaction: CreateBankTransactionService, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -41,7 +44,8 @@ export class CategorizeCashflowTransaction { // Retrieves the uncategorized transaction or throw an error. const oldUncategorizedTransactions = - await this.uncategorizedBankTransactionModel.query() + await this.uncategorizedBankTransactionModel() + .query() .whereIn('id', uncategorizedTransactionIds) .throwIfNotFound(); @@ -81,7 +85,8 @@ export class CategorizeCashflowTransaction { ); // Updates the uncategorized transaction as categorized. - await this.uncategorizedBankTransactionModel.query(trx) + await this.uncategorizedBankTransactionModel() + .query(trx) .whereIn('id', uncategorizedTransactionIds) .patch({ categorized: true, @@ -90,10 +95,9 @@ export class CategorizeCashflowTransaction { }); // Fetch the new updated uncategorized transactions. const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel.query(trx).whereIn( - 'id', - uncategorizedTransactionIds, - ); + await this.uncategorizedBankTransactionModel() + .query(trx) + .whereIn('id', uncategorizedTransactionIds); // Triggers `onCashflowTransactionCategorized` event. await this.eventPublisher.emitAsync( events.cashflow.onTransactionCategorized, diff --git a/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeTransactionAsExpense.ts b/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeTransactionAsExpense.ts index 5c95698a9..11b46d34e 100644 --- a/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeTransactionAsExpense.ts +++ b/packages/server-nest/src/modules/BankingCategorize/commands/CategorizeTransactionAsExpense.ts @@ -10,6 +10,7 @@ import { ICashflowTransactionCategorizedPayload, ICategorizeCashflowTransactioDTO, } from '../types/BankingCategorize.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CategorizeTransactionAsExpense { @@ -19,7 +20,9 @@ export class CategorizeTransactionAsExpense { private readonly createExpenseService: CreateExpense, @Inject(BankTransaction.name) - private readonly bankTransactionModel: typeof BankTransaction, + private readonly bankTransactionModel: TenantModelProxy< + typeof BankTransaction + >, ) {} /** @@ -31,7 +34,7 @@ export class CategorizeTransactionAsExpense { cashflowTransactionId: number, transactionDTO: ICategorizeCashflowTransactioDTO, ) { - const transaction = await this.bankTransactionModel + const transaction = await this.bankTransactionModel() .query() .findById(cashflowTransactionId) .throwIfNotFound(); @@ -53,7 +56,7 @@ export class CategorizeTransactionAsExpense { }); // Updates the item on the storage and fetches the updated once. - const cashflowTransaction = await this.bankTransactionModel + const cashflowTransaction = await this.bankTransactionModel() .query(trx) .patchAndFetchById(cashflowTransactionId, { categorizeRefType: 'Expense', diff --git a/packages/server-nest/src/modules/BankingCategorize/commands/CreateUncategorizedTransaction.service.ts b/packages/server-nest/src/modules/BankingCategorize/commands/CreateUncategorizedTransaction.service.ts index b8afc38a5..2b69b60b2 100644 --- a/packages/server-nest/src/modules/BankingCategorize/commands/CreateUncategorizedTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingCategorize/commands/CreateUncategorizedTransaction.service.ts @@ -9,6 +9,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UncategorizedBankTransaction } from '../../BankingTransactions/models/UncategorizedBankTransaction'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateUncategorizedTransactionService { @@ -17,7 +18,9 @@ export class CreateUncategorizedTransactionService { private readonly eventPublisher: EventEmitter2, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransaction: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransaction: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -28,34 +31,32 @@ export class CreateUncategorizedTransactionService { */ public create( createUncategorizedTransactionDTO: CreateUncategorizedTransactionDTO, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) { - return this.uow.withTransaction( - async (trx: Knex.Transaction) => { - await this.eventPublisher.emitAsync( - events.cashflow.onTransactionUncategorizedCreating, - { - createUncategorizedTransactionDTO, - trx, - } as IUncategorizedTransactionCreatingEventPayload - ); + return this.uow.withTransaction(async (trx: Knex.Transaction) => { + await this.eventPublisher.emitAsync( + events.cashflow.onTransactionUncategorizedCreating, + { + createUncategorizedTransactionDTO, + trx, + } as IUncategorizedTransactionCreatingEventPayload, + ); - const uncategorizedTransaction = - await this.uncategorizedBankTransaction.query(trx).insertAndFetch({ - ...createUncategorizedTransactionDTO, - }); + const uncategorizedTransaction = await this.uncategorizedBankTransaction + .query(trx) + .insertAndFetch({ + ...createUncategorizedTransactionDTO, + }); - await this.eventPublisher.emitAsync( - events.cashflow.onTransactionUncategorizedCreated, - { - uncategorizedTransaction, - createUncategorizedTransactionDTO, - trx, - } as IUncategorizedTransactionCreatedEventPayload - ); - return uncategorizedTransaction; - }, - trx - ); + await this.eventPublisher.emitAsync( + events.cashflow.onTransactionUncategorizedCreated, + { + uncategorizedTransaction, + createUncategorizedTransactionDTO, + trx, + } as IUncategorizedTransactionCreatedEventPayload, + ); + return uncategorizedTransaction; + }, trx); } } diff --git a/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizeCashflowTransaction.service.ts b/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizeCashflowTransaction.service.ts index 3b4a25ee6..73e2cf343 100644 --- a/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizeCashflowTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizeCashflowTransaction.service.ts @@ -9,6 +9,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { UncategorizedBankTransaction } from '../../BankingTransactions/models/UncategorizedBankTransaction'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class UncategorizeCashflowTransactionService { @@ -17,7 +18,9 @@ export class UncategorizeCashflowTransactionService { private readonly uow: UnitOfWork, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -29,7 +32,7 @@ export class UncategorizeCashflowTransactionService { uncategorizedTransactionId: number, ): Promise> { const oldMainUncategorizedTransaction = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query() .findById(uncategorizedTransactionId) .throwIfNotFound(); @@ -37,7 +40,7 @@ export class UncategorizeCashflowTransactionService { validateTransactionShouldBeCategorized(oldMainUncategorizedTransaction); const associatedUncategorizedTransactions = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query() .where( 'categorizeRefId', @@ -69,7 +72,7 @@ export class UncategorizeCashflowTransactionService { } as ICashflowTransactionUncategorizingPayload, ); // Removes the ref relation with the related transaction. - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query(trx) .whereIn('id', oldUncategoirzedTransactionsIds) .patch({ @@ -78,7 +81,7 @@ export class UncategorizeCashflowTransactionService { categorizeRefType: null, }); const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query(trx) .whereIn('id', oldUncategoirzedTransactionsIds); // Triggers `onTransactionUncategorized` event. diff --git a/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizedTransactionsImportable.ts b/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizedTransactionsImportable.ts index b912fbe85..0694dfe78 100644 --- a/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizedTransactionsImportable.ts +++ b/packages/server-nest/src/modules/BankingCategorize/commands/UncategorizedTransactionsImportable.ts @@ -8,6 +8,7 @@ import { ImportableContext } from '../../Import/interfaces'; import { BankTransactionsSampleData } from '../../BankingTransactions/constants'; import { Account } from '@/modules/Accounts/models/Account.model'; import { CreateUncategorizedTransactionDTO } from '../types/BankingCategorize.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class UncategorizedTransactionsImportable extends Importable { @@ -15,14 +16,14 @@ export class UncategorizedTransactionsImportable extends Importable { private readonly createUncategorizedTransaction: CreateUncategorizedTransactionService, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) { super(); } /** * Passing the sheet DTO to create uncategorized transaction. - * @param {CreateUncategorizedTransactionDTO,} createDTO + * @param {CreateUncategorizedTransactionDTO,} createDTO * @param {Knex.Transaction} trx */ public async importable( @@ -77,7 +78,7 @@ export class UncategorizedTransactionsImportable extends Importable { */ public async validateParams(params: Record): Promise { if (params.accountId) { - await this.accountModel + await this.accountModel() .query() .findById(params.accountId) .throwIfNotFound({}); diff --git a/packages/server-nest/src/modules/BankingMatching/BankingMatching.module.ts b/packages/server-nest/src/modules/BankingMatching/BankingMatching.module.ts index a22469f91..f2f5f90cc 100644 --- a/packages/server-nest/src/modules/BankingMatching/BankingMatching.module.ts +++ b/packages/server-nest/src/modules/BankingMatching/BankingMatching.module.ts @@ -28,12 +28,12 @@ const models = [RegisterTenancyModel(MatchedBankTransaction)]; @Module({ controllers: [BankingMatchingController], imports: [ + ...models, BillPaymentsModule, BankingTransactionsModule, PaymentsReceivedModule, ], providers: [ - ...models, ValidateTransactionMatched, MatchBankTransactions, MatchTransactionsTypes, diff --git a/packages/server-nest/src/modules/BankingMatching/commands/MatchTransactions.ts b/packages/server-nest/src/modules/BankingMatching/commands/MatchTransactions.ts index 7177db4b9..81ad5d19d 100644 --- a/packages/server-nest/src/modules/BankingMatching/commands/MatchTransactions.ts +++ b/packages/server-nest/src/modules/BankingMatching/commands/MatchTransactions.ts @@ -20,6 +20,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ServiceError } from '@/modules/Items/ServiceError'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class MatchBankTransactions { @@ -29,7 +30,9 @@ export class MatchBankTransactions { private readonly matchedBankTransactions: MatchTransactionsTypes, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -46,7 +49,7 @@ export class MatchBankTransactions { // Validates the uncategorized transaction existance. const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query() .whereIn('id', uncategorizedTransactionIds) .withGraphFetched('matchedBankTransactions') diff --git a/packages/server-nest/src/modules/BankingMatching/commands/UnmatchMatchedTransaction.service.ts b/packages/server-nest/src/modules/BankingMatching/commands/UnmatchMatchedTransaction.service.ts index 073069d11..005b61664 100644 --- a/packages/server-nest/src/modules/BankingMatching/commands/UnmatchMatchedTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingMatching/commands/UnmatchMatchedTransaction.service.ts @@ -4,6 +4,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { MatchedBankTransaction } from '../models/MatchedBankTransaction'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class UnmatchMatchedBankTransaction { @@ -12,7 +13,9 @@ export class UnmatchMatchedBankTransaction { private readonly eventPublisher: EventEmitter2, @Inject(MatchedBankTransaction.name) - private readonly matchedBankTransactionModel: typeof MatchedBankTransaction, + private readonly matchedBankTransactionModel: TenantModelProxy< + typeof MatchedBankTransaction + >, ) {} /** @@ -29,7 +32,7 @@ export class UnmatchMatchedBankTransaction { trx, } as IBankTransactionUnmatchingEventPayload); - await this.matchedBankTransactionModel + await this.matchedBankTransactionModel() .query(trx) .where('uncategorizedTransactionId', uncategorizedTransactionId) .delete(); diff --git a/packages/server-nest/src/modules/BankingMatching/commands/ValidateTransactionsMatched.service.ts b/packages/server-nest/src/modules/BankingMatching/commands/ValidateTransactionsMatched.service.ts index 2c2f00606..b87733002 100644 --- a/packages/server-nest/src/modules/BankingMatching/commands/ValidateTransactionsMatched.service.ts +++ b/packages/server-nest/src/modules/BankingMatching/commands/ValidateTransactionsMatched.service.ts @@ -3,12 +3,15 @@ import { ERRORS } from '../types'; import { Inject, Injectable } from '@nestjs/common'; import { ServiceError } from '@/modules/Items/ServiceError'; import { MatchedBankTransaction } from '../models/MatchedBankTransaction'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ValidateTransactionMatched { constructor( @Inject(MatchedBankTransaction.name) - private readonly matchedBankTransactionModel: typeof MatchedBankTransaction, + private readonly matchedBankTransactionModel: TenantModelProxy< + typeof MatchedBankTransaction + >, ) {} /** @@ -20,13 +23,15 @@ export class ValidateTransactionMatched { public async validateTransactionNoMatchLinking( referenceType: string, referenceId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) { - const foundMatchedTransaction = - await this.matchedBankTransactionModel.query(trx).findOne({ + const foundMatchedTransaction = await this.matchedBankTransactionModel() + .query(trx) + .findOne({ referenceType, referenceId, }); + if (foundMatchedTransaction) { throw new ServiceError(ERRORS.CANNOT_DELETE_TRANSACTION_MATCHED); } diff --git a/packages/server-nest/src/modules/BankingMatching/events/DecrementUncategorizedTransactionsOnMatch.ts b/packages/server-nest/src/modules/BankingMatching/events/DecrementUncategorizedTransactionsOnMatch.ts index 8c5a9977c..be01746dc 100644 --- a/packages/server-nest/src/modules/BankingMatching/events/DecrementUncategorizedTransactionsOnMatch.ts +++ b/packages/server-nest/src/modules/BankingMatching/events/DecrementUncategorizedTransactionsOnMatch.ts @@ -8,15 +8,18 @@ import { Account } from '@/modules/Accounts/models/Account.model'; import { Inject, Injectable } from '@nestjs/common'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DecrementUncategorizedTransactionOnMatchingSubscriber { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -29,14 +32,14 @@ export class DecrementUncategorizedTransactionOnMatchingSubscriber { trx, }: IBankTransactionMatchedEventPayload) { const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel.query().whereIn( - 'id', - uncategorizedTransactionIds - ); + await this.uncategorizedBankTransactionModel() + .query() + .whereIn('id', uncategorizedTransactionIds); + await PromisePool.withConcurrency(1) .for(uncategorizedTransactions) .process(async (transaction) => { - await this.accountModel + await this.accountModel() .query(trx) .findById(transaction.accountId) .decrement('uncategorizedTransactions', 1); @@ -52,11 +55,11 @@ export class DecrementUncategorizedTransactionOnMatchingSubscriber { uncategorizedTransactionId, trx, }: IBankTransactionUnmatchedEventPayload) { - const transaction = - await this.uncategorizedBankTransactionModel.query().findById( - uncategorizedTransactionId - ); - await this.accountModel + const transaction = await this.uncategorizedBankTransactionModel() + .query() + .findById(uncategorizedTransactionId); + + await this.accountModel() .query(trx) .findById(transaction.accountId) .increment('uncategorizedTransactions', 1); diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactions.service.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactions.service.ts index 70c6f27ca..d0faa7424 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactions.service.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactions.service.ts @@ -3,7 +3,10 @@ import * as moment from 'moment'; import { first, sumBy } from 'lodash'; import { PromisePool } from '@supercharge/promise-pool'; import { Inject, Injectable } from '@nestjs/common'; -import { GetMatchedTransactionsFilter, MatchedTransactionsPOJO } from '../types'; +import { + GetMatchedTransactionsFilter, + MatchedTransactionsPOJO, +} from '../types'; import { GetMatchedTransactionsByExpenses } from './GetMatchedTransactionsByExpenses'; import { GetMatchedTransactionsByBills } from './GetMatchedTransactionsByBills.service'; import { GetMatchedTransactionsByManualJournals } from './GetMatchedTransactionsByManualJournals.service'; @@ -11,6 +14,7 @@ import { GetMatchedTransactionsByCashflow } from './GetMatchedTransactionsByCash import { GetMatchedTransactionsByInvoices } from './GetMatchedTransactionsByInvoices.service'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { sortClosestMatchTransactions } from '../_utils'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetMatchedTransactions { @@ -22,7 +26,9 @@ export class GetMatchedTransactions { private readonly getMatchedCashflowService: GetMatchedTransactionsByCashflow, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -46,10 +52,11 @@ export class GetMatchedTransactions { */ public async getMatchedTransactions( uncategorizedTransactionIds: Array, - filter: GetMatchedTransactionsFilter + filter: GetMatchedTransactionsFilter, ): Promise { const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel.query() + await this.uncategorizedBankTransactionModel() + .query() .whereIn('id', uncategorizedTransactionIds) .throwIfNotFound(); @@ -66,7 +73,7 @@ export class GetMatchedTransactions { }); const { perfectMatches, possibleMatches } = this.groupMatchedResults( uncategorizedTransactions, - matchedTransactions + matchedTransactions, ); return { perfectMatches, @@ -84,7 +91,7 @@ export class GetMatchedTransactions { */ private groupMatchedResults( uncategorizedTransactions: Array, - matchedTransactions + matchedTransactions, ): MatchedTransactionsPOJO { const results = R.compose(R.flatten)(matchedTransactions?.results); @@ -97,7 +104,7 @@ export class GetMatchedTransactions { const perfectMatches = R.filter( (match) => match.amount === amount && moment(match.date).isSame(date, 'day'), - closestResullts + closestResullts, ); const possibleMatches = R.difference(closestResullts, perfectMatches); const totalPending = sumBy(uncategorizedTransactions, 'amount'); diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByBills.service.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByBills.service.ts index fbadf2414..1a001a291 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByBills.service.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByBills.service.ts @@ -13,6 +13,7 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { IBillPaymentDTO } from '@/modules/BillPayments/types/BillPayments.types'; import { Bill } from '@/modules/Bills/models/Bill'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetMatchedTransactionsByBills extends GetMatchedTransactionsByType { @@ -21,10 +22,12 @@ export class GetMatchedTransactionsByBills extends GetMatchedTransactionsByType private readonly transformer: TransformerInjectable, @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) { super(); } @@ -34,23 +37,23 @@ export class GetMatchedTransactionsByBills extends GetMatchedTransactionsByType * @param {number} tenantId - * @param {GetMatchedTransactionsFilter} filter - */ - public async getMatchedTransactions( - filter: GetMatchedTransactionsFilter, - ) { + public async getMatchedTransactions(filter: GetMatchedTransactionsFilter) { // Retrieves the bill matches. - const bills = await Bill.query().onBuild((q) => { - q.withGraphJoined('matchedBankTransaction'); - q.whereNull('matchedBankTransaction.id'); - q.modify('published'); + const bills = await this.billModel() + .query() + .onBuild((q) => { + q.withGraphJoined('matchedBankTransaction'); + q.whereNull('matchedBankTransaction.id'); + q.modify('published'); - if (filter.fromDate) { - q.where('billDate', '>=', filter.fromDate); - } - if (filter.toDate) { - q.where('billDate', '<=', filter.toDate); - } - q.orderBy('billDate', 'DESC'); - }); + if (filter.fromDate) { + q.where('billDate', '>=', filter.fromDate); + } + if (filter.toDate) { + q.where('billDate', '<=', filter.toDate); + } + q.orderBy('billDate', 'DESC'); + }); return this.transformer.transform( bills, @@ -67,7 +70,7 @@ export class GetMatchedTransactionsByBills extends GetMatchedTransactionsByType public async getMatchedTransaction( transactionId: number, ): Promise { - const bill = await this.billModel + const bill = await this.billModel() .query() .findById(transactionId) .throwIfNotFound(); @@ -97,12 +100,12 @@ export class GetMatchedTransactionsByBills extends GetMatchedTransactionsByType ); const uncategorizedTransactionId = first(uncategorizedTransactionIds); const uncategorizedTransaction = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query(trx) .findById(uncategorizedTransactionId) .throwIfNotFound(); - const bill = await this.billModel + const bill = await this.billModel() .query(trx) .findById(matchTransactionDTO.referenceId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByCashflow.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByCashflow.ts index 496fb1df3..0419a33ff 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByCashflow.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByCashflow.ts @@ -4,6 +4,7 @@ import { GetMatchedTransactionsFilter } from '../types'; import { BankTransaction } from '@/modules/BankingTransactions/models/BankTransaction'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { Inject, Injectable } from '@nestjs/common'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetMatchedTransactionsByCashflow extends GetMatchedTransactionsByType { @@ -11,7 +12,9 @@ export class GetMatchedTransactionsByCashflow extends GetMatchedTransactionsByTy private readonly transformer: TransformerInjectable, @Inject(BankTransaction.name) - private readonly bankTransactionModel: typeof BankTransaction, + private readonly bankTransactionModel: TenantModelProxy< + typeof BankTransaction + >, ) { super(); } @@ -25,7 +28,7 @@ export class GetMatchedTransactionsByCashflow extends GetMatchedTransactionsByTy async getMatchedTransactions( filter: Omit, ) { - const transactions = await this.bankTransactionModel + const transactions = await this.bankTransactionModel() .query() .onBuild((q) => { // Not matched to bank transaction. @@ -60,7 +63,7 @@ export class GetMatchedTransactionsByCashflow extends GetMatchedTransactionsByTy * @returns */ async getMatchedTransaction(transactionId: number) { - const transactions = await this.bankTransactionModel + const transactions = await this.bankTransactionModel() .query() .findById(transactionId) .withGraphJoined('matchedBankTransaction') diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByExpenses.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByExpenses.ts index 331df5922..3650e547b 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByExpenses.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByExpenses.ts @@ -4,6 +4,7 @@ import { GetMatchedTransactionsByType } from './GetMatchedTransactionsByType'; import { GetMatchedTransactionExpensesTransformer } from './GetMatchedTransactionExpensesTransformer'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { Expense } from '@/modules/Expenses/models/Expense.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetMatchedTransactionsByExpenses extends GetMatchedTransactionsByType { @@ -11,7 +12,7 @@ export class GetMatchedTransactionsByExpenses extends GetMatchedTransactionsByTy protected readonly transformer: TransformerInjectable, @Inject(Expense.name) - protected readonly expenseModel: typeof Expense, + protected readonly expenseModel: TenantModelProxy, ) { super(); } @@ -24,28 +25,30 @@ export class GetMatchedTransactionsByExpenses extends GetMatchedTransactionsByTy */ async getMatchedTransactions(filter: GetMatchedTransactionsFilter) { // Retrieve the expense matches. - const expenses = await this.expenseModel.query().onBuild((query) => { - // Filter out the not matched to bank transactions. - query.withGraphJoined('matchedBankTransaction'); - query.whereNull('matchedBankTransaction.id'); + const expenses = await this.expenseModel() + .query() + .onBuild((query) => { + // Filter out the not matched to bank transactions. + query.withGraphJoined('matchedBankTransaction'); + query.whereNull('matchedBankTransaction.id'); - // Filter the published onyl - query.modify('filterByPublished'); + // Filter the published onyl + query.modify('filterByPublished'); - if (filter.fromDate) { - query.where('paymentDate', '>=', filter.fromDate); - } - if (filter.toDate) { - query.where('paymentDate', '<=', filter.toDate); - } - if (filter.minAmount) { - query.where('totalAmount', '>=', filter.minAmount); - } - if (filter.maxAmount) { - query.where('totalAmount', '<=', filter.maxAmount); - } - query.orderBy('paymentDate', 'DESC'); - }); + if (filter.fromDate) { + query.where('paymentDate', '>=', filter.fromDate); + } + if (filter.toDate) { + query.where('paymentDate', '<=', filter.toDate); + } + if (filter.minAmount) { + query.where('totalAmount', '>=', filter.minAmount); + } + if (filter.maxAmount) { + query.where('totalAmount', '<=', filter.maxAmount); + } + query.orderBy('paymentDate', 'DESC'); + }); return this.transformer.transform( expenses, new GetMatchedTransactionExpensesTransformer(), @@ -61,7 +64,7 @@ export class GetMatchedTransactionsByExpenses extends GetMatchedTransactionsByTy public async getMatchedTransaction( transactionId: number, ): Promise { - const expense = await this.expenseModel + const expense = await this.expenseModel() .query() .findById(transactionId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByInvoices.service.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByInvoices.service.ts index 33450c5d2..3fc736aa1 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByInvoices.service.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByInvoices.service.ts @@ -14,6 +14,7 @@ import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { IPaymentReceivedCreateDTO } from '@/modules/PaymentReceived/types/PaymentReceived.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetMatchedTransactionsByInvoices extends GetMatchedTransactionsByType { @@ -22,10 +23,12 @@ export class GetMatchedTransactionsByInvoices extends GetMatchedTransactionsByTy private readonly createPaymentReceivedService: CreatePaymentReceivedService, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) { super(); } @@ -36,27 +39,29 @@ export class GetMatchedTransactionsByInvoices extends GetMatchedTransactionsByTy * @returns {Promise} */ public async getMatchedTransactions( - filter: GetMatchedTransactionsFilter + filter: GetMatchedTransactionsFilter, ): Promise { // Retrieve the invoices that not matched, unpaid. - const invoices = await this.saleInvoiceModel.query().onBuild((q) => { - q.withGraphJoined('matchedBankTransaction'); - q.whereNull('matchedBankTransaction.id'); - q.modify('unpaid'); - q.modify('published'); + const invoices = await this.saleInvoiceModel() + .query() + .onBuild((q) => { + q.withGraphJoined('matchedBankTransaction'); + q.whereNull('matchedBankTransaction.id'); + q.modify('unpaid'); + q.modify('published'); - if (filter.fromDate) { - q.where('invoiceDate', '>=', filter.fromDate); - } - if (filter.toDate) { - q.where('invoiceDate', '<=', filter.toDate); - } - q.orderBy('invoiceDate', 'DESC'); - }); + if (filter.fromDate) { + q.where('invoiceDate', '>=', filter.fromDate); + } + if (filter.toDate) { + q.where('invoiceDate', '<=', filter.toDate); + } + q.orderBy('invoiceDate', 'DESC'); + }); return this.transformer.transform( invoices, - new GetMatchedTransactionInvoicesTransformer() + new GetMatchedTransactionInvoicesTransformer(), ); } @@ -67,13 +72,15 @@ export class GetMatchedTransactionsByInvoices extends GetMatchedTransactionsByTy * @returns {Promise} */ public async getMatchedTransaction( - transactionId: number + transactionId: number, ): Promise { - const invoice = await this.saleInvoiceModel.query().findById(transactionId); + const invoice = await this.saleInvoiceModel() + .query() + .findById(transactionId); return this.transformer.transform( invoice, - new GetMatchedTransactionInvoicesTransformer() + new GetMatchedTransactionInvoicesTransformer(), ); } @@ -87,16 +94,17 @@ export class GetMatchedTransactionsByInvoices extends GetMatchedTransactionsByTy public async createMatchedTransaction( uncategorizedTransactionIds: Array, matchTransactionDTO: IMatchTransactionDTO, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) { await super.createMatchedTransaction( uncategorizedTransactionIds, matchTransactionDTO, - trx + trx, ); const uncategorizedTransactionId = first(uncategorizedTransactionIds); const uncategorizedTransaction = - await this.uncategorizedBankTransactionModel.query(trx) + await this.uncategorizedBankTransactionModel() + .query(trx) .findById(uncategorizedTransactionId) .throwIfNotFound(); @@ -119,14 +127,19 @@ export class GetMatchedTransactionsByInvoices extends GetMatchedTransactionsByTy branchId: invoice.branchId, }; // Create a payment received associated to the matched invoice. - const paymentReceived = await this.createPaymentReceivedService.createPaymentReceived( - createPaymentReceivedDTO, - trx - ); + const paymentReceived = + await this.createPaymentReceivedService.createPaymentReceived( + createPaymentReceivedDTO, + trx, + ); // Link the create payment received with matched invoice transaction. - await super.createMatchedTransaction(uncategorizedTransactionIds, { - referenceType: 'PaymentReceive', - referenceId: paymentReceived.id, - }, trx) + await super.createMatchedTransaction( + uncategorizedTransactionIds, + { + referenceType: 'PaymentReceive', + referenceId: paymentReceived.id, + }, + trx, + ); } } diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByManualJournals.service.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByManualJournals.service.ts index fbc16b1a4..85be269e9 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByManualJournals.service.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByManualJournals.service.ts @@ -4,6 +4,7 @@ import { GetMatchedTransactionsByType } from './GetMatchedTransactionsByType'; import { GetMatchedTransactionsFilter } from '../types'; import { ManualJournal } from '@/modules/ManualJournals/models/ManualJournal'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetMatchedTransactionsByManualJournals extends GetMatchedTransactionsByType { @@ -11,14 +12,13 @@ export class GetMatchedTransactionsByManualJournals extends GetMatchedTransactio private readonly transformer: TransformerInjectable, @Inject(ManualJournal.name) - private readonly manualJournalModel: typeof ManualJournal, + private readonly manualJournalModel: TenantModelProxy, ) { super(); } /** * Retrieve the matched transactions of manual journals. - * @param {number} tenantId * @param {GetMatchedTransactionsFilter} filter * @returns */ @@ -28,27 +28,29 @@ export class GetMatchedTransactionsByManualJournals extends GetMatchedTransactio // @todo: get the account id from the filter const accountId = 1000; - const manualJournals = await this.manualJournalModel.query().onBuild((query) => { - query.withGraphJoined('matchedBankTransaction'); - query.whereNull('matchedBankTransaction.id'); + const manualJournals = await this.manualJournalModel() + .query() + .onBuild((query) => { + query.withGraphJoined('matchedBankTransaction'); + query.whereNull('matchedBankTransaction.id'); - query.withGraphJoined('entries'); - query.where('entries.accountId', accountId); - query.modify('filterByPublished'); + query.withGraphJoined('entries'); + query.where('entries.accountId', accountId); + query.modify('filterByPublished'); - if (filter.fromDate) { - query.where('date', '>=', filter.fromDate); - } - if (filter.toDate) { - query.where('date', '<=', filter.toDate); - } - if (filter.minAmount) { - query.where('amount', '>=', filter.minAmount); - } - if (filter.maxAmount) { - query.where('amount', '<=', filter.maxAmount); - } - }); + if (filter.fromDate) { + query.where('date', '>=', filter.fromDate); + } + if (filter.toDate) { + query.where('date', '<=', filter.toDate); + } + if (filter.minAmount) { + query.where('amount', '>=', filter.minAmount); + } + if (filter.maxAmount) { + query.where('amount', '<=', filter.maxAmount); + } + }); return this.transformer.transform( manualJournals, new GetMatchedTransactionManualJournalsTransformer(), @@ -62,7 +64,8 @@ export class GetMatchedTransactionsByManualJournals extends GetMatchedTransactio * @returns */ public async getMatchedTransaction(transactionId: number) { - const manualJournal = await this.manualJournalModel.query() + const manualJournal = await this.manualJournalModel() + .query() .findById(transactionId) .whereNotExists(ManualJournal.relatedQuery('matchedBankTransaction')) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByType.ts b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByType.ts index 7ca1c7c8e..a256339df 100644 --- a/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByType.ts +++ b/packages/server-nest/src/modules/BankingMatching/queries/GetMatchedTransactionsByType.ts @@ -8,10 +8,13 @@ import { import PromisePool from '@supercharge/promise-pool'; import { MatchedBankTransaction } from '../models/MatchedBankTransaction'; import { Inject } from '@nestjs/common'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; export abstract class GetMatchedTransactionsByType { @Inject(MatchedBankTransaction.name) - private readonly matchedBankTransactionModel: typeof MatchedBankTransaction; + private readonly matchedBankTransactionModel: TenantModelProxy< + typeof MatchedBankTransaction + >; /** * Retrieves the matched transactions. @@ -20,10 +23,10 @@ export abstract class GetMatchedTransactionsByType { * @returns {Promise} */ public async getMatchedTransactions( - filter: GetMatchedTransactionsFilter + filter: GetMatchedTransactionsFilter, ): Promise { throw new Error( - 'The `getMatchedTransactions` method is not defined for the transaction type.' + 'The `getMatchedTransactions` method is not defined for the transaction type.', ); } @@ -34,10 +37,10 @@ export abstract class GetMatchedTransactionsByType { * @returns {Promise} */ public async getMatchedTransaction( - transactionId: number + transactionId: number, ): Promise { throw new Error( - 'The `getMatchedTransaction` method is not defined for the transaction type.' + 'The `getMatchedTransaction` method is not defined for the transaction type.', ); } @@ -51,12 +54,12 @@ export abstract class GetMatchedTransactionsByType { public async createMatchedTransaction( uncategorizedTransactionIds: Array, matchTransactionDTO: IMatchTransactionDTO, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) { await PromisePool.withConcurrency(2) .for(uncategorizedTransactionIds) .process(async (uncategorizedTransactionId) => { - await this.matchedBankTransactionModel.query(trx).insert({ + await this.matchedBankTransactionModel().query(trx).insert({ uncategorizedTransactionId, referenceType: matchTransactionDTO.referenceType, referenceId: matchTransactionDTO.referenceId, diff --git a/packages/server-nest/src/modules/BankingPlaid/BankingPlaid.module.ts b/packages/server-nest/src/modules/BankingPlaid/BankingPlaid.module.ts index ed89c2cbb..77f11adca 100644 --- a/packages/server-nest/src/modules/BankingPlaid/BankingPlaid.module.ts +++ b/packages/server-nest/src/modules/BankingPlaid/BankingPlaid.module.ts @@ -16,10 +16,7 @@ import { TenancyContext } from '../Tenancy/TenancyContext.service'; import { InjectSystemModel } from '../System/SystemModels/SystemModels.module'; import { SystemPlaidItem } from './models/SystemPlaidItem'; -const models = [ - RegisterTenancyModel(PlaidItem), - InjectSystemModel(SystemPlaidItem), -]; +const models = [RegisterTenancyModel(PlaidItem)]; @Module({ imports: [ @@ -27,9 +24,10 @@ const models = [ AccountsModule, BankingCategorizeModule, BankingTransactionsModule, + ...models, ], providers: [ - ...models, + InjectSystemModel(SystemPlaidItem), PlaidItemService, PlaidUpdateTransactions, PlaidSyncDb, diff --git a/packages/server-nest/src/modules/BankingPlaid/command/PlaidItem.ts b/packages/server-nest/src/modules/BankingPlaid/command/PlaidItem.ts index 1ce266ec7..e500f6fd2 100644 --- a/packages/server-nest/src/modules/BankingPlaid/command/PlaidItem.ts +++ b/packages/server-nest/src/modules/BankingPlaid/command/PlaidItem.ts @@ -6,7 +6,11 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; import { SystemPlaidItem } from '../models/SystemPlaidItem'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; -import { IPlaidItemCreatedEventPayload, PlaidItemDTO } from '../types/BankingPlaid.types'; +import { + IPlaidItemCreatedEventPayload, + PlaidItemDTO, +} from '../types/BankingPlaid.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PlaidItemService { @@ -15,10 +19,12 @@ export class PlaidItemService { private readonly tenancyContext: TenancyContext, @Inject(SystemPlaidItem.name) - private readonly systemPlaidItemModel: typeof SystemPlaidItem, + private readonly systemPlaidItemModel: TenantModelProxy< + typeof SystemPlaidItem + >, @Inject(PlaidItem.name) - private readonly plaidItemModel: typeof PlaidItem, + private readonly plaidItemModel: TenantModelProxy, @Inject(PLAID_CLIENT) private readonly plaidClient: PlaidApi, @@ -44,14 +50,14 @@ export class PlaidItemService { const plaidItemId = response.data.item_id; // Store the Plaid item metadata on tenant scope. - const plaidItem = await this.plaidItemModel.query().insertAndFetch({ + const plaidItem = await this.plaidItemModel().query().insertAndFetch({ tenantId, plaidAccessToken, plaidItemId, plaidInstitutionId: institutionId, }); // Stores the Plaid item id on system scope. - await this.systemPlaidItemModel.query().insert({ tenantId, plaidItemId }); + await this.systemPlaidItemModel().query().insert({ tenantId, plaidItemId }); // Triggers `onPlaidItemCreated` event. await this.eventEmitter.emitAsync(events.plaid.onItemCreated, { diff --git a/packages/server-nest/src/modules/BankingPlaid/command/PlaidSyncDB.ts b/packages/server-nest/src/modules/BankingPlaid/command/PlaidSyncDB.ts index 0a572e61c..b077c782a 100644 --- a/packages/server-nest/src/modules/BankingPlaid/command/PlaidSyncDB.ts +++ b/packages/server-nest/src/modules/BankingPlaid/command/PlaidSyncDB.ts @@ -24,6 +24,7 @@ import { IPlaidTransactionsSyncedEventPayload } from '../types/BankingPlaid.type import { UncategorizedBankTransaction } from '../../BankingTransactions/models/UncategorizedBankTransaction'; import { Inject, Injectable } from '@nestjs/common'; import { CreateUncategorizedTransactionService } from '@/modules/BankingCategorize/commands/CreateUncategorizedTransaction.service'; +import { TenantModelProxy } from '../../System/models/TenantBaseModel'; const CONCURRENCY_ASYNC = 10; @@ -36,13 +37,15 @@ export class PlaidSyncDb { private readonly eventPublisher: EventEmitter2, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(PlaidItemModel.name) - private readonly plaidItemModel: typeof PlaidItemModel, + private readonly plaidItemModel: TenantModelProxy, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -55,7 +58,7 @@ export class PlaidSyncDb { createBankAccountDTO: IAccountCreateDTO, trx?: Knex.Transaction, ) { - const plaidAccount = await this.accountModel + const plaidAccount = await this.accountModel() .query(trx) .findOne('plaidAccountId', createBankAccountDTO.plaidAccountId); // Can't continue if the Plaid account is already created. @@ -102,7 +105,7 @@ export class PlaidSyncDb { trx?: Knex.Transaction, ): Promise { const batch = uniqid(); - const cashflowAccount = await this.accountModel + const cashflowAccount = await this.accountModel() .query(trx) .findOne({ plaidAccountId }) .throwIfNotFound(); @@ -165,7 +168,7 @@ export class PlaidSyncDb { trx?: Knex.Transaction, ) { const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query(trx) .whereIn('plaidTransactionId', plaidTransactionsIds); const uncategorizedTransactionsIds = uncategorizedTransactions.map( @@ -193,7 +196,7 @@ export class PlaidSyncDb { lastCursor: string, trx?: Knex.Transaction, ): Promise { - await this.plaidItemModel + await this.plaidItemModel() .query(trx) .findOne({ plaidItemId }) .patch({ lastCursor }); @@ -208,7 +211,7 @@ export class PlaidSyncDb { plaidAccountIds: string[], trx?: Knex.Transaction, ): Promise { - await this.accountModel + await this.accountModel() .query(trx) .whereIn('plaid_account_id', plaidAccountIds) .patch({ @@ -227,7 +230,7 @@ export class PlaidSyncDb { isFeedsActive: boolean = true, trx?: Knex.Transaction, ): Promise { - await this.accountModel + await this.accountModel() .query(trx) .whereIn('plaid_account_id', plaidAccountIds) .patch({ diff --git a/packages/server-nest/src/modules/BankingPlaid/command/PlaidUpdateTransactions.ts b/packages/server-nest/src/modules/BankingPlaid/command/PlaidUpdateTransactions.ts index 0afd2ec18..3d7658af0 100644 --- a/packages/server-nest/src/modules/BankingPlaid/command/PlaidUpdateTransactions.ts +++ b/packages/server-nest/src/modules/BankingPlaid/command/PlaidUpdateTransactions.ts @@ -11,6 +11,7 @@ import { RemovedTransaction, } from 'plaid'; import { PLAID_CLIENT } from '@/modules/Plaid/Plaid.module'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PlaidUpdateTransactions { @@ -19,7 +20,7 @@ export class PlaidUpdateTransactions { private readonly uow: UnitOfWork, @Inject(PlaidItem.name) - private readonly plaidItemModel: typeof PlaidItem, + private readonly plaidItemModel: TenantModelProxy, @Inject(PLAID_CLIENT) private readonly plaidClient: PlaidApi, @@ -105,9 +106,10 @@ export class PlaidUpdateTransactions { ): Promise { // the transactions endpoint is paginated, so we may need to hit it multiple times to // retrieve all available transactions. - const plaidItem = await this.plaidItemModel + const plaidItem = await this.plaidItemModel() .query() .findOne('plaidItemId', plaidItemId); + if (!plaidItem) { throw new Error('The given Plaid item id is not found.'); } diff --git a/packages/server-nest/src/modules/BankingTranasctionsRegonize/BankingTransactionsRegonize.module.ts b/packages/server-nest/src/modules/BankingTranasctionsRegonize/BankingTransactionsRegonize.module.ts index 06214b058..5ffd15015 100644 --- a/packages/server-nest/src/modules/BankingTranasctionsRegonize/BankingTransactionsRegonize.module.ts +++ b/packages/server-nest/src/modules/BankingTranasctionsRegonize/BankingTransactionsRegonize.module.ts @@ -11,9 +11,12 @@ import { BankRulesModule } from '../BankRules/BankRules.module'; const models = [RegisterTenancyModel(RecognizedBankTransaction)]; @Module({ - imports: [BankingTransactionsModule, forwardRef(() => BankRulesModule)], - providers: [ + imports: [ + BankingTransactionsModule, + forwardRef(() => BankRulesModule), ...models, + ], + providers: [ GetAutofillCategorizeTransactionService, RevertRecognizedTransactionsService, RecognizeTranasctionsService, diff --git a/packages/server-nest/src/modules/BankingTranasctionsRegonize/commands/RecognizeTranasctions.service.ts b/packages/server-nest/src/modules/BankingTranasctionsRegonize/commands/RecognizeTranasctions.service.ts index bec128bfa..9d79678c0 100644 --- a/packages/server-nest/src/modules/BankingTranasctionsRegonize/commands/RecognizeTranasctions.service.ts +++ b/packages/server-nest/src/modules/BankingTranasctionsRegonize/commands/RecognizeTranasctions.service.ts @@ -8,18 +8,23 @@ import { BankRule } from '@/modules/BankRules/models/BankRule'; import { RecognizedBankTransaction } from '../models/RecognizedBankTransaction'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { transformToMapBy } from '@/utils/transform-to-map-by'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RecognizeTranasctionsService { constructor( @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedCashflowTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedCashflowTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, @Inject(RecognizedBankTransaction.name) - private readonly recognizedBankTransactionModel: typeof RecognizedBankTransaction, + private readonly recognizedBankTransactionModel: TenantModelProxy< + typeof RecognizedBankTransaction + >, @Inject(BankRule.name) - private readonly bankRuleModel: typeof BankRule, + private readonly bankRuleModel: TenantModelProxy, ) {} /** @@ -33,7 +38,7 @@ export class RecognizeTranasctionsService { transaction: UncategorizedBankTransaction, trx?: Knex.Transaction, ) { - const recognizedTransaction = await this.recognizedBankTransactionModel + const recognizedTransaction = await this.recognizedBankTransactionModel() .query(trx) .insert({ bankRuleId: bankRule.id, @@ -43,7 +48,8 @@ export class RecognizeTranasctionsService { assignedPayee: bankRule.assignPayee, assignedMemo: bankRule.assignMemo, }); - await this.uncategorizedCashflowTransactionModel + + await this.uncategorizedCashflowTransactionModel() .query(trx) .findById(transaction.id) .patch({ @@ -52,7 +58,7 @@ export class RecognizeTranasctionsService { } /** - * Regonized the uncategorized transactions. + * Recognized the uncategorized transactions. * @param {number|Array} ruleId - The target rule id/ids. * @param {RecognizeTransactionsCriteria} * @param {Knex.Transaction} trx - @@ -63,7 +69,7 @@ export class RecognizeTranasctionsService { trx?: Knex.Transaction, ) { const uncategorizedTranasctions = - await this.uncategorizedCashflowTransactionModel + await this.uncategorizedCashflowTransactionModel() .query(trx) .onBuild((query) => { query.modify('notRecognized'); @@ -78,14 +84,17 @@ export class RecognizeTranasctionsService { } }); - const bankRules = await this.bankRuleModel.query(trx).onBuild((q) => { - const rulesIds = !isEmpty(ruleId) ? castArray(ruleId) : []; + const bankRules = await this.bankRuleModel() + .query(trx) + .onBuild((q) => { + const rulesIds = !isEmpty(ruleId) ? castArray(ruleId) : []; + + if (rulesIds?.length > 0) { + q.whereIn('id', rulesIds); + } + q.withGraphFetched('conditions'); + }); - if (rulesIds?.length > 0) { - q.whereIn('id', rulesIds); - } - q.withGraphFetched('conditions'); - }); const bankRulesByAccountId = transformToMapBy( bankRules, 'applyIfAccountId', diff --git a/packages/server-nest/src/modules/BankingTranasctionsRegonize/queries/GetAutofillCategorizeTransaction.service.ts b/packages/server-nest/src/modules/BankingTranasctionsRegonize/queries/GetAutofillCategorizeTransaction.service.ts index 03ae30db7..27868c3b5 100644 --- a/packages/server-nest/src/modules/BankingTranasctionsRegonize/queries/GetAutofillCategorizeTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTranasctionsRegonize/queries/GetAutofillCategorizeTransaction.service.ts @@ -3,6 +3,7 @@ import { castArray, first, uniq } from 'lodash'; import { GetAutofillCategorizeTransctionTransformer } from './GetAutofillCategorizeTransactionTransformer'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetAutofillCategorizeTransactionService { @@ -10,7 +11,9 @@ export class GetAutofillCategorizeTransactionService { private readonly transformer: TransformerInjectable, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -18,13 +21,14 @@ export class GetAutofillCategorizeTransactionService { * @param {Array | number} uncategorizeTransactionsId - Uncategorized transactions ids. */ public async getAutofillCategorizeTransaction( - uncategorizeTransactionsId: Array | number + uncategorizeTransactionsId: Array | number, ) { const uncategorizeTransactionsIds = uniq( - castArray(uncategorizeTransactionsId) + castArray(uncategorizeTransactionsId), ); const uncategorizedTransactions = - await this.uncategorizedBankTransactionModel.query() + await this.uncategorizedBankTransactionModel() + .query() .whereIn('id', uncategorizeTransactionsIds) .withGraphFetched('recognizedTransaction.assignAccount') .withGraphFetched('recognizedTransaction.bankRule') @@ -36,7 +40,7 @@ export class GetAutofillCategorizeTransactionService { { uncategorizedTransactions, firstUncategorizedTransaction: first(uncategorizedTransactions), - } + }, ); } } diff --git a/packages/server-nest/src/modules/BankingTransactions/BankingTransactions.module.ts b/packages/server-nest/src/modules/BankingTransactions/BankingTransactions.module.ts index c8f609229..d50193fd4 100644 --- a/packages/server-nest/src/modules/BankingTransactions/BankingTransactions.module.ts +++ b/packages/server-nest/src/modules/BankingTransactions/BankingTransactions.module.ts @@ -38,6 +38,7 @@ const models = [ LedgerModule, BranchesModule, DynamicListModule, + ...models, ], controllers: [BankingTransactionsController], providers: [ @@ -56,7 +57,6 @@ const models = [ CommandBankTransactionValidator, BranchTransactionDTOTransformer, RemovePendingUncategorizedTransaction, - ...models, ], exports: [...models, RemovePendingUncategorizedTransaction], }) diff --git a/packages/server-nest/src/modules/BankingTransactions/commands/CreateBankTransaction.service.ts b/packages/server-nest/src/modules/BankingTransactions/commands/CreateBankTransaction.service.ts index b10fc4571..5f6d26864 100644 --- a/packages/server-nest/src/modules/BankingTransactions/commands/CreateBankTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTransactions/commands/CreateBankTransaction.service.ts @@ -17,6 +17,7 @@ import { ICommandCashflowCreatedPayload, ICommandCashflowCreatingPayload, } from '../types/BankingTransactions.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateBankTransactionService { @@ -28,10 +29,10 @@ export class CreateBankTransactionService { private branchDTOTransform: BranchTransactionDTOTransformer, @Inject(BankTransaction.name) - private bankTransactionModel: typeof BankTransaction, + private bankTransactionModel: TenantModelProxy, @Inject(Account.name) - private accountModel: typeof Account, + private accountModel: TenantModelProxy, ) {} /** @@ -118,13 +119,13 @@ export class CreateBankTransactionService { userId?: number, ): Promise => { // Retrieves the cashflow account or throw not found error. - const cashflowAccount = await this.accountModel + const cashflowAccount = await this.accountModel() .query() .findById(newTransactionDTO.cashflowAccountId) .throwIfNotFound(); // Retrieves the credit account or throw not found error. - const creditAccount = await this.accountModel + const creditAccount = await this.accountModel() .query() .findById(newTransactionDTO.creditAccountId) .throwIfNotFound(); @@ -149,7 +150,7 @@ export class CreateBankTransactionService { } as ICommandCashflowCreatingPayload, ); // Inserts cashflow owner contribution transaction. - const cashflowTransaction = await this.bankTransactionModel + const cashflowTransaction = await this.bankTransactionModel() .query(trx) .upsertGraph(cashflowTransactionObj); diff --git a/packages/server-nest/src/modules/BankingTransactions/commands/DeleteCashflowTransaction.service.ts b/packages/server-nest/src/modules/BankingTransactions/commands/DeleteCashflowTransaction.service.ts index 69e9cf3da..fb7591df8 100644 --- a/packages/server-nest/src/modules/BankingTransactions/commands/DeleteCashflowTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTransactions/commands/DeleteCashflowTransaction.service.ts @@ -11,6 +11,7 @@ import { ICommandCashflowDeletedPayload, ICommandCashflowDeletingPayload, } from '../types/BankingTransactions.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteCashflowTransaction { @@ -19,10 +20,12 @@ export class DeleteCashflowTransaction { private readonly eventEmitter: EventEmitter2, @Inject(BankTransaction.name) - private readonly bankTransaction: typeof BankTransaction, + private readonly bankTransaction: TenantModelProxy, @Inject(BankTransactionLine.name) - private readonly bankTransactionLine: typeof BankTransactionLine, + private readonly bankTransactionLine: TenantModelProxy< + typeof BankTransactionLine + >, ) {} /** @@ -35,7 +38,7 @@ export class DeleteCashflowTransaction { trx?: Knex.Transaction, ): Promise => { // Retrieve the cashflow transaction. - const oldCashflowTransaction = await this.bankTransaction + const oldCashflowTransaction = await this.bankTransaction() .query() .findById(cashflowTransactionId); // Throw not found error if the given transaction id not found. @@ -50,13 +53,13 @@ export class DeleteCashflowTransaction { } as ICommandCashflowDeletingPayload); // Delete cashflow transaction associated lines first. - await this.bankTransactionLine + await this.bankTransactionLine() .query(trx) .where('cashflow_transaction_id', cashflowTransactionId) .delete(); // Delete cashflow transaction. - await this.bankTransaction + await this.bankTransaction() .query(trx) .findById(cashflowTransactionId) .delete(); diff --git a/packages/server-nest/src/modules/BankingTransactions/commands/RemovePendingUncategorizedTransaction.service.ts b/packages/server-nest/src/modules/BankingTransactions/commands/RemovePendingUncategorizedTransaction.service.ts index 60ee0d318..65ebddf63 100644 --- a/packages/server-nest/src/modules/BankingTransactions/commands/RemovePendingUncategorizedTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTransactions/commands/RemovePendingUncategorizedTransaction.service.ts @@ -10,6 +10,7 @@ import { UncategorizedBankTransaction } from '../models/UncategorizedBankTransac import { ServiceError } from '@/modules/Items/ServiceError'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RemovePendingUncategorizedTransaction { @@ -18,7 +19,9 @@ export class RemovePendingUncategorizedTransaction { private readonly uow: UnitOfWork, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransaction: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransaction: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -31,7 +34,7 @@ export class RemovePendingUncategorizedTransaction { uncategorizedTransactionId: number, trx?: Knex.Transaction, ): Promise { - const pendingTransaction = await this.uncategorizedBankTransaction + const pendingTransaction = await this.uncategorizedBankTransaction() .query(trx) .findById(uncategorizedTransactionId) .throwIfNotFound(); @@ -49,7 +52,7 @@ export class RemovePendingUncategorizedTransaction { } as IPendingTransactionRemovingEventPayload, ); // Removes the pending uncategorized transaction. - await this.uncategorizedBankTransaction + await this.uncategorizedBankTransaction() .query(trx) .findById(uncategorizedTransactionId) .delete(); diff --git a/packages/server-nest/src/modules/BankingTransactions/commands/ValidateDeleteBankAccountTransactions.service.ts b/packages/server-nest/src/modules/BankingTransactions/commands/ValidateDeleteBankAccountTransactions.service.ts index aebd97a6e..d3ed1f298 100644 --- a/packages/server-nest/src/modules/BankingTransactions/commands/ValidateDeleteBankAccountTransactions.service.ts +++ b/packages/server-nest/src/modules/BankingTransactions/commands/ValidateDeleteBankAccountTransactions.service.ts @@ -2,12 +2,15 @@ import { Inject, Injectable } from '@nestjs/common'; import { ERRORS } from '../constants'; import { ServiceError } from '../../Items/ServiceError'; import { BankTransactionLine } from '../models/BankTransactionLine'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ValidateDeleteBankAccountTransactions { constructor( @Inject(BankTransactionLine.name) - private readonly bankTransactionLineModel: typeof BankTransactionLine, + private readonly bankTransactionLineModel: TenantModelProxy< + typeof BankTransactionLine + >, ) {} /** @@ -15,7 +18,7 @@ export class ValidateDeleteBankAccountTransactions { * @param {number} accountId */ public validateAccountHasNoCashflowEntries = async (accountId: number) => { - const associatedLines = await this.bankTransactionLineModel + const associatedLines = await this.bankTransactionLineModel() .query() .where('creditAccountId', accountId) .orWhere('cashflowAccountId', accountId); diff --git a/packages/server-nest/src/modules/BankingTransactions/queries/GetRecognizedTransaction.service.ts b/packages/server-nest/src/modules/BankingTransactions/queries/GetRecognizedTransaction.service.ts index 35f7368db..8000b60e4 100644 --- a/packages/server-nest/src/modules/BankingTransactions/queries/GetRecognizedTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTransactions/queries/GetRecognizedTransaction.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { GetRecognizedTransactionTransformer } from './GetRecognizedTransactionTransformer'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { UncategorizedBankTransaction } from '../models/UncategorizedBankTransaction'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetRecognizedTransactionService { @@ -9,7 +10,9 @@ export class GetRecognizedTransactionService { private readonly transformer: TransformerInjectable, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -17,11 +20,10 @@ export class GetRecognizedTransactionService { * @param {number} tenantId * @param {number} uncategorizedTransactionId */ - public async getRecognizedTransaction( - uncategorizedTransactionId: number - ) { + public async getRecognizedTransaction(uncategorizedTransactionId: number) { const uncategorizedTransaction = - await this.uncategorizedBankTransactionModel.query() + await this.uncategorizedBankTransactionModel() + .query() .findById(uncategorizedTransactionId) .withGraphFetched('matchedBankTransactions') .withGraphFetched('recognizedTransaction.assignAccount') @@ -31,7 +33,7 @@ export class GetRecognizedTransactionService { return this.transformer.transform( uncategorizedTransaction, - new GetRecognizedTransactionTransformer() + new GetRecognizedTransactionTransformer(), ); } } diff --git a/packages/server-nest/src/modules/BankingTransactionsExclude/commands/ExcludeBankTransaction.service.ts b/packages/server-nest/src/modules/BankingTransactionsExclude/commands/ExcludeBankTransaction.service.ts index 7c3621fa0..d5165b3ba 100644 --- a/packages/server-nest/src/modules/BankingTransactionsExclude/commands/ExcludeBankTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTransactionsExclude/commands/ExcludeBankTransaction.service.ts @@ -12,12 +12,15 @@ import { import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ExcludeBankTransactionService { constructor( @Inject(UncategorizedBankTransaction.name) - private uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, private uow: UnitOfWork, private eventEmitter: EventEmitter2, @@ -30,7 +33,7 @@ export class ExcludeBankTransactionService { */ public async excludeBankTransaction(uncategorizedTransactionId: number) { const oldUncategorizedTransaction = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query() .findById(uncategorizedTransactionId) .throwIfNotFound(); @@ -47,7 +50,7 @@ export class ExcludeBankTransactionService { trx, } as IBankTransactionUnexcludingEventPayload); - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query(trx) .findById(uncategorizedTransactionId) .patch({ diff --git a/packages/server-nest/src/modules/BankingTransactionsExclude/commands/UnexcludeBankTransaction.service.ts b/packages/server-nest/src/modules/BankingTransactionsExclude/commands/UnexcludeBankTransaction.service.ts index c78e83704..86e5f4525 100644 --- a/packages/server-nest/src/modules/BankingTransactionsExclude/commands/UnexcludeBankTransaction.service.ts +++ b/packages/server-nest/src/modules/BankingTransactionsExclude/commands/UnexcludeBankTransaction.service.ts @@ -12,6 +12,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class UnexcludeBankTransactionService { @@ -20,7 +21,9 @@ export class UnexcludeBankTransactionService { private readonly uow: UnitOfWork, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransactionModel: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransactionModel: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -33,7 +36,7 @@ export class UnexcludeBankTransactionService { uncategorizedTransactionId: number, ): Promise { const oldUncategorizedTransaction = - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query() .findById(uncategorizedTransactionId) .throwIfNotFound(); @@ -49,7 +52,7 @@ export class UnexcludeBankTransactionService { uncategorizedTransactionId, } as IBankTransactionExcludingEventPayload); - await this.uncategorizedBankTransactionModel + await this.uncategorizedBankTransactionModel() .query(trx) .findById(uncategorizedTransactionId) .patch({ diff --git a/packages/server-nest/src/modules/BankingTransactionsExclude/queries/GetExcludedBankTransactions.ts b/packages/server-nest/src/modules/BankingTransactionsExclude/queries/GetExcludedBankTransactions.ts index b67b29e7b..60e980100 100644 --- a/packages/server-nest/src/modules/BankingTransactionsExclude/queries/GetExcludedBankTransactions.ts +++ b/packages/server-nest/src/modules/BankingTransactionsExclude/queries/GetExcludedBankTransactions.ts @@ -3,14 +3,21 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { ExcludedBankTransactionsQuery } from '../types/BankTransactionsExclude.types'; import { UncategorizedTransactionTransformer } from '@/modules/BankingCategorize/commands/UncategorizedTransaction.transformer'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetExcludedBankTransactionsService { + /** + * @param {TransformerInjectable} transformer + * @param {TenantModelProxy} uncategorizedBankTransaction + */ constructor( private readonly transformer: TransformerInjectable, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransaction: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransaction: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -27,7 +34,7 @@ export class GetExcludedBankTransactionsService { pageSize: 20, ...filter, }; - const { results, pagination } = await this.uncategorizedBankTransaction + const { results, pagination } = await this.uncategorizedBankTransaction() .query() .onBuild((q) => { q.modify('excluded'); diff --git a/packages/server-nest/src/modules/BankingTransactionsExclude/subscribers/DecrementUncategorizedTransactionOnExclude.ts b/packages/server-nest/src/modules/BankingTransactionsExclude/subscribers/DecrementUncategorizedTransactionOnExclude.ts index be1c731e3..ce56b324f 100644 --- a/packages/server-nest/src/modules/BankingTransactionsExclude/subscribers/DecrementUncategorizedTransactionOnExclude.ts +++ b/packages/server-nest/src/modules/BankingTransactionsExclude/subscribers/DecrementUncategorizedTransactionOnExclude.ts @@ -7,15 +7,18 @@ import { import { Account } from '@/modules/Accounts/models/Account.model'; import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DecrementUncategorizedTransactionOnExclude { constructor( @Inject(Account.name) - private readonly account: typeof Account, + private readonly account: TenantModelProxy, @Inject(UncategorizedBankTransaction.name) - private readonly uncategorizedBankTransaction: typeof UncategorizedBankTransaction, + private readonly uncategorizedBankTransaction: TenantModelProxy< + typeof UncategorizedBankTransaction + >, ) {} /** @@ -27,11 +30,12 @@ export class DecrementUncategorizedTransactionOnExclude { uncategorizedTransactionId, trx, }: IBankTransactionExcludedEventPayload) { - const transaction = await this.uncategorizedBankTransaction.query( - trx - ).findById(uncategorizedTransactionId); + const transaction = await this.uncategorizedBankTransaction() + .query(trx) + .findById(uncategorizedTransactionId); - await this.account.query(trx) + await this.account() + .query(trx) .findById(transaction.accountId) .decrement('uncategorizedTransactions', 1); } @@ -45,11 +49,12 @@ export class DecrementUncategorizedTransactionOnExclude { uncategorizedTransactionId, trx, }: IBankTransactionUnexcludedEventPayload) { - const transaction = await this.uncategorizedBankTransaction.query().findById( - uncategorizedTransactionId - ); + const transaction = await this.uncategorizedBankTransaction() + .query() + .findById(uncategorizedTransactionId); // - await this.account.query(trx) + await this.account() + .query(trx) .findById(transaction.accountId) .increment('uncategorizedTransactions', 1); } diff --git a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentBillSync.service.ts b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentBillSync.service.ts index 3e0f3e1d2..c526e492c 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentBillSync.service.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentBillSync.service.ts @@ -4,12 +4,13 @@ import { Bill } from '../../Bills/models/Bill'; import { IBillPaymentEntryDTO } from '../types/BillPayments.types'; import { entriesAmountDiff } from '@/utils/entries-amount-diff'; import Objection from 'objection'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class BillPaymentBillSync { constructor( @Inject(Bill.name) - private readonly bill: typeof Bill + private readonly bill: TenantModelProxy, ) {} /** @@ -36,7 +37,7 @@ export class BillPaymentBillSync { if (diffEntry.paymentAmount === 0) { return; } - const oper = this.bill.changePaymentAmount( + const oper = this.bill().changePaymentAmount( diffEntry.billId, diffEntry.paymentAmount, trx, diff --git a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentGLEntries.ts b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentGLEntries.ts index db91a8132..0421e57f8 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentGLEntries.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentGLEntries.ts @@ -6,6 +6,7 @@ import { Account } from '@/modules/Accounts/models/Account.model'; import { BillPayment } from '../models/BillPayment'; import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class BillPaymentGLEntries { @@ -15,24 +16,23 @@ export class BillPaymentGLEntries { private readonly tenancyContext: TenancyContext, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) {} /** * Creates a bill payment GL entries. - * @param {number} tenantId - * @param {number} billPaymentId - * @param {Knex.Transaction} trx + * @param {number} billPaymentId - Bill payment id. + * @param {Knex.Transaction} trx - Knex transaction. */ public writePaymentGLEntries = async ( billPaymentId: number, trx?: Knex.Transaction, ): Promise => { // Retrieves the bill payment details with associated entries. - const payment = await this.billPaymentModel + const payment = await this.billPaymentModel() .query(trx) .findById(billPaymentId) .withGraphFetched('entries.bill'); @@ -47,7 +47,7 @@ export class BillPaymentGLEntries { trx, ); // Exchange gain or loss account. - const EXGainLossAccount = await this.accountModel + const EXGainLossAccount = await this.accountModel() .query(trx) .modify('findBySlug', 'exchange-grain-loss') .first(); diff --git a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentValidators.service.ts b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentValidators.service.ts index 615cc5c8b..461b1ca54 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentValidators.service.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentValidators.service.ts @@ -11,21 +11,24 @@ import { BillPaymentEntry } from '../models/BillPaymentEntry'; import { ServiceError } from '../../Items/ServiceError'; import { ACCOUNT_TYPE } from '@/constants/accounts'; import { Account } from '../../Accounts/models/Account.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class BillPaymentValidators { constructor( @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, @Inject(BillPaymentEntry.name) - private readonly billPaymentEntryModel: typeof BillPaymentEntry, + private readonly billPaymentEntryModel: TenantModelProxy< + typeof BillPaymentEntry + >, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) {} /** @@ -35,7 +38,7 @@ export class BillPaymentValidators { * @param {Function} next */ public async getPaymentMadeOrThrowError(paymentMadeId: number) { - const billPayment = await this.billPaymentModel + const billPayment = await this.billPaymentModel() .query() .withGraphFetched('entries') .findById(paymentMadeId); @@ -53,9 +56,10 @@ export class BillPaymentValidators { * @return {Promise} */ public async getPaymentAccountOrThrowError(paymentAccountId: number) { - const paymentAccount = await this.accountModel + const paymentAccount = await this.accountModel() .query() .findById(paymentAccountId); + if (!paymentAccount) { throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_FOUND); } @@ -82,7 +86,7 @@ export class BillPaymentValidators { paymentMadeNumber: string, notPaymentMadeId?: number, ) { - const foundBillPayment = await this.billPaymentModel + const foundBillPayment = await this.billPaymentModel() .query() .onBuild((builder: any) => { builder.findOne('payment_number', paymentMadeNumber); @@ -107,7 +111,7 @@ export class BillPaymentValidators { ) { const entriesBillsIds = billPaymentEntries.map((e: any) => e.billId); - const storedBills = await this.billModel + const storedBills = await this.billModel() .query() .whereIn('id', entriesBillsIds) .where('vendor_id', vendorId); @@ -144,7 +148,7 @@ export class BillPaymentValidators { (entry: IBillPaymentEntryDTO) => entry.billId, ); - const storedBills = await this.billModel.query().whereIn('id', billsIds); + const storedBills = await this.billModel().query().whereIn('id', billsIds); const storedBillsMap = new Map( storedBills.map((bill) => { const oldEntries = oldPaymentEntries.filter( @@ -191,7 +195,7 @@ export class BillPaymentValidators { .filter((entry: any) => entry.id) .map((entry: any) => entry.id); - const storedEntries = await this.billPaymentEntryModel + const storedEntries = await this.billPaymentEntryModel() .query() .where('bill_payment_id', billPaymentId); @@ -243,7 +247,7 @@ export class BillPaymentValidators { * @param {number} vendorId */ public async validateVendorHasNoPayments(vendorId: number) { - const payments = await this.billPaymentModel + const payments = await this.billPaymentModel() .query() .where('vendor_id', vendorId); diff --git a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentsPages.service.ts b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentsPages.service.ts index 2b41fb013..d1c469d34 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/BillPaymentsPages.service.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/BillPaymentsPages.service.ts @@ -5,19 +5,20 @@ import { Bill } from '../../Bills/models/Bill'; import { BillPayment } from '../models/BillPayment'; import { IBillReceivePageEntry } from '../types/BillPayments.types'; import { ServiceError } from '../../Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export default class BillPaymentsPages { /** - * @param {typeof Bill} billModel - Bill model. - * @param {typeof BillPayment} billPaymentModel - Bill payment model. + * @param {TenantModelProxy} billModel - Bill model. + * @param {TenantModelProxy} billPaymentModel - Bill payment model. */ constructor( @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, ) {} /** @@ -29,7 +30,7 @@ export default class BillPaymentsPages { billPayment: Omit; entries: IBillReceivePageEntry[]; }> { - const billPayment = await this.billPaymentModel + const billPayment = await this.billPaymentModel() .query() .findById(billPaymentId) .withGraphFetched('entries.bill') @@ -74,7 +75,7 @@ export default class BillPaymentsPages { vendorId: number, ): Promise { // Retrieve all payable bills that associated to the payment made transaction. - const payableBills = await this.billModel + const payableBills = await this.billModel() .query() .modify('opened') .modify('dueBills') diff --git a/packages/server-nest/src/modules/BillPayments/commands/CreateBillPayment.service.ts b/packages/server-nest/src/modules/BillPayments/commands/CreateBillPayment.service.ts index e33a32217..a4c04c306 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/CreateBillPayment.service.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/CreateBillPayment.service.ts @@ -13,6 +13,7 @@ import { events } from '@/common/events/events'; import { TenancyContext } from '../../Tenancy/TenancyContext.service'; import { BillPayment } from '../models/BillPayment'; import { Vendor } from '../../Vendors/models/Vendor'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateBillPaymentService { @@ -22,8 +23,8 @@ export class CreateBillPaymentService { * @param {BillPaymentValidators} validators - Bill payment validators service. * @param {CommandBillPaymentDTOTransformer} commandTransformerDTO - Command bill payment DTO transformer service. * @param {TenancyContext} tenancyContext - Tenancy context service. - * @param {typeof Vendor} vendorModel - Vendor model. - * @param {typeof BillPayment} billPaymentModel - Bill payment model. + * @param {TenantModelProxy} vendorModel - Vendor model. + * @param {TenantModelProxy} billPaymentModel - Bill payment model. */ constructor( private uow: UnitOfWork, @@ -33,10 +34,10 @@ export class CreateBillPaymentService { private tenancyContext: TenancyContext, @Inject(Vendor.name) - private readonly vendorModel: typeof Vendor, + private readonly vendorModel: TenantModelProxy, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, ) {} /** @@ -61,7 +62,7 @@ export class CreateBillPaymentService { const tenantMeta = await this.tenancyContext.getTenant(true); // Retrieves the payment vendor or throw not found error. - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .findById(billPaymentDTO.vendorId) .throwIfNotFound(); @@ -102,7 +103,7 @@ export class CreateBillPaymentService { } as IBillPaymentCreatingPayload); // Writes the bill payment graph to the storage. - const billPayment = await this.billPaymentModel + const billPayment = await this.billPaymentModel() .query(trx) .insertGraphAndFetch({ ...billPaymentObj, diff --git a/packages/server-nest/src/modules/BillPayments/commands/DeleteBillPayment.service.ts b/packages/server-nest/src/modules/BillPayments/commands/DeleteBillPayment.service.ts index 8bc9575d2..a46dd2ed4 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/DeleteBillPayment.service.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/DeleteBillPayment.service.ts @@ -9,6 +9,7 @@ import { BillPaymentEntry } from '../models/BillPaymentEntry'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteBillPayment { @@ -23,10 +24,12 @@ export class DeleteBillPayment { private readonly uow: UnitOfWork, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, @Inject(BillPaymentEntry.name) - private readonly billPaymentEntryModel: typeof BillPaymentEntry, + private readonly billPaymentEntryModel: TenantModelProxy< + typeof BillPaymentEntry + >, ) {} /** @@ -36,7 +39,7 @@ export class DeleteBillPayment { */ public async deleteBillPayment(billPaymentId: number) { // Retrieve the bill payment or throw not found service error. - const oldBillPayment = await this.billPaymentModel + const oldBillPayment = await this.billPaymentModel() .query() .withGraphFetched('entries') .findById(billPaymentId) @@ -52,13 +55,13 @@ export class DeleteBillPayment { } as IBillPaymentDeletingPayload); // Deletes the bill payment associated entries. - await this.billPaymentEntryModel + await this.billPaymentEntryModel() .query(trx) .where('bill_payment_id', billPaymentId) .delete(); // Deletes the bill payment transaction. - await this.billPaymentModel + await this.billPaymentModel() .query(trx) .where('id', billPaymentId) .delete(); diff --git a/packages/server-nest/src/modules/BillPayments/commands/EditBillPayment.service.ts b/packages/server-nest/src/modules/BillPayments/commands/EditBillPayment.service.ts index 757b14320..735291281 100644 --- a/packages/server-nest/src/modules/BillPayments/commands/EditBillPayment.service.ts +++ b/packages/server-nest/src/modules/BillPayments/commands/EditBillPayment.service.ts @@ -12,6 +12,7 @@ import { CommandBillPaymentDTOTransformer } from './CommandBillPaymentDTOTransfo import { Vendor } from '@/modules/Vendors/models/Vendor'; import { events } from '@/common/events/events'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditBillPayment { @@ -23,10 +24,10 @@ export class EditBillPayment { private readonly tenancyContext: TenancyContext, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, @Inject(Vendor.name) - private readonly vendorModel: typeof Vendor, + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -53,13 +54,13 @@ export class EditBillPayment { ): Promise { const tenantMeta = await this.tenancyContext.getTenant(true); - const oldBillPayment = await this.billPaymentModel + const oldBillPayment = await this.billPaymentModel() .query() .findById(billPaymentId) .withGraphFetched('entries') .throwIfNotFound(); - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .findById(billPaymentDTO.vendorId) .throwIfNotFound(); @@ -115,7 +116,7 @@ export class EditBillPayment { } as IBillPaymentEditingPayload); // Edits the bill payment transaction graph on the storage. - const billPayment = await this.billPaymentModel + const billPayment = await this.billPaymentModel() .query(trx) .upsertGraphAndFetch({ id: billPaymentId, diff --git a/packages/server-nest/src/modules/BillPayments/queries/GetBillPayment.service.ts b/packages/server-nest/src/modules/BillPayments/queries/GetBillPayment.service.ts index 060f846df..923873378 100644 --- a/packages/server-nest/src/modules/BillPayments/queries/GetBillPayment.service.ts +++ b/packages/server-nest/src/modules/BillPayments/queries/GetBillPayment.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service'; import { BillPayment } from '../models/BillPayment'; import { BillPaymentTransformer } from './BillPaymentTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetBillPayment { @@ -9,7 +10,7 @@ export class GetBillPayment { private readonly transformer: TransformerInjectable, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, ) {} /** @@ -18,7 +19,7 @@ export class GetBillPayment { * @return {Promise} */ public async getBillPayment(billPyamentId: number): Promise { - const billPayment = await this.billPaymentModel + const billPayment = await this.billPaymentModel() .query() .withGraphFetched('entries.bill') .withGraphFetched('vendor') diff --git a/packages/server-nest/src/modules/BillPayments/queries/GetPaymentBills.service.ts b/packages/server-nest/src/modules/BillPayments/queries/GetPaymentBills.service.ts index edc36b476..745e145ee 100644 --- a/packages/server-nest/src/modules/BillPayments/queries/GetPaymentBills.service.ts +++ b/packages/server-nest/src/modules/BillPayments/queries/GetPaymentBills.service.ts @@ -1,6 +1,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { Bill } from '@/modules/Bills/models/Bill'; import { BillPayment } from '../models/BillPayment'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPaymentBills { @@ -10,10 +11,10 @@ export class GetPaymentBills { */ constructor( @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, @Inject(BillPayment.name) - private readonly billPaymentModel: typeof BillPayment, + private readonly billPaymentModel: TenantModelProxy, ) {} /** @@ -21,14 +22,14 @@ export class GetPaymentBills { * @param {number} billPaymentId - Bill payment id. */ public async getPaymentBills(billPaymentId: number) { - const billPayment = await this.billPaymentModel + const billPayment = await this.billPaymentModel() .query() .findById(billPaymentId) .throwIfNotFound(); const paymentBillsIds = billPayment.entries.map((entry) => entry.id); - const bills = await this.billModel.query().whereIn('id', paymentBillsIds); + const bills = await this.billModel().query().whereIn('id', paymentBillsIds); return bills; } diff --git a/packages/server-nest/src/modules/Bills/commands/BillDTOTransformer.service.ts b/packages/server-nest/src/modules/Bills/commands/BillDTOTransformer.service.ts index d832544fb..a386170a2 100644 --- a/packages/server-nest/src/modules/Bills/commands/BillDTOTransformer.service.ts +++ b/packages/server-nest/src/modules/Bills/commands/BillDTOTransformer.service.ts @@ -14,6 +14,7 @@ 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'; @Injectable() export class BillDTOTransformer { @@ -23,8 +24,9 @@ export class BillDTOTransformer { private taxDTOTransformer: ItemEntriesTaxTransactions, private tenancyContext: TenancyContext, - @Inject(ItemEntry.name) private itemEntryModel: typeof ItemEntry, - @Inject(Item.name) private itemModel: typeof Item, + @Inject(ItemEntry.name) + private itemEntryModel: TenantModelProxy, + @Inject(Item.name) private itemModel: TenantModelProxy, ) {} /** @@ -33,7 +35,7 @@ export class BillDTOTransformer { * @returns {number} */ private getBillEntriesTotal(entries: ItemEntry[]): number { - return sumBy(entries, (e) => this.itemEntryModel.calcAmount(e)); + return sumBy(entries, (e) => this.itemEntryModel().calcAmount(e)); } /** @@ -61,7 +63,7 @@ export class BillDTOTransformer { oldBill?: Bill, ): Promise { const amount = sumBy(billDTO.entries, (e) => - this.itemEntryModel.calcAmount(e), + this.itemEntryModel().calcAmount(e), ); // Retrieve the landed cost amount from landed cost entries. const landedCostAmount = this.getBillLandedCostAmount(billDTO); @@ -125,7 +127,9 @@ export class BillDTOTransformer { private setBillEntriesDefaultAccounts() { return async (entries: ItemEntry[]) => { const entriesItemsIds = entries.map((e) => e.itemId); - const items = await this.itemModel.query().whereIn('id', entriesItemsIds); + const items = await this.itemModel() + .query() + .whereIn('id', entriesItemsIds); return entries.map((entry) => { const item = items.find((i) => i.id === entry.itemId); diff --git a/packages/server-nest/src/modules/Bills/commands/BillInventoryTransactions.ts b/packages/server-nest/src/modules/Bills/commands/BillInventoryTransactions.ts index 1c670642f..c7af1b739 100644 --- a/packages/server-nest/src/modules/Bills/commands/BillInventoryTransactions.ts +++ b/packages/server-nest/src/modules/Bills/commands/BillInventoryTransactions.ts @@ -4,6 +4,8 @@ import { Bill } from '../models/Bill'; import { Inject, Injectable } from '@nestjs/common'; import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service'; import { InventoryTransactionsService } from '@/modules/InventoryCost/InventoryTransactions.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; + @Injectable() export class BillInventoryTransactions { constructor( @@ -11,7 +13,7 @@ export class BillInventoryTransactions { private readonly inventoryTransactionsService: InventoryTransactionsService, @Inject(Bill.name) - private readonly bill: typeof Bill, + private readonly bill: TenantModelProxy, ) {} /** @@ -26,7 +28,7 @@ export class BillInventoryTransactions { ): Promise { // Retireve bill with assocaited entries and allocated cost entries. - const bill = await this.bill + const bill = await this.bill() .query(trx) .findById(billId) .withGraphFetched('entries.allocatedCostEntries'); diff --git a/packages/server-nest/src/modules/Bills/commands/BillsGLEntries.ts b/packages/server-nest/src/modules/Bills/commands/BillsGLEntries.ts index ec82398f8..568f40be7 100644 --- a/packages/server-nest/src/modules/Bills/commands/BillsGLEntries.ts +++ b/packages/server-nest/src/modules/Bills/commands/BillsGLEntries.ts @@ -4,6 +4,7 @@ import { AccountRepository } from '@/modules/Accounts/repositories/Account.repos 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 { @@ -17,7 +18,7 @@ export class BillGLEntries { private readonly accountRepository: AccountRepository, @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, ) {} /** @@ -30,7 +31,7 @@ export class BillGLEntries { trx?: Knex.Transaction, ) => { // Retrieves bill with associated entries and landed costs. - const bill = await this.billModel + const bill = await this.billModel() .query(trx) .findById(billId) .withGraphFetched('entries.item') diff --git a/packages/server-nest/src/modules/Bills/commands/BillsValidators.service.ts b/packages/server-nest/src/modules/Bills/commands/BillsValidators.service.ts index 343515361..072ab5fd1 100644 --- a/packages/server-nest/src/modules/Bills/commands/BillsValidators.service.ts +++ b/packages/server-nest/src/modules/Bills/commands/BillsValidators.service.ts @@ -8,22 +8,25 @@ 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'; @Injectable() export class BillsValidators { constructor( - @Inject(Bill.name) private billModel: typeof Bill, + @Inject(Bill.name) private billModel: TenantModelProxy, @Inject(BillPaymentEntry.name) - private billPaymentEntryModel: typeof BillPaymentEntry, + private billPaymentEntryModel: TenantModelProxy, @Inject(BillLandedCost.name) - private billLandedCostModel: typeof BillLandedCost, + private billLandedCostModel: TenantModelProxy, @Inject(VendorCreditAppliedBill.name) - private vendorCreditAppliedBillModel: typeof VendorCreditAppliedBill, + private vendorCreditAppliedBillModel: TenantModelProxy< + typeof VendorCreditAppliedBill + >, - @Inject(Item.name) private itemModel: typeof Item, + @Inject(Item.name) private itemModel: TenantModelProxy, ) {} /** @@ -57,7 +60,7 @@ export class BillsValidators { billNumber: string, notBillId?: number, ) { - const foundBills = await this.billModel + const foundBills = await this.billModel() .query() .where('bill_number', billNumber) .onBuild((builder) => { @@ -80,7 +83,7 @@ export class BillsValidators { */ public async validateBillHasNoEntries(billId: number) { // Retrieve the bill associate payment made entries. - const entries = await this.billPaymentEntryModel + const entries = await this.billPaymentEntryModel() .query() .where('bill_id', billId); @@ -105,7 +108,7 @@ export class BillsValidators { * @param {number} billId */ public async validateBillHasNoLandedCost(billId: number) { - const billLandedCosts = await this.billLandedCostModel + const billLandedCosts = await this.billLandedCostModel() .query() .where('billId', billId); @@ -123,7 +126,7 @@ export class BillsValidators { newEntriesDTO: IItemEntryDTO[], ) { const entriesItemsIds = newEntriesDTO.map((e) => e.itemId); - const entriesItems = await this.itemModel + const entriesItems = await this.itemModel() .query() .whereIn('id', entriesItemsIds); @@ -147,9 +150,10 @@ export class BillsValidators { * @param {number} billId */ public validateBillHasNoAppliedToCredit = async (billId: number) => { - const appliedTransactions = await this.vendorCreditAppliedBillModel + const appliedTransactions = await this.vendorCreditAppliedBillModel() .query() .where('billId', billId); + if (appliedTransactions.length > 0) { throw new ServiceError(ERRORS.BILL_HAS_APPLIED_TO_VENDOR_CREDIT); } @@ -160,7 +164,7 @@ export class BillsValidators { * @param {number} vendorId - Vendor id. */ public async validateVendorHasNoBills(vendorId: number) { - const bills = await this.billModel.query().where('vendor_id', vendorId); + const bills = await this.billModel().query().where('vendor_id', vendorId); if (bills.length > 0) { throw new ServiceError(ERRORS.VENDOR_HAS_BILLS); diff --git a/packages/server-nest/src/modules/Bills/commands/CreateBill.service.ts b/packages/server-nest/src/modules/Bills/commands/CreateBill.service.ts index e92de344c..ffa1cdbbd 100644 --- a/packages/server-nest/src/modules/Bills/commands/CreateBill.service.ts +++ b/packages/server-nest/src/modules/Bills/commands/CreateBill.service.ts @@ -13,6 +13,7 @@ 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'; @Injectable() export class CreateBill { @@ -24,10 +25,10 @@ export class CreateBill { private transformerDTO: BillDTOTransformer, @Inject(Bill.name) - private billModel: typeof Bill, + private billModel: TenantModelProxy, @Inject(Vendor.name) - private vendorModel: typeof Vendor, + private vendorModel: TenantModelProxy, ) {} /** @@ -49,7 +50,7 @@ export class CreateBill { trx?: Knex.Transaction, ): Promise { // Retrieves the given bill vendor or throw not found error. - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .findById(billDTO.vendorId) .throwIfNotFound(); @@ -80,7 +81,9 @@ export class CreateBill { } as IBillCreatingPayload); // Inserts the bill graph object to the storage. - const bill = await this.billModel.query(trx).upsertGraphAndFetch(billObj); + const bill = await this.billModel() + .query(trx) + .upsertGraphAndFetch(billObj); // Triggers `onBillCreated` event. await this.eventPublisher.emitAsync(events.bill.onCreated, { diff --git a/packages/server-nest/src/modules/Bills/commands/DeleteBill.service.ts b/packages/server-nest/src/modules/Bills/commands/DeleteBill.service.ts index 558ca54a4..62d691da9 100644 --- a/packages/server-nest/src/modules/Bills/commands/DeleteBill.service.ts +++ b/packages/server-nest/src/modules/Bills/commands/DeleteBill.service.ts @@ -10,6 +10,7 @@ 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 { @@ -17,8 +18,12 @@ export class DeleteBill { 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, + + @Inject(Bill.name) + private readonly billModel: TenantModelProxy, + + @Inject(ItemEntry.name) + private readonly itemEntryModel: TenantModelProxy, ) {} /** @@ -28,7 +33,7 @@ export class DeleteBill { */ public async deleteBill(billId: number) { // Retrieve the given bill or throw not found error. - const oldBill = await this.billModel + const oldBill = await this.billModel() .query() .findById(billId) .withGraphFetched('entries'); @@ -55,7 +60,8 @@ export class DeleteBill { } as IBillEventDeletingPayload); // Delete all associated bill entries. - await this.itemEntryModel.query(trx) + await this.itemEntryModel() + .query(trx) .where('reference_type', 'Bill') .where('reference_id', billId) .delete(); diff --git a/packages/server-nest/src/modules/Bills/commands/EditBill.service.ts b/packages/server-nest/src/modules/Bills/commands/EditBill.service.ts index fa03e517d..ca6300bed 100644 --- a/packages/server-nest/src/modules/Bills/commands/EditBill.service.ts +++ b/packages/server-nest/src/modules/Bills/commands/EditBill.service.ts @@ -14,6 +14,7 @@ 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'; @Injectable() export class EditBillService { @@ -25,8 +26,8 @@ export class EditBillService { private transactionLandedCostEntries: TransactionLandedCostEntriesService, private transformerDTO: BillDTOTransformer, - @Inject(Bill.name) private billModel: typeof Bill, - @Inject(Vendor.name) private contactModel: typeof Vendor, + @Inject(Bill.name) private billModel: TenantModelProxy, + @Inject(Vendor.name) private contactModel: TenantModelProxy, ) {} /** @@ -45,12 +46,9 @@ export class EditBillService { * @param {IBillEditDTO} billDTO - The given new bill details. * @return {Promise} */ - public async editBill( - billId: number, - billDTO: IBillEditDTO, - ): Promise { + public async editBill(billId: number, billDTO: IBillEditDTO): Promise { // Retrieve the given bill or throw not found error. - const oldBill = await this.billModel + const oldBill = await this.billModel() .query() .findById(billId) .withGraphFetched('entries'); @@ -59,7 +57,7 @@ export class EditBillService { this.validators.validateBillExistance(oldBill); // Retrieve vendor details or throw not found service error. - const vendor = await this.contactModel + const vendor = await this.contactModel() .query() .findById(billDTO.vendorId) .modify('vendor') @@ -69,44 +67,42 @@ export class EditBillService { if (billDTO.billNumber) { await this.validators.validateBillNumberExists( billDTO.billNumber, - billId + billId, ); } // Validate the entries ids existance. await this.itemsEntriesService.validateEntriesIdsExistance( billId, 'Bill', - billDTO.entries + billDTO.entries, ); // Validate the items ids existance on the storage. - await this.itemsEntriesService.validateItemsIdsExistance( - billDTO.entries - ); + await this.itemsEntriesService.validateItemsIdsExistance(billDTO.entries); // Accept the purchasable items only. await this.itemsEntriesService.validateNonPurchasableEntriesItems( - billDTO.entries + billDTO.entries, ); - + // Transforms the bill DTO to model object. const billObj = await this.transformerDTO.billDTOToModel( billDTO, vendor, - oldBill + oldBill, ); // Validate bill total amount should be bigger than paid amount. this.validators.validateBillAmountBiggerPaidAmount( billObj.amount, - oldBill.paymentAmount + oldBill.paymentAmount, ); // Validate landed cost entries that have allocated cost could not be deleted. await this.transactionLandedCostEntries.validateLandedCostEntriesNotDeleted( oldBill.entries, - billObj.entries + billObj.entries, ); // Validate new landed cost entries should be bigger than new entries. await this.transactionLandedCostEntries.validateLocatedCostEntriesSmallerThanNewEntries( oldBill.entries, - billObj.entries + billObj.entries, ); // Edits bill transactions and associated transactions under UOW envirement. return this.uow.withTransaction(async (trx: Knex.Transaction) => { @@ -118,10 +114,12 @@ export class EditBillService { } as IBillEditingPayload); // Update the bill transaction. - const bill = await this.billModel.query(trx).upsertGraphAndFetch({ - id: billId, - ...billObj, - }); + const bill = await this.billModel() + .query(trx) + .upsertGraphAndFetch({ + id: billId, + ...billObj, + }); // Triggers event `onBillEdited`. await this.eventPublisher.emitAsync(events.bill.onEdited, { oldBill, diff --git a/packages/server-nest/src/modules/Bills/commands/OpenBill.service.ts b/packages/server-nest/src/modules/Bills/commands/OpenBill.service.ts index 4317fc66b..0c9fe7726 100644 --- a/packages/server-nest/src/modules/Bills/commands/OpenBill.service.ts +++ b/packages/server-nest/src/modules/Bills/commands/OpenBill.service.ts @@ -8,6 +8,7 @@ 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 { @@ -17,7 +18,7 @@ export class OpenBillService { private readonly eventPublisher: EventEmitter2, @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, ) {} /** @@ -27,7 +28,7 @@ export class OpenBillService { */ public async openBill(billId: number): Promise { // Retrieve the given bill or throw not found error. - const oldBill = await this.billModel + const oldBill = await this.billModel() .query() .findById(billId) .withGraphFetched('entries'); @@ -47,7 +48,7 @@ export class OpenBillService { } as IBillOpeningPayload); // Save the bill opened at on the storage. - const bill = await this.billModel + const bill = await this.billModel() .query(trx) .patchAndFetchById(billId, { openedAt: moment().toMySqlDateTime(), diff --git a/packages/server-nest/src/modules/Bills/queries/GetBill.ts b/packages/server-nest/src/modules/Bills/queries/GetBill.ts index 1fe21d5b8..89835ae16 100644 --- a/packages/server-nest/src/modules/Bills/queries/GetBill.ts +++ b/packages/server-nest/src/modules/Bills/queries/GetBill.ts @@ -3,11 +3,12 @@ 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: typeof Bill, + @Inject(Bill.name) private billModel: TenantModelProxy, private transformer: TransformerInjectable, private validators: BillsValidators, @@ -19,7 +20,7 @@ export class GetBill { * @returns {Promise} */ public async getBill(billId: number): Promise { - const bill = await this.billModel + const bill = await this.billModel() .query() .findById(billId) .withGraphFetched('vendor') @@ -31,9 +32,6 @@ export class GetBill { // Validates the bill existence. this.validators.validateBillExistance(bill); - return this.transformer.transform( - bill, - new BillTransformer(), - ); + return this.transformer.transform(bill, new BillTransformer()); } } diff --git a/packages/server-nest/src/modules/Bills/queries/GetBills.service.ts b/packages/server-nest/src/modules/Bills/queries/GetBills.service.ts index 14dcae783..1e33c8e9f 100644 --- a/packages/server-nest/src/modules/Bills/queries/GetBills.service.ts +++ b/packages/server-nest/src/modules/Bills/queries/GetBills.service.ts @@ -6,6 +6,7 @@ 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 { @@ -13,7 +14,7 @@ export class GetBillsService { private transformer: TransformerInjectable, private dynamicListService: DynamicListService, - @Inject(Bill.name) private billModel: typeof Bill, + @Inject(Bill.name) private billModel: TenantModelProxy, ) {} /** @@ -30,10 +31,10 @@ export class GetBillsService { // Dynamic list service. const dynamicFilter = await this.dynamicListService.dynamicList( - this.billModel, + this.billModel(), filter, ); - const { results, pagination } = await this.billModel + const { results, pagination } = await this.billModel() .query() .onBuild((builder) => { builder.withGraphFetched('vendor'); diff --git a/packages/server-nest/src/modules/Bills/queries/GetDueBills.service.ts b/packages/server-nest/src/modules/Bills/queries/GetDueBills.service.ts index 264c71a2b..2f8dfa7a7 100644 --- a/packages/server-nest/src/modules/Bills/queries/GetDueBills.service.ts +++ b/packages/server-nest/src/modules/Bills/queries/GetDueBills.service.ts @@ -1,11 +1,11 @@ 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: typeof Bill, + @Inject(Bill.name) private billModel: TenantModelProxy, ) {} /** @@ -13,14 +13,16 @@ export class GetDueBills { * @param {number} vendorId - */ public async getDueBills(vendorId?: number): Promise { - const dueBills = await this.billModel.query().onBuild((query) => { - query.orderBy('bill_date', 'DESC'); - query.modify('dueBills'); + const dueBills = await this.billModel() + .query() + .onBuild((query) => { + query.orderBy('bill_date', 'DESC'); + query.modify('dueBills'); - if (vendorId) { - query.where('vendor_id', vendorId); - } - }); + if (vendorId) { + query.where('vendor_id', vendorId); + } + }); return dueBills; } } diff --git a/packages/server-nest/src/modules/Branches/commands/ActivateBranchesFeature.service.ts b/packages/server-nest/src/modules/Branches/commands/ActivateBranchesFeature.service.ts index 617ae61ef..35ecdea4b 100644 --- a/packages/server-nest/src/modules/Branches/commands/ActivateBranchesFeature.service.ts +++ b/packages/server-nest/src/modules/Branches/commands/ActivateBranchesFeature.service.ts @@ -13,6 +13,7 @@ import { ServiceError } from '@/modules/Items/ServiceError'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Branch } from '../models/Branch.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ActivateBranches { @@ -24,7 +25,7 @@ export class ActivateBranches { private readonly i18n: I18nService, @Inject(Branch.name) - private readonly branchModel: typeof Branch, + private readonly branchModel: TenantModelProxy, ) {} /** diff --git a/packages/server-nest/src/modules/Branches/commands/BranchCommandValidator.service.ts b/packages/server-nest/src/modules/Branches/commands/BranchCommandValidator.service.ts index b23845414..581eea9f8 100644 --- a/packages/server-nest/src/modules/Branches/commands/BranchCommandValidator.service.ts +++ b/packages/server-nest/src/modules/Branches/commands/BranchCommandValidator.service.ts @@ -3,11 +3,12 @@ import { ERRORS } from '../constants'; import { Branch } from '../models/Branch.model'; import { ServiceError } from '../../Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class BranchCommandValidator { constructor( @Inject(Branch.name) - private readonly branchModel: typeof Branch, + private readonly branchModel: TenantModelProxy, ) {} /** @@ -15,7 +16,9 @@ export class BranchCommandValidator { * @param {number} branchId */ public validateBranchNotOnlyWarehouse = async (branchId: number) => { - const warehouses = await this.branchModel.query().whereNot('id', branchId); + const warehouses = await this.branchModel() + .query() + .whereNot('id', branchId); if (warehouses.length === 0) { throw new ServiceError(ERRORS.COULD_NOT_DELETE_ONLY_BRANCH); @@ -31,7 +34,7 @@ export class BranchCommandValidator { code: string, exceptBranchId?: number, ): Promise => { - const branch = await this.branchModel + const branch = await this.branchModel() .query() .onBuild((query) => { query.select(['id']); diff --git a/packages/server-nest/src/modules/Branches/commands/CreateBranch.service.ts b/packages/server-nest/src/modules/Branches/commands/CreateBranch.service.ts index 94b3824ae..60767ffb7 100644 --- a/packages/server-nest/src/modules/Branches/commands/CreateBranch.service.ts +++ b/packages/server-nest/src/modules/Branches/commands/CreateBranch.service.ts @@ -9,6 +9,7 @@ import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { Branch } from '../models/Branch.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateBranchService { @@ -22,7 +23,7 @@ export class CreateBranchService { private readonly eventPublisher: EventEmitter2, @Inject(Branch.name) - private readonly branchModel: typeof Branch, + private readonly branchModel: TenantModelProxy, ) {} /** @@ -41,10 +42,11 @@ export class CreateBranchService { trx, } as IBranchCreatePayload); - const branch = await this.branchModel.query().insertAndFetch({ - ...createBranchDTO, - }); - + const branch = await this.branchModel() + .query() + .insertAndFetch({ + ...createBranchDTO, + }); // Triggers `onBranchCreated` event. await this.eventPublisher.emitAsync(events.warehouse.onEdited, { createBranchDTO, diff --git a/packages/server-nest/src/modules/Branches/commands/DeleteBranch.service.ts b/packages/server-nest/src/modules/Branches/commands/DeleteBranch.service.ts index 9af1293fa..fc27bd178 100644 --- a/packages/server-nest/src/modules/Branches/commands/DeleteBranch.service.ts +++ b/packages/server-nest/src/modules/Branches/commands/DeleteBranch.service.ts @@ -7,12 +7,13 @@ import { Branch } from '../models/Branch.model'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteBranchService { constructor( @Inject(Branch.name) - private readonly branchModel: typeof Branch, + private readonly branchModel: TenantModelProxy, private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, private readonly validator: BranchCommandValidator, @@ -29,18 +30,18 @@ export class DeleteBranchService { /** * Deletes branch. - * @param {number} branchId + * @param {number} branchId * @returns {Promise} */ public deleteBranch = async (branchId: number): Promise => { // Retrieves the old branch or throw not found service error. - const oldBranch = await this.branchModel + const oldBranch = await this.branchModel() .query() .findById(branchId) .throwIfNotFound(); - // .queryAndThrowIfHasRelations({ - // type: ERRORS.BRANCH_HAS_ASSOCIATED_TRANSACTIONS, - // }); + // .queryAndThrowIfHasRelations({ + // type: ERRORS.BRANCH_HAS_ASSOCIATED_TRANSACTIONS, + // }); // Authorize the branch before deleting. await this.authorize(branchId); @@ -53,7 +54,7 @@ export class DeleteBranchService { trx, } as IBranchDeletePayload); - await this.branchModel.query().findById(branchId).delete(); + await this.branchModel().query().findById(branchId).delete(); // Triggers `onBranchCreate` event. await this.eventPublisher.emitAsync(events.warehouse.onEdited, { diff --git a/packages/server-nest/src/modules/Branches/commands/EditBranch.service.ts b/packages/server-nest/src/modules/Branches/commands/EditBranch.service.ts index c4352e1c2..ae59d4857 100644 --- a/packages/server-nest/src/modules/Branches/commands/EditBranch.service.ts +++ b/packages/server-nest/src/modules/Branches/commands/EditBranch.service.ts @@ -9,12 +9,13 @@ import { Branch } from '../models/Branch.model'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditBranchService { constructor( @Inject(Branch.name) - private readonly branchModel: typeof Branch, + private readonly branchModel: TenantModelProxy, private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, ) {} @@ -29,7 +30,7 @@ export class EditBranchService { editBranchDTO: IEditBranchDTO, ) => { // Retrieves the old branch or throw not found service error. - const oldBranch = await this.branchModel + const oldBranch = await this.branchModel() .query() .findById(branchId) .throwIfNotFound(); @@ -43,7 +44,7 @@ export class EditBranchService { } as IBranchEditPayload); // Edits the branch on the storage. - const branch = await this.branchModel + const branch = await this.branchModel() .query() .patchAndFetchById(branchId, { ...editBranchDTO, diff --git a/packages/server-nest/src/modules/Branches/commands/MarkBranchAsPrimary.service.ts b/packages/server-nest/src/modules/Branches/commands/MarkBranchAsPrimary.service.ts index be68aebef..7dd3b33c7 100644 --- a/packages/server-nest/src/modules/Branches/commands/MarkBranchAsPrimary.service.ts +++ b/packages/server-nest/src/modules/Branches/commands/MarkBranchAsPrimary.service.ts @@ -8,6 +8,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { Branch } from '../models/Branch.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class MarkBranchAsPrimaryService { @@ -16,7 +17,7 @@ export class MarkBranchAsPrimaryService { private readonly eventPublisher: EventEmitter2, @Inject(Branch.name) - private readonly branchModel: typeof Branch, + private readonly branchModel: TenantModelProxy, ) {} /** @@ -26,7 +27,7 @@ export class MarkBranchAsPrimaryService { */ public async markAsPrimary(branchId: number): Promise { // Retrieves the old branch or throw not found service error. - const oldBranch = await this.branchModel + const oldBranch = await this.branchModel() .query() .findById(branchId) .throwIfNotFound(); @@ -40,10 +41,10 @@ export class MarkBranchAsPrimaryService { } as IBranchMarkAsPrimaryPayload); // Updates all branches as not primary. - await this.branchModel.query(trx).update({ primary: false }); + await this.branchModel().query(trx).update({ primary: false }); // Updates the given branch as primary. - const markedBranch = await this.branchModel + const markedBranch = await this.branchModel() .query(trx) .patchAndFetchById(branchId, { primary: true, diff --git a/packages/server-nest/src/modules/Branches/queries/GetBranch.service.ts b/packages/server-nest/src/modules/Branches/queries/GetBranch.service.ts index 7e123a4be..e01ed0f9b 100644 --- a/packages/server-nest/src/modules/Branches/queries/GetBranch.service.ts +++ b/packages/server-nest/src/modules/Branches/queries/GetBranch.service.ts @@ -1,12 +1,13 @@ import { Inject } from '@nestjs/common'; import { Injectable } from '@nestjs/common'; import { Branch } from '../models/Branch.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetBranchService { constructor( @Inject(Branch.name) - private readonly branch: typeof Branch, + private readonly branch: TenantModelProxy, ) {} /** @@ -15,7 +16,7 @@ export class GetBranchService { * @returns {Promise} */ public getBranch = async (branchId: number): Promise => { - const branch = await this.branch + const branch = await this.branch() .query() .findById(branchId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/Branches/queries/GetBranches.service.ts b/packages/server-nest/src/modules/Branches/queries/GetBranches.service.ts index d70ed4d0a..933eb60bc 100644 --- a/packages/server-nest/src/modules/Branches/queries/GetBranches.service.ts +++ b/packages/server-nest/src/modules/Branches/queries/GetBranches.service.ts @@ -1,11 +1,12 @@ import { Inject, Injectable } from '@nestjs/common'; import { Branch } from '../models/Branch.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetBranchesService { constructor( @Inject(Branch.name) - private readonly branch: typeof Branch, + private readonly branch: TenantModelProxy, ) {} /** @@ -13,7 +14,7 @@ export class GetBranchesService { * @returns */ public getBranches = async () => { - const branches = await this.branch.query().orderBy('name', 'DESC'); + const branches = await this.branch().query().orderBy('name', 'DESC'); return branches; }; diff --git a/packages/server-nest/src/modules/ChromiumlyTenancy/ChromiumlyHtmlConvert.service.ts b/packages/server-nest/src/modules/ChromiumlyTenancy/ChromiumlyHtmlConvert.service.ts index b79575c06..0e25d396a 100644 --- a/packages/server-nest/src/modules/ChromiumlyTenancy/ChromiumlyHtmlConvert.service.ts +++ b/packages/server-nest/src/modules/ChromiumlyTenancy/ChromiumlyHtmlConvert.service.ts @@ -10,17 +10,20 @@ import { getPdfFilesStorageDir, } from './utils'; import { Document } from './models/Document'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ChromiumlyHtmlConvert { /** - * @param {typeof Document} documentModel - Document model. + * @param {TenantModelProxy} documentModel - Document model. */ - constructor(@Inject(Document.name) private documentModel: typeof Document) {} + constructor( + @Inject(Document.name) + private documentModel: TenantModelProxy, + ) {} /** * Write HTML content to temporary file. - * @param {number} tenantId - Tenant id. * @param {string} content - HTML content. * @returns {Promise<[string, () => Promise]>} */ @@ -31,7 +34,7 @@ export class ChromiumlyHtmlConvert { const filePath = getPdfFilePath(filename); await fs.writeFile(filePath, content); - await this.documentModel + await this.documentModel() .query() .insert({ key: filename, mimeType: 'text/html' }); diff --git a/packages/server-nest/src/modules/CreditNoteRefunds/commands/CreateRefundCreditNote.service.ts b/packages/server-nest/src/modules/CreditNoteRefunds/commands/CreateRefundCreditNote.service.ts index a04eab248..0e61609b4 100644 --- a/packages/server-nest/src/modules/CreditNoteRefunds/commands/CreateRefundCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNoteRefunds/commands/CreateRefundCreditNote.service.ts @@ -12,6 +12,7 @@ import { RefundCreditNote } from '@/modules/CreditNoteRefunds/models/RefundCredi import { CommandCreditNoteDTOTransform } from '@/modules/CreditNotes/commands/CommandCreditNoteDTOTransform.service'; import { CreditNote } from '@/modules/CreditNotes/models/CreditNote'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateRefundCreditNoteService { @@ -19,9 +20,9 @@ export class CreateRefundCreditNoteService { * @param {UnitOfWork} uow - The unit of work service. * @param {EventEmitter2} eventPublisher - The event emitter service. * @param {CommandCreditNoteDTOTransform} commandCreditNoteDTOTransform - The command credit note DTO transform service. - * @param {typeof RefundCreditNote} refundCreditNoteModel - The refund credit note model. - * @param {typeof Account} accountModel - The account model. - * @param {typeof CreditNote} creditNoteModel - The credit note model. + * @param {TenantModelProxy} refundCreditNoteModel - The refund credit note model. + * @param {TenantModelProxy} accountModel - The account model. + * @param {TenantModelProxy} creditNoteModel - The credit note model. */ constructor( private uow: UnitOfWork, @@ -29,10 +30,13 @@ export class CreateRefundCreditNoteService { private commandCreditNoteDTOTransform: CommandCreditNoteDTOTransform, @Inject(RefundCreditNote.name) - private refundCreditNoteModel: typeof RefundCreditNote, + private refundCreditNoteModel: TenantModelProxy, - @Inject(Account.name) private accountModel: typeof Account, - @Inject(CreditNote.name) private creditNoteModel: typeof CreditNote, + @Inject(Account.name) + private accountModel: TenantModelProxy, + + @Inject(CreditNote.name) + private creditNoteModel: TenantModelProxy, ) {} /** @@ -46,13 +50,13 @@ export class CreateRefundCreditNoteService { newCreditNoteDTO: ICreditNoteRefundDTO, ): Promise { // Retrieve the credit note or throw not found service error. - const creditNote = await this.creditNoteModel + const creditNote = await this.creditNoteModel() .query() .findById(creditNoteId) .throwIfNotFound(); // Retrieve the withdrawal account or throw not found service error. - const fromAccount = await this.accountModel + const fromAccount = await this.accountModel() .query() .findById(newCreditNoteDTO.fromAccountId) .throwIfNotFound(); @@ -76,7 +80,7 @@ export class CreateRefundCreditNoteService { } as IRefundCreditNoteCreatingPayload); // Stores the refund credit note graph to the storage layer. - const refundCreditNote = await this.refundCreditNoteModel + const refundCreditNote = await this.refundCreditNoteModel() .query(trx) .insertAndFetch({ ...this.transformDTOToModel(creditNote, newCreditNoteDTO), diff --git a/packages/server-nest/src/modules/CreditNoteRefunds/commands/DeleteRefundCreditNote.service.ts b/packages/server-nest/src/modules/CreditNoteRefunds/commands/DeleteRefundCreditNote.service.ts index 57cd146d0..058592219 100644 --- a/packages/server-nest/src/modules/CreditNoteRefunds/commands/DeleteRefundCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNoteRefunds/commands/DeleteRefundCreditNote.service.ts @@ -8,6 +8,7 @@ import { import { RefundCreditNote } from '../models/RefundCreditNote'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteRefundCreditNoteService { @@ -21,7 +22,9 @@ export class DeleteRefundCreditNoteService { private readonly eventPublisher: EventEmitter2, @Inject(RefundCreditNote.name) - private readonly refundCreditNoteModel: typeof RefundCreditNote, + private readonly refundCreditNoteModel: TenantModelProxy< + typeof RefundCreditNote + >, ) {} /** @@ -31,7 +34,7 @@ export class DeleteRefundCreditNoteService { */ public deleteCreditNoteRefund = async (refundCreditId: number) => { // Retrieve the old credit note or throw not found service error. - const oldRefundCredit = await this.refundCreditNoteModel + const oldRefundCredit = await this.refundCreditNoteModel() .query() .findById(refundCreditId) .throwIfNotFound(); @@ -56,7 +59,7 @@ export class DeleteRefundCreditNoteService { eventPayload, ); // Deletes the refund credit note graph from the storage. - await this.refundCreditNoteModel + await this.refundCreditNoteModel() .query(trx) .findById(refundCreditId) .delete(); diff --git a/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundCreditNote.service.ts b/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundCreditNote.service.ts index 013903895..4153151a8 100644 --- a/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundCreditNote.service.ts @@ -3,15 +3,18 @@ import { ERRORS } from '../../CreditNotes/constants'; import { RefundCreditNote } from '../models/RefundCreditNote'; import { ServiceError } from '@/modules/Items/ServiceError'; import { Account } from '@/modules/Accounts/models/Account.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RefundCreditNoteService { /** - * @param {typeof RefundCreditNote} refundCreditNoteModel - The refund credit note model. + * @param {TenantModelProxy} refundCreditNoteModel - The refund credit note model. */ constructor( @Inject(RefundCreditNote.name) - private readonly refundCreditNoteModel: typeof RefundCreditNote, + private readonly refundCreditNoteModel: TenantModelProxy< + typeof RefundCreditNote + >, ) {} /** @@ -22,7 +25,7 @@ export class RefundCreditNoteService { public getCreditNoteRefundOrThrowError = async ( refundCreditId: number, ): Promise => { - const refundCreditNote = await this.refundCreditNoteModel + const refundCreditNote = await this.refundCreditNoteModel() .query() .findById(refundCreditId); if (!refundCreditNote) { diff --git a/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundSyncCreditNoteBalance.ts b/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundSyncCreditNoteBalance.ts index 0af481a3d..428b55bba 100644 --- a/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundSyncCreditNoteBalance.ts +++ b/packages/server-nest/src/modules/CreditNoteRefunds/commands/RefundSyncCreditNoteBalance.ts @@ -1,15 +1,16 @@ import { Knex } from 'knex'; import { Inject, Injectable } from '@nestjs/common'; import { CreditNote } from '@/modules/CreditNotes/models/CreditNote'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RefundSyncCreditNoteBalanceService { /** - * @param {typeof CreditNote} creditNoteModel - The credit note model. + * @param {TenantModelProxy} creditNoteModel - The credit note model. */ constructor( @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** @@ -21,9 +22,9 @@ export class RefundSyncCreditNoteBalanceService { public incrementCreditNoteRefundAmount = async ( creditNoteId: number, amount: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise => { - await this.creditNoteModel + await this.creditNoteModel() .query(trx) .findById(creditNoteId) .increment('refunded_amount', amount); @@ -38,9 +39,9 @@ export class RefundSyncCreditNoteBalanceService { public decrementCreditNoteRefundAmount = async ( creditNoteId: number, amount: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise => { - await this.creditNoteModel + await this.creditNoteModel() .query(trx) .findById(creditNoteId) .decrement('refunded_amount', amount); diff --git a/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetCreditNoteRefunds.service.ts b/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetCreditNoteRefunds.service.ts index e8b22704e..fd60b4366 100644 --- a/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetCreditNoteRefunds.service.ts +++ b/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetCreditNoteRefunds.service.ts @@ -3,6 +3,7 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { RefundCreditNote } from '../models/RefundCreditNote'; import { RefundCreditNoteTransformer } from '@/modules/CreditNotes/queries/RefundCreditNoteTransformer'; import { IRefundCreditNotePOJO } from '../types/CreditNoteRefunds.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ListCreditNoteRefunds { @@ -10,7 +11,9 @@ export class ListCreditNoteRefunds { private readonly transformer: TransformerInjectable, @Inject(RefundCreditNote.name) - private readonly refundCreditNoteModel: typeof RefundCreditNote, + private readonly refundCreditNoteModel: TenantModelProxy< + typeof RefundCreditNote + >, ) {} /** @@ -22,7 +25,7 @@ export class ListCreditNoteRefunds { creditNoteId: number, ): Promise { // Retrieve refund credit notes associated to the given credit note. - const refundCreditTransactions = await this.refundCreditNoteModel + const refundCreditTransactions = await this.refundCreditNoteModel() .query() .where('creditNoteId', creditNoteId) .withGraphFetched('creditNote') diff --git a/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetRefundCreditNoteTransaction.service.ts b/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetRefundCreditNoteTransaction.service.ts index aaf2201a6..a8df1f92c 100644 --- a/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetRefundCreditNoteTransaction.service.ts +++ b/packages/server-nest/src/modules/CreditNoteRefunds/queries/GetRefundCreditNoteTransaction.service.ts @@ -1,6 +1,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { RefundCreditNote } from '../models/RefundCreditNote'; import { RefundCreditNoteTransformer } from '../../CreditNotes/queries/RefundCreditNoteTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetRefundCreditNoteTransaction { @@ -12,9 +13,10 @@ export class GetRefundCreditNoteTransaction { private readonly transformer: RefundCreditNoteTransformer, @Inject(RefundCreditNote.name) - private readonly refundCreditNoteModel: typeof RefundCreditNote, - ) { - } + private readonly refundCreditNoteModel: TenantModelProxy< + typeof RefundCreditNote + >, + ) {} /** * Retrieve credit note associated invoices to apply. @@ -22,9 +24,9 @@ export class GetRefundCreditNoteTransaction { * @returns {Promise} */ public async getRefundCreditTransaction( - refundCreditId: number + refundCreditId: number, ): Promise { - const refundCreditNote = await this.refundCreditNoteModel + const refundCreditNote = await this.refundCreditNoteModel() .query() .findById(refundCreditId) .withGraphFetched('fromAccount') diff --git a/packages/server-nest/src/modules/CreditNotes/commands/CreateCreditNote.service.ts b/packages/server-nest/src/modules/CreditNotes/commands/CreateCreditNote.service.ts index 4d4fd7205..b82e72393 100644 --- a/packages/server-nest/src/modules/CreditNotes/commands/CreateCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/commands/CreateCreditNote.service.ts @@ -12,6 +12,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateCreditNoteService { @@ -30,10 +31,10 @@ export class CreateCreditNoteService { private readonly commandCreditNoteDTOTransform: CommandCreditNoteDTOTransform, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, @Inject(Contact.name) - private readonly contactModel: typeof Contact, + private readonly contactModel: TenantModelProxy, ) {} /** @@ -49,7 +50,7 @@ export class CreateCreditNoteService { creditNoteDTO, }); // Validate customer existance. - const customer = await this.contactModel + const customer = await this.contactModel() .query() .modify('customer') .findById(creditNoteDTO.customerId) @@ -78,9 +79,11 @@ export class CreateCreditNoteService { } as ICreditNoteCreatingPayload); // Upsert the credit note graph. - const creditNote = await this.creditNoteModel.query(trx).upsertGraph({ - ...creditNoteModel, - }); + const creditNote = await this.creditNoteModel() + .query(trx) + .upsertGraph({ + ...creditNoteModel, + }); // Triggers `onCreditNoteCreated` event. await this.eventPublisher.emitAsync(events.creditNote.onCreated, { creditNoteDTO, diff --git a/packages/server-nest/src/modules/CreditNotes/commands/CreditNoteGLEntries.ts b/packages/server-nest/src/modules/CreditNotes/commands/CreditNoteGLEntries.ts index e2eb4d459..92aba6a07 100644 --- a/packages/server-nest/src/modules/CreditNotes/commands/CreditNoteGLEntries.ts +++ b/packages/server-nest/src/modules/CreditNotes/commands/CreditNoteGLEntries.ts @@ -4,6 +4,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service'; import { CreditNote } from '../models/CreditNote'; import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreditNoteGLEntries { @@ -12,7 +13,7 @@ export class CreditNoteGLEntries { private readonly accountRepository: AccountRepository, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** diff --git a/packages/server-nest/src/modules/CreditNotes/commands/DeleteCreditNote.service.ts b/packages/server-nest/src/modules/CreditNotes/commands/DeleteCreditNote.service.ts index def8bfc67..beb16d606 100644 --- a/packages/server-nest/src/modules/CreditNotes/commands/DeleteCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/commands/DeleteCreditNote.service.ts @@ -7,14 +7,13 @@ import { import { ERRORS } from '../constants'; import { CreditNote } from '../models/CreditNote'; import { CreditNoteAppliedInvoice } from '../../CreditNotesApplyInvoice/models/CreditNoteAppliedInvoice'; -import { - RefundCreditNote as RefundCreditNoteModel, -} from '../../CreditNoteRefunds/models/RefundCreditNote'; +import { RefundCreditNote as RefundCreditNoteModel } from '../../CreditNoteRefunds/models/RefundCreditNote'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry'; import { ServiceError } from '@/modules/Items/ServiceError'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteCreditNoteService { @@ -31,16 +30,20 @@ export class DeleteCreditNoteService { private readonly eventPublisher: EventEmitter2, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, @Inject(ItemEntry.name) - private readonly itemEntryModel: typeof ItemEntry, + private readonly itemEntryModel: TenantModelProxy, @Inject(CreditNoteAppliedInvoice.name) - private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice, + private readonly creditNoteAppliedInvoiceModel: TenantModelProxy< + typeof CreditNoteAppliedInvoice + >, @Inject(RefundCreditNoteModel.name) - private readonly refundCreditNoteModel: typeof RefundCreditNoteModel, + private readonly refundCreditNoteModel: TenantModelProxy< + typeof RefundCreditNoteModel + >, ) {} /** @@ -50,7 +53,7 @@ export class DeleteCreditNoteService { */ public async deleteCreditNote(creditNoteId: number): Promise { // Retrieve the credit note or throw not found service error. - const oldCreditNote = await this.creditNoteModel + const oldCreditNote = await this.creditNoteModel() .query() .findById(creditNoteId) .throwIfNotFound(); @@ -70,14 +73,14 @@ export class DeleteCreditNoteService { } as ICreditNoteDeletingPayload); // Deletes the associated credit note entries. - await this.itemEntryModel + await this.itemEntryModel() .query(trx) .where('reference_id', creditNoteId) .where('reference_type', 'CreditNote') .delete(); // Deletes the credit note transaction. - await this.creditNoteModel.query(trx).findById(creditNoteId).delete(); + await this.creditNoteModel().query(trx).findById(creditNoteId).delete(); // Triggers `onCreditNoteDeleted` event. await this.eventPublisher.emitAsync(events.creditNote.onDeleted, { @@ -96,7 +99,7 @@ export class DeleteCreditNoteService { private async validateCreditNoteHasNoRefundTransactions( creditNoteId: number, ): Promise { - const refundTransactions = await this.refundCreditNoteModel + const refundTransactions = await this.refundCreditNoteModel() .query() .where('creditNoteId', creditNoteId); @@ -113,7 +116,7 @@ export class DeleteCreditNoteService { private async validateCreditNoteHasNoApplyInvoiceTransactions( creditNoteId: number, ): Promise { - const appliedTransactions = await this.creditNoteAppliedInvoiceModel + const appliedTransactions = await this.creditNoteAppliedInvoiceModel() .query() .where('creditNoteId', creditNoteId); diff --git a/packages/server-nest/src/modules/CreditNotes/commands/EditCreditNote.service.ts b/packages/server-nest/src/modules/CreditNotes/commands/EditCreditNote.service.ts index 330561a6c..d263d567f 100644 --- a/packages/server-nest/src/modules/CreditNotes/commands/EditCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/commands/EditCreditNote.service.ts @@ -12,6 +12,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { CommandCreditNoteDTOTransform } from './CommandCreditNoteDTOTransform.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditCreditNoteService { @@ -24,8 +25,11 @@ export class EditCreditNoteService { * @param {UnitOfWork} uow - The unit of work. */ constructor( - @Inject(CreditNote.name) private creditNoteModel: typeof CreditNote, - @Inject(Contact.name) private contactModel: typeof Contact, + @Inject(CreditNote.name) + private creditNoteModel: TenantModelProxy, + @Inject(Contact.name) + private contactModel: TenantModelProxy, + private commandCreditNoteDTOTransform: CommandCreditNoteDTOTransform, private itemsEntriesService: ItemsEntriesService, private eventPublisher: EventEmitter2, @@ -41,13 +45,13 @@ export class EditCreditNoteService { creditNoteEditDTO: ICreditNoteEditDTO, ) { // Retrieve the sale invoice or throw not found service error. - const oldCreditNote = await this.creditNoteModel + const oldCreditNote = await this.creditNoteModel() .query() .findById(creditNoteId) .throwIfNotFound(); // Validate customer existance. - const customer = await this.contactModel + const customer = await this.contactModel() .query() .findById(creditNoteEditDTO.customerId); @@ -82,10 +86,12 @@ export class EditCreditNoteService { } as ICreditNoteEditingPayload); // Saves the credit note graph to the storage. - const creditNote = await this.creditNoteModel.query(trx).upsertGraph({ - id: creditNoteId, - ...creditNoteModel, - }); + const creditNote = await this.creditNoteModel() + .query(trx) + .upsertGraph({ + id: creditNoteId, + ...creditNoteModel, + }); // Triggers `onCreditNoteEdited` event. await this.eventPublisher.emitAsync(events.creditNote.onEdited, { trx, diff --git a/packages/server-nest/src/modules/CreditNotes/commands/OpenCreditNote.service.ts b/packages/server-nest/src/modules/CreditNotes/commands/OpenCreditNote.service.ts index 3b5345c20..ac3101f10 100644 --- a/packages/server-nest/src/modules/CreditNotes/commands/OpenCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/commands/OpenCreditNote.service.ts @@ -10,6 +10,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { CreditNote } from '../models/CreditNote'; import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class OpenCreditNoteService { @@ -23,7 +24,7 @@ export class OpenCreditNoteService { private readonly uow: UnitOfWork, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** @@ -33,7 +34,7 @@ export class OpenCreditNoteService { */ public openCreditNote = async (creditNoteId: number): Promise => { // Retrieve the sale invoice or throw not found service error. - const oldCreditNote = await this.creditNoteModel + const oldCreditNote = await this.creditNoteModel() .query() .findById(creditNoteId) .throwIfNotFound(); @@ -59,7 +60,7 @@ export class OpenCreditNoteService { eventPayload, ); // Saves the credit note graph to the storage. - const creditNote = await this.creditNoteModel + const creditNote = await this.creditNoteModel() .query(trx) .updateAndFetchById(creditNoteId, { openedAt: new Date(), diff --git a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNote.service.ts b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNote.service.ts index 6e2126be2..498e7e187 100644 --- a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNote.service.ts @@ -4,6 +4,7 @@ import { CreditNoteTransformer } from './CreditNoteTransformer'; import { Inject, Injectable } from '@nestjs/common'; import { CreditNote } from '../models/CreditNote'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNote { @@ -11,18 +12,16 @@ export class GetCreditNote { private readonly transformer: TransformerInjectable, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** * Retrieve the credit note graph. - * @param {number} tenantId * @param {number} creditNoteId - * @returns */ public async getCreditNote(creditNoteId: number) { // Retrieve the vendor credit model graph. - const creditNote = await this.creditNoteModel + const creditNote = await this.creditNoteModel() .query() .findById(creditNoteId) .withGraphFetched('entries.item') diff --git a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotePdf.serivce.ts b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotePdf.serivce.ts index abdacff49..80cc91477 100644 --- a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotePdf.serivce.ts +++ b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotePdf.serivce.ts @@ -9,6 +9,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNotePdf { @@ -29,10 +30,12 @@ export class GetCreditNotePdf { private readonly eventPublisher: EventEmitter2, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, ) {} /** @@ -69,7 +72,7 @@ export class GetCreditNotePdf { * @returns {Promise} */ public async getCreditNoteFilename(creditNoteId: number): Promise { - const creditNote = await this.creditNoteModel + const creditNote = await this.creditNoteModel() .query() .findById(creditNoteId); return `Credit-${creditNote.creditNoteNumber}`; @@ -90,7 +93,7 @@ export class GetCreditNotePdf { const templateId = creditNote.pdfTemplateId ?? ( - await this.pdfTemplateModel.query().findOne({ + await this.pdfTemplateModel().query().findOne({ resource: 'CreditNote', default: true, }) diff --git a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNoteState.service.ts b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNoteState.service.ts index 1138264d1..adfe1a342 100644 --- a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNoteState.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNoteState.service.ts @@ -1,12 +1,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { ICreditNoteState } from '../types/CreditNotes.types'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNoteState { constructor( @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -14,7 +15,8 @@ export class GetCreditNoteState { * @return {Promise} */ public async getCreditNoteState(): Promise { - const defaultPdfTemplate = await this.pdfTemplateModel.query() + const defaultPdfTemplate = await this.pdfTemplateModel() + .query() .findOne({ resource: 'CreditNote' }) .modify('default'); diff --git a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotes.service.ts b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotes.service.ts index db2c71b4d..7457c923b 100644 --- a/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotes.service.ts +++ b/packages/server-nest/src/modules/CreditNotes/queries/GetCreditNotes.service.ts @@ -1,11 +1,15 @@ import * as R from 'ramda'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service'; -import { GetCreditNotesResponse, ICreditNotesQueryDTO } from '../types/CreditNotes.types'; +import { + GetCreditNotesResponse, + ICreditNotesQueryDTO, +} from '../types/CreditNotes.types'; import { CreditNote } from '../models/CreditNote'; import { CreditNoteTransformer } from './CreditNoteTransformer'; import { Inject } from '@nestjs/common'; import { Injectable } from '@nestjs/common'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNotesService { @@ -14,7 +18,7 @@ export class GetCreditNotesService { private readonly transformer: TransformerInjectable, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** @@ -39,10 +43,10 @@ export class GetCreditNotesService { // Dynamic list service. const dynamicFilter = await this.dynamicListService.dynamicList( - this.creditNoteModel, + this.creditNoteModel(), filter, ); - const { results, pagination } = await this.creditNoteModel + const { results, pagination } = await this.creditNoteModel() .query() .onBuild((builder) => { builder.withGraphFetched('entries.item'); diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncCredit.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncCredit.service.ts index 8b7a58964..30fcce60a 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncCredit.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncCredit.service.ts @@ -1,12 +1,13 @@ import { Knex } from 'knex'; import { Inject, Injectable } from '@nestjs/common'; import { CreditNote } from '../../CreditNotes/models/CreditNote'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreditNoteApplySyncCredit { constructor( @Inject(CreditNote.name) - private creditNoteModel: typeof CreditNote, + private creditNoteModel: TenantModelProxy, ) {} /** @@ -20,7 +21,7 @@ export class CreditNoteApplySyncCredit { invoicesAppliedAmount: number, trx?: Knex.Transaction, ): Promise { - await this.creditNoteModel + await this.creditNoteModel() .query(trx) .findById(creditNoteId) .increment('invoicesAmount', invoicesAppliedAmount); @@ -37,7 +38,7 @@ export class CreditNoteApplySyncCredit { invoicesAppliedAmount: number, trx?: Knex.Transaction, ): Promise { - await this.creditNoteModel + await this.creditNoteModel() .query(trx) .findById(creditNoteId) .decrement('invoicesAmount', invoicesAppliedAmount); diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncInvoices.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncInvoices.service.ts index 06ac32ed1..efc14b72f 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncInvoices.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplySyncInvoices.service.ts @@ -4,6 +4,7 @@ import Bluebird from 'bluebird'; import { ICreditNoteAppliedToInvoice } from '../types/CreditNoteApplyInvoice.types'; import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice'; import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreditNoteApplySyncInvoicesCreditedAmount { @@ -12,7 +13,7 @@ export class CreditNoteApplySyncInvoicesCreditedAmount { */ constructor( @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -22,30 +23,32 @@ export class CreditNoteApplySyncInvoicesCreditedAmount { */ public incrementInvoicesCreditedAmount = async ( creditNoteAppliedInvoices: ICreditNoteAppliedToInvoice[], - trx?: Knex.Transaction + trx?: Knex.Transaction, ) => { await Bluebird.each( creditNoteAppliedInvoices, (creditNoteAppliedInvoice: CreditNoteAppliedInvoice) => { - return this.saleInvoiceModel.query(trx) + return this.saleInvoiceModel() + .query(trx) .where('id', creditNoteAppliedInvoice.invoiceId) .increment('creditedAmount', creditNoteAppliedInvoice.amount); - } + }, ); }; /** * * @param {number} invoicesIds - * @param {number} amount - - * @param {Knex.Transaction} knex - + * @param {number} amount - + * @param {Knex.Transaction} knex - */ public decrementInvoiceCreditedAmount = async ( invoiceId: number, amount: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) => { - await this.saleInvoiceModel.query(trx) + await this.saleInvoiceModel() + .query(trx) .findById(invoiceId) .decrement('creditedAmount', amount); }; diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplyToInvoices.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplyToInvoices.service.ts index ab462f48d..c58254bc7 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplyToInvoices.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/CreditNoteApplyToInvoices.service.ts @@ -16,6 +16,7 @@ import { ServiceError } from '@/modules/Items/ServiceError'; import { CreditNote } from '@/modules/CreditNotes/models/CreditNote'; import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice'; import { CommandCreditNoteDTOTransform } from '@/modules/CreditNotes/commands/CommandCreditNoteDTOTransform.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreditNoteApplyToInvoices { @@ -32,10 +33,12 @@ export class CreditNoteApplyToInvoices { private readonly creditNoteDTOTransform: CommandCreditNoteDTOTransform, @Inject(CreditNoteAppliedInvoice.name) - private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice, + private readonly creditNoteAppliedInvoiceModel: TenantModelProxy< + typeof CreditNoteAppliedInvoice + >, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** @@ -48,7 +51,7 @@ export class CreditNoteApplyToInvoices { applyCreditToInvoicesDTO: IApplyCreditToInvoicesDTO, ): Promise { // Saves the credit note or throw not found service error. - const creditNote = await this.creditNoteModel + const creditNote = await this.creditNoteModel() .query() .findById(creditNoteId) .throwIfNotFound(); @@ -78,9 +81,10 @@ export class CreditNoteApplyToInvoices { // Creates credit note apply to invoice transaction. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Saves the credit note apply to invoice graph to the storage layer. - const creditNoteAppliedInvoices = await this.creditNoteAppliedInvoiceModel - .query() - .insertGraph(creditNoteAppliedModel.entries); + const creditNoteAppliedInvoices = + await this.creditNoteAppliedInvoiceModel() + .query() + .insertGraph(creditNoteAppliedModel.entries); // Triggers `onCreditNoteApplyToInvoiceCreated` event. await this.eventPublisher.emitAsync( diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCreditNoteApplyToInvoices.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCreditNoteApplyToInvoices.service.ts index 1b90ce211..c98ecd2ac 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCreditNoteApplyToInvoices.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCreditNoteApplyToInvoices.service.ts @@ -8,6 +8,7 @@ import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; import { CreditNote } from '../../CreditNotes/models/CreditNote'; import { ERRORS } from '../../CreditNotes/constants'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export default class DeleteCreditNoteApplyToInvoices { @@ -20,10 +21,14 @@ export default class DeleteCreditNoteApplyToInvoices { constructor( private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, - private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice, + + @Inject(CreditNoteAppliedInvoice.name) + private readonly creditNoteAppliedInvoiceModel: TenantModelProxy< + typeof CreditNoteAppliedInvoice + >, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** @@ -34,15 +39,16 @@ export default class DeleteCreditNoteApplyToInvoices { public deleteApplyCreditNoteToInvoices = async ( applyCreditToInvoicesId: number, ): Promise => { - const creditNoteAppliedToInvoice = await this.creditNoteAppliedInvoiceModel - .query() - .findById(applyCreditToInvoicesId); + const creditNoteAppliedToInvoice = + await this.creditNoteAppliedInvoiceModel() + .query() + .findById(applyCreditToInvoicesId); if (!creditNoteAppliedToInvoice) { throw new ServiceError(ERRORS.CREDIT_NOTE_APPLY_TO_INVOICES_NOT_FOUND); } // Retrieve the credit note or throw not found service error. - const creditNote = await this.creditNoteModel + const creditNote = await this.creditNoteModel() .query() .findById(creditNoteAppliedToInvoice.creditNoteId) .throwIfNotFound(); @@ -50,7 +56,7 @@ export default class DeleteCreditNoteApplyToInvoices { // Creates credit note apply to invoice transaction. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Delete credit note applied to invoices. - await this.creditNoteAppliedInvoiceModel + await this.creditNoteAppliedInvoiceModel() .query(trx) .findById(applyCreditToInvoicesId) .delete(); diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCustomerLinkedCreditNote.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCustomerLinkedCreditNote.service.ts index 914eb58e6..500dd8f9c 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCustomerLinkedCreditNote.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/commands/DeleteCustomerLinkedCreditNote.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { CreditNote } from '../../CreditNotes/models/CreditNote'; import { ERRORS } from '../../CreditNotes/constants'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteCustomerLinkedCreditNoteService { @@ -10,7 +11,7 @@ export class DeleteCustomerLinkedCreditNoteService { */ constructor( @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote, + private readonly creditNoteModel: TenantModelProxy, ) {} /** @@ -18,7 +19,7 @@ export class DeleteCustomerLinkedCreditNoteService { * @param {number} customerId - The customer identifier. */ public async validateCustomerHasNoCreditTransaction(customerId: number) { - const associatedCredits = await this.creditNoteModel + const associatedCredits = await this.creditNoteModel() .query() .where('customerId', customerId); diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedAppliedInvoices.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedAppliedInvoices.service.ts index c7fa4eccb..4d0af7722 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedAppliedInvoices.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedAppliedInvoices.service.ts @@ -3,6 +3,7 @@ import { CreditNoteAppliedInvoiceTransformer } from './CreditNoteAppliedInvoiceT import { CreditNote } from '../../CreditNotes/models/CreditNote'; import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service'; import { CreditNoteAppliedInvoice } from '../models/CreditNoteAppliedInvoice'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNoteAssociatedAppliedInvoices { @@ -11,9 +12,8 @@ export class GetCreditNoteAssociatedAppliedInvoices { private readonly creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice, @Inject(CreditNote.name) - private readonly creditNoteModel: typeof CreditNote - ) { - } + private readonly creditNoteModel: TenantModelProxy, + ) {} /** * Retrieve credit note associated invoices to apply. @@ -21,14 +21,16 @@ export class GetCreditNoteAssociatedAppliedInvoices { * @returns {Promise} */ public async getCreditAssociatedAppliedInvoices( - creditNoteId: number + creditNoteId: number, ): Promise { // Retrieve credit note or throw not found service error. - const creditNote = await this.creditNoteModel.query() + const creditNote = await this.creditNoteModel() + .query() .findById(creditNoteId) .throwIfNotFound(); - const appliedToInvoices = await this.creditNoteAppliedInvoiceModel.query() + const appliedToInvoices = await this.creditNoteAppliedInvoiceModel + .query() .where('credit_note_id', creditNoteId) .withGraphFetched('saleInvoice') .withGraphFetched('creditNote'); @@ -36,7 +38,7 @@ export class GetCreditNoteAssociatedAppliedInvoices { // Transforms credit note applied to invoices. return this.transformer.transform( appliedToInvoices, - new CreditNoteAppliedInvoiceTransformer() + new CreditNoteAppliedInvoiceTransformer(), ); } } diff --git a/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedInvoicesToApply.service.ts b/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedInvoicesToApply.service.ts index 6feb4c006..83a975071 100644 --- a/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedInvoicesToApply.service.ts +++ b/packages/server-nest/src/modules/CreditNotesApplyInvoice/queries/GetCreditNoteAssociatedInvoicesToApply.service.ts @@ -3,6 +3,7 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice'; import { GetCreditNote } from '../../CreditNotes/queries/GetCreditNote.service'; import { CreditNoteWithInvoicesToApplyTransformer } from './CreditNoteWithInvoicesToApplyTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCreditNoteAssociatedInvoicesToApply { @@ -16,7 +17,7 @@ export class GetCreditNoteAssociatedInvoicesToApply { private getCreditNote: GetCreditNote, @Inject(SaleInvoice.name) - private saleInvoiceModel: typeof SaleInvoice, + private saleInvoiceModel: TenantModelProxy, ) {} /** @@ -31,7 +32,7 @@ export class GetCreditNoteAssociatedInvoicesToApply { const creditNote = await this.getCreditNote.getCreditNote(creditNoteId); // Retrieves the published due invoices that associated to the given customer. - const saleInvoices = await this.saleInvoiceModel + const saleInvoices = await this.saleInvoiceModel() .query() .where('customerId', creditNote.customerId) .modify('dueInvoices') diff --git a/packages/server-nest/src/modules/Customers/commands/ActivateCustomer.service.ts b/packages/server-nest/src/modules/Customers/commands/ActivateCustomer.service.ts index adc6dbbf1..8a497fb22 100644 --- a/packages/server-nest/src/modules/Customers/commands/ActivateCustomer.service.ts +++ b/packages/server-nest/src/modules/Customers/commands/ActivateCustomer.service.ts @@ -9,6 +9,7 @@ import { import { Customer } from '@/modules/Customers/models/Customer'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ActivateCustomer { @@ -24,7 +25,7 @@ export class ActivateCustomer { private validators: CustomerValidators, @Inject(Customer.name) - private customerModel: typeof Customer, + private customerModel: TenantModelProxy, ) {} /** @@ -34,7 +35,7 @@ export class ActivateCustomer { */ public async activateCustomer(customerId: number): Promise { // Retrieves the customer or throw not found error. - const oldCustomer = await this.customerModel + const oldCustomer = await this.customerModel() .query() .findById(customerId) .throwIfNotFound(); @@ -50,7 +51,7 @@ export class ActivateCustomer { } as ICustomerActivatingPayload); // Update the given customer details. - const customer = await this.customerModel + const customer = await this.customerModel() .query(trx) .findById(customerId) .updateAndFetchById(customerId, { active: true }); diff --git a/packages/server-nest/src/modules/Customers/commands/CreateCustomer.service.ts b/packages/server-nest/src/modules/Customers/commands/CreateCustomer.service.ts index a9d5a0a8c..4f40dd0c9 100644 --- a/packages/server-nest/src/modules/Customers/commands/CreateCustomer.service.ts +++ b/packages/server-nest/src/modules/Customers/commands/CreateCustomer.service.ts @@ -10,6 +10,7 @@ import { ICustomerEventCreatingPayload, ICustomerNewDTO, } from '../types/Customers.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateCustomer { @@ -25,7 +26,7 @@ export class CreateCustomer { private readonly customerDTO: CreateEditCustomerDTO, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -49,9 +50,11 @@ export class CreateCustomer { } as ICustomerEventCreatingPayload); // Creates a new contact as customer. - const customer = await this.customerModel.query(trx).insertAndFetch({ - ...customerObj, - }); + const customer = await this.customerModel() + .query(trx) + .insertAndFetch({ + ...customerObj, + }); // Triggers `onCustomerCreated` event. await this.eventPublisher.emitAsync(events.customers.onCreated, { customer, diff --git a/packages/server-nest/src/modules/Customers/commands/CreateEditCustomerDTO.service.ts b/packages/server-nest/src/modules/Customers/commands/CreateEditCustomerDTO.service.ts index 4a2605eec..250357666 100644 --- a/packages/server-nest/src/modules/Customers/commands/CreateEditCustomerDTO.service.ts +++ b/packages/server-nest/src/modules/Customers/commands/CreateEditCustomerDTO.service.ts @@ -14,7 +14,7 @@ export class CreateEditCustomerDTO { /** * Transformes the create/edit DTO. - * @param {ICustomerNewDTO | ICustomerEditDTO} customerDTO + * @param {ICustomerNewDTO | ICustomerEditDTO} customerDTO * @returns */ private transformCommonDTO = ( diff --git a/packages/server-nest/src/modules/Customers/commands/DeleteCustomer.service.ts b/packages/server-nest/src/modules/Customers/commands/DeleteCustomer.service.ts index 623bbc474..8e54509de 100644 --- a/packages/server-nest/src/modules/Customers/commands/DeleteCustomer.service.ts +++ b/packages/server-nest/src/modules/Customers/commands/DeleteCustomer.service.ts @@ -8,6 +8,7 @@ import { import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Customer } from '../models/Customer'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteCustomer { @@ -19,7 +20,9 @@ export class DeleteCustomer { constructor( private uow: UnitOfWork, private eventPublisher: EventEmitter2, - @Inject(Customer.name) private customerModel: typeof Customer, + + @Inject(Customer.name) + private customerModel: TenantModelProxy, ) {} /** @@ -27,17 +30,15 @@ export class DeleteCustomer { * @param {number} customerId - Customer ID. * @return {Promise} */ - public async deleteCustomer( - customerId: number, - ): Promise { + public async deleteCustomer(customerId: number): Promise { // Retrieve the customer or throw not found service error. - const oldCustomer = await this.customerModel + const oldCustomer = await this.customerModel() .query() .findById(customerId) .throwIfNotFound(); - // .queryAndThrowIfHasRelations({ - // type: ERRORS.CUSTOMER_HAS_TRANSACTIONS, - // }); + // .queryAndThrowIfHasRelations({ + // type: ERRORS.CUSTOMER_HAS_TRANSACTIONS, + // }); // Triggers `onCustomerDeleting` event. await this.eventPublisher.emitAsync(events.customers.onDeleting, { @@ -48,7 +49,7 @@ export class DeleteCustomer { // Deletes the customer and associated entities under UOW transaction. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Delete the customer from the storage. - await this.customerModel.query(trx).findById(customerId).delete(); + await this.customerModel().query(trx).findById(customerId).delete(); // Throws `onCustomerDeleted` event. await this.eventPublisher.emitAsync(events.customers.onDeleted, { diff --git a/packages/server-nest/src/modules/Customers/commands/EditCustomer.service.ts b/packages/server-nest/src/modules/Customers/commands/EditCustomer.service.ts index 1cfdcca56..3fa40273d 100644 --- a/packages/server-nest/src/modules/Customers/commands/EditCustomer.service.ts +++ b/packages/server-nest/src/modules/Customers/commands/EditCustomer.service.ts @@ -10,6 +10,7 @@ import { Customer } from '../models/Customer'; import { events } from '@/common/events/events'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditCustomer { @@ -17,13 +18,15 @@ export class EditCustomer { * @param {UnitOfWork} uow - Unit of work service. * @param {EventEmitter2} eventPublisher - Event emitter service. * @param {CreateEditCustomerDTO} customerDTO - Customer DTO. - * @param {typeof Customer} contactModel - Customer model. + * @param {TenantModelProxy} contactModel - Customer model. */ constructor( private uow: UnitOfWork, private eventPublisher: EventEmitter2, private customerDTO: CreateEditCustomerDTO, - @Inject(Customer.name) private customerModel: typeof Customer, + + @Inject(Customer.name) + private customerModel: TenantModelProxy, ) {} /** @@ -37,7 +40,7 @@ export class EditCustomer { customerDTO: ICustomerEditDTO, ): Promise { // Retrieve the customer or throw not found error. - const oldCustomer = await this.customerModel + const oldCustomer = await this.customerModel() .query() .findById(customerId) .throwIfNotFound(); @@ -55,7 +58,7 @@ export class EditCustomer { } as ICustomerEventEditingPayload); // Edits the customer details on the storage. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .updateAndFetchById(customerId, { ...customerObj, diff --git a/packages/server-nest/src/modules/Customers/commands/EditOpeningBalanceCustomer.service.ts b/packages/server-nest/src/modules/Customers/commands/EditOpeningBalanceCustomer.service.ts index 871f1c6e9..b58165ab6 100644 --- a/packages/server-nest/src/modules/Customers/commands/EditOpeningBalanceCustomer.service.ts +++ b/packages/server-nest/src/modules/Customers/commands/EditOpeningBalanceCustomer.service.ts @@ -9,6 +9,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Customer } from '../models/Customer'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditOpeningBalanceCustomer { @@ -20,7 +21,9 @@ export class EditOpeningBalanceCustomer { constructor( private eventPublisher: EventEmitter2, private uow: UnitOfWork, - @Inject(Customer.name) private customerModel: typeof Customer, + + @Inject(Customer.name) + private customerModel: TenantModelProxy, ) {} /** @@ -33,7 +36,7 @@ export class EditOpeningBalanceCustomer { openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO, ): Promise { // Retrieves the old customer or throw not found error. - const oldCustomer = await this.customerModel + const oldCustomer = await this.customerModel() .query() .findById(customerId) .throwIfNotFound(); @@ -50,7 +53,7 @@ export class EditOpeningBalanceCustomer { } as ICustomerOpeningBalanceEditingPayload, ); // Mutates the customer on the storage. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .patchAndFetchById(customerId, { ...openingBalanceEditDTO, diff --git a/packages/server-nest/src/modules/Customers/queries/GetCustomer.service.ts b/packages/server-nest/src/modules/Customers/queries/GetCustomer.service.ts index 64c30960e..061d0e77e 100644 --- a/packages/server-nest/src/modules/Customers/queries/GetCustomer.service.ts +++ b/packages/server-nest/src/modules/Customers/queries/GetCustomer.service.ts @@ -1,14 +1,16 @@ - import { Inject, Injectable } from '@nestjs/common'; import { CustomerTransfromer } from './CustomerTransformer'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { Customer } from '../models/Customer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCustomerService { constructor( private transformer: TransformerInjectable, - @Inject(Customer.name) private customerModel: typeof Customer, + + @Inject(Customer.name) + private customerModel: TenantModelProxy, ) {} /** @@ -17,15 +19,12 @@ export class GetCustomerService { */ public async getCustomer(customerId: number) { // Retrieve the customer model or throw not found error. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .findById(customerId) .throwIfNotFound(); // Retrieves the transformered customers. - return this.transformer.transform( - customer, - new CustomerTransfromer() - ); + return this.transformer.transform(customer, new CustomerTransfromer()); } } diff --git a/packages/server-nest/src/modules/Customers/queries/GetCustomers.service.ts b/packages/server-nest/src/modules/Customers/queries/GetCustomers.service.ts index 62338d06f..32601334a 100644 --- a/packages/server-nest/src/modules/Customers/queries/GetCustomers.service.ts +++ b/packages/server-nest/src/modules/Customers/queries/GetCustomers.service.ts @@ -8,6 +8,7 @@ import { GetCustomersResponse, ICustomersFilter, } from '../types/Customers.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetCustomers { @@ -15,7 +16,8 @@ export class GetCustomers { private dynamicListService: DynamicListService, private transformer: TransformerInjectable, - @Inject(Customer.name) private customerModel: typeof Customer, + @Inject(Customer.name) + private customerModel: TenantModelProxy, ) {} /** @@ -38,10 +40,10 @@ export class GetCustomers { const filter = this.parseCustomersListFilterDTO(filterDTO); const dynamicList = await this.dynamicListService.dynamicList( - this.customerModel, + this.customerModel(), filter, ); - const { results, pagination } = await this.customerModel + const { results, pagination } = await this.customerModel() .query() .onBuild((builder) => { dynamicList.buildQuery()(builder); diff --git a/packages/server-nest/src/modules/Expenses/Expenses.module.ts b/packages/server-nest/src/modules/Expenses/Expenses.module.ts index 889215104..f00b75f14 100644 --- a/packages/server-nest/src/modules/Expenses/Expenses.module.ts +++ b/packages/server-nest/src/modules/Expenses/Expenses.module.ts @@ -21,9 +21,7 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module'; @Module({ imports: [LedgerModule, BranchesModule, DynamicListModule], controllers: [ExpensesController], - exports: [ - CreateExpense, - ], + exports: [CreateExpense], providers: [ CreateExpense, ExpenseDTOTransformer, @@ -42,4 +40,3 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module'; ], }) export class ExpensesModule {} - diff --git a/packages/server-nest/src/modules/Expenses/commands/CreateExpense.service.ts b/packages/server-nest/src/modules/Expenses/commands/CreateExpense.service.ts index cb7d5c03d..82144a71a 100644 --- a/packages/server-nest/src/modules/Expenses/commands/CreateExpense.service.ts +++ b/packages/server-nest/src/modules/Expenses/commands/CreateExpense.service.ts @@ -12,6 +12,7 @@ import { Expense } from '@/modules/Expenses/models/Expense.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateExpense { @@ -30,10 +31,10 @@ export class CreateExpense { private readonly transformDTO: ExpenseDTOTransformer, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(Expense.name) - private readonly expenseModel: typeof Expense, + private readonly expenseModel: TenantModelProxy, ) {} /** @@ -42,7 +43,7 @@ export class CreateExpense { */ private authorize = async (expenseDTO: IExpenseCreateDTO) => { // Validate payment account existance on the storage. - const paymentAccount = await this.accountModel + const paymentAccount = await this.accountModel() .query() .findById(expenseDTO.paymentAccountId) .throwIfNotFound(); @@ -52,7 +53,7 @@ export class CreateExpense { (category) => category.expenseAccountId, ); // Retrieves the expenses accounts. - const expenseAccounts = await this.accountModel + const expenseAccounts = await this.accountModel() .query() .whereIn('id', DTOExpenseAccountsIds); // Validate expense accounts exist on the storage. @@ -104,7 +105,7 @@ export class CreateExpense { } as IExpenseCreatingPayload); // Creates a new expense transaction graph. - const expense = await this.expenseModel + const expense = await this.expenseModel() .query(trx) .upsertGraph(expenseObj); // Triggers `onExpenseCreated` event. diff --git a/packages/server-nest/src/modules/Expenses/commands/DeleteExpense.service.ts b/packages/server-nest/src/modules/Expenses/commands/DeleteExpense.service.ts index b7f8620d3..5820642a2 100644 --- a/packages/server-nest/src/modules/Expenses/commands/DeleteExpense.service.ts +++ b/packages/server-nest/src/modules/Expenses/commands/DeleteExpense.service.ts @@ -10,6 +10,7 @@ import { IExpenseEventDeletePayload, IExpenseDeletingPayload, } from '../interfaces/Expenses.interface'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteExpense { @@ -17,18 +18,19 @@ export class DeleteExpense { * @param {EventEmitter2} eventEmitter - Event emitter. * @param {UnitOfWork} uow - Unit of work. * @param {CommandExpenseValidator} validator - Command expense validator. - * @param {typeof Expense} expenseModel - Expense model. - * @param {typeof ExpenseCategory} expenseCategoryModel - Expense category model. + * @param {TenantModelProxy} expenseModel - Expense model. + * @param {TenantModelProxy} expenseCategoryModel - Expense category model. */ constructor( private readonly eventEmitter: EventEmitter2, private readonly uow: UnitOfWork, private readonly validator: CommandExpenseValidator, + @Inject(Expense.name) - private expenseModel: typeof Expense, + private expenseModel: TenantModelProxy, @Inject(ExpenseCategory.name) - private expenseCategoryModel: typeof ExpenseCategory, + private expenseCategoryModel: TenantModelProxy, ) {} /** @@ -39,7 +41,7 @@ export class DeleteExpense { public async deleteExpense(expenseId: number): Promise { // Retrieves the expense transaction with associated entries or // throw not found error. - const oldExpense = await this.expenseModel + const oldExpense = await this.expenseModel() .query() .findById(expenseId) .withGraphFetched('categories') @@ -58,13 +60,13 @@ export class DeleteExpense { } as IExpenseDeletingPayload); // Deletes expense associated entries. - await this.expenseCategoryModel + await this.expenseCategoryModel() .query(trx) .where('expenseId', expenseId) .delete(); // Deletes expense transactions. - await this.expenseModel.query(trx).findById(expenseId).delete(); + await this.expenseModel().query(trx).findById(expenseId).delete(); // Triggers `onExpenseDeleted` event. await this.eventEmitter.emitAsync(events.expenses.onDeleted, { diff --git a/packages/server-nest/src/modules/Expenses/commands/EditExpense.service.ts b/packages/server-nest/src/modules/Expenses/commands/EditExpense.service.ts index 94411db8c..5b74228b4 100644 --- a/packages/server-nest/src/modules/Expenses/commands/EditExpense.service.ts +++ b/packages/server-nest/src/modules/Expenses/commands/EditExpense.service.ts @@ -13,6 +13,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Account } from '@/modules/Accounts/models/Account.model'; import { Expense } from '../models/Expense.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditExpense { @@ -31,9 +32,10 @@ export class EditExpense { private transformDTO: ExpenseDTOTransformer, // private entriesService: EntriesService, @Inject(Expense.name) - private expenseModel: typeof Expense, + private expenseModel: TenantModelProxy, + @Inject(Account.name) - private accountModel: typeof Account, + private accountModel: TenantModelProxy, ) {} /** @@ -45,7 +47,7 @@ export class EditExpense { expenseDTO: IExpenseEditDTO, ) => { // Validate payment account existance on the storage. - const paymentAccount = await this.accountModel + const paymentAccount = await this.accountModel() .query() .findById(expenseDTO.paymentAccountId) .throwIfNotFound(); @@ -55,7 +57,7 @@ export class EditExpense { (category) => category.expenseAccountId, ); // Retrieves the expenses accounts. - const expenseAccounts = await this.accountModel + const expenseAccounts = await this.accountModel() .query() .whereIn('id', DTOExpenseAccountsIds); // Validate expense accounts exist on the storage. @@ -103,7 +105,7 @@ export class EditExpense { expenseDTO: IExpenseEditDTO, ): Promise { // Retrieves the expense model or throw not found error. - const oldExpense = await this.expenseModel + const oldExpense = await this.expenseModel() .query() .findById(expenseId) .withGraphFetched('categories') @@ -125,7 +127,7 @@ export class EditExpense { } as IExpenseEventEditingPayload); // Upsert the expense object with expense entries. - const expense = await this.expenseModel + const expense = await this.expenseModel() .query(trx) .upsertGraphAndFetch({ id: expenseId, diff --git a/packages/server-nest/src/modules/Expenses/commands/PublishExpense.service.ts b/packages/server-nest/src/modules/Expenses/commands/PublishExpense.service.ts index 898f8f613..b2baeb813 100644 --- a/packages/server-nest/src/modules/Expenses/commands/PublishExpense.service.ts +++ b/packages/server-nest/src/modules/Expenses/commands/PublishExpense.service.ts @@ -9,6 +9,7 @@ import { Expense } from '../models/Expense.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { EventEmitter2 } from '@nestjs/event-emitter'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PublishExpense { @@ -24,7 +25,7 @@ export class PublishExpense { private readonly validator: CommandExpenseValidator, @Inject(Expense.name) - private readonly expenseModel: typeof Expense, + private readonly expenseModel: TenantModelProxy, ) {} /** @@ -35,7 +36,7 @@ export class PublishExpense { */ public async publishExpense(expenseId: number) { // Retrieves the old expense or throw not found error. - const oldExpense = await this.expenseModel + const oldExpense = await this.expenseModel() .query() .findById(expenseId) .throwIfNotFound(); @@ -53,10 +54,10 @@ export class PublishExpense { } as IExpensePublishingPayload); // Publish the given expense on the storage. - await this.expenseModel.query().findById(expenseId).modify('publish'); + await this.expenseModel().query().findById(expenseId).modify('publish'); // Retrieve the new expense after modification. - const expense = await this.expenseModel + const expense = await this.expenseModel() .query() .findById(expenseId) .withGraphFetched('categories'); diff --git a/packages/server-nest/src/modules/Expenses/queries/GetExpense.service.ts b/packages/server-nest/src/modules/Expenses/queries/GetExpense.service.ts index 5da180083..469bde3df 100644 --- a/packages/server-nest/src/modules/Expenses/queries/GetExpense.service.ts +++ b/packages/server-nest/src/modules/Expenses/queries/GetExpense.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { ExpenseTransfromer } from './Expense.transformer'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { Expense } from '../models/Expense.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetExpenseService { @@ -9,7 +10,7 @@ export class GetExpenseService { private readonly transformerService: TransformerInjectable, @Inject(Expense.name) - private readonly expenseModel: typeof Expense, + private readonly expenseModel: TenantModelProxy, ) {} /** @@ -18,7 +19,7 @@ export class GetExpenseService { * @return {Promise} */ public async getExpense(expenseId: number): Promise { - const expense = await this.expenseModel + const expense = await this.expenseModel() .query() .findById(expenseId) .withGraphFetched('categories.expenseAccount') diff --git a/packages/server-nest/src/modules/Expenses/queries/GetExpenses.service.ts b/packages/server-nest/src/modules/Expenses/queries/GetExpenses.service.ts index 81b1e680e..35209389f 100644 --- a/packages/server-nest/src/modules/Expenses/queries/GetExpenses.service.ts +++ b/packages/server-nest/src/modules/Expenses/queries/GetExpenses.service.ts @@ -6,6 +6,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { IExpensesFilter, IPaginationMeta } from '../Expenses.types'; import { Expense } from '../models/Expense.model'; import { IFilterMeta } from '@/interfaces/Model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetExpensesService { @@ -14,7 +15,7 @@ export class GetExpensesService { private readonly dynamicListService: DynamicListService, @Inject(Expense.name) - private readonly expense: typeof Expense, + private readonly expense: TenantModelProxy, ) {} /** @@ -22,9 +23,7 @@ export class GetExpensesService { * @param {IExpensesFilter} expensesFilter * @return {IExpense[]} */ - public async getExpensesList( - filterDTO: IExpensesFilter - ): Promise<{ + public async getExpensesList(filterDTO: IExpensesFilter): Promise<{ expenses: Expense[]; pagination: IPaginationMeta; filterMeta: IFilterMeta; @@ -34,11 +33,12 @@ export class GetExpensesService { // Dynamic list service. const dynamicList = await this.dynamicListService.dynamicList( - this.expense, - filter + this.expense(), + filter, ); // Retrieves the paginated results. - const { results, pagination } = await this.expense.query() + const { results, pagination } = await this.expense() + .query() .onBuild((builder) => { builder.withGraphFetched('paymentAccount'); builder.withGraphFetched('categories.expenseAccount'); @@ -51,14 +51,14 @@ export class GetExpensesService { // Transformes the expenses models to POJO. const expenses = await this.transformer.transform( results, - new ExpenseTransfromer() + new ExpenseTransfromer(), ); return { expenses, pagination, filterMeta: dynamicList.getResponseMeta(), }; - }; + } /** * Parses filter DTO of expenses list. diff --git a/packages/server-nest/src/modules/Expenses/subscribers/ExpenseGLEntries.service.ts b/packages/server-nest/src/modules/Expenses/subscribers/ExpenseGLEntries.service.ts index 3048607c6..dcd9a2b34 100644 --- a/packages/server-nest/src/modules/Expenses/subscribers/ExpenseGLEntries.service.ts +++ b/packages/server-nest/src/modules/Expenses/subscribers/ExpenseGLEntries.service.ts @@ -3,15 +3,16 @@ import { ExpenseGL } from './ExpenseGL'; import { Inject, Injectable } from '@nestjs/common'; import { Expense } from '../models/Expense.model'; import { ILedger } from '@/modules/Ledger/types/Ledger.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ExpenseGLEntriesService { /** - * @param {typeof Expense} expense - Expense model. + * @param {TenantModelProxy} expense - Expense model. */ constructor( @Inject(Expense.name) - private readonly expense: typeof Expense, + private readonly expense: TenantModelProxy, ) {} /** @@ -24,7 +25,7 @@ export class ExpenseGLEntriesService { expenseId: number, trx?: Knex.Transaction, ): Promise => { - const expense = await this.expense + const expense = await this.expense() .query(trx) .findById(expenseId) .withGraphFetched('categories') diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowRepository.ts b/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowRepository.ts index 6a54ca980..aa012ad89 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowRepository.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowRepository.ts @@ -6,6 +6,7 @@ import { ModelObject } from 'objection'; import { ICashFlowStatementQuery } from './Cashflow.types'; import { Account } from '@/modules/Accounts/models/Account.model'; import { AccountTransaction } from '@/modules/Accounts/models/AccountTransaction.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CashFlowRepository { @@ -15,10 +16,12 @@ export class CashFlowRepository { */ constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(AccountTransaction.name) - private readonly accountTransactionModel: typeof AccountTransaction, + private readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, ) {} /** @@ -42,7 +45,7 @@ export class CashFlowRepository { * @returns {Promise} */ public async cashFlowAccounts(): Promise { - const accounts = await this.accountModel.query(); + const accounts = await this.accountModel().query(); return accounts; } @@ -58,7 +61,7 @@ export class CashFlowRepository { .subtract(1, 'day') .toDate(); - const transactions = await this.accountTransactionModel + const transactions = await this.accountTransactionModel() .query() .onBuild((query) => { query.modify('creditDebitSummation'); @@ -85,19 +88,21 @@ export class CashFlowRepository { const groupByDateType = this.getGroupTypeFromPeriodsType( filter.displayColumnsBy, ); - return await this.accountTransactionModel.query().onBuild((query) => { - query.modify('creditDebitSummation'); - query.modify('groupByDateFormat', groupByDateType); + return await this.accountTransactionModel() + .query() + .onBuild((query) => { + query.modify('creditDebitSummation'); + query.modify('groupByDateFormat', groupByDateType); - query.select('accountId'); + query.select('accountId'); - query.groupBy('accountId'); - query.withGraphFetched('account'); + query.groupBy('accountId'); + query.withGraphFetched('account'); - query.modify('filterDateRange', filter.fromDate, filter.toDate); + query.modify('filterDateRange', filter.fromDate, filter.toDate); - this.commonFilterBranchesQuery(filter, query); - }); + this.commonFilterBranchesQuery(filter, query); + }); } /** @@ -112,18 +117,20 @@ export class CashFlowRepository { const groupByDateType = this.getGroupTypeFromPeriodsType( filter.displayColumnsBy, ); - return await this.accountTransactionModel.query().onBuild((query) => { - query.modify('creditDebitSummation'); - query.modify('groupByDateFormat', groupByDateType); + return await this.accountTransactionModel() + .query() + .onBuild((query) => { + query.modify('creditDebitSummation'); + query.modify('groupByDateFormat', groupByDateType); - query.select('accountId'); - query.groupBy('accountId'); + query.select('accountId'); + query.groupBy('accountId'); - query.withGraphFetched('account'); - query.modify('filterDateRange', filter.fromDate, filter.toDate); + query.withGraphFetched('account'); + query.modify('filterDateRange', filter.fromDate, filter.toDate); - this.commonFilterBranchesQuery(filter, query); - }); + this.commonFilterBranchesQuery(filter, query); + }); } /** @@ -138,18 +145,20 @@ export class CashFlowRepository { filter.displayColumnsBy, ); - return await this.accountTransactionModel.query().onBuild((query) => { - query.modify('creditDebitSummation'); - query.modify('groupByDateFormat', groupByDateType); + return await this.accountTransactionModel() + .query() + .onBuild((query) => { + query.modify('creditDebitSummation'); + query.modify('groupByDateFormat', groupByDateType); - query.select('accountId'); - query.groupBy('accountId'); + query.select('accountId'); + query.groupBy('accountId'); - query.withGraphFetched('account'); - query.modify('filterDateRange', filter.fromDate, filter.toDate); + query.withGraphFetched('account'); + query.modify('filterDateRange', filter.fromDate, filter.toDate); - this.commonFilterBranchesQuery(filter, query); - }); + this.commonFilterBranchesQuery(filter, query); + }); } /** diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowTable.ts b/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowTable.ts index 36c75845d..20a5465b9 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowTable.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/CashFlowStatement/CashFlowTable.ts @@ -239,7 +239,7 @@ export class CashFlowTable { ): ICashFlowStatementSection => { const label = section.footerLabel ? section.footerLabel - : this.i18n.__('Total {{accountName}}', { accountName: section.label }); + : this.i18n.t('Total {{accountName}}', { accountName: section.label }); section.children.push({ sectionType: ICashFlowStatementSectionType.TOTAL, @@ -300,7 +300,7 @@ export class CashFlowTable { * @returns {ITableColumn} */ private totalColumns = (): ITableColumn[] => { - return [{ key: 'total', label: this.i18n.__('Total') }]; + return [{ key: 'total', label: this.i18n.t('Total') }]; }; /** diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/CustomerBalanceSummary/CustomerBalanceSummaryRepository.ts b/packages/server-nest/src/modules/FinancialStatements/modules/CustomerBalanceSummary/CustomerBalanceSummaryRepository.ts index 15682a597..913ea657b 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/CustomerBalanceSummary/CustomerBalanceSummaryRepository.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/CustomerBalanceSummary/CustomerBalanceSummaryRepository.ts @@ -5,18 +5,21 @@ import { AccountTransaction } from '@/modules/Accounts/models/AccountTransaction import { Customer } from '@/modules/Customers/models/Customer'; import { ModelObject } from 'objection'; import { ACCOUNT_TYPE } from '@/constants/accounts'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CustomerBalanceSummaryRepository { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(AccountTransaction.name) - private readonly accountTransactionModel: typeof AccountTransaction, + private readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -27,7 +30,7 @@ export class CustomerBalanceSummaryRepository { public async getCustomers( customersIds: number[], ): Promise[]> { - return await this.customerModel + return await this.customerModel() .query() .orderBy('displayName') .onBuild((query) => { @@ -42,7 +45,7 @@ export class CustomerBalanceSummaryRepository { * @returns {Promise} */ public async getReceivableAccounts(): Promise[]> { - return await this.accountModel + return await this.accountModel() .query() .where('accountType', ACCOUNT_TYPE.ACCOUNTS_RECEIVABLE); } @@ -59,7 +62,7 @@ export class CustomerBalanceSummaryRepository { const receivableAccountsIds = map(receivableAccounts, 'id'); // Retrieve the customers transactions of A/R accounts. - const customersTranasctions = await this.accountTransactionModel + const customersTranasctions = await this.accountTransactionModel() .query() .onBuild((query) => { query.whereIn('accountId', receivableAccountsIds); diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/PurchasesByItems/PurchasesByItems.service.ts b/packages/server-nest/src/modules/FinancialStatements/modules/PurchasesByItems/PurchasesByItems.service.ts index 82959a597..41f5aacec 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/PurchasesByItems/PurchasesByItems.service.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/PurchasesByItems/PurchasesByItems.service.ts @@ -11,6 +11,7 @@ import { Item } from '@/modules/Items/models/Item'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; import { events } from '@/common/events/events'; import { getPurchasesByItemsDefaultQuery } from './utils'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PurchasesByItemsService { @@ -27,10 +28,12 @@ export class PurchasesByItemsService { private readonly tenancyContext: TenancyContext, @Inject(InventoryTransaction.name) - private readonly inventoryTransactionModel: typeof InventoryTransaction, + private readonly inventoryTransactionModel: TenantModelProxy< + typeof InventoryTransaction + >, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, ) {} /** @@ -46,17 +49,19 @@ export class PurchasesByItemsService { ...getPurchasesByItemsDefaultQuery(), ...query, }; - const inventoryItems = await this.itemModel.query().onBuild((q) => { - q.where('type', 'inventory'); + const inventoryItems = await this.itemModel() + .query() + .onBuild((q) => { + q.where('type', 'inventory'); - if (filter.itemsIds.length > 0) { - q.whereIn('id', filter.itemsIds); - } - }); + if (filter.itemsIds.length > 0) { + q.whereIn('id', filter.itemsIds); + } + }); const inventoryItemsIds = inventoryItems.map((item) => item.id); // Calculates the total inventory total quantity and rate `IN` transactions. - const inventoryTransactions = await this.inventoryTransactionModel + const inventoryTransactions = await this.inventoryTransactionModel() .query() .onBuild((builder: any) => { builder.modify('itemsTotals'); diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/SalesByItems/SalesByItemsService.ts b/packages/server-nest/src/modules/FinancialStatements/modules/SalesByItems/SalesByItemsService.ts index 7efc64f39..12cafc900 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/SalesByItems/SalesByItemsService.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/SalesByItems/SalesByItemsService.ts @@ -11,6 +11,7 @@ import { InventoryTransaction } from '@/modules/InventoryCost/models/InventoryTr import { events } from '@/common/events/events'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; import { SalesByItemsReport } from './SalesByItems'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SalesByItemsReportService { @@ -20,10 +21,12 @@ export class SalesByItemsReportService { private readonly tenancyContext: TenancyContext, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, @Inject(InventoryTransaction.name) - private readonly inventoryTransactionModel: typeof InventoryTransaction, + private readonly inventoryTransactionModel: TenantModelProxy< + typeof InventoryTransaction + >, ) {} /** @@ -41,18 +44,21 @@ export class SalesByItemsReportService { const tenantMetadata = await this.tenancyContext.getTenantMetadata(); // Inventory items for sales report. - const inventoryItems = await this.itemModel.query().onBuild((q) => { - q.where('type', 'inventory'); + const inventoryItems = await this.itemModel() + .query() + .onBuild((q) => { + q.where('type', 'inventory'); - if (filter.itemsIds.length > 0) { - q.whereIn('id', filter.itemsIds); - } - }); + if (filter.itemsIds.length > 0) { + q.whereIn('id', filter.itemsIds); + } + }); const inventoryItemsIds = inventoryItems.map((item) => item.id); // Calculates the total inventory total quantity and rate `IN` transactions. - const inventoryTransactions = await this.inventoryTransactionModel.query().onBuild( - (builder: any) => { + const inventoryTransactions = await this.inventoryTransactionModel() + .query() + .onBuild((builder: any) => { builder.modify('itemsTotals'); builder.modify('OUTDirection'); @@ -61,8 +67,7 @@ export class SalesByItemsReportService { // Filter the date range of the sheet. builder.modify('filterDateRange', filter.fromDate, filter.toDate); - }, - ); + }); const sheet = new SalesByItemsReport( filter, inventoryItems, diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByCustomer/TransactionsByCustomersRepository.ts b/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByCustomer/TransactionsByCustomersRepository.ts index 548f4dd66..dbe50adc4 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByCustomer/TransactionsByCustomersRepository.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByCustomer/TransactionsByCustomersRepository.ts @@ -14,17 +14,20 @@ import { ITransactionsByCustomersFilter } from './TransactionsByCustomer.types'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; import { TransactionsByContactRepository } from '../TransactionsByContact/TransactionsByContactRepository'; import { DateInput } from '@/common/types/Date'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable({ scope: Scope.TRANSIENT }) export class TransactionsByCustomersRepository extends TransactionsByContactRepository { @Inject(Customer.name) - private readonly customerModel: typeof Customer; + private readonly customerModel: TenantModelProxy; @Inject(Account.name) - private readonly accountModel: typeof Account; + private readonly accountModel: TenantModelProxy; @Inject(AccountTransaction.name) - private readonly accountTransactionModel: typeof AccountTransaction; + private readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >; @Inject(AccountRepository) private readonly accountRepository: AccountRepository; @@ -168,11 +171,10 @@ export class TransactionsByCustomersRepository extends TransactionsByContactRepo fromDate: DateInput, toDate: DateInput, ): Promise { - const transactions = - await this.getCustomersPeriodTransactions( - fromDate, - toDate, - ); + const transactions = await this.getCustomersPeriodTransactions( + fromDate, + toDate, + ); // @ts-ignore return R.pipe( @@ -192,13 +194,15 @@ export class TransactionsByCustomersRepository extends TransactionsByContactRepo * @returns {Promise} */ public async getCustomers(customersIds?: number[]) { - return this.customerModel.query().onBuild((q) => { - q.orderBy('displayName'); + return this.customerModel() + .query() + .onBuild((q) => { + q.orderBy('displayName'); - if (!isEmpty(customersIds)) { - q.whereIn('id', customersIds); - } - }); + if (!isEmpty(customersIds)) { + q.whereIn('id', customersIds); + } + }); } /** @@ -206,7 +210,7 @@ export class TransactionsByCustomersRepository extends TransactionsByContactRepo * @returns {Promise} */ public async getReceivableAccounts(): Promise { - const accounts = await this.accountModel + const accounts = await this.accountModel() .query() .where('accountType', ACCOUNT_TYPE.ACCOUNTS_RECEIVABLE); return accounts; @@ -225,7 +229,7 @@ export class TransactionsByCustomersRepository extends TransactionsByContactRepo const receivableAccounts = await this.getReceivableAccounts(); const receivableAccountsIds = map(receivableAccounts, 'id'); - const openingTransactions = await this.accountTransactionModel + const openingTransactions = await this.accountTransactionModel() .query() .modify( 'contactsOpeningBalance', @@ -249,7 +253,7 @@ export class TransactionsByCustomersRepository extends TransactionsByContactRepo const receivableAccounts = await this.getReceivableAccounts(); const receivableAccountsIds = map(receivableAccounts, 'id'); - const transactions = await this.accountTransactionModel + const transactions = await this.accountTransactionModel() .query() .onBuild((query) => { // Filter by date. diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByReference/TransactionsByReferenceRepository.ts b/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByReference/TransactionsByReferenceRepository.ts index 6f515ad73..aa6a3f9cf 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByReference/TransactionsByReferenceRepository.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByReference/TransactionsByReferenceRepository.ts @@ -1,4 +1,5 @@ import { AccountTransaction } from '@/modules/Accounts/models/AccountTransaction.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; import { Inject, Injectable } from '@nestjs/common'; import { ModelObject } from 'objection'; @@ -6,12 +7,13 @@ import { ModelObject } from 'objection'; export class TransactionsByReferenceRepository { constructor( @Inject(AccountTransaction.name) - private readonly accountTransactionModel: typeof AccountTransaction, + private readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, ) {} /** * Retrieve the accounts transactions of the givne reference id and type. - * @param {number} tenantId - * @param {number} referenceId - Reference id. * @param {string} referenceType - Reference type. * @return {Promise} @@ -20,7 +22,8 @@ export class TransactionsByReferenceRepository { referenceId: number, referenceType: string, ): Promise>> { - return this.accountTransactionModel.query() + return this.accountTransactionModel() + .query() .where('reference_id', referenceId) .where('reference_type', referenceType) .withGraphFetched('account'); diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByVendor/TransactionsByVendorRepository.ts b/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByVendor/TransactionsByVendorRepository.ts index 0c1aeed79..ad45136cb 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByVendor/TransactionsByVendorRepository.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/TransactionsByVendor/TransactionsByVendorRepository.ts @@ -14,6 +14,7 @@ import { Ledger } from '@/modules/Ledger/Ledger'; import { ModelObject } from 'objection'; import { ITransactionsByVendorsFilter } from './TransactionsByVendor.types'; import { DateInput } from '@/common/types/Date'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class TransactionsByVendorRepository extends TransactionsByContactRepository { @@ -24,13 +25,15 @@ export class TransactionsByVendorRepository extends TransactionsByContactReposit public readonly accountRepository: AccountRepository; @Inject(Vendor.name) - public readonly vendorModel: typeof Vendor; + public readonly vendorModel: TenantModelProxy; @Inject(Account.name) - public readonly accountModel: typeof Account; + public readonly accountModel: TenantModelProxy; @Inject(AccountTransaction.name) - public readonly accountTransactionModel: typeof AccountTransaction; + public readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >; /** * Ledger. @@ -197,13 +200,15 @@ export class TransactionsByVendorRepository extends TransactionsByContactReposit * @returns {Promise} */ public async getVendors(vendorsIds?: number[]): Promise { - return await this.vendorModel.query().onBuild((q) => { - q.orderBy('displayName'); + return await this.vendorModel() + .query() + .onBuild((q) => { + q.orderBy('displayName'); - if (!isEmpty(vendorsIds)) { - q.whereIn('id', vendorsIds); - } - }); + if (!isEmpty(vendorsIds)) { + q.whereIn('id', vendorsIds); + } + }); } /** @@ -211,7 +216,7 @@ export class TransactionsByVendorRepository extends TransactionsByContactReposit * @returns {Promise} */ public async getPayableAccounts(): Promise { - const accounts = await this.accountModel + const accounts = await this.accountModel() .query() .where('accountType', ACCOUNT_TYPE.ACCOUNTS_PAYABLE); return accounts; @@ -230,7 +235,7 @@ export class TransactionsByVendorRepository extends TransactionsByContactReposit const payableAccounts = await this.getPayableAccounts(); const payableAccountsIds = map(payableAccounts, 'id'); - const openingTransactions = await this.accountTransactionModel + const openingTransactions = await this.accountTransactionModel() .query() .modify( 'contactsOpeningBalance', @@ -254,7 +259,7 @@ export class TransactionsByVendorRepository extends TransactionsByContactReposit const receivableAccounts = await this.getPayableAccounts(); const receivableAccountsIds = map(receivableAccounts, 'id'); - const transactions = await this.accountTransactionModel + const transactions = await this.accountTransactionModel() .query() .onBuild((query) => { // Filter by date. diff --git a/packages/server-nest/src/modules/FinancialStatements/modules/TrialBalanceSheet/TrialBalanceSheetRepository.ts b/packages/server-nest/src/modules/FinancialStatements/modules/TrialBalanceSheet/TrialBalanceSheetRepository.ts index 7ff33856b..533e8c8b5 100644 --- a/packages/server-nest/src/modules/FinancialStatements/modules/TrialBalanceSheet/TrialBalanceSheetRepository.ts +++ b/packages/server-nest/src/modules/FinancialStatements/modules/TrialBalanceSheet/TrialBalanceSheetRepository.ts @@ -7,16 +7,17 @@ import { Inject, Injectable, Scope } from '@nestjs/common'; import { ITrialBalanceSheetQuery } from './TrialBalanceSheet.types'; import { Ledger } from '@/modules/Ledger/Ledger'; import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable({ scope: Scope.TRANSIENT }) export class TrialBalanceSheetRepository { private query: ITrialBalanceSheetQuery; @Inject(Account.name) - private accountModel: typeof Account; + private accountModel: TenantModelProxy; @Inject(AccountTransaction.name) - private accountTransactionModel: typeof AccountTransaction; + private accountTransactionModel: TenantModelProxy; @Inject(AccountRepository) private accountRepository: AccountRepository; @@ -77,7 +78,7 @@ export class TrialBalanceSheetRepository { * @return {Promise} */ private getAccounts = () => { - return this.accountModel.query(); + return this.accountModel().query(); }; /** @@ -85,18 +86,20 @@ export class TrialBalanceSheetRepository { * @param {Date|string} openingDate - */ public closingAccountsTotal = async (openingDate: Date | string) => { - return this.accountTransactionModel.query().onBuild((query) => { - query.sum('credit as credit'); - query.sum('debit as debit'); - query.groupBy('accountId'); - query.select(['accountId']); + return this.accountTransactionModel() + .query() + .onBuild((query) => { + query.sum('credit as credit'); + query.sum('debit as debit'); + query.groupBy('accountId'); + query.select(['accountId']); - query.modify('filterDateRange', null, openingDate); - query.withGraphFetched('account'); + query.modify('filterDateRange', null, openingDate); + query.withGraphFetched('account'); - // @ts-ignore - this.commonFilterBranchesQuery(query); - }); + // @ts-ignore + this.commonFilterBranchesQuery(query); + }); }; /** diff --git a/packages/server-nest/src/modules/InventoryAdjutments/InventoryAdjustments.module.ts b/packages/server-nest/src/modules/InventoryAdjutments/InventoryAdjustments.module.ts index 3b0605992..07208a4d0 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/InventoryAdjustments.module.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/InventoryAdjustments.module.ts @@ -31,10 +31,10 @@ const models = [ LedgerModule, DynamicListModule, InventoryCostModule, + ...models, ], controllers: [InventoryAdjustmentsController], providers: [ - ...models, CreateQuickInventoryAdjustmentService, PublishInventoryAdjustmentService, GetInventoryAdjustmentsService, diff --git a/packages/server-nest/src/modules/InventoryAdjutments/commands/CreateQuickInventoryAdjustment.service.ts b/packages/server-nest/src/modules/InventoryAdjutments/commands/CreateQuickInventoryAdjustment.service.ts index 0aa8b7bf8..d5c9bebb8 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/commands/CreateQuickInventoryAdjustment.service.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/commands/CreateQuickInventoryAdjustment.service.ts @@ -19,18 +19,21 @@ import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; import { ERRORS } from '../constants/InventoryAdjustments.constants'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateQuickInventoryAdjustmentService { constructor( @Inject(InventoryAdjustment.name) - private readonly inventoryAdjustmentModel: typeof InventoryAdjustment, + private readonly inventoryAdjustmentModel: TenantModelProxy< + typeof InventoryAdjustment + >, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, private readonly tenancyContext: TenancyContext, private readonly eventEmitter: EventEmitter2, @@ -89,13 +92,13 @@ export class CreateQuickInventoryAdjustmentService { quickAdjustmentDTO: IQuickInventoryAdjustmentDTO, ): Promise { // Retrieve the adjustment account or throw not found error. - const adjustmentAccount = await this.accountModel + const adjustmentAccount = await this.accountModel() .query() .findById(quickAdjustmentDTO.adjustmentAccountId) .throwIfNotFound(); // Retrieve the item model or throw not found service error. - const item = await this.itemModel + const item = await this.itemModel() .query() .findById(quickAdjustmentDTO.itemId) .throwIfNotFound(); @@ -119,7 +122,7 @@ export class CreateQuickInventoryAdjustmentService { } as IInventoryAdjustmentCreatingPayload, ); // Saves the inventory adjustment with associated entries to the storage. - const inventoryAdjustment = await this.inventoryAdjustmentModel + const inventoryAdjustment = await this.inventoryAdjustmentModel() .query(trx) .upsertGraphAndFetch({ ...invAdjustmentObject, diff --git a/packages/server-nest/src/modules/InventoryAdjutments/commands/DeleteInventoryAdjustment.service.ts b/packages/server-nest/src/modules/InventoryAdjutments/commands/DeleteInventoryAdjustment.service.ts index 1c39ed515..fd27d4802 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/commands/DeleteInventoryAdjustment.service.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/commands/DeleteInventoryAdjustment.service.ts @@ -9,6 +9,7 @@ import { import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { InventoryAdjustmentEntry } from '../models/InventoryAdjustmentEntry'; import { InventoryAdjustment } from '../models/InventoryAdjustment'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteInventoryAdjustmentService { @@ -17,10 +18,14 @@ export class DeleteInventoryAdjustmentService { private readonly uow: UnitOfWork, @Inject(InventoryAdjustment.name) - private readonly inventoryAdjustmentModel: typeof InventoryAdjustment, + private readonly inventoryAdjustmentModel: TenantModelProxy< + typeof InventoryAdjustment + >, @Inject(InventoryAdjustmentEntry.name) - private readonly inventoryAdjustmentEntryModel: typeof InventoryAdjustmentEntry, + private readonly inventoryAdjustmentEntryModel: TenantModelProxy< + typeof InventoryAdjustmentEntry + >, ) {} /** @@ -31,7 +36,7 @@ export class DeleteInventoryAdjustmentService { inventoryAdjustmentId: number, ): Promise { // Retrieve the inventory adjustment or throw not found service error. - const oldInventoryAdjustment = await this.inventoryAdjustmentModel + const oldInventoryAdjustment = await this.inventoryAdjustmentModel() .query() .findById(inventoryAdjustmentId) .throwIfNotFound(); @@ -46,13 +51,13 @@ export class DeleteInventoryAdjustmentService { } as IInventoryAdjustmentDeletingPayload); // Deletes the inventory adjustment entries. - await this.inventoryAdjustmentEntryModel + await this.inventoryAdjustmentEntryModel() .query(trx) .where('adjustment_id', inventoryAdjustmentId) .delete(); // Deletes the inventory adjustment transaction. - await this.inventoryAdjustmentModel + await this.inventoryAdjustmentModel() .query(trx) .findById(inventoryAdjustmentId) .delete(); diff --git a/packages/server-nest/src/modules/InventoryAdjutments/commands/PublishInventoryAdjustment.service.ts b/packages/server-nest/src/modules/InventoryAdjutments/commands/PublishInventoryAdjustment.service.ts index feff3cad5..004718d0a 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/commands/PublishInventoryAdjustment.service.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/commands/PublishInventoryAdjustment.service.ts @@ -11,6 +11,7 @@ import { import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ERRORS } from '../constants/InventoryAdjustments.constants'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PublishInventoryAdjustmentService { @@ -19,7 +20,9 @@ export class PublishInventoryAdjustmentService { private readonly uow: UnitOfWork, @Inject(InventoryAdjustment.name) - private readonly inventoryAdjustmentModel: typeof InventoryAdjustment, + private readonly inventoryAdjustmentModel: TenantModelProxy< + typeof InventoryAdjustment + >, ) {} /** @@ -30,7 +33,7 @@ export class PublishInventoryAdjustmentService { inventoryAdjustmentId: number, ): Promise { // Retrieve the inventory adjustment or throw not found service error. - const oldInventoryAdjustment = await this.inventoryAdjustmentModel + const oldInventoryAdjustment = await this.inventoryAdjustmentModel() .query() .findById(inventoryAdjustmentId) .throwIfNotFound(); @@ -50,14 +53,14 @@ export class PublishInventoryAdjustmentService { ); // Publish the inventory adjustment transaction. - await this.inventoryAdjustmentModel + await this.inventoryAdjustmentModel() .query() .findById(inventoryAdjustmentId) .patch({ publishedAt: moment().toMySqlDateTime(), }); // Retrieve the inventory adjustment after the modification. - const inventoryAdjustment = await this.inventoryAdjustmentModel + const inventoryAdjustment = await this.inventoryAdjustmentModel() .query() .findById(inventoryAdjustmentId) .withGraphFetched('entries'); diff --git a/packages/server-nest/src/modules/InventoryAdjutments/commands/ledger/InventoryAdjustmentsGLEntries.ts b/packages/server-nest/src/modules/InventoryAdjutments/commands/ledger/InventoryAdjustmentsGLEntries.ts index f68af93db..784b9b5a0 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/commands/ledger/InventoryAdjustmentsGLEntries.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/commands/ledger/InventoryAdjustmentsGLEntries.ts @@ -4,6 +4,7 @@ import { LedgerStorageService } from '../../../Ledger/LedgerStorage.service'; import { InventoryAdjustment } from '../../models/InventoryAdjustment'; import { TenancyContext } from '../../../Tenancy/TenancyContext.service'; import { InventoryAdjustmentsGL } from './InventoryAdjustmentGL'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class InventoryAdjustmentsGLEntries { @@ -12,7 +13,9 @@ export class InventoryAdjustmentsGLEntries { private readonly tenancyContext: TenancyContext, @Inject(InventoryAdjustment.name) - private readonly inventoryAdjustment: typeof InventoryAdjustment, + private readonly inventoryAdjustment: TenantModelProxy< + typeof InventoryAdjustment + >, ) {} /** @@ -25,7 +28,8 @@ export class InventoryAdjustmentsGLEntries { trx?: Knex.Transaction, ): Promise => { // Retrieves the inventory adjustment with associated entries. - const adjustment = await this.inventoryAdjustment.query(trx) + const adjustment = await this.inventoryAdjustment() + .query(trx) .findById(inventoryAdjustmentId) .withGraphFetched('entries.item'); diff --git a/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustment.service.ts b/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustment.service.ts index a20e41dcd..8621e4a55 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustment.service.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustment.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { InventoryAdjustment } from '../models/InventoryAdjustment'; import { InventoryAdjustmentTransformer } from '../InventoryAdjustmentTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetInventoryAdjustmentService { @@ -9,7 +10,9 @@ export class GetInventoryAdjustmentService { private readonly transformer: TransformerInjectable, @Inject(InventoryAdjustment.name) - private readonly inventoryAdjustmentModel: typeof InventoryAdjustment, + private readonly inventoryAdjustmentModel: TenantModelProxy< + typeof InventoryAdjustment + >, ) {} /** @@ -18,7 +21,7 @@ export class GetInventoryAdjustmentService { */ async getInventoryAdjustment(inventoryAdjustmentId: number) { // Retrieve inventory adjustment transation with associated models. - const inventoryAdjustment = await this.inventoryAdjustmentModel + const inventoryAdjustment = await this.inventoryAdjustmentModel() .query() .findById(inventoryAdjustmentId) .withGraphFetched('entries.item') diff --git a/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustments.service.ts b/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustments.service.ts index 8cabfe132..64b5a6bcb 100644 --- a/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustments.service.ts +++ b/packages/server-nest/src/modules/InventoryAdjutments/queries/GetInventoryAdjustments.service.ts @@ -6,6 +6,7 @@ import { InventoryAdjustment } from '../models/InventoryAdjustment'; import { IInventoryAdjustmentsFilter } from '../types/InventoryAdjustments.types'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetInventoryAdjustmentsService { @@ -14,7 +15,9 @@ export class GetInventoryAdjustmentsService { private readonly dynamicListService: DynamicListService, @Inject(InventoryAdjustment.name) - private readonly inventoryAdjustmentModel: typeof InventoryAdjustment, + private readonly inventoryAdjustmentModel: TenantModelProxy< + typeof InventoryAdjustment + >, ) {} /** * Retrieve the inventory adjustments paginated list. @@ -32,10 +35,10 @@ export class GetInventoryAdjustmentsService { // Dynamic list service. const dynamicFilter = await this.dynamicListService.dynamicList( - this.inventoryAdjustmentModel, + this.inventoryAdjustmentModel(), filter, ); - const { results, pagination } = await this.inventoryAdjustmentModel + const { results, pagination } = await this.inventoryAdjustmentModel() .query() .onBuild((query) => { query.withGraphFetched('entries.item'); diff --git a/packages/server-nest/src/modules/InventoryCost/InventoryCost.module.ts b/packages/server-nest/src/modules/InventoryCost/InventoryCost.module.ts index 07700195e..6f91ab040 100644 --- a/packages/server-nest/src/modules/InventoryCost/InventoryCost.module.ts +++ b/packages/server-nest/src/modules/InventoryCost/InventoryCost.module.ts @@ -15,9 +15,8 @@ const models = [ ]; @Module({ - imports: [LedgerModule], + imports: [LedgerModule, ...models], providers: [ - ...models, InventoryCostGLBeforeWriteSubscriber, InventoryCostGLStorage, InventoryItemsQuantitySyncService, diff --git a/packages/server-nest/src/modules/InventoryCost/InventoryCostMethod.ts b/packages/server-nest/src/modules/InventoryCost/InventoryCostMethod.ts index f7b2c1b6a..fc11d383f 100644 --- a/packages/server-nest/src/modules/InventoryCost/InventoryCostMethod.ts +++ b/packages/server-nest/src/modules/InventoryCost/InventoryCostMethod.ts @@ -2,11 +2,14 @@ import { Knex } from 'knex'; import { Inject } from '@nestjs/common'; import { omit } from 'lodash'; import { InventoryCostLotTracker } from './models/InventoryCostLotTracker'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; export class InventoryCostMethod { constructor( @Inject(InventoryCostLotTracker.name) - private readonly inventoryCostLotTracker: typeof InventoryCostLotTracker, + private readonly inventoryCostLotTracker: TenantModelProxy< + typeof InventoryCostLotTracker + >, ) {} /** @@ -23,16 +26,18 @@ export class InventoryCostMethod { costLotsTransactions.forEach((transaction: any) => { if (transaction.lotTransId && transaction.decrement) { - const decrementOper = this.inventoryCostLotTracker + const decrementOper = this.inventoryCostLotTracker() .query(trx) .where('id', transaction.lotTransId) .decrement('remaining', transaction.decrement); opers.push(decrementOper); } else if (!transaction.lotTransId) { - const operation = this.inventoryCostLotTracker.query(trx).insert({ - ...omit(transaction, ['decrement', 'invTransId', 'lotTransId']), - }); + const operation = this.inventoryCostLotTracker() + .query(trx) + .insert({ + ...omit(transaction, ['decrement', 'invTransId', 'lotTransId']), + }); opers.push(operation); } }); diff --git a/packages/server-nest/src/modules/InventoryCost/InventoryItemsQuantitySync.service.ts b/packages/server-nest/src/modules/InventoryCost/InventoryItemsQuantitySync.service.ts index a16ccc2c3..6a87da8d3 100644 --- a/packages/server-nest/src/modules/InventoryCost/InventoryItemsQuantitySync.service.ts +++ b/packages/server-nest/src/modules/InventoryCost/InventoryItemsQuantitySync.service.ts @@ -5,6 +5,7 @@ import { Inject } from '@nestjs/common'; import { Item } from '../Items/models/Item'; import { Injectable } from '@nestjs/common'; import { InventoryTransaction } from './models/InventoryTransaction'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; /** * Syncs the inventory transactions with inventory items quantity. @@ -12,7 +13,8 @@ import { InventoryTransaction } from './models/InventoryTransaction'; @Injectable() export class InventoryItemsQuantitySyncService { constructor( - @Inject(Item.name) private readonly itemModel: typeof Item, + @Inject(Item.name) + private readonly itemModel: TenantModelProxy, ) {} /** @@ -84,7 +86,7 @@ export class InventoryItemsQuantitySyncService { const opers = []; itemsQuantity.forEach((itemQuantity: IItemsQuantityChanges) => { - const changeQuantityOper = this.itemModel + const changeQuantityOper = this.itemModel() .query(trx) .where({ id: itemQuantity.itemId, type: 'inventory' }) .modify('quantityOnHand', itemQuantity.balanceChange); diff --git a/packages/server-nest/src/modules/ItemCategories/ItemCategory.interfaces.ts b/packages/server-nest/src/modules/ItemCategories/ItemCategory.interfaces.ts index 60ab175e2..b5dca63be 100644 --- a/packages/server-nest/src/modules/ItemCategories/ItemCategory.interfaces.ts +++ b/packages/server-nest/src/modules/ItemCategories/ItemCategory.interfaces.ts @@ -44,5 +44,5 @@ export interface IItemCategoriesFilter extends IDynamicListFilter { export interface GetItemCategoriesResponse { itemCategories: ItemCategory[]; - filterMeta: IFilterMeta; + // filterMeta: IFilterMeta; } diff --git a/packages/server-nest/src/modules/ItemCategories/ItemCategory.module.ts b/packages/server-nest/src/modules/ItemCategories/ItemCategory.module.ts index d76b0684b..f78e46145 100644 --- a/packages/server-nest/src/modules/ItemCategories/ItemCategory.module.ts +++ b/packages/server-nest/src/modules/ItemCategories/ItemCategory.module.ts @@ -24,7 +24,7 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module'; ItemCategoryApplication, CommandItemCategoryValidatorService, TransformerInjectable, - TenancyContext + TenancyContext, ], }) export class ItemCategoryModule {} diff --git a/packages/server-nest/src/modules/ItemCategories/commands/CommandItemCategoryValidator.service.ts b/packages/server-nest/src/modules/ItemCategories/commands/CommandItemCategoryValidator.service.ts index 9d1e853a6..12d7a29c6 100644 --- a/packages/server-nest/src/modules/ItemCategories/commands/CommandItemCategoryValidator.service.ts +++ b/packages/server-nest/src/modules/ItemCategories/commands/CommandItemCategoryValidator.service.ts @@ -4,19 +4,20 @@ import { Inject, Injectable } from '@nestjs/common'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ERRORS } from '../constants'; import { ACCOUNT_ROOT_TYPE, ACCOUNT_TYPE } from '@/constants/accounts'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CommandItemCategoryValidatorService { /** - * @param {typeof ItemCategory} itemCategoryModel - Item category model. - * @param {typeof Account} accountModel - Account model. + * @param {TenantModelProxy} itemCategoryModel - Item category model. + * @param {TenantModelProxy} accountModel - Account model. */ constructor( @Inject(ItemCategory.name) - private readonly itemCategoryModel: typeof ItemCategory, + private readonly itemCategoryModel: TenantModelProxy, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) {} /** @@ -28,7 +29,7 @@ export class CommandItemCategoryValidatorService { categoryName: string, notCategoryId?: number, ) { - const foundItemCategory = await this.itemCategoryModel + const foundItemCategory = await this.itemCategoryModel() .query() .findOne('name', categoryName) .onBuild((query) => { @@ -51,7 +52,7 @@ export class CommandItemCategoryValidatorService { * @return {Promise} */ public async validateSellAccount(sellAccountId: number) { - const foundAccount = await this.accountModel + const foundAccount = await this.accountModel() .query() .findById(sellAccountId); @@ -68,7 +69,7 @@ export class CommandItemCategoryValidatorService { * @return {Promise} */ public async validateCostAccount(costAccountId: number) { - const foundAccount = await this.accountModel + const foundAccount = await this.accountModel() .query() .findById(costAccountId); @@ -85,7 +86,7 @@ export class CommandItemCategoryValidatorService { * @return {Promise} */ public async validateInventoryAccount(inventoryAccountId: number) { - const foundAccount = await this.accountModel + const foundAccount = await this.accountModel() .query() .findById(inventoryAccountId); diff --git a/packages/server-nest/src/modules/ItemCategories/commands/CreateItemCategory.service.ts b/packages/server-nest/src/modules/ItemCategories/commands/CreateItemCategory.service.ts index 125f828b2..8f72c3d97 100644 --- a/packages/server-nest/src/modules/ItemCategories/commands/CreateItemCategory.service.ts +++ b/packages/server-nest/src/modules/ItemCategories/commands/CreateItemCategory.service.ts @@ -10,6 +10,7 @@ import { CommandItemCategoryValidatorService } from './CommandItemCategoryValida import { ItemCategory } from '../models/ItemCategory.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { SystemUser } from '@/modules/System/models/SystemUser'; +import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateItemCategoryService { @@ -25,7 +26,7 @@ export class CreateItemCategoryService { private readonly eventEmitter: EventEmitter2, @Inject(ItemCategory.name) - private readonly itemCategoryModel: typeof ItemCategory, + private readonly itemCategoryModel: () => typeof ItemCategory, ) {} /** @@ -72,9 +73,11 @@ export class CreateItemCategoryService { // Creates item category under unit-of-work evnirement. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Inserts the item category. - const itemCategory = await this.itemCategoryModel.query(trx).insert({ - ...itemCategoryObj, - }); + const itemCategory = await this.itemCategoryModel() + .query(trx) + .insert({ + ...itemCategoryObj, + }); // Triggers `onItemCategoryCreated` event. await this.eventEmitter.emitAsync(events.itemCategory.onCreated, { itemCategory, diff --git a/packages/server-nest/src/modules/ItemCategories/commands/DeleteItemCategory.service.ts b/packages/server-nest/src/modules/ItemCategories/commands/DeleteItemCategory.service.ts index 7cbf59dcf..5db7b4fd5 100644 --- a/packages/server-nest/src/modules/ItemCategories/commands/DeleteItemCategory.service.ts +++ b/packages/server-nest/src/modules/ItemCategories/commands/DeleteItemCategory.service.ts @@ -7,6 +7,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; import { IItemCategoryDeletedPayload } from '../ItemCategory.interfaces'; import { Item } from '@/modules/Items/models/Item'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteItemCategoryService { @@ -20,11 +21,12 @@ export class DeleteItemCategoryService { private readonly uow: UnitOfWork, private readonly validator: CommandItemCategoryValidatorService, private readonly eventEmitter: EventEmitter2, + @Inject(ItemCategory.name) - private readonly itemCategoryModel: typeof ItemCategory, + private readonly itemCategoryModel: TenantModelProxy, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, ) {} /** @@ -35,7 +37,7 @@ export class DeleteItemCategoryService { */ public async deleteItemCategory(itemCategoryId: number) { // Retrieve item category or throw not found error. - const oldItemCategory = await this.itemCategoryModel + const oldItemCategory = await this.itemCategoryModel() .query() .findById(itemCategoryId) .throwIfNotFound(); @@ -68,7 +70,8 @@ export class DeleteItemCategoryService { ? itemCategoryId : [itemCategoryId]; - await this.itemModel.query(trx) + await this.itemModel() + .query(trx) .whereIn('category_id', ids) .patch({ categoryId: null }); } diff --git a/packages/server-nest/src/modules/ItemCategories/commands/EditItemCategory.service.ts b/packages/server-nest/src/modules/ItemCategories/commands/EditItemCategory.service.ts index ad2e276f9..76e765d6f 100644 --- a/packages/server-nest/src/modules/ItemCategories/commands/EditItemCategory.service.ts +++ b/packages/server-nest/src/modules/ItemCategories/commands/EditItemCategory.service.ts @@ -11,6 +11,7 @@ import { Knex } from 'knex'; import { ItemCategory } from '../models/ItemCategory.model'; import { Inject } from '@nestjs/common'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; export class EditItemCategoryService { /** @@ -25,8 +26,9 @@ export class EditItemCategoryService { private readonly validator: CommandItemCategoryValidatorService, private readonly eventEmitter: EventEmitter2, private readonly tenancyContext: TenancyContext, + @Inject(ItemCategory.name) - private readonly itemCategoryModel: typeof ItemCategory, + private readonly itemCategoryModel: TenantModelProxy, ) {} /** @@ -41,7 +43,7 @@ export class EditItemCategoryService { itemCategoryOTD: IItemCategoryOTD, ): Promise { // Retrieve the item category from the storage. - const oldItemCategory = await this.itemCategoryModel + const oldItemCategory = await this.itemCategoryModel() .query() .findById(itemCategoryId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategories.service.ts b/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategories.service.ts index c6e112ceb..daff24be3 100644 --- a/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategories.service.ts +++ b/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategories.service.ts @@ -6,13 +6,14 @@ import { GetItemCategoriesResponse, IItemCategoriesFilter, } from '../ItemCategory.interfaces'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; export class GetItemCategoriesService { constructor( private readonly dynamicListService: DynamicListService, @Inject(ItemCategory.name) - private readonly itemCategoryModel: typeof ItemCategory, + private readonly itemCategoryModel: TenantModelProxy, ) {} /** @@ -39,22 +40,23 @@ export class GetItemCategoriesService { const filter = this.parsesListFilterDTO(filterDTO); // Dynamic list service. - const dynamicList = await this.dynamicListService.dynamicList( - this.itemCategoryModel, - filter, - ); + // const dynamicList = await this.dynamicListService.dynamicList( + // this.itemCategoryModel(), + // filter, + // ); // Items categories. - const itemCategories = await this.itemCategoryModel + const itemCategories = await this.itemCategoryModel() .query() .onBuild((query) => { // Subquery to calculate sumation of associated items to the item category. query.select( '*', - this.itemCategoryModel.relatedQuery('items').count().as('count'), + this.itemCategoryModel().relatedQuery('items').count().as('count'), ); - dynamicList.buildQuery()(query); + // dynamicList.buildQuery()(query); }); - return { itemCategories, filterMeta: dynamicList.getResponseMeta() }; + + return { itemCategories }; } } diff --git a/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategory.service.ts b/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategory.service.ts index 0304bf0f4..a85d5609d 100644 --- a/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategory.service.ts +++ b/packages/server-nest/src/modules/ItemCategories/queries/GetItemCategory.service.ts @@ -1,5 +1,6 @@ import { Inject, Injectable } from '@nestjs/common'; import { ItemCategory } from '../models/ItemCategory.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetItemCategoryService { @@ -8,7 +9,7 @@ export class GetItemCategoryService { */ constructor( @Inject(ItemCategory.name) - private readonly itemCategoryModel: typeof ItemCategory, + private readonly itemCategoryModel: TenantModelProxy, ) {} /** @@ -17,7 +18,7 @@ export class GetItemCategoryService { * @returns {Promise} */ public async getItemCategory(itemCategoryId: number) { - const itemCategory = await this.itemCategoryModel + const itemCategory = await this.itemCategoryModel() .query() .findById(itemCategoryId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/Items/ActivateItem.service.ts b/packages/server-nest/src/modules/Items/ActivateItem.service.ts index 8de6e529a..c51764c35 100644 --- a/packages/server-nest/src/modules/Items/ActivateItem.service.ts +++ b/packages/server-nest/src/modules/Items/ActivateItem.service.ts @@ -4,12 +4,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { Item } from './models/Item'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ActivateItemService { constructor( @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, private readonly eventEmitter: EventEmitter2, private readonly uow: UnitOfWork, ) {} @@ -24,7 +25,7 @@ export class ActivateItemService { trx?: Knex.Transaction, ): Promise { // Retrieves the given item or throw not found error. - const oldItem = await this.itemModel + const oldItem = await this.itemModel() .query() .findById(itemId) .throwIfNotFound(); @@ -32,7 +33,10 @@ export class ActivateItemService { // Activate the given item with associated transactions under unit-of-work environment. return this.uow.withTransaction(async (trx) => { // Mutate item on the storage. - await this.itemModel.query(trx).findById(itemId).patch({ active: true }); + await this.itemModel() + .query(trx) + .findById(itemId) + .patch({ active: true }); // Triggers `onItemActivated` event. await this.eventEmitter.emitAsync(events.item.onActivated, {}); diff --git a/packages/server-nest/src/modules/Items/CreateItem.service.ts b/packages/server-nest/src/modules/Items/CreateItem.service.ts index 3a22613b3..82dcbee3f 100644 --- a/packages/server-nest/src/modules/Items/CreateItem.service.ts +++ b/packages/server-nest/src/modules/Items/CreateItem.service.ts @@ -7,6 +7,7 @@ import { events } from '@/common/events/events'; import { ItemsValidators } from './ItemValidator.service'; import { Item } from './models/Item'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable({ scope: Scope.REQUEST }) export class CreateItemService { @@ -23,7 +24,7 @@ export class CreateItemService { private readonly validators: ItemsValidators, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, ) {} /** @@ -103,9 +104,11 @@ export class CreateItemService { const itemInsert = this.transformNewItemDTOToModel(itemDTO); // Inserts a new item and fetch the created item. - const item = await this.itemModel.query(trx).insertAndFetch({ - ...itemInsert, - }); + const item = await this.itemModel() + .query(trx) + .insertAndFetch({ + ...itemInsert, + }); // Triggers `onItemCreated` event. await this.eventEmitter.emitAsync(events.item.onCreated, { item, diff --git a/packages/server-nest/src/modules/Items/DeleteItem.service.ts b/packages/server-nest/src/modules/Items/DeleteItem.service.ts index 8f3ac32a1..fbb5d66e1 100644 --- a/packages/server-nest/src/modules/Items/DeleteItem.service.ts +++ b/packages/server-nest/src/modules/Items/DeleteItem.service.ts @@ -9,6 +9,7 @@ import { events } from '@/common/events/events'; import { Item } from './models/Item'; import { ERRORS } from './Items.constants'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class DeleteItemService { @@ -23,7 +24,7 @@ export class DeleteItemService { private readonly uow: UnitOfWork, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, ) {} /** @@ -36,13 +37,13 @@ export class DeleteItemService { trx?: Knex.Transaction, ): Promise { // Retrieve the given item or throw not found service error. - const oldItem = await this.itemModel + const oldItem = await this.itemModel() .query() .findById(itemId) .throwIfNotFound(); - // .queryAndThrowIfHasRelations({ - // type: ERRORS.ITEM_HAS_ASSOCIATED_TRANSACTIONS, - // }); + // .queryAndThrowIfHasRelations({ + // type: ERRORS.ITEM_HAS_ASSOCIATED_TRANSACTIONS, + // }); // Delete item in unit of work. return this.uow.withTransaction(async (trx: Knex.Transaction) => { @@ -53,7 +54,7 @@ export class DeleteItemService { } as IItemEventDeletingPayload); // Deletes the item. - await this.itemModel.query(trx).findById(itemId).delete(); + await this.itemModel().query(trx).findById(itemId).delete(); // Triggers `onItemDeleted` event. await this.eventEmitter.emitAsync(events.item.onDeleted, { diff --git a/packages/server-nest/src/modules/Items/EditItem.service.ts b/packages/server-nest/src/modules/Items/EditItem.service.ts index 661998bf0..43abb4fd7 100644 --- a/packages/server-nest/src/modules/Items/EditItem.service.ts +++ b/packages/server-nest/src/modules/Items/EditItem.service.ts @@ -6,6 +6,7 @@ import { events } from '@/common/events/events'; import { ItemsValidators } from './ItemValidator.service'; import { Item } from './models/Item'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class EditItemService { @@ -22,7 +23,7 @@ export class EditItemService { private readonly validators: ItemsValidators, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, ) {} /** @@ -110,7 +111,7 @@ export class EditItemService { trx?: Knex.Transaction, ): Promise { // Validates the given item existance on the storage. - const oldItem = await this.itemModel + const oldItem = await this.itemModel() .query() .findById(itemId) .throwIfNotFound(); @@ -124,7 +125,7 @@ export class EditItemService { // Edits the item with associated transactions under unit-of-work environment. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Updates the item on the storage and fetches the updated one. - const newItem = await this.itemModel + const newItem = await this.itemModel() .query(trx) .patchAndFetchById(itemId, itemModel); diff --git a/packages/server-nest/src/modules/Items/GetItem.service.ts b/packages/server-nest/src/modules/Items/GetItem.service.ts index 4ebb69ccb..b815aa2c2 100644 --- a/packages/server-nest/src/modules/Items/GetItem.service.ts +++ b/packages/server-nest/src/modules/Items/GetItem.service.ts @@ -4,12 +4,12 @@ import { Item } from './models/Item'; import { events } from '@/common/events/events'; import { TransformerInjectable } from '../Transformer/TransformerInjectable.service'; import { ItemTransformer } from './Item.transformer'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class GetItemService { constructor( - @Inject(Item.name) - private itemModel: typeof Item, + @Inject(Item.name) private itemModel: TenantModelProxy, private eventEmitter2: EventEmitter2, private transformerInjectable: TransformerInjectable, ) {} @@ -20,7 +20,7 @@ export class GetItemService { * @param {number} itemId - The item id. */ public async getItem(itemId: number): Promise { - const item = await this.itemModel + const item = await this.itemModel() .query() .findById(itemId) .withGraphFetched('sellAccount') diff --git a/packages/server-nest/src/modules/Items/GetItems.service.ts b/packages/server-nest/src/modules/Items/GetItems.service.ts index 1366b4322..7d0d31b2e 100644 --- a/packages/server-nest/src/modules/Items/GetItems.service.ts +++ b/packages/server-nest/src/modules/Items/GetItems.service.ts @@ -5,15 +5,15 @@ import { DynamicListService } from '../DynamicListing/DynamicList.service'; import { Item } from './models/Item'; import { IItemsFilter } from './types/Items.types'; import { ItemTransformer } from './Item.transformer'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class GetItemsService { constructor( private readonly dynamicListService: DynamicListService, private readonly transformer: TransformerInjectable, - @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, ) {} /** @@ -39,7 +39,7 @@ export class GetItemsService { Item, filter, ); - const { results: items, pagination } = await this.itemModel + const { results: items, pagination } = await this.itemModel() .query() .onBuild((builder) => { builder.modify('inactiveMode', filter.inactiveMode); diff --git a/packages/server-nest/src/modules/Items/InactivateItem.service.ts b/packages/server-nest/src/modules/Items/InactivateItem.service.ts index 8bf9bd4a0..ae2612363 100644 --- a/packages/server-nest/src/modules/Items/InactivateItem.service.ts +++ b/packages/server-nest/src/modules/Items/InactivateItem.service.ts @@ -4,11 +4,12 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { Item } from './models/Item'; import { events } from '@/common/events/events'; import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class InactivateItem { constructor( - @Inject(Item.name) private itemModel: typeof Item, + @Inject(Item.name) private itemModel: TenantModelProxy, private readonly eventEmitter: EventEmitter2, private readonly uow: UnitOfWork, ) {} @@ -23,7 +24,7 @@ export class InactivateItem { trx?: Knex.Transaction, ): Promise { // Retrieves the item or throw not found error. - const oldItem = await this.itemModel + const oldItem = await this.itemModel() .query() .findById(itemId) .throwIfNotFound(); @@ -31,7 +32,10 @@ export class InactivateItem { // Inactivate item under unit-of-work environment. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Inactivate item on the storage. - await this.itemModel.query(trx).findById(itemId).patch({ active: false }); + await this.itemModel() + .query(trx) + .findById(itemId) + .patch({ active: false }); // Triggers `onItemInactivated` event. await this.eventEmitter.emitAsync(events.item.onInactivated, { trx }); diff --git a/packages/server-nest/src/modules/Items/ItemTransactions.service.ts b/packages/server-nest/src/modules/Items/ItemTransactions.service.ts index 8c7198cc2..7137a7223 100644 --- a/packages/server-nest/src/modules/Items/ItemTransactions.service.ts +++ b/packages/server-nest/src/modules/Items/ItemTransactions.service.ts @@ -5,6 +5,7 @@ import { ItemBillTransactionTransformer } from './ItemBillsTransactions.transfor import { ItemReceiptTransactionTransformer } from './ItemReceiptsTransactions.transformer'; import { TransformerInjectable } from '../Transformer/TransformerInjectable.service'; import { ItemEntry } from '../TransactionItemEntry/models/ItemEntry'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ItemTransactionsService { @@ -12,7 +13,7 @@ export class ItemTransactionsService { private transformer: TransformerInjectable, @Inject(ItemEntry.name) - private readonly itemEntry: typeof ItemEntry, + private readonly itemEntry: TenantModelProxy, ) {} /** @@ -20,7 +21,8 @@ export class ItemTransactionsService { * @param {number} itemId - */ public async getItemInvoicesTransactions(itemId: number) { - const invoiceEntries = await this.itemEntry.query() + const invoiceEntries = await this.itemEntry() + .query() .where('itemId', itemId) .where('referenceType', 'SaleInvoice') .withGraphJoined('invoice.customer(selectCustomerColumns)') @@ -43,7 +45,8 @@ export class ItemTransactionsService { * @returns */ public async getItemBillTransactions(itemId: number) { - const billEntries = await this.itemEntry.query() + const billEntries = await this.itemEntry() + .query() .where('itemId', itemId) .where('referenceType', 'Bill') .withGraphJoined('bill.vendor(selectVendorColumns)') @@ -66,7 +69,8 @@ export class ItemTransactionsService { * @returns */ public async getItemEstimateTransactions(itemId: number) { - const estimatesEntries = await this.itemEntry.query() + const estimatesEntries = await this.itemEntry() + .query() .where('itemId', itemId) .where('referenceType', 'SaleEstimate') .withGraphJoined('estimate.customer(selectCustomerColumns)') @@ -89,7 +93,8 @@ export class ItemTransactionsService { * @returns */ public async getItemReceiptTransactions(itemId: number) { - const receiptsEntries = await this.itemEntry.query() + const receiptsEntries = await this.itemEntry() + .query() .where('itemId', itemId) .where('referenceType', 'SaleReceipt') .withGraphJoined('receipt.customer(selectCustomerColumns)') diff --git a/packages/server-nest/src/modules/Items/ItemValidator.service.ts b/packages/server-nest/src/modules/Items/ItemValidator.service.ts index 455f2bbb3..19668926a 100644 --- a/packages/server-nest/src/modules/Items/ItemValidator.service.ts +++ b/packages/server-nest/src/modules/Items/ItemValidator.service.ts @@ -14,17 +14,34 @@ import { ItemEntry } from '../TransactionItemEntry/models/ItemEntry'; import { ItemCategory } from '../ItemCategories/models/ItemCategory.model'; import { AccountTransaction } from '../Accounts/models/AccountTransaction.model'; import { InventoryAdjustment } from '../InventoryAdjutments/models/InventoryAdjustment'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ItemsValidators { constructor( - @Inject(Item.name) private itemModel: typeof Item, - @Inject(Account.name) private accountModel: typeof Account, - @Inject(TaxRateModel.name) private taxRateModel: typeof TaxRateModel, - @Inject(ItemEntry.name) private itemEntryModel: typeof ItemEntry, - @Inject(ItemCategory.name) private itemCategoryModel: typeof ItemCategory, - @Inject(AccountTransaction.name) private accountTransactionModel: typeof AccountTransaction, - @Inject(InventoryAdjustment.name) private inventoryAdjustmentEntryModel: typeof InventoryAdjustment, + @Inject(Item.name) private itemModel: TenantModelProxy, + + @Inject(Account.name) + private accountModel: TenantModelProxy, + + @Inject(TaxRateModel.name) + private taxRateModel: TenantModelProxy, + + @Inject(ItemEntry.name) + private itemEntryModel: TenantModelProxy, + + @Inject(ItemCategory.name) + private itemCategoryModel: TenantModelProxy, + + @Inject(AccountTransaction.name) + private accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, + + @Inject(InventoryAdjustment.name) + private inventoryAdjustmentEntryModel: TenantModelProxy< + typeof InventoryAdjustment + >, ) {} /** @@ -37,12 +54,14 @@ export class ItemsValidators { itemName: string, notItemId?: number, ): Promise { - const foundItems = await this.itemModel.query().onBuild((builder: any) => { - builder.where('name', itemName); - if (notItemId) { - builder.whereNot('id', notItemId); - } - }); + const foundItems = await this.itemModel() + .query() + .onBuild((builder: any) => { + builder.where('name', itemName); + if (notItemId) { + builder.whereNot('id', notItemId); + } + }); if (foundItems.length > 0) { throw new ServiceError( @@ -60,7 +79,7 @@ export class ItemsValidators { public async validateItemCostAccountExistance( costAccountId: number, ): Promise { - const foundAccount = await this.accountModel + const foundAccount = await this.accountModel() .query() .findById(costAccountId); @@ -78,7 +97,7 @@ export class ItemsValidators { * @param {number} sellAccountId - Sell account id. */ public async validateItemSellAccountExistance(sellAccountId: number) { - const foundAccount = await this.accountModel + const foundAccount = await this.accountModel() .query() .findById(sellAccountId); @@ -132,7 +151,7 @@ export class ItemsValidators { public async validateItemInventoryAccountExistance( inventoryAccountId: number, ) { - const foundAccount = await this.accountModel + const foundAccount = await this.accountModel() .query() .findById(inventoryAccountId); @@ -148,7 +167,7 @@ export class ItemsValidators { * @param {number} itemCategoryId */ public async validateItemCategoryExistance(itemCategoryId: number) { - const foundCategory = await this.itemCategoryModel + const foundCategory = await this.itemCategoryModel() .query() .findById(itemCategoryId); @@ -164,7 +183,7 @@ export class ItemsValidators { */ public async validateHasNoInvoicesOrBills(itemId: number[] | number) { const ids = Array.isArray(itemId) ? itemId : [itemId]; - const foundItemEntries = await this.itemEntryModel + const foundItemEntries = await this.itemEntryModel() .query() .whereIn('item_id', ids); @@ -185,7 +204,7 @@ export class ItemsValidators { itemId: number[] | number, ): Promise { const itemsIds = Array.isArray(itemId) ? itemId : [itemId]; - const inventoryAdjEntries = await this.inventoryAdjustmentEntryModel + const inventoryAdjEntries = await this.inventoryAdjustmentEntryModel() .query() .whereIn('item_id', itemsIds); @@ -208,7 +227,7 @@ export class ItemsValidators { return; } // Retrieve all transactions that associated to the given item id. - const itemTransactionsCount = await this.accountTransactionModel + const itemTransactionsCount = await this.accountTransactionModel() .query() .where('item_id', oldItem.id) .count('item_id', { as: 'transactions' }) @@ -240,7 +259,7 @@ export class ItemsValidators { return; } // Inventory transactions associated to the given item id. - const transactions = await this.accountTransactionModel.query().where({ + const transactions = await this.accountTransactionModel().query().where({ itemId: oldItem.id, }); // Throw the service error in case item has associated inventory transactions. @@ -269,7 +288,7 @@ export class ItemsValidators { * @param {number} taxRateId - */ public async validatePurchaseTaxRateExistance(taxRateId: number) { - const foundTaxRate = await this.taxRateModel.query().findById(taxRateId); + const foundTaxRate = await this.taxRateModel().query().findById(taxRateId); if (!foundTaxRate) { throw new ServiceError(ERRORS.PURCHASE_TAX_RATE_NOT_FOUND); @@ -281,7 +300,7 @@ export class ItemsValidators { * @param {number} taxRateId */ public async validateSellTaxRateExistance(taxRateId: number) { - const foundTaxRate = await this.taxRateModel.query().findById(taxRateId); + const foundTaxRate = await this.taxRateModel().query().findById(taxRateId); if (!foundTaxRate) { throw new ServiceError(ERRORS.SELL_TAX_RATE_NOT_FOUND); diff --git a/packages/server-nest/src/modules/Items/ItemsEntries.service.ts b/packages/server-nest/src/modules/Items/ItemsEntries.service.ts index b35c2572c..2997df8f7 100644 --- a/packages/server-nest/src/modules/Items/ItemsEntries.service.ts +++ b/packages/server-nest/src/modules/Items/ItemsEntries.service.ts @@ -5,6 +5,7 @@ import { Item } from './models/Item'; import { ItemEntry } from '../TransactionItemEntry/models/ItemEntry'; import { ServiceError } from './ServiceError'; import { IItemEntryDTO } from '../TransactionItemEntry/ItemEntry.types'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; const ERRORS = { ITEMS_NOT_FOUND: 'ITEMS_NOT_FOUND', @@ -16,12 +17,15 @@ const ERRORS = { @Injectable() export class ItemsEntriesService { /** - * @param {typeof Item} itemModel - Item model. - * @param {typeof ItemEntry} itemEntryModel - Item entry model. + * @param {TenantModelProxy} itemModel - Item model. + * @param {TenantModelProxy} itemEntryModel - Item entry model. */ constructor( - @Inject(Item.name) private readonly itemModel: typeof Item, - @Inject(ItemEntry.name) private readonly itemEntryModel: typeof ItemEntry, + @Inject(Item.name) + private readonly itemModel: TenantModelProxy, + + @Inject(ItemEntry.name) + private readonly itemEntryModel: TenantModelProxy, ) {} /** @@ -34,12 +38,12 @@ export class ItemsEntriesService { referenceType: string, referenceId: number, ): Promise { - const itemsEntries = await this.itemEntryModel + const itemsEntries = await this.itemEntryModel() .query() .where('reference_type', referenceType) .where('reference_id', referenceId); - const inventoryItems = await this.itemModel + const inventoryItems = await this.itemModel() .query() .whereIn('id', map(itemsEntries, 'itemId')) .where('type', 'inventory'); @@ -63,7 +67,7 @@ export class ItemsEntriesService { ): Promise { const entriesItemsIds = entries.map((e) => e.itemId); - const inventoryItems = await this.itemModel + const inventoryItems = await this.itemModel() .query(trx) .whereIn('id', entriesItemsIds) .where('type', 'inventory'); @@ -81,7 +85,7 @@ export class ItemsEntriesService { public async validateItemsIdsExistance(itemEntries: IItemEntryDTO[]) { const itemsIds = itemEntries.map((e) => e.itemId); - const foundItems = await this.itemModel.query().whereIn('id', itemsIds); + const foundItems = await this.itemModel().query().whereIn('id', itemsIds); const foundItemsIds = foundItems.map((item: Item) => item.id); const notFoundItemsIds = difference(itemsIds, foundItemsIds); @@ -107,7 +111,7 @@ export class ItemsEntriesService { .filter((e: ItemEntry) => e.id) .map((e: ItemEntry) => e.id); - const storedEntries = await this.itemEntryModel + const storedEntries = await this.itemEntryModel() .query() .whereIn('reference_id', [referenceId]) .whereIn('reference_type', [referenceType]); @@ -128,7 +132,7 @@ export class ItemsEntriesService { itemEntries: IItemEntryDTO[], ) { const itemsIds = itemEntries.map((e: IItemEntryDTO) => e.itemId); - const purchasbleItems = await this.itemModel + const purchasbleItems = await this.itemModel() .query() .where('purchasable', true) .whereIn('id', itemsIds); @@ -148,7 +152,7 @@ export class ItemsEntriesService { public async validateNonSellableEntriesItems(itemEntries: IItemEntryDTO[]) { const itemsIds = itemEntries.map((e: IItemEntryDTO) => e.itemId); - const sellableItems = await this.itemModel + const sellableItems = await this.itemModel() .query() .where('sellable', true) .whereIn('id', itemsIds); @@ -215,7 +219,7 @@ export class ItemsEntriesService { */ public setItemsEntriesDefaultAccounts = async (entries: IItemEntryDTO[]) => { const entriesItemsIds = entries.map((e) => e.itemId); - const items = await this.itemModel.query().whereIn('id', entriesItemsIds); + const items = await this.itemModel().query().whereIn('id', entriesItemsIds); return entries.map((entry) => { const item = items.find((i) => i.id === entry.itemId); @@ -228,7 +232,7 @@ export class ItemsEntriesService { }), }; }); - } + }; /** * Retrieve the total items entries. diff --git a/packages/server-nest/src/modules/Ledger/LedgerContactStorage.service.ts b/packages/server-nest/src/modules/Ledger/LedgerContactStorage.service.ts index 89429ccd2..0e44b19d7 100644 --- a/packages/server-nest/src/modules/Ledger/LedgerContactStorage.service.ts +++ b/packages/server-nest/src/modules/Ledger/LedgerContactStorage.service.ts @@ -10,6 +10,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { Contact } from '../Contacts/models/Contact'; import { Account } from '../Accounts/models/Account.model'; import { TenancyContext } from '../Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class LedgerContactsBalanceStorage { @@ -17,10 +18,10 @@ export class LedgerContactsBalanceStorage { private tenancyContext: TenancyContext, @Inject(Contact.name) - private contactModel: typeof Contact, + private contactModel: TenantModelProxy, @Inject(Account.name) - private accountModel: typeof Account, + private accountModel: TenantModelProxy, ) {} /** @@ -69,7 +70,7 @@ export class LedgerContactsBalanceStorage { private filterARAPLedgerEntris = async ( trx?: Knex.Transaction, ): Promise<(entry: ILedgerEntry) => boolean> => { - const ARAPAccounts = await this.accountModel + const ARAPAccounts = await this.accountModel() .query(trx) .whereIn('accountType', [ ACCOUNT_TYPE.ACCOUNTS_RECEIVABLE, @@ -94,7 +95,7 @@ export class LedgerContactsBalanceStorage { contactId: number, trx?: Knex.Transaction, ): Promise => { - const contact = await this.contactModel.query(trx).findById(contactId); + const contact = await this.contactModel().query(trx).findById(contactId); const tenant = await this.tenancyContext.getTenant(true); // Detarmines whether the contact has foreign currency. diff --git a/packages/server-nest/src/modules/Ledger/LedgerEntriesStorage.service.ts b/packages/server-nest/src/modules/Ledger/LedgerEntriesStorage.service.ts index 738f4a817..213e4a479 100644 --- a/packages/server-nest/src/modules/Ledger/LedgerEntriesStorage.service.ts +++ b/packages/server-nest/src/modules/Ledger/LedgerEntriesStorage.service.ts @@ -8,6 +8,7 @@ import { } from './types/Ledger.types'; import { ILedger } from './types/Ledger.types'; import { AccountTransaction } from '../Accounts/models/AccountTransaction.model'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; // Filter the blank entries. const filterBlankEntry = (entry: ILedgerEntry) => @@ -16,11 +17,13 @@ const filterBlankEntry = (entry: ILedgerEntry) => @Injectable() export class LedgerEntriesStorageService { /** - * @param {typeof AccountTransaction} accountTransactionModel - Account transaction model. + * @param {TenantModelProxy} accountTransactionModel - Account transaction model. */ constructor( @Inject(AccountTransaction.name) - private readonly accountTransactionModel: typeof AccountTransaction, + private readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, ) {} /** @@ -50,7 +53,10 @@ export class LedgerEntriesStorageService { .filter((e) => e.entryId) .map((e) => e.entryId); - await AccountTransaction.query(trx).whereIn('id', entriesIds).delete(); + await this.accountTransactionModel() + .query(trx) + .whereIn('id', entriesIds) + .delete(); }; /** @@ -65,7 +71,7 @@ export class LedgerEntriesStorageService { ): Promise => { const transaction = transformLedgerEntryToTransaction(entry); - await this.accountTransactionModel.query(trx).insert(transaction); + await this.accountTransactionModel().query(trx).insert(transaction); }; /** diff --git a/packages/server-nest/src/modules/Ledger/LedgerStorage.service.ts b/packages/server-nest/src/modules/Ledger/LedgerStorage.service.ts index 3e76020db..c6b0ad1b0 100644 --- a/packages/server-nest/src/modules/Ledger/LedgerStorage.service.ts +++ b/packages/server-nest/src/modules/Ledger/LedgerStorage.service.ts @@ -6,6 +6,7 @@ import { LedegrAccountsStorage } from './LedgetAccountStorage.service'; import { LedgerEntriesStorageService } from './LedgerEntriesStorage.service'; import { AccountTransaction } from '../Accounts/models/AccountTransaction.model'; import { Ledger } from './Ledger'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class LedgerStorageService { @@ -20,7 +21,9 @@ export class LedgerStorageService { private ledgerEntriesService: LedgerEntriesStorageService, @Inject(AccountTransaction.name) - private accountTransactionModel: typeof AccountTransaction, + private accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, ) {} /** @@ -78,7 +81,7 @@ export class LedgerStorageService { trx?: Knex.Transaction, ) => { // Retrieves the transactions of the given reference. - const transactions = await this.accountTransactionModel + const transactions = await this.accountTransactionModel() .query(trx) .modify('filterByReference', referenceId, referenceType) .withGraphFetched('account'); diff --git a/packages/server-nest/src/modules/Ledger/LedgerStorageRevert.service.ts b/packages/server-nest/src/modules/Ledger/LedgerStorageRevert.service.ts index f86614ffe..e3b516c67 100644 --- a/packages/server-nest/src/modules/Ledger/LedgerStorageRevert.service.ts +++ b/packages/server-nest/src/modules/Ledger/LedgerStorageRevert.service.ts @@ -4,18 +4,21 @@ import { Knex } from 'knex'; import { Ledger } from './Ledger'; import { LedgerStorageService } from './LedgerStorage.service'; import { AccountTransaction } from '../Accounts/models/AccountTransaction.model'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class LedgerRevertService { /** - * @param ledgerStorage - Ledger storage service. - * @param accountTransactionModel - Account transaction model. + * @param {LedgerStorageService} ledgerStorage - Ledger storage service. + * @param {TenantModelProxy} accountTransactionModel - Account transaction model. */ constructor( private readonly ledgerStorage: LedgerStorageService, @Inject(AccountTransaction.name) - private readonly accountTransactionModel: typeof AccountTransaction, + private readonly accountTransactionModel: TenantModelProxy< + typeof AccountTransaction + >, ) {} /** @@ -27,7 +30,7 @@ export class LedgerRevertService { referenceId: number | number[], referenceType: string | string[], ) => { - const transactions = await this.accountTransactionModel + const transactions = await this.accountTransactionModel() .query() .whereIn('reference_type', castArray(referenceType)) .whereIn('reference_id', castArray(referenceId)) diff --git a/packages/server-nest/src/modules/Ledger/LedgetAccountStorage.service.ts b/packages/server-nest/src/modules/Ledger/LedgetAccountStorage.service.ts index c719e4a76..937816a4e 100644 --- a/packages/server-nest/src/modules/Ledger/LedgetAccountStorage.service.ts +++ b/packages/server-nest/src/modules/Ledger/LedgetAccountStorage.service.ts @@ -9,6 +9,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { Account } from '../Accounts/models/Account.model'; import { AccountRepository } from '../Accounts/repositories/Account.repository'; import { TenancyContext } from '../Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class LedegrAccountsStorage { @@ -21,7 +22,7 @@ export class LedegrAccountsStorage { private accountRepository: AccountRepository, @Inject(Account.name) - private accountModel: typeof Account, + private accountModel: TenantModelProxy, ) {} /** @@ -114,7 +115,7 @@ export class LedegrAccountsStorage { accountId: number, trx?: Knex.Transaction, ): Promise => { - const account = await this.accountModel.query(trx).findById(accountId); + const account = await this.accountModel().query(trx).findById(accountId); // Filters the ledger entries by the current account. const accountLedger = ledger.whereAccountId(accountId); @@ -139,10 +140,9 @@ export class LedegrAccountsStorage { /** * Saves the account balance. - * @param {number} tenantId - * @param {number} accountId - * @param {number} change - * @param {Knex.Transaction} trx - + * @param {number} accountId + * @param {number} change + * @param {Knex.Transaction} trx - * @returns {Promise} */ private saveAccountBalance = async ( @@ -151,7 +151,7 @@ export class LedegrAccountsStorage { trx?: Knex.Transaction, ) => { // Ensure the account has atleast zero in amount. - await this.accountModel + await this.accountModel() .query(trx) .findById(accountId) .whereNull('amount') diff --git a/packages/server-nest/src/modules/ManualJournals/commands/CommandManualJournalValidators.service.ts b/packages/server-nest/src/modules/ManualJournals/commands/CommandManualJournalValidators.service.ts index eda77d709..b69669eee 100644 --- a/packages/server-nest/src/modules/ManualJournals/commands/CommandManualJournalValidators.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/commands/CommandManualJournalValidators.service.ts @@ -9,18 +9,19 @@ import { ServiceError } from '@/modules/Items/ServiceError'; import { Account } from '@/modules/Accounts/models/Account.model'; import { ManualJournal } from '../models/ManualJournal'; import { Contact } from '@/modules/Contacts/models/Contact'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CommandManualJournalValidators { constructor( @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(ManualJournal.name) - private readonly manualJournalModel: typeof ManualJournal, + private readonly manualJournalModel: TenantModelProxy, @Inject(Contact.name) - private readonly contactModel: typeof Contact, + private readonly contactModel: TenantModelProxy, ) {} /** @@ -51,7 +52,7 @@ export class CommandManualJournalValidators { */ public async validateAccountsExistance(manualJournalDTO: IManualJournalDTO) { const manualAccountsIds = manualJournalDTO.entries.map((e) => e.accountId); - const accounts = await this.accountModel + const accounts = await this.accountModel() .query() .whereIn('id', manualAccountsIds); @@ -71,7 +72,7 @@ export class CommandManualJournalValidators { journalNumber: string, notId?: number, ) { - const journals = await this.manualJournalModel + const journals = await this.manualJournalModel() .query() .where('journal_number', journalNumber) .onBuild((builder) => { @@ -100,17 +101,19 @@ export class CommandManualJournalValidators { contactType: string, ): Promise { // Retrieve account meta by the given account slug. - const account = await this.accountModel + const account = await this.accountModel() .query() .findOne('slug', accountBySlug); // Retrieve all stored contacts on the storage from contacts entries. - const storedContacts = await this.contactModel.query().whereIn( - 'id', - entriesDTO - .filter((entry) => entry.contactId) - .map((entry) => entry.contactId), - ); + const storedContacts = await this.contactModel() + .query() + .whereIn( + 'id', + entriesDTO + .filter((entry) => entry.contactId) + .map((entry) => entry.contactId), + ); // Converts the stored contacts to map with id as key and entry as value. const storedContactsMap = new Map( storedContacts.map((contact) => [contact.id, contact]), @@ -179,7 +182,6 @@ export class CommandManualJournalValidators { /** * Validate entries contacts existance. - * @param {number} tenantId - * @param {IManualJournalDTO} manualJournalDTO */ public async validateContactsExistance(manualJournalDTO: IManualJournalDTO) { @@ -193,7 +195,7 @@ export class CommandManualJournalValidators { (entry) => entry.contactId, ); // Retrieve all stored contacts on the storage from contacts entries. - const storedContacts = await this.contactModel + const storedContacts = await this.contactModel() .query() .whereIn('id', entriesContactsIds); @@ -266,7 +268,6 @@ export class CommandManualJournalValidators { /** * - * @param {number} tenantId * @param {IManualJournalDTO} manualJournalDTO */ public validateJournalCurrencyWithAccountsCurrency = async ( @@ -274,7 +275,9 @@ export class CommandManualJournalValidators { baseCurrency: string, ) => { const accountsIds = manualJournalDTO.entries.map((e) => e.accountId); - const accounts = await this.accountModel.query().whereIn('id', accountsIds); + const accounts = await this.accountModel() + .query() + .whereIn('id', accountsIds); // Filters the accounts that has no base currency or DTO currency. const notSupportedCurrency = accounts.filter((account) => { diff --git a/packages/server-nest/src/modules/ManualJournals/commands/CreateManualJournal.service.ts b/packages/server-nest/src/modules/ManualJournals/commands/CreateManualJournal.service.ts index 00636f58b..a4d35fe35 100644 --- a/packages/server-nest/src/modules/ManualJournals/commands/CreateManualJournal.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/commands/CreateManualJournal.service.ts @@ -17,6 +17,7 @@ import { ManualJournal } from '../models/ManualJournal'; import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; import { ManualJournalBranchesDTOTransformer } from '@/modules/Branches/integrations/ManualJournals/ManualJournalDTOTransformer.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateManualJournalService { @@ -29,7 +30,7 @@ export class CreateManualJournalService { private branchesDTOTransformer: ManualJournalBranchesDTOTransformer, @Inject(ManualJournal.name) - private manualJournalModel: typeof ManualJournal, + private manualJournalModel: TenantModelProxy, ) {} /** @@ -108,7 +109,7 @@ export class CreateManualJournalService { // Validate accounts with contact type from the given config. await this.validator.dynamicValidateAccountsWithContactType( manualJournalDTO.entries, - ) + ); // Validates the accounts currency with journal currency. await this.validator.validateJournalCurrencyWithAccountsCurrency( manualJournalDTO, @@ -129,7 +130,8 @@ export class CreateManualJournalService { // Authorize manual journal creating. await this.authorize(manualJournalDTO); // Transformes the next DTO to model. - const manualJournalObj = await this.transformNewDTOToModel(manualJournalDTO); + const manualJournalObj = + await this.transformNewDTOToModel(manualJournalDTO); // Creates a manual journal transactions with associated transactions // under unit-of-work envirement. @@ -141,7 +143,7 @@ export class CreateManualJournalService { } as IManualJournalCreatingPayload); // Upsert the manual journal object. - const manualJournal = await this.manualJournalModel + const manualJournal = await this.manualJournalModel() .query(trx) .upsertGraph({ ...manualJournalObj, diff --git a/packages/server-nest/src/modules/ManualJournals/commands/DeleteManualJournal.service.ts b/packages/server-nest/src/modules/ManualJournals/commands/DeleteManualJournal.service.ts index f5aa6a1fa..0f87103e3 100644 --- a/packages/server-nest/src/modules/ManualJournals/commands/DeleteManualJournal.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/commands/DeleteManualJournal.service.ts @@ -9,6 +9,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ManualJournal } from '../models/ManualJournal'; import { ManualJournalEntry } from '../models/ManualJournalEntry'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteManualJournalService { @@ -17,10 +18,12 @@ export class DeleteManualJournalService { private readonly uow: UnitOfWork, @Inject(ManualJournal.name) - private readonly manualJournalModel: typeof ManualJournal, + private readonly manualJournalModel: TenantModelProxy, @Inject(ManualJournalEntry.name) - private readonly manualJournalEntryModel: typeof ManualJournalEntry, + private readonly manualJournalEntryModel: TenantModelProxy< + typeof ManualJournalEntry + >, ) {} /** @@ -34,7 +37,8 @@ export class DeleteManualJournalService { oldManualJournal: ManualJournal; }> => { // Validate the manual journal exists on the storage. - const oldManualJournal = await this.manualJournalModel.query() + const oldManualJournal = await this.manualJournalModel() + .query() .findById(manualJournalId) .throwIfNotFound(); @@ -47,13 +51,13 @@ export class DeleteManualJournalService { } as IManualJournalDeletingPayload); // Deletes the manual journal entries. - await this.manualJournalEntryModel + await this.manualJournalEntryModel() .query(trx) .where('manualJournalId', manualJournalId) .delete(); // Deletes the manual journal transaction. - await this.manualJournalModel + await this.manualJournalModel() .query(trx) .findById(manualJournalId) .delete(); diff --git a/packages/server-nest/src/modules/ManualJournals/commands/EditManualJournal.service.ts b/packages/server-nest/src/modules/ManualJournals/commands/EditManualJournal.service.ts index 23ce868bc..d3ded951f 100644 --- a/packages/server-nest/src/modules/ManualJournals/commands/EditManualJournal.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/commands/EditManualJournal.service.ts @@ -12,6 +12,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { CommandManualJournalValidators } from './CommandManualJournalValidators.service'; import { events } from '@/common/events/events'; import { ManualJournal } from '../models/ManualJournal'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditManualJournal { @@ -21,7 +22,7 @@ export class EditManualJournal { private validator: CommandManualJournalValidators, @Inject(ManualJournal.name) - private manualJournalModel: typeof ManualJournal, + private manualJournalModel: TenantModelProxy, ) {} /** @@ -91,7 +92,7 @@ export class EditManualJournal { oldManualJournal: ManualJournal; }> { // Validates the manual journal existance on the storage. - const oldManualJournal = await this.manualJournalModel + const oldManualJournal = await this.manualJournalModel() .query() .findById(manualJournalId) .throwIfNotFound(); @@ -115,11 +116,13 @@ export class EditManualJournal { } as IManualJournalEditingPayload); // Upserts the manual journal graph to the storage. - await this.manualJournalModel.query(trx).upsertGraph({ - ...manualJournalObj, - }); + await this.manualJournalModel() + .query(trx) + .upsertGraph({ + ...manualJournalObj, + }); // Retrieve the given manual journal with associated entries after modifications. - const manualJournal = await this.manualJournalModel + const manualJournal = await this.manualJournalModel() .query(trx) .findById(manualJournalId) .withGraphFetched('entries'); diff --git a/packages/server-nest/src/modules/ManualJournals/commands/ManualJournalGLEntries.ts b/packages/server-nest/src/modules/ManualJournals/commands/ManualJournalGLEntries.ts index 917051158..ab0acc119 100644 --- a/packages/server-nest/src/modules/ManualJournals/commands/ManualJournalGLEntries.ts +++ b/packages/server-nest/src/modules/ManualJournals/commands/ManualJournalGLEntries.ts @@ -3,6 +3,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service'; import { ManualJournal } from '../models/ManualJournal'; import { ManualJournalGL } from './ManualJournalGL'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ManualJournalGLEntries { @@ -12,7 +13,7 @@ export class ManualJournalGLEntries { */ constructor( @Inject(ManualJournal.name) - private readonly manualJournalModel: typeof ManualJournal, + private readonly manualJournalModel: TenantModelProxy, private readonly ledgerStorage: LedgerStorageService, ) {} @@ -26,7 +27,7 @@ export class ManualJournalGLEntries { trx?: Knex.Transaction, ) => { // Retrieves the given manual journal with associated entries. - const manualJournal = await this.manualJournalModel + const manualJournal = await this.manualJournalModel() .query(trx) .findById(manualJournalId) .withGraphFetched('entries.account'); diff --git a/packages/server-nest/src/modules/ManualJournals/commands/PublishManualJournal.service.ts b/packages/server-nest/src/modules/ManualJournals/commands/PublishManualJournal.service.ts index baa447d53..857df0171 100644 --- a/packages/server-nest/src/modules/ManualJournals/commands/PublishManualJournal.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/commands/PublishManualJournal.service.ts @@ -10,6 +10,7 @@ import { CommandManualJournalValidators } from './CommandManualJournalValidators import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ManualJournal } from '../models/ManualJournal'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PublishManualJournal { @@ -19,7 +20,7 @@ export class PublishManualJournal { private validator: CommandManualJournalValidators, @Inject(ManualJournal.name) - private manualJournalModel: typeof ManualJournal, + private manualJournalModel: TenantModelProxy, ) {} /** @@ -37,7 +38,7 @@ export class PublishManualJournal { */ public async publishManualJournal(manualJournalId: number): Promise { // Find the old manual journal or throw not found error. - const oldManualJournal = await this.manualJournalModel + const oldManualJournal = await this.manualJournalModel() .query() .findById(manualJournalId) .throwIfNotFound(); @@ -54,11 +55,15 @@ export class PublishManualJournal { } as IManualJournalPublishingPayload); // Mark the given manual journal as published. - await this.manualJournalModel.query(trx).findById(manualJournalId).patch({ - publishedAt: moment().toMySqlDateTime(), - }); + await this.manualJournalModel() + .query(trx) + .findById(manualJournalId) + .patch({ + publishedAt: moment().toMySqlDateTime(), + }); // Retrieve the manual journal with enrties after modification. - const manualJournal = await this.manualJournalModel.query() + const manualJournal = await this.manualJournalModel() + .query() .findById(manualJournalId) .withGraphFetched('entries'); diff --git a/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournal.service.ts b/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournal.service.ts index 9fcafd22e..d5fa982f8 100644 --- a/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournal.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournal.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { ManualJournal } from '../models/ManualJournal'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { ManualJournalTransfromer } from './ManualJournalTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetManualJournal { @@ -9,7 +10,7 @@ export class GetManualJournal { private readonly transformer: TransformerInjectable, @Inject(ManualJournal.name) - private readonly manualJournalModel: typeof ManualJournal, + private readonly manualJournalModel: TenantModelProxy, ) {} /** @@ -18,7 +19,7 @@ export class GetManualJournal { * @param {number} manualJournalId */ public getManualJournal = async (manualJournalId: number) => { - const manualJournal = await this.manualJournalModel + const manualJournal = await this.manualJournalModel() .query() .findById(manualJournalId) .withGraphFetched('entries.account') diff --git a/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournals.service.ts b/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournals.service.ts index 89b5cdbd7..603c772b9 100644 --- a/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournals.service.ts +++ b/packages/server-nest/src/modules/ManualJournals/queries/GetManualJournals.service.ts @@ -6,6 +6,7 @@ import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service import { ManualJournal } from '../models/ManualJournal'; import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model'; import { IManualJournalsFilter } from '../types/ManualJournals.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetManualJournals { @@ -14,7 +15,7 @@ export class GetManualJournals { private readonly transformer: TransformerInjectable, @Inject(ManualJournal.name) - private readonly manualJournalModel: typeof ManualJournal, + private readonly manualJournalModel: TenantModelProxy, ) {} /** @@ -41,10 +42,10 @@ export class GetManualJournals { // Dynamic service. const dynamicService = await this.dynamicListService.dynamicList( - this.manualJournalModel, + this.manualJournalModel(), filter, ); - const { results, pagination } = await this.manualJournalModel + const { results, pagination } = await this.manualJournalModel() .query() .onBuild((builder) => { dynamicService.buildQuery()(builder); diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/CreatePaymentReceived.serivce.ts b/packages/server-nest/src/modules/PaymentReceived/commands/CreatePaymentReceived.serivce.ts index 62bfc573b..9d94fc7a8 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/CreatePaymentReceived.serivce.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/CreatePaymentReceived.serivce.ts @@ -13,6 +13,7 @@ import { events } from '@/common/events/events'; import { Customer } from '@/modules/Customers/models/Customer'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; import { Inject, Injectable } from '@nestjs/common'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreatePaymentReceivedService { @@ -24,10 +25,10 @@ export class CreatePaymentReceivedService { private tenancyContext: TenancyContext, @Inject(PaymentReceived.name) - private paymentReceived: typeof PaymentReceived, + private paymentReceived: TenantModelProxy, @Inject(Customer.name) - private customer: typeof Customer, + private customer: TenantModelProxy, ) {} /** @@ -43,7 +44,7 @@ export class CreatePaymentReceivedService { const tenant = await this.tenancyContext.getTenant(true); // Validate customer existance. - const paymentCustomer = await this.customer + const paymentCustomer = await this.customer() .query() .findById(paymentReceiveDTO.customerId) .throwIfNotFound(); @@ -85,7 +86,7 @@ export class CreatePaymentReceivedService { } as IPaymentReceivedCreatingPayload); // Inserts the payment receive transaction. - const paymentReceive = await this.paymentReceived + const paymentReceive = await this.paymentReceived() .query(trx) .insertGraphAndFetch({ ...paymentReceiveObj, diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/DeletePaymentReceived.service.ts b/packages/server-nest/src/modules/PaymentReceived/commands/DeletePaymentReceived.service.ts index 88c1a6dc4..7d17c4f2f 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/DeletePaymentReceived.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/DeletePaymentReceived.service.ts @@ -9,6 +9,7 @@ import { IPaymentReceivedDeletingPayload, IPaymentReceivedDeletedPayload, } from '../types/PaymentReceived.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeletePaymentReceivedService { @@ -23,10 +24,12 @@ export class DeletePaymentReceivedService { private uow: UnitOfWork, @Inject(PaymentReceived.name) - private paymentReceiveModel: typeof PaymentReceived, + private paymentReceiveModel: TenantModelProxy, @Inject(PaymentReceivedEntry.name) - private paymentReceiveEntryModel: typeof PaymentReceivedEntry, + private paymentReceiveEntryModel: TenantModelProxy< + typeof PaymentReceivedEntry + >, ) {} /** @@ -44,7 +47,7 @@ export class DeletePaymentReceivedService { */ public async deletePaymentReceive(paymentReceiveId: number) { // Retreive payment receive or throw not found service error. - const oldPaymentReceive = await this.paymentReceiveModel + const oldPaymentReceive = await this.paymentReceiveModel() .query() .withGraphFetched('entries') .findById(paymentReceiveId) @@ -59,13 +62,13 @@ export class DeletePaymentReceivedService { } as IPaymentReceivedDeletingPayload); // Deletes the payment receive associated entries. - await this.paymentReceiveEntryModel + await this.paymentReceiveEntryModel() .query(trx) .where('payment_receive_id', paymentReceiveId) .delete(); // Deletes the payment receive transaction. - await this.paymentReceiveModel + await this.paymentReceiveModel() .query(trx) .findById(paymentReceiveId) .delete(); diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/EditPaymentReceived.service.ts b/packages/server-nest/src/modules/PaymentReceived/commands/EditPaymentReceived.service.ts index 0086538a8..1546c87c2 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/EditPaymentReceived.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/EditPaymentReceived.service.ts @@ -13,6 +13,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { Customer } from '@/modules/Customers/models/Customer'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditPaymentReceivedService { @@ -24,10 +25,12 @@ export class EditPaymentReceivedService { private readonly tenancyContext: TenancyContext, @Inject(PaymentReceived.name) - private readonly paymentReceiveModel: typeof PaymentReceived, + private readonly paymentReceiveModel: TenantModelProxy< + typeof PaymentReceived + >, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -51,7 +54,7 @@ export class EditPaymentReceivedService { const tenant = await this.tenancyContext.getTenant(true); // Validate the payment receive existance. - const oldPaymentReceive = await this.paymentReceiveModel + const oldPaymentReceive = await this.paymentReceiveModel() .query() .withGraphFetched('entries') .findById(paymentReceiveId) @@ -61,7 +64,7 @@ export class EditPaymentReceivedService { this.validators.validatePaymentExistance(oldPaymentReceive); // Validate customer existance. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .findById(paymentReceiveDTO.customerId) .throwIfNotFound(); @@ -120,7 +123,7 @@ export class EditPaymentReceivedService { } as IPaymentReceivedEditingPayload); // Update the payment receive transaction. - const paymentReceive = await this.paymentReceiveModel + const paymentReceive = await this.paymentReceiveModel() .query(trx) .upsertGraphAndFetch({ id: paymentReceiveId, diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedDTOTransformer.ts b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedDTOTransformer.ts index 56783a619..bd5809650 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedDTOTransformer.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedDTOTransformer.ts @@ -14,6 +14,7 @@ import { PaymentReceived } from '../models/PaymentReceived'; import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index'; import { Customer } from '@/modules/Customers/models/Customer'; import { formatDateFields } from '@/utils/format-date-fields'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PaymentReceiveDTOTransformer { @@ -24,7 +25,9 @@ export class PaymentReceiveDTOTransformer { private readonly brandingTemplatesTransformer: BrandingTemplateDTOTransformer, @Inject(PaymentReceived.name) - private readonly paymentReceivedModel: typeof PaymentReceived, + private readonly paymentReceivedModel: TenantModelProxy< + typeof PaymentReceived + >, ) {} /** @@ -36,15 +39,14 @@ export class PaymentReceiveDTOTransformer { public async transformPaymentReceiveDTOToModel( customer: Customer, paymentReceiveDTO: IPaymentReceivedCreateDTO | IPaymentReceivedEditDTO, - oldPaymentReceive?: PaymentReceived + oldPaymentReceive?: PaymentReceived, ): Promise { const amount = paymentReceiveDTO.amount ?? sumBy(paymentReceiveDTO.entries, 'paymentAmount'); // Retreive the next invoice number. - const autoNextNumber = - this.increments.getNextPaymentReceiveNumber(); + const autoNextNumber = this.increments.getNextPaymentReceiveNumber(); // Retrieve the next payment receive number. const paymentReceiveNo = @@ -56,7 +58,7 @@ export class PaymentReceiveDTOTransformer { const entries = R.compose( // Associate the default index to each item entry line. - assocItemEntriesDefaultIndex + assocItemEntriesDefaultIndex, )(paymentReceiveDTO.entries); const initialDTO = { @@ -72,12 +74,12 @@ export class PaymentReceiveDTOTransformer { const initialAsyncDTO = await composeAsync( // Assigns the default branding template id to the invoice DTO. this.brandingTemplatesTransformer.assocDefaultBrandingTemplate( - 'SaleInvoice' - ) + 'SaleInvoice', + ), )(initialDTO); - return R.compose( - this.branchDTOTransform.transformDTO - )(initialAsyncDTO) as PaymentReceived; + return R.compose(this.branchDTOTransform.transformDTO)( + initialAsyncDTO, + ) as PaymentReceived; } } diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedInvoiceSync.service.ts b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedInvoiceSync.service.ts index 74c4dd7f5..5cfb90b3f 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedInvoiceSync.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedInvoiceSync.service.ts @@ -3,12 +3,13 @@ import { Knex } from 'knex'; import { SaleInvoice } from '../../SaleInvoices/models/SaleInvoice'; import { IPaymentReceivedEntryDTO } from '../types/PaymentReceived.types'; import { entriesAmountDiff } from '@/utils/entries-amount-diff'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PaymentReceivedInvoiceSync { constructor( @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -20,7 +21,7 @@ export class PaymentReceivedInvoiceSync { public async saveChangeInvoicePaymentAmount( newPaymentReceiveEntries: IPaymentReceivedEntryDTO[], oldPaymentReceiveEntries?: IPaymentReceivedEntryDTO[], - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { const opers: Promise[] = []; @@ -28,16 +29,16 @@ export class PaymentReceivedInvoiceSync { newPaymentReceiveEntries, oldPaymentReceiveEntries, 'paymentAmount', - 'invoiceId' + 'invoiceId', ); diffEntries.forEach((diffEntry: any) => { if (diffEntry.paymentAmount === 0) { return; } - const oper = this.saleInvoiceModel.changePaymentAmount( + const oper = this.saleInvoiceModel().changePaymentAmount( diffEntry.invoiceId, diffEntry.paymentAmount, - trx + trx, ); opers.push(oper); }); diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedMailNotification.ts b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedMailNotification.ts index c33b1d003..548955518 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedMailNotification.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedMailNotification.ts @@ -16,6 +16,7 @@ import { PaymentReceiveMailPresendEvent } from '../types/PaymentReceived.types'; import { SendInvoiceMailDTO } from '@/modules/SaleInvoices/SaleInvoice.types'; import { Mail } from '@/modules/Mail/Mail'; import { MailTransporter } from '@/modules/Mail/MailTransporter.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SendPaymentReceiveMailNotification { @@ -26,7 +27,9 @@ export class SendPaymentReceiveMailNotification { private readonly mailTransport: MailTransporter, @Inject(PaymentReceived.name) - private readonly paymentReceiveModel: typeof PaymentReceived, + private readonly paymentReceiveModel: TenantModelProxy< + typeof PaymentReceived + >, ) {} /** @@ -61,7 +64,7 @@ export class SendPaymentReceiveMailNotification { public getMailOptions = async ( paymentId: number, ): Promise => { - const paymentReceive = await this.paymentReceiveModel + const paymentReceive = await this.paymentReceiveModel() .query() .findById(paymentId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedValidators.service.ts b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedValidators.service.ts index a51851fe2..6c30e8514 100644 --- a/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedValidators.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/commands/PaymentReceivedValidators.service.ts @@ -11,21 +11,26 @@ import { Account } from '@/modules/Accounts/models/Account.model'; import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ACCOUNT_TYPE } from '@/constants/accounts'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class PaymentReceivedValidators { constructor( @Inject(PaymentReceived.name) - private readonly paymentReceiveModel: typeof PaymentReceived, + private readonly paymentReceiveModel: TenantModelProxy< + typeof PaymentReceived + >, @Inject(PaymentReceivedEntry.name) - private readonly paymentReceiveEntryModel: typeof PaymentReceivedEntry, + private readonly paymentReceiveEntryModel: TenantModelProxy< + typeof PaymentReceivedEntry + >, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, ) {} /** @@ -45,9 +50,10 @@ export class PaymentReceivedValidators { */ public async validatePaymentReceiveNoExistance( paymentReceiveNo: string, - notPaymentReceiveId?: number + notPaymentReceiveId?: number, ): Promise { - const paymentReceive = await this.paymentReceiveModel.query() + const paymentReceive = await this.paymentReceiveModel() + .query() .findOne('payment_receive_no', paymentReceiveNo) .onBuild((builder) => { if (notPaymentReceiveId) { @@ -67,12 +73,13 @@ export class PaymentReceivedValidators { */ public async validateInvoicesIDsExistance( customerId: number, - paymentReceiveEntries: { invoiceId: number }[] + paymentReceiveEntries: { invoiceId: number }[], ): Promise { const invoicesIds = paymentReceiveEntries.map( - (e: { invoiceId: number }) => e.invoiceId + (e: { invoiceId: number }) => e.invoiceId, ); - const storedInvoices = await this.saleInvoiceModel.query() + const storedInvoices = await this.saleInvoiceModel() + .query() .whereIn('id', invoicesIds) .where('customer_id', customerId); @@ -84,7 +91,7 @@ export class PaymentReceivedValidators { } // Filters the not delivered invoices. const notDeliveredInvoices = storedInvoices.filter( - (invoice) => !invoice.isDelivered + (invoice) => !invoice.isDelivered, ); if (notDeliveredInvoices.length > 0) { throw new ServiceError(ERRORS.INVOICES_NOT_DELIVERED_YET, null, { @@ -101,13 +108,14 @@ export class PaymentReceivedValidators { */ public async validateInvoicesPaymentsAmount( paymentReceiveEntries: IPaymentReceivedEntryDTO[], - oldPaymentEntries: PaymentReceivedEntry[] = [] + oldPaymentEntries: PaymentReceivedEntry[] = [], ) { const invoicesIds = paymentReceiveEntries.map( - (e: IPaymentReceivedEntryDTO) => e.invoiceId + (e: IPaymentReceivedEntryDTO) => e.invoiceId, ); - - const storedInvoices = await this.saleInvoiceModel.query().whereIn('id', invoicesIds); + const storedInvoices = await this.saleInvoiceModel() + .query() + .whereIn('id', invoicesIds); const storedInvoicesMap = new Map( storedInvoices.map((invoice: SaleInvoice) => { @@ -118,7 +126,7 @@ export class PaymentReceivedValidators { invoice.id, { ...invoice, dueAmount: invoice.dueAmount + oldPaymentAmount }, ]; - }) + }), ); const hasWrongPaymentAmount: any[] = []; @@ -130,7 +138,7 @@ export class PaymentReceivedValidators { if (dueAmount < entry.paymentAmount) { hasWrongPaymentAmount.push({ index, due_amount: dueAmount }); } - } + }, ); if (hasWrongPaymentAmount.length > 0) { throw new ServiceError(ERRORS.INVALID_PAYMENT_AMOUNT); @@ -154,16 +162,15 @@ export class PaymentReceivedValidators { */ public async validateEntriesIdsExistance( paymentReceiveId: number, - paymentReceiveEntries: IPaymentReceivedEntryDTO[] + paymentReceiveEntries: IPaymentReceivedEntryDTO[], ) { const entriesIds = paymentReceiveEntries .filter((entry) => entry.id) .map((entry) => entry.id); - const storedEntries = await this.paymentReceiveEntryModel.query().where( - 'payment_receive_id', - paymentReceiveId - ); + const storedEntries = await this.paymentReceiveEntryModel() + .query() + .where('payment_receive_id', paymentReceiveId); const storedEntriesIds = storedEntries.map((entry: any) => entry.id); const notFoundEntriesIds = difference(entriesIds, storedEntriesIds); @@ -189,7 +196,7 @@ export class PaymentReceivedValidators { */ public validateCustomerNotModified( paymentReceiveDTO: IPaymentReceivedEditDTO, - oldPaymentReceive: PaymentReceived + oldPaymentReceive: PaymentReceived, ) { if (paymentReceiveDTO.customerId !== oldPaymentReceive.customerId) { throw new ServiceError(ERRORS.PAYMENT_CUSTOMER_SHOULD_NOT_UPDATE); @@ -199,15 +206,15 @@ export class PaymentReceivedValidators { /** * Validates the payment account currency code. The deposit account curreny * should be equals the customer currency code or the base currency. - * @param {string} paymentAccountCurrency - * @param {string} customerCurrency - * @param {string} baseCurrency + * @param {string} paymentAccountCurrency + * @param {string} customerCurrency + * @param {string} baseCurrency * @throws {ServiceError(ERRORS.PAYMENT_ACCOUNT_CURRENCY_INVALID)} */ public validatePaymentAccountCurrency = ( paymentAccountCurrency: string, customerCurrency: string, - baseCurrency: string + baseCurrency: string, ) => { if ( paymentAccountCurrency !== customerCurrency && @@ -222,9 +229,10 @@ export class PaymentReceivedValidators { * @param {number} paymentReceiveId - Payment receive id. */ async getPaymentReceiveOrThrowError( - paymentReceiveId: number + paymentReceiveId: number, ): Promise { - const paymentReceive = await this.paymentReceiveModel.query() + const paymentReceive = await this.paymentReceiveModel() + .query() .withGraphFetched('entries') .findById(paymentReceiveId); @@ -240,9 +248,11 @@ export class PaymentReceivedValidators { * @return {Promise} */ async getDepositAccountOrThrowError( - depositAccountId: number + depositAccountId: number, ): Promise { - const depositAccount = await this.accountModel.query().findById(depositAccountId); + const depositAccount = await this.accountModel() + .query() + .findById(depositAccountId); if (!depositAccount) { throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND); @@ -264,13 +274,10 @@ export class PaymentReceivedValidators { * Validate the given customer has no payments receives. * @param {number} customerId - Customer id. */ - public async validateCustomerHasNoPayments( - customerId: number - ) { - const paymentReceives = await this.paymentReceiveModel.query().where( - 'customer_id', - customerId - ); + public async validateCustomerHasNoPayments(customerId: number) { + const paymentReceives = await this.paymentReceiveModel() + .query() + .where('customer_id', customerId); if (paymentReceives.length > 0) { throw new ServiceError(ERRORS.CUSTOMER_HAS_PAYMENT_RECEIVES); } diff --git a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceived.service.ts b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceived.service.ts index eaf4c6736..9f159becb 100644 --- a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceived.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceived.service.ts @@ -4,6 +4,7 @@ import { PaymentReceiveTransfromer } from './PaymentReceivedTransformer'; import { PaymentReceived } from '../models/PaymentReceived'; import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service'; import { ServiceError } from '../../Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPaymentReceivedService { @@ -11,7 +12,9 @@ export class GetPaymentReceivedService { private readonly transformer: TransformerInjectable, @Inject(PaymentReceived.name) - private readonly paymentReceiveModel: typeof PaymentReceived, + private readonly paymentReceiveModel: TenantModelProxy< + typeof PaymentReceived + >, ) {} /** @@ -20,9 +23,10 @@ export class GetPaymentReceivedService { * @return {Promise} */ public async getPaymentReceive( - paymentReceiveId: number + paymentReceiveId: number, ): Promise { - const paymentReceive = await this.paymentReceiveModel.query() + const paymentReceive = await this.paymentReceiveModel() + .query() .withGraphFetched('customer') .withGraphFetched('depositAccount') .withGraphFetched('entries.invoice') @@ -35,7 +39,7 @@ export class GetPaymentReceivedService { } return this.transformer.transform( paymentReceive, - new PaymentReceiveTransfromer() + new PaymentReceiveTransfromer(), ); } } diff --git a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedInvoices.service.ts b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedInvoices.service.ts index 6f5ffedf2..d0bdb09de 100644 --- a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedInvoices.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedInvoices.service.ts @@ -2,15 +2,16 @@ import { Inject, Injectable } from '@nestjs/common'; import { PaymentReceivedValidators } from '../commands/PaymentReceivedValidators.service'; import { SaleInvoice } from '../../SaleInvoices/models/SaleInvoice'; import { PaymentReceived } from '../models/PaymentReceived'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPaymentReceivedInvoices { constructor( @Inject(PaymentReceived.name) - private paymentReceiveModel: typeof PaymentReceived, + private paymentReceiveModel: TenantModelProxy, @Inject(SaleInvoice.name) - private saleInvoiceModel: typeof SaleInvoice, + private saleInvoiceModel: TenantModelProxy, private validators: PaymentReceivedValidators, ) {} @@ -21,7 +22,7 @@ export class GetPaymentReceivedInvoices { * @return {Promise} */ public async getPaymentReceiveInvoices(paymentReceiveId: number) { - const paymentReceive = await this.paymentReceiveModel + const paymentReceive = await this.paymentReceiveModel() .query() .findById(paymentReceiveId) .withGraphFetched('entries'); @@ -32,7 +33,7 @@ export class GetPaymentReceivedInvoices { const paymentReceiveInvoicesIds = paymentReceive.entries.map( (entry) => entry.invoiceId, ); - const saleInvoices = await this.saleInvoiceModel + const saleInvoices = await this.saleInvoiceModel() .query() .whereIn('id', paymentReceiveInvoicesIds); diff --git a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedPdf.service.ts b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedPdf.service.ts index c7831f1d7..62d199335 100644 --- a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedPdf.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedPdf.service.ts @@ -10,6 +10,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { TemplateInjectable } from '@/modules/TemplateInjectable/TemplateInjectable.service'; import { PaymentReceivedPdfTemplateAttributes } from '../types/PaymentReceived.types'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPaymentReceivedPdfService { @@ -21,10 +22,10 @@ export class GetPaymentReceivedPdfService { private eventPublisher: EventEmitter2, @Inject(PaymentReceived.name) - private paymentReceiveModel: typeof PaymentReceived, + private paymentReceiveModel: TenantModelProxy, @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -66,7 +67,7 @@ export class GetPaymentReceivedPdfService { private async getPaymentReceivedFilename( paymentReceivedId: number, ): Promise { - const payment = await this.paymentReceiveModel + const payment = await this.paymentReceiveModel() .query() .findById(paymentReceivedId); @@ -87,7 +88,7 @@ export class GetPaymentReceivedPdfService { const templateId = paymentReceived?.pdfTemplateId ?? ( - await this.pdfTemplateModel.query().findOne({ + await this.pdfTemplateModel().query().findOne({ resource: 'PaymentReceive', default: true, }) diff --git a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedState.service.ts b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedState.service.ts index 121bcf0c9..244943a8d 100644 --- a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedState.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentReceivedState.service.ts @@ -1,12 +1,13 @@ import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { Inject, Injectable } from '@nestjs/common'; import { IPaymentReceivedState } from '../types/PaymentReceived.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPaymentReceivedStateService { constructor( @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -14,7 +15,7 @@ export class GetPaymentReceivedStateService { * @returns {Promise} - A promise resolving to the payment received state. */ public async getPaymentReceivedState(): Promise { - const defaultPdfTemplate = await this.pdfTemplateModel + const defaultPdfTemplate = await this.pdfTemplateModel() .query() .findOne({ resource: 'PaymentReceive' }) .modify('default'); diff --git a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentsReceived.service.ts b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentsReceived.service.ts index ebf1b4d97..efe2e8e7d 100644 --- a/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentsReceived.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/queries/GetPaymentsReceived.service.ts @@ -6,6 +6,7 @@ import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service import { PaymentReceived } from '../models/PaymentReceived'; import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model'; import { IPaymentsReceivedFilter } from '../types/PaymentReceived.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPaymentsReceivedService { @@ -14,7 +15,9 @@ export class GetPaymentsReceivedService { private readonly transformer: TransformerInjectable, @Inject(PaymentReceived.name) - private readonly paymentReceivedModel: typeof PaymentReceived, + private readonly paymentReceivedModel: TenantModelProxy< + typeof PaymentReceived + >, ) {} /** @@ -34,7 +37,7 @@ export class GetPaymentsReceivedService { PaymentReceived, filter, ); - const { results, pagination } = await this.paymentReceivedModel + const { results, pagination } = await this.paymentReceivedModel() .query() .onBuild((builder) => { builder.withGraphFetched('customer'); diff --git a/packages/server-nest/src/modules/PaymentReceived/queries/PaymentsReceivedPages.service.ts b/packages/server-nest/src/modules/PaymentReceived/queries/PaymentsReceivedPages.service.ts index d14b9b6b4..70a1532a7 100644 --- a/packages/server-nest/src/modules/PaymentReceived/queries/PaymentsReceivedPages.service.ts +++ b/packages/server-nest/src/modules/PaymentReceived/queries/PaymentsReceivedPages.service.ts @@ -5,6 +5,7 @@ import { ERRORS } from '../constants'; import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice'; import { PaymentReceived } from '../models/PaymentReceived'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; /** * Payment receives edit/new pages service. @@ -13,10 +14,10 @@ import { ServiceError } from '@/modules/Items/ServiceError'; export class PaymentsReceivedPagesService { constructor( @Inject(SaleInvoice.name) - private readonly saleInvoice: typeof SaleInvoice, + private readonly saleInvoice: TenantModelProxy, @Inject(PaymentReceived.name) - private readonly paymentReceived: typeof PaymentReceived, + private readonly paymentReceived: TenantModelProxy, ) {} /** @@ -46,7 +47,7 @@ export class PaymentsReceivedPagesService { */ public async getNewPageEntries(tenantId: number, customerId: number) { // Retrieve due invoices. - const entries = await this.saleInvoice + const entries = await this.saleInvoice() .query() .modify('delivered') .modify('dueInvoices') @@ -69,7 +70,7 @@ export class PaymentsReceivedPagesService { entries: IPaymentReceivePageEntry[]; }> { // Retrieve payment receive. - const paymentReceive = await this.paymentReceived + const paymentReceive = await this.paymentReceived() .query() .findById(paymentReceiveId) .withGraphFetched('entries.invoice') @@ -86,7 +87,7 @@ export class PaymentsReceivedPagesService { index: entry.index, })); // Retrieves all receivable bills that associated to the payment receive transaction. - const restReceivableInvoices = await this.saleInvoice + const restReceivableInvoices = await this.saleInvoice() .query() .modify('delivered') .modify('dueInvoices') diff --git a/packages/server-nest/src/modules/PdfTemplate/BrandingTemplateDTOTransformer.ts b/packages/server-nest/src/modules/PdfTemplate/BrandingTemplateDTOTransformer.ts index 277f2255e..22f295900 100644 --- a/packages/server-nest/src/modules/PdfTemplate/BrandingTemplateDTOTransformer.ts +++ b/packages/server-nest/src/modules/PdfTemplate/BrandingTemplateDTOTransformer.ts @@ -1,6 +1,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { isNil } from 'lodash'; import { PdfTemplateModel } from './models/PdfTemplate'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class BrandingTemplateDTOTransformer { @@ -9,13 +10,13 @@ export class BrandingTemplateDTOTransformer { */ constructor( @Inject(PdfTemplateModel.name) - private readonly pdfTemplate: typeof PdfTemplateModel, + private readonly pdfTemplate: TenantModelProxy, ) {} /** * Associates the default branding template id. * @param {string} resource - Resource name. - * @param {Record} object - + * @param {Record} object - * @param {string} attributeName * @returns */ @@ -23,7 +24,7 @@ export class BrandingTemplateDTOTransformer { (resource: string) => async (object: Record) => { const attributeName = 'pdfTemplateId'; - const defaultTemplate = await this.pdfTemplate + const defaultTemplate = await this.pdfTemplate() .query() .modify('default') .findOne({ resource }); diff --git a/packages/server-nest/src/modules/PdfTemplate/commands/AssignPdfTemplateDefault.service.ts b/packages/server-nest/src/modules/PdfTemplate/commands/AssignPdfTemplateDefault.service.ts index 2b35066a9..89a2c9c56 100644 --- a/packages/server-nest/src/modules/PdfTemplate/commands/AssignPdfTemplateDefault.service.ts +++ b/packages/server-nest/src/modules/PdfTemplate/commands/AssignPdfTemplateDefault.service.ts @@ -4,14 +4,18 @@ import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { PdfTemplateModel } from '../models/PdfTemplate'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class AssignPdfTemplateDefaultService { constructor( private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, + @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, ) {} /** @@ -21,35 +25,36 @@ export class AssignPdfTemplateDefaultService { * @throws {Error} Throws an error if the specified template is not found. */ public async assignDefaultTemplate(templateId: number) { - const oldPdfTemplate = await this.pdfTemplateModel.query() + const oldPdfTemplate = await this.pdfTemplateModel() + .query() .findById(templateId) .throwIfNotFound(); - return this.uow.withTransaction( - async (trx?: Knex.Transaction) => { - // Triggers `onPdfTemplateAssigningDefault` event. - await this.eventPublisher.emitAsync( - events.pdfTemplate.onAssigningDefault, - { - templateId, - } - ); - await this.pdfTemplateModel.query(trx) - .where('resource', oldPdfTemplate.resource) - .patch({ default: false }); + return this.uow.withTransaction(async (trx?: Knex.Transaction) => { + // Triggers `onPdfTemplateAssigningDefault` event. + await this.eventPublisher.emitAsync( + events.pdfTemplate.onAssigningDefault, + { + templateId, + }, + ); + await this.pdfTemplateModel() + .query(trx) + .where('resource', oldPdfTemplate.resource) + .patch({ default: false }); - await this.pdfTemplateModel.query(trx) - .findById(templateId) - .patch({ default: true }); + await this.pdfTemplateModel() + .query(trx) + .findById(templateId) + .patch({ default: true }); - // Triggers `onPdfTemplateAssignedDefault` event. - await this.eventPublisher.emitAsync( - events.pdfTemplate.onAssignedDefault, - { - templateId, - } - ); - } - ); + // Triggers `onPdfTemplateAssignedDefault` event. + await this.eventPublisher.emitAsync( + events.pdfTemplate.onAssignedDefault, + { + templateId, + }, + ); + }); } } diff --git a/packages/server-nest/src/modules/PdfTemplate/commands/CreatePdfTemplate.service.ts b/packages/server-nest/src/modules/PdfTemplate/commands/CreatePdfTemplate.service.ts index 9d4c3d9fc..a6c5d99f1 100644 --- a/packages/server-nest/src/modules/PdfTemplate/commands/CreatePdfTemplate.service.ts +++ b/packages/server-nest/src/modules/PdfTemplate/commands/CreatePdfTemplate.service.ts @@ -4,6 +4,7 @@ import { events } from '@/common/events/events'; import { ICreateInvoicePdfTemplateDTO } from '../types'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { PdfTemplateModel } from '../models/PdfTemplate'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreatePdfTemplateService { @@ -12,7 +13,9 @@ export class CreatePdfTemplateService { private readonly eventEmitter: EventEmitter2, @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, ) {} /** @@ -32,7 +35,7 @@ export class CreatePdfTemplateService { // Triggers `onPdfTemplateCreating` event. await this.eventEmitter.emitAsync(events.pdfTemplate.onCreating, {}); - const pdfTemplate = await this.pdfTemplateModel.query(trx).insert({ + const pdfTemplate = await this.pdfTemplateModel().query(trx).insert({ templateName, resource, attributes, diff --git a/packages/server-nest/src/modules/PdfTemplate/commands/DeletePdfTemplate.service.ts b/packages/server-nest/src/modules/PdfTemplate/commands/DeletePdfTemplate.service.ts index d3b501ddf..32683d481 100644 --- a/packages/server-nest/src/modules/PdfTemplate/commands/DeletePdfTemplate.service.ts +++ b/packages/server-nest/src/modules/PdfTemplate/commands/DeletePdfTemplate.service.ts @@ -5,12 +5,15 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; import { ServiceError } from '../../Items/ServiceError'; import { PdfTemplateModel } from '../models/PdfTemplate'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeletePdfTemplateService { constructor( @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, private readonly uow: UnitOfWork, private readonly eventEmitter: EventEmitter2, ) {} @@ -20,7 +23,8 @@ export class DeletePdfTemplateService { * @param {number} templateId - Pdf template id. */ public async deletePdfTemplate(templateId: number) { - const oldPdfTemplate = await this.pdfTemplateModel.query() + const oldPdfTemplate = await this.pdfTemplateModel() + .query() .findById(templateId) .throwIfNotFound(); @@ -36,7 +40,7 @@ export class DeletePdfTemplateService { oldPdfTemplate, trx, }); - await this.pdfTemplateModel.query(trx).deleteById(templateId); + await this.pdfTemplateModel().query(trx).deleteById(templateId); // Triggers `onPdfTemplateDeleted` event. await this.eventEmitter.emitAsync(events.pdfTemplate.onDeleted, { diff --git a/packages/server-nest/src/modules/PdfTemplate/commands/EditPdfTemplate.service.ts b/packages/server-nest/src/modules/PdfTemplate/commands/EditPdfTemplate.service.ts index b6febaf9a..16ecc6d85 100644 --- a/packages/server-nest/src/modules/PdfTemplate/commands/EditPdfTemplate.service.ts +++ b/packages/server-nest/src/modules/PdfTemplate/commands/EditPdfTemplate.service.ts @@ -5,12 +5,15 @@ import { PdfTemplateModel } from '../models/PdfTemplate'; import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditPdfTemplateService { constructor( @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, private readonly uow: UnitOfWork, private readonly eventEmitter: EventEmitter2, ) {} @@ -22,9 +25,10 @@ export class EditPdfTemplateService { */ public async editPdfTemplate( templateId: number, - editTemplateDTO: IEditPdfTemplateDTO + editTemplateDTO: IEditPdfTemplateDTO, ) { - const oldPdfTemplate = await this.pdfTemplateModel.query() + const oldPdfTemplate = await this.pdfTemplateModel() + .query() .findById(templateId) .throwIfNotFound(); @@ -34,7 +38,8 @@ export class EditPdfTemplateService { templateId, }); - const pdfTemplate = await this.pdfTemplateModel.query(trx) + const pdfTemplate = await this.pdfTemplateModel() + .query(trx) .where('id', templateId) .update({ templateName: editTemplateDTO.templateName, diff --git a/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplate.service.ts b/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplate.service.ts index edbef0206..990a04d52 100644 --- a/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplate.service.ts +++ b/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplate.service.ts @@ -3,12 +3,15 @@ import { Knex } from 'knex'; import { GetPdfTemplateTransformer } from './GetPdfTemplate.transformer'; import { PdfTemplateModel } from '../models/PdfTemplate'; import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPdfTemplateService { constructor( @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, private readonly transformer: TransformerInjectable, ) {} @@ -19,15 +22,16 @@ export class GetPdfTemplateService { */ async getPdfTemplate( templateId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { - const template = await this.pdfTemplateModel.query(trx) + const template = await this.pdfTemplateModel() + .query(trx) .findById(templateId) .throwIfNotFound(); return this.transformer.transform( template, - new GetPdfTemplateTransformer() + new GetPdfTemplateTransformer(), ); } } diff --git a/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplates.service.ts b/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplates.service.ts index 4fd7b8dc2..f69e57022 100644 --- a/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplates.service.ts +++ b/packages/server-nest/src/modules/PdfTemplate/queries/GetPdfTemplates.service.ts @@ -2,13 +2,17 @@ import { Inject, Injectable } from '@nestjs/common'; import { GetPdfTemplatesTransformer } from './GetPdfTemplates.transformer'; import { PdfTemplateModel } from '../models/PdfTemplate'; import { TransformerInjectable } from '../../Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetPdfTemplates { constructor( private readonly transformInjectable: TransformerInjectable, + @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, ) {} /** @@ -18,12 +22,14 @@ export class GetPdfTemplates { * @returns {Promise} - A promise that resolves to the transformed list of PDF templates. */ async getPdfTemplates(query?: { resource?: string }) { - const templates = await this.pdfTemplateModel.query().onBuild((q) => { - if (query?.resource) { - q.where('resource', query?.resource); - } - q.orderBy('createdAt', 'ASC'); - }); + const templates = await this.pdfTemplateModel() + .query() + .onBuild((q) => { + if (query?.resource) { + q.where('resource', query?.resource); + } + q.orderBy('createdAt', 'ASC'); + }); return this.transformInjectable.transform( templates, diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/ApproveSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/ApproveSaleEstimate.service.ts index 721a1bd89..a17e9348e 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/ApproveSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/ApproveSaleEstimate.service.ts @@ -11,12 +11,14 @@ import { SaleEstimate } from '../models/SaleEstimate'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ApproveSaleEstimateService { constructor( @Inject(SaleEstimate.name) - private saleEstimateModel: typeof SaleEstimate, + private saleEstimateModel: TenantModelProxy, + private uow: UnitOfWork, private eventPublisher: EventEmitter2, ) {} @@ -28,7 +30,7 @@ export class ApproveSaleEstimateService { */ public async approveSaleEstimate(saleEstimateId: number): Promise { // Retrieve details of the given sale estimate id. - const oldSaleEstimate = await this.saleEstimateModel + const oldSaleEstimate = await this.saleEstimateModel() .query() .findById(saleEstimateId) .throwIfNotFound(); @@ -50,7 +52,7 @@ export class ApproveSaleEstimateService { } as ISaleEstimateApprovingEvent); // Update estimate as approved. - const saleEstimate = await this.saleEstimateModel + const saleEstimate = await this.saleEstimateModel() .query(trx) .patchAndFetchById(saleEstimateId, { approvedAt: moment().toMySqlDateTime(), diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/ConvetSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/ConvetSaleEstimate.service.ts index 8e71ebc92..aa807e0df 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/ConvetSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/ConvetSaleEstimate.service.ts @@ -4,6 +4,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { Knex } from 'knex'; import { SaleEstimate } from '../models/SaleEstimate'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ConvertSaleEstimate { @@ -11,7 +12,7 @@ export class ConvertSaleEstimate { private readonly eventPublisher: EventEmitter2, @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, ) {} /** @@ -22,23 +23,24 @@ export class ConvertSaleEstimate { public async convertEstimateToInvoice( estimateId: number, invoiceId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { // Retrieve details of the given sale estimate. - const saleEstimate = await this.saleEstimateModel.query() + const saleEstimate = await this.saleEstimateModel() + .query() .findById(estimateId) .throwIfNotFound(); // Marks the estimate as converted from the givne invoice. - await this.saleEstimateModel.query(trx).where('id', estimateId).patch({ + await this.saleEstimateModel().query(trx).where('id', estimateId).patch({ convertedToInvoiceId: invoiceId, convertedToInvoiceAt: moment().toMySqlDateTime(), }); - + // Triggers `onSaleEstimateConvertedToInvoice` event. await this.eventPublisher.emitAsync( events.saleEstimate.onConvertedToInvoice, - {} + {}, ); } } diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/CreateSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/CreateSaleEstimate.service.ts index c7221e423..d0329f050 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/CreateSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/CreateSaleEstimate.service.ts @@ -13,12 +13,17 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service'; import { Customer } from '@/modules/Customers/models/Customer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateSaleEstimate { constructor( - @Inject(SaleEstimate.name) private saleEstimateModel: typeof SaleEstimate, - @Inject(Customer.name) private customerModel: typeof Customer, + @Inject(SaleEstimate.name) + private saleEstimateModel: TenantModelProxy, + + @Inject(Customer.name) + private customerModel: TenantModelProxy, + private itemsEntriesService: ItemsEntriesService, private eventPublisher: EventEmitter2, private uow: UnitOfWork, @@ -36,7 +41,7 @@ export class CreateSaleEstimate { trx?: Knex.Transaction, ): Promise { // Retrieve the given customer or throw not found service error. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .findById(estimateDTO.customerId) .throwIfNotFound(); @@ -67,7 +72,7 @@ export class CreateSaleEstimate { } as ISaleEstimateCreatingPayload); // Upsert the sale estimate graph to the storage. - const saleEstimate = await this.saleEstimateModel + const saleEstimate = await this.saleEstimateModel() .query(trx) .upsertGraphAndFetch({ ...estimateObj, diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/DeleteSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/DeleteSaleEstimate.service.ts index 3ab7f8da7..823c60bb2 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/DeleteSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/DeleteSaleEstimate.service.ts @@ -11,15 +11,16 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteSaleEstimate { constructor( @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, @Inject(ItemEntry.name) - private readonly itemEntryModel: typeof ItemEntry, + private readonly itemEntryModel: TenantModelProxy, private readonly eventPublisher: EventEmitter2, private readonly uow: UnitOfWork, @@ -33,7 +34,7 @@ export class DeleteSaleEstimate { */ public async deleteEstimate(estimateId: number): Promise { // Retrieve sale estimate or throw not found service error. - const oldSaleEstimate = await this.saleEstimateModel + const oldSaleEstimate = await this.saleEstimateModel() .query() .findById(estimateId) .throwIfNotFound(); @@ -51,14 +52,17 @@ export class DeleteSaleEstimate { } as ISaleEstimateDeletingPayload); // Delete sale estimate entries. - await this.itemEntryModel + await this.itemEntryModel() .query(trx) .where('reference_id', estimateId) .where('reference_type', 'SaleEstimate') .delete(); // Delete sale estimate transaction. - await this.saleEstimateModel.query(trx).where('id', estimateId).delete(); + await this.saleEstimateModel() + .query(trx) + .where('id', estimateId) + .delete(); // Triggers `onSaleEstimatedDeleted` event. await this.eventPublisher.emitAsync(events.saleEstimate.onDeleted, { diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/DeliverSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/DeliverSaleEstimate.service.ts index d0e89e31c..e2ca0d4e3 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/DeliverSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/DeliverSaleEstimate.service.ts @@ -11,12 +11,14 @@ import { SaleEstimate } from '../models/SaleEstimate'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeliverSaleEstimateService { constructor( @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, + private readonly eventPublisher: EventEmitter2, private readonly uow: UnitOfWork, ) {} @@ -27,7 +29,7 @@ export class DeliverSaleEstimateService { */ public async deliverSaleEstimate(saleEstimateId: number): Promise { // Retrieve details of the given sale estimate id. - const oldSaleEstimate = await this.saleEstimateModel + const oldSaleEstimate = await this.saleEstimateModel() .query() .findById(saleEstimateId) .throwIfNotFound(); @@ -47,7 +49,7 @@ export class DeliverSaleEstimateService { } as ISaleEstimateEventDeliveringPayload); // Record the delivered at on the storage. - const saleEstimate = await this.saleEstimateModel + const saleEstimate = await this.saleEstimateModel() .query(trx) .patchAndFetchById(saleEstimateId, { deliveredAt: moment().toMySqlDateTime(), diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/EditSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/EditSaleEstimate.service.ts index 7d9d1fb4c..fbbc1263b 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/EditSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/EditSaleEstimate.service.ts @@ -13,6 +13,7 @@ import { events } from '@/common/events/events'; import { SaleEstimate } from '../models/SaleEstimate'; import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service'; import { Customer } from '@/modules/Customers/models/Customer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditSaleEstimate { @@ -24,10 +25,10 @@ export class EditSaleEstimate { private readonly transformerDTO: SaleEstimateDTOTransformer, @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -42,7 +43,7 @@ export class EditSaleEstimate { estimateDTO: ISaleEstimateDTO, ): Promise { // Retrieve details of the given sale estimate id. - const oldSaleEstimate = await this.saleEstimateModel + const oldSaleEstimate = await this.saleEstimateModel() .query() .findById(estimateId); @@ -50,7 +51,7 @@ export class EditSaleEstimate { this.validators.validateEstimateExistance(oldSaleEstimate); // Retrieve the given customer or throw not found service error. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .findById(estimateDTO.customerId) .throwIfNotFound(); @@ -93,7 +94,7 @@ export class EditSaleEstimate { } as ISaleEstimateEditingPayload); // Upsert the estimate graph to the storage. - const saleEstimate = await this.saleEstimateModel + const saleEstimate = await this.saleEstimateModel() .query(trx) .upsertGraphAndFetch({ id: estimateId, diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/RejectSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/RejectSaleEstimate.service.ts index 37dd9c9bf..961bf6a54 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/RejectSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/RejectSaleEstimate.service.ts @@ -7,13 +7,13 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ERRORS } from '../constants'; import { events } from '@/common/events/events'; - +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RejectSaleEstimateService { constructor( @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, private readonly eventPublisher: EventEmitter2, private readonly uow: UnitOfWork, ) {} @@ -24,7 +24,8 @@ export class RejectSaleEstimateService { */ public async rejectSaleEstimate(saleEstimateId: number): Promise { // Retrieve details of the given sale estimate id. - const saleEstimate = await this.saleEstimateModel.query() + const saleEstimate = await this.saleEstimateModel() + .query() .findById(saleEstimateId) .throwIfNotFound(); @@ -39,10 +40,13 @@ export class RejectSaleEstimateService { return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Mark the sale estimate as reject on the storage. - await this.saleEstimateModel.query(trx).where('id', saleEstimateId).patch({ - rejectedAt: moment().toMySqlDateTime(), - approvedAt: null, - }); + await this.saleEstimateModel() + .query(trx) + .where('id', saleEstimateId) + .patch({ + rejectedAt: moment().toMySqlDateTime(), + approvedAt: null, + }); // Triggers `onSaleEstimateRejected` event. await this.eventPublisher.emitAsync(events.saleEstimate.onRejected, {}); }); diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateDTOTransformer.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateDTOTransformer.service.ts index 7da69c35d..669cc3b81 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateDTOTransformer.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateDTOTransformer.service.ts @@ -1,7 +1,7 @@ import * as R from 'ramda'; import { Inject, Injectable } from '@nestjs/common'; import { omit, sumBy } from 'lodash'; -import * as composeAsync from 'async/compose'; +import * as composeAsync from 'async/compose'; // import { ICustomer, ISaleEstimate, ISaleEstimateDTO } from '../types/SaleEstimates.types'; import { SaleEstimateValidators } from './SaleEstimateValidators.service'; // import { BranchTransactionDTOTransform } from '@/services/Branches/Integrations/BranchTransactionDTOTransform'; @@ -17,6 +17,7 @@ import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry'; import { SaleEstimate } from '../models/SaleEstimate'; import { Customer } from '@/modules/Customers/models/Customer'; import { ISaleEstimateDTO } from '../types/SaleEstimates.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; // import { assocItemEntriesDefaultIndex } from '@/services/Items/utils'; // import { BrandingTemplateDTOTransformer } from '@/services/PdfTemplate/BrandingTemplateDTOTransformer'; @@ -24,7 +25,8 @@ import { ISaleEstimateDTO } from '../types/SaleEstimates.types'; export class SaleEstimateDTOTransformer { constructor( @Inject(ItemEntry.name) - private itemEntryModel: typeof ItemEntry, + private itemEntryModel: TenantModelProxy, + private readonly validators: SaleEstimateValidators, private readonly branchDTOTransform: BranchTransactionDTOTransformer, private readonly warehouseDTOTransform: WarehouseTransactionDTOTransform, @@ -42,10 +44,10 @@ export class SaleEstimateDTOTransformer { async transformDTOToModel( estimateDTO: ISaleEstimateDTO, paymentCustomer: Customer, - oldSaleEstimate?: SaleEstimate + oldSaleEstimate?: SaleEstimate, ): Promise { - const amount = sumBy(estimateDTO.entries, (e) => - this.itemEntryModel.calcAmount(e) + const amount = sumBy(estimateDTO.entries, (e) => + this.itemEntryModel().calcAmount(e), ); // Retrieve the next invoice number. const autoNextNumber = this.estimateIncrement.getNextEstimateNumber(); @@ -64,14 +66,14 @@ export class SaleEstimateDTOTransformer { R.map((entry) => R.assoc('reference_type', 'SaleEstimate', entry)), // Associate default index to item entries. - assocItemEntriesDefaultIndex + assocItemEntriesDefaultIndex, )(estimateDTO.entries); const initialDTO = { amount, ...formatDateFields( omit(estimateDTO, ['delivered', 'entries', 'attachments']), - ['estimateDate', 'expirationDate'] + ['estimateDate', 'expirationDate'], ), currencyCode: paymentCustomer.currencyCode, exchangeRate: estimateDTO.exchangeRate || 1, @@ -86,8 +88,8 @@ export class SaleEstimateDTOTransformer { const initialAsyncDTO = await composeAsync( // Assigns the default branding template id to the invoice DTO. this.brandingTemplatesTransformer.assocDefaultBrandingTemplate( - 'SaleEstimate' - ) + 'SaleEstimate', + ), )(initialDTO); return R.compose( @@ -103,7 +105,7 @@ export class SaleEstimateDTOTransformer { */ public transformEstimateNumberToModel( saleEstimateDTO: ISaleEstimateDTO, - oldSaleEstimate?: SaleEstimate + oldSaleEstimate?: SaleEstimate, ): string { const autoNextNumber = this.estimateIncrement.getNextEstimateNumber(); diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateValidators.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateValidators.service.ts index 7746c5626..7287823c6 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateValidators.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/SaleEstimateValidators.service.ts @@ -2,12 +2,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { ERRORS } from '../constants'; import { SaleEstimate } from '../models/SaleEstimate'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleEstimateValidators { constructor( @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, ) {} /** @@ -29,7 +30,7 @@ export class SaleEstimateValidators { estimateNumber: string, notEstimateId?: number, ) { - const foundSaleEstimate = await this.saleEstimateModel + const foundSaleEstimate = await this.saleEstimateModel() .query() .findOne('estimate_number', estimateNumber) .onBuild((builder) => { @@ -70,7 +71,7 @@ export class SaleEstimateValidators { * @param {number} customerId - The customer id. */ public async validateCustomerHasNoEstimates(customerId: number) { - const estimates = await this.saleEstimateModel + const estimates = await this.saleEstimateModel() .query() .where('customer_id', customerId); diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/SendSaleEstimateMail.ts b/packages/server-nest/src/modules/SaleEstimates/commands/SendSaleEstimateMail.ts index 7ba24e966..3ae385a91 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/SendSaleEstimateMail.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/SendSaleEstimateMail.ts @@ -22,6 +22,7 @@ import { import { SaleEstimateMailOptions } from '../types/SaleEstimates.types'; import { Mail } from '@/modules/Mail/Mail'; import { MailTransporter } from '@/modules/Mail/MailTransporter.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SendSaleEstimateMail { @@ -41,7 +42,8 @@ export class SendSaleEstimateMail { private readonly mailTransporter: MailTransporter, @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, + @InjectQueue(SendSaleEstimateMailQueue) private readonly sendEstimateMailQueue: Queue, ) {} @@ -91,7 +93,7 @@ export class SendSaleEstimateMail { defaultSubject: string = DEFAULT_ESTIMATE_REMINDER_MAIL_SUBJECT, defaultMessage: string = DEFAULT_ESTIMATE_REMINDER_MAIL_CONTENT, ): Promise => { - const saleEstimate = await this.saleEstimateModel + const saleEstimate = await this.saleEstimateModel() .query() .findById(saleEstimateId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/SaleEstimates/commands/UnlinkConvertedSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/commands/UnlinkConvertedSaleEstimate.service.ts index 4bd05de52..50af5037e 100644 --- a/packages/server-nest/src/modules/SaleEstimates/commands/UnlinkConvertedSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/commands/UnlinkConvertedSaleEstimate.service.ts @@ -1,12 +1,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { Knex } from 'knex'; import { SaleEstimate } from '../models/SaleEstimate'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class UnlinkConvertedSaleEstimate { constructor( @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, ) {} /** @@ -16,9 +17,10 @@ export class UnlinkConvertedSaleEstimate { */ public async unlinkConvertedEstimateFromInvoice( invoiceId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { - await this.saleEstimateModel.query(trx) + await this.saleEstimateModel() + .query(trx) .where({ convertedToInvoiceId: invoiceId, }) diff --git a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimate.service.ts b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimate.service.ts index bd6f5f664..f56cae01c 100644 --- a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimate.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimate.service.ts @@ -5,12 +5,14 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { SaleEstimate } from '../models/SaleEstimate'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleEstimate { constructor( @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, + private readonly transformer: TransformerInjectable, private readonly validators: SaleEstimateValidators, private readonly eventPublisher: EventEmitter2, @@ -22,7 +24,8 @@ export class GetSaleEstimate { * @param {Integer} estimateId */ public async getEstimate(estimateId: number) { - const estimate = await this.saleEstimateModel.query() + const estimate = await this.saleEstimateModel() + .query() .findById(estimateId) .withGraphFetched('entries.item') .withGraphFetched('customer') @@ -35,14 +38,14 @@ export class GetSaleEstimate { // Transformes sale estimate model to POJO. const transformed = await this.transformer.transform( estimate, - new SaleEstimateTransfromer() + new SaleEstimateTransfromer(), ); const eventPayload = { saleEstimateId: estimateId }; // Triggers `onSaleEstimateViewed` event. await this.eventPublisher.emitAsync( events.saleEstimate.onViewed, - eventPayload + eventPayload, ); return transformed; } diff --git a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimatePdf.ts b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimatePdf.ts index 3c9ab97c9..84de0df7e 100644 --- a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimatePdf.ts +++ b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimatePdf.ts @@ -1,14 +1,15 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { EventEmitter2 } from '@nestjs/event-emitter'; import { GetSaleEstimate } from './GetSaleEstimate.service'; import { transformEstimateToPdfTemplate } from '../utils'; import { EstimatePdfBrandingAttributes } from '../constants'; -import { EventEmitter2 } from '@nestjs/event-emitter'; import { SaleEstimatePdfTemplate } from '@/modules/SaleInvoices/queries/SaleEstimatePdfTemplate.service'; import { TemplateInjectable } from '@/modules/TemplateInjectable/TemplateInjectable.service'; import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; -import { Inject, Injectable } from '@nestjs/common'; import { events } from '@/common/events/events'; import { SaleEstimate } from '../models/SaleEstimate'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleEstimatePdf { @@ -20,10 +21,12 @@ export class GetSaleEstimatePdf { private readonly eventPublisher: EventEmitter2, @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, ) {} /** @@ -37,6 +40,7 @@ export class GetSaleEstimatePdf { const filename = await this.getSaleEstimateFilename(saleEstimateId); const brandingAttributes = await this.getEstimateBrandingAttributes(saleEstimateId); + const htmlContent = await this.templateInjectable.render( 'modules/estimate-regular', brandingAttributes, @@ -59,7 +63,9 @@ export class GetSaleEstimatePdf { * @returns {Promise} */ private async getSaleEstimateFilename(estimateId: number) { - const estimate = await this.saleEstimateModel.query().findById(estimateId); + const estimate = await this.saleEstimateModel() + .query() + .findById(estimateId); return `Estimate-${estimate.estimateNumber}`; } @@ -78,7 +84,7 @@ export class GetSaleEstimatePdf { const templateId = saleEstimate.pdfTemplateId ?? ( - await this.pdfTemplateModel.query().findOne({ + await this.pdfTemplateModel().query().findOne({ resource: 'SaleEstimate', default: true, }) diff --git a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimateState.service.ts b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimateState.service.ts index aae6613b5..8166b7132 100644 --- a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimateState.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimateState.service.ts @@ -1,12 +1,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { ISaleEstimateState } from '../types/SaleEstimates.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleEstimateState { constructor( @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -14,7 +15,7 @@ export class GetSaleEstimateState { * @return {Promise} */ public async getSaleEstimateState(): Promise { - const defaultPdfTemplate = await this.pdfTemplateModel + const defaultPdfTemplate = await this.pdfTemplateModel() .query() .findOne({ resource: 'SaleEstimate' }) .modify('default'); diff --git a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimates.service.ts b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimates.service.ts index 589593442..e0cecf679 100644 --- a/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimates.service.ts +++ b/packages/server-nest/src/modules/SaleEstimates/queries/GetSaleEstimates.service.ts @@ -6,6 +6,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model'; import { ISalesEstimatesFilter } from '../types/SaleEstimates.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleEstimatesService { @@ -14,16 +15,14 @@ export class GetSaleEstimatesService { private readonly transformer: TransformerInjectable, @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, ) {} /** * Retrieves estimates filterable and paginated list. * @param {IEstimatesFilter} estimatesFilter - */ - public async getEstimates( - filterDTO: ISalesEstimatesFilter - ): Promise<{ + public async getEstimates(filterDTO: ISalesEstimatesFilter): Promise<{ salesEstimates: SaleEstimate[]; pagination: IPaginationMeta; filterMeta: IFilterMeta; @@ -34,13 +33,14 @@ export class GetSaleEstimatesService { // Dynamic list service. const dynamicFilter = await this.dynamicListService.dynamicList( SaleEstimate, - filter + filter, ); - const { results, pagination } = await this.saleEstimateModel.query() + const { results, pagination } = await this.saleEstimateModel() + .query() .onBuild((builder) => { builder.withGraphFetched('customer'); builder.withGraphFetched('entries'); - builder.withGraphFetched('entries.item'); + builder.withGraphFetched('entries.item'); dynamicFilter.buildQuery()(builder); filterDTO?.filterQuery && filterDTO?.filterQuery(builder); @@ -49,7 +49,7 @@ export class GetSaleEstimatesService { const transformedEstimates = await this.transformer.transform( results, - new SaleEstimateTransfromer() + new SaleEstimateTransfromer(), ); return { salesEstimates: transformedEstimates, diff --git a/packages/server-nest/src/modules/SaleInvoices/SaleInvoice.types.ts b/packages/server-nest/src/modules/SaleInvoices/SaleInvoice.types.ts index 5878fd745..3859986f9 100644 --- a/packages/server-nest/src/modules/SaleInvoices/SaleInvoice.types.ts +++ b/packages/server-nest/src/modules/SaleInvoices/SaleInvoice.types.ts @@ -7,6 +7,7 @@ import { CommonMailOptions, CommonMailOptionsDTO, } from '../MailNotification/MailNotification.types'; +import { TenantJobPayload } from '@/interfaces/Tenant'; // import SaleInvoice from './models/SaleInvoice'; // import { SystemUser } from '../System/models/SystemUser'; // import { ISystemUser, IAccount, ITaxTransaction } from '@/interfaces'; @@ -323,8 +324,12 @@ export interface ISaleInvocieState { defaultTemplateId: number; } - export interface SaleInvoiceSendMailData { saleInvoiceId: number; messageOptions: SendInvoiceMailDTO; -} \ No newline at end of file +} + +export interface SendSaleInvoiceMailJobPayload extends TenantJobPayload { + messageOptions: any; + saleInvoiceId: number; +} diff --git a/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.controller.ts b/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.controller.ts index 273382cfb..76746811e 100644 --- a/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.controller.ts +++ b/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.controller.ts @@ -20,7 +20,13 @@ import { } from './SaleInvoice.types'; import { SaleInvoiceApplication } from './SaleInvoices.application'; import { PublicRoute } from '../Auth/Jwt.guard'; -import { ApiHeader, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { + ApiHeader, + ApiOperation, + ApiParam, + ApiResponse, + ApiTags, +} from '@nestjs/swagger'; @Controller('sale-invoices') @ApiTags('sale-invoices') diff --git a/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.module.ts b/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.module.ts index cfa8e6469..4aa6e2166 100644 --- a/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.module.ts +++ b/packages/server-nest/src/modules/SaleInvoices/SaleInvoices.module.ts @@ -99,7 +99,7 @@ import { SendSaleInvoiceQueue } from './constants'; GetSaleInvoicesService, GetSaleInvoiceMailState, SendSaleInvoiceMailCommon, - SendSaleInvoiceMailProcessor + SendSaleInvoiceMailProcessor, ], exports: [GetSaleInvoice], }) diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceDTOTransformer.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceDTOTransformer.service.ts index 56a7a7bb9..570a846f2 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceDTOTransformer.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceDTOTransformer.service.ts @@ -43,9 +43,7 @@ export class CommandSaleInvoiceDTOTransformer { private invoiceIncrement: SaleInvoiceIncrement, private taxDTOTransformer: ItemEntriesTaxTransactions, private brandingTemplatesTransformer: BrandingTemplateDTOTransformer, - private tenancyContext: TenancyContext, - - @Inject(SaleInvoice.name) private saleInvoiceModel: typeof SaleInvoice, + private tenancyContext: TenancyContext ) {} /** diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceValidators.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceValidators.service.ts index 31333f903..93d1e9e3b 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceValidators.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/CommandSaleInvoiceValidators.service.ts @@ -2,12 +2,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { SaleInvoice } from '../models/SaleInvoice'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ERRORS } from '../constants'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CommandSaleInvoiceValidators { constructor( @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -29,7 +30,7 @@ export class CommandSaleInvoiceValidators { invoiceNumber: string, notInvoiceId?: number, ) { - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .findOne('invoice_no', invoiceNumber) .onBuild((builder) => { @@ -71,7 +72,7 @@ export class CommandSaleInvoiceValidators { * @param {number} customerId - Customer id. */ public async validateCustomerHasNoInvoices(customerId: number) { - const invoices = await this.saleInvoiceModel + const invoices = await this.saleInvoiceModel() .query() .where('customer_id', customerId); diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/CreateSaleInvoice.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/CreateSaleInvoice.service.ts index 265e157af..e5f48c18a 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/CreateSaleInvoice.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/CreateSaleInvoice.service.ts @@ -15,6 +15,7 @@ import { SaleInvoice } from '../models/SaleInvoice'; import { SaleEstimate } from '@/modules/SaleEstimates/models/SaleEstimate'; import { Customer } from '@/modules/Customers/models/Customer'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateSaleInvoice { @@ -27,13 +28,13 @@ export class CreateSaleInvoice { private readonly uow: UnitOfWork, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, @Inject(SaleEstimate.name) - private readonly saleEstimateModel: typeof SaleEstimate, + private readonly saleEstimateModel: TenantModelProxy, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -50,14 +51,14 @@ export class CreateSaleInvoice { trx?: Knex.Transaction, ): Promise => { // Validate customer existance. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .findById(saleInvoiceDTO.customerId) .throwIfNotFound(); // Validate the from estimate id exists on the storage. if (saleInvoiceDTO.fromEstimateId) { - const fromEstimate = await this.saleEstimateModel + const fromEstimate = await this.saleEstimateModel() .query() .findById(saleInvoiceDTO.fromEstimateId) .throwIfNotFound(); @@ -94,7 +95,7 @@ export class CreateSaleInvoice { } as ISaleInvoiceCreatingPaylaod); // Create sale invoice graph to the storage. - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query(trx) .upsertGraph(saleInvoiceObj); @@ -122,9 +123,6 @@ export class CreateSaleInvoice { customer: Customer, saleInvoiceDTO: ISaleInvoiceCreateDTO, ) => { - return this.transformerDTO.transformDTOToModel( - customer, - saleInvoiceDTO, - ); + return this.transformerDTO.transformDTOToModel(customer, saleInvoiceDTO); }; } diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/DeleteSaleInvoice.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/DeleteSaleInvoice.service.ts index 9a7eed94a..57a3f600f 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/DeleteSaleInvoice.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/DeleteSaleInvoice.service.ts @@ -15,6 +15,7 @@ import { ERRORS } from '../constants'; import { events } from '@/common/events/events'; import { PaymentReceivedEntry } from '@/modules/PaymentReceived/models/PaymentReceivedEntry'; import { CreditNoteAppliedInvoice } from '@/modules/CreditNotesApplyInvoice/models/CreditNoteAppliedInvoice'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteSaleInvoice { @@ -24,13 +25,17 @@ export class DeleteSaleInvoice { private uow: UnitOfWork, @Inject(PaymentReceivedEntry.name) - private paymentReceivedEntryModel: typeof PaymentReceivedEntry, + private paymentReceivedEntryModel: TenantModelProxy< + typeof PaymentReceivedEntry + >, @Inject(CreditNoteAppliedInvoice.name) - private creditNoteAppliedInvoiceModel: typeof CreditNoteAppliedInvoice, + private creditNoteAppliedInvoiceModel: TenantModelProxy< + typeof CreditNoteAppliedInvoice + >, @Inject(SaleInvoice.name) - private saleInvoiceModel: typeof SaleInvoice, + private saleInvoiceModel: TenantModelProxy, ) {} /** @@ -39,7 +44,7 @@ export class DeleteSaleInvoice { */ private async validateInvoiceHasNoPaymentEntries(saleInvoiceId: number) { // Retrieve the sale invoice associated payment receive entries. - const entries = await this.paymentReceivedEntryModel + const entries = await this.paymentReceivedEntryModel() .query() .where('invoice_id', saleInvoiceId); @@ -57,7 +62,7 @@ export class DeleteSaleInvoice { public validateInvoiceHasNoAppliedToCredit = async ( invoiceId: number, ): Promise => { - const appliedTransactions = await this.creditNoteAppliedInvoiceModel + const appliedTransactions = await this.creditNoteAppliedInvoiceModel() .query() .where('invoiceId', invoiceId); @@ -75,7 +80,7 @@ export class DeleteSaleInvoice { public async deleteSaleInvoice(saleInvoiceId: number): Promise { // Retrieve the given sale invoice with associated entries // or throw not found error. - const oldSaleInvoice = await this.saleInvoiceModel + const oldSaleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId) .withGraphFetched('entries') diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/DeliverSaleInvoice.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/DeliverSaleInvoice.service.ts index 5e78dd0e4..19f4c53e6 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/DeliverSaleInvoice.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/DeliverSaleInvoice.service.ts @@ -12,6 +12,7 @@ import { events } from '@/common/events/events'; import { ERRORS } from '../constants'; import { SaleInvoice } from '../models/SaleInvoice'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeliverSaleInvoice { @@ -20,7 +21,8 @@ export class DeliverSaleInvoice { private uow: UnitOfWork, private validators: CommandSaleInvoiceValidators, - @Inject(SaleInvoice.name) private saleInvoiceModel: typeof SaleInvoice, + @Inject(SaleInvoice.name) + private saleInvoiceModel: TenantModelProxy, ) {} /** @@ -30,7 +32,7 @@ export class DeliverSaleInvoice { */ public async deliverSaleInvoice(saleInvoiceId: number): Promise { // Retrieve details of the given sale invoice id. - const oldSaleInvoice = await this.saleInvoiceModel + const oldSaleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId); @@ -51,7 +53,7 @@ export class DeliverSaleInvoice { } as ISaleInvoiceDeliveringPayload); // Record the delivered at on the storage. - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query(trx) .patchAndFetchById(saleInvoiceId, { deliveredAt: moment().toMySqlDateTime(), diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/EditSaleInvoice.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/EditSaleInvoice.service.ts index ea05a6a86..8be2c5b54 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/EditSaleInvoice.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/EditSaleInvoice.service.ts @@ -13,6 +13,7 @@ import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service'; import { events } from '@/common/events/events'; import { SaleInvoice } from '../models/SaleInvoice'; import { Customer } from '@/modules/Customers/models/Customer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditSaleInvoice { @@ -24,9 +25,10 @@ export class EditSaleInvoice { private readonly uow: UnitOfWork, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, - - @Inject(Customer.name) private readonly customerModel: typeof Customer, + private readonly saleInvoiceModel: TenantModelProxy, + + @Inject(Customer.name) + private readonly customerModel: TenantModelProxy, ) {} /** @@ -41,7 +43,7 @@ export class EditSaleInvoice { saleInvoiceDTO: ISaleInvoiceEditDTO, ): Promise { // Retrieve the sale invoice or throw not found service error. - const oldSaleInvoice = await this.saleInvoiceModel + const oldSaleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId) .withGraphJoined('entries'); @@ -50,7 +52,7 @@ export class EditSaleInvoice { this.validators.validateInvoiceExistance(oldSaleInvoice); // Validate customer existance. - const customer = await this.customerModel + const customer = await this.customerModel() .query() .findById(saleInvoiceDTO.customerId) .throwIfNotFound(); @@ -97,7 +99,7 @@ export class EditSaleInvoice { } as ISaleInvoiceEditingPayload); // Upsert the the invoice graph to the storage. - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .upsertGraphAndFetch({ id: saleInvoiceId, diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/GenerateInvoicePaymentLink.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/GenerateInvoicePaymentLink.service.ts index 15765852b..af78aa548 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/GenerateInvoicePaymentLink.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/GenerateInvoicePaymentLink.service.ts @@ -8,7 +8,7 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { events } from '@/common/events/events'; import { PaymentLink } from '@/modules/PaymentLinks/models/PaymentLink'; import { SaleInvoice } from '../models/SaleInvoice'; - +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GenerateShareLink { @@ -16,8 +16,12 @@ export class GenerateShareLink { private uow: UnitOfWork, private eventPublisher: EventEmitter2, private transformer: TransformerInjectable, - @Inject(SaleInvoice.name) private saleInvoiceModel: typeof SaleInvoice, - @Inject(PaymentLink.name) private paymentLinkModel: typeof PaymentLink, + + @Inject(SaleInvoice.name) + private saleInvoiceModel: TenantModelProxy, + + @Inject(PaymentLink.name) + private paymentLinkModel: TenantModelProxy, ) {} /** @@ -29,9 +33,10 @@ export class GenerateShareLink { async generatePaymentLink( saleInvoiceId: number, publicity: string = 'private', - expiryTime: string = '' + expiryTime: string = '', ) { - const foundInvoice = await this.saleInvoiceModel.query() + const foundInvoice = await this.saleInvoiceModel() + .query() .findById(saleInvoiceId) .throwIfNotFound(); @@ -47,9 +52,9 @@ export class GenerateShareLink { // Triggers `onPublicSharableLinkGenerating` event. await this.eventPublisher.emitAsync( events.saleInvoice.onPublicLinkGenerating, - { ...commonEventPayload, trx } + { ...commonEventPayload, trx }, ); - const paymentLink = await this.paymentLinkModel.query().insert({ + const paymentLink = await this.paymentLinkModel().query().insert({ linkId, publicity, resourceId: foundInvoice.id, @@ -62,11 +67,11 @@ export class GenerateShareLink { ...commonEventPayload, paymentLink, trx, - } + }, ); return this.transformer.transform( paymentLink, - new GeneratePaymentLinkTransformer() + new GeneratePaymentLinkTransformer(), ); }); } diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/SendInvoiceInvoiceMailCommon.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/SendInvoiceInvoiceMailCommon.service.ts index f79276a79..2a26a2a06 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/SendInvoiceInvoiceMailCommon.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/SendInvoiceInvoiceMailCommon.service.ts @@ -20,7 +20,7 @@ export class SendSaleInvoiceMailCommon { private generatePaymentLinkService: GenerateShareLink, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: () => typeof SaleInvoice, ) {} /** @@ -35,7 +35,7 @@ export class SendSaleInvoiceMailCommon { defaultSubject: string = DEFAULT_INVOICE_MAIL_SUBJECT, defaultMessage: string = DEFAULT_INVOICE_MAIL_CONTENT, ): Promise { - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .findById(invoiceId) .throwIfNotFound(); @@ -97,7 +97,7 @@ export class SendSaleInvoiceMailCommon { * @param {string} text - The given text. * @returns {Promise} */ - // @ts-nocheck + // @ts-nocheck public getInvoiceFormatterArgs = async ( invoiceId: number, ): Promise> => { diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/SendSaleInvoiceMail.ts b/packages/server-nest/src/modules/SaleInvoices/commands/SendSaleInvoiceMail.ts index 9ae608b99..b5fee249b 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/SendSaleInvoiceMail.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/SendSaleInvoiceMail.ts @@ -9,11 +9,13 @@ import { mergeAndValidateMailOptions } from '@/modules/MailNotification/utils'; import { SaleInvoiceMailOptions, SendInvoiceMailDTO, + SendSaleInvoiceMailJobPayload, } from '../SaleInvoice.types'; import { ISaleInvoiceMailSend } from '../SaleInvoice.types'; import { Mail } from '@/modules/Mail/Mail'; import { MailTransporter } from '@/modules/Mail/MailTransporter.service'; import { SendSaleInvoiceMailJob, SendSaleInvoiceQueue } from '../constants'; +import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; @Injectable() export class SendSaleInvoiceMail { @@ -28,6 +30,8 @@ export class SendSaleInvoiceMail { private readonly invoiceMail: SendSaleInvoiceMailCommon, private readonly eventEmitter: EventEmitter2, private readonly mailTransporter: MailTransporter, + private readonly tenancyContect: TenancyContext, + @InjectQueue(SendSaleInvoiceQueue) private readonly sendInvoiceQueue: Queue, ) {} @@ -40,11 +44,21 @@ export class SendSaleInvoiceMail { saleInvoiceId: number, messageOptions: SendInvoiceMailDTO, ) { + const tenant = await this.tenancyContect.getTenant(); + const user = await this.tenancyContect.getSystemUser(); + + const organizationId = tenant.organizationId; + const userId = user.id; + const payload = { saleInvoiceId, messageOptions, - }; + userId, + organizationId, + } as SendSaleInvoiceMailJobPayload; + await this.sendInvoiceQueue.add(SendSaleInvoiceMailJob, payload); + // Triggers the event `onSaleInvoicePreMailSend`. await this.eventEmitter.emitAsync(events.saleInvoice.onPreMailSend, { saleInvoiceId, diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/WriteoffSaleInvoice.service.ts b/packages/server-nest/src/modules/SaleInvoices/commands/WriteoffSaleInvoice.service.ts index e728dac2a..8b4d08b6d 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/WriteoffSaleInvoice.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/WriteoffSaleInvoice.service.ts @@ -13,6 +13,7 @@ import { CommandSaleInvoiceValidators } from './CommandSaleInvoiceValidators.ser import { SaleInvoice } from '../models/SaleInvoice'; import { events } from '@/common/events/events'; import { ServiceError } from '../../Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class WriteoffSaleInvoice { @@ -28,7 +29,7 @@ export class WriteoffSaleInvoice { private readonly validators: CommandSaleInvoiceValidators, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -41,7 +42,7 @@ export class WriteoffSaleInvoice { saleInvoiceId: number, writeoffDTO: ISaleInvoiceWriteoffDTO, ): Promise => { - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId) .throwIfNotFound(); @@ -69,7 +70,7 @@ export class WriteoffSaleInvoice { eventPayload, ); // Mark the sale invoice as written-off. - const newSaleInvoice = await this.saleInvoiceModel + const newSaleInvoice = await this.saleInvoiceModel() .query(trx) .patch({ writtenoffExpenseAccountId: writeoffDTO.expenseAccountId, @@ -99,7 +100,7 @@ export class WriteoffSaleInvoice { // Validate the sale invoice existance. // Retrieve the sale invoice or throw not found service error. - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId); diff --git a/packages/server-nest/src/modules/SaleInvoices/commands/writeoff/SaleInvoiceWriteoffGLStorage.ts b/packages/server-nest/src/modules/SaleInvoices/commands/writeoff/SaleInvoiceWriteoffGLStorage.ts index 31eb964da..7ec288cea 100644 --- a/packages/server-nest/src/modules/SaleInvoices/commands/writeoff/SaleInvoiceWriteoffGLStorage.ts +++ b/packages/server-nest/src/modules/SaleInvoices/commands/writeoff/SaleInvoiceWriteoffGLStorage.ts @@ -5,6 +5,7 @@ import { AccountRepository } from '@/modules/Accounts/repositories/Account.repos import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service'; import { SaleInvoice } from '../../models/SaleInvoice'; import { SaleInvoiceWriteoffGL } from './SaleInvoiceWriteoffGL'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleInvoiceWriteoffGLStorage { @@ -18,9 +19,10 @@ export class SaleInvoiceWriteoffGLStorage { private readonly ledgerStorage: LedgerStorageService, private readonly accountRepository: AccountRepository, - @Inject(Account.name) private readonly accountModel: typeof Account, + @Inject(Account.name) + private readonly accountModel: TenantModelProxy, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -34,7 +36,7 @@ export class SaleInvoiceWriteoffGLStorage { trx?: Knex.Transaction, ) { // Retrieves the sale invoice. - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query(trx) .findById(saleInvoiceId) .withGraphFetched('writtenoffExpenseAccount'); @@ -64,7 +66,6 @@ export class SaleInvoiceWriteoffGLStorage { trx?: Knex.Transaction, ) { await this.revertInvoiceWriteoffEntries(saleInvoiceId, trx); - await this.writeInvoiceWriteoffEntries(saleInvoiceId, trx); } diff --git a/packages/server-nest/src/modules/SaleInvoices/ledger/InvoiceGLEntries.ts b/packages/server-nest/src/modules/SaleInvoices/ledger/InvoiceGLEntries.ts index e29d11aef..3d52c5963 100644 --- a/packages/server-nest/src/modules/SaleInvoices/ledger/InvoiceGLEntries.ts +++ b/packages/server-nest/src/modules/SaleInvoices/ledger/InvoiceGLEntries.ts @@ -4,6 +4,7 @@ import { LedgerStorageService } from '../../Ledger/LedgerStorage.service'; import { SaleInvoice } from '../models/SaleInvoice'; import { AccountRepository } from '../../Accounts/repositories/Account.repository'; import { InvoiceGL } from './InvoiceGL'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleInvoiceGLEntries { @@ -12,7 +13,7 @@ export class SaleInvoiceGLEntries { private readonly accountRepository: AccountRepository, @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -24,7 +25,7 @@ export class SaleInvoiceGLEntries { saleInvoiceId: number, trx?: Knex.Transaction, ) => { - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query(trx) .findById(saleInvoiceId) .withGraphFetched('entries.item'); diff --git a/packages/server-nest/src/modules/SaleInvoices/processors/SendSaleInvoiceMail.processor.ts b/packages/server-nest/src/modules/SaleInvoices/processors/SendSaleInvoiceMail.processor.ts index d12cfd6b1..69e366b6b 100644 --- a/packages/server-nest/src/modules/SaleInvoices/processors/SendSaleInvoiceMail.processor.ts +++ b/packages/server-nest/src/modules/SaleInvoices/processors/SendSaleInvoiceMail.processor.ts @@ -4,7 +4,8 @@ import { SendSaleInvoiceMailJob, SendSaleInvoiceQueue } from '../constants'; import { SendSaleInvoiceMail } from '../commands/SendSaleInvoiceMail'; import { Inject, Scope } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; -import { UseCls } from 'nestjs-cls'; +import { ClsService, UseCls } from 'nestjs-cls'; +import { SendSaleInvoiceMailJobPayload } from '../SaleInvoice.types'; @Processor({ name: SendSaleInvoiceQueue, @@ -14,12 +15,18 @@ export class SendSaleInvoiceMailProcessor { constructor( private readonly sendSaleInvoiceMail: SendSaleInvoiceMail, @Inject(REQUEST) private readonly request: Request, - @Inject(JOB_REF) private readonly jobRef: Job, + @Inject(JOB_REF) + private readonly jobRef: Job, + private readonly clsService: ClsService, ) {} @Process(SendSaleInvoiceMailJob) async handleSendInvoice() { - const { messageOptions, saleInvoiceId } = this.jobRef.data; + const { messageOptions, saleInvoiceId, organizationId, userId } = + this.jobRef.data; + + this.clsService.set('organizationId', organizationId); + this.clsService.set('userId', userId); try { await this.sendSaleInvoiceMail.sendMail(saleInvoiceId, messageOptions); diff --git a/packages/server-nest/src/modules/SaleInvoices/queries/GetInvoicePayments.service.ts b/packages/server-nest/src/modules/SaleInvoices/queries/GetInvoicePayments.service.ts index 267a42901..f9e6895ac 100644 --- a/packages/server-nest/src/modules/SaleInvoices/queries/GetInvoicePayments.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/queries/GetInvoicePayments.service.ts @@ -2,6 +2,7 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { InvoicePaymentTransactionTransformer } from './InvoicePaymentTransaction.transformer'; import { Inject, Injectable } from '@nestjs/common'; import { PaymentReceivedEntry } from '@/modules/PaymentReceived/models/PaymentReceivedEntry'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetInvoicePaymentsService { @@ -9,7 +10,9 @@ export class GetInvoicePaymentsService { private readonly transformer: TransformerInjectable, @Inject(PaymentReceivedEntry.name) - private readonly paymentReceivedEntryModel: typeof PaymentReceivedEntry, + private readonly paymentReceivedEntryModel: TenantModelProxy< + typeof PaymentReceivedEntry + >, ) {} /** @@ -18,7 +21,7 @@ export class GetInvoicePaymentsService { * @param {number} invoiceId - Invoice id. */ public getInvoicePayments = async (invoiceId: number) => { - const paymentsEntries = await this.paymentReceivedEntryModel + const paymentsEntries = await this.paymentReceivedEntryModel() .query() .where('invoiceId', invoiceId) .withGraphJoined('payment.depositAccount') diff --git a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoice.service.ts b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoice.service.ts index f19093f38..31a71d073 100644 --- a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoice.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoice.service.ts @@ -5,6 +5,7 @@ import { SaleInvoice } from '../models/SaleInvoice'; import { SaleInvoiceTransformer } from './SaleInvoice.transformer'; import { CommandSaleInvoiceValidators } from '../commands/CommandSaleInvoiceValidators.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleInvoice { @@ -14,7 +15,7 @@ export class GetSaleInvoice { private eventPublisher: EventEmitter2, @Inject(SaleInvoice.name) - private saleInvoiceModel: typeof SaleInvoice, + private saleInvoiceModel: TenantModelProxy, ) {} /** @@ -24,7 +25,7 @@ export class GetSaleInvoice { * @return {Promise} */ public async getSaleInvoice(saleInvoiceId: number): Promise { - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId) .withGraphFetched('entries.item') diff --git a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceMailState.service.ts b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceMailState.service.ts index 4b84d86ea..8d50eb6f8 100644 --- a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceMailState.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceMailState.service.ts @@ -4,6 +4,7 @@ import { GetSaleInvoiceMailStateTransformer } from './GetSaleInvoiceMailState.tr import { SendSaleInvoiceMailCommon } from '../commands/SendInvoiceInvoiceMailCommon.service'; import { SaleInvoice } from '../models/SaleInvoice'; import { SaleInvoiceMailState } from '../SaleInvoice.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleInvoiceMailState { @@ -12,7 +13,7 @@ export class GetSaleInvoiceMailState { private invoiceMail: SendSaleInvoiceMailCommon, @Inject(SaleInvoice.name) - private saleInvoiceModel: typeof SaleInvoice, + private saleInvoiceModel: TenantModelProxy, ) {} /** @@ -24,7 +25,7 @@ export class GetSaleInvoiceMailState { public async getInvoiceMailState( saleInvoiceId: number, ): Promise { - const saleInvoice = await this.saleInvoiceModel + const saleInvoice = await this.saleInvoiceModel() .query() .findById(saleInvoiceId) .withGraphFetched('customer') diff --git a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceState.service.ts b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceState.service.ts index 548c52638..fe9b1734c 100644 --- a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceState.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoiceState.service.ts @@ -1,12 +1,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { ISaleInvocieState } from '../SaleInvoice.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleInvoiceState { constructor( @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -14,7 +15,7 @@ export class GetSaleInvoiceState { * @return {Promise} */ public async getSaleInvoiceState(): Promise { - const defaultPdfTemplate = await this.pdfTemplateModel + const defaultPdfTemplate = await this.pdfTemplateModel() .query() .findOne({ resource: 'SaleInvoice' }) .modify('default'); diff --git a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoicesPayable.service.ts b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoicesPayable.service.ts index 7dc030704..3e539ea31 100644 --- a/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoicesPayable.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/queries/GetSaleInvoicesPayable.service.ts @@ -1,11 +1,12 @@ import { Injectable, Inject } from '@nestjs/common'; import { SaleInvoice } from '../models/SaleInvoice'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleInvoicesPayable { constructor( @Inject(SaleInvoice.name) - private readonly saleInvoiceModel: typeof SaleInvoice, + private readonly saleInvoiceModel: TenantModelProxy, ) {} /** @@ -15,7 +16,7 @@ export class GetSaleInvoicesPayable { public async getPayableInvoices( customerId?: number, ): Promise> { - const salesInvoices = await this.saleInvoiceModel + const salesInvoices = await this.saleInvoiceModel() .query() .onBuild((query) => { query.modify('dueInvoices'); diff --git a/packages/server-nest/src/modules/SaleInvoices/queries/SaleInvoicePdf.service.ts b/packages/server-nest/src/modules/SaleInvoices/queries/SaleInvoicePdf.service.ts index 183a0ca9d..ce5ea72f6 100644 --- a/packages/server-nest/src/modules/SaleInvoices/queries/SaleInvoicePdf.service.ts +++ b/packages/server-nest/src/modules/SaleInvoices/queries/SaleInvoicePdf.service.ts @@ -9,6 +9,7 @@ import { SaleInvoice } from '../models/SaleInvoice'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { events } from '@/common/events/events'; import { InvoicePdfTemplateAttributes } from '../SaleInvoice.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleInvoicePdf { @@ -19,10 +20,10 @@ export class SaleInvoicePdf { private eventPublisher: EventEmitter2, @Inject(SaleInvoice.name) - private saleInvoiceModel: typeof SaleInvoice, + private saleInvoiceModel: TenantModelProxy, @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -67,7 +68,7 @@ export class SaleInvoicePdf { * @returns {Promise} */ private async getInvoicePdfFilename(invoiceId: number): Promise { - const invoice = await this.saleInvoiceModel.query().findById(invoiceId); + const invoice = await this.saleInvoiceModel().query().findById(invoiceId); return `Invoice-${invoice.invoiceNo}`; } @@ -85,7 +86,7 @@ export class SaleInvoicePdf { const templateId = invoice.pdfTemplateId ?? ( - await this.pdfTemplateModel.query().findOne({ + await this.pdfTemplateModel().query().findOne({ resource: 'SaleInvoice', default: true, }) diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/CloseSaleReceipt.service.ts b/packages/server-nest/src/modules/SaleReceipts/commands/CloseSaleReceipt.service.ts index 99ced01f8..36990db5d 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/CloseSaleReceipt.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/CloseSaleReceipt.service.ts @@ -10,6 +10,7 @@ import { SaleReceipt } from '../models/SaleReceipt'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CloseSaleReceipt { @@ -17,7 +18,7 @@ export class CloseSaleReceipt { * @param {EventEmitter2} eventEmitter - Event emitter. * @param {UnitOfWork} uow - Unit of work. * @param {SaleReceiptValidators} validators - Sale receipt validators. - * @param {typeof SaleReceipt} saleReceiptModel - Sale receipt model. + * @param {TenantModelProxy} saleReceiptModel - Sale receipt model. */ constructor( private readonly eventEmitter: EventEmitter2, @@ -25,7 +26,7 @@ export class CloseSaleReceipt { private readonly validators: SaleReceiptValidators, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, ) {} /** @@ -35,7 +36,7 @@ export class CloseSaleReceipt { */ public async closeSaleReceipt(saleReceiptId: number): Promise { // Retrieve sale receipt or throw not found service error. - const oldSaleReceipt = await this.saleReceiptModel + const oldSaleReceipt = await this.saleReceiptModel() .query() .findById(saleReceiptId) .withGraphFetched('entries') @@ -53,12 +54,12 @@ export class CloseSaleReceipt { } as ISaleReceiptEventClosingPayload); // Mark the sale receipt as closed on the storage. - const saleReceipt = await this.saleReceiptModel + const saleReceipt = await this.saleReceiptModel() .query(trx) .patchAndFetchById(saleReceiptId, { closedAt: moment().toMySqlDateTime(), }); - + // Triggers `onSaleReceiptClosed` event. await this.eventEmitter.emitAsync(events.saleReceipt.onClosed, { saleReceiptId, diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/CreateSaleReceipt.service.ts b/packages/server-nest/src/modules/SaleReceipts/commands/CreateSaleReceipt.service.ts index d7775e9e5..155939c49 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/CreateSaleReceipt.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/CreateSaleReceipt.service.ts @@ -13,6 +13,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { SaleReceipt } from '../models/SaleReceipt'; import { Customer } from '@/modules/Customers/models/Customer'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateSaleReceipt { @@ -33,10 +34,10 @@ export class CreateSaleReceipt { private readonly validators: SaleReceiptValidators, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -50,7 +51,7 @@ export class CreateSaleReceipt { trx?: Knex.Transaction, ): Promise { // Retrieves the payment customer model. - const paymentCustomer = await this.customerModel + const paymentCustomer = await this.customerModel() .query() .findById(saleReceiptDTO.customerId) .throwIfNotFound(); @@ -87,9 +88,11 @@ export class CreateSaleReceipt { } as ISaleReceiptCreatingPayload); // Inserts the sale receipt graph to the storage. - const saleReceipt = await this.saleReceiptModel.query().upsertGraph({ - ...saleReceiptObj, - }); + const saleReceipt = await this.saleReceiptModel() + .query() + .upsertGraph({ + ...saleReceiptObj, + }); // Triggers `onSaleReceiptCreated` event. await this.eventEmitter.emitAsync(events.saleReceipt.onCreated, { diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/DeleteSaleReceipt.service.ts b/packages/server-nest/src/modules/SaleReceipts/commands/DeleteSaleReceipt.service.ts index 956b52b3f..ef89df19b 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/DeleteSaleReceipt.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/DeleteSaleReceipt.service.ts @@ -10,6 +10,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteSaleReceipt { @@ -19,10 +20,10 @@ export class DeleteSaleReceipt { private readonly validators: SaleReceiptValidators, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, @Inject(ItemEntry.name) - private readonly itemEntryModel: typeof ItemEntry, + private readonly itemEntryModel: TenantModelProxy, ) {} /** @@ -31,7 +32,7 @@ export class DeleteSaleReceipt { * @return {void} */ public async deleteSaleReceipt(saleReceiptId: number) { - const oldSaleReceipt = await this.saleReceiptModel + const oldSaleReceipt = await this.saleReceiptModel() .query() .findById(saleReceiptId) .withGraphFetched('entries'); @@ -46,14 +47,14 @@ export class DeleteSaleReceipt { oldSaleReceipt, } as ISaleReceiptDeletingPayload); - await this.itemEntryModel + await this.itemEntryModel() .query(trx) .where('reference_id', saleReceiptId) .where('reference_type', 'SaleReceipt') .delete(); // Delete the sale receipt transaction. - await this.saleReceiptModel + await this.saleReceiptModel() .query(trx) .where('id', saleReceiptId) .delete(); diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/EditSaleReceipt.service.ts b/packages/server-nest/src/modules/SaleReceipts/commands/EditSaleReceipt.service.ts index 878ddb8e3..4c52f4900 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/EditSaleReceipt.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/EditSaleReceipt.service.ts @@ -13,6 +13,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Contact } from '@/modules/Contacts/models/Contact'; import { events } from '@/common/events/events'; import { Customer } from '@/modules/Customers/models/Customer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditSaleReceipt { @@ -24,10 +25,10 @@ export class EditSaleReceipt { private readonly dtoTransformer: SaleReceiptDTOTransformer, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, @Inject(Customer.name) - private readonly customerModel: typeof Customer, + private readonly customerModel: TenantModelProxy, ) {} /** @@ -38,14 +39,14 @@ export class EditSaleReceipt { */ public async editSaleReceipt(saleReceiptId: number, saleReceiptDTO: any) { // Retrieve sale receipt or throw not found service error. - const oldSaleReceipt = await this.saleReceiptModel + const oldSaleReceipt = await this.saleReceiptModel() .query() .findById(saleReceiptId) .withGraphFetched('entries') .throwIfNotFound(); // Retrieves the payment customer model. - const paymentCustomer = await this.customerModel + const paymentCustomer = await this.customerModel() .query() .findById(saleReceiptDTO.customerId) .throwIfNotFound(); @@ -85,7 +86,7 @@ export class EditSaleReceipt { } as ISaleReceiptEditingPayload); // Upsert the receipt graph to the storage. - const saleReceipt = await this.saleReceiptModel + const saleReceipt = await this.saleReceiptModel() .query(trx) .upsertGraphAndFetch({ id: saleReceiptId, diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptDTOTransformer.service.ts b/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptDTOTransformer.service.ts index 6f13b1055..96c52e685 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptDTOTransformer.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptDTOTransformer.service.ts @@ -15,6 +15,7 @@ import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-ind import { SaleReceipt } from '../models/SaleReceipt'; import { ISaleReceiptDTO } from '../types/SaleReceipts.types'; import { Customer } from '@/modules/Customers/models/Customer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleReceiptDTOTransformer { @@ -36,7 +37,7 @@ export class SaleReceiptDTOTransformer { private readonly brandingTemplatesTransformer: BrandingTemplateDTOTransformer, @Inject(ItemEntry.name) - private readonly itemEntryModel: typeof ItemEntry, + private readonly itemEntryModel: TenantModelProxy, ) {} /** @@ -51,7 +52,7 @@ export class SaleReceiptDTOTransformer { oldSaleReceipt?: SaleReceipt, ): Promise { const amount = sumBy(saleReceiptDTO.entries, (e) => - this.itemEntryModel.calcAmount(e), + this.itemEntryModel().calcAmount(e), ); // Retrieve the next invoice number. const autoNextNumber = await this.receiptIncrement.getNextReceiptNumber(); diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptMailNotification.ts b/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptMailNotification.ts index 3bc47e857..e69574073 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptMailNotification.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptMailNotification.ts @@ -18,10 +18,12 @@ import { ISaleReceiptMailPresend, SaleReceiptMailOpts, SaleReceiptMailOptsDTO, + SaleReceiptSendMailPayload, } from '../types/SaleReceipts.types'; import { SaleReceipt } from '../models/SaleReceipt'; import { MailTransporter } from '@/modules/Mail/MailTransporter.service'; import { Mail } from '@/modules/Mail/Mail'; +import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; @Injectable() export class SaleReceiptMailNotification { @@ -38,6 +40,7 @@ export class SaleReceiptMailNotification { private readonly contactMailNotification: ContactMailNotification, private readonly eventEmitter: EventEmitter2, private readonly mailTransporter: MailTransporter, + private readonly tenancyContext: TenancyContext, @Inject(SaleReceipt.name) private readonly saleReceiptModel: typeof SaleReceipt, @@ -55,10 +58,19 @@ export class SaleReceiptMailNotification { saleReceiptId: number, messageOptions: SaleReceiptMailOptsDTO, ) { + const tenant = await this.tenancyContext.getTenant(); + const user = await this.tenancyContext.getSystemUser(); + + const organizationId = tenant.organizationId; + const userId = user.id; + const payload = { saleReceiptId, messageOpts: messageOptions, - }; + userId, + organizationId, + } as SaleReceiptSendMailPayload; + this.sendSaleReceiptMailProcess.add(SendSaleReceiptMailJob, { ...payload }); // Triggers the event `onSaleReceiptPreMailSend`. @@ -70,7 +82,7 @@ export class SaleReceiptMailNotification { /** * Retrieves the mail options of the given sale receipt. - * @param {number} saleReceiptId + * @param {number} saleReceiptId - Sale receipt id. * @returns {Promise} */ public async getMailOptions( @@ -97,7 +109,6 @@ export class SaleReceiptMailNotification { /** * Retrieves the formatted text of the given sale receipt. - * @param {number} tenantId - Tenant id. * @param {number} receiptId - Sale receipt id. * @param {string} text - The given text. * @returns {Promise} @@ -112,7 +123,6 @@ export class SaleReceiptMailNotification { /** * Formats the mail options of the given sale receipt. - * @param {number} tenantId * @param {number} receiptId * @param {SaleReceiptMailOpts} mailOptions * @returns {Promise} @@ -132,7 +142,6 @@ export class SaleReceiptMailNotification { /** * Retrieves the formatted mail options of the given sale receipt. - * @param {number} tenantId * @param {number} saleReceiptId * @param {SaleReceiptMailOptsDTO} messageOpts * @returns {Promise} diff --git a/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptValidators.service.ts b/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptValidators.service.ts index 58f0eafc3..d3a9ccc09 100644 --- a/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptValidators.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/commands/SaleReceiptValidators.service.ts @@ -4,16 +4,20 @@ import { SaleReceipt } from '../models/SaleReceipt'; import { Account } from '@/modules/Accounts/models/Account.model'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ACCOUNT_PARENT_TYPE } from '@/constants/accounts'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleReceiptValidators { /** - * @param {typeof SaleReceipt} saleReceiptModel - Sale receipt model. - * @param {typeof Account} accountModel - Account model. + * @param {TenantModelProxy} saleReceiptModel - Sale receipt model. + * @param {TenantModelProxy} accountModel - Account model. */ constructor( - @Inject(SaleReceipt.name) private saleReceiptModel: typeof SaleReceipt, - @Inject(Account.name) private accountModel: typeof Account, + @Inject(SaleReceipt.name) + private saleReceiptModel: TenantModelProxy, + + @Inject(Account.name) + private accountModel: TenantModelProxy, ) {} /** @@ -41,7 +45,9 @@ export class SaleReceiptValidators { * @param {number} accountId - Account id. */ public async validateReceiptDepositAccountExistence(accountId: number) { - const depositAccount = await this.accountModel.query().findById(accountId); + const depositAccount = await this.accountModel() + .query() + .findById(accountId); if (!depositAccount) { throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND); @@ -60,7 +66,7 @@ export class SaleReceiptValidators { receiptNumber: string, notReceiptId?: number, ) { - const saleReceipt = await this.saleReceiptModel + const saleReceipt = await this.saleReceiptModel() .query() .findOne('receipt_number', receiptNumber) .onBuild((builder) => { @@ -89,7 +95,7 @@ export class SaleReceiptValidators { * @param {number} customerId - Customer id. */ public async validateCustomerHasNoReceipts(customerId: number) { - const receipts = await this.saleReceiptModel + const receipts = await this.saleReceiptModel() .query() .where('customer_id', customerId); diff --git a/packages/server-nest/src/modules/SaleReceipts/ledger/SaleReceiptGLEntries.ts b/packages/server-nest/src/modules/SaleReceipts/ledger/SaleReceiptGLEntries.ts index 5626a5841..d7c0ef665 100644 --- a/packages/server-nest/src/modules/SaleReceipts/ledger/SaleReceiptGLEntries.ts +++ b/packages/server-nest/src/modules/SaleReceipts/ledger/SaleReceiptGLEntries.ts @@ -4,6 +4,7 @@ import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service'; import { SaleReceipt } from '../models/SaleReceipt'; import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository'; import { SaleReceiptGL } from './SaleReceiptGL'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleReceiptGLEntries { @@ -12,7 +13,7 @@ export class SaleReceiptGLEntries { private readonly accountRepository: AccountRepository, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, ) {} /** @@ -22,17 +23,16 @@ export class SaleReceiptGLEntries { */ public writeIncomeGLEntries = async ( saleReceiptId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise => { - const saleReceipt = await this.saleReceiptModel.query(trx) + const saleReceipt = await this.saleReceiptModel() + .query(trx) .findById(saleReceiptId) .withGraphFetched('entries.item'); // Find or create the discount expense account. - const discountAccount = await this.accountRepository.findOrCreateDiscountAccount( - {}, - trx - ); + const discountAccount = + await this.accountRepository.findOrCreateDiscountAccount({}, trx); // Find or create the other charges account. const otherChargesAccount = await this.accountRepository.findOrCreateOtherChargesAccount({}, trx); @@ -55,12 +55,12 @@ export class SaleReceiptGLEntries { */ public revertReceiptGLEntries = async ( saleReceiptId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise => { await this.ledgerStorage.deleteByReference( saleReceiptId, 'SaleReceipt', - trx + trx, ); }; @@ -72,7 +72,7 @@ export class SaleReceiptGLEntries { */ public rewriteReceiptGLEntries = async ( saleReceiptId: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise => { // Reverts the receipt GL entries. await this.revertReceiptGLEntries(saleReceiptId, trx); diff --git a/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipt.service.ts b/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipt.service.ts index ca58148ed..aa88d1d19 100644 --- a/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipt.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipt.service.ts @@ -3,14 +3,14 @@ import { SaleReceiptTransformer } from './SaleReceiptTransformer'; import { SaleReceiptValidators } from '../commands/SaleReceiptValidators.service'; import { SaleReceipt } from '../models/SaleReceipt'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleReceipt { constructor( @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, private readonly transformer: TransformerInjectable, - private readonly validators: SaleReceiptValidators, ) {} /** @@ -19,7 +19,7 @@ export class GetSaleReceipt { * @return {ISaleReceipt} */ public async getSaleReceipt(saleReceiptId: number) { - const saleReceipt = await this.saleReceiptModel + const saleReceipt = await this.saleReceiptModel() .query() .findById(saleReceiptId) .withGraphFetched('entries.item') diff --git a/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceiptState.service.ts b/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceiptState.service.ts index 0c65b06ea..b4800de09 100644 --- a/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceiptState.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceiptState.service.ts @@ -1,12 +1,13 @@ import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { Inject, Injectable } from '@nestjs/common'; import { ISaleReceiptState } from '../types/SaleReceipts.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetSaleReceiptState { constructor( @Inject(PdfTemplateModel.name) - private pdfTemplateModel: typeof PdfTemplateModel, + private pdfTemplateModel: TenantModelProxy, ) {} /** @@ -14,7 +15,7 @@ export class GetSaleReceiptState { * @return {Promise} */ public async getSaleReceiptState(): Promise { - const defaultPdfTemplate = await this.pdfTemplateModel + const defaultPdfTemplate = await this.pdfTemplateModel() .query() .findOne({ resource: 'SaleReceipt' }) .modify('default'); diff --git a/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipts.service.ts b/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipts.service.ts index c13772bed..4217413f4 100644 --- a/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipts.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/queries/GetSaleReceipts.service.ts @@ -6,6 +6,7 @@ import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model'; import { ISalesReceiptsFilter } from '../types/SaleReceipts.types'; import { SaleReceipt } from '../models/SaleReceipt'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; interface GetSaleReceiptsSettings { fetchEntriesGraph?: boolean; @@ -17,7 +18,7 @@ export class GetSaleReceiptsService { private readonly dynamicListService: DynamicListService, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, ) {} /** @@ -37,7 +38,7 @@ export class GetSaleReceiptsService { SaleReceipt, filter, ); - const { results, pagination } = await this.saleReceiptModel + const { results, pagination } = await this.saleReceiptModel() .query() .onBuild((builder) => { builder.withGraphFetched('depositAccount'); diff --git a/packages/server-nest/src/modules/SaleReceipts/queries/SaleReceiptsPdf.service.ts b/packages/server-nest/src/modules/SaleReceipts/queries/SaleReceiptsPdf.service.ts index 7d26c44a9..0ce8e126b 100644 --- a/packages/server-nest/src/modules/SaleReceipts/queries/SaleReceiptsPdf.service.ts +++ b/packages/server-nest/src/modules/SaleReceipts/queries/SaleReceiptsPdf.service.ts @@ -9,6 +9,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { ISaleReceiptBrandingTemplateAttributes } from '../types/SaleReceipts.types'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SaleReceiptsPdfService { @@ -29,10 +30,12 @@ export class SaleReceiptsPdfService { private readonly eventPublisher: EventEmitter2, @Inject(SaleReceipt.name) - private readonly saleReceiptModel: typeof SaleReceipt, + private readonly saleReceiptModel: TenantModelProxy, @Inject(PdfTemplateModel.name) - private readonly pdfTemplateModel: typeof PdfTemplateModel, + private readonly pdfTemplateModel: TenantModelProxy< + typeof PdfTemplateModel + >, ) {} /** @@ -71,7 +74,7 @@ export class SaleReceiptsPdfService { * @returns {Promise} */ public async getSaleReceiptFilename(receiptId: number): Promise { - const receipt = await this.saleReceiptModel.query().findById(receiptId); + const receipt = await this.saleReceiptModel().query().findById(receiptId); return `Receipt-${receipt.receiptNumber}`; } @@ -91,7 +94,7 @@ export class SaleReceiptsPdfService { const templateId = saleReceipt.pdfTemplateId ?? ( - await this.pdfTemplateModel.query().findOne({ + await this.pdfTemplateModel().query().findOne({ resource: 'SaleReceipt', default: true, }) diff --git a/packages/server-nest/src/modules/SaleReceipts/types/SaleReceipts.types.ts b/packages/server-nest/src/modules/SaleReceipts/types/SaleReceipts.types.ts index 4bd6b1bcb..4eabad688 100644 --- a/packages/server-nest/src/modules/SaleReceipts/types/SaleReceipts.types.ts +++ b/packages/server-nest/src/modules/SaleReceipts/types/SaleReceipts.types.ts @@ -5,6 +5,7 @@ import { AttachmentLinkDTO } from '../../Attachments/Attachments.types'; import { SaleReceipt } from '../models/SaleReceipt'; import { CommonMailOptionsDTO } from '@/modules/MailNotification/MailNotification.types'; import { CommonMailOptions } from '@/modules/MailNotification/MailNotification.types'; +import { TenantJobPayload } from '@/interfaces/Tenant'; export interface ISalesReceiptsFilter { filterQuery?: (query: any) => void; @@ -33,7 +34,6 @@ export interface ISaleReceiptSmsDetails { } export interface ISaleReceiptCreatingPayload { saleReceiptDTO: ISaleReceiptDTO; - // tenantId: number; trx: Knex.Transaction; } @@ -46,7 +46,6 @@ export interface ISaleReceiptCreatedPayload { } export interface ISaleReceiptEditedPayload { - // tenantId: number; oldSaleReceipt: SaleReceipt; saleReceipt: SaleReceipt; // saleReceiptId: number; @@ -55,20 +54,17 @@ export interface ISaleReceiptEditedPayload { } export interface ISaleReceiptEditingPayload { - // tenantId: number; oldSaleReceipt: SaleReceipt; saleReceiptDTO: ISaleReceiptDTO; trx: Knex.Transaction; } export interface ISaleReceiptEventClosedPayload { - // tenantId: number; saleReceiptId: number; saleReceipt: SaleReceipt; trx: Knex.Transaction; } export interface ISaleReceiptEventClosingPayload { - // tenantId: number; oldSaleReceipt: SaleReceipt; trx: Knex.Transaction; } @@ -167,3 +163,8 @@ export interface ISaleReceiptBrandingTemplateAttributes { export interface ISaleReceiptState { defaultTemplateId: number; } + +export interface SaleReceiptSendMailPayload extends TenantJobPayload { + messageOpts: SaleReceiptMailOptsDTO; + saleReceiptId: number; +} diff --git a/packages/server-nest/src/modules/StripePayment/CreateStripeAccountService.ts b/packages/server-nest/src/modules/StripePayment/CreateStripeAccountService.ts index da3c194b3..0b90e2432 100644 --- a/packages/server-nest/src/modules/StripePayment/CreateStripeAccountService.ts +++ b/packages/server-nest/src/modules/StripePayment/CreateStripeAccountService.ts @@ -4,6 +4,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { StripePaymentService } from './StripePaymentService'; import { events } from '@/common/events/events'; import { PaymentIntegration } from './models/PaymentIntegration.model'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class CreateStripeAccountService { @@ -12,7 +13,9 @@ export class CreateStripeAccountService { private readonly eventPublisher: EventEmitter2, @Inject(PaymentIntegration.name) - private readonly paymentIntegrationModel: typeof PaymentIntegration, + private readonly paymentIntegrationModel: TenantModelProxy< + typeof PaymentIntegration + >, ) {} /** @@ -31,7 +34,7 @@ export class CreateStripeAccountService { ...stripeAccountDTO, }; // Stores the details of the Stripe account. - await this.paymentIntegrationModel.query().insert({ + await this.paymentIntegrationModel().query().insert({ name: parsedStripeAccountDTO.name, accountId: stripeAccountId, active: false, // Active will turn true after onboarding. diff --git a/packages/server-nest/src/modules/StripePayment/ExchangeStripeOauthToken.ts b/packages/server-nest/src/modules/StripePayment/ExchangeStripeOauthToken.ts index 3a8d0c258..636b03352 100644 --- a/packages/server-nest/src/modules/StripePayment/ExchangeStripeOauthToken.ts +++ b/packages/server-nest/src/modules/StripePayment/ExchangeStripeOauthToken.ts @@ -6,6 +6,7 @@ import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { PaymentIntegration } from './models/PaymentIntegration.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ExchangeStripeOAuthTokenService { @@ -15,7 +16,9 @@ export class ExchangeStripeOAuthTokenService { private readonly uow: UnitOfWork, @Inject(PaymentIntegration.name) - private readonly paymentIntegrationModel: typeof PaymentIntegration, + private readonly paymentIntegrationModel: TenantModelProxy< + typeof PaymentIntegration + >, ) {} /** @@ -43,7 +46,7 @@ export class ExchangeStripeOAuthTokenService { return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Stores the details of the Stripe account. - const paymentIntegration = await this.paymentIntegrationModel + const paymentIntegration = await this.paymentIntegrationModel() .query(trx) .insert({ name: companyName, diff --git a/packages/server-nest/src/modules/StripePayment/subscribers/SeedStripeAccounts.ts b/packages/server-nest/src/modules/StripePayment/subscribers/SeedStripeAccounts.ts index 7e5b33f36..cebabc776 100644 --- a/packages/server-nest/src/modules/StripePayment/subscribers/SeedStripeAccounts.ts +++ b/packages/server-nest/src/modules/StripePayment/subscribers/SeedStripeAccounts.ts @@ -4,14 +4,21 @@ import { events } from '@/common/events/events'; import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository'; import { PaymentIntegration } from '../models/PaymentIntegration.model'; import { StripeOAuthCodeGrantedEventPayload } from '../types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SeedStripeAccountsOnOAuthGrantedSubscriber { + /** + * @param {AccountRepository} accountRepository + * @param {TenantModelProxy} paymentIntegrationModel + */ constructor( private readonly accountRepository: AccountRepository, @Inject(PaymentIntegration.name) - private readonly paymentIntegrationModel: typeof PaymentIntegration, + private readonly paymentIntegrationModel: TenantModelProxy< + typeof PaymentIntegration + >, ) {} /** @@ -29,7 +36,7 @@ export class SeedStripeAccountsOnOAuthGrantedSubscriber { const bankAccount = await this.accountRepository.findBySlug('bank-account'); // Patch the Stripe integration default settings. - await this.paymentIntegrationModel + await this.paymentIntegrationModel() .query(trx) .findById(paymentIntegrationId) .patch({ diff --git a/packages/server-nest/src/modules/StripePayment/subscribers/StripeWebhooksSubscriber.ts b/packages/server-nest/src/modules/StripePayment/subscribers/StripeWebhooksSubscriber.ts index 3c4323705..beadbcb73 100644 --- a/packages/server-nest/src/modules/StripePayment/subscribers/StripeWebhooksSubscriber.ts +++ b/packages/server-nest/src/modules/StripePayment/subscribers/StripeWebhooksSubscriber.ts @@ -9,6 +9,7 @@ import { OnEvent } from '@nestjs/event-emitter'; import { Inject, Injectable } from '@nestjs/common'; import { events } from '@/common/events/events'; import { PaymentIntegration } from '../models/PaymentIntegration.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class StripeWebhooksSubscriber { @@ -16,7 +17,9 @@ export class StripeWebhooksSubscriber { private readonly createPaymentReceiveStripePayment: CreatePaymentReceiveStripePayment, @Inject(PaymentIntegration.name) - private readonly paymentIntegrationModel: typeof PaymentIntegration, + private readonly paymentIntegrationModel: TenantModelProxy< + typeof PaymentIntegration + >, ) {} /** @@ -65,7 +68,7 @@ export class StripeWebhooksSubscriber { // Check if the account capabilities are active if (account.capabilities.card_payments === 'active') { // Marks the payment method integration as active. - await this.paymentIntegrationModel + await this.paymentIntegrationModel() .query() .findById(metadata?.paymentIntegrationId) .patch({ diff --git a/packages/server-nest/src/modules/Subscription/interceptors/Subscription.guard.ts b/packages/server-nest/src/modules/Subscription/interceptors/Subscription.guard.ts index 8d67ca8c2..bb31cb2ef 100644 --- a/packages/server-nest/src/modules/Subscription/interceptors/Subscription.guard.ts +++ b/packages/server-nest/src/modules/Subscription/interceptors/Subscription.guard.ts @@ -7,12 +7,15 @@ import { } from '@nestjs/common'; import { PlanSubscription } from '../models/PlanSubscription'; import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class SubscriptionGuard implements CanActivate { constructor( @Inject(PlanSubscription.name) - private readonly planSubscriptionModel: typeof PlanSubscription, + private readonly planSubscriptionModel: TenantModelProxy< + typeof PlanSubscription + >, private readonly tenancyContext: TenancyContext, ) {} @@ -27,7 +30,7 @@ export class SubscriptionGuard implements CanActivate { subscriptionSlug: string = 'main', // Default value ): Promise { const tenant = await this.tenancyContext.getTenant(); - const subscription = await this.planSubscriptionModel + const subscription = await this.planSubscriptionModel() .query() .findOne('slug', subscriptionSlug) .where('tenant_id', tenant.id); diff --git a/packages/server-nest/src/modules/System/models/TenantBaseModel.ts b/packages/server-nest/src/modules/System/models/TenantBaseModel.ts index 905ad8c4a..62c70626d 100644 --- a/packages/server-nest/src/modules/System/models/TenantBaseModel.ts +++ b/packages/server-nest/src/modules/System/models/TenantBaseModel.ts @@ -13,3 +13,5 @@ const ExtendedItem = R.pipe( )(BaseModel); export class TenantBaseModel extends ExtendedItem {} + +export type TenantModelProxy = () => T; diff --git a/packages/server-nest/src/modules/TaxRates/ItemEntriesTaxTransactions.service.ts b/packages/server-nest/src/modules/TaxRates/ItemEntriesTaxTransactions.service.ts index ed76c272c..e3112d6b2 100644 --- a/packages/server-nest/src/modules/TaxRates/ItemEntriesTaxTransactions.service.ts +++ b/packages/server-nest/src/modules/TaxRates/ItemEntriesTaxTransactions.service.ts @@ -2,12 +2,16 @@ import { Inject, Injectable } from '@nestjs/common'; import { keyBy, sumBy } from 'lodash'; import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry'; import { TaxRateModel } from './models/TaxRate.model'; +import { TenantModelProxy } from '../System/models/TenantBaseModel'; @Injectable() export class ItemEntriesTaxTransactions { constructor( - @Inject(ItemEntry.name) private itemEntryModel: typeof ItemEntry, - @Inject(TaxRateModel.name) private taxRateModel: typeof TaxRateModel, + @Inject(ItemEntry.name) + private itemEntryModel: TenantModelProxy, + + @Inject(TaxRateModel.name) + private taxRateModel: TenantModelProxy, ) {} /** @@ -17,7 +21,7 @@ export class ItemEntriesTaxTransactions { */ public assocTaxAmountWithheldFromEntries = (model: any) => { const entries = model.entries.map((entry) => - this.itemEntryModel.fromJson(entry), + this.itemEntryModel().fromJson(entry), ); const taxAmountWithheld = sumBy(entries, 'taxAmount'); @@ -25,47 +29,47 @@ export class ItemEntriesTaxTransactions { model.taxAmountWithheld = taxAmountWithheld; } return model; - } + }; /** * Associates tax rate id from tax code to entries. * @param {any} entries */ public assocTaxRateIdFromCodeToEntries = async (entries: any) => { - const entriesWithCode = entries.filter((entry) => entry.taxCode); - const taxCodes = entriesWithCode.map((entry) => entry.taxCode); - const foundTaxCodes = await this.taxRateModel - .query() - .whereIn('code', taxCodes); + const entriesWithCode = entries.filter((entry) => entry.taxCode); + const taxCodes = entriesWithCode.map((entry) => entry.taxCode); + const foundTaxCodes = await this.taxRateModel() + .query() + .whereIn('code', taxCodes); - const taxCodesMap = keyBy(foundTaxCodes, 'code'); + const taxCodesMap = keyBy(foundTaxCodes, 'code'); - return entries.map((entry) => { - if (entry.taxCode) { - entry.taxRateId = taxCodesMap[entry.taxCode]?.id; - } - return entry; - }); - }; + return entries.map((entry) => { + if (entry.taxCode) { + entry.taxRateId = taxCodesMap[entry.taxCode]?.id; + } + return entry; + }); + }; /** * Associates tax rate from tax id to entries. * @returns {Promise} */ public assocTaxRateFromTaxIdToEntries = async (entries: ItemEntry[]) => { - const entriesWithId = entries.filter((e) => e.taxRateId); - const taxRateIds = entriesWithId.map((e) => e.taxRateId); - const foundTaxes = await this.taxRateModel - .query() - .whereIn('id', taxRateIds); + const entriesWithId = entries.filter((e) => e.taxRateId); + const taxRateIds = entriesWithId.map((e) => e.taxRateId); + const foundTaxes = await this.taxRateModel() + .query() + .whereIn('id', taxRateIds); - const taxRatesMap = keyBy(foundTaxes, 'id'); + const taxRatesMap = keyBy(foundTaxes, 'id'); - return entries.map((entry) => { - if (entry.taxRateId) { - entry.taxRate = taxRatesMap[entry.taxRateId]?.rate; - } - return entry; - }); - }; + return entries.map((entry) => { + if (entry.taxRateId) { + entry.taxRate = taxRatesMap[entry.taxRateId]?.rate; + } + return entry; + }); + }; } diff --git a/packages/server-nest/src/modules/TaxRates/commands/ActivateTaxRate.service.ts b/packages/server-nest/src/modules/TaxRates/commands/ActivateTaxRate.service.ts index 7208c1d35..59e03755e 100644 --- a/packages/server-nest/src/modules/TaxRates/commands/ActivateTaxRate.service.ts +++ b/packages/server-nest/src/modules/TaxRates/commands/ActivateTaxRate.service.ts @@ -9,6 +9,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { TaxRateModel } from '../models/TaxRate.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ActivateTaxRateService { @@ -24,7 +25,7 @@ export class ActivateTaxRateService { private readonly validators: CommandTaxRatesValidators, @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, ) {} /** @@ -33,7 +34,7 @@ export class ActivateTaxRateService { * @returns {Promise} */ public async activateTaxRate(taxRateId: number) { - const oldTaxRate = await this.taxRateModel.query().findById(taxRateId); + const oldTaxRate = await this.taxRateModel().query().findById(taxRateId); // Validates the tax rate existance. this.validators.validateTaxRateExistance(oldTaxRate); @@ -48,7 +49,7 @@ export class ActivateTaxRateService { trx, } as ITaxRateActivatingPayload); - const taxRate = await this.taxRateModel + const taxRate = await this.taxRateModel() .query(trx) .findById(taxRateId) .patch({ active: true }); diff --git a/packages/server-nest/src/modules/TaxRates/commands/CommandTaxRatesValidator.service.ts b/packages/server-nest/src/modules/TaxRates/commands/CommandTaxRatesValidator.service.ts index a26da8992..3982728c9 100644 --- a/packages/server-nest/src/modules/TaxRates/commands/CommandTaxRatesValidator.service.ts +++ b/packages/server-nest/src/modules/TaxRates/commands/CommandTaxRatesValidator.service.ts @@ -6,15 +6,16 @@ import { TaxRateModel } from '../models/TaxRate.model'; import { Inject } from '@nestjs/common'; import { Injectable } from '@nestjs/common'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CommandTaxRatesValidators { /** - * @param {typeof TaxRateModel} taxRateModel - The tax rate model. + * @param {TenantModelProxy} taxRateModel - The tax rate model. */ constructor( @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, ) {} /** @@ -54,7 +55,7 @@ export class CommandTaxRatesValidators { * @param {Knex.Transaction} trx - */ public async validateTaxCodeUnique(taxCode: string, trx?: Knex.Transaction) { - const foundTaxCode = await this.taxRateModel + const foundTaxCode = await this.taxRateModel() .query(trx) .findOne({ code: taxCode }); diff --git a/packages/server-nest/src/modules/TaxRates/commands/CreateTaxRate.service.ts b/packages/server-nest/src/modules/TaxRates/commands/CreateTaxRate.service.ts index a06027b68..9b29fd6b7 100644 --- a/packages/server-nest/src/modules/TaxRates/commands/CreateTaxRate.service.ts +++ b/packages/server-nest/src/modules/TaxRates/commands/CreateTaxRate.service.ts @@ -10,6 +10,7 @@ import { TaxRateModel } from '../models/TaxRate.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateTaxRate { @@ -25,7 +26,7 @@ export class CreateTaxRate { private readonly validators: CommandTaxRatesValidators, @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, ) {} /** @@ -34,36 +35,32 @@ export class CreateTaxRate { */ public async createTaxRate( createTaxRateDTO: ICreateTaxRateDTO, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) { // Validates the tax code uniquiness. - await this.validators.validateTaxCodeUnique( - createTaxRateDTO.code, - trx - ); + await this.validators.validateTaxCodeUnique(createTaxRateDTO.code, trx); - return this.uow.withTransaction( - async (trx: Knex.Transaction) => { - // Triggers `onTaxRateCreating` event. - await this.eventEmitter.emitAsync(events.taxRates.onCreating, { - createTaxRateDTO, - trx, - } as ITaxRateCreatingPayload); + return this.uow.withTransaction(async (trx: Knex.Transaction) => { + // Triggers `onTaxRateCreating` event. + await this.eventEmitter.emitAsync(events.taxRates.onCreating, { + createTaxRateDTO, + trx, + } as ITaxRateCreatingPayload); - const taxRate = await this.taxRateModel.query(trx).insertAndFetch({ + const taxRate = await this.taxRateModel() + .query(trx) + .insertAndFetch({ ...createTaxRateDTO, }); - // Triggers `onTaxRateCreated` event. - await this.eventEmitter.emitAsync(events.taxRates.onCreated, { - createTaxRateDTO, - taxRate, - trx, - } as ITaxRateCreatedPayload); + // Triggers `onTaxRateCreated` event. + await this.eventEmitter.emitAsync(events.taxRates.onCreated, { + createTaxRateDTO, + taxRate, + trx, + } as ITaxRateCreatedPayload); - return taxRate; - }, - trx - ); + return taxRate; + }, trx); } } diff --git a/packages/server-nest/src/modules/TaxRates/commands/DeleteTaxRate.service.ts b/packages/server-nest/src/modules/TaxRates/commands/DeleteTaxRate.service.ts index 987e6d060..33c0107ac 100644 --- a/packages/server-nest/src/modules/TaxRates/commands/DeleteTaxRate.service.ts +++ b/packages/server-nest/src/modules/TaxRates/commands/DeleteTaxRate.service.ts @@ -9,6 +9,7 @@ import { TaxRateModel } from '../models/TaxRate.model'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteTaxRateService { @@ -24,7 +25,7 @@ export class DeleteTaxRateService { private readonly validators: CommandTaxRatesValidators, @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, ) {} /** @@ -33,7 +34,7 @@ export class DeleteTaxRateService { * @returns {Promise} */ public async deleteTaxRate(taxRateId: number): Promise { - const oldTaxRate = await this.taxRateModel.query().findById(taxRateId); + const oldTaxRate = await this.taxRateModel().query().findById(taxRateId); // Validates the tax rate existance. this.validators.validateTaxRateExistance(oldTaxRate); @@ -45,7 +46,7 @@ export class DeleteTaxRateService { trx, } as ITaxRateDeletingPayload); - await this.taxRateModel.query(trx).findById(taxRateId).delete(); + await this.taxRateModel().query(trx).findById(taxRateId).delete(); // Triggers `onTaxRateDeleted` event. await this.eventEmitter.emitAsync(events.taxRates.onDeleted, { diff --git a/packages/server-nest/src/modules/TaxRates/commands/EditTaxRate.service.ts b/packages/server-nest/src/modules/TaxRates/commands/EditTaxRate.service.ts index 98fda576b..336707765 100644 --- a/packages/server-nest/src/modules/TaxRates/commands/EditTaxRate.service.ts +++ b/packages/server-nest/src/modules/TaxRates/commands/EditTaxRate.service.ts @@ -11,6 +11,7 @@ import { TaxRateModel } from '../models/TaxRate.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; import { EventEmitter2 } from '@nestjs/event-emitter'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditTaxRateService { @@ -18,7 +19,7 @@ export class EditTaxRateService { * @param {EventEmitter2} eventEmitter - The event emitter. * @param {UnitOfWork} uow - The unit of work. * @param {CommandTaxRatesValidators} validators - The tax rates validators. - * @param {typeof TaxRateModel} taxRateModel - The tax rate model. + * @param {TenantModelProxy} taxRateModel - The tax rate model. */ constructor( private readonly eventEmitter: EventEmitter2, @@ -26,18 +27,18 @@ export class EditTaxRateService { private readonly validators: CommandTaxRatesValidators, @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, ) {} /** - * Detarmines whether the tax rate, name or code have been changed. + * Determines whether the tax rate, name or code have been changed. * @param {ITaxRate} taxRate * @param {IEditTaxRateDTO} editTaxRateDTO * @returns {boolean} */ private isTaxRateDTOChanged = ( taxRate: TaxRateModel, - editTaxRateDTO: IEditTaxRateDTO + editTaxRateDTO: IEditTaxRateDTO, ) => { return ( taxRate.rate !== editTaxRateDTO.rate || @@ -57,25 +58,29 @@ export class EditTaxRateService { private async editTaxRateOrCreate( oldTaxRate: TaxRateModel, editTaxRateDTO: IEditTaxRateDTO, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) { const isTaxDTOChanged = this.isTaxRateDTOChanged( oldTaxRate, - editTaxRateDTO + editTaxRateDTO, ); if (isTaxDTOChanged) { // Soft deleting the old tax rate. - await this.taxRateModel.query(trx).findById(oldTaxRate.id).delete(); + await this.taxRateModel().query(trx).findById(oldTaxRate.id).delete(); // Create a new tax rate with new edited data. - return this.taxRateModel.query(trx).insertAndFetch({ - ...omit(oldTaxRate, ['id']), - ...editTaxRateDTO, - }); + return this.taxRateModel() + .query(trx) + .insertAndFetch({ + ...omit(oldTaxRate, ['id']), + ...editTaxRateDTO, + }); } else { - return this.taxRateModel.query(trx).patchAndFetchById(oldTaxRate.id, { - ...editTaxRateDTO, - }); + return this.taxRateModel() + .query(trx) + .patchAndFetchById(oldTaxRate.id, { + ...editTaxRateDTO, + }); } } @@ -85,11 +90,8 @@ export class EditTaxRateService { * @param {IEditTaxRateDTO} editTaxRateDTO - The tax rate data to edit. * @returns {Promise} */ - public async editTaxRate( - taxRateId: number, - editTaxRateDTO: IEditTaxRateDTO - ) { - const oldTaxRate = await this.taxRateModel.query().findById(taxRateId); + public async editTaxRate(taxRateId: number, editTaxRateDTO: IEditTaxRateDTO) { + const oldTaxRate = await this.taxRateModel().query().findById(taxRateId); // Validates the tax rate existance. this.validators.validateTaxRateExistance(oldTaxRate); @@ -104,7 +106,7 @@ export class EditTaxRateService { const taxRate = await this.editTaxRateOrCreate( oldTaxRate, editTaxRateDTO, - trx + trx, ); // Triggers `onTaxRateEdited` event. await this.eventEmitter.emitAsync(events.taxRates.onEdited, { diff --git a/packages/server-nest/src/modules/TaxRates/commands/InactivateTaxRate.ts b/packages/server-nest/src/modules/TaxRates/commands/InactivateTaxRate.ts index f6f4bcff9..7e05aa02d 100644 --- a/packages/server-nest/src/modules/TaxRates/commands/InactivateTaxRate.ts +++ b/packages/server-nest/src/modules/TaxRates/commands/InactivateTaxRate.ts @@ -9,6 +9,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { TaxRateModel } from '../models/TaxRate.model'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class InactivateTaxRateService { @@ -24,7 +25,7 @@ export class InactivateTaxRateService { private readonly validators: CommandTaxRatesValidators, @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, ) {} /** @@ -33,7 +34,7 @@ export class InactivateTaxRateService { * @returns {Promise} */ public async inactivateTaxRate(taxRateId: number) { - const oldTaxRate = await this.taxRateModel.query().findById(taxRateId); + const oldTaxRate = await this.taxRateModel().query().findById(taxRateId); // Validates the tax rate existance. this.validators.validateTaxRateExistance(oldTaxRate); @@ -48,7 +49,7 @@ export class InactivateTaxRateService { trx, } as ITaxRateActivatingPayload); - const taxRate = await this.taxRateModel + const taxRate = await this.taxRateModel() .query(trx) .findById(taxRateId) .patch({ active: false }); diff --git a/packages/server-nest/src/modules/TaxRates/queries/GetTaxRate.service.ts b/packages/server-nest/src/modules/TaxRates/queries/GetTaxRate.service.ts index 666b69712..a39168216 100644 --- a/packages/server-nest/src/modules/TaxRates/queries/GetTaxRate.service.ts +++ b/packages/server-nest/src/modules/TaxRates/queries/GetTaxRate.service.ts @@ -3,6 +3,7 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { TaxRateTransformer } from './TaxRate.transformer'; import { TaxRateModel } from '../models/TaxRate.model'; import { CommandTaxRatesValidators } from '../commands/CommandTaxRatesValidator.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetTaxRateService { @@ -13,7 +14,7 @@ export class GetTaxRateService { */ constructor( @Inject(TaxRateModel.name) - private readonly taxRateModel: typeof TaxRateModel, + private readonly taxRateModel: TenantModelProxy, private readonly validators: CommandTaxRatesValidators, private readonly transformer: TransformerInjectable, ) {} @@ -24,15 +25,12 @@ export class GetTaxRateService { * @returns {Promise} */ public async getTaxRate(taxRateId: number) { - const taxRate = await this.taxRateModel.query().findById(taxRateId); + const taxRate = await this.taxRateModel().query().findById(taxRateId); // Validates the tax rate existance. this.validators.validateTaxRateExistance(taxRate); // Transforms the tax rate. - return this.transformer.transform( - taxRate, - new TaxRateTransformer() - ); + return this.transformer.transform(taxRate, new TaxRateTransformer()); } } diff --git a/packages/server-nest/src/modules/TaxRates/queries/GetTaxRates.service.ts b/packages/server-nest/src/modules/TaxRates/queries/GetTaxRates.service.ts index 72c22bfe9..842384660 100644 --- a/packages/server-nest/src/modules/TaxRates/queries/GetTaxRates.service.ts +++ b/packages/server-nest/src/modules/TaxRates/queries/GetTaxRates.service.ts @@ -2,12 +2,14 @@ import { Inject, Injectable } from '@nestjs/common'; import { TaxRateTransformer } from './TaxRate.transformer'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { TaxRateModel } from '../models/TaxRate.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetTaxRatesService { constructor( private transformer: TransformerInjectable, - @Inject(TaxRateModel.name) private taxRateModel: typeof TaxRateModel, + @Inject(TaxRateModel.name) + private taxRateModel: TenantModelProxy, ) {} /** @@ -16,7 +18,7 @@ export class GetTaxRatesService { */ public async getTaxRates() { // Retrieves the tax rates. - const taxRates = await this.taxRateModel.query().orderBy('name', 'ASC'); + const taxRates = await this.taxRateModel().query().orderBy('name', 'ASC'); // Transforms the tax rates. return this.transformer.transform(taxRates, new TaxRateTransformer()); diff --git a/packages/server-nest/src/modules/Tenancy/TenancyDB/TenancyDB.module.ts b/packages/server-nest/src/modules/Tenancy/TenancyDB/TenancyDB.module.ts index e752a0891..2bfd0a26a 100644 --- a/packages/server-nest/src/modules/Tenancy/TenancyDB/TenancyDB.module.ts +++ b/packages/server-nest/src/modules/Tenancy/TenancyDB/TenancyDB.module.ts @@ -1,20 +1,17 @@ import knex from 'knex'; -import { Global, Module, Scope } from '@nestjs/common'; -import { REQUEST } from '@nestjs/core'; +import { Global, Module } from '@nestjs/common'; +import { knexSnakeCaseMappers } from 'objection'; +import { ClsModule, ClsService } from 'nestjs-cls'; import { ConfigService } from '@nestjs/config'; import { TENANCY_DB_CONNECTION } from './TenancyDB.constants'; import { UnitOfWork } from './UnitOfWork.service'; -import { knexSnakeCaseMappers } from 'objection'; -import { ClsService } from 'nestjs-cls'; -const connectionFactory = { +export const TenancyDatabaseProxyProvider = ClsModule.forFeatureAsync({ provide: TENANCY_DB_CONNECTION, - scope: Scope.REQUEST, - useFactory: async ( - request: Request, - configService: ConfigService, - cls: ClsService, - ) => { + global: true, + strict: true, + inject: [ConfigService, ClsService], + useFactory: async (configService: ConfigService, cls: ClsService) => () => { const organizationId = cls.get('organizationId'); return knex({ @@ -36,12 +33,13 @@ const connectionFactory = { ...knexSnakeCaseMappers({ upperCase: true }), }); }, - inject: [REQUEST, ConfigService, ClsService], -}; + type: 'function', +}); @Global() @Module({ - providers: [connectionFactory, UnitOfWork], - exports: [TENANCY_DB_CONNECTION, UnitOfWork], + imports: [TenancyDatabaseProxyProvider], + providers: [UnitOfWork], + exports: [UnitOfWork], }) export class TenancyDatabaseModule {} diff --git a/packages/server-nest/src/modules/Tenancy/TenancyModels/Tenancy.module.ts b/packages/server-nest/src/modules/Tenancy/TenancyModels/Tenancy.module.ts index cadeff046..4d8444c69 100644 --- a/packages/server-nest/src/modules/Tenancy/TenancyModels/Tenancy.module.ts +++ b/packages/server-nest/src/modules/Tenancy/TenancyModels/Tenancy.module.ts @@ -1,7 +1,6 @@ import { Knex } from 'knex'; import { Global, Module, Scope } from '@nestjs/common'; import { TENANCY_DB_CONNECTION } from '../TenancyDB/TenancyDB.constants'; - import { Item } from '../../../modules/Items/models/Item'; import { Account } from '@/modules/Accounts/models/Account.model'; import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry'; @@ -38,8 +37,8 @@ import { RefundCreditNote } from '@/modules/CreditNoteRefunds/models/RefundCredi import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; import { RefundVendorCredit } from '@/modules/VendorCreditsRefund/models/RefundVendorCredit'; import { PaymentReceived } from '@/modules/PaymentReceived/models/PaymentReceived'; -import { BaseModel } from '@/models/Model'; import { Model } from 'objection'; +import { ClsModule } from 'nestjs-cls'; const models = [ Item, @@ -78,7 +77,7 @@ const models = [ VendorCreditAppliedBill, RefundVendorCredit, PaymentReceived, - PaymentReceivedEntry + PaymentReceivedEntry, ]; /** @@ -86,14 +85,17 @@ const models = [ * @param model The model class to register */ export function RegisterTenancyModel(model: typeof Model) { - return { + console.log(model.name); + + return ClsModule.forFeatureAsync({ provide: model.name, - inject: [TENANCY_DB_CONNECTION], - scope: Scope.REQUEST, - useFactory: async (tenantKnex: Knex) => { - return model.bindKnex(tenantKnex); - } - }; + inject: [TENANCY_DB_CONNECTION], + global: true, + useFactory: async (tenantKnex: () => Knex) => () => { + return model.bindKnex(tenantKnex()); + }, + type: 'function', + }); } // Register all models using the decorator @@ -101,7 +103,7 @@ const modelProviders = models.map((model) => RegisterTenancyModel(model)); @Global() @Module({ - providers: [...modelProviders], + imports: [...modelProviders], exports: [...modelProviders], }) export class TenancyModelsModule {} diff --git a/packages/server-nest/src/modules/VendorCredit/commands/CreateVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCredit/commands/CreateVendorCredit.service.ts index fa0ce26fb..9a89dd68a 100644 --- a/packages/server-nest/src/modules/VendorCredit/commands/CreateVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCredit/commands/CreateVendorCredit.service.ts @@ -12,6 +12,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { ItemsEntriesService } from '@/modules/Items/ItemsEntries.service'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { VendorCreditDTOTransformService } from './VendorCreditDTOTransform.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateVendorCreditService { @@ -29,9 +30,10 @@ export class CreateVendorCreditService { private readonly vendorCreditDTOTransformService: VendorCreditDTOTransformService, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, - @Inject(Vendor.name) private readonly vendorModel: typeof Vendor, + @Inject(Vendor.name) + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -48,7 +50,7 @@ export class CreateVendorCreditService { vendorCreditCreateDTO, }); // Retrieve the given vendor or throw not found service error. - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .findById(vendorCreditCreateDTO.vendorId) .throwIfNotFound(); @@ -72,7 +74,7 @@ export class CreateVendorCreditService { } as IVendorCreditCreatingPayload); // Saves the vendor credit graph. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query(trx) .upsertGraphAndFetch({ ...vendorCreditModel, diff --git a/packages/server-nest/src/modules/VendorCredit/commands/DeleteVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCredit/commands/DeleteVendorCredit.service.ts index d0ea79268..f50987cc4 100644 --- a/packages/server-nest/src/modules/VendorCredit/commands/DeleteVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCredit/commands/DeleteVendorCredit.service.ts @@ -13,6 +13,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { ServiceError } from '@/modules/Items/ServiceError'; import { RefundVendorCredit } from '../../VendorCreditsRefund/models/RefundVendorCredit'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteVendorCreditService { @@ -29,16 +30,20 @@ export class DeleteVendorCreditService { private uow: UnitOfWork, @Inject(ItemEntry.name) - private itemEntryModel: typeof ItemEntry, + private itemEntryModel: TenantModelProxy, @Inject(VendorCredit.name) - private vendorCreditModel: typeof VendorCredit, + private vendorCreditModel: TenantModelProxy, @Inject(RefundVendorCredit.name) - private refundVendorCreditModel: typeof RefundVendorCredit, + private refundVendorCreditModel: TenantModelProxy< + typeof RefundVendorCredit + >, @Inject(VendorCreditAppliedBill.name) - private vendorCreditAppliedBillModel: typeof VendorCreditAppliedBill, + private vendorCreditAppliedBillModel: TenantModelProxy< + typeof VendorCreditAppliedBill + >, ) {} /** @@ -50,7 +55,7 @@ export class DeleteVendorCreditService { trx?: Knex.Transaction, ) => { // Retrieve the old vendor credit. - const oldVendorCredit = await this.vendorCreditModel + const oldVendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); @@ -70,14 +75,17 @@ export class DeleteVendorCreditService { } as IVendorCreditDeletingPayload); // Deletes the associated credit note entries. - await this.itemEntryModel + await this.itemEntryModel() .query(trx) .where('reference_id', vendorCreditId) .where('reference_type', 'VendorCredit') .delete(); // Deletes the credit note transaction. - await this.vendorCreditModel.query(trx).findById(vendorCreditId).delete(); + await this.vendorCreditModel() + .query(trx) + .findById(vendorCreditId) + .delete(); // Triggers `onVendorCreditDeleted` event. await this.eventPublisher.emitAsync(events.vendorCredit.onDeleted, { @@ -95,7 +103,7 @@ export class DeleteVendorCreditService { private validateVendorCreditHasNoRefundTransactions = async ( vendorCreditId: number, ): Promise => { - const refundCredits = await this.refundVendorCreditModel + const refundCredits = await this.refundVendorCreditModel() .query() .where('vendorCreditId', vendorCreditId); if (refundCredits.length > 0) { @@ -110,7 +118,7 @@ export class DeleteVendorCreditService { private validateVendorCreditHasNoApplyBillsTransactions = async ( vendorCreditId: number, ): Promise => { - const appliedTransactions = await this.vendorCreditAppliedBillModel + const appliedTransactions = await this.vendorCreditAppliedBillModel() .query() .where('vendorCreditId', vendorCreditId); if (appliedTransactions.length > 0) { diff --git a/packages/server-nest/src/modules/VendorCredit/commands/EditVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCredit/commands/EditVendorCredit.service.ts index 4d8c3a6aa..5c6c9a49a 100644 --- a/packages/server-nest/src/modules/VendorCredit/commands/EditVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCredit/commands/EditVendorCredit.service.ts @@ -12,6 +12,7 @@ import { Contact } from '@/modules/Contacts/models/Contact'; import { events } from '@/common/events/events'; import { Knex } from 'knex'; import { VendorCreditDTOTransformService } from './VendorCreditDTOTransform.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditVendorCreditService { @@ -29,10 +30,10 @@ export class EditVendorCreditService { private readonly vendorCreditDTOTransform: VendorCreditDTOTransformService, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, @Inject(Contact.name) - private readonly contactModel: typeof Contact, + private readonly contactModel: TenantModelProxy, ) {} /** @@ -45,13 +46,13 @@ export class EditVendorCreditService { trx?: Knex.Transaction, ) => { // Retrieve the vendor credit or throw not found service error. - const oldVendorCredit = await this.vendorCreditModel + const oldVendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); // Validate customer existance. - const vendor = await this.contactModel + const vendor = await this.contactModel() .query() .modify('vendor') .findById(vendorCreditDTO.vendorId) @@ -88,7 +89,7 @@ export class EditVendorCreditService { } as IVendorCreditEditingPayload); // Saves the vendor credit graph to the storage. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query(trx) .upsertGraphAndFetch({ id: vendorCreditId, diff --git a/packages/server-nest/src/modules/VendorCredit/commands/OpenVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCredit/commands/OpenVendorCredit.service.ts index 338f98df4..dd0f7d012 100644 --- a/packages/server-nest/src/modules/VendorCredit/commands/OpenVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCredit/commands/OpenVendorCredit.service.ts @@ -11,6 +11,7 @@ import { VendorCredit } from '../models/VendorCredit'; import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; import { Knex } from 'knex'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class OpenVendorCreditService { @@ -23,7 +24,8 @@ export class OpenVendorCreditService { private eventPublisher: EventEmitter2, private uow: UnitOfWork, - @Inject(VendorCredit.name) private vendorCreditModel: typeof VendorCredit, + @Inject(VendorCredit.name) + private vendorCreditModel: TenantModelProxy, ) {} /** @@ -36,7 +38,7 @@ export class OpenVendorCreditService { trx?: Knex.Transaction, ): Promise => { // Retrieve the vendor credit or throw not found service error. - const oldVendorCredit = await this.vendorCreditModel + const oldVendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); @@ -64,7 +66,7 @@ export class OpenVendorCreditService { eventPayload as IVendorCreditOpeningPayload, ); // Saves the vendor credit graph to the storage. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query(trx) .findById(vendorCreditId) .updateAndFetchById(vendorCreditId, { diff --git a/packages/server-nest/src/modules/VendorCredit/commands/VendorCreditGLEntries.ts b/packages/server-nest/src/modules/VendorCredit/commands/VendorCreditGLEntries.ts index ed2359a60..8cd16b961 100644 --- a/packages/server-nest/src/modules/VendorCredit/commands/VendorCreditGLEntries.ts +++ b/packages/server-nest/src/modules/VendorCredit/commands/VendorCreditGLEntries.ts @@ -4,6 +4,7 @@ import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service'; import { Inject, Injectable } from '@nestjs/common'; import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository'; import { VendorCredit } from '../models/VendorCredit'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class VendorCreditGLEntries { @@ -12,7 +13,7 @@ export class VendorCreditGLEntries { private readonly accountRepository: AccountRepository, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -25,7 +26,7 @@ export class VendorCreditGLEntries { trx?: Knex.Transaction, ) => { // Vendor credit with entries items. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query(trx) .findById(vendorCreditId) .withGraphFetched('entries.item'); @@ -84,5 +85,5 @@ export class VendorCreditGLEntries { 'VendorCredit', trx, ); - }; + } } diff --git a/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredit.service.ts index dffb2be3f..610896fe9 100644 --- a/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredit.service.ts @@ -5,6 +5,7 @@ import { ERRORS } from '../constants'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { VendorCredit } from '../models/VendorCredit'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetVendorCreditService { @@ -14,7 +15,7 @@ export class GetVendorCreditService { */ constructor( @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, private readonly transformer: TransformerInjectable, ) {} @@ -25,7 +26,7 @@ export class GetVendorCreditService { */ public async getVendorCredit(vendorCreditId: number, trx?: Knex.Transaction) { // Retrieve the vendor credit model graph. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query(trx) .findById(vendorCreditId) .withGraphFetched('entries.item') diff --git a/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredits.service.ts b/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredits.service.ts index 4d1b7350e..cabae58a8 100644 --- a/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredits.service.ts +++ b/packages/server-nest/src/modules/VendorCredit/queries/GetVendorCredits.service.ts @@ -5,6 +5,7 @@ import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { VendorCredit } from '../models/VendorCredit'; import { IVendorCreditsQueryDTO } from '../types/VendorCredit.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetVendorCreditsService { @@ -13,7 +14,7 @@ export class GetVendorCreditsService { private readonly transformer: TransformerInjectable, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -40,7 +41,7 @@ export class GetVendorCreditsService { VendorCredit, filter, ); - const { results, pagination } = await this.vendorCreditModel + const { results, pagination } = await this.vendorCreditModel() .query() .onBuild((builder) => { builder.withGraphFetched('entries'); diff --git a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncBills.service.ts b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncBills.service.ts index bf1a37622..60a002ac6 100644 --- a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncBills.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncBills.service.ts @@ -3,12 +3,13 @@ import { Inject, Injectable } from '@nestjs/common'; import { Knex } from 'knex'; import { IVendorCreditAppliedBill } from '../types/VendorCreditApplyBills.types'; import { Bill } from '@/modules/Bills/models/Bill'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ApplyVendorCreditSyncBillsService { constructor( @Inject(Bill.name) - private readonly billModel: typeof Bill, + private readonly billModel: TenantModelProxy, ) {} /** @@ -23,7 +24,7 @@ export class ApplyVendorCreditSyncBillsService { await Bluebird.each( vendorCreditAppliedBills, (vendorCreditAppliedBill: IVendorCreditAppliedBill) => { - return this.billModel + return this.billModel() .query(trx) .where('id', vendorCreditAppliedBill.billId) .increment('creditedAmount', vendorCreditAppliedBill.amount); @@ -40,7 +41,7 @@ export class ApplyVendorCreditSyncBillsService { vendorCreditAppliedBill: IVendorCreditAppliedBill, trx?: Knex.Transaction, ) => { - await this.billModel + await this.billModel() .query(trx) .findById(vendorCreditAppliedBill.billId) .decrement('creditedAmount', vendorCreditAppliedBill.amount); diff --git a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncInvoiced.service.ts b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncInvoiced.service.ts index 51426795a..3cdc328fe 100644 --- a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncInvoiced.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditSyncInvoiced.service.ts @@ -1,15 +1,16 @@ import { Inject, Injectable } from '@nestjs/common'; import { Knex } from 'knex'; import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ApplyVendorCreditSyncInvoicedService { /** - * @param {typeof VendorCredit} vendorCreditModel - The vendor credit model. + * @param {TenantModelProxy} vendorCreditModel - The vendor credit model. */ constructor( @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -21,9 +22,10 @@ export class ApplyVendorCreditSyncInvoicedService { public incrementVendorCreditInvoicedAmount = async ( vendorCreditId: number, amount: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) => { - await this.vendorCreditModel.query(trx) + await this.vendorCreditModel() + .query(trx) .findById(vendorCreditId) .increment('invoicedAmount', amount); }; @@ -37,9 +39,10 @@ export class ApplyVendorCreditSyncInvoicedService { public decrementVendorCreditInvoicedAmount = async ( vendorCreditId: number, amount: number, - trx?: Knex.Transaction + trx?: Knex.Transaction, ) => { - await this.vendorCreditModel.query(trx) + await this.vendorCreditModel() + .query(trx) .findById(vendorCreditId) .decrement('invoicedAmount', amount); }; diff --git a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditToBills.service.ts b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditToBills.service.ts index 7660b8fb7..e0865b55b 100644 --- a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditToBills.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/ApplyVendorCreditToBills.service.ts @@ -16,6 +16,7 @@ import { Bill } from '@/modules/Bills/models/Bill'; import { ServiceError } from '@/modules/Items/ServiceError'; import { events } from '@/common/events/events'; import { VendorCreditDTOTransformService } from '@/modules/VendorCredit/commands/VendorCreditDTOTransform.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ApplyVendorCreditToBillsService { @@ -23,8 +24,8 @@ export class ApplyVendorCreditToBillsService { * @param {UnitOfWork} uow - The unit of work service. * @param {EventEmitter2} eventPublisher - The event emitter service. * @param {BillPaymentValidators} billPaymentValidators - The bill payment validators service. - * @param {typeof VendorCreditAppliedBill} vendorCreditAppliedBillModel - The vendor credit applied bill model. - * @param {typeof VendorCredit} vendorCreditModel - The vendor credit model. + * @param {TenantModelProxy} vendorCreditAppliedBillModel - The vendor credit applied bill model. + * @param {TenantModelProxy} vendorCreditModel - The vendor credit model. */ constructor( private readonly uow: UnitOfWork, @@ -33,10 +34,12 @@ export class ApplyVendorCreditToBillsService { private readonly vendorCreditDTOTransform: VendorCreditDTOTransformService, @Inject(VendorCreditAppliedBill.name) - private readonly vendorCreditAppliedBillModel: typeof VendorCreditAppliedBill, + private readonly vendorCreditAppliedBillModel: TenantModelProxy< + typeof VendorCreditAppliedBill + >, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -49,7 +52,7 @@ export class ApplyVendorCreditToBillsService { applyCreditToBillsDTO: IVendorCreditApplyToInvoicesDTO, ): Promise => { // Retrieves the vendor credit or throw not found service error. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); @@ -80,7 +83,7 @@ export class ApplyVendorCreditToBillsService { // Saves vendor credit applied to bills under unit-of-work envirement. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Inserts vendor credit applied to bills graph to the storage layer. - const vendorCreditAppliedBills = await this.vendorCreditAppliedBillModel + const vendorCreditAppliedBills = await this.vendorCreditAppliedBillModel() .query(trx) .insertGraph(vendorCreditAppliedModel.entries); diff --git a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/DeleteApplyVendorCreditToBill.service.ts b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/DeleteApplyVendorCreditToBill.service.ts index 85038b31a..fad07473d 100644 --- a/packages/server-nest/src/modules/VendorCreditsApplyBills/command/DeleteApplyVendorCreditToBill.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsApplyBills/command/DeleteApplyVendorCreditToBill.service.ts @@ -7,6 +7,7 @@ import { IVendorCreditApplyToBillDeletedPayload } from '../types/VendorCreditApp import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; import { ERRORS } from '../VendorCreditsApplyBills.constants'; import { VendorCreditAppliedBill } from '../models/VendorCreditAppliedBill'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteApplyVendorCreditToBillService { @@ -19,12 +20,14 @@ export class DeleteApplyVendorCreditToBillService { constructor( private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, - + @Inject(VendorCreditAppliedBill.name) - private readonly vendorCreditAppliedBillModel: typeof VendorCreditAppliedBill, + private readonly vendorCreditAppliedBillModel: TenantModelProxy< + typeof VendorCreditAppliedBill + >, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -33,7 +36,7 @@ export class DeleteApplyVendorCreditToBillService { * @returns {Promise} */ public async deleteApplyVendorCreditToBills(appliedCreditToBillId: number) { - const oldCreditAppliedToBill = await this.vendorCreditAppliedBillModel + const oldCreditAppliedToBill = await this.vendorCreditAppliedBillModel() .query() .findById(appliedCreditToBillId); @@ -41,7 +44,7 @@ export class DeleteApplyVendorCreditToBillService { throw new ServiceError(ERRORS.VENDOR_CREDIT_APPLY_TO_BILLS_NOT_FOUND); } // Retrieve the vendor credit or throw not found service error. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query() .findById(oldCreditAppliedToBill.vendorCreditId) .throwIfNotFound(); @@ -49,7 +52,7 @@ export class DeleteApplyVendorCreditToBillService { // Deletes vendor credit apply under unit-of-work environment. return this.uow.withTransaction(async (trx) => { // Delete vendor credit applied to bill transaction. - await this.vendorCreditAppliedBillModel + await this.vendorCreditAppliedBillModel() .query(trx) .findById(appliedCreditToBillId) .delete(); diff --git a/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetAppliedBillsToVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetAppliedBillsToVendorCredit.service.ts index f5ec53880..48e39fd23 100644 --- a/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetAppliedBillsToVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetAppliedBillsToVendorCredit.service.ts @@ -3,6 +3,7 @@ import { VendorCreditAppliedBillTransformer } from './VendorCreditAppliedBillTra import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { VendorCreditAppliedBill } from '@/modules/VendorCreditsApplyBills/models/VendorCreditAppliedBill'; import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetAppliedBillsToVendorCreditService { @@ -10,10 +11,12 @@ export class GetAppliedBillsToVendorCreditService { private readonly transformer: TransformerInjectable, @Inject(VendorCreditAppliedBill.name) - private readonly vendorCreditAppliedBillModel: typeof VendorCreditAppliedBill, + private readonly vendorCreditAppliedBillModel: TenantModelProxy< + typeof VendorCreditAppliedBill + >, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -22,12 +25,12 @@ export class GetAppliedBillsToVendorCreditService { * @returns */ public getAppliedBills = async (vendorCreditId: number) => { - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); - const appliedToBills = await this.vendorCreditAppliedBillModel + const appliedToBills = await this.vendorCreditAppliedBillModel() .query() .where('vendorCreditId', vendorCreditId) .withGraphFetched('bill') diff --git a/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetVendorCreditToApplyBills.service.ts b/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetVendorCreditToApplyBills.service.ts index c795d4f3c..e624c16ce 100644 --- a/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetVendorCreditToApplyBills.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsApplyBills/queries/GetVendorCreditToApplyBills.service.ts @@ -3,9 +3,10 @@ import { VendorCreditToApplyBillTransformer } from './VendorCreditToApplyBillTra import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; import { Bill } from '@/modules/Bills/models/Bill'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() -export class GetVendorCreditToApplyBills { +export class GetVendorCreditToApplyBills { /** * @param {TransformerService} transformerService - The transformer service. * @param {typeof Bill} billModel - The bill model. @@ -13,10 +14,11 @@ export class GetVendorCreditToApplyBills { */ constructor( private readonly transformerService: TransformerInjectable, - @Inject(Bill.name) private readonly billModel: typeof Bill, + @Inject(Bill.name) + private readonly billModel: TenantModelProxy, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -26,13 +28,13 @@ export class GetVendorCreditToApplyBills { */ public async getCreditToApplyBills(vendorCreditId: number) { // Retrieve vendor credit or throw not found service error. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); // Retrieve open bills associated to the given vendor. - const openBills = await this.billModel + const openBills = await this.billModel() .query() .where('vendor_id', vendorCredit.vendorId) .modify('dueBills') diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/commands/CreateRefundVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/commands/CreateRefundVendorCredit.service.ts index 55be7501a..14fab9ccc 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/commands/CreateRefundVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/commands/CreateRefundVendorCredit.service.ts @@ -16,6 +16,7 @@ import { IVendorCreditCreatePayload } from '@/modules/VendorCredit/types/VendorC import { events } from '@/common/events/events'; import { ServiceError } from '@/modules/Items/ServiceError'; import { ERRORS } from '../constants'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateRefundVendorCredit { @@ -25,13 +26,15 @@ export class CreateRefundVendorCredit { private readonly branchDTOTransform: BranchTransactionDTOTransformer, @Inject(RefundVendorCredit.name) - private readonly refundVendorCreditModel: typeof RefundVendorCredit, + private readonly refundVendorCreditModel: TenantModelProxy< + typeof RefundVendorCredit + >, @Inject(Account.name) - private readonly accountModel: typeof Account, + private readonly accountModel: TenantModelProxy, @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -45,13 +48,13 @@ export class CreateRefundVendorCredit { refundVendorCreditDTO: IRefundVendorCreditDTO, ): Promise => { // Retrieve the vendor credit or throw not found service error. - const vendorCredit = await this.vendorCreditModel + const vendorCredit = await this.vendorCreditModel() .query() .findById(vendorCreditId) .throwIfNotFound(); // Retrieve the deposit account or throw not found service error. - const depositAccount = await this.accountModel + const depositAccount = await this.accountModel() .query() .findById(refundVendorCreditDTO.depositAccountId) .throwIfNotFound(); @@ -88,7 +91,7 @@ export class CreateRefundVendorCredit { eventPayload as IRefundVendorCreditCreatingPayload, ); // Inserts refund vendor credit to the storage layer. - const refundVendorCredit = await this.refundVendorCreditModel + const refundVendorCredit = await this.refundVendorCreditModel() .query() .insertAndFetch(refundCreditObj); diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/commands/DeleteRefundVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/commands/DeleteRefundVendorCredit.service.ts index 67437f450..bccb2695d 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/commands/DeleteRefundVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/commands/DeleteRefundVendorCredit.service.ts @@ -10,6 +10,7 @@ import { RefundVendorCredit } from '../models/RefundVendorCredit'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteRefundVendorCreditService { @@ -23,7 +24,9 @@ export class DeleteRefundVendorCreditService { private readonly eventPublisher: EventEmitter2, @Inject(RefundVendorCredit.name) - private readonly refundVendorCreditModel: typeof RefundVendorCredit, + private readonly refundVendorCreditModel: TenantModelProxy< + typeof RefundVendorCredit + >, ) {} /** @@ -35,7 +38,7 @@ export class DeleteRefundVendorCreditService { refundCreditId: number, ): Promise { // Retrieve the old credit note or throw not found service error. - const oldRefundCredit = await this.refundVendorCreditModel + const oldRefundCredit = await this.refundVendorCreditModel() .query() .findById(refundCreditId) .throwIfNotFound(); @@ -60,7 +63,7 @@ export class DeleteRefundVendorCreditService { eventPayload, ); // Deletes the refund vendor credit graph from the storage. - await this.refundVendorCreditModel + await this.refundVendorCreditModel() .query(trx) .findById(refundCreditId) .delete(); diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncCreditRefundedAmount.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncCreditRefundedAmount.service.ts index 6618b358b..1002538cf 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncCreditRefundedAmount.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncCreditRefundedAmount.service.ts @@ -1,6 +1,7 @@ import { Transaction } from 'objection'; import { Inject, Injectable } from '@nestjs/common'; import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RefundSyncCreditRefundedAmount { @@ -9,7 +10,7 @@ export class RefundSyncCreditRefundedAmount { */ constructor( @Inject(VendorCredit.name) - private vendorCreditModel: typeof VendorCredit, + private vendorCreditModel: TenantModelProxy, ) {} /** @@ -23,7 +24,7 @@ export class RefundSyncCreditRefundedAmount { amount: number, trx?: Transaction, ): Promise => { - await this.vendorCreditModel + await this.vendorCreditModel() .query(trx) .findById(vendorCreditId) .increment('refundedAmount', amount); @@ -40,7 +41,7 @@ export class RefundSyncCreditRefundedAmount { amount: number, trx?: Transaction, ): Promise => { - await this.vendorCreditModel + await this.vendorCreditModel() .query(trx) .findById(vendorCreditId) .decrement('refundedAmount', amount); diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncVendorCreditBalance.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncVendorCreditBalance.service.ts index f138b22ec..188e0b6f0 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncVendorCreditBalance.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundSyncVendorCreditBalance.service.ts @@ -2,12 +2,13 @@ import { Knex } from 'knex'; import { Inject, Injectable } from '@nestjs/common'; import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; import { RefundVendorCredit } from '../models/RefundVendorCredit'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RefundSyncVendorCreditBalance { constructor( @Inject(VendorCredit.name) - private readonly vendorCreditModel: typeof VendorCredit, + private readonly vendorCreditModel: TenantModelProxy, ) {} /** @@ -17,9 +18,9 @@ export class RefundSyncVendorCreditBalance { */ public async incrementVendorCreditRefundAmount( refundVendorCredit: RefundVendorCredit, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { - await this.vendorCreditModel + await this.vendorCreditModel() .query(trx) .increment('refundedAmount', refundVendorCredit.amount); } @@ -31,9 +32,9 @@ export class RefundSyncVendorCreditBalance { */ public async decrementVendorCreditRefundAmount( refundVendorCredit: RefundVendorCredit, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { - await this.vendorCreditModel + await this.vendorCreditModel() .query(trx) .decrement('refundedAmount', refundVendorCredit.amount); } diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundVendorCredit.service.ts index 1db412eff..e49ed38e2 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/commands/RefundVendorCredit.service.ts @@ -4,18 +4,21 @@ import { Account } from '@/modules/Accounts/models/Account.model'; import { RefundVendorCredit } from '../models/RefundVendorCredit'; import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit'; import { ServiceError } from '@/modules/Items/ServiceError'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class RefundVendorCreditService { constructor( @Inject(RefundVendorCredit.name) - private refundVendorCreditModel: typeof RefundVendorCredit, + private refundVendorCreditModel: TenantModelProxy< + typeof RefundVendorCredit + >, @Inject(Account.name) - private accountModel: typeof Account, + private accountModel: TenantModelProxy, @Inject(VendorCredit.name) - private vendorCreditModel: typeof VendorCredit, + private vendorCreditModel: TenantModelProxy, ) {} /** @@ -26,7 +29,7 @@ export class RefundVendorCreditService { public getRefundVendorCreditOrThrowError = async ( refundVendorCreditId: number, ) => { - const refundCredit = await this.refundVendorCreditModel + const refundCredit = await this.refundVendorCreditModel() .query() .findById(refundVendorCreditId); if (!refundCredit) { diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredit.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredit.service.ts index 078a64f3f..e1c400437 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredit.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredit.service.ts @@ -5,18 +5,21 @@ import { RefundVendorCredit as RefundVendorCreditModel, } from '../models/RefundVendorCredit'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetRefundVendorCreditService { /** * @param {TransformerInjectable} transformer - Transformer injectable service. - * @param {typeof RefundVendorCreditModel} refundVendorCreditModel - Refund vendor credit model. + * @param {TenantModelProxy} refundVendorCreditModel - Refund vendor credit model. */ constructor( private readonly transformer: TransformerInjectable, @Inject(RefundVendorCredit.name) - private readonly refundVendorCreditModel: typeof RefundVendorCreditModel, + private readonly refundVendorCreditModel: TenantModelProxy< + typeof RefundVendorCreditModel + >, ) {} /** @@ -27,13 +30,13 @@ export class GetRefundVendorCreditService { public getRefundCreditTransaction = async ( refundId: number, ): Promise => { - await this.refundVendorCreditModel + await this.refundVendorCreditModel() .query() .findById(refundId) .throwIfNotFound(); // Retrieve refund transactions associated to the given vendor credit. - const refundVendorTransactions = await this.refundVendorCreditModel + const refundVendorTransactions = await this.refundVendorCreditModel() .query() .findById(refundId) .withGraphFetched('vendorCredit') diff --git a/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredits.service.ts b/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredits.service.ts index bdf1106d8..192e94761 100644 --- a/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredits.service.ts +++ b/packages/server-nest/src/modules/VendorCreditsRefund/queries/GetRefundVendorCredits.service.ts @@ -3,18 +3,21 @@ import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectab import { RefundVendorCreditTransformer } from '../commands/RefundVendorCreditTransformer'; import { IRefundVendorCreditPOJO } from '../types/VendorCreditRefund.types'; import { RefundVendorCredit } from '../models/RefundVendorCredit'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetRefundVendorCreditsService { /** * @param {TransformerInjectable} transformer - Transformer injectable service. - * @param {typeof RefundVendorCredit} refundVendorCreditModel - Refund vendor credit model. + * @param {TenantModelProxy} refundVendorCreditModel - Refund vendor credit model. */ constructor( private readonly transformer: TransformerInjectable, @Inject(RefundVendorCredit.name) - private readonly refundVendorCreditModel: typeof RefundVendorCredit, + private readonly refundVendorCreditModel: TenantModelProxy< + typeof RefundVendorCredit + >, ) {} /** @@ -26,13 +29,13 @@ export class GetRefundVendorCreditsService { vendorCreditId: number, ): Promise => { // Retrieve refund transactions associated to the given vendor credit. - const refundVendorTransactions = await this.refundVendorCreditModel + const refundVendorTransactions = await this.refundVendorCreditModel() .query() .where('vendorCreditId', vendorCreditId) .withGraphFetched('vendorCredit') .withGraphFetched('depositAccount'); - // Transformes refund vendor credit models to POJO objects. + // Transforms refund vendor credit models to POJO objects. return this.transformer.transform( refundVendorTransactions, new RefundVendorCreditTransformer(), diff --git a/packages/server-nest/src/modules/Vendors/commands/ActivateVendor.service.ts b/packages/server-nest/src/modules/Vendors/commands/ActivateVendor.service.ts index 9d4637847..179952762 100644 --- a/packages/server-nest/src/modules/Vendors/commands/ActivateVendor.service.ts +++ b/packages/server-nest/src/modules/Vendors/commands/ActivateVendor.service.ts @@ -6,6 +6,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { Vendor } from '../models/Vendor'; import { events } from '@/common/events/events'; import { IVendorActivatedPayload } from '../types/Vendors.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class ActivateVendorService { @@ -15,7 +16,7 @@ export class ActivateVendorService { private readonly validators: VendorValidators, @Inject(Vendor.name) - private readonly vendorModel: typeof Vendor, + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -25,7 +26,7 @@ export class ActivateVendorService { */ public async activateVendor(vendorId: number): Promise { // Retrieves the old vendor or throw not found error. - const oldVendor = await this.vendorModel + const oldVendor = await this.vendorModel() .query() .findById(vendorId) .throwIfNotFound(); @@ -42,7 +43,7 @@ export class ActivateVendorService { } as IVendorActivatedPayload); // Updates the vendor on the storage. - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query(trx) .updateAndFetchById(vendorId, { active: true, diff --git a/packages/server-nest/src/modules/Vendors/commands/CreateVendor.service.ts b/packages/server-nest/src/modules/Vendors/commands/CreateVendor.service.ts index 13fe2416b..88b76e152 100644 --- a/packages/server-nest/src/modules/Vendors/commands/CreateVendor.service.ts +++ b/packages/server-nest/src/modules/Vendors/commands/CreateVendor.service.ts @@ -10,6 +10,7 @@ import { IVendorNewDTO, } from '../types/Vendors.types'; import { CreateEditVendorDTOService } from './CreateEditVendorDTO'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateVendorService { @@ -25,7 +26,7 @@ export class CreateVendorService { private readonly transformDTO: CreateEditVendorDTOService, @Inject(Vendor.name) - private readonly vendorModel: typeof Vendor, + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -46,9 +47,11 @@ export class CreateVendorService { } as IVendorEventCreatingPayload); // Creates a new contact as vendor. - const vendor = await this.vendorModel.query(trx).insertAndFetch({ - ...vendorObject, - }); + const vendor = await this.vendorModel() + .query(trx) + .insertAndFetch({ + ...vendorObject, + }); // Triggers `onVendorCreated` event. await this.eventPublisher.emitAsync(events.vendors.onCreated, { vendorId: vendor.id, diff --git a/packages/server-nest/src/modules/Vendors/commands/DeleteVendor.service.ts b/packages/server-nest/src/modules/Vendors/commands/DeleteVendor.service.ts index 0fc84c78f..ea47ebe93 100644 --- a/packages/server-nest/src/modules/Vendors/commands/DeleteVendor.service.ts +++ b/packages/server-nest/src/modules/Vendors/commands/DeleteVendor.service.ts @@ -8,6 +8,7 @@ import { IVendorEventDeletedPayload, IVendorEventDeletingPayload, } from '../types/Vendors.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteVendorService { @@ -19,7 +20,7 @@ export class DeleteVendorService { constructor( private eventPublisher: EventEmitter2, private uow: UnitOfWork, - @Inject(Vendor.name) private vendorModel: typeof Vendor, + @Inject(Vendor.name) private vendorModel: TenantModelProxy, ) {} /** @@ -29,7 +30,7 @@ export class DeleteVendorService { */ public async deleteVendor(vendorId: number) { // Retrieves the old vendor or throw not found service error. - const oldVendor = await this.vendorModel + const oldVendor = await this.vendorModel() .query() .findById(vendorId) .throwIfNotFound(); @@ -46,7 +47,7 @@ export class DeleteVendorService { // Deletes vendor contact under unit-of-work. return this.uow.withTransaction(async (trx: Knex.Transaction) => { // Deletes the vendor contact from the storage. - await this.vendorModel.query(trx).findById(vendorId).delete(); + await this.vendorModel().query(trx).findById(vendorId).delete(); // Triggers `onVendorDeleted` event. await this.eventPublisher.emitAsync(events.vendors.onDeleted, { diff --git a/packages/server-nest/src/modules/Vendors/commands/EditOpeningBalanceVendor.service.ts b/packages/server-nest/src/modules/Vendors/commands/EditOpeningBalanceVendor.service.ts index 11166258d..41ccdad0d 100644 --- a/packages/server-nest/src/modules/Vendors/commands/EditOpeningBalanceVendor.service.ts +++ b/packages/server-nest/src/modules/Vendors/commands/EditOpeningBalanceVendor.service.ts @@ -9,6 +9,7 @@ import { import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Vendor } from '../models/Vendor'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditOpeningBalanceVendorService { @@ -22,7 +23,7 @@ export class EditOpeningBalanceVendorService { private readonly uow: UnitOfWork, @Inject(Vendor.name) - private readonly vendorModel: typeof Vendor, + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -36,7 +37,7 @@ export class EditOpeningBalanceVendorService { openingBalanceEditDTO: IVendorOpeningBalanceEditDTO, ) { // Retrieves the old vendor or throw not found error. - const oldVendor = await this.vendorModel + const oldVendor = await this.vendorModel() .query() .findById(vendorId) .throwIfNotFound(); @@ -54,7 +55,7 @@ export class EditOpeningBalanceVendorService { ); // Mutates the vendor on the storage. - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .patchAndFetchById(vendorId, { ...openingBalanceEditDTO, diff --git a/packages/server-nest/src/modules/Vendors/commands/EditVendor.service.ts b/packages/server-nest/src/modules/Vendors/commands/EditVendor.service.ts index 34767ab42..25312f193 100644 --- a/packages/server-nest/src/modules/Vendors/commands/EditVendor.service.ts +++ b/packages/server-nest/src/modules/Vendors/commands/EditVendor.service.ts @@ -10,6 +10,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { Vendor } from '../models/Vendor'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditVendorService { @@ -18,7 +19,8 @@ export class EditVendorService { private readonly uow: UnitOfWork, private readonly transformDTO: CreateEditVendorDTOService, - @Inject(Vendor.name) private readonly vendorModel: typeof Vendor, + @Inject(Vendor.name) + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -29,7 +31,7 @@ export class EditVendorService { */ public async editVendor(vendorId: number, vendorDTO: IVendorEditDTO) { // Retrieve the vendor or throw not found error. - const oldVendor = await this.vendorModel + const oldVendor = await this.vendorModel() .query() .findById(vendorId) .throwIfNotFound(); @@ -46,7 +48,7 @@ export class EditVendorService { } as IVendorEventEditingPayload); // Edits the vendor contact. - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .updateAndFetchById(vendorId, { ...vendorObj, diff --git a/packages/server-nest/src/modules/Vendors/queries/GetVendor.ts b/packages/server-nest/src/modules/Vendors/queries/GetVendor.ts index aa9b9a4d3..584ca67c6 100644 --- a/packages/server-nest/src/modules/Vendors/queries/GetVendor.ts +++ b/packages/server-nest/src/modules/Vendors/queries/GetVendor.ts @@ -2,12 +2,14 @@ import { Inject, Injectable } from '@nestjs/common'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { Vendor } from '../models/Vendor'; import { VendorTransfromer } from './VendorTransformer'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetVendorService { constructor( private readonly transformer: TransformerInjectable, - @Inject(Vendor.name) private readonly vendorModel: typeof Vendor, + @Inject(Vendor.name) + private readonly vendorModel: TenantModelProxy, ) {} /** @@ -15,7 +17,7 @@ export class GetVendorService { * @param {number} vendorId */ public async getVendor(vendorId: number) { - const vendor = await this.vendorModel + const vendor = await this.vendorModel() .query() .findById(vendorId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/Vendors/queries/GetVendors.service.ts b/packages/server-nest/src/modules/Vendors/queries/GetVendors.service.ts index a0f3fad44..c1f32c58a 100644 --- a/packages/server-nest/src/modules/Vendors/queries/GetVendors.service.ts +++ b/packages/server-nest/src/modules/Vendors/queries/GetVendors.service.ts @@ -5,6 +5,7 @@ import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; import { VendorTransfromer } from './VendorTransformer'; import { GetVendorsResponse, IVendorsFilter } from '../types/Vendors.types'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetVendorsService { @@ -18,7 +19,7 @@ export class GetVendorsService { private dynamicListService: DynamicListService, private transformer: TransformerInjectable, - @Inject(Vendor.name) private vendorModel: typeof Vendor, + @Inject(Vendor.name) private vendorModel: TenantModelProxy, ) {} /** @@ -34,11 +35,11 @@ export class GetVendorsService { // Dynamic list service. const dynamicList = await this.dynamicListService.dynamicList( - this.vendorModel, + this.vendorModel(), filter, ); // Vendors list. - const { results, pagination } = await this.vendorModel + const { results, pagination } = await this.vendorModel() .query() .onBuild((builder) => { dynamicList.buildQuery()(builder); diff --git a/packages/server-nest/src/modules/Warehouses/Items/GetItemWarehouses.ts b/packages/server-nest/src/modules/Warehouses/Items/GetItemWarehouses.ts index 0dde7c901..53763f149 100644 --- a/packages/server-nest/src/modules/Warehouses/Items/GetItemWarehouses.ts +++ b/packages/server-nest/src/modules/Warehouses/Items/GetItemWarehouses.ts @@ -3,15 +3,18 @@ import { Inject, Injectable } from '@nestjs/common'; import { ItemWarehouseQuantity } from '../models/ItemWarehouseQuantity'; import { Item } from '@/modules/Items/models/Item'; import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetItemWarehouses { constructor( @Inject(ItemWarehouseQuantity.name) - private readonly itemWarehouseQuantityModel: typeof ItemWarehouseQuantity, + private readonly itemWarehouseQuantityModel: TenantModelProxy< + typeof ItemWarehouseQuantity + >, @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProxy, private readonly transformer: TransformerInjectable, ) {} @@ -22,12 +25,12 @@ export class GetItemWarehouses { */ public getItemWarehouses = async (itemId: number) => { // Retrieves specific item or throw not found service error. - const item = await this.itemModel + const item = await this.itemModel() .query() .findById(itemId) .throwIfNotFound(); - const itemWarehouses = await this.itemWarehouseQuantityModel + const itemWarehouses = await this.itemWarehouseQuantityModel() .query() .where('itemId', itemId) .withGraphFetched('warehouse'); diff --git a/packages/server-nest/src/modules/Warehouses/Warehouses.module.ts b/packages/server-nest/src/modules/Warehouses/Warehouses.module.ts index bf44b13da..7164adffc 100644 --- a/packages/server-nest/src/modules/Warehouses/Warehouses.module.ts +++ b/packages/server-nest/src/modules/Warehouses/Warehouses.module.ts @@ -1,4 +1,5 @@ import { Module } from '@nestjs/common'; +import { I18nContext } from 'nestjs-i18n'; import { TenancyDatabaseModule } from '../Tenancy/TenancyDB/TenancyDB.module'; import { TenancyContext } from '../Tenancy/TenancyContext.service'; import { TransformerInjectable } from '../Transformer/TransformerInjectable.service'; @@ -15,7 +16,6 @@ import { WarehousesApplication } from './WarehousesApplication.service'; import { ActivateWarehousesService } from './commands/ActivateWarehouses.service'; import { CreateInitialWarehouse } from './commands/CreateInitialWarehouse.service'; import { WarehousesSettings } from './WarehousesSettings'; -import { I18nContext } from 'nestjs-i18n'; import { WarehouseTransactionDTOTransform } from './Integrations/WarehouseTransactionDTOTransform'; @Module({ @@ -37,7 +37,7 @@ import { WarehouseTransactionDTOTransform } from './Integrations/WarehouseTransa I18nContext, TenancyContext, TransformerInjectable, - WarehouseTransactionDTOTransform + WarehouseTransactionDTOTransform, ], exports: [WarehouseTransactionDTOTransform], }) diff --git a/packages/server-nest/src/modules/Warehouses/commands/CreateWarehouse.service.ts b/packages/server-nest/src/modules/Warehouses/commands/CreateWarehouse.service.ts index d057062eb..70107ae26 100644 --- a/packages/server-nest/src/modules/Warehouses/commands/CreateWarehouse.service.ts +++ b/packages/server-nest/src/modules/Warehouses/commands/CreateWarehouse.service.ts @@ -10,6 +10,7 @@ import { Warehouse } from '../models/Warehouse.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class CreateWarehouse { @@ -25,7 +26,7 @@ export class CreateWarehouse { private readonly validator: WarehouseValidator, @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, ) {} /** @@ -43,7 +44,7 @@ export class CreateWarehouse { * @param {ICreateWarehouseDTO} warehouseDTO */ public createWarehouse = async ( - warehouseDTO: ICreateWarehouseDTO + warehouseDTO: ICreateWarehouseDTO, ): Promise => { // Authorize warehouse before creating. await this.authorize(warehouseDTO); @@ -56,9 +57,11 @@ export class CreateWarehouse { } as IWarehouseCreatePayload); // Creates a new warehouse on the storage. - const warehouse = await this.warehouseModel.query(trx).insertAndFetch({ - ...warehouseDTO, - }); + const warehouse = await this.warehouseModel() + .query(trx) + .insertAndFetch({ + ...warehouseDTO, + }); // Triggers `onWarehouseCreated` event. await this.eventEmitter.emitAsync(events.warehouse.onCreated, { diff --git a/packages/server-nest/src/modules/Warehouses/commands/DeleteItemWarehousesQuantity.ts b/packages/server-nest/src/modules/Warehouses/commands/DeleteItemWarehousesQuantity.ts index 89f2611dc..ce989ab17 100644 --- a/packages/server-nest/src/modules/Warehouses/commands/DeleteItemWarehousesQuantity.ts +++ b/packages/server-nest/src/modules/Warehouses/commands/DeleteItemWarehousesQuantity.ts @@ -1,6 +1,7 @@ import { Knex } from 'knex'; import { Inject, Injectable } from '@nestjs/common'; import { ItemWarehouseQuantity } from '../models/ItemWarehouseQuantity'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteItemWarehousesQuantity { @@ -9,7 +10,9 @@ export class DeleteItemWarehousesQuantity { */ constructor( @Inject(ItemWarehouseQuantity.name) - private readonly itemWarehouseQuantityModel: typeof ItemWarehouseQuantity, + private readonly itemWarehouseQuantityModel: TenantModelProxy< + typeof ItemWarehouseQuantity + >, ) {} /** @@ -21,7 +24,7 @@ export class DeleteItemWarehousesQuantity { itemId: number, trx?: Knex.Transaction, ): Promise => { - await this.itemWarehouseQuantityModel + await this.itemWarehouseQuantityModel() .query(trx) .where('itemId', itemId) .delete(); diff --git a/packages/server-nest/src/modules/Warehouses/commands/DeleteWarehouse.service.ts b/packages/server-nest/src/modules/Warehouses/commands/DeleteWarehouse.service.ts index 8a03dc127..fc55c4189 100644 --- a/packages/server-nest/src/modules/Warehouses/commands/DeleteWarehouse.service.ts +++ b/packages/server-nest/src/modules/Warehouses/commands/DeleteWarehouse.service.ts @@ -10,6 +10,7 @@ import { ERRORS } from '../contants'; import { Warehouse } from '../models/Warehouse.model'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class DeleteWarehouseService { @@ -25,7 +26,7 @@ export class DeleteWarehouseService { private readonly validator: WarehouseValidator, @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, ) {} /** @@ -44,7 +45,7 @@ export class DeleteWarehouseService { */ public deleteWarehouse = async (warehouseId: number): Promise => { // Retrieves the old warehouse or throw not found service error. - const oldWarehouse = await this.warehouseModel + const oldWarehouse = await this.warehouseModel() .query() .findById(warehouseId) .throwIfNotFound(); @@ -69,7 +70,7 @@ export class DeleteWarehouseService { eventPayload, ); // Deletes the given warehouse from the storage. - await this.warehouseModel.query().findById(warehouseId).delete(); + await this.warehouseModel().query().findById(warehouseId).delete(); // Triggers `onWarehouseCreated`. await this.eventPublisher.emitAsync( diff --git a/packages/server-nest/src/modules/Warehouses/commands/EditWarehouse.service.ts b/packages/server-nest/src/modules/Warehouses/commands/EditWarehouse.service.ts index d8b06fd99..9227c36e7 100644 --- a/packages/server-nest/src/modules/Warehouses/commands/EditWarehouse.service.ts +++ b/packages/server-nest/src/modules/Warehouses/commands/EditWarehouse.service.ts @@ -6,6 +6,7 @@ import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { Warehouse } from '../models/Warehouse.model'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class EditWarehouse { @@ -21,7 +22,7 @@ export class EditWarehouse { private readonly validator: WarehouseValidator, @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, ) {} /** @@ -60,7 +61,7 @@ export class EditWarehouse { trx, }); // Updates the given branch on the storage. - const warehouse = await this.warehouseModel + const warehouse = await this.warehouseModel() .query() .patchAndFetchById(warehouseId, { ...warehouseDTO, diff --git a/packages/server-nest/src/modules/Warehouses/commands/WarehouseMarkPrimary.service.ts b/packages/server-nest/src/modules/Warehouses/commands/WarehouseMarkPrimary.service.ts index 269a9c7ac..9f9541887 100644 --- a/packages/server-nest/src/modules/Warehouses/commands/WarehouseMarkPrimary.service.ts +++ b/packages/server-nest/src/modules/Warehouses/commands/WarehouseMarkPrimary.service.ts @@ -8,16 +8,17 @@ import { Warehouse } from '../models/Warehouse.model'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service'; import { events } from '@/common/events/events'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class WarehouseMarkPrimary { constructor( @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, + private readonly uow: UnitOfWork, private readonly eventPublisher: EventEmitter2, - ) { - } + ) {} /** * Marks the given warehouse as primary. @@ -25,7 +26,7 @@ export class WarehouseMarkPrimary { * @returns {Promise} */ public async markAsPrimary(warehouseId: number) { - const oldWarehouse = await this.warehouseModel + const oldWarehouse = await this.warehouseModel() .query() .findById(warehouseId) .throwIfNotFound(); @@ -36,9 +37,9 @@ export class WarehouseMarkPrimary { trx, } as IWarehouseMarkAsPrimaryPayload); - await this.warehouseModel.query(trx).update({ primary: false }); + await this.warehouseModel().query(trx).update({ primary: false }); - const markedWarehouse = await this.warehouseModel + const markedWarehouse = await this.warehouseModel() .query(trx) .patchAndFetchById(warehouseId, { primary: true }); diff --git a/packages/server-nest/src/modules/Warehouses/commands/WarehouseValidator.service.ts b/packages/server-nest/src/modules/Warehouses/commands/WarehouseValidator.service.ts index b209162bc..a8db4fcb5 100644 --- a/packages/server-nest/src/modules/Warehouses/commands/WarehouseValidator.service.ts +++ b/packages/server-nest/src/modules/Warehouses/commands/WarehouseValidator.service.ts @@ -1,15 +1,15 @@ - import { ServiceError } from '@/modules/Items/ServiceError'; import { Inject } from '@nestjs/common'; import { Injectable } from '@nestjs/common'; import { ERRORS } from '../contants'; import { Warehouse } from '../models/Warehouse.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class WarehouseValidator { constructor( @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, ) {} /** @@ -17,7 +17,9 @@ export class WarehouseValidator { * @param {number} warehouseId */ public validateWarehouseNotOnlyWarehouse = async (warehouseId: number) => { - const warehouses = await this.warehouseModel.query().whereNot('id', warehouseId); + const warehouses = await this.warehouseModel() + .query() + .whereNot('id', warehouseId); if (warehouses.length === 0) { throw new ServiceError(ERRORS.COULD_NOT_DELETE_ONLY_WAERHOUSE); @@ -33,7 +35,8 @@ export class WarehouseValidator { code: string, exceptWarehouseId?: number, ) => { - const warehouse = await this.warehouseModel.query() + const warehouse = await this.warehouseModel() + .query() .onBuild((query) => { query.select(['id']); query.where('code', code); diff --git a/packages/server-nest/src/modules/Warehouses/queries/GetWarehouse.ts b/packages/server-nest/src/modules/Warehouses/queries/GetWarehouse.ts index 5b44910d1..7f1d79579 100644 --- a/packages/server-nest/src/modules/Warehouses/queries/GetWarehouse.ts +++ b/packages/server-nest/src/modules/Warehouses/queries/GetWarehouse.ts @@ -1,11 +1,12 @@ import { Inject, Injectable } from '@nestjs/common'; import { Warehouse } from '../models/Warehouse.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetWarehouse { constructor( @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, ) {} /** * Retrieves warehouse details. @@ -13,7 +14,7 @@ export class GetWarehouse { * @returns {Promise} */ public getWarehouse = async (warehouseId: number) => { - const warehouse = await this.warehouseModel + const warehouse = await this.warehouseModel() .query() .findById(warehouseId) .throwIfNotFound(); diff --git a/packages/server-nest/src/modules/Warehouses/queries/GetWarehouses.ts b/packages/server-nest/src/modules/Warehouses/queries/GetWarehouses.ts index 651b29d2c..4c2dfabe6 100644 --- a/packages/server-nest/src/modules/Warehouses/queries/GetWarehouses.ts +++ b/packages/server-nest/src/modules/Warehouses/queries/GetWarehouses.ts @@ -1,11 +1,12 @@ import { Inject, Injectable } from '@nestjs/common'; import { Warehouse } from '../models/Warehouse.model'; +import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; @Injectable() export class GetWarehouses { constructor( @Inject(Warehouse.name) - private readonly warehouseModel: typeof Warehouse, + private readonly warehouseModel: TenantModelProxy, ) {} /** @@ -13,7 +14,7 @@ export class GetWarehouses { * @returns */ public getWarehouses = async () => { - const warehouses = await this.warehouseModel + const warehouses = await this.warehouseModel() .query() .orderBy('name', 'DESC'); diff --git a/packages/server/src/services/Items/ItemsEntriesService.ts b/packages/server/src/services/Items/ItemsEntriesService.ts index e0f3c8745..89cdb62b7 100644 --- a/packages/server/src/services/Items/ItemsEntriesService.ts +++ b/packages/server/src/services/Items/ItemsEntriesService.ts @@ -17,10 +17,11 @@ const ERRORS = { export default class ItemsEntriesService { constructor( @Inject(Item.name) - private readonly itemModel: typeof Item, + private readonly itemModel: TenantModelProx, + @Inject(ItemEntry.name) - private readonly itemEntryModel: typeof ItemEntry, - private readonly itemRepository: any, // Replace 'any' with proper repository type + private readonly itemEntryModel: TenantModelProxy, + private readonly itemRepository: any // Replace 'any' with proper repository type ) {} /** @@ -33,11 +34,13 @@ export default class ItemsEntriesService { referenceType: string, referenceId: number ): Promise { - const itemsEntries = await this.itemEntryModel.query() + const itemsEntries = await this.itemEntryModel + .query() .where('reference_type', referenceType) .where('reference_id', referenceId); - const inventoryItems = await this.itemModel.query() + const inventoryItems = await this.itemModel + .query() .whereIn('id', map(itemsEntries, 'itemId')) .where('type', 'inventory'); @@ -60,7 +63,8 @@ export default class ItemsEntriesService { ): Promise { const entriesItemsIds = entries.map((e) => e.itemId); - const inventoryItems = await this.itemModel.query(trx) + const inventoryItems = await this.itemModel + .query(trx) .whereIn('id', entriesItemsIds) .where('type', 'inventory'); @@ -75,9 +79,7 @@ export default class ItemsEntriesService { * @async * @param {IItemEntryDTO[]} itemEntries - */ - public async validateItemsIdsExistance( - itemEntries: IItemEntryDTO[] - ) { + public async validateItemsIdsExistance(itemEntries: IItemEntryDTO[]) { const itemsIds = itemEntries.map((e) => e.itemId); const foundItems = await this.itemModel.query().whereIn('id', itemsIds); @@ -105,7 +107,8 @@ export default class ItemsEntriesService { .filter((e: IItemEntry) => e.id) .map((e: IItemEntry) => e.id); - const storedEntries = await this.itemEntryModel.query() + const storedEntries = await this.itemEntryModel + .query() .whereIn('reference_id', [referenceId]) .whereIn('reference_type', [referenceType]); @@ -125,7 +128,8 @@ export default class ItemsEntriesService { ) { const itemsIds = itemEntries.map((e: IItemEntryDTO) => e.itemId); - const purchasbleItems = await this.itemModel.query() + const purchasbleItems = await this.itemModel + .query() .where('purchasable', true) .whereIn('id', itemsIds); @@ -140,12 +144,11 @@ export default class ItemsEntriesService { /** * Validate the entries items that not sell-able. */ - public async validateNonSellableEntriesItems( - itemEntries: IItemEntryDTO[] - ) { + public async validateNonSellableEntriesItems(itemEntries: IItemEntryDTO[]) { const itemsIds = itemEntries.map((e: IItemEntryDTO) => e.itemId); - const sellableItems = await this.itemModel.query() + const sellableItems = await this.itemModel + .query() .where('sellable', true) .whereIn('id', itemsIds); @@ -189,9 +192,7 @@ export default class ItemsEntriesService { * Increment items quantity from the given items entries. * @param {IItemEntry[]} entries - Items entries. */ - public async incrementItemsEntries( - entries: IItemEntry[] - ): Promise { + public async incrementItemsEntries(entries: IItemEntry[]): Promise { return this.changeItemsQuantity(entries); } @@ -199,9 +200,7 @@ export default class ItemsEntriesService { * Decrement items quantity from the given items entries. * @param {IItemEntry[]} entries - Items entries. */ - public async decrementItemsQuantity( - entries: IItemEntry[] - ): Promise { + public async decrementItemsQuantity(entries: IItemEntry[]): Promise { return this.changeItemsQuantity( entries.map((entry) => ({ ...entry, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 392e37acd..964c2b8ec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -611,8 +611,8 @@ importers: specifier: ^3.11.3 version: 3.11.4 nestjs-cls: - specifier: ^4.4.1 - version: 4.4.1(@nestjs/common@10.4.7)(@nestjs/core@10.4.7)(reflect-metadata@0.2.2)(rxjs@7.8.1) + specifier: ^5.2.0 + version: 5.2.0(@nestjs/common@10.4.7)(@nestjs/core@10.4.7)(reflect-metadata@0.2.2)(rxjs@7.8.1) nestjs-i18n: specifier: ^10.4.9 version: 10.5.0(@nestjs/common@10.4.7)(@nestjs/core@10.4.7)(class-validator@0.14.1)(rxjs@7.8.1) @@ -25830,12 +25830,12 @@ packages: /nested-error-stacks@2.1.1: resolution: {integrity: sha512-9iN1ka/9zmX1ZvLV9ewJYEk9h7RyRRtqdK0woXcqohu8EWIerfPUjYJPg0ULy0UqP7cslmdGc8xKDJcojlKiaw==} - /nestjs-cls@4.4.1(@nestjs/common@10.4.7)(@nestjs/core@10.4.7)(reflect-metadata@0.2.2)(rxjs@7.8.1): - resolution: {integrity: sha512-4yhldwm/cJ02lQ8ZAdM8KQ7gMfjAc1z3fo5QAQgXNyN4N6X5So9BCwv+BTLRugDCkELUo3qtzQHnKhGYL/ftPg==} - engines: {node: '>=16'} + /nestjs-cls@5.2.0(@nestjs/common@10.4.7)(@nestjs/core@10.4.7)(reflect-metadata@0.2.2)(rxjs@7.8.1): + resolution: {integrity: sha512-xabZQ7aPHttZ5TwC4rEyYgsxm3/ArM+Dz4oJPWc5Q1p+jOp+UaDe37fKna6sIMeUmYpvZxMVtUKIhv7CfLxbOw==} + engines: {node: '>=18'} peerDependencies: - '@nestjs/common': '> 7.0.0 < 11' - '@nestjs/core': '> 7.0.0 < 11' + '@nestjs/common': '>= 10 < 12' + '@nestjs/core': '>= 10 < 12' reflect-metadata: '*' rxjs: '>= 7' dependencies: