diff --git a/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts b/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts index 3e3e6c7b1..d165fbca9 100644 --- a/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts +++ b/packages/server/src/services/ManualJournals/CommandManualJournalValidators.ts @@ -1,4 +1,4 @@ -import { difference, isEmpty } from 'lodash'; +import { difference, isEmpty, round, sumBy } from 'lodash'; import { Service, Inject } from 'typedi'; import { ServiceError } from '@/exceptions'; import { @@ -23,20 +23,18 @@ export class CommandManualJournalValidators { * @param {IManualJournalDTO} manualJournalDTO */ public valdiateCreditDebitTotalEquals(manualJournalDTO: IManualJournalDTO) { - let totalCredit = 0; - let totalDebit = 0; - - manualJournalDTO.entries.forEach((entry) => { - if (entry.credit > 0) { - totalCredit += entry.credit; - } - if (entry.debit > 0) { - totalDebit += entry.debit; - } - }); + const totalCredit = round( + sumBy(manualJournalDTO.entries, (entry) => entry.credit || 0), + 2 + ); + const totalDebit = round( + sumBy(manualJournalDTO.entries, (entry) => entry.debit || 0), + 2 + ); 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); } diff --git a/packages/webapp/src/containers/Accounting/MakeJournal/MakeJournalEntriesForm.tsx b/packages/webapp/src/containers/Accounting/MakeJournal/MakeJournalEntriesForm.tsx index a47b3b6aa..02a347b13 100644 --- a/packages/webapp/src/containers/Accounting/MakeJournal/MakeJournalEntriesForm.tsx +++ b/packages/webapp/src/containers/Accounting/MakeJournal/MakeJournalEntriesForm.tsx @@ -4,7 +4,7 @@ import { Formik, Form } from 'formik'; import { Intent } from '@blueprintjs/core'; import intl from 'react-intl-universal'; import * as R from 'ramda'; -import { isEmpty, omit } from 'lodash'; +import { sumBy, round, isEmpty, omit } from 'lodash'; import classNames from 'classnames'; import { useHistory } from 'react-router-dom'; @@ -88,15 +88,17 @@ function MakeJournalEntriesForm({ const entries = values.entries.filter( (entry) => entry.debit || entry.credit, ); + // Updated getTotal function using lodash const getTotal = (type = 'credit') => { - return entries.reduce((total, item) => { - return item[type] ? item[type] + total : total; - }, 0); + return round( + sumBy(entries, (entry) => parseFloat(entry[type] || 0)), + 2, + ); }; const totalCredit = getTotal('credit'); const totalDebit = getTotal('debit'); - // Validate the total credit should be eqials total debit. + // Validate the total credit should be equals total debit. if (totalCredit !== totalDebit) { AppToaster.show({ message: intl.get('should_total_of_credit_and_debit_be_equal'),