From d79f26f1b50a1690a1f0e6f0c3c54b5f49ed4673 Mon Sep 17 00:00:00 2001 From: Nana Kofi Larbi Mantey Date: Sun, 20 Oct 2024 17:44:39 +0000 Subject: [PATCH] refactors backend validator for credit-debit equals --- .../CommandManualJournalValidators.ts | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts b/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts index 3e3e6c7b1..40c8dd509 100644 --- a/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts +++ b/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts @@ -23,23 +23,20 @@ export class CommandManualJournalValidators { * @param {IManualJournalDTO} manualJournalDTO */ public valdiateCreditDebitTotalEquals(manualJournalDTO: IManualJournalDTO) { - let totalCredit = 0; - let totalDebit = 0; + const totalCredit = this.roundToTwoDecimals( + manualJournalDTO.entries.reduce((sum, entry) => sum + (entry.credit || 0), 0) + ); + const totalDebit = this.roundToTwoDecimals( + manualJournalDTO.entries.reduce((sum, entry) => sum + (entry.debit || 0), 0) + ); - manualJournalDTO.entries.forEach((entry) => { - if (entry.credit > 0) { - totalCredit += entry.credit; - } - if (entry.debit > 0) { - totalDebit += entry.debit; - } - }); if (totalCredit <= 0 || totalDebit <= 0) { throw new ServiceError(ERRORS.CREDIT_DEBIT_NOT_EQUAL_ZERO); } - if (totalCredit !== totalDebit) { - throw new ServiceError(ERRORS.CREDIT_DEBIT_NOT_EQUAL); - } + } + + private roundToTwoDecimals(value: number): number { + return Math.round(value * 100) / 100; } /** @@ -308,3 +305,4 @@ export class CommandManualJournalValidators { } }; } +