Skip to content
Merged
1 change: 1 addition & 0 deletions public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"group_name_update_failed": "Error in updating group name",
"import_failed": "Error importing file",
"invalid_currency_code": "Invalid currency code {code}",
"invalid_expression": "Invalid expression",
"invalid_split": "Adjust who owes this expense before saving.",
"language_change_failed": "Error changing language",
"less_than": "File should be less than {size}MB",
Expand Down
24 changes: 22 additions & 2 deletions src/components/AddExpense/AddExpensePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ import { UploadFile } from './UploadFile';
import { UserInput } from './UserInput';
import { CurrencyInput } from '../ui/currency-input';
import { CurrencyConversion } from '../Friend/CurrencyConversion';
import { currencyConversion } from '~/utils/numbers';
import { BigMath, currencyConversion } from '~/utils/numbers';
import { isExpression, safeEvaluateExpression } from '~/utils/expression';
import { CurrencyConversionIcon } from '../ui/categoryIcons';
import { useSession } from 'next-auth/react';
import { isStringQueryParam } from '~/utils/queryParams';
Expand Down Expand Up @@ -111,6 +112,22 @@ export const AddOrEditExpensePage: React.FC<{
return;
}

let finalAmount = amount;
Comment thread
krokosik marked this conversation as resolved.
Resolved
if (isExpression(amtStr)) {
const evaluated = safeEvaluateExpression(amtStr);
if (null === evaluated) {
toast.error(t('errors.invalid_expression'));
return;
}
finalAmount = BigMath.abs(
getCurrencyHelpersCached(currency).expressionResultToBigInt(evaluated),
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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

setMultipleTransactions([]);
setIsTransactionLoading(false);

Expand All @@ -122,7 +139,7 @@ export const AddOrEditExpensePage: React.FC<{
{
name: description,
currency,
amount: amount * sign,
amount: finalAmount * sign,
groupId: group?.id ?? null,
splitType,
participants: participants.map((p) => ({
Expand Down Expand Up @@ -194,6 +211,7 @@ export const AddOrEditExpensePage: React.FC<{
currency,
isNegative,
amount,
amtStr,
participants,
category,
expenseDate,
Expand All @@ -212,6 +230,7 @@ export const AddOrEditExpensePage: React.FC<{
setSingleTransaction,
t,
update,
getCurrencyHelpersCached,
]);

const handleDescriptionChange = useCallback(
Expand Down Expand Up @@ -315,6 +334,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
44 changes: 39 additions & 5 deletions src/components/ui/currency-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,66 @@ import React from 'react';
import { Input, InputProps } from './input';
import { cn } from '~/lib/utils';
import { useTranslationWithUtils } from '~/hooks/useTranslationWithUtils';
import { isExpression, safeEvaluateExpression, sanitizeExpressionInput } from '~/utils/expression';

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 {
decimalDigits,
format,
parseToCleanString,
toSafeBigInt,
expressionResultToBigInt,
sanitizeInput,
} = getCurrencyHelpersCached(currency);

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)) {
onValueChange({ strValue: parseToCleanString(strValue, allowNegative) });
}
}}
onBlur={() => {
if (allowExpressions && isExpression(strValue)) {
return;
}

const formattedValue = format(strValue, { signed: allowNegative, hideSymbol });
return onValueChange({ strValue: formattedValue });
}}
onChange={(e) => {
const rawValue = e.target.value;
if (allowExpressions && isExpression(rawValue)) {
const strValue = sanitizeExpressionInput(rawValue, decimalDigits);
const evaluated = safeEvaluateExpression(strValue);
return onValueChange({
strValue,
bigIntValue: null === evaluated ? 0n : expressionResultToBigInt(evaluated),
});
}

const strValue = sanitizeInput(rawValue, allowNegative, true);
const bigIntValue = toSafeBigInt(strValue, allowNegative);
onValueChange({ strValue, bigIntValue });
Expand Down
49 changes: 49 additions & 0 deletions src/tests/expression.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { isExpression, 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('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('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 }],
['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();
});
});
15 changes: 15 additions & 0 deletions src/tests/number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@
import { currencyConversion, getCurrencyHelpers } from '../utils/numbers';

describe('getCurrencyHelpers', () => {
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
Loading
Loading