fix: bugs bashing

- Added English translations for customer types in `customer.json`.
- Updated `Model.ts` to improve deletion logic by filtering dependent relations.
- Introduced `BillPaymentBillSyncSubscriber` to handle bill payment events.
- Enhanced `CreateBillPaymentService` and `EditBillPaymentService` to fetch entries after insertion/updating.
- Updated `SaleInvoiceCostGLEntries` to include item entry details in GL entries.
- Refactored various components in the webapp for consistency in naming conventions.
This commit is contained in:
Ahmed Bouhuolia
2026-01-04 01:24:10 +02:00
parent 987ad992a4
commit 0475ce136a
14 changed files with 167 additions and 32 deletions

View File

@@ -0,0 +1,5 @@
{
"type.business": "Business",
"type.individual": "Individual"
}

View File

@@ -48,14 +48,30 @@ export class PaginationQueryBuilder<
// No relations defined // No relations defined
return this.delete(); return this.delete();
} }
// Only check HasManyRelation and ManyToManyRelation relations, as BelongsToOneRelation are just
// foreign key references and shouldn't prevent deletion. Only dependent records should block deletion.
const dependentRelationNames = relationNames.filter((name) => {
const relation = relationMappings[name];
return relation && (
relation.relation === Model.HasManyRelation ||
relation.relation === Model.ManyToManyRelation
);
});
if (dependentRelationNames.length === 0) {
// No dependent relations defined, safe to delete
return this.delete();
}
const recordQuery = this.clone(); const recordQuery = this.clone();
relationNames.forEach((relationName: string) => { dependentRelationNames.forEach((relationName: string) => {
recordQuery.withGraphFetched(relationName); recordQuery.withGraphFetched(relationName);
}); });
const record = await recordQuery; const record = await recordQuery;
const hasRelations = relationNames.some((name) => { const hasRelations = dependentRelationNames.some((name) => {
const val = record[name]; const val = record[name];
return Array.isArray(val) ? val.length > 0 : val != null; return Array.isArray(val) ? val.length > 0 : val != null;
}); });

View File

@@ -14,6 +14,7 @@ import { BranchesSettingsService } from '../Branches/BranchesSettings';
import { BillPaymentsController } from './BillPayments.controller'; import { BillPaymentsController } from './BillPayments.controller';
import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries'; import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries';
import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber'; import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber';
import { BillPaymentBillSyncSubscriber } from './subscribers/BillPaymentBillSyncSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module'; import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module'; import { AccountsModule } from '../Accounts/Accounts.module';
import { BillPaymentsExportable } from './queries/BillPaymentsExportable'; import { BillPaymentsExportable } from './queries/BillPaymentsExportable';
@@ -39,6 +40,7 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
TenancyContext, TenancyContext,
BillPaymentGLEntries, BillPaymentGLEntries,
BillPaymentGLEntriesSubscriber, BillPaymentGLEntriesSubscriber,
BillPaymentBillSyncSubscriber,
BillPaymentsExportable, BillPaymentsExportable,
BillPaymentsImportable, BillPaymentsImportable,
GetBillPaymentsService, GetBillPaymentsService,
@@ -52,4 +54,4 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
], ],
controllers: [BillPaymentsController], controllers: [BillPaymentsController],
}) })
export class BillPaymentsModule {} export class BillPaymentsModule { }

View File

@@ -38,7 +38,7 @@ export class CreateBillPaymentService {
@Inject(BillPayment.name) @Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>, private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {} ) { }
/** /**
* Creates a new bill payment transcations and store it to the storage * Creates a new bill payment transcations and store it to the storage
@@ -103,11 +103,19 @@ export class CreateBillPaymentService {
} as IBillPaymentCreatingPayload); } as IBillPaymentCreatingPayload);
// Writes the bill payment graph to the storage. // Writes the bill payment graph to the storage.
const billPayment = await this.billPaymentModel() const insertedBillPayment = await this.billPaymentModel()
.query(trx) .query(trx)
.insertGraphAndFetch({ .insertGraphAndFetch({
...billPaymentObj, ...billPaymentObj,
}); });
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
const billPayment = await this.billPaymentModel()
.query(trx)
.withGraphFetched('entries')
.findById(insertedBillPayment.id)
.throwIfNotFound();
// Triggers `onBillPaymentCreated` event. // Triggers `onBillPaymentCreated` event.
await this.eventPublisher.emitAsync(events.billPayment.onCreated, { await this.eventPublisher.emitAsync(events.billPayment.onCreated, {
billPayment, billPayment,

View File

@@ -29,7 +29,7 @@ export class EditBillPayment {
@Inject(Vendor.name) @Inject(Vendor.name)
private readonly vendorModel: TenantModelProxy<typeof Vendor>, private readonly vendorModel: TenantModelProxy<typeof Vendor>,
) {} ) { }
/** /**
* Edits the details of the given bill payment. * Edits the details of the given bill payment.
@@ -116,12 +116,20 @@ export class EditBillPayment {
} as IBillPaymentEditingPayload); } as IBillPaymentEditingPayload);
// Edits the bill payment transaction graph on the storage. // Edits the bill payment transaction graph on the storage.
const billPayment = await this.billPaymentModel() await this.billPaymentModel()
.query(trx) .query(trx)
.upsertGraphAndFetch({ .upsertGraph({
id: billPaymentId, id: billPaymentId,
...billPaymentObj, ...billPaymentObj,
}); });
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
const billPayment = await this.billPaymentModel()
.query(trx)
.withGraphFetched('entries')
.findById(billPaymentId)
.throwIfNotFound();
// Triggers `onBillPaymentEdited` event. // Triggers `onBillPaymentEdited` event.
await this.eventPublisher.emitAsync(events.billPayment.onEdited, { await this.eventPublisher.emitAsync(events.billPayment.onEdited, {
billPaymentId, billPaymentId,

View File

@@ -0,0 +1,80 @@
import {
IBillPaymentEventCreatedPayload,
IBillPaymentEventDeletedPayload,
IBillPaymentEventEditedPayload,
} from '../types/BillPayments.types';
import { BillPaymentBillSync } from '../commands/BillPaymentBillSync.service';
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
@Injectable()
export class BillPaymentBillSyncSubscriber {
/**
* @param {BillPaymentBillSync} billPaymentBillSync - Bill payment bill sync service.
*/
constructor(private readonly billPaymentBillSync: BillPaymentBillSync) { }
/**
* Handle bill increment/decrement payment amount
* once created, edited or deleted.
*/
@OnEvent(events.billPayment.onCreated)
async handleBillIncrementPaymentOnceCreated({
billPayment,
trx,
}: IBillPaymentEventCreatedPayload) {
// Ensure entries are available - they should be included in insertGraphAndFetch
const entries = billPayment.entries || [];
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
entries.map((entry) => ({
billId: entry.billId,
paymentAmount: entry.paymentAmount,
})),
null,
trx,
);
}
/**
* Handle bill increment/decrement payment amount once edited.
*/
@OnEvent(events.billPayment.onEdited)
async handleBillIncrementPaymentOnceEdited({
billPayment,
oldBillPayment,
trx,
}: IBillPaymentEventEditedPayload) {
const entries = billPayment.entries || [];
const oldEntries = oldBillPayment?.entries || null;
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
entries.map((entry) => ({
billId: entry.billId,
paymentAmount: entry.paymentAmount,
})),
oldEntries,
trx,
);
}
/**
* Handle revert bills payment amount once bill payment deleted.
*/
@OnEvent(events.billPayment.onDeleted)
async handleBillDecrementPaymentAmount({
oldBillPayment,
trx,
}: IBillPaymentEventDeletedPayload) {
const oldEntries = oldBillPayment.entries || [];
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
oldEntries.map((entry) => ({
billId: entry.billId,
paymentAmount: 0,
})),
oldEntries,
trx,
);
}
}

View File

@@ -10,6 +10,7 @@ import {
import { FinancialSheet } from '../../common/FinancialSheet'; import { FinancialSheet } from '../../common/FinancialSheet';
import { JournalSheetRepository } from './JournalSheetRepository'; import { JournalSheetRepository } from './JournalSheetRepository';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types'; import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { getTransactionTypeLabel } from '@/modules/BankingTransactions/utils';
export class JournalSheet extends FinancialSheet { export class JournalSheet extends FinancialSheet {
readonly query: IJournalReportQuery; readonly query: IJournalReportQuery;
@@ -97,10 +98,13 @@ export class JournalSheet extends FinancialSheet {
transactionType: groupEntry.transactionType, transactionType: groupEntry.transactionType,
referenceId: groupEntry.transactionId, referenceId: groupEntry.transactionId,
referenceTypeFormatted: this.i18n.t(groupEntry.transactionType), referenceTypeFormatted: this.i18n.t(
getTransactionTypeLabel(
groupEntry.transactionType,
groupEntry.transactionSubType,
),
),
entries: this.entriesMapper(entriesGroup), entries: this.entriesMapper(entriesGroup),
currencyCode: this.baseCurrency, currencyCode: this.baseCurrency,
credit: totalCredit, credit: totalCredit,

View File

@@ -6,6 +6,7 @@ import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
import { SaleReceipt } from '@/modules/SaleReceipts/models/SaleReceipt'; import { SaleReceipt } from '@/modules/SaleReceipts/models/SaleReceipt';
import { Item } from '@/modules/Items/models/Item'; import { Item } from '@/modules/Items/models/Item';
import { BaseModel } from '@/models/Model'; import { BaseModel } from '@/models/Model';
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
export class InventoryCostLotTracker extends BaseModel { export class InventoryCostLotTracker extends BaseModel {
date: Date; date: Date;
@@ -27,6 +28,7 @@ export class InventoryCostLotTracker extends BaseModel {
warehouseId: number; warehouseId: number;
item?: Item; item?: Item;
itemEntry?: ItemEntry;
invoice?: SaleInvoice; invoice?: SaleInvoice;
receipt?: SaleReceipt; receipt?: SaleReceipt;

View File

@@ -20,7 +20,7 @@ export class InventoryCostSubscriber {
private readonly itemsQuantitySync: InventoryItemsQuantitySyncService, private readonly itemsQuantitySync: InventoryItemsQuantitySyncService,
private readonly inventoryService: InventoryComputeCostService, private readonly inventoryService: InventoryComputeCostService,
private readonly importAls: ImportAls, private readonly importAls: ImportAls,
) {} ) { }
/** /**
* Sync inventory items quantity once inventory transactions created. * Sync inventory items quantity once inventory transactions created.
@@ -60,7 +60,7 @@ export class InventoryCostSubscriber {
* Marks items cost compute running state. * Marks items cost compute running state.
*/ */
@OnEvent(events.inventory.onInventoryTransactionsCreated) @OnEvent(events.inventory.onInventoryTransactionsCreated)
async markGlobalSettingsComputeItems({}) { async markGlobalSettingsComputeItems({ }) {
await this.inventoryService.markItemsCostComputeRunning(true); await this.inventoryService.markItemsCostComputeRunning(true);
} }
@@ -68,7 +68,7 @@ export class InventoryCostSubscriber {
* Marks items cost compute as completed. * Marks items cost compute as completed.
*/ */
@OnEvent(events.inventory.onInventoryCostEntriesWritten) @OnEvent(events.inventory.onInventoryCostEntriesWritten)
async markGlobalSettingsComputeItemsCompeted({}) { async markGlobalSettingsComputeItemsCompeted({ }) {
await this.inventoryService.markItemsCostComputeRunning(false); await this.inventoryService.markItemsCostComputeRunning(false);
} }
@@ -80,15 +80,13 @@ export class InventoryCostSubscriber {
itemId, itemId,
startingDate, startingDate,
}: IComputeItemCostJobCompletedPayload) { }: IComputeItemCostJobCompletedPayload) {
// const dependsComputeJobs = await this.agenda.jobs({ // Convert startingDate to Date if it's a string
// name: 'compute-item-cost', const startingDateObj = startingDate instanceof Date
// nextRunAt: { $ne: null }, ? startingDate
// 'data.tenantId': tenantId, : new Date(startingDate);
// });
// // There is no scheduled compute jobs waiting. // Write GL entries for inventory cost lots after cost computation completes
// if (dependsComputeJobs.length === 0) { await this.saleInvoicesCost.writeCostLotsGLEntries(startingDateObj);
// await this.saleInvoicesCost.scheduleWriteJournalEntries(startingDate);
// }
} }
/** /**

View File

@@ -38,7 +38,8 @@ export class SaleInvoiceCostGLEntries {
.modify('filterDateRange', startingDate) .modify('filterDateRange', startingDate)
.orderBy('date', 'ASC') .orderBy('date', 'ASC')
.withGraphFetched('invoice') .withGraphFetched('invoice')
.withGraphFetched('item'); .withGraphFetched('item')
.withGraphFetched('itemEntry');
const ledger = this.getInventoryCostLotsLedger(inventoryCostLotTrans); const ledger = this.getInventoryCostLotsLedger(inventoryCostLotTrans);
@@ -79,6 +80,9 @@ export class SaleInvoiceCostGLEntries {
transactionType: inventoryCostLot.transactionType, transactionType: inventoryCostLot.transactionType,
transactionId: inventoryCostLot.transactionId, transactionId: inventoryCostLot.transactionId,
transactionNumber: inventoryCostLot.invoice.invoiceNo,
referenceNumber: inventoryCostLot.invoice.referenceNo,
date: inventoryCostLot.date, date: inventoryCostLot.date,
indexGroup: 20, indexGroup: 20,
costable: true, costable: true,
@@ -105,6 +109,9 @@ export class SaleInvoiceCostGLEntries {
const costAccountId = const costAccountId =
inventoryCostLot.costAccountId || inventoryCostLot.item.costAccountId; inventoryCostLot.costAccountId || inventoryCostLot.item.costAccountId;
// Get description from item entry if available
const description = inventoryCostLot.itemEntry?.description || null;
// XXX Debit - Cost account. // XXX Debit - Cost account.
const costEntry = { const costEntry = {
...commonEntry, ...commonEntry,
@@ -112,6 +119,7 @@ export class SaleInvoiceCostGLEntries {
accountId: costAccountId, accountId: costAccountId,
accountNormal: AccountNormal.DEBIT, accountNormal: AccountNormal.DEBIT,
itemId: inventoryCostLot.itemId, itemId: inventoryCostLot.itemId,
note: description,
index: getIndexIncrement(), index: getIndexIncrement(),
}; };
// XXX Credit - Inventory account. // XXX Credit - Inventory account.
@@ -121,6 +129,7 @@ export class SaleInvoiceCostGLEntries {
accountId: inventoryCostLot.item.inventoryAccountId, accountId: inventoryCostLot.item.inventoryAccountId,
accountNormal: AccountNormal.DEBIT, accountNormal: AccountNormal.DEBIT,
itemId: inventoryCostLot.itemId, itemId: inventoryCostLot.itemId,
note: description,
index: getIndexIncrement(), index: getIndexIncrement(),
}; };
return [costEntry, inventoryEntry]; return [costEntry, inventoryEntry];

View File

@@ -1,15 +1,18 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
import { IInventoryCostLotsGLEntriesWriteEvent } from '@/modules/InventoryCost/types/InventoryCost.types'; import { IInventoryCostLotsGLEntriesWriteEvent } from '@/modules/InventoryCost/types/InventoryCost.types';
import { SaleInvoiceCostGLEntries } from '../SaleInvoiceCostGLEntries'; import { SaleInvoiceCostGLEntries } from '../SaleInvoiceCostGLEntries';
@Injectable() @Injectable()
export class InvoiceCostGLEntriesSubscriber { export class InvoiceCostGLEntriesSubscriber {
constructor(private readonly invoiceCostEntries: SaleInvoiceCostGLEntries) {} constructor(private readonly invoiceCostEntries: SaleInvoiceCostGLEntries) { }
/** /**
* Writes the invoices cost GL entries once the inventory cost lots be written. * Writes the invoices cost GL entries once the inventory cost lots be written.
* @param {IInventoryCostLotsGLEntriesWriteEvent} * @param {IInventoryCostLotsGLEntriesWriteEvent}
*/ */
@OnEvent(events.inventory.onCostLotsGLEntriesWrite)
async writeInvoicesCostEntriesOnCostLotsWritten({ async writeInvoicesCostEntriesOnCostLotsWritten({
trx, trx,
startingDate, startingDate,

View File

@@ -40,10 +40,10 @@ import { compose } from '@/utils';
* Payment made actions bar. * Payment made actions bar.
*/ */
function PaymentMadeActionsBar({ function PaymentMadeActionsBar({
// #withPaymentMadesActions // #withPaymentMadeActions
setPaymentMadesTableState, setPaymentMadesTableState,
// #withPaymentMades // #withPaymentMade
paymentMadesFilterConditions, paymentMadesFilterConditions,
// #withSettings // #withSettings
@@ -133,7 +133,7 @@ function PaymentMadeActionsBar({
icon={<Icon icon={'trash-16'} iconSize={16} />} icon={<Icon icon={'trash-16'} iconSize={16} />}
text={<T id={'delete'} />} text={<T id={'delete'} />}
intent={Intent.DANGER} intent={Intent.DANGER}
// onClick={handleBulkDelete} // onClick={handleBulkDelete}
/> />
</If> </If>
<Button <Button

View File

@@ -8,7 +8,7 @@ import { PaymentMadesListProvider } from './PaymentMadesListProvider';
import PaymentMadeActionsBar from './PaymentMadeActionsBar'; import PaymentMadeActionsBar from './PaymentMadeActionsBar';
import PaymentMadesTable from './PaymentMadesTable'; import PaymentMadesTable from './PaymentMadesTable';
import { withPaymentMades } from './withPaymentMade'; import { withPaymentMade } from './withPaymentMade';
import { withPaymentMadeActions } from './withPaymentMadeActions'; import { withPaymentMadeActions } from './withPaymentMadeActions';
import { compose, transformTableStateToQuery } from '@/utils'; import { compose, transformTableStateToQuery } from '@/utils';
@@ -17,7 +17,7 @@ import { compose, transformTableStateToQuery } from '@/utils';
* Payment mades list. * Payment mades list.
*/ */
function PaymentMadeList({ function PaymentMadeList({
// #withPaymentMades // #withPaymentMade
paymentMadesTableState, paymentMadesTableState,
paymentsTableStateChanged, paymentsTableStateChanged,
@@ -47,7 +47,7 @@ function PaymentMadeList({
} }
export default compose( export default compose(
withPaymentMades(({ paymentMadesTableState, paymentsTableStateChanged }) => ({ withPaymentMade(({ paymentMadesTableState, paymentsTableStateChanged }) => ({
paymentMadesTableState, paymentMadesTableState,
paymentsTableStateChanged, paymentsTableStateChanged,
})), })),

View File

@@ -15,7 +15,7 @@ import { withPaymentMadeActions } from './withPaymentMadeActions';
* Payment made views tabs. * Payment made views tabs.
*/ */
function PaymentMadeViewTabs({ function PaymentMadeViewTabs({
// #withPaymentMadesActions // #withPaymentMadeActions
setPaymentMadesTableState, setPaymentMadesTableState,
// #withPaymentMade // #withPaymentMade