Skip to content

A local-first personal finance app

feat(currency): add currency display to rules (#5639)

Michael Süssemilch99ca34458ee6
diff --git a/packages/desktop-client/src/components/filters/FilterExpression.tsx b/packages/desktop-client/src/components/filters/FilterExpression.tsx
index f553a89d95..eb88bdbdbb 100644
--- a/packages/desktop-client/src/components/filters/FilterExpression.tsx
+++ b/packages/desktop-client/src/components/filters/FilterExpression.tsx
@@ -9,7 +9,6 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { mapField, friendlyOp } from 'loot-core/shared/rules';
-import { integerToCurrency } from 'loot-core/shared/util';
import { type RuleConditionEntity } from 'loot-core/types/models';
import { FilterEditor } from './FiltersMenu';
@@ -139,11 +138,7 @@ export function FilterExpression<T extends RuleConditionEntity>({
<FilterEditor
field={originalField}
op={op}
- value={
- field === 'amount' && typeof value === 'number'
- ? integerToCurrency(value)
- : value
- }
+ value={value}
options={options}
onSave={onChange}
onClose={() => setEditing(false)}
diff --git a/packages/desktop-client/src/components/filters/FiltersMenu.jsx b/packages/desktop-client/src/components/filters/FiltersMenu.jsx
index 7f59fecab2..c344c49634 100644
--- a/packages/desktop-client/src/components/filters/FiltersMenu.jsx
+++ b/packages/desktop-client/src/components/filters/FiltersMenu.jsx
@@ -42,6 +42,7 @@ import { updateFilterReducer } from './updateFilterReducer';
import { GenericInput } from '@desktop-client/components/util/GenericInput';
import { useDateFormat } from '@desktop-client/hooks/useDateFormat';
+import { useFormat } from '@desktop-client/hooks/useFormat';
import { useTransactionFilters } from '@desktop-client/hooks/useTransactionFilters';
let isDatepickerClick = false;
@@ -68,6 +69,7 @@ function ConfigureField({
onApply,
}) {
const { t } = useTranslation();
+ const format = useFormat();
const [subfield, setSubfield] = useState(initialSubfield);
const inputRef = useRef();
const prevOp = useRef(null);
@@ -222,10 +224,33 @@ function ConfigureField({
<Form
onSubmit={e => {
e.preventDefault();
+
+ let submitValue = value;
+
+ if (field === 'amount' && inputRef.current) {
+ try {
+ if (inputRef.current.getCurrentAmount) {
+ submitValue = inputRef.current.getCurrentAmount();
+ } else {
+ const rawValue = inputRef.current.value || '';
+ const parsed = format.fromEdit(rawValue, null);
+ if (parsed == null) {
+ submitValue = value; // keep previous if parsing failed
+ } else {
+ const opts = subfieldToOptions(field, subfield);
+ submitValue =
+ opts?.inflow || opts?.outflow ? Math.abs(parsed) : parsed;
+ }
+ }
+ } catch {
+ submitValue = value;
+ }
+ }
+
onApply({
field,
op,
- value,
+ value: submitValue,
options: subfieldToOptions(field, subfield),
});
}}
@@ -244,9 +269,11 @@ function ConfigureField({
? 'string'
: type
}
+ numberFormatType="currency"
value={formattedValue}
multi={op === 'oneOf' || op === 'notOneOf'}
op={op}
+ options={subfieldToOptions(field, subfield)}
style={{ marginTop: 10 }}
onChange={v => {
dispatch({ type: 'set-value', value: v });
diff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsx
index 71688ab22f..70c1600f22 100644
--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx
+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx
@@ -48,11 +48,6 @@ import {
isValidOp,
getValidOps,
} from 'loot-core/shared/rules';
-import {
- integerToCurrency,
- integerToAmount,
- amountToInteger,
-} from 'loot-core/shared/util';
import {
type RuleEntity,
type NewRuleEntity,
@@ -66,6 +61,7 @@ import { DisplayId } from '@desktop-client/components/util/DisplayId';
import { GenericInput } from '@desktop-client/components/util/GenericInput';
import { useDateFormat } from '@desktop-client/hooks/useDateFormat';
import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';
+import { useFormat } from '@desktop-client/hooks/useFormat';
import {
useSchedules,
type ScheduleStatusType,
@@ -360,14 +356,15 @@ function ConditionEditor({
);
}
-function formatAmount(amount) {
+function formatAmount(amount, format) {
if (!amount) {
- return integerToCurrency(0);
+ return format(0, 'financial');
} else if (typeof amount === 'number') {
- return integerToCurrency(amount);
+ return format(amount, 'financial');
} else {
- return `${integerToCurrency(amount.num1)} to ${integerToCurrency(
+ return `${format(amount.num1, 'financial')} to ${format(
amount.num2,
+ 'financial',
)}`;
}
}
@@ -375,6 +372,7 @@ function formatAmount(amount) {
function ScheduleDescription({ id }) {
const { isNarrowWidth } = useResponsive();
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
+ const format = useFormat();
const scheduleQuery = useMemo(
() => q('schedules').filter({ id }).select('*'),
[id],
@@ -423,7 +421,7 @@ function ScheduleDescription({ id }) {
<Text style={{ flexShrink: 0 }}>
<Text> — </Text>
- <Trans>Amount:</Trans> {formatAmount(schedule._amount)}
+ <Trans>Amount:</Trans> {formatAmount(schedule._amount, format)}
</Text>
<Text style={{ flexShrink: 0 }}>
@@ -824,13 +822,13 @@ function ConditionsList({
// behavior and we can probably get rid of `makeValue`
return makeValue(
{
- num1: amountToInteger(cond.value),
- num2: amountToInteger(cond.value),
+ num1: cond.value,
+ num2: cond.value,
},
{ ...cond, op: value },
);
} else if (cond.op === 'isbetween' && op !== 'isbetween') {
- return makeValue(integerToAmount(cond.value.num1 || 0), {
+ return makeValue(cond.value.num1 || 0, {
...cond,
op: value,
});
diff --git a/packages/desktop-client/src/components/rules/Value.tsx b/packages/desktop-client/src/components/rules/Value.tsx
index 21f85c5d4d..a4ae662a61 100644
--- a/packages/desktop-client/src/components/rules/Value.tsx
+++ b/packages/desktop-client/src/components/rules/Value.tsx
@@ -8,12 +8,12 @@ import { format as formatDate, parseISO } from 'date-fns';
import { getMonthYearFormat } from 'loot-core/shared/months';
import { getRecurringDescription } from 'loot-core/shared/schedules';
-import { integerToCurrency } from 'loot-core/shared/util';
import { Link } from '@desktop-client/components/common/Link';
import { useAccounts } from '@desktop-client/hooks/useAccounts';
import { useCategories } from '@desktop-client/hooks/useCategories';
import { useDateFormat } from '@desktop-client/hooks/useDateFormat';
+import { useFormat } from '@desktop-client/hooks/useFormat';
import { useLocale } from '@desktop-client/hooks/useLocale';
import { usePayees } from '@desktop-client/hooks/usePayees';
@@ -38,6 +38,7 @@ export function Value<T>({
style,
}: ValueProps<T>) {
const { t } = useTranslation();
+ const format = useFormat();
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const payees = usePayees();
const { list: categories } = useCategories();
@@ -73,7 +74,7 @@ export function Value<T>({
} else {
switch (field) {
case 'amount':
- return integerToCurrency(value);
+ return format(value, 'financial');
case 'date':
if (value) {
if (value.frequency) {
diff --git a/packages/desktop-client/src/components/util/AmountInput.tsx b/packages/desktop-client/src/components/util/AmountInput.tsx
index 0df7a5283c..77816f9b79 100644
--- a/packages/desktop-client/src/components/util/AmountInput.tsx
+++ b/packages/desktop-client/src/components/util/AmountInput.tsx
@@ -5,8 +5,9 @@ import React, {
useState,
useEffect,
type FocusEventHandler,
- type KeyboardEventHandler,
+ type KeyboardEvent,
type CSSProperties,
+ useCallback,
} from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,22 +18,19 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { css, cx } from '@emotion/css';
-import { evalArithmetic } from 'loot-core/shared/arithmetic';
-import { amountToInteger, appendDecimals } from 'loot-core/shared/util';
-
import { useFormat } from '@desktop-client/hooks/useFormat';
import { useMergedRefs } from '@desktop-client/hooks/useMergedRefs';
-import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
type AmountInputProps = {
id?: string;
inputRef?: Ref<HTMLInputElement>;
value: number;
zeroSign?: '-' | '+';
+ sign?: '-' | '+';
onChangeValue?: (value: string) => void;
onFocus?: FocusEventHandler<HTMLInputElement>;
onBlur?: FocusEventHandler<HTMLInputElement>;
- onEnter?: KeyboardEventHandler<HTMLInputElement>;
+ onEnter?: (event: KeyboardEvent<HTMLInputElement>, amount?: number) => void;
onUpdate?: (amount: number) => void;
style?: CSSProperties;
inputStyle?: CSSProperties;
@@ -47,6 +45,7 @@ export function AmountInput({
inputRef,
value: initialValue,
zeroSign = '-', // + or -
+ sign,
onFocus,
onBlur,
onChangeValue,
@@ -61,20 +60,32 @@ export function AmountInput({
}: AmountInputProps) {
const { t } = useTranslation();
const format = useFormat();
- const [symbol, setSymbol] = useState<'+' | '-'>(
- initialValue === 0 ? zeroSign : initialValue > 0 ? '+' : '-',
- );
+ const [symbol, setSymbol] = useState<'+' | '-'>(() => {
+ if (sign) return sign;
+ return initialValue === 0 ? zeroSign : initialValue > 0 ? '+' : '-';
+ });
const [isFocused, setIsFocused] = useState(focused ?? false);
- const initialValueAbsolute = format(Math.abs(initialValue || 0), 'financial');
- const [value, setValue] = useState(initialValueAbsolute);
- useEffect(() => setValue(initialValueAbsolute), [initialValueAbsolute]);
+ const getDisplayValue = useCallback(
+ (value: number, isEditing: boolean) => {
+ const absoluteValue = Math.abs(value || 0);
+ return isEditing
+ ? format.forEdit(absoluteValue)
+ : format(absoluteValue, 'financial');
+ },
+ [format],
+ );
+
+ const [value, setValue] = useState(getDisplayValue(initialValue, false));
+ useEffect(
+ () => setValue(getDisplayValue(initialValue, isFocused)),
+ [initialValue, isFocused, getDisplayValue],
+ );
const buttonRef = useRef(null);
const ref = useRef<HTMLInputElement>(null);
const mergedRef = useMergedRefs<HTMLInputElement>(inputRef, ref);
- const [hideFraction] = useSyncedPref('hideFraction');
useEffect(() => {
if (focused) {
@@ -82,7 +93,30 @@ export function AmountInput({
}
}, [focused]);
+ useEffect(() => {
+ if (sign) {
+ setSymbol(sign);
+ }
+ }, [sign]);
+
+ const getAmount = useCallback(() => {
+ const signedValued = symbol === '-' ? symbol + value : value;
+ return format.fromEdit(signedValued, 0);
+ }, [symbol, value, format]);
+
+ useEffect(() => {
+ if (ref.current) {
+ (
+ ref.current as HTMLInputElement & { getCurrentAmount?: () => number }
+ ).getCurrentAmount = () => getAmount();
+ }
+ }, [getAmount]);
+
function onSwitch() {
+ if (sign) {
+ return;
+ }
+
const amount = getAmount();
if (amount === 0) {
setSymbol(symbol === '+' ? '-' : '+');
@@ -90,26 +124,35 @@ export function AmountInput({
fireUpdate(amount * -1);
}
- function getAmount() {
- const signedValued = symbol === '-' ? symbol + value : value;
- return amountToInteger(evalArithmetic(signedValued));
- }
-
function onInputTextChange(val) {
- val = autoDecimals
- ? appendDecimals(val, String(hideFraction) === 'true')
- : val;
- setValue(val ? val : '');
- onChangeValue?.(val);
+ let newText = val;
+ if (autoDecimals) {
+ const digits = val.replace(/\D/g, '');
+ if (digits === '') {
+ newText = '';
+ } else {
+ const intValue = parseInt(digits, 10);
+ newText = format.forEdit(intValue);
+ }
+ }
+
+ setValue(newText || '');
+ onChangeValue?.(newText);
}
function fireUpdate(amount) {
onUpdate?.(amount);
- if (amount > 0) {
- setSymbol('+');
- } else if (amount < 0) {
- setSymbol('-');
+
+ if (sign) {
+ setSymbol(sign);
+ } else {
+ if (amount > 0) {
+ setSymbol('+');
+ } else if (amount < 0) {
+ setSymbol('-');
+ }
}
+ setValue(format(Math.abs(amount), 'financial'));
}
function onInputAmountBlur(e) {
@@ -136,7 +179,7 @@ export function AmountInput({
>
<Button
variant="bare"
- isDisabled={disabled}
+ isDisabled={disabled || !!sign}
aria-label={symbol === '-' ? t('Make positive') : t('Make negative')}
style={{ padding: '0 7px' }}
onPress={onSwitch}
@@ -172,6 +215,7 @@ export function AmountInput({
)}
onFocus={e => {
setIsFocused(true);
+ setValue(format.forEdit(Math.abs(initialValue ?? 0)));
onFocus?.(e);
}}
onBlur={e => {
@@ -179,9 +223,9 @@ export function AmountInput({
onInputAmountBlur(e);
}}
onEnter={(_, e) => {
- onEnter?.(e);
const amount = getAmount();
fireUpdate(amount);
+ onEnter?.(e, amount);
}}
onChangeValue={onInputTextChange}
/>
diff --git a/packages/desktop-client/src/components/util/GenericInput.jsx b/packages/desktop-client/src/components/util/GenericInput.jsx
index c976c99a1f..b1f971c581 100644
--- a/packages/desktop-client/src/components/util/GenericInput.jsx
+++ b/packages/desktop-client/src/components/util/GenericInput.jsx
@@ -6,7 +6,6 @@ import { Input } from '@actual-app/components/input';
import { View } from '@actual-app/components/view';
import { getMonthYearFormat } from 'loot-core/shared/months';
-import { integerToAmount, amountToInteger } from 'loot-core/shared/util';
import { AmountInput } from './AmountInput';
import { PercentInput } from './PercentInput';
@@ -37,6 +36,7 @@ export function GenericInput({
style,
onChange,
op = undefined,
+ options = undefined,
}) {
const dispatch = useDispatch();
const { isNarrowWidth } = useResponsive();
@@ -67,8 +67,9 @@ export function GenericInput({
return (
<AmountInput
inputRef={ref}
- value={amountToInteger(value)}
- onUpdate={v => onChange(integerToAmount(v))}
+ value={value}
+ onUpdate={v => onChange(v)}
+ sign={options?.inflow || options?.outflow ? '+' : undefined}
/>
);
case 'percentage':
diff --git a/packages/loot-core/src/shared/rules.ts b/packages/loot-core/src/shared/rules.ts
index 24dd2fbf82..6cd007ee36 100644
--- a/packages/loot-core/src/shared/rules.ts
+++ b/packages/loot-core/src/shared/rules.ts
@@ -3,13 +3,6 @@ import { t } from 'i18next';
import { FieldValueTypes, RuleConditionOp } from '../types/models';
-import {
- integerToAmount,
- amountToInteger,
- currencyToAmount,
- getNumberFormat,
-} from './util';
-
// For now, this info is duplicated from the backend. Figure out how
// to share it later.
const TYPE_INFO = {
@@ -293,22 +286,14 @@ export function sortNumbers(num1, num2) {
export function parse(item) {
if (item.op === 'set-split-amount') {
if (item.options.method === 'fixed-amount') {
- return { ...item, value: item.value && integerToAmount(item.value) };
+ return { ...item };
}
return item;
}
switch (item.type) {
case 'number': {
- let parsed = item.value;
- if (
- item.field === 'amount' &&
- item.op !== 'isbetween' &&
- parsed != null
- ) {
- parsed = integerToAmount(parsed);
- }
- return { ...item, value: parsed };
+ return { ...item };
}
case 'string': {
const parsed = item.value == null ? '' : item.value;
@@ -329,7 +314,6 @@ export function unparse({ error, inputKey, ...item }) {
if (item.options.method === 'fixed-amount') {
return {
...item,
- value: item.value && amountToInteger(item.value),
};
}
if (item.options.method === 'fixed-percent') {
@@ -343,23 +327,7 @@ export function unparse({ error, inputKey, ...item }) {
switch (item.type) {
case 'number': {
- let unparsed = item.value;
- if (item.field === 'amount' && item.op !== 'isbetween') {
- // Handle both string (formatted) and number inputs
- if (typeof unparsed === 'string') {
- // Convert formatted string back to number first
- unparsed = currencyToAmount(unparsed);
- if (unparsed !== null && !isNaN(unparsed)) {
- unparsed = amountToInteger(unparsed);
- } else {
- unparsed = null;
- }
- } else {
- unparsed = amountToInteger(unparsed);
- }
- }
-
- return { ...item, value: unparsed };
+ return { ...item };
}
case 'string': {
const unparsed = item.value == null ? '' : item.value;
@@ -376,38 +344,16 @@ export function unparse({ error, inputKey, ...item }) {
}
export function makeValue(value, cond) {
- switch (cond.type) {
- case 'number': {
- if (cond.op !== 'isbetween') {
- const stringValue = String(value);
- const { decimalSeparator } = getNumberFormat();
-
- // preserve trailing decimal separator to allow decimal input during typing
- if (stringValue && stringValue.endsWith(decimalSeparator)) {
- return {
- ...cond,
- error: null,
- value: stringValue,
- };
- }
-
- return {
- ...cond,
- error: null,
- value: value ? currencyToAmount(stringValue) || 0 : 0,
- };
- }
- break;
- }
- default:
- }
-
const isMulti = ['oneOf', 'notOneOf'].includes(cond.op);
if (isMulti) {
return { ...cond, error: null, value: value || [] };
}
+ if (cond.type === 'number' && value == null) {
+ return { ...cond, error: null, value: 0 };
+ }
+
return { ...cond, error: null, value };
}
diff --git a/upcoming-release-notes/5639.md b/upcoming-release-notes/5639.md
new file mode 100644
index 0000000000..ec27534f06
--- /dev/null
+++ b/upcoming-release-notes/5639.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [misu-dev]
+---
+
+Adds currency display to the rules