Skip to content

Commit

Permalink
fix(PaymentsForm.tsx): fix total formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
moconnell committed Feb 23, 2024
1 parent 8319d52 commit 3c0fa5e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
23 changes: 17 additions & 6 deletions packages/forms/src/PaymentsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ import {
Select,
useMediaStyles,
} from '@smart-invoice/ui';
import { commify, escrowPaymentsSchema } from '@smart-invoice/utils';
import {
commify,
escrowPaymentsSchema,
getDecimals,
} from '@smart-invoice/utils';
import _ from 'lodash';
import { useEffect, useMemo } from 'react';
import { useFieldArray, useForm, UseFormReturn } from 'react-hook-form';
Expand Down Expand Up @@ -90,10 +94,17 @@ export function PaymentsForm({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [TOKENS]);

const total = _.sumBy(
localMilestones,
(milestone: { value: string }) => _.toNumber(milestone.value) || 0,
);
const [total, decimals] = localMilestones
? localMilestones
.map((milestone: { value: string }) => [
_.toNumber(milestone.value) || 0,
getDecimals(milestone.value),
])
.reduce(
([tot, maxDecimals], [v, d]) => [tot + v, Math.max(d, maxDecimals)],
[0, 0],
)
: [0, 0];

return (
<Stack as="form" onSubmit={handleSubmit(onSubmit)} spacing={4}>
Expand Down Expand Up @@ -174,7 +185,7 @@ export function PaymentsForm({
</Button>

<Text>
Total: {commify(total || 0)} {invoiceTokenData?.symbol}
Total: {commify(total, decimals)} {invoiceTokenData?.symbol}
</Text>
</Flex>
</Stack>
Expand Down
12 changes: 10 additions & 2 deletions packages/utils/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,18 @@ export const isValidLink = (url: string) => {
return isValidURL(url);
};

export function commify(x: number | bigint | string): string {
export const getDecimals = (value: string) => {
const [, decimal] = value.split('.');
return decimal?.length || 0;
};

export function commify(
x: number | bigint | string,
decimals?: number,
): string {
if (_.toString(x).includes('.')) {
const [whole, decimal] = x.toString().split('.');
return `${commify(whole)}.${decimal}`;
return `${commify(whole)}.${decimal.substring(0, Math.min(decimals ?? decimal.length, decimal.length))}`;
}
return _.toString(x).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Expand Down

0 comments on commit 3c0fa5e

Please sign in to comment.