Skip to content
Merged
26 changes: 24 additions & 2 deletions src/components/AddExpense/AddExpensePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { UserInput } from './UserInput';
import { CurrencyInput } from '../ui/currency-input';
import { CurrencyConversion } from '../Friend/CurrencyConversion';
import { currencyConversion } from '~/utils/numbers';
import { isExpression } from '~/utils/expression';
import { CurrencyConversionIcon } from '../ui/categoryIcons';
import { useSession } from 'next-auth/react';
import { isStringQueryParam } from '~/utils/queryParams';
Expand Down Expand Up @@ -94,10 +95,26 @@ export const AddOrEditExpensePage: React.FC<{

updateProfile.mutate({ currency: newCurrency });

setPreviousCurrency(currency);
if (isExpression(amtStr)) {
Comment thread
krokosik marked this conversation as resolved.
Resolved
// The new currency has a different minor-unit scale; update the amount and splits from the expression.
const result = getCurrencyHelpersCached(newCurrency).evaluateExpressionInput(amtStr);
setAmountStr(result.strValue);
setAmount(result.bigIntValue);
setPreviousCurrency(null);
} else {
setPreviousCurrency(currency);
}
setCurrency(newCurrency);
},
[currency, setCurrency, updateProfile],
[
amtStr,
currency,
getCurrencyHelpersCached,
setAmount,
setAmountStr,
setCurrency,
updateProfile,
],
);

const router = useRouter();
Expand All @@ -120,6 +137,10 @@ export const AddOrEditExpensePage: React.FC<{
return;
}

if (0n === amount) {
return;
Comment thread
krokosik marked this conversation as resolved.
Resolved
}

setMultipleTransactions([]);
setIsTransactionLoading(false);

Expand Down Expand Up @@ -335,6 +356,7 @@ export const AddOrEditExpensePage: React.FC<{
placeholder={t('expense_details.add_expense_details.amount_placeholder')}
currency={currency}
strValue={amtStr}
allowExpressions
allowNegative
hideSymbol
onValueChange={onUpdateAmount}
Expand Down
55 changes: 47 additions & 8 deletions src/components/ui/currency-input.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,73 @@
import React from 'react';
import { Input, InputProps } from './input';
import { cn } from '~/lib/utils';

import { useTranslationWithUtils } from '~/hooks/useTranslationWithUtils';
import { cn } from '~/lib/utils';
import { isExpression } from '~/utils/expression';

import { Input, type InputProps } from './input';

const CurrencyInput: React.FC<
Omit<InputProps, 'type' | 'inputMode'> & {
currency: string;
strValue: string;
onValueChange: (v: { strValue?: string; bigIntValue?: bigint }) => void;
allowExpressions?: boolean;
allowNegative?: boolean;
hideSymbol?: boolean;
}
> = ({ className, currency, allowNegative, strValue, onValueChange, hideSymbol, ...props }) => {
> = ({
className,
currency,
allowExpressions = false,
allowNegative,
strValue,
onValueChange,
hideSymbol,
...props
}) => {
const { getCurrencyHelpersCached } = useTranslationWithUtils(undefined);
const { format, parseToCleanString, toSafeBigInt, sanitizeInput } =
getCurrencyHelpersCached(currency);
const {
format,
parseToCleanString,
toSafeBigInt,
evaluateExpressionInput,
hasDuplicateDecimalSeparator,
removeValidGroupingSeparators,
sanitizeInput,
} = getCurrencyHelpersCached(currency);
const hasDuplicateDecimal = hasDuplicateDecimalSeparator(strValue);

return (
<Input
className={cn('text-lg placeholder:text-sm', className)}
inputMode="decimal"
inputMode={allowExpressions ? 'text' : 'decimal'}
Comment thread
krokosik marked this conversation as resolved.
Resolved
value={strValue}
onFocus={() => onValueChange({ strValue: parseToCleanString(strValue, allowNegative) })}
onFocus={() => {
if (!allowExpressions || (!isExpression(strValue) && !hasDuplicateDecimal)) {
Comment thread
mikimandoki marked this conversation as resolved.
Resolved
onValueChange({ strValue: parseToCleanString(strValue, allowNegative) });
}
}}
onBlur={() => {
if (allowExpressions && (isExpression(strValue) || hasDuplicateDecimal)) {
return;
}

const formattedValue = format(strValue, { signed: allowNegative, hideSymbol });
return onValueChange({ strValue: formattedValue });
}}
onChange={(e) => {
const rawValue = e.target.value;
const strValue = sanitizeInput(rawValue, allowNegative, true);
const normalizedValue = allowExpressions
Comment thread
krokosik marked this conversation as resolved.
Resolved
? removeValidGroupingSeparators(rawValue)
: rawValue;
if (allowExpressions && hasDuplicateDecimalSeparator(normalizedValue)) {
return onValueChange({ strValue: normalizedValue, bigIntValue: 0n });
}
if (allowExpressions && isExpression(normalizedValue)) {
return onValueChange(evaluateExpressionInput(normalizedValue));
}

const strValue = sanitizeInput(normalizedValue, allowNegative, true);
const bigIntValue = toSafeBigInt(strValue, allowNegative);
onValueChange({ strValue, bigIntValue });
}}
Expand Down
104 changes: 104 additions & 0 deletions src/tests/expression.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import {
hasDuplicateDecimalSeparator,
isExpression,
removeValidGroupingSeparators,
safeEvaluateExpression,
sanitizeExpressionInput,
} from '../utils/expression';

describe('isExpression', () => {
it.each([
['123.45', false],
['-123.45', false],
['-', false],
['30.5+10.75-12-1.86', true],
['10*5', true],
['10/4', true],
['(2+3)*4', true],
])('returns %p for %p', (input, expected) => {
expect(isExpression(input)).toBe(expected);
});
});

describe('hasDuplicateDecimalSeparator', () => {
it.each([
['1.2.3', '.', ',', '', true],
['1.2.3+4', '.', ',', '', true],
['(1.2.3)+4', '.', ',', '', true],
['1.2+3.4', '.', ',', '', false],
['1,2,3', ',', '.', '', true],
['1,234.56', '.', ',', ',', false],
['1,000,000', '.', ',', ',', false],
['1,000,000.56', '.', ',', ',', false],
['1,2,3', '.', ',', ',', true],
['1.000.000,56', ',', '.', '.', false],
])(
'returns %p for %p with separators %p, %p, and group %p',
(input, decimal, alternative, group, expected) => {
expect(hasDuplicateDecimalSeparator(input, decimal, alternative, group)).toBe(expected);
},
);
});

describe('removeValidGroupingSeparators', () => {
it.each([
['1,000,000', '.', ',', '1000000'],
['1,000,000.50+1,000', '.', ',', '1000000.50+1000'],
['1.000.000,50+1.000', ',', '.', '1000000,50+1000'],
['1,5+2', '.', ',', '1,5+2'],
['1,2,3+4', '.', ',', '1,2,3+4'],
])('normalizes grouped amounts %p', (input, decimalSeparator, groupSeparator, expected) => {
expect(removeValidGroupingSeparators(input, decimalSeparator, groupSeparator)).toBe(expected);
});
});

describe('sanitizeExpressionInput', () => {
it('keeps arithmetic and decimal characters only', () => {
expect(sanitizeExpressionInput('$30.5 + 10,75 xyz', 2)).toBe('30.5+10.75');
});

it('limits each operand to the currency precision', () => {
expect(sanitizeExpressionInput('1.234+3.456/0.789', 2)).toBe('1.23+3.45/0.78');
});

it('normalizes alternate decimal marks to the locale separator', () => {
expect(sanitizeExpressionInput('12,5+3.75', 2, '.', ',')).toBe('12.5+3.75');
expect(sanitizeExpressionInput('12,5+3.75', 2, ',', '.')).toBe('12,5+3,75');
});

it('drops fractional digits for zero-decimal currencies', () => {
expect(sanitizeExpressionInput('12.34+5.6', 0)).toBe('12+5');
});
});

describe('safeEvaluateExpression', () => {
it.each([
['30.5+10.75-12-1.86', { numerator: 2739n, denominator: 100n }],
['2+3*4', { numerator: 14n, denominator: 1n }],
['(2+3)*4', { numerator: 20n, denominator: 1n }],
['10/4', { numerator: 5n, denominator: 2n }],
['2++3', { numerator: 5n, denominator: 1n }],
['0.1+0.2', { numerator: 3n, denominator: 10n }],
['1,5+2', { numerator: 7n, denominator: 2n }],
['12,5+3,75', { numerator: 65n, denominator: 4n }],
['9007199254740992+1', { numerator: 9007199254740993n, denominator: 1n }],
['-10+5', { numerator: -5n, denominator: 1n }],
])('evaluates %p exactly', (input, expected) => {
expect(safeEvaluateExpression(input)).toEqual(expected);
});

it.each(['', 'abc', '30.5+', '()', '(2+3', '30/0', '1.2.3'])('rejects %p', (input) => {
expect(safeEvaluateExpression(input)).toBeNull();
});
});

describe('expression limits', () => {
it.each([
`${'('.repeat(10000)}1${')'.repeat(10000)}`,
`${'('.repeat(33)}1${')'.repeat(33)}`,
`${'9'.repeat(33)}+1`,
`${'1+'.repeat(257)}1`,
])('rejects oversized input safely', (input) => {
expect(safeEvaluateExpression(input)).toBeNull();
});
});
85 changes: 56 additions & 29 deletions src/tests/number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,35 @@ import {
} from '../utils/numbers';

describe('getCurrencyHelpers', () => {
describe('expression input normalization', () => {
const { hasDuplicateDecimalSeparator, removeValidGroupingSeparators, sanitizeExpressionInput } =
getCurrencyHelpers({ locale: 'en-US', currency: 'USD' });

it('uses locale separators when normalizing grouped expression input', () => {
const normalized = removeValidGroupingSeparators('1,000,000+1');

expect(normalized).toBe('1000000+1');
expect(sanitizeExpressionInput(normalized)).toBe('1000000+1');
expect(sanitizeExpressionInput('1,5+2')).toBe('1.5+2');
expect(hasDuplicateDecimalSeparator('1.2.3+4')).toBe(true);
});
});

describe('expressionResultToBigInt', () => {
it('converts exact expression results to minor currency units', () => {
const { expressionResultToBigInt } = getCurrencyHelpers({ currency: 'USD' });

expect(expressionResultToBigInt({ numerator: 2739n, denominator: 100n })).toBe(2739n);
expect(expressionResultToBigInt({ numerator: 1n, denominator: 3n })).toBe(33n);
});

it('rounds results using the currency precision', () => {
const { expressionResultToBigInt } = getCurrencyHelpers({ currency: 'JPY' });

expect(expressionResultToBigInt({ numerator: 7n, denominator: 2n })).toBe(4n);
});
});

describe('toUIString', () => {
describe('en-US locale', () => {
const locale = 'en-US';
Expand Down Expand Up @@ -36,11 +65,9 @@ describe('getCurrencyHelpers', () => {
expect(toUIString(value)).toBe('$1,234');
});

it.each([
[7n, '$0.07'],
[-7n, '$0.07'],
])('Should correctly format single digit cent amounts', (value, expected) => {
expect(toUIString(value)).toBe(expected);
it('Should correctly format single digit cent amounts', () => {
const value = 7n;
expect(toUIString(value)).toBe('$0.07');
});

it.each([
Expand Down Expand Up @@ -91,30 +118,6 @@ describe('getCurrencyHelpers', () => {
});
});

describe('round trip through the displayed string', () => {
it.each([
['de-DE', 'JPY', 123456n, '123.456 ¥'],
['de-DE', 'KRW', 1234567n, '1.234.567 ₩'],
['pl-PL', 'JPY', 1235n, '1235 JPY'],
['en-US', 'JPY', 1235n, '¥1,235'],
['de-DE', 'EUR', 123456n, '1.234,56 €'],
])('parses %s %s %p back from %p', (locale, currency, value, displayed) => {
const { toUIString, toSafeBigInt, parseToCleanString } = getCurrencyHelpers({
locale,
currency,
});
expect(toUIString(value).replace(/\s/g, ' ')).toBe(displayed);
expect(toSafeBigInt(toUIString(value))).toBe(value);
// CurrencyInput reformats on blur and cleans on focus; neither may change the value.
expect(toSafeBigInt(parseToCleanString(toUIString(value)))).toBe(value);
});

it('drops typed decimals for a zero-decimal currency instead of misreading the separator', () => {
const { toSafeBigInt } = getCurrencyHelpers({ locale: 'de-DE', currency: 'JPY' });
expect(toSafeBigInt('12,7')).toBe(12n);
});
});

describe('bg-BG locale', () => {
const locale = 'bg-BG';

Expand Down Expand Up @@ -284,6 +287,30 @@ describe('currencyConversion', () => {
});
});

describe('currency-aware expression evaluation', () => {
it('normalizes operands when changing from USD to JPY', () => {
const usd = getCurrencyHelpers({ currency: 'USD' });
const jpy = getCurrencyHelpers({ currency: 'JPY' });
const original = usd.evaluateExpressionInput('1.99+1.99');
expect(original.bigIntValue).toBe(398n);
expect(jpy.evaluateExpressionInput(original.strValue)).toEqual({
strValue: '1+1',
bigIntValue: 2n,
});
});
it('preserves invalid decimal input instead of evaluating a different amount', () => {
expect(getCurrencyHelpers({ currency: 'USD' }).evaluateExpressionInput('1.2.3+4')).toEqual({
strValue: '1.2.3+4',
bigIntValue: 0n,
});
});
it('evaluates grouped and alternate-decimal expressions', () => {
const helpers = getCurrencyHelpers({ currency: 'USD', locale: 'en-US' });
expect(helpers.evaluateExpressionInput('1,000+1').bigIntValue).toBe(100100n);
expect(helpers.evaluateExpressionInput('1,5+2').bigIntValue).toBe(350n);
});
});

describe('formatApproximately', () => {
it('should prefix the approximately sign for any formatter', () => {
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
Expand Down
Loading