Skip to content

A local-first personal finance app

Formula feedback improvements (#7989)

lelemm674c6f1b53b4
diff --git a/.github/actions/docs-spelling/expect.txt b/.github/actions/docs-spelling/expect.txt
index a356ad365b..b0aea401cf 100644
--- a/.github/actions/docs-spelling/expect.txt
+++ b/.github/actions/docs-spelling/expect.txt
@@ -213,3 +213,5 @@ WOR
worktree
youngcw
zizmor
+FORMATCURRENCY
+FORMATNUMBER
diff --git a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx
index 41037fcb9c..16b91360bc 100644
--- a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx
+++ b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx
@@ -13,7 +13,12 @@ import {
} from '@codemirror/language';
import type { StreamParser } from '@codemirror/language';
import type { Extension } from '@codemirror/state';
-import { EditorView, hoverTooltip, tooltips } from '@codemirror/view';
+import {
+ EditorView,
+ hoverTooltip,
+ tooltips,
+ ViewPlugin,
+} from '@codemirror/view';
import type { Tooltip } from '@codemirror/view';
import { tags } from '@lezer/highlight';
import { t } from 'i18next';
@@ -70,20 +75,11 @@ function FieldTooltip({ label, info }: { label: string; info: string }) {
type FormulaMode = 'query' | 'transaction';
-// Function categories for different syntax highlighting
const MATH_FUNCTIONS = new Set([
'SUM',
'AVERAGE',
- 'AVERAGEA',
- 'COUNT',
- 'COUNTA',
- 'COUNTBLANK',
- 'COUNTIF',
- 'COUNTIFS',
'MAX',
- 'MAXA',
'MIN',
- 'MINA',
'ABS',
'ROUND',
'ROUNDUP',
@@ -105,19 +101,6 @@ const MATH_FUNCTIONS = new Set([
'LOG10',
'EXP',
'PRODUCT',
- 'SUMIF',
- 'SUMIFS',
- 'SUMPRODUCT',
- 'SUMSQ',
- 'MEDIAN',
- 'MODE',
- 'STDEV',
- 'STDEVP',
- 'VAR',
- 'VARP',
- 'PERCENTILE',
- 'QUARTILE',
- 'RANK',
'PMT',
'FV',
'PV',
@@ -143,6 +126,8 @@ const LOGICAL_FUNCTIONS = new Set([
const TEXT_FUNCTIONS = new Set([
'TEXT',
'FIXED',
+ 'FORMATNUMBER',
+ 'FORMATCURRENCY',
'CONCATENATE',
'LEFT',
'RIGHT',
@@ -192,11 +177,6 @@ const QUERY_FUNCTIONS = new Set([
'QUERY_EXTRACT_CATEGORIES',
'QUERY_EXTRACT_TIMEFRAME_START',
'QUERY_EXTRACT_TIMEFRAME_END',
- 'LOOKUP',
- 'VLOOKUP',
- 'HLOOKUP',
- 'INDEX',
- 'MATCH',
'CHOOSE',
'ISBLANK',
'ISERROR',
@@ -204,7 +184,6 @@ const QUERY_FUNCTIONS = new Set([
'ISNUMBER',
'ISTEXT',
'ISLOGICAL',
- 'ISREF',
'ISEVEN',
'ISODD',
]);
@@ -296,7 +275,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Transaction amount in cents. Use for calculations and comparisons.\n\nExample: `=amount / 100` to get dollar value',
+ 'Transaction amount in cents. Use for calculations and comparisons.\n\nExample: =amount / 100 to get dollar value',
),
},
{
@@ -305,7 +284,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Transaction date in YYYY-MM-DD format. Use with date functions.\n\nExample: `=TEXT(date, "MMMM")` to get month name',
+ 'Transaction date in YYYY-MM-DD format. Use with date functions.\n\nExample: =TEXT(date, "MMMM") to get month name',
),
},
{
@@ -314,7 +293,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Transaction notes/memo text. Use for string operations.\n\nExample: `=UPPER(notes)` to convert to uppercase',
+ 'Transaction notes/memo text. Use for string operations.\n\nExample: =UPPER(notes) to convert to uppercase',
),
},
{
@@ -323,7 +302,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Original imported payee name from bank import. Contains the raw text before matching.\n\nExample: `=LEFT(imported_payee, 10)` to get first 10 characters',
+ 'Original imported payee name from bank import. Contains the raw text before matching.\n\nExample: =LEFT(imported_payee, 10) to get first 10 characters',
),
},
{
@@ -332,7 +311,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Payee ID (string). The ID of the payee.\n\nExample: `=CONCATENATE("Payment to ", payee)`',
+ 'Payee ID (string). The ID of the payee.\n\nExample: =CONCATENATE("Payment to ", payee)',
),
},
{
@@ -341,7 +320,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Payee name (string). The human-readable name of the payee.\n\nExample: `=UPPER(payee_name)` or `=CONCATENATE("Payment to ", payee_name)`',
+ 'Payee name (string). The human-readable name of the payee.\n\nExample: =UPPER(payee_name) or =CONCATENATE("Payment to ", payee_name)',
),
},
{
@@ -350,7 +329,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Account ID (string). The ID of the account.\n\nExample: `=CONCATENATE("Paid from ", account)`',
+ 'Account ID (string). The ID of the account.\n\nExample: =CONCATENATE("Paid from ", account)',
),
},
{
@@ -359,7 +338,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Account name (string). The human-readable name of the account.\n\nExample: `=CONCATENATE("Paid from ", account_name)`',
+ 'Account name (string). The human-readable name of the account.\n\nExample: =CONCATENATE("Paid from ", account_name)',
),
},
{
@@ -368,7 +347,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Category ID (string). The ID of the category.\n\nExample: `=IF(category="Groceries", "Food", "Other")`',
+ 'Category ID (string). The ID of the category.\n\nExample: =IF(category="Groceries", "Food", "Other")',
),
},
{
@@ -377,7 +356,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Category Name (string). The human-readable name of the category.\n\nExample: `=IF(category_name="Groceries", "Food", "Other")`',
+ 'Category Name (string). The human-readable name of the category.\n\nExample: =IF(category_name="Groceries", "Food", "Other")',
),
},
{
@@ -386,7 +365,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Boolean cleared status. TRUE if transaction is cleared, FALSE otherwise.\n\nExample: `=IF(cleared, "Cleared", "Pending")`',
+ 'Boolean cleared status. TRUE if transaction is cleared, FALSE otherwise.\n\nExample: =IF(cleared, "Cleared", "Pending")',
),
},
{
@@ -404,7 +383,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'Account balance as of the date of the transaction, excluding the transaction amount. Use for calculations and comparisons.\n\nExample: `=IF(balance < 0, "Negative Balance", "Positive Balance")`',
+ 'Account balance as of the date of the transaction, excluding the transaction amount. Use for calculations and comparisons.\n\nExample: =IF(balance < 0, "Negative Balance", "Positive Balance")',
),
},
{
@@ -413,7 +392,7 @@ const transactionFields: Completion[] = [
section: 'πŸ’° Transaction Fields',
boost: 5,
info: t(
- 'The amount of the parent transaction in cents in split transactions.\n\nExample: `=(parent_amount / 100) * .05`',
+ 'The amount of the parent transaction in cents in split transactions.\n\nExample: =(parent_amount / 100) * .05',
),
},
];
@@ -710,6 +689,7 @@ const tooltipPortalConfig =
const autocompletePopoverTheme = EditorView.baseTheme({
// Wrapper: keep transparent; the list and info panel are the actual "cards".
'.cm-tooltip.cm-tooltip-autocomplete': {
+ ...styles.darkScrollbar,
backgroundColor: 'transparent',
border: 'none',
boxShadow: 'none',
@@ -724,13 +704,12 @@ const autocompletePopoverTheme = EditorView.baseTheme({
'.cm-tooltip.cm-tooltip-autocomplete > ul': {
...styles.shadowLarge,
margin: 0,
- // Outer inset gutter for the whole list (so content never hugs the edges)
- padding: '12px',
+ padding: '5px 0',
maxHeight: '260px',
minWidth: '280px',
listStyle: 'none',
- backgroundColor: theme.menuBackground,
- color: theme.menuItemText,
+ backgroundColor: theme.menuAutoCompleteBackground,
+ color: theme.menuAutoCompleteText,
borderRadius: '6px',
overflow: 'hidden',
overflowY: 'auto',
@@ -748,44 +727,64 @@ const autocompletePopoverTheme = EditorView.baseTheme({
},
// Section headers
- '.cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection': {
- padding: '6px 10px 4px',
- fontSize: '11px',
- lineHeight: '1em',
- textTransform: 'uppercase',
- letterSpacing: '0.03em',
- color: theme.menuItemTextHeader,
- opacity: 0.9,
- marginTop: '8px',
- },
- '.cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection:first-child': {
- marginTop: 0,
- },
-
+ '.cm-tooltip.cm-tooltip-autocomplete > ul > completion-section, .cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection':
+ {
+ padding: '7px 12px 3px !important',
+ paddingLeft: '12px !important',
+ paddingRight: '12px !important',
+ fontSize: '11px',
+ lineHeight: '1em',
+ textTransform: 'uppercase',
+ letterSpacing: '0.03em',
+ color: theme.menuItemTextHeader,
+ opacity: '1 !important',
+ marginTop: '8px',
+ position: 'sticky',
+ top: 0,
+ backgroundColor: theme.menuAutoCompleteBackground,
+ borderTop: 'none !important',
+ borderBottom: 'none !important',
+ zIndex: 1,
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete > ul > completion-section:first-child, .cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection:first-child':
+ {
+ marginTop: 0,
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete > ul > completion-section::before, .cm-tooltip.cm-tooltip-autocomplete > ul > completion-section::after, .cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection::before, .cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection::after':
+ {
+ display: 'none !important',
+ },
// Completion rows
+ '.cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem, .cm-tooltip.cm-tooltip-autocomplete li[role="option"]':
+ {
+ padding: '5px 14px !important',
+ paddingLeft: '14px !important',
+ paddingRight: '14px !important',
+ lineHeight: '1.2',
+ cursor: 'default',
+ display: 'flex',
+ alignItems: 'baseline',
+ gap: '8px',
+ borderRadius: 0,
+ },
+
'.cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem': {
- padding: '8px 10px',
lineHeight: '1.2',
cursor: 'default',
display: 'flex',
alignItems: 'baseline',
gap: '8px',
- borderRadius: '4px',
+ borderRadius: 0,
},
- '.cm-tooltip.cm-tooltip-autocomplete > ul > completion-section, .cm-tooltip.cm-tooltip-autocomplete li.cm-completionSection':
+ '.cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem[aria-selected], .cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem:hover, .cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem-hover':
{
- padding: '0 !important',
- position: 'sticky',
- top: 0,
- backgroundColor: theme.menuBackground,
- opacity: '1 !important',
- zIndex: 1,
+ backgroundColor: theme.menuAutoCompleteBackgroundHover,
+ color: theme.menuAutoCompleteItemTextHover,
},
-
- '.cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem[aria-selected]': {
- backgroundColor: theme.menuItemBackgroundHover,
- color: theme.menuItemTextHover,
+ '.cm-tooltip.cm-tooltip-autocomplete li[role="option"]:hover': {
+ backgroundColor: theme.menuAutoCompleteBackgroundHover,
+ color: theme.menuAutoCompleteItemTextHover,
},
// Matched text within a label
@@ -811,7 +810,7 @@ const autocompletePopoverTheme = EditorView.baseTheme({
},
'.cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem[aria-selected] .cm-completionDetail':
{
- color: theme.menuItemTextHover,
+ color: theme.menuAutoCompleteItemTextHover,
},
// Docs panel for selected completion
@@ -830,6 +829,202 @@ const autocompletePopoverTheme = EditorView.baseTheme({
},
});
+//hack: this is a workaround to forward the pointer events to the completion item.
+//isPointInsideRect / findAutocompleteElementAtPoint / autocompletePopoverPointerHandler are needed to forward the pointer events to the completion item.
+//Otherwise the mouse interactions will not work as expected.
+function isPointInsideRect(x: number, y: number, rect: DOMRect) {
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
+}
+
+function findAutocompleteElementAtPoint(
+ document: Document,
+ selector: string,
+ x: number,
+ y: number,
+) {
+ return Array.from(document.querySelectorAll(selector)).find(element =>
+ isPointInsideRect(x, y, element.getBoundingClientRect()),
+ );
+}
+
+const autocompletePopoverPointerHandler = ViewPlugin.define(view => {
+ let hoveredCompletionItem: HTMLElement | null = null;
+
+ function setHoveredCompletionItem(completionItem: HTMLElement | null) {
+ if (hoveredCompletionItem === completionItem) {
+ return;
+ }
+
+ hoveredCompletionItem?.classList.remove('cm-completionItem-hover');
+ hoveredCompletionItem = completionItem;
+ hoveredCompletionItem?.classList.add('cm-completionItem-hover');
+ }
+
+ const handleWheel = (event: WheelEvent) => {
+ if (!(event.target instanceof Element)) {
+ return;
+ }
+
+ let scrollContainer: Element | null | undefined = event.target.closest(
+ '.cm-tooltip.cm-tooltip-autocomplete > ul',
+ );
+ if (!(scrollContainer instanceof HTMLElement)) {
+ // React Aria modals use the browser top layer, so wheel events can target
+ // modal content even when the autocomplete list is visually under the pointer.
+ scrollContainer = findAutocompleteElementAtPoint(
+ view.dom.ownerDocument,
+ '.cm-tooltip.cm-tooltip-autocomplete > ul',
+ event.clientX,
+ event.clientY,
+ );
+ }
+
+ if (!(scrollContainer instanceof HTMLElement)) {
+ return;
+ }
+
+ const canScrollY =
+ scrollContainer.scrollHeight > scrollContainer.clientHeight;
+ const canScrollX =
+ scrollContainer.scrollWidth > scrollContainer.clientWidth;
+ if (!canScrollY && !canScrollX) {
+ return;
+ }
+
+ const deltaMultiplier =
+ event.deltaMode === WheelEvent.DOM_DELTA_LINE
+ ? 16
+ : event.deltaMode === WheelEvent.DOM_DELTA_PAGE
+ ? scrollContainer.clientHeight
+ : 1;
+
+ const previousScrollTop = scrollContainer.scrollTop;
+ const previousScrollLeft = scrollContainer.scrollLeft;
+
+ scrollContainer.scrollTop += event.deltaY * deltaMultiplier;
+ scrollContainer.scrollLeft += event.deltaX * deltaMultiplier;
+
+ if (
+ scrollContainer.scrollTop !== previousScrollTop ||
+ scrollContainer.scrollLeft !== previousScrollLeft
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ };
+
+ const handleMouseDown = (event: MouseEvent) => {
+ if (!(event.target instanceof Element)) {
+ return;
+ }
+
+ if (event.target.closest('.cm-tooltip.cm-tooltip-autocomplete')) {
+ return;
+ }
+
+ const completionItem = findAutocompleteElementAtPoint(
+ view.dom.ownerDocument,
+ '.cm-tooltip.cm-tooltip-autocomplete li[role="option"], .cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem',
+ event.clientX,
+ event.clientY,
+ );
+
+ if (!(completionItem instanceof HTMLElement)) {
+ setHoveredCompletionItem(null);
+ return;
+ }
+
+ setHoveredCompletionItem(completionItem);
+
+ completionItem.dispatchEvent(
+ new MouseEvent(event.type, {
+ bubbles: true,
+ cancelable: true,
+ view: view.dom.ownerDocument.defaultView,
+ clientX: event.clientX,
+ clientY: event.clientY,
+ screenX: event.screenX,
+ screenY: event.screenY,
+ button: event.button,
+ buttons: event.buttons,
+ ctrlKey: event.ctrlKey,
+ shiftKey: event.shiftKey,
+ altKey: event.altKey,
+ metaKey: event.metaKey,
+ }),
+ );
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const handleMouseMove = (event: MouseEvent) => {
+ if (!(event.target instanceof Element)) {
+ return;
+ }
+
+ if (event.target.closest('.cm-tooltip.cm-tooltip-autocomplete')) {
+ return;
+ }
+
+ const completionItem = findAutocompleteElementAtPoint(
+ view.dom.ownerDocument,
+ '.cm-tooltip.cm-tooltip-autocomplete li[role="option"], .cm-tooltip.cm-tooltip-autocomplete li.cm-completionItem',
+ event.clientX,
+ event.clientY,
+ );
+
+ if (!(completionItem instanceof HTMLElement)) {
+ return;
+ }
+
+ completionItem.dispatchEvent(
+ new MouseEvent(event.type, {
+ bubbles: true,
+ cancelable: true,
+ view: view.dom.ownerDocument.defaultView,
+ clientX: event.clientX,
+ clientY: event.clientY,
+ screenX: event.screenX,
+ screenY: event.screenY,
+ button: event.button,
+ buttons: event.buttons,
+ ctrlKey: event.ctrlKey,
+ shiftKey: event.shiftKey,
+ altKey: event.altKey,
+ metaKey: event.metaKey,
+ }),
+ );
+ };
+
+ view.dom.ownerDocument.addEventListener('wheel', handleWheel, {
+ capture: true,
+ passive: false,
+ });
+ view.dom.ownerDocument.addEventListener('mousedown', handleMouseDown, {
+ capture: true,
+ passive: false,
+ });
+ view.dom.ownerDocument.addEventListener('mousemove', handleMouseMove, {
+ capture: true,
+ passive: true,
+ });
+
+ return {
+ destroy() {
+ view.dom.ownerDocument.removeEventListener('wheel', handleWheel, {
+ capture: true,
+ });
+ view.dom.ownerDocument.removeEventListener('mousedown', handleMouseDown, {
+ capture: true,
+ });
+ view.dom.ownerDocument.removeEventListener('mousemove', handleMouseMove, {
+ capture: true,
+ });
+ setHoveredCompletionItem(null);
+ },
+ };
+});
+
// Custom theme for categorized function highlighting (light)
const functionCategoryTheme = EditorView.baseTheme({
'&light .cm-keyword': { color: '#0066CC' }, // Math functions in blue
@@ -890,5 +1085,6 @@ export function excelFormulaExtension(
tooltipZIndexTheme,
tooltipPortalConfig,
autocompletePopoverTheme,
+ autocompletePopoverPointerHandler,
];
}
diff --git a/packages/desktop-client/src/components/formula/queryModeFunctions.ts b/packages/desktop-client/src/components/formula/queryModeFunctions.ts
index 6a236fe28c..37e5463de8 100644
--- a/packages/desktop-client/src/components/formula/queryModeFunctions.ts
+++ b/packages/desktop-client/src/components/formula/queryModeFunctions.ts
@@ -23,70 +23,20 @@ export const queryModeFunctions: Record<string, FunctionDef> = {
{ name: 'numbers', description: 'Number1, Number2, ...NumberN' },
],
},
- AVERAGEA: {
- name: 'AVERAGEA',
- description: t('Returns the average, including text and logical values.'),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
- COUNT: {
- name: 'COUNT',
- description: t('Counts the number of numeric values.'),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
- COUNTA: {
- name: 'COUNTA',
- description: t('Counts non-empty values.'),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
- COUNTBLANK: {
- name: 'COUNTBLANK',
- description: t('Counts empty cells.'),
- parameters: [{ name: 'range', description: 'Range' }],
- },
- COUNTIF: {
- name: 'COUNTIF',
- description: t('Counts cells that meet a criteria.'),
- parameters: [
- { name: 'range', description: 'Range' },
- { name: 'criteria', description: 'Criteria' },
- ],
- },
- COUNTIFS: {
- name: 'COUNTIFS',
- description: t('Counts cells that meet multiple criteria.'),
- parameters: [
- { name: 'range1', description: 'Range1' },
- { name: 'criteria1', description: 'Criteria1' },
- ],
- },
MAX: {
name: 'MAX',
- description: t('Returns the maximum value.'),
+ description: t('Returns the maximum value from numbers.'),
parameters: [
{ name: 'numbers', description: 'Number1, Number2, ...NumberN' },
],
},
- MAXA: {
- name: 'MAXA',
- description: t(
- 'Returns the maximum value, including text and logical values.',
- ),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
MIN: {
name: 'MIN',
- description: t('Returns the minimum value.'),
+ description: t('Returns the minimum value from numbers.'),
parameters: [
{ name: 'numbers', description: 'Number1, Number2, ...NumberN' },
],
},
- MINA: {
- name: 'MINA',
- description: t(
- 'Returns the minimum value, including text and logical values.',
- ),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
ABS: {
name: 'ABS',
description: t('Returns the absolute value of a number.'),
@@ -251,105 +201,6 @@ export const queryModeFunctions: Record<string, FunctionDef> = {
{ name: 'numbers', description: 'Number1, Number2, ...NumberN' },
],
},
- SUMIF: {
- name: 'SUMIF',
- description: t('Sums cells that meet a criteria.'),
- parameters: [
- { name: 'range', description: 'Range' },
- { name: 'criteria', description: 'Criteria' },
- { name: 'sum_range', description: 'SumRange' },
- ],
- },
- SUMIFS: {
- name: 'SUMIFS',
- description: t('Sums cells that meet multiple criteria.'),
- parameters: [
- { name: 'sum_range', description: 'SumRange' },
- { name: 'range1', description: 'Range1' },
- { name: 'criteria1', description: 'Criteria1' },
- ],
- },
- SUMPRODUCT: {
- name: 'SUMPRODUCT',
- description: t('Multiplies corresponding elements and returns the sum.'),
- parameters: [
- { name: 'array1', description: 'Array1' },
- { name: 'array2', description: 'Array2' },
- ],
- },
- SUMSQ: {
- name: 'SUMSQ',
- description: t('Returns the sum of the squares.'),
- parameters: [
- { name: 'numbers', description: 'Number1, Number2, ...NumberN' },
- ],
- },
-
- // Statistical Functions
- MEDIAN: {
- name: 'MEDIAN',
- description: t('Returns the median value.'),
- parameters: [
- { name: 'numbers', description: 'Number1, Number2, ...NumberN' },
- ],
- },
- MODE: {
- name: 'MODE',
- description: t('Returns the most frequently occurring value.'),
- parameters: [
- { name: 'numbers', description: 'Number1, Number2, ...NumberN' },
- ],
- },
- STDEV: {
- name: 'STDEV',
- description: t('Returns the standard deviation of a sample.'),
- parameters: [
- { name: 'numbers', description: 'Number1, Number2, ...NumberN' },
- ],
- },
- STDEVP: {
- name: 'STDEVP',
- description: t('Returns the standard deviation of a population.'),
- parameters: [
- { name: 'numbers', description: 'Number1, Number2, ...NumberN' },
- ],
- },
- VAR: {
- name: 'VAR',
- description: t('Returns the variance of a sample.'),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
- VARP: {
- name: 'VARP',
- description: t('Returns the variance of a population.'),
- parameters: [{ name: 'values', description: 'Value1, Value2, ...ValueN' }],
- },
- PERCENTILE: {
- name: 'PERCENTILE',
- description: t('Returns the k-th percentile.'),
- parameters: [
- { name: 'array', description: 'Array' },
- { name: 'k', description: 'K' },
- ],
- },
- QUARTILE: {
- name: 'QUARTILE',
- description: t('Returns the quartile of a dataset.'),
- parameters: [
- { name: 'array', description: 'Array' },
- { name: 'quart', description: 'Quart' },
- ],
- },
- RANK: {
- name: 'RANK',
- description: t('Returns the rank of a number in a list.'),
- parameters: [
- { name: 'value', description: 'Value' },
- { name: 'array', description: 'Array' },
- { name: 'order', description: 'Order' },
- ],
- },
-
// Logical Functions
IF: {
name: 'IF',
@@ -567,6 +418,60 @@ export const queryModeFunctions: Record<string, FunctionDef> = {
{ name: 'decimals', description: 'Decimals' },
],
},
+ FORMATNUMBER: {
+ name: 'FORMATNUMBER',
+ description: t(
+ 'Formats a number with thousands separators. Uses your app number format settings by default.',
+ ),
+ parameters: [
+ { name: 'value', description: 'Number to format' },
+ {
+ name: 'decimals',
+ description: 'Decimal places (optional, uses app settings)',
+ },
+ {
+ name: 'thousandsSeparator',
+ description: 'Thousands separator (optional, uses app settings)',
+ },
+ {
+ name: 'decimalSeparator',
+ description: 'Decimal separator (optional, uses app settings)',
+ },
+ ],
+ },
+ FORMATCURRENCY: {
+ name: 'FORMATCURRENCY',
+ description: t(
+ 'Formats a number as currency. Uses your app currency and number format settings by default.',
+ ),
+ parameters: [
+ { name: 'value', description: 'Number to format' },
+ {
+ name: 'currencySymbol',
+ description: 'Currency symbol (optional, uses app settings)',
+ },
+ {
+ name: 'decimals',
+ description: 'Decimal places (optional, uses app settings)',
+ },
+ {
+ name: 'thousandsSeparator',
+ description: 'Thousands separator (optional, uses app settings)',
+ },
+ {
+ name: 'decimalSeparator',
+ description: 'Decimal separator (optional, uses app settings)',
+ },
+ {
+ name: 'symbolPosition',
+ description: '"before" or "after" (optional, uses app settings)',
+ },
+ {
+ name: 'spaceBetweenAmountAndSymbol',
+ description: 'TRUE or FALSE (optional, uses app settings)',
+ },
+ ],
+ },
REPT: {
name: 'REPT',
description: t('Repeats text specified number of times.'),
@@ -686,61 +591,13 @@ export const queryModeFunctions: Record<string, FunctionDef> = {
{ name: 'type', description: 'Type' },
],
},
-
- // Lookup and Reference
- VLOOKUP: {
- name: 'VLOOKUP',
- description: t('Searches vertically in first column and returns value.'),
- parameters: [
- { name: 'lookup_value', description: 'LookupValue' },
- { name: 'table_array', description: 'TableArray' },
- { name: 'col_index', description: 'ColIndex' },
- { name: 'range_lookup', description: 'RangeLookup' },
- ],
- },
- HLOOKUP: {
- name: 'HLOOKUP',
- description: t('Searches horizontally in first row and returns value.'),
- parameters: [
- { name: 'lookup_value', description: 'LookupValue' },
- { name: 'table_array', description: 'TableArray' },
- { name: 'row_index', description: 'RowIndex' },
- { name: 'range_lookup', description: 'RangeLookup' },
- ],
- },
- INDEX: {
- name: 'INDEX',
- description: t('Returns value at specified row and column.'),
- parameters: [
- { name: 'array', description: 'Array' },
- { name: 'row', description: 'Row' },
- { name: 'column', description: 'Column' },
- ],
- },
- MATCH: {
- name: 'MATCH',
- description: t('Returns position of value in array.'),
- parameters: [
- { name: 'lookup_value', description: 'LookupValue' },
- { name: 'lookup_array', description: 'LookupArray' },
- { name: 'match_type', description: 'MatchType' },
- ],
- },
CHOOSE: {
name: 'CHOOSE',
description: t('Returns value from list based on index.'),
parameters: [
- { name: 'index', description: 'Index' },
+ { name: 'index', description: 'Index (1-based)' },
{ name: 'value1', description: 'Value1' },
- { name: 'value2', description: 'Value2' },
- ],
- },
- LOOKUP: {
- name: 'LOOKUP',
- description: t('Looks up values in a vector or array.'),
- parameters: [
- { name: 'lookup_value', description: 'LookupValue' },
- { name: 'lookup_vector', description: 'LookupVector' },
+ { name: 'value2', description: 'Value2, ...ValueN' },
],
},
diff --git a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts b/packages/desktop-client/src/components/formula/transactionModeFunctions.ts
index 3ddc6540a5..a094e14a22 100644
--- a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts
+++ b/packages/desktop-client/src/components/formula/transactionModeFunctions.ts
@@ -142,6 +142,60 @@ export const transactionModeFunctions: Record<string, FunctionDef> = {
{ name: 'decimals', description: 'Decimals' },
],
},
+ FORMATNUMBER: {
+ name: 'FORMATNUMBER',
+ description: t(
+ 'Formats a number with thousands separators. Uses your app number format settings by default.',
+ ),
+ parameters: [
+ { name: 'value', description: 'Number to format' },
+ {
+ name: 'decimals',
+ description: 'Decimal places (optional, uses app settings)',
+ },
+ {
+ name: 'thousandsSeparator',
+ description: 'Thousands separator (optional, uses app settings)',
+ },
+ {
+ name: 'decimalSeparator',
+ description: 'Decimal separator (optional, uses app settings)',
+ },
+ ],
+ },
+ FORMATCURRENCY: {
+ name: 'FORMATCURRENCY',
+ description: t(
+ 'Formats a number as currency. Uses your app currency and number format settings by default.',
+ ),
+ parameters: [
+ { name: 'value', description: 'Number to format' },
+ {
+ name: 'currencySymbol',
+ description: 'Currency symbol (optional, uses app settings)',
+ },
+ {
+ name: 'decimals',
+ description: 'Decimal places (optional, uses app settings)',
+ },
+ {
+ name: 'thousandsSeparator',
+ description: 'Thousands separator (optional, uses app settings)',
+ },
+ {
+ name: 'decimalSeparator',
+ description: 'Decimal separator (optional, uses app settings)',
+ },
+ {
+ name: 'symbolPosition',
+ description: '"before" or "after" (optional, uses app settings)',
+ },
+ {
+ name: 'spaceBetweenAmountAndSymbol',
+ description: 'TRUE or FALSE (optional, uses app settings)',
+ },
+ ],
+ },
REPT: {
name: 'REPT',
description: t('Repeats text specified number of times.'),
@@ -496,11 +550,6 @@ export const transactionModeFunctions: Record<string, FunctionDef> = {
description: t('Returns TRUE if value is logical (TRUE/FALSE).'),
parameters: [{ name: 'value', description: 'Value' }],
},
- ISREF: {
- name: 'ISREF',
- description: t('Returns TRUE if value is a reference.'),
- parameters: [{ name: 'value', description: 'Value' }],
- },
ISEVEN: {
name: 'ISEVEN',
description: t('Returns TRUE if number is even.'),
diff --git a/packages/desktop-client/src/components/reports/FormulaResult.tsx b/packages/desktop-client/src/components/reports/FormulaResult.tsx
index 33941b5f90..d90dd36572 100644
--- a/packages/desktop-client/src/components/reports/FormulaResult.tsx
+++ b/packages/desktop-client/src/components/reports/FormulaResult.tsx
@@ -81,12 +81,15 @@ export function FormulaResult({
if (width <= 0 || height <= 0) return;
- // Get the actual display value length at calculation time
- const valueLength = displayValue.length || 1; // Avoid division by zero
+ // Check if the display value contains line breaks and calculate font size accordingly.
+ const lines = displayValue.split(/\r?\n/);
+ const lineCount = lines.length;
+ const longestLineLength = Math.max(...lines.map(line => line.length), 1);
+ // Calculate font size based on the longest line and number of lines
const calculatedFontSize = Math.min(
- (width * FONT_SIZE_SCALE_FACTOR) / valueLength,
- height, // Ensure the text fits vertically by using the height as the limiting factor
+ (width * FONT_SIZE_SCALE_FACTOR) / longestLineLength,
+ height / lineCount, // Divide height by number of lines to fit all lines
);
if (calculatedFontSize > 0) {
@@ -184,7 +187,14 @@ export function FormulaResult({
{!showContent ? (
<ReportCardValueSkeleton />
) : (
- <span aria-hidden="true">
+ <span
+ aria-hidden="true"
+ style={{
+ whiteSpace: 'pre-wrap',
+ textAlign: 'center',
+ wordBreak: 'break-word',
+ }}
+ >
<PrivacyFilter>{displayValue}</PrivacyFilter>
</span>
)}
diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsx
index 581ce581cf..5c44bc2aaa 100644
--- a/packages/desktop-client/src/components/reports/Overview.tsx
+++ b/packages/desktop-client/src/components/reports/Overview.tsx
@@ -78,7 +78,11 @@ function isCustomReportWidget(
}
function getWidgetMinHeight(widget: DashboardWidgetEntity) {
- if (isCustomReportWidget(widget) || widget.type === 'markdown-card') {
+ if (
+ isCustomReportWidget(widget) ||
+ widget.type === 'markdown-card' ||
+ widget.type === 'formula-card'
+ ) {
return 1;
}
@@ -90,6 +94,10 @@ function getWidgetMinHeight(widget: DashboardWidgetEntity) {
}
function getWidgetMinWidth(widget: DashboardWidgetEntity) {
+ if (widget.type === 'formula-card') {
+ return 1;
+ }
+
if (isCustomReportWidget(widget) || widget.type === 'markdown-card') {
return 2;
}
diff --git a/packages/desktop-client/src/components/reports/reports/Formula.tsx b/packages/desktop-client/src/components/reports/reports/Formula.tsx
index 8483304e52..5f3ecbbfff 100644
--- a/packages/desktop-client/src/components/reports/reports/Formula.tsx
+++ b/packages/desktop-client/src/components/reports/reports/Formula.tsx
@@ -9,6 +9,7 @@ import { Input } from '@actual-app/components/input';
import { Select } from '@actual-app/components/select';
import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
+import { Toggle } from '@actual-app/components/toggle';
import { View } from '@actual-app/components/view';
import type { FormulaWidget } from '@actual-app/core/types/models';
@@ -70,6 +71,7 @@ function FormulaInner({ widget }: FormulaInnerProps) {
const [staticFontSize, setStaticFontSize] = useState<number>(
widget?.meta?.staticFontSize || 32,
);
+ const [showTitle, setShowTitle] = useState(widget?.meta?.showTitle ?? true);
const [colorFormula, setColorFormula] = useState(
widget?.meta?.colorFormula || '',
);
@@ -136,6 +138,7 @@ function FormulaInner({ widget }: FormulaInnerProps) {
queries: queriesRef.current,
fontSizeMode,
staticFontSize,
+ showTitle,
colorFormula,
},
},
@@ -165,6 +168,7 @@ function FormulaInner({ widget }: FormulaInnerProps) {
queries: queriesRef.current,
fontSizeMode,
staticFontSize,
+ showTitle,
colorFormula,
},
},
@@ -250,6 +254,24 @@ function FormulaInner({ widget }: FormulaInnerProps) {
flexDirection: 'column',
}}
>
+ <View style={{ padding: 20, paddingBottom: 0 }}>
+ <div
+ style={{
+ fontSize: 13,
+ color: theme.pageTextSubdued,
+ marginBottom: 5,
+ }}
+ >
+ <label htmlFor="formula-show-title">
+ <Trans>Show title:</Trans>
+ </label>
+ </div>
+ <Toggle
+ id="formula-show-title"
+ isOn={showTitle}
+ onToggle={setShowTitle}
+ />
+ </View>
<View
style={{
padding: 20,
@@ -290,7 +312,6 @@ function FormulaInner({ widget }: FormulaInnerProps) {
/>
</View>
</View>
-
<View
style={{
flex: 1,
@@ -319,7 +340,6 @@ function FormulaInner({ widget }: FormulaInnerProps) {
/>
</Suspense>
</View>
-
<View
style={{
padding: '0 20px 20px 20px',
@@ -372,7 +392,6 @@ function FormulaInner({ widget }: FormulaInnerProps) {
</View>
)}
</View>
-
<View
style={{
padding: 20,
diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx
index a81103c327..903c3bea74 100644
--- a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx
+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx
@@ -39,6 +39,7 @@ export function FormulaCard({
const fontSize = meta?.fontSize;
const fontSizeMode = meta?.fontSizeMode || 'dynamic';
const staticFontSize = meta?.staticFontSize || 32;
+ const showTitle = meta?.showTitle ?? true;
const colorFormula = meta?.colorFormula || '';
const { result, isLoading, error } = useFormulaExecution(
@@ -77,10 +78,14 @@ export function FormulaCard({
disableClick={nameMenuOpen}
to={`/reports/formula/${widgetId}`}
menuItems={[
- {
- name: 'rename',
- text: t('Rename'),
- },
+ ...(showTitle
+ ? [
+ {
+ name: 'rename',
+ text: t('Rename'),
+ },
+ ]
+ : []),
{
name: 'remove',
text: t('Remove'),
@@ -102,20 +107,22 @@ export function FormulaCard({
}}
>
<View style={{ flex: 1, overflow: 'hidden' }}>
- <View style={{ flexGrow: 0, flexShrink: 0, padding: 20 }}>
- <ReportCardName
- name={meta?.name || t('Formula')}
- isEditing={nameMenuOpen}
- onChange={newName => {
- onMetaChange({
- ...meta,
- name: newName,
- });
- setNameMenuOpen(false);
- }}
- onClose={() => setNameMenuOpen(false)}
- />
- </View>
+ {showTitle && (
+ <View style={{ flexGrow: 0, flexShrink: 0, padding: 20 }}>
+ <ReportCardName
+ name={meta?.name || t('Formula')}
+ isEditing={nameMenuOpen}
+ onChange={newName => {
+ onMetaChange({
+ ...meta,
+ name: newName,
+ });
+ setNameMenuOpen(false);
+ }}
+ onClose={() => setNameMenuOpen(false)}
+ />
+ </View>
+ )}
<View
ref={containerRef}
style={{
diff --git a/packages/desktop-client/src/components/settings/Format.tsx b/packages/desktop-client/src/components/settings/Format.tsx
index e1e660fa98..9d2cc53c0e 100644
--- a/packages/desktop-client/src/components/settings/Format.tsx
+++ b/packages/desktop-client/src/components/settings/Format.tsx
@@ -16,6 +16,8 @@ import { useSidebar } from '#components/sidebar/SidebarProvider';
import { useDateFormat } from '#hooks/useDateFormat';
import { useDaysOfWeek } from '#hooks/useDaysOfWeek';
import { useSyncedPref } from '#hooks/useSyncedPref';
+import { saveSyncedPrefs } from '#prefs/prefsSlice';
+import { useDispatch } from '#redux';
import { Column, Setting } from './UI';
@@ -30,6 +32,7 @@ const dateFormats: { value: SyncedPrefs['dateFormat']; label: string }[] = [
export function FormatSettings() {
const { t } = useTranslation();
+ const dispatch = useDispatch();
const sidebar = useSidebar();
const [_firstDayOfWeekIdx, setFirstDayOfWeekIdxPref] =
@@ -37,7 +40,7 @@ export function FormatSettings() {
const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const [, setDateFormatPref] = useSyncedPref('dateFormat');
- const [_numberFormat, setNumberFormatPref] = useSyncedPref('numberFormat');
+ const [_numberFormat] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction, setHideFractionPref] = useSyncedPref('hideFraction');
@@ -70,7 +73,11 @@ export function FormatSettings() {
<Select
key={String(hideFraction)} // needed because label does not update
value={numberFormat}
- onChange={format => setNumberFormatPref(format)}
+ onChange={format => {
+ void dispatch(
+ saveSyncedPrefs({ prefs: { numberFormat: format } }),
+ );
+ }}
options={numberFormats.map(f => [
f.value,
String(hideFraction) === 'true' ? f.labelNoFraction : f.label,
diff --git a/packages/desktop-client/src/components/settings/index.tsx b/packages/desktop-client/src/components/settings/index.tsx
index e9aa929601..134ec19e0f 100644
--- a/packages/desktop-client/src/components/settings/index.tsx
+++ b/packages/desktop-client/src/components/settings/index.tsx
@@ -23,8 +23,7 @@ import { useServerVersion } from '#components/ServerContext';
import { useFeatureFlag } from '#hooks/useFeatureFlag';
import { useGlobalPref } from '#hooks/useGlobalPref';
import { useMetadataPref } from '#hooks/useMetadataPref';
-import { useSyncedPref } from '#hooks/useSyncedPref';
-import { loadPrefs } from '#prefs/prefsSlice';
+import { loadPrefs, saveSyncedPrefs } from '#prefs/prefsSlice';
import { useDispatch, useSelector } from '#redux';
import { AuthSettings } from './AuthSettings';
@@ -172,7 +171,6 @@ export function Settings() {
const [budgetName] = useMetadataPref('budgetName');
const dispatch = useDispatch();
const isCurrencyExperimentalEnabled = useFeatureFlag('currency');
- const [_, setDefaultCurrencyCodePref] = useSyncedPref('defaultCurrencyCode');
const onCloseBudget = () => {
void dispatch(closeBudget());
@@ -189,9 +187,9 @@ export function Settings() {
useEffect(() => {
if (!isCurrencyExperimentalEnabled) {
- setDefaultCurrencyCodePref('');
+ void dispatch(saveSyncedPrefs({ prefs: { defaultCurrencyCode: '' } }));
}
- }, [isCurrencyExperimentalEnabled, setDefaultCurrencyCodePref]);
+ }, [dispatch, isCurrencyExperimentalEnabled]);
const { isNarrowWidth } = useResponsive();
diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.ts
index 1ed87f34c0..1770506e81 100644
--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts
+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts
@@ -3,10 +3,9 @@ import { useEffect, useState } from 'react';
import { send } from '@actual-app/core/platform/client/connection';
import {
createBudgetQueryPrefetchKey,
- CustomFunctionsPlugin,
- customFunctionsTranslations,
-} from '@actual-app/core/server/rules/customFunctions';
-import type { FormulaQueryContext } from '@actual-app/core/server/rules/customFunctions';
+ setCachedUserPreferences,
+} from '@actual-app/core/shared/formulas/customFunctions';
+import type { FormulaQueryContext } from '@actual-app/core/shared/formulas/customFunctions';
import * as monthUtils from '@actual-app/core/shared/months';
import { q } from '@actual-app/core/shared/query';
import type { Query } from '@actual-app/core/shared/query';
@@ -17,13 +16,16 @@ import type {
TimeFrame,
} from '@actual-app/core/types/models';
import { HyperFormula } from 'hyperformula';
-import enUS from 'hyperformula/i18n/languages/enUS';
import { getLiveRange } from '#components/reports/getLiveRange';
import { calculateTimeRange } from '#components/reports/reportRanges';
+import { bootstrapHyperFormula } from '#util/bootstrapHyperFormula';
+import { useGlobalPref } from './useGlobalPref';
import { useLocale } from './useLocale';
+bootstrapHyperFormula();
+
type QueryConfig = {
conditions?: RuleConditionEntity[];
conditionsOp?: 'and' | 'or';
@@ -32,15 +34,6 @@ type QueryConfig = {
type QueriesMap = Record<string, QueryConfig>;
-if (!HyperFormula.getRegisteredLanguagesCodes().includes('enUS')) {
- HyperFormula.registerLanguage('enUS', enUS);
-}
-
-HyperFormula.registerFunctionPlugin(
- CustomFunctionsPlugin,
- customFunctionsTranslations,
-);
-
type FormulaCellValue = number | string | boolean | null;
function createFormulaQueryContext(): Required<FormulaQueryContext> {
@@ -139,6 +132,7 @@ export function useFormulaExecution(
namedExpressions?: Record<string, number | string>,
) {
const locale = useLocale();
+ const [language] = useGlobalPref('language');
const [result, setResult] = useState<number | string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -157,12 +151,27 @@ export function useFormulaExecution(
setError(null);
try {
+ const browserLocale =
+ typeof navigator === 'undefined' ? undefined : navigator.language;
+ const formulaLocale = language || browserLocale || locale || 'en-US';
+
+ try {
+ setCachedUserPreferences(
+ await send('formula-load-user-preferences', {
+ selectedLocale: language,
+ browserLocale,
+ }),
+ );
+ } catch (err) {
+ console.error('Error loading formula preferences:', err);
+ }
+
const formulaQueryContext = createFormulaQueryContext();
evaluateFormulaWithContext({
formula,
formulaQueryContext,
- locale,
+ locale: formulaLocale,
namedExpressions,
throwOnCellError: false,
});
@@ -173,7 +182,7 @@ export function useFormulaExecution(
evaluateFormulaWithContext({
formula,
formulaQueryContext,
- locale,
+ locale: formulaLocale,
namedExpressions,
throwOnCellError: false,
});
@@ -183,7 +192,7 @@ export function useFormulaExecution(
const cellValue = evaluateFormulaWithContext({
formula,
formulaQueryContext,
- locale,
+ locale: formulaLocale,
namedExpressions,
});
@@ -208,7 +217,7 @@ export function useFormulaExecution(
return () => {
cancelled = true;
};
- }, [formula, queriesVersion, locale, queries, namedExpressions]);
+ }, [formula, queriesVersion, locale, language, queries, namedExpressions]);
return { result, isLoading, error };
}
@@ -461,7 +470,9 @@ function extractCategoryConditions(
conditions: RuleConditionEntity[],
): RuleConditionEntity[] {
return conditions.filter(
- cond => !cond.customName && cond.field === 'category',
+ cond =>
+ !cond.customName &&
+ (cond.field === 'category' || cond.field === 'category_group'),
);
}
@@ -478,32 +489,53 @@ async function getCategoriesFromConditions(
.map((cat: CategoryEntity) => cat.id);
}
+ // Get category groups for resolving group IDs to names
+ const { grouped: categoryGroups } = await send('get-categories');
+ const groupNameById = new Map(
+ categoryGroups.map((g: { id: string; name: string }) => [g.id, g.name]),
+ );
+
// Evaluate each condition to get sets of matching categories
const conditionResults = conditions.map(cond => {
+ // For category_group conditions, we check cat.group; for category, we check cat.id
+ const getKey = (cat: CategoryEntity) =>
+ cond.field === 'category_group' ? cat.group : cat.id;
+
const matching = allCategories.filter((cat: CategoryEntity) => {
+ const key = getKey(cat);
+
+ const textValue =
+ cond.field === 'category_group'
+ ? (groupNameById.get(key) ?? key)
+ : cat.name;
+
if (cond.op === 'is') {
- return cond.value === cat.id;
+ return cond.value === key;
} else if (cond.op === 'isNot') {
- return cond.value !== cat.id;
+ return cond.value !== key;
} else if (cond.op === 'oneOf') {
- return cond.value.includes(cat.id);
+ return cond.value.includes(key);
} else if (cond.op === 'notOneOf') {
- return !cond.value.includes(cat.id);
+ return !cond.value.includes(key);
} else if (cond.op === 'contains') {
- return cat.name.includes(cond.value as string);
+ return textValue
+ .toLowerCase()
+ .includes((cond.value as string).toLowerCase());
} else if (cond.op === 'doesNotContain') {
- return !cat.name.includes(cond.value as string);
+ return !textValue
+ .toLowerCase()
+ .includes((cond.value as string).toLowerCase());
} else if (cond.op === 'matches') {
try {
- return new RegExp(cond.value as string).test(cat.name);
+ return new RegExp(cond.value as string, 'i').test(textValue);
} catch (e) {
console.warn('Invalid regexp in matches condition', e);
- return true;
+ return false;
}
}
- // Unknown operator: include category by default and log warning
+ // Unknown operator: exclude category by default and log warning
console.warn(`Unknown category condition operator: ${cond.op}`);
- return true;
+ return false;
});
return matching.map((cat: CategoryEntity) => cat.id);
});
diff --git a/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts b/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts
index 1667738d73..05b32b397b 100644
--- a/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts
+++ b/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts
@@ -1,21 +1,15 @@
import { useEffect, useState } from 'react';
-import {
- CustomFunctionsPlugin,
- customFunctionsTranslations,
-} from '@actual-app/core/server/rules/customFunctions';
+import { send } from '@actual-app/core/platform/client/connection';
+import { setCachedUserPreferences } from '@actual-app/core/shared/formulas/customFunctions';
import { HyperFormula } from 'hyperformula';
-import enUS from 'hyperformula/i18n/languages/enUS';
+import { bootstrapHyperFormula } from '#util/bootstrapHyperFormula';
+
+import { useGlobalPref } from './useGlobalPref';
import { useLocale } from './useLocale';
-if (!HyperFormula.getRegisteredLanguagesCodes().includes('enUS')) {
- HyperFormula.registerLanguage('enUS', enUS);
-}
-HyperFormula.registerFunctionPlugin(
- CustomFunctionsPlugin,
- customFunctionsTranslations,
-);
+bootstrapHyperFormula();
type TransactionContext = {
amount?: number;
@@ -35,13 +29,14 @@ export function useTransactionFormulaExecution(
transaction: TransactionContext,
) {
const locale = useLocale();
+ const [language] = useGlobalPref('language');
const [result, setResult] = useState<number | string | boolean | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
- function executeFormula() {
+ async function executeFormula() {
let hfInstance: ReturnType<typeof HyperFormula.buildEmpty> | null = null;
if (!formula || !formula.startsWith('=')) {
@@ -51,11 +46,26 @@ export function useTransactionFormulaExecution(
}
try {
+ const browserLocale =
+ typeof navigator === 'undefined' ? undefined : navigator.language;
+ const formulaLocale = language || browserLocale || 'en-US';
+
+ try {
+ setCachedUserPreferences(
+ await send('formula-load-user-preferences', {
+ selectedLocale: language,
+ browserLocale,
+ }),
+ );
+ } catch (err) {
+ console.error('Error loading formula preferences:', err);
+ }
+
// Create HyperFormula instance
hfInstance = HyperFormula.buildEmpty({
licenseKey: 'gpl-v3',
language: 'enUS',
- localeLang: typeof locale === 'string' ? locale : 'en-US',
+ localeLang: formulaLocale,
dateFormats: ['DD/MM/YYYY', 'YYYY-MM-DD', 'YYYY/MM/DD'],
context: {
// No server prefetch in preview
@@ -138,12 +148,12 @@ export function useTransactionFormulaExecution(
}
}
- executeFormula();
+ void executeFormula();
return () => {
cancelled = true;
};
- }, [formula, transaction, locale]);
+ }, [formula, transaction, locale, language]);
return { result, error };
}
diff --git a/packages/desktop-client/src/util/bootstrapHyperFormula.ts b/packages/desktop-client/src/util/bootstrapHyperFormula.ts
new file mode 100644
index 0000000000..25a70b378d
--- /dev/null
+++ b/packages/desktop-client/src/util/bootstrapHyperFormula.ts
@@ -0,0 +1,16 @@
+import {
+ CustomFunctionsPlugin,
+ customFunctionsTranslations,
+} from '@actual-app/core/shared/formulas/customFunctions';
+import { HyperFormula } from 'hyperformula';
+import enUS from 'hyperformula/i18n/languages/enUS';
+
+export function bootstrapHyperFormula() {
+ if (!HyperFormula.getRegisteredLanguagesCodes().includes('enUS')) {
+ HyperFormula.registerLanguage('enUS', enUS);
+ }
+ HyperFormula.registerFunctionPlugin(
+ CustomFunctionsPlugin,
+ customFunctionsTranslations,
+ );
+}
diff --git a/packages/docs/docs/experimental/formulas.md b/packages/docs/docs/experimental/formulas.md
index ae4faf0fa5..6094ddd0fe 100644
--- a/packages/docs/docs/experimental/formulas.md
+++ b/packages/docs/docs/experimental/formulas.md
@@ -47,132 +47,151 @@ This list documents the functions that appear in the in-app **autocomplete/hover
If a function isn’t listed here, it still might work. Actual uses HyperFormula under the hood, so you can also refer to [HyperFormula’s built-in functions list](https://hyperformula.handsontable.com/guide/built-in-functions.html).
:::
-| Function | Available in | Description | Syntax example | Optional params |
-| ------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
-| `ABS` | Query, Rules | Returns the absolute value of a number. | `=ABS(-42)` | β€” |
-| `AND` | Query, Rules | Returns TRUE if all arguments are TRUE. | `=AND(1=1, 2=2)` | Accepts more than 2 conditions |
-| `AVERAGE` | Query | Returns the average of all numbers in a range. | `=AVERAGE(1, 2, 3)` | Accepts more than 2 values |
-| `AVERAGEA` | Query | Returns the average, including text and logical values. | `=AVERAGEA(1, TRUE, "2")` | Accepts more than 2 values |
-| `BALANCE_OF` | Rules | Returns running balance for another account in cents; pass a quoted account id or exact account name. | `=BALANCE_OF("550e8400-e29b-41d4-a716-446655440000"); =BALANCE_OF("Checking")` | β€” |
-| `BUDGET_QUERY` | Query | Returns a budget dimension total for a set of categories over a month range. Dimension is one of: `budgeted`, `spent`, `balance_start`, `balance_end`, `goal`. | `=BUDGET_QUERY("spent", QUERY_EXTRACT_CATEGORIES("q"), QUERY_EXTRACT_TIMEFRAME_START("q"), QUERY_EXTRACT_TIMEFRAME_END("q"))` | β€” |
-| `CEILING` | Query, Rules | Rounds up to nearest multiple of significance. | `=CEILING(10.2, 1)` | β€” |
-| `CHAR` | Query, Rules | Converts number to character. | `=CHAR(65)` | β€” |
-| `CHOOSE` | Query | Returns value from list based on index. | `=CHOOSE(2, "A", "B", "C")` | Accepts more than 2 values |
-| `CLEAN` | Rules | Removes non-printable characters from text. | `=CLEAN(notes)` | β€” |
-| `CODE` | Query, Rules | Returns numeric code for first character. | `=CODE("A")` | β€” |
-| `CONCATENATE` | Query, Rules | Combines several text strings into one. | `=CONCATENATE("Paid ", payee_name)` | Accepts more than 2 texts |
-| `COS` | Query | Returns the cosine of an angle. | `=COS(1)` | β€” |
-| `COUNT` | Query | Counts the number of numeric values. | `=COUNT(1, 2, "x")` | Accepts more than 2 values |
-| `COUNTA` | Query | Counts non-empty values. | `=COUNTA(1, "", "x")` | Accepts more than 2 values |
-| `COUNTBLANK` | Query | Counts empty cells. | `=COUNTBLANK(A1:A10)` | β€” |
-| `COUNTIF` | Query | Counts cells that meet a criteria. | `=COUNTIF(A1:A10, ">0")` | β€” |
-| `COUNTIFS` | Query | Counts cells that meet multiple criteria. | `=COUNTIFS(A1:A10, ">0", B1:B10, "<=5")` | Repeat `(range, criteria)` pairs |
-| `DATE` | Query, Rules | Returns date as number of days since null date. | `=DATE(2025, 12, 16)` | β€” |
-| `DATEDIF` | Query, Rules | Calculates distance between dates. | `=DATEDIF("2025-01-01", "2025-12-31", "D")` | β€” |
-| `DATEVALUE` | Rules | Parses a date string and returns it as a number. | `=DATEVALUE("2025-12-16")` | β€” |
-| `DAY` | Query, Rules | Returns the day from a date. | `=DAY(date)` | β€” |
-| `DAYS` | Query, Rules | Calculates difference between dates in days. | `=DAYS("2025-12-31", "2025-12-01")` | β€” |
-| `EDATE` | Query, Rules | Returns date shifted by specified months. | `=EDATE(date, 1)` | β€” |
-| `EOMONTH` | Query, Rules | Returns last day of month after specified months. | `=EOMONTH(date, 0)` | β€” |
-| `EXACT` | Query, Rules | Returns TRUE if texts are exactly the same. | `=EXACT("A", "a")` | β€” |
-| `EXP` | Query | Returns e raised to the power of number. | `=EXP(1)` | β€” |
-| `FALSE` | Query, Rules | Returns the logical value FALSE. | `=FALSE()` | β€” |
-| `FIND` | Query, Rules | Finds text within text (case-sensitive). | `=FIND("foo", notes)` | β€” |
-| `FLOOR` | Query, Rules | Rounds down to nearest multiple of significance. | `=FLOOR(10.8, 1)` | β€” |
-| `FV` | Query | Calculates future value of investment. | `=FV(0.05/12, 12, -100)` | β€” |
-| `HLOOKUP` | Query | Searches horizontally in first row and returns value. | `=HLOOKUP("key", A1:D10, 2, TRUE)` | β€” |
-| `IF` | Query, Rules | Returns one value if condition is TRUE, another if FALSE. | `=IF(amount<0, "Expense", "Income")` | β€” |
-| `IFERROR` | Query, Rules | Returns value if no error, otherwise returns alternative. | `=IFERROR(1/0, 0)` | β€” |
-| `IFNA` | Query, Rules | Returns value if not #N/A error, otherwise returns alternative. | `=IFNA(VLOOKUP("x", A1:B10, 2, FALSE), 0)` | β€” |
-| `IFS` | Query, Rules | Checks multiple conditions and returns corresponding values. | `=IFS(amount<0, "Expense", amount>0, "Income")` | Repeat `(condition, value)` pairs |
-| `INDEX` | Query | Returns value at specified row and column. | `=INDEX(A1:C10, 2, 3)` | β€” |
-| `INTEGER_TO_AMOUNT` | Query, Rules | Converts integer amount to decimal amount (e.g., 1234 -> 12.34). | `=INTEGER_TO_AMOUNT(amount, 2)` | `decimal_places` (default: 2) |
-| `INT` | Rules | Rounds down to nearest integer. | `=INT(10.9)` | β€” |
-| `IRR` | Query | Calculates internal rate of return. | `=IRR(A1:A12)` | β€” |
-| `ISEVEN` | Rules | Returns TRUE if number is even. | `=ISEVEN(10)` | β€” |
-| `ISODD` | Rules | Returns TRUE if number is odd. | `=ISODD(11)` | β€” |
-| `ISBLANK` | Query, Rules | Returns TRUE if value is blank. | `=ISBLANK(notes)` | β€” |
-| `ISERROR` | Query, Rules | Returns TRUE if value is any error. | `=ISERROR(1/0)` | β€” |
-| `ISLOGICAL` | Query, Rules | Returns TRUE if value is logical (TRUE/FALSE). | `=ISLOGICAL(TRUE())` | β€” |
-| `ISNA` | Query, Rules | Returns TRUE if value is #N/A error. | `=ISNA(NA())` | β€” |
-| `ISNUMBER` | Query, Rules | Returns TRUE if value is a number. | `=ISNUMBER(amount)` | β€” |
-| `ISOWEEKNUM` | Rules | Returns ISO week number. | `=ISOWEEKNUM(date)` | β€” |
-| `ISREF` | Query, Rules | Returns TRUE if value is a reference. | `=ISREF(A1)` | β€” |
-| `ISTEXT` | Query, Rules | Returns TRUE if value is text. | `=ISTEXT(notes)` | β€” |
-| `LEFT` | Query, Rules | Returns leftmost characters from text. | `=LEFT(imported_payee, 10)` | β€” |
-| `LEN` | Query, Rules | Returns length of text. | `=LEN(notes)` | β€” |
-| `LN` | Query | Returns the natural logarithm. | `=LN(10)` | β€” |
-| `LOG` | Query | Returns the logarithm to specified base. | `=LOG(100, 10)` | β€” |
-| `LOG10` | Query | Returns the base-10 logarithm. | `=LOG10(1000)` | β€” |
-| `LOOKUP` | Query | Looks up values in a vector or array. | `=LOOKUP("x", A1:A10)` | β€” |
-| `LOWER` | Query, Rules | Converts text to lowercase. | `=LOWER(notes)` | β€” |
-| `MATCH` | Query | Returns position of value in array. | `=MATCH("x", A1:A10, 0)` | β€” |
-| `MAX` | Query | Returns the maximum value. | `=MAX(1, 2, 3)` | Accepts more than 2 values |
-| `MAXA` | Query | Returns the maximum value, including text and logical values. | `=MAXA(1, TRUE, "2")` | Accepts more than 2 values |
-| `MEDIAN` | Query | Returns the median value. | `=MEDIAN(1, 2, 100)` | Accepts more than 2 values |
-| `MID` | Query, Rules | Returns substring from specified position. | `=MID(notes, 1, 10)` | β€” |
-| `MIN` | Query | Returns the minimum value. | `=MIN(1, 2, 3)` | Accepts more than 2 values |
-| `MINA` | Query | Returns the minimum value, including text and logical values. | `=MINA(1, TRUE, "2")` | Accepts more than 2 values |
-| `MOD` | Query, Rules | Returns the remainder of division. | `=MOD(10, 3)` | β€” |
-| `MODE` | Query | Returns the most frequently occurring value. | `=MODE(1, 1, 2)` | Accepts more than 2 values |
-| `MONTH` | Query, Rules | Returns the month from a date. | `=MONTH(date)` | β€” |
-| `N` | Rules | Converts value to a number. | `=N(TRUE())` | β€” |
-| `NETWORKDAYS` | Query | Returns number of working days between dates. | `=NETWORKDAYS("2025-12-01", "2025-12-31")` | β€” |
-| `NOT` | Query, Rules | Reverses the logical value. | `=NOT(amount<0)` | β€” |
-| `NOW` | Query, Rules | Returns current date and time. | `=NOW()` | β€” |
-| `NPV` | Query | Calculates net present value. | `=NPV(0.1, -1000, 200, 300)` | Accepts more than 2 values |
-| `OR` | Query, Rules | Returns TRUE if any argument is TRUE. | `=OR(amount<0, amount>0)` | Accepts more than 2 conditions |
-| `PERCENTILE` | Query | Returns the k-th percentile. | `=PERCENTILE(A1:A100, 0.9)` | β€” |
-| `PI` | Query | Returns the value of PI. | `=PI()` | β€” |
-| `PMT` | Query | Calculates payment for a loan. | `=PMT(0.05/12, 60, 10000)` | β€” |
-| `POWER` | Query, Rules | Returns base raised to the power of exponent. | `=POWER(2, 8)` | β€” |
-| `PROPER` | Query, Rules | Capitalizes first letter of each word. | `=PROPER(notes)` | β€” |
-| `PRODUCT` | Query | Returns the product of all numbers. | `=PRODUCT(2, 3, 4)` | Accepts more than 2 values |
-| `PV` | Query | Calculates present value of investment. | `=PV(0.05/12, 12, -100)` | β€” |
-| `QUARTILE` | Query | Returns the quartile of a dataset. | `=QUARTILE(A1:A100, 1)` | β€” |
-| `QUERY` | Query | Execute a query and return the result. | `=QUERY("expenses")` | β€” |
-| `QUERY_COUNT` | Query | Execute a query and return the number of matching rows. | `=QUERY_COUNT("expenses")` | β€” |
-| `QUERY_EXTRACT_CATEGORIES` | Query | Determines which categories to include based on a named query's category filters; used as the `categories` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_CATEGORIES("expenses")` | β€” |
-| `QUERY_EXTRACT_TIMEFRAME_END` | Query | Extracts the end month from a named query's date range; used as the `endMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_END("expenses")` | β€” |
-| `QUERY_EXTRACT_TIMEFRAME_START` | Query | Extracts the start month from a named query's date range; used as the `startMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_START("expenses")` | β€” |
-| `RANK` | Query | Returns the rank of a number in a list. | `=RANK(10, A1:A10, 0)` | β€” |
-| `RATE` | Query | Calculates interest rate per period. | `=RATE(60, -200, 10000)` | β€” |
-| `REPLACE` | Query, Rules | Replaces substring at specified position. | `=REPLACE(notes, 1, 5, "")` | β€” |
-| `REPT` | Query, Rules | Repeats text specified number of times. | `=REPT("*", 10)` | β€” |
-| `RIGHT` | Query, Rules | Returns rightmost characters from text. | `=RIGHT(imported_payee, 4)` | β€” |
-| `ROUND` | Query, Rules | Rounds a number to specified decimals. | `=ROUND(amount/100, 2)` | β€” |
-| `ROUNDDOWN` | Query, Rules | Rounds down to specified decimals. | `=ROUNDDOWN(amount/100, 0)` | β€” |
-| `ROUNDUP` | Query, Rules | Rounds up to specified decimals. | `=ROUNDUP(amount/100, 0)` | β€” |
-| `SEARCH` | Query, Rules | Finds text within text (case-insensitive, supports wildcards). | `=SEARCH("foo", notes)` | β€” |
-| `SIGN` | Rules | Returns -1 for negative, 0 for zero, 1 for positive. | `=SIGN(amount)` | β€” |
-| `SIN` | Query | Returns the sine of an angle. | `=SIN(1)` | β€” |
-| `SPLIT` | Rules | Splits text by space and returns part at index. | `=SPLIT(imported_payee, 0)` | β€” |
-| `SQRT` | Query, Rules | Returns the square root. | `=SQRT(9)` | β€” |
-| `STDEV` | Query | Returns the standard deviation of a sample. | `=STDEV(A1:A10)` | β€” |
-| `STDEVP` | Query | Returns the standard deviation of a population. | `=STDEVP(A1:A10)` | β€” |
-| `SUBSTITUTE` | Query, Rules | Replaces occurrences of text. | `=SUBSTITUTE(imported_payee, " 12345", "")` | β€” |
-| `SUM` | Query, Rules | Returns the sum of all numbers in a range. | `=SUM(1, 2, 3)` | Accepts more than 2 values |
-| `SUMIF` | Query | Sums cells that meet a criteria. | `=SUMIF(A1:A10, ">0", B1:B10)` | β€” |
-| `SUMIFS` | Query | Sums cells that meet multiple criteria. | `=SUMIFS(B1:B10, A1:A10, ">0", C1:C10, "X")` | Repeat `(range, criteria)` pairs |
-| `SUMPRODUCT` | Query | Multiplies corresponding elements and returns the sum. | `=SUMPRODUCT(A1:A10, B1:B10)` | Accepts more arrays |
-| `SUMSQ` | Query | Returns the sum of the squares. | `=SUMSQ(1, 2, 3)` | Accepts more than 2 values |
-| `SWITCH` | Query, Rules | Matches expression against values and returns corresponding result. | `=SWITCH(category_name, "Groceries", "Food", "Fuel", "Transport")` | Repeat `(value, result)` pairs; default supported |
-| `T` | Rules | Returns text if value is text, empty string otherwise. | `=T(notes)` | β€” |
-| `TAN` | Query | Returns the tangent of an angle. | `=TAN(1)` | β€” |
-| `TEXT` | Query, Rules | Converts number to text with format. | `=TEXT(date, "MMMM yyyy")` | β€” |
-| `TODAY` | Query, Rules | Returns current date. | `=TODAY()` | β€” |
-| `TRIM` | Query, Rules | Removes extra spaces from text. | `=TRIM(notes)` | β€” |
-| `TRUNC` | Rules | Truncates number to specified decimals. | `=TRUNC(amount/100, 0)` | β€” |
-| `TRUE` | Query, Rules | Returns the logical value TRUE. | `=TRUE()` | β€” |
-| `UPPER` | Query, Rules | Converts text to uppercase. | `=UPPER(notes)` | β€” |
-| `VALUE` | Rules | Converts text to a number. | `=VALUE("123.45")` | β€” |
-| `VAR` | Query | Returns the variance of a sample. | `=VAR(A1:A10)` | β€” |
-| `VARP` | Query | Returns the variance of a population. | `=VARP(A1:A10)` | β€” |
-| `VLOOKUP` | Query | Searches vertically in first column and returns value. | `=VLOOKUP("key", A1:D10, 2, TRUE)` | β€” |
-| `WEEKDAY` | Query, Rules | Returns day of week (1-7). | `=WEEKDAY(date, 1)` | β€” |
-| `WEEKNUM` | Query, Rules | Returns week number of year. | `=WEEKNUM(date, 1)` | β€” |
-| `XOR` | Query, Rules | Returns TRUE if odd number of arguments are TRUE. | `=XOR(TRUE(), FALSE())` | Accepts more than 2 conditions |
-| `YEAR` | Query, Rules | Returns the year from a date. | `=YEAR(date)` | β€” |
+| Function | Available in | Description | Syntax example | Optional params |
+| ------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
+| `ABS` | Query, Rules | Returns the absolute value of a number. | `=ABS(-42)` | β€” |
+| `AND` | Query, Rules | Returns TRUE if all arguments are TRUE. | `=AND(1=1, 2=2)` | Accepts more than 2 conditions |
+| `AVERAGE` | Query | Returns the average of all numbers in a range. | `=AVERAGE(1, 2, 3)` | Accepts more than 2 values |
+| `AVERAGEA` | Query | Returns the average, including text and logical values. | `=AVERAGEA(1, TRUE, "2")` | Accepts more than 2 values |
+| `BALANCE_OF` | Rules | Returns running balance for another account in cents; pass a quoted account id or exact account name. | `=BALANCE_OF("550e8400-e29b-41d4-a716-446655440000"); =BALANCE_OF("Checking")` | β€” |
+| `BUDGET_QUERY` | Query | Returns a budget dimension total for a set of categories over a month range. Dimension is one of: `budgeted`, `spent`, `balance_start`, `balance_end`, `goal`. | `=BUDGET_QUERY("spent", QUERY_EXTRACT_CATEGORIES("q"), QUERY_EXTRACT_TIMEFRAME_START("q"), QUERY_EXTRACT_TIMEFRAME_END("q"))` | β€” |
+| `CEILING` | Query, Rules | Rounds up to nearest multiple of significance. | `=CEILING(10.2, 1)` | β€” |
+| `CHAR` | Query, Rules | Converts number to character. | `=CHAR(65)` | β€” |
+| `CHOOSE` | Query | Returns value from list based on index. | `=CHOOSE(2, "A", "B", "C")` | Accepts more than 2 values |
+| `CLEAN` | Rules | Removes non-printable characters from text. | `=CLEAN(notes)` | β€” |
+| `CODE` | Query, Rules | Returns numeric code for first character. | `=CODE("A")` | β€” |
+| `CONCATENATE` | Query, Rules | Combines several text strings into one. | `=CONCATENATE("Paid ", payee_name)` | Accepts more than 2 texts |
+| `COS` | Query | Returns the cosine of an angle. | `=COS(1)` | β€” |
+| `COUNT` | Query | Counts the number of numeric values. | `=COUNT(1, 2, "x")` | Accepts more than 2 values |
+| `COUNTA` | Query | Counts non-empty values. | `=COUNTA(1, "", "x")` | Accepts more than 2 values |
+| `COUNTBLANK` | Query | Counts empty cells. | `=COUNTBLANK(A1:A10)` | β€” |
+| `COUNTIF` | Query | Counts cells that meet a criteria. | `=COUNTIF(A1:A10, ">0")` | β€” |
+| `COUNTIFS` | Query | Counts cells that meet multiple criteria. | `=COUNTIFS(A1:A10, ">0", B1:B10, "<=5")` | Repeat `(range, criteria)` pairs |
+| `DATE` | Query, Rules | Returns date as number of days since null date. | `=DATE(2025, 12, 16)` | β€” |
+| `DATEDIF` | Query, Rules | Calculates distance between dates. | `=DATEDIF("2025-01-01", "2025-12-31", "D")` | β€” |
+| `DATEVALUE` | Rules | Parses a date string and returns it as a number. | `=DATEVALUE("2025-12-16")` | β€” |
+| `DAY` | Query, Rules | Returns the day from a date. | `=DAY(date)` | β€” |
+| `DAYS` | Query, Rules | Calculates difference between dates in days. | `=DAYS("2025-12-31", "2025-12-01")` | β€” |
+| `EDATE` | Query, Rules | Returns date shifted by specified months. | `=EDATE(date, 1)` | β€” |
+| `EOMONTH` | Query, Rules | Returns last day of month after specified months. | `=EOMONTH(date, 0)` | β€” |
+| `EXACT` | Query, Rules | Returns TRUE if texts are exactly the same. | `=EXACT("A", "a")` | β€” |
+| `EXP` | Query | Returns e raised to the power of number. | `=EXP(1)` | β€” |
+| `FALSE` | Query, Rules | Returns the logical value FALSE. | `=FALSE()` | β€” |
+| `FIND` | Query, Rules | Finds text within text (case-sensitive). | `=FIND("foo", notes)` | β€” |
+| `FLOOR` | Query, Rules | Rounds down to nearest multiple of significance. | `=FLOOR(10.8, 1)` | β€” |
+| `FORMATCURRENCY` | Query, Rules | Formats a number as currency using your app currency, number format, symbol position, and spacing settings by default. | `=FORMATCURRENCY(1234.5)` | `symbol`, `decimals`, `thousandsSeparator`, `decimalSeparator`, `symbolPosition`, `spaceBetweenAmountAndSymbol` |
+| `FORMATNUMBER` | Query, Rules | Formats a number using your app number format settings by default. | `=FORMATNUMBER(1234.5, 2)` | `decimals`, `thousandsSeparator`, `decimalSeparator` |
+| `FV` | Query | Calculates future value of investment. | `=FV(0.05/12, 12, -100)` | β€” |
+| `HLOOKUP` | Query | Searches horizontally in first row and returns value. | `=HLOOKUP("key", A1:D10, 2, TRUE)` | β€” |
+| `IF` | Query, Rules | Returns one value if condition is TRUE, another if FALSE. | `=IF(amount<0, "Expense", "Income")` | β€” |
+| `IFERROR` | Query, Rules | Returns value if no error, otherwise returns alternative. | `=IFERROR(1/0, 0)` | β€” |
+| `IFNA` | Query, Rules | Returns value if not #N/A error, otherwise returns alternative. | `=IFNA(VLOOKUP("x", A1:B10, 2, FALSE), 0)` | β€” |
+| `IFS` | Query, Rules | Checks multiple conditions and returns corresponding values. | `=IFS(amount<0, "Expense", amount>0, "Income")` | Repeat `(condition, value)` pairs |
+| `INDEX` | Query | Returns value at specified row and column. | `=INDEX(A1:C10, 2, 3)` | β€” |
+| `INTEGER_TO_AMOUNT` | Query, Rules | Converts integer amount to decimal amount (e.g., 1234 -> 12.34). | `=INTEGER_TO_AMOUNT(amount, 2)` | `decimal_places` (default: 2) |
+| `INT` | Rules | Rounds down to nearest integer. | `=INT(10.9)` | β€” |
+| `IRR` | Query | Calculates internal rate of return. | `=IRR(A1:A12)` | β€” |
+| `ISEVEN` | Rules | Returns TRUE if number is even. | `=ISEVEN(10)` | β€” |
+| `ISODD` | Rules | Returns TRUE if number is odd. | `=ISODD(11)` | β€” |
+| `ISBLANK` | Query, Rules | Returns TRUE if value is blank. | `=ISBLANK(notes)` | β€” |
+| `ISERROR` | Query, Rules | Returns TRUE if value is any error. | `=ISERROR(1/0)` | β€” |
+| `ISLOGICAL` | Query, Rules | Returns TRUE if value is logical (TRUE/FALSE). | `=ISLOGICAL(TRUE())` | β€” |
+| `ISNA` | Query, Rules | Returns TRUE if value is #N/A error. | `=ISNA(NA())` | β€” |
+| `ISNUMBER` | Query, Rules | Returns TRUE if value is a number. | `=ISNUMBER(amount)` | β€” |
+| `ISOWEEKNUM` | Rules | Returns ISO week number. | `=ISOWEEKNUM(date)` | β€” |
+| `ISREF` | Query, Rules | Returns TRUE if value is a reference. | `=ISREF(A1)` | β€” |
+| `ISTEXT` | Query, Rules | Returns TRUE if value is text. | `=ISTEXT(notes)` | β€” |
+| `LEFT` | Query, Rules | Returns leftmost characters from text. | `=LEFT(imported_payee, 10)` | β€” |
+| `LEN` | Query, Rules | Returns length of text. | `=LEN(notes)` | β€” |
+| `LN` | Query | Returns the natural logarithm. | `=LN(10)` | β€” |
+| `LOG` | Query | Returns the logarithm to specified base. | `=LOG(100, 10)` | β€” |
+| `LOG10` | Query | Returns the base-10 logarithm. | `=LOG10(1000)` | β€” |
+| `LOOKUP` | Query | Looks up values in a vector or array. | `=LOOKUP("x", A1:A10)` | β€” |
+| `LOWER` | Query, Rules | Converts text to lowercase. | `=LOWER(notes)` | β€” |
+| `MATCH` | Query | Returns position of value in array. | `=MATCH("x", A1:A10, 0)` | β€” |
+| `MAX` | Query | Returns the maximum value. | `=MAX(1, 2, 3)` | Accepts more than 2 values |
+| `MAXA` | Query | Returns the maximum value, including text and logical values. | `=MAXA(1, TRUE, "2")` | Accepts more than 2 values |
+| `MEDIAN` | Query | Returns the median value. | `=MEDIAN(1, 2, 100)` | Accepts more than 2 values |
+| `MID` | Query, Rules | Returns substring from specified position. | `=MID(notes, 1, 10)` | β€” |
+| `MIN` | Query | Returns the minimum value. | `=MIN(1, 2, 3)` | Accepts more than 2 values |
+| `MINA` | Query | Returns the minimum value, including text and logical values. | `=MINA(1, TRUE, "2")` | Accepts more than 2 values |
+| `MOD` | Query, Rules | Returns the remainder of division. | `=MOD(10, 3)` | β€” |
+| `MODE` | Query | Returns the most frequently occurring value. | `=MODE(1, 1, 2)` | Accepts more than 2 values |
+| `MONTH` | Query, Rules | Returns the month from a date. | `=MONTH(date)` | β€” |
+| `N` | Rules | Converts value to a number. | `=N(TRUE())` | β€” |
+| `NETWORKDAYS` | Query | Returns number of working days between dates. | `=NETWORKDAYS("2025-12-01", "2025-12-31")` | β€” |
+| `NOT` | Query, Rules | Reverses the logical value. | `=NOT(amount<0)` | β€” |
+| `NOW` | Query, Rules | Returns current date and time. | `=NOW()` | β€” |
+| `NPV` | Query | Calculates net present value. | `=NPV(0.1, -1000, 200, 300)` | Accepts more than 2 values |
+| `OR` | Query, Rules | Returns TRUE if any argument is TRUE. | `=OR(amount<0, amount>0)` | Accepts more than 2 conditions |
+| `PERCENTILE` | Query | Returns the k-th percentile. | `=PERCENTILE(A1:A100, 0.9)` | β€” |
+| `PI` | Query | Returns the value of PI. | `=PI()` | β€” |
+| `PMT` | Query | Calculates payment for a loan. | `=PMT(0.05/12, 60, 10000)` | β€” |
+| `POWER` | Query, Rules | Returns base raised to the power of exponent. | `=POWER(2, 8)` | β€” |
+| `PROPER` | Query, Rules | Capitalizes first letter of each word. | `=PROPER(notes)` | β€” |
+| `PRODUCT` | Query | Returns the product of all numbers. | `=PRODUCT(2, 3, 4)` | Accepts more than 2 values |
+| `PV` | Query | Calculates present value of investment. | `=PV(0.05/12, 12, -100)` | β€” |
+| `QUARTILE` | Query | Returns the quartile of a dataset. | `=QUARTILE(A1:A100, 1)` | β€” |
+| `QUERY` | Query | Execute a query and return the result. | `=QUERY("expenses")` | β€” |
+| `QUERY_COUNT` | Query | Execute a query and return the number of matching rows. | `=QUERY_COUNT("expenses")` | β€” |
+| `QUERY_EXTRACT_CATEGORIES` | Query | Determines which categories to include based on a named query's category filters; used as the `categories` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_CATEGORIES("expenses")` | β€” |
+| `QUERY_EXTRACT_TIMEFRAME_END` | Query | Extracts the end month from a named query's date range; used as the `endMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_END("expenses")` | β€” |
+| `QUERY_EXTRACT_TIMEFRAME_START` | Query | Extracts the start month from a named query's date range; used as the `startMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_START("expenses")` | β€” |
+| `RANK` | Query | Returns the rank of a number in a list. | `=RANK(10, A1:A10, 0)` | β€” |
+| `RATE` | Query | Calculates interest rate per period. | `=RATE(60, -200, 10000)` | β€” |
+| `REPLACE` | Query, Rules | Replaces substring at specified position. | `=REPLACE(notes, 1, 5, "")` | β€” |
+| `REPT` | Query, Rules | Repeats text specified number of times. | `=REPT("*", 10)` | β€” |
+| `RIGHT` | Query, Rules | Returns rightmost characters from text. | `=RIGHT(imported_payee, 4)` | β€” |
+| `ROUND` | Query, Rules | Rounds a number to specified decimals. | `=ROUND(amount/100, 2)` | β€” |
+| `ROUNDDOWN` | Query, Rules | Rounds down to specified decimals. | `=ROUNDDOWN(amount/100, 0)` | β€” |
+| `ROUNDUP` | Query, Rules | Rounds up to specified decimals. | `=ROUNDUP(amount/100, 0)` | β€” |
+| `SEARCH` | Query, Rules | Finds text within text (case-insensitive, supports wildcards). | `=SEARCH("foo", notes)` | β€” |
+| `SIGN` | Rules | Returns -1 for negative, 0 for zero, 1 for positive. | `=SIGN(amount)` | β€” |
+| `SIN` | Query | Returns the sine of an angle. | `=SIN(1)` | β€” |
+| `SPLIT` | Rules | Splits text by space and returns part at index. | `=SPLIT(imported_payee, 0)` | β€” |
+| `SQRT` | Query, Rules | Returns the square root. | `=SQRT(9)` | β€” |
+| `STDEV` | Query | Returns the standard deviation of a sample. | `=STDEV(A1:A10)` | β€” |
+| `STDEVP` | Query | Returns the standard deviation of a population. | `=STDEVP(A1:A10)` | β€” |
+| `SUBSTITUTE` | Query, Rules | Replaces occurrences of text. | `=SUBSTITUTE(imported_payee, " 12345", "")` | β€” |
+| `SUM` | Query, Rules | Returns the sum of all numbers in a range. | `=SUM(1, 2, 3)` | Accepts more than 2 values |
+| `SUMIF` | Query | Sums cells that meet a criteria. | `=SUMIF(A1:A10, ">0", B1:B10)` | β€” |
+| `SUMIFS` | Query | Sums cells that meet multiple criteria. | `=SUMIFS(B1:B10, A1:A10, ">0", C1:C10, "X")` | Repeat `(range, criteria)` pairs |
+| `SUMPRODUCT` | Query | Multiplies corresponding elements and returns the sum. | `=SUMPRODUCT(A1:A10, B1:B10)` | Accepts more arrays |
+| `SUMSQ` | Query | Returns the sum of the squares. | `=SUMSQ(1, 2, 3)` | Accepts more than 2 values |
+| `SWITCH` | Query, Rules | Matches expression against values and returns corresponding result. | `=SWITCH(category_name, "Groceries", "Food", "Fuel", "Transport")` | Repeat `(value, result)` pairs; default supported |
+| `T` | Rules | Returns text if value is text, empty string otherwise. | `=T(notes)` | β€” |
+| `TAN` | Query | Returns the tangent of an angle. | `=TAN(1)` | β€” |
+| `TEXT` | Query, Rules | Converts number to text with format. | `=TEXT(date, "MMMM yyyy")` | β€” |
+| `TODAY` | Query, Rules | Returns current date. | `=TODAY()` | β€” |
+| `TRIM` | Query, Rules | Removes extra spaces from text. | `=TRIM(notes)` | β€” |
+| `TRUNC` | Rules | Truncates number to specified decimals. | `=TRUNC(amount/100, 0)` | β€” |
+| `TRUE` | Query, Rules | Returns the logical value TRUE. | `=TRUE()` | β€” |
+| `UPPER` | Query, Rules | Converts text to uppercase. | `=UPPER(notes)` | β€” |
+| `VALUE` | Rules | Converts text to a number. | `=VALUE("123.45")` | β€” |
+| `VAR` | Query | Returns the variance of a sample. | `=VAR(A1:A10)` | β€” |
+| `VARP` | Query | Returns the variance of a population. | `=VARP(A1:A10)` | β€” |
+| `VLOOKUP` | Query | Searches vertically in first column and returns value. | `=VLOOKUP("key", A1:D10, 2, TRUE)` | β€” |
+| `WEEKDAY` | Query, Rules | Returns day of week (1-7). | `=WEEKDAY(date, 1)` | β€” |
+| `WEEKNUM` | Query, Rules | Returns week number of year. | `=WEEKNUM(date, 1)` | β€” |
+| `XOR` | Query, Rules | Returns TRUE if odd number of arguments are TRUE. | `=XOR(TRUE(), FALSE())` | Accepts more than 2 conditions |
+| `YEAR` | Query, Rules | Returns the year from a date. | `=YEAR(date)` | β€” |
+
+### Formatting numbers and currency
+
+`FORMATNUMBER` and `FORMATCURRENCY` use your app formatting preferences when optional arguments are omitted.
+
+```text
+=FORMATNUMBER(1234.5, 2)
+=FORMATCURRENCY(1234.5)
+```
+
+You can override separators and currency display for a single formula:
+
+```text
+=FORMATCURRENCY(1234.5, "€", 2, ".", ",", "after", TRUE())
+```
+
+The `symbolPosition` argument accepts `"before"` or `"after"`. The `spaceBetweenAmountAndSymbol` argument accepts `TRUE()` or `FALSE()`.
### Use queries with `QUERY("name")` and `QUERY_COUNT("name")`
diff --git a/packages/loot-core/src/server/budgetfiles/app.ts b/packages/loot-core/src/server/budgetfiles/app.ts
index 99c3f80e04..8d841945d3 100644
--- a/packages/loot-core/src/server/budgetfiles/app.ts
+++ b/packages/loot-core/src/server/budgetfiles/app.ts
@@ -12,6 +12,7 @@ import * as budget from '#server/budget/base';
import * as cloudStorage from '#server/cloud-storage';
import * as db from '#server/db';
import * as mappings from '#server/db/mappings';
+import { resetFormulaPreferencesCache } from '#server/formulas/bootstrap';
import { handleBudgetImport } from '#server/importers';
import type { ImportableBudgetType } from '#server/importers';
import { app as mainApp } from '#server/main-app';
@@ -256,6 +257,7 @@ async function createDemoBudget() {
async function closeBudget() {
captureBreadcrumb({ message: 'Closing budget' });
+ resetFormulaPreferencesCache();
// The spreadsheet may be running, wait for it to complete
await sheet.waitOnSpreadsheet();
@@ -531,6 +533,7 @@ async function _loadBudget(id: Budget['id']): Promise<{
}
try {
+ resetFormulaPreferencesCache();
await prefs.loadPrefs(id);
await db.openDatabase(id);
} catch (e) {
diff --git a/packages/loot-core/src/server/formulas/app.ts b/packages/loot-core/src/server/formulas/app.ts
new file mode 100644
index 0000000000..8c8a4acc95
--- /dev/null
+++ b/packages/loot-core/src/server/formulas/app.ts
@@ -0,0 +1,10 @@
+import { createApp } from '#server/app';
+import { loadUserPreferencesForFormulas } from '#server/formulas/customFunctionsPreferences';
+
+export type FormulasHandlers = {
+ 'formula-load-user-preferences': typeof loadUserPreferencesForFormulas;
+};
+
+export const app = createApp<FormulasHandlers>();
+
+app.method('formula-load-user-preferences', loadUserPreferencesForFormulas);
diff --git a/packages/loot-core/src/server/formulas/bootstrap.test.ts b/packages/loot-core/src/server/formulas/bootstrap.test.ts
new file mode 100644
index 0000000000..d3a51dfa79
--- /dev/null
+++ b/packages/loot-core/src/server/formulas/bootstrap.test.ts
@@ -0,0 +1,136 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as asyncStorage from '#platform/server/asyncStorage';
+import * as aql from '#server/aql';
+import * as db from '#server/db';
+import { handlers } from '#server/main';
+import { runHandler } from '#server/mutators';
+import { Action } from '#server/rules/action';
+
+import {
+ ensureFormulaPreferencesLoaded,
+ resetFormulaPreferencesCache,
+} from './bootstrap';
+import { loadUserPreferencesForFormulas } from './customFunctionsPreferences';
+
+function executeFormula(formula: string) {
+ const action = new Action('set', 'notes', null, { formula });
+ const transaction = { notes: '' };
+
+ action.exec(transaction);
+
+ return transaction.notes;
+}
+
+describe('formula preference bootstrap', () => {
+ beforeEach(async () => {
+ // oxlint-disable-next-line typescript/no-explicit-any
+ await (global as any).emptyDatabase()();
+ vi.clearAllMocks();
+ resetFormulaPreferencesCache();
+ });
+
+ it('reloads cached user preferences after reset', async () => {
+ await ensureFormulaPreferencesLoaded();
+ expect(executeFormula('=FORMATNUMBER(1234.5, 2)')).toBe('1,234.50');
+
+ await db.update('preferences', {
+ id: 'numberFormat',
+ value: 'dot-comma',
+ });
+
+ resetFormulaPreferencesCache();
+ await ensureFormulaPreferencesLoaded();
+
+ expect(executeFormula('=FORMATNUMBER(1234.5, 2)')).toBe('1.234,50');
+ });
+
+ it('infers number separators from locale formatting', async () => {
+ const preferences = await loadUserPreferencesForFormulas({
+ selectedLocale: 'de-DE',
+ });
+
+ expect(preferences.numberFormat).toBe('dot-comma');
+ expect(preferences.decimalPlaces).toBe(2);
+ expect(preferences.thousandsSeparator).toBe('.');
+ expect(preferences.decimalSeparator).toBe(',');
+ });
+
+ it('loads hidden fraction preference for formula number formatting', async () => {
+ await db.update('preferences', {
+ id: 'hideFraction',
+ value: 'true',
+ });
+
+ const preferences = await loadUserPreferencesForFormulas();
+
+ expect(preferences.decimalPlaces).toBe(0);
+ });
+
+ it('loads formula preferences with one preferences query', async () => {
+ const aqlQuerySpy = vi.spyOn(aql, 'aqlQuery');
+
+ await loadUserPreferencesForFormulas();
+
+ expect(aqlQuerySpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('reloads cached user preferences after relevant synced preferences change', async () => {
+ await ensureFormulaPreferencesLoaded();
+ expect(executeFormula('=FORMATNUMBER(1234.5)')).toBe('1,234.50');
+
+ await runHandler(handlers['preferences/save'], {
+ id: 'numberFormat',
+ value: 'dot-comma',
+ });
+ await ensureFormulaPreferencesLoaded();
+
+ expect(executeFormula('=FORMATNUMBER(1234.5)')).toBe('1.234,50');
+ });
+
+ it('reloads cached user preferences after hide fraction changes', async () => {
+ await ensureFormulaPreferencesLoaded();
+ expect(executeFormula('=FORMATNUMBER(1234.5)')).toBe('1,234.50');
+
+ await runHandler(handlers['preferences/save'], {
+ id: 'hideFraction',
+ value: 'true',
+ });
+ await ensureFormulaPreferencesLoaded();
+
+ expect(executeFormula('=FORMATNUMBER(1234.5)')).toBe('1,235');
+ });
+
+ it('keeps cached user preferences after unrelated synced preferences change', async () => {
+ await ensureFormulaPreferencesLoaded();
+ await db.update('preferences', {
+ id: 'numberFormat',
+ value: 'dot-comma',
+ });
+
+ await runHandler(handlers['preferences/save'], {
+ id: 'dateFormat',
+ value: 'dd/MM/yyyy',
+ });
+ await ensureFormulaPreferencesLoaded();
+
+ expect(executeFormula('=FORMATNUMBER(1234.5, 2)')).toBe('1,234.50');
+ });
+
+ it('reloads cached user preferences after language changes', async () => {
+ await ensureFormulaPreferencesLoaded();
+ expect(executeFormula('=FORMATNUMBER(1234.5, 2)')).toBe('1,234.50');
+
+ await runHandler(handlers['save-global-prefs'], {
+ language: 'de-DE',
+ });
+ vi.mocked(asyncStorage.getItem).mockResolvedValue('de-DE');
+ await ensureFormulaPreferencesLoaded();
+
+ expect(vi.mocked(asyncStorage.setItem)).toHaveBeenCalledWith(
+ 'language',
+ 'de-DE',
+ );
+ expect(executeFormula('=FORMATNUMBER(1234.5, 2)')).toBe('1.234,50');
+ });
+});
diff --git a/packages/loot-core/src/server/formulas/bootstrap.ts b/packages/loot-core/src/server/formulas/bootstrap.ts
new file mode 100644
index 0000000000..4166f37b71
--- /dev/null
+++ b/packages/loot-core/src/server/formulas/bootstrap.ts
@@ -0,0 +1,27 @@
+import {
+ clearCachedUserPreferences,
+ setCachedUserPreferences,
+} from '#shared/formulas/customFunctions';
+
+import { loadUserPreferencesForFormulas } from './customFunctionsPreferences';
+
+let formulaPreferencesPromise: Promise<void> | null = null;
+let formulaPreferencesCacheVersion = 0;
+
+export function resetFormulaPreferencesCache(): void {
+ formulaPreferencesCacheVersion += 1;
+ formulaPreferencesPromise = null;
+ clearCachedUserPreferences();
+}
+
+export function ensureFormulaPreferencesLoaded(): Promise<void> {
+ const cacheVersion = formulaPreferencesCacheVersion;
+
+ formulaPreferencesPromise ??= loadUserPreferencesForFormulas().then(prefs => {
+ if (cacheVersion === formulaPreferencesCacheVersion) {
+ setCachedUserPreferences(prefs);
+ }
+ });
+
+ return formulaPreferencesPromise;
+}
diff --git a/packages/loot-core/src/server/formulas/customFunctionsPreferences.ts b/packages/loot-core/src/server/formulas/customFunctionsPreferences.ts
new file mode 100644
index 0000000000..c9cfc06d4d
--- /dev/null
+++ b/packages/loot-core/src/server/formulas/customFunctionsPreferences.ts
@@ -0,0 +1,202 @@
+import * as asyncStorage from '#platform/server/asyncStorage';
+import { aqlQuery } from '#server/aql';
+import { getCurrency } from '#shared/currencies';
+import type { Currency } from '#shared/currencies';
+import type { UserPreferences } from '#shared/formulas/customFunctions';
+import { q } from '#shared/query';
+import { getNumberFormat } from '#shared/util';
+import type { NumberFormats } from '#shared/util';
+
+type FormulaPreferencesOptions = {
+ selectedLocale?: string;
+ browserLocale?: string;
+};
+
+type CurrencySymbolPosition = 'before' | 'after';
+
+const DEFAULT_CURRENCY = getCurrency('USD');
+const LOCALE_NUMBER_FORMAT_SAMPLE = 1_000_000.23;
+type FormulaPreferenceId =
+ | 'flags.currency'
+ | 'defaultCurrencyCode'
+ | 'numberFormat'
+ | 'hideFraction'
+ | 'currencySymbolPosition'
+ | 'currencySpaceBetweenAmountAndSymbol';
+
+const FORMULA_PREFERENCE_IDS: FormulaPreferenceId[] = [
+ 'flags.currency',
+ 'defaultCurrencyCode',
+ 'numberFormat',
+ 'hideFraction',
+ 'currencySymbolPosition',
+ 'currencySpaceBetweenAmountAndSymbol',
+];
+
+function normalizeLocale(locale?: string | null): string | null {
+ const normalized = locale?.trim();
+ return normalized ? normalized : null;
+}
+
+function getLocaleDefaults(locale?: string): {
+ thousandsSeparator: string;
+ decimalSeparator: string;
+} {
+ const parts = new Intl.NumberFormat(locale || 'en-US').formatToParts(
+ LOCALE_NUMBER_FORMAT_SAMPLE,
+ );
+
+ return {
+ thousandsSeparator: parts.find(part => part.type === 'group')?.value ?? ',',
+ decimalSeparator: parts.find(part => part.type === 'decimal')?.value ?? '.',
+ };
+}
+
+function getNumberFormatFromLocale(locale: string): NumberFormats {
+ const { thousandsSeparator, decimalSeparator } = getLocaleDefaults(locale);
+
+ if (decimalSeparator === '.' && thousandsSeparator === ',') {
+ return 'comma-dot';
+ }
+
+ if (decimalSeparator === ',' && thousandsSeparator === '.') {
+ return 'dot-comma';
+ }
+
+ if (decimalSeparator === ',' && thousandsSeparator.trim() === '') {
+ return 'space-comma';
+ }
+
+ if (
+ decimalSeparator === '.' &&
+ (thousandsSeparator === "'" || thousandsSeparator === '\u2019')
+ ) {
+ return 'apostrophe-dot';
+ }
+
+ return 'comma-dot';
+}
+
+function getCurrencyFromPreference(
+ currencyCode: string | null,
+): Currency | null {
+ if (!currencyCode) {
+ return null;
+ }
+
+ const currency = getCurrency(currencyCode);
+ return currency.code ? currency : null;
+}
+
+function getCurrencySymbolPosition(
+ value: string | null,
+ currency: Currency,
+): CurrencySymbolPosition {
+ if (value === 'before' || value === 'after') {
+ return value;
+ }
+
+ return currency.symbolFirst ? 'before' : 'after';
+}
+
+const DEFAULT_CURRENCY_SYMBOL_POSITION: CurrencySymbolPosition = 'before';
+
+// Function to load user preferences from the database
+// This should be called before formula execution
+export async function loadUserPreferencesForFormulas({
+ selectedLocale,
+ browserLocale,
+}: FormulaPreferencesOptions = {}): Promise<UserPreferences> {
+ try {
+ const preferencesQuery = await aqlQuery(
+ q('preferences')
+ .filter({ id: { $oneof: FORMULA_PREFERENCE_IDS } })
+ .select('*'),
+ );
+
+ const preferences: Partial<Record<FormulaPreferenceId, string | null>> = {};
+ for (const preference of preferencesQuery.data) {
+ preferences[preference.id as FormulaPreferenceId] = preference.value;
+ }
+
+ const isCurrencyFeatureEnabled = preferences['flags.currency'] === 'true';
+ const currencyCode = preferences.defaultCurrencyCode ?? null;
+ const currencyFromPreference = isCurrencyFeatureEnabled
+ ? getCurrencyFromPreference(currencyCode)
+ : null;
+
+ const numberFormatValue =
+ (preferences.numberFormat as NumberFormats | undefined) ?? null;
+ const hideFraction = preferences.hideFraction === 'true';
+
+ const locale =
+ normalizeLocale(selectedLocale) ??
+ normalizeLocale(await asyncStorage.getItem('language')) ??
+ normalizeLocale(browserLocale) ??
+ 'en-US';
+
+ const currency = currencyFromPreference ?? DEFAULT_CURRENCY;
+ const symbolPositionValue = preferences.currencySymbolPosition ?? null;
+ const spaceEnabledValue =
+ preferences.currencySpaceBetweenAmountAndSymbol ?? null;
+ const shouldUseCurrencyPreferences = currencyFromPreference !== null;
+
+ const numberFormat = numberFormatValue
+ ? numberFormatValue
+ : currencyFromPreference?.numberFormat ||
+ getNumberFormatFromLocale(locale);
+
+ // Get number format settings
+ const numberFormatSettings = getNumberFormat({
+ format: numberFormat,
+ });
+
+ // Get locale-based defaults as fallback
+ const localeDefaults = getLocaleDefaults(locale);
+
+ return {
+ currency,
+ numberFormat,
+ decimalPlaces: hideFraction ? 0 : currency.decimalPlaces,
+ thousandsSeparator:
+ numberFormatSettings.thousandsSeparator ||
+ localeDefaults.thousandsSeparator,
+ decimalSeparator:
+ numberFormatSettings.decimalSeparator ||
+ localeDefaults.decimalSeparator,
+ locale,
+ currencySymbolPosition: shouldUseCurrencyPreferences
+ ? getCurrencySymbolPosition(symbolPositionValue, currency)
+ : DEFAULT_CURRENCY_SYMBOL_POSITION,
+ currencySpaceBetweenAmountAndSymbol: shouldUseCurrencyPreferences
+ ? spaceEnabledValue === 'true'
+ : false,
+ };
+ } catch {
+ const locale =
+ normalizeLocale(selectedLocale) ??
+ normalizeLocale(browserLocale) ??
+ 'en-US';
+ const currency = DEFAULT_CURRENCY;
+ const numberFormat = getNumberFormatFromLocale(locale);
+ const numberFormatSettings = getNumberFormat({
+ format: numberFormat,
+ });
+ const localeDefaults = getLocaleDefaults(locale);
+
+ return {
+ currency,
+ numberFormat,
+ decimalPlaces: 2,
+ thousandsSeparator:
+ numberFormatSettings.thousandsSeparator ||
+ localeDefaults.thousandsSeparator,
+ decimalSeparator:
+ numberFormatSettings.decimalSeparator ||
+ localeDefaults.decimalSeparator,
+ locale,
+ currencySymbolPosition: DEFAULT_CURRENCY_SYMBOL_POSITION,
+ currencySpaceBetweenAmountAndSymbol: false,
+ };
+ }
+}
diff --git a/packages/loot-core/src/server/main.ts b/packages/loot-core/src/server/main.ts
index 67034650c7..58373eb95c 100644
--- a/packages/loot-core/src/server/main.ts
+++ b/packages/loot-core/src/server/main.ts
@@ -21,6 +21,7 @@ import * as encryption from './encryption';
import { app as encryptionApp } from './encryption/app';
import { app as filtersApp } from './filters/app';
import { app as forecastApp } from './forecast/app';
+import { app as formulasApp } from './formulas/app';
import { app } from './main-app';
import { mutator, runHandler } from './mutators';
import { app as notesApp } from './notes/app';
@@ -135,6 +136,7 @@ app.combine(
preferencesApp,
toolsApp,
filtersApp,
+ formulasApp,
forecastApp,
reportsApp,
rulesApp,
diff --git a/packages/loot-core/src/server/preferences/app.ts b/packages/loot-core/src/server/preferences/app.ts
index 81818149a0..1a4afbd468 100644
--- a/packages/loot-core/src/server/preferences/app.ts
+++ b/packages/loot-core/src/server/preferences/app.ts
@@ -3,6 +3,7 @@ import * as fs from '#platform/server/fs';
import { createApp } from '#server/app';
import * as db from '#server/db';
import { PostError } from '#server/errors';
+import { resetFormulaPreferencesCache } from '#server/formulas/bootstrap';
import { getDefaultDocumentDir } from '#server/main';
import { mutator } from '#server/mutators';
import { post } from '#server/post';
@@ -27,6 +28,14 @@ export type PreferencesHandlers = {
export const app = createApp<PreferencesHandlers>();
+const FORMULA_FORMAT_SYNCED_PREFS = new Set<keyof SyncedPrefs>([
+ 'numberFormat',
+ 'hideFraction',
+ 'defaultCurrencyCode',
+ 'currencySymbolPosition',
+ 'currencySpaceBetweenAmountAndSymbol',
+]);
+
app.method('preferences/save', mutator(undoable(saveSyncedPrefs)));
app.method('preferences/get', getSyncedPrefs);
app.method('save-global-prefs', saveGlobalPrefs);
@@ -50,6 +59,10 @@ async function saveSyncedPrefs({
id,
value,
});
+
+ if (FORMULA_FORMAT_SYNCED_PREFS.has(id)) {
+ resetFormulaPreferencesCache();
+ }
}
async function getSyncedPrefs(): Promise<SyncedPrefs> {
@@ -85,6 +98,7 @@ async function saveGlobalPrefs(prefs: GlobalPrefs) {
}
if (prefs.language !== undefined) {
await asyncStorage.setItem('language', prefs.language);
+ resetFormulaPreferencesCache();
}
if (prefs.theme !== undefined) {
await asyncStorage.setItem('theme', prefs.theme);
diff --git a/packages/loot-core/src/server/reports/formula-card-integration.test.ts b/packages/loot-core/src/server/reports/formula-card-integration.test.ts
new file mode 100644
index 0000000000..cd401b7522
--- /dev/null
+++ b/packages/loot-core/src/server/reports/formula-card-integration.test.ts
@@ -0,0 +1,739 @@
+import { HyperFormula } from 'hyperformula';
+import enUS from 'hyperformula/i18n/languages/enUS';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { aqlQuery } from '#server/aql';
+import * as db from '#server/db';
+import { loadMappings } from '#server/db/mappings';
+import { conditionsToAQL } from '#server/transactions/transaction-rules';
+import {
+ CustomFunctionsPlugin,
+ customFunctionsTranslations,
+} from '#shared/formulas/customFunctions';
+import { q } from '#shared/query';
+
+// Integration tests for formula cards with real database queries
+// These tests validate formulas with actual query results from the database
+
+// Register HyperFormula language and plugins if not already registered
+try {
+ HyperFormula.registerLanguage('enUS', enUS);
+} catch {
+ // Already registered, ignore
+}
+
+try {
+ HyperFormula.registerFunctionPlugin(
+ CustomFunctionsPlugin,
+ customFunctionsTranslations,
+ );
+} catch {
+ // Already registered, ignore
+}
+
+beforeEach(async () => {
+ // oxlint-disable-next-line typescript/no-explicit-any
+ await (global as any).emptyDatabase()();
+ await loadMappings();
+});
+
+describe('Formula Card - Integration Tests with Queries', () => {
+ // Helper functions using db helper methods
+ async function createTestAccount(name: string) {
+ return await db.insertAccount({ name });
+ }
+
+ async function createCategoryGroup(name: string) {
+ return await db.insertCategoryGroup({ name });
+ }
+
+ async function createTestCategory(
+ name: string,
+ groupId: string,
+ isIncome = false,
+ ) {
+ return await db.insertCategory({
+ name,
+ cat_group: groupId,
+ is_income: isIncome ? 1 : 0,
+ });
+ }
+
+ async function createTestTransaction(data: {
+ accountId: string;
+ amount: number;
+ date: string;
+ categoryId?: string;
+ notes?: string;
+ }) {
+ return await db.insertTransaction({
+ account: data.accountId,
+ amount: data.amount,
+ date: data.date,
+ category: data.categoryId || null,
+ notes: data.notes || null,
+ });
+ }
+
+ async function executeQuery(
+ conditions: unknown[],
+ timeFrame?: { start?: string; end?: string },
+ ) {
+ // Simulate query execution like the formula card does
+ const { filters } = conditionsToAQL(conditions);
+
+ let transQuery = q('transactions');
+
+ if (timeFrame?.start && timeFrame?.end) {
+ transQuery = transQuery.filter({
+ $and: [
+ { date: { $gte: timeFrame.start } },
+ { date: { $lte: timeFrame.end } },
+ ],
+ });
+ }
+
+ if (filters.length > 0) {
+ transQuery = transQuery.filter({ $and: filters });
+ }
+
+ const summedQuery = transQuery.calculate({ $sum: '$amount' });
+ const { data } = await aqlQuery(summedQuery);
+ return data || 0;
+ }
+
+ async function executeFormulaWithQuery(
+ formula: string,
+ queryResults: Record<string, number>,
+ ) {
+ let hfInstance: ReturnType<typeof HyperFormula.buildEmpty> | null = null;
+
+ try {
+ hfInstance = HyperFormula.buildEmpty({
+ licenseKey: 'gpl-v3',
+ language: 'enUS',
+ dateFormats: ['DD/MM/YYYY', 'YYYY-MM-DD', 'YYYY/MM/DD'],
+ });
+
+ const sheetName = hfInstance.addSheet('Sheet1');
+ const sheetId = hfInstance.getSheetId(sheetName);
+
+ if (sheetId === undefined) {
+ throw new Error('Failed to create sheet');
+ }
+
+ // Replace QUERY() calls with actual values
+ let processedFormula = formula;
+ for (const [queryName, value] of Object.entries(queryResults)) {
+ const regex = new RegExp(
+ `QUERY\\s*\\(\\s*["']${queryName}["']\\s*\\)`,
+ 'gi',
+ );
+ // Convert cents to dollars for display
+ const dollarValue = value / 100;
+ processedFormula = processedFormula.replace(regex, String(dollarValue));
+ }
+
+ hfInstance.setCellContents({ sheet: sheetId, col: 0, row: 0 }, [
+ [processedFormula],
+ ]);
+
+ const cellValue = hfInstance.getCellValue({
+ sheet: sheetId,
+ col: 0,
+ row: 0,
+ });
+
+ if (cellValue && typeof cellValue === 'object' && 'type' in cellValue) {
+ throw new Error(`Formula error: ${cellValue.type}`);
+ }
+
+ return cellValue;
+ } finally {
+ hfInstance?.destroy();
+ }
+ }
+
+ describe('Basic Query Integration', () => {
+ it('should execute formula with single query result', async () => {
+ // Integration test: Simple query sum with formula
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Expenses');
+ const categoryId = await createTestCategory('Groceries', groupId);
+
+ // Create test transactions
+ await createTestTransaction({
+ accountId,
+ amount: -5000,
+ date: '2024-01-15',
+ categoryId,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -7500,
+ date: '2024-01-20',
+ categoryId,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -3000,
+ date: '2024-01-25',
+ categoryId,
+ });
+
+ // Execute query
+ const queryResult = await executeQuery([
+ { field: 'category', op: 'is', value: categoryId, type: 'id' },
+ ]);
+
+ // Execute formula with query result
+ const formula = '=FORMATCURRENCY(QUERY("Groceries"))';
+ const result = await executeFormulaWithQuery(formula, {
+ Groceries: queryResult,
+ });
+
+ // FORMATCURRENCY places negative sign before currency symbol
+ expect(result).toBe('-$155.00');
+ });
+
+ it('should calculate percentage from query results', async () => {
+ // Integration test: Calculate spending as percentage of income
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Income');
+ const incomeCategory = await createTestCategory('Salary', groupId, true);
+ const expenseGroup = await createCategoryGroup('Expenses');
+ const expenseCategory = await createTestCategory('Food', expenseGroup);
+
+ // Create income
+ await createTestTransaction({
+ accountId,
+ amount: 500000, // $5000
+ date: '2024-01-01',
+ categoryId: incomeCategory,
+ });
+
+ // Create expenses
+ await createTestTransaction({
+ accountId,
+ amount: -75000, // $750
+ date: '2024-01-15',
+ categoryId: expenseCategory,
+ });
+
+ const incomeResult = await executeQuery([
+ { field: 'category', op: 'is', value: incomeCategory, type: 'id' },
+ ]);
+
+ const expenseResult = await executeQuery([
+ { field: 'category', op: 'is', value: expenseCategory, type: 'id' },
+ ]);
+
+ const formula =
+ '=CONCATENATE(FORMATNUMBER((ABS(QUERY("Expenses")) / QUERY("Income")) * 100, 1), "%")';
+ const result = await executeFormulaWithQuery(formula, {
+ Income: incomeResult,
+ Expenses: expenseResult,
+ });
+
+ expect(result).toBe('15.0%');
+ });
+
+ it('should format large query results with thousands separators', async () => {
+ // Integration test: Format large numbers from queries
+ const accountId = await createTestAccount('Investment');
+ const groupId = await createCategoryGroup('Income');
+ const categoryId = await createTestCategory('Dividends', groupId, true);
+
+ // Create large transactions
+ await createTestTransaction({
+ accountId,
+ amount: 123456789, // $1,234,567.89
+ date: '2024-01-01',
+ categoryId,
+ });
+
+ const queryResult = await executeQuery([
+ { field: 'category', op: 'is', value: categoryId, type: 'id' },
+ ]);
+
+ const formula = '=FORMATNUMBER(QUERY("Dividends"), 2)';
+ const result = await executeFormulaWithQuery(formula, {
+ Dividends: queryResult,
+ });
+
+ expect(result).toBe('1,234,567.89');
+ });
+ });
+
+ describe('Multiple Query Integration', () => {
+ it('should combine multiple query results in formula', async () => {
+ // Integration test: Calculate net worth from multiple queries
+ const checkingId = await createTestAccount('Checking');
+ const savingsId = await createTestAccount('Savings');
+ const creditCardId = await createTestAccount('Credit Card');
+
+ // Create transactions
+ await createTestTransaction({
+ accountId: checkingId,
+ amount: 250000, // $2500
+ date: '2024-01-01',
+ });
+ await createTestTransaction({
+ accountId: savingsId,
+ amount: 1000000, // $10000
+ date: '2024-01-01',
+ });
+ await createTestTransaction({
+ accountId: creditCardId,
+ amount: -50000, // -$500
+ date: '2024-01-01',
+ });
+
+ const checkingResult = await executeQuery([
+ { field: 'account', op: 'is', value: checkingId, type: 'id' },
+ ]);
+
+ const savingsResult = await executeQuery([
+ { field: 'account', op: 'is', value: savingsId, type: 'id' },
+ ]);
+
+ const creditCardResult = await executeQuery([
+ { field: 'account', op: 'is', value: creditCardId, type: 'id' },
+ ]);
+
+ const formula =
+ '=FORMATCURRENCY(QUERY("Checking") + QUERY("Savings") + QUERY("CreditCard"))';
+ const result = await executeFormulaWithQuery(formula, {
+ Checking: checkingResult,
+ Savings: savingsResult,
+ CreditCard: creditCardResult,
+ });
+
+ // Query results: 250000 + 1000000 - 50000 = 1200000 cents = 12000 dollars
+ expect(result).toBe('$12,000.00');
+ });
+
+ it('should calculate ratios between multiple queries', async () => {
+ // Integration test: Calculate savings rate
+ const accountId = await createTestAccount('Checking');
+ const incomeGroup = await createCategoryGroup('Income');
+ const incomeCategory = await createTestCategory(
+ 'Salary',
+ incomeGroup,
+ true,
+ );
+ const savingsGroup = await createCategoryGroup('Savings');
+ const savingsCategory = await createTestCategory('Savings', savingsGroup);
+
+ await createTestTransaction({
+ accountId,
+ amount: 600000, // $6000 income
+ date: '2024-01-01',
+ categoryId: incomeCategory,
+ });
+
+ await createTestTransaction({
+ accountId,
+ amount: -120000, // $1200 savings
+ date: '2024-01-15',
+ categoryId: savingsCategory,
+ });
+
+ const incomeResult = await executeQuery([
+ { field: 'category', op: 'is', value: incomeCategory, type: 'id' },
+ ]);
+
+ const savingsResult = await executeQuery([
+ { field: 'category', op: 'is', value: savingsCategory, type: 'id' },
+ ]);
+
+ const formula =
+ '=CONCATENATE("Savings Rate: ", FORMATNUMBER((ABS(QUERY("Savings")) / QUERY("Income")) * 100, 1), "%")';
+ const result = await executeFormulaWithQuery(formula, {
+ Income: incomeResult,
+ Savings: savingsResult,
+ });
+
+ expect(result).toBe('Savings Rate: 20.0%');
+ });
+ });
+
+ describe('Complex Nested Formulas with Queries', () => {
+ it('should handle deeply nested calculations with multiple queries', async () => {
+ // Integration test: Complex budget analysis
+ const accountId = await createTestAccount('Checking');
+ const incomeGroup = await createCategoryGroup('Income');
+ const incomeCategory = await createTestCategory(
+ 'Salary',
+ incomeGroup,
+ true,
+ );
+ const needsGroup = await createCategoryGroup('Needs');
+ const needsCategory = await createTestCategory('Housing', needsGroup);
+ const wantsGroup = await createCategoryGroup('Wants');
+ const wantsCategory = await createTestCategory(
+ 'Entertainment',
+ wantsGroup,
+ );
+
+ await createTestTransaction({
+ accountId,
+ amount: 500000, // $5000 income
+ date: '2024-01-01',
+ categoryId: incomeCategory,
+ });
+
+ await createTestTransaction({
+ accountId,
+ amount: -200000, // $2000 needs
+ date: '2024-01-10',
+ categoryId: needsCategory,
+ });
+
+ await createTestTransaction({
+ accountId,
+ amount: -100000, // $1000 wants
+ date: '2024-01-15',
+ categoryId: wantsCategory,
+ });
+
+ const incomeResult = await executeQuery([
+ { field: 'category', op: 'is', value: incomeCategory, type: 'id' },
+ ]);
+
+ const needsResult = await executeQuery([
+ { field: 'category', op: 'is', value: needsCategory, type: 'id' },
+ ]);
+
+ const wantsResult = await executeQuery([
+ { field: 'category', op: 'is', value: wantsCategory, type: 'id' },
+ ]);
+
+ const formula =
+ '=CONCATENATE("Income: ", FORMATCURRENCY(QUERY("Income")), " | Needs: ", FORMATNUMBER((ABS(QUERY("Needs")) / QUERY("Income")) * 100, 0), "% | Wants: ", FORMATNUMBER((ABS(QUERY("Wants")) / QUERY("Income")) * 100, 0), "%")';
+ const result = await executeFormulaWithQuery(formula, {
+ Income: incomeResult,
+ Needs: needsResult,
+ Wants: wantsResult,
+ });
+
+ // Income: 500000 cents = 5000 dollars
+ expect(result).toBe('Income: $5,000.00 | Needs: 40% | Wants: 20%');
+ });
+
+ it('should use conditional logic with query results', async () => {
+ // Integration test: Budget status with IF statements
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Expenses');
+ const categoryId = await createTestCategory('Dining', groupId);
+
+ await createTestTransaction({
+ accountId,
+ amount: -35000, // $350
+ date: '2024-01-15',
+ categoryId,
+ });
+
+ const queryResult = await executeQuery([
+ { field: 'category', op: 'is', value: categoryId, type: 'id' },
+ ]);
+
+ const formula =
+ '=IF(ABS(QUERY("Dining")) > 400, "Over Budget", IF(ABS(QUERY("Dining")) > 300, "Near Limit", "On Track"))';
+ const result = await executeFormulaWithQuery(formula, {
+ Dining: queryResult,
+ });
+
+ expect(result).toBe('Near Limit');
+ });
+
+ it('should create multi-line output with query results', async () => {
+ // Integration test: Multi-line summary with CHAR(10)
+ const accountId = await createTestAccount('Checking');
+ const incomeGroup = await createCategoryGroup('Income');
+ const incomeCategory = await createTestCategory(
+ 'Salary',
+ incomeGroup,
+ true,
+ );
+ const expenseGroup = await createCategoryGroup('Expenses');
+ const expenseCategory = await createTestCategory('Total', expenseGroup);
+
+ await createTestTransaction({
+ accountId,
+ amount: 400000, // $4000
+ date: '2024-01-01',
+ categoryId: incomeCategory,
+ });
+
+ await createTestTransaction({
+ accountId,
+ amount: -150000, // $1500
+ date: '2024-01-15',
+ categoryId: expenseCategory,
+ });
+
+ const incomeResult = await executeQuery([
+ { field: 'category', op: 'is', value: incomeCategory, type: 'id' },
+ ]);
+
+ const expenseResult = await executeQuery([
+ { field: 'category', op: 'is', value: expenseCategory, type: 'id' },
+ ]);
+
+ const formula =
+ '=CONCATENATE("Income: ", FORMATCURRENCY(QUERY("Income")), CHAR(10), "Expenses: ", FORMATCURRENCY(QUERY("Expenses")), CHAR(10), "Net: ", FORMATCURRENCY(QUERY("Income") + QUERY("Expenses")))';
+ const result = await executeFormulaWithQuery(formula, {
+ Income: incomeResult,
+ Expenses: expenseResult,
+ });
+
+ // Income: 400000 cents = 4000 dollars, Expenses: -150000 cents = -1500 dollars
+ expect(result).toContain('Income: $4,000.00');
+ expect(result).toContain('\n');
+ expect(result).toContain('Expenses: -$1,500.00');
+ expect(result).toContain('Net: $2,500.00');
+ });
+ });
+
+ describe('Date-based Query Integration', () => {
+ it('should filter queries by date range', async () => {
+ // Integration test: Query with time frame
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Expenses');
+ const categoryId = await createTestCategory('Shopping', groupId);
+
+ // Transactions in different months
+ await createTestTransaction({
+ accountId,
+ amount: -10000,
+ date: '2024-01-15',
+ categoryId,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -15000,
+ date: '2024-02-15',
+ categoryId,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -20000,
+ date: '2024-03-15',
+ categoryId,
+ });
+
+ // Query only January
+ const queryResult = await executeQuery(
+ [{ field: 'category', op: 'is', value: categoryId, type: 'id' }],
+ { start: '2024-01-01', end: '2024-01-31' },
+ );
+
+ const formula = '=FORMATCURRENCY(QUERY("Shopping"))';
+ const result = await executeFormulaWithQuery(formula, {
+ Shopping: queryResult,
+ });
+
+ // Query result: -10000 cents = -100 dollars
+ expect(result).toBe('-$100.00');
+ });
+
+ it('should compare different time periods', async () => {
+ // Integration test: Month-over-month comparison
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Expenses');
+ const categoryId = await createTestCategory('Utilities', groupId);
+
+ await createTestTransaction({
+ accountId,
+ amount: -12000,
+ date: '2024-01-15',
+ categoryId,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -15000,
+ date: '2024-02-15',
+ categoryId,
+ });
+
+ const jan = await executeQuery(
+ [{ field: 'category', op: 'is', value: categoryId, type: 'id' }],
+ { start: '2024-01-01', end: '2024-01-31' },
+ );
+
+ const feb = await executeQuery(
+ [{ field: 'category', op: 'is', value: categoryId, type: 'id' }],
+ { start: '2024-02-01', end: '2024-02-29' },
+ );
+
+ const formula =
+ '=CONCATENATE("Change: ", FORMATNUMBER(((ABS(QUERY("Feb")) - ABS(QUERY("Jan"))) / ABS(QUERY("Jan"))) * 100, 1), "%")';
+ const result = await executeFormulaWithQuery(formula, {
+ Jan: jan,
+ Feb: feb,
+ });
+
+ expect(result).toBe('Change: 25.0%');
+ });
+ });
+
+ describe('Error Handling with Queries', () => {
+ it('should handle empty query results', async () => {
+ // Integration test: Query with no matching transactions
+ const groupId = await createCategoryGroup('Expenses');
+ const categoryId = await createTestCategory('Empty', groupId);
+
+ // No transactions created for this category
+
+ const queryResult = await executeQuery([
+ { field: 'category', op: 'is', value: categoryId, type: 'id' },
+ ]);
+
+ const formula = '=FORMATCURRENCY(QUERY("Empty"))';
+ const result = await executeFormulaWithQuery(formula, {
+ Empty: queryResult,
+ });
+
+ expect(result).toBe('$0.00');
+ });
+
+ it('should handle division by zero with IFERROR', async () => {
+ // Integration test: Safe division with empty query
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Income');
+ const incomeCategory = await createTestCategory('Salary', groupId, true);
+ const expenseGroup = await createCategoryGroup('Expenses');
+ const expenseCategory = await createTestCategory('Food', expenseGroup);
+
+ // Only create expense, no income
+ await createTestTransaction({
+ accountId,
+ amount: -10000,
+ date: '2024-01-15',
+ categoryId: expenseCategory,
+ });
+
+ const incomeResult = await executeQuery([
+ { field: 'category', op: 'is', value: incomeCategory, type: 'id' },
+ ]);
+
+ const expenseResult = await executeQuery([
+ { field: 'category', op: 'is', value: expenseCategory, type: 'id' },
+ ]);
+
+ const formula =
+ '=IFERROR(CONCATENATE(FORMATNUMBER((ABS(QUERY("Expenses")) / QUERY("Income")) * 100, 0), "%"), "No Income")';
+ const result = await executeFormulaWithQuery(formula, {
+ Income: incomeResult,
+ Expenses: expenseResult,
+ });
+
+ expect(result).toBe('No Income');
+ });
+ });
+
+ describe('Advanced Query Scenarios', () => {
+ it('should calculate running totals across accounts', async () => {
+ // Integration test: Net worth calculation
+ const checking = await createTestAccount('Checking');
+ const savings = await createTestAccount('Savings');
+ const investment = await createTestAccount('Investment');
+ const creditCard = await createTestAccount('Credit Card');
+
+ await createTestTransaction({
+ accountId: checking,
+ amount: 150000,
+ date: '2024-01-01',
+ });
+ await createTestTransaction({
+ accountId: savings,
+ amount: 500000,
+ date: '2024-01-01',
+ });
+ await createTestTransaction({
+ accountId: investment,
+ amount: 1000000,
+ date: '2024-01-01',
+ });
+ await createTestTransaction({
+ accountId: creditCard,
+ amount: -25000,
+ date: '2024-01-01',
+ });
+
+ const checkingResult = await executeQuery([
+ { field: 'account', op: 'is', value: checking, type: 'id' },
+ ]);
+ const savingsResult = await executeQuery([
+ { field: 'account', op: 'is', value: savings, type: 'id' },
+ ]);
+ const investmentResult = await executeQuery([
+ { field: 'account', op: 'is', value: investment, type: 'id' },
+ ]);
+ const creditCardResult = await executeQuery([
+ { field: 'account', op: 'is', value: creditCard, type: 'id' },
+ ]);
+
+ const formula =
+ '=FORMATCURRENCY(QUERY("Checking") + QUERY("Savings") + QUERY("Investment") + QUERY("CreditCard"))';
+ const result = await executeFormulaWithQuery(formula, {
+ Checking: checkingResult,
+ Savings: savingsResult,
+ Investment: investmentResult,
+ CreditCard: creditCardResult,
+ });
+
+ expect(result).toBe('$16,250.00');
+ });
+
+ it('should use MAX and MIN with query results', async () => {
+ // Integration test: Find highest spending category
+ const accountId = await createTestAccount('Checking');
+ const groupId = await createCategoryGroup('Expenses');
+ const cat1 = await createTestCategory('Category1', groupId);
+ const cat2 = await createTestCategory('Category2', groupId);
+ const cat3 = await createTestCategory('Category3', groupId);
+
+ await createTestTransaction({
+ accountId,
+ amount: -15000,
+ date: '2024-01-15',
+ categoryId: cat1,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -25000,
+ date: '2024-01-15',
+ categoryId: cat2,
+ });
+ await createTestTransaction({
+ accountId,
+ amount: -10000,
+ date: '2024-01-15',
+ categoryId: cat3,
+ });
+
+ const result1 = await executeQuery([
+ { field: 'category', op: 'is', value: cat1, type: 'id' },
+ ]);
+ const result2 = await executeQuery([
+ { field: 'category', op: 'is', value: cat2, type: 'id' },
+ ]);
+ const result3 = await executeQuery([
+ { field: 'category', op: 'is', value: cat3, type: 'id' },
+ ]);
+
+ const formula =
+ '=CONCATENATE("Highest: ", FORMATCURRENCY(MIN(QUERY("Cat1"), QUERY("Cat2"), QUERY("Cat3"))))';
+ const result = await executeFormulaWithQuery(formula, {
+ Cat1: result1,
+ Cat2: result2,
+ Cat3: result3,
+ });
+
+ // MIN of -150, -250, -100 = -250 dollars
+ expect(result).toBe('Highest: -$250.00');
+ });
+ });
+});
diff --git a/packages/loot-core/src/server/rules/action.ts b/packages/loot-core/src/server/rules/action.ts
index bd960afaec..1fa741939c 100644
--- a/packages/loot-core/src/server/rules/action.ts
+++ b/packages/loot-core/src/server/rules/action.ts
@@ -6,14 +6,14 @@ import enUS from 'hyperformula/i18n/languages/enUS';
import { logger } from '#platform/server/log';
import type { TransactionForRules } from '#server/transactions/transaction-rules';
+import {
+ CustomFunctionsPlugin,
+ customFunctionsTranslations,
+} from '#shared/formulas/customFunctions';
import { currentDay, format, parseDate } from '#shared/months';
import { FIELD_TYPES } from '#shared/rules';
import { amountToInteger } from '#shared/util';
-import {
- CustomFunctionsPlugin,
- customFunctionsTranslations,
-} from './customFunctions';
import { assert } from './rule-utils';
if (!HyperFormula.getRegisteredLanguagesCodes().includes('enUS')) {
diff --git a/packages/loot-core/src/server/rules/customFunctions.test.ts b/packages/loot-core/src/server/rules/customFunctions.test.ts
index 4c7875b10b..c839e5c433 100644
--- a/packages/loot-core/src/server/rules/customFunctions.test.ts
+++ b/packages/loot-core/src/server/rules/customFunctions.test.ts
@@ -6,8 +6,8 @@ import {
createBudgetQueryPrefetchKey,
CustomFunctionsPlugin,
customFunctionsTranslations,
-} from './customFunctions';
-import type { FormulaQueryContext } from './customFunctions';
+} from '#shared/formulas/customFunctions';
+import type { FormulaQueryContext } from '#shared/formulas/customFunctions';
function createFormulaQueryContext(): Required<FormulaQueryContext> {
return {
diff --git a/packages/loot-core/src/server/rules/formula-action-integration.test.ts b/packages/loot-core/src/server/rules/formula-action-integration.test.ts
new file mode 100644
index 0000000000..83cf3b5122
--- /dev/null
+++ b/packages/loot-core/src/server/rules/formula-action-integration.test.ts
@@ -0,0 +1,1159 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import * as db from '#server/db';
+import { loadMappings } from '#server/db/mappings';
+import {
+ insertRule,
+ loadRules,
+ resetState,
+ runRules,
+} from '#server/transactions/transaction-rules';
+
+// Integration tests for formula-based rule actions
+// These tests validate formulas with real transaction data and rule execution
+// Note: Rules must have conditions on 'imported_payee' or 'payee' to be indexed and executed
+
+beforeEach(async () => {
+ // oxlint-disable-next-line typescript/no-explicit-any
+ await (global as any).emptyDatabase()();
+ resetState();
+ await loadMappings();
+ await loadRules();
+});
+
+describe('Formula Rule Actions - Integration Tests', () => {
+ describe('Basic Formula Operations', () => {
+ it('should calculate percentage of transaction amount with FORMATCURRENCY', async () => {
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Bank' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Interest: ", FORMATCURRENCY(amount * 0.05))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 100000, // $1000.00 in cents
+ date: '2024-01-01',
+ imported_payee: 'Bank Transfer',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Interest: $5,000.00');
+ });
+
+ it('should use nested IF statements with transaction fields', async () => {
+ // Integration test: Complex nested IF for categorization
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Store' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=IF(amount > 0, "Income", IF(ABS(amount) > 10000, "Large Expense", IF(ABS(amount) > 5000, "Medium Expense", "Small Expense")))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000, // -$50.00
+ date: '2024-01-15',
+ imported_payee: 'Store Purchase',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Small Expense');
+ });
+
+ it('should format dates with TEXT function', async () => {
+ // Integration test: Format transaction date
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Shop' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Transaction on ", TEXT(date, "MMMM DD, YYYY"))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -2500,
+ date: '2024-03-15',
+ imported_payee: 'Shop',
+ notes: '',
+ });
+
+ expect(transaction.notes).toContain('Transaction on');
+ expect(transaction.notes).toContain('2024');
+ });
+ });
+
+ describe('Text Manipulation Functions', () => {
+ it('should use CONCATENATE with UPPER and FORMATCURRENCY', async () => {
+ // Integration test: Build descriptive notes from multiple fields
+ const payeeId = await db.insertPayee({ name: 'Amazon' });
+
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [{ field: 'payee', op: 'is', value: payeeId }],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE(UPPER(payee_name), " - ", FORMATCURRENCY(amount / 100), " on ", TEXT(date, "MM/DD/YYYY"))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -15000, // cents
+ date: '2024-02-10',
+ payee: payeeId,
+ payee_name: 'Amazon',
+ _payee_name: 'Amazon',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('AMAZON - -$150.00 on 02/10/2024');
+ });
+
+ it('should extract parts of text with RIGHT', async () => {
+ // Integration test: Parse imported payee name
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'DEBIT CARD' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=CONCATENATE("Store: ", RIGHT(imported_payee, 10))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-01-20',
+ imported_payee: 'DEBIT CARD PURCHASE - STORE #1234',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Store: TORE #1234');
+ });
+
+ it('should use TRIM and PROPER for text formatting', async () => {
+ // Integration test: Clean and format text
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'grocery' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=PROPER(TRIM(imported_payee))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -2000,
+ date: '2024-01-30',
+ imported_payee: ' grocery shopping ',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Grocery Shopping');
+ });
+
+ it('should use LEFT to extract prefix', async () => {
+ // Integration test: Extract first part of payee name
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Amazon' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=CONCATENATE("Merchant: ", LEFT(imported_payee, 6))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -8000,
+ date: '2024-02-01',
+ imported_payee: 'Amazon Prime Subscription',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Merchant: Amazon');
+ });
+ });
+
+ describe('Math and Rounding Functions', () => {
+ it('should calculate split amounts with ROUND and FORMATCURRENCY', async () => {
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Split' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Split: ", FORMATCURRENCY(ROUND((amount / 100) * 0.333, 2)))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -10000, // $100.00 in cents
+ date: '2024-01-30',
+ imported_payee: 'Split Payment',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Split: -$33.30');
+ });
+
+ it('should use ABS, MAX for amount calculations', async () => {
+ // Integration test: Calculate fee as percentage with minimum
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [{ field: 'imported_payee', op: 'contains', value: 'Fee' }],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Fee: ", FORMATCURRENCY(MAX((ABS(amount) / 100) * 0.01, 5)))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -50000, // $500.00 in cents
+ date: '2024-02-01',
+ imported_payee: 'Fee Charge',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Fee: $5.00');
+ });
+
+ it('should use CEILING for rounding up', async () => {
+ // Integration test: Round up to nearest dollar
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Round' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Rounded: ", FORMATCURRENCY(CEILING(amount / 100, -1)))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -4567, // $45.67 in cents
+ date: '2024-02-05',
+ imported_payee: 'Round Up',
+ notes: '',
+ });
+
+ // CEILING rounds toward positive infinity, so -45.67 rounds to -46
+ expect(transaction.notes).toBe('Rounded: -$46.00');
+ });
+
+ it('should use SQRT for calculations', async () => {
+ // Integration test: Square root calculation
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Math' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Square root: ", FORMATNUMBER(SQRT(ABS(amount)), 2))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 10000, // $100.00
+ date: '2024-02-10',
+ imported_payee: 'Math Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Square root: 100.00');
+ });
+ });
+
+ describe('Date Functions', () => {
+ it('should extract date components with YEAR, MONTH, DAY', async () => {
+ // Integration test: Build date description
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Date' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Year: ", YEAR(date), ", Month: ", MONTH(date), ", Day: ", DAY(date))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -7500,
+ date: '2024-06-15',
+ imported_payee: 'Date Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Year: 2024, Month: 6, Day: 15');
+ });
+
+ it('should calculate date differences with DAYS', async () => {
+ // Integration test: Calculate days since transaction
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Days' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Days since: ", DAYS(TODAY(), date), " days")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-01-01',
+ imported_payee: 'Days Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toContain('Days since:');
+ expect(transaction.notes).toContain('days');
+ });
+
+ it('should use EOMONTH for end-of-month calculations', async () => {
+ // Integration test: Calculate next billing date
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Billing' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Due: ", TEXT(EOMONTH(date, 0), "YYYY-MM-DD"))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -12000,
+ date: '2024-03-15',
+ imported_payee: 'Billing Cycle',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Due: 2024-03-31');
+ });
+
+ it('should use WEEKDAY to determine day of week', async () => {
+ // Integration test: Check if transaction is on weekend
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Week' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=IF(OR(WEEKDAY(date) = 1, WEEKDAY(date) = 7), "Weekend", "Weekday")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -3000,
+ date: '2024-01-15', // Monday
+ imported_payee: 'Week Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Weekday');
+ });
+ });
+
+ describe('Logical Functions', () => {
+ it('should use AND/OR for complex conditions', async () => {
+ // Integration test: Complex logical conditions
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Logic' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=IF(AND(amount < 0, ABS(amount) > 10000), "Large Expense", IF(OR(amount > 0, ABS(amount) < 1000), "Small Transaction", "Medium Transaction"))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -15000,
+ date: '2024-02-20',
+ imported_payee: 'Logic Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Large Expense');
+ });
+
+ it('should use IFERROR for safe calculations', async () => {
+ // Integration test: Handle potential errors gracefully
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Error' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=IFERROR(CONCATENATE("Ratio: ", ROUND(10000 / amount, 2)), "Cannot divide by zero")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 0,
+ date: '2024-02-25',
+ imported_payee: 'Error Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Cannot divide by zero');
+ });
+
+ it('should use SWITCH for multiple value matching', async () => {
+ // Integration test: Map month numbers to quarters
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Quarter' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Quarter: ", SWITCH(MONTH(date), 1, "Q1", 2, "Q1", 3, "Q1", 4, "Q2", 5, "Q2", 6, "Q2", 7, "Q3", 8, "Q3", 9, "Q3", 10, "Q4", 11, "Q4", 12, "Q4", "Unknown"))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -8000,
+ date: '2024-04-10',
+ imported_payee: 'Quarter Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Quarter: Q2');
+ });
+
+ it('should use NOT to invert conditions', async () => {
+ // Integration test: Use NOT for logical inversion
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [{ field: 'imported_payee', op: 'contains', value: 'Not' }],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=IF(NOT(amount > 0), "Expense", "Income")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-03-01',
+ imported_payee: 'Not Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Expense');
+ });
+ });
+
+ describe('New Formatting Functions', () => {
+ it('should use FORMATNUMBER for thousands separators', async () => {
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Format' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Amount: ", FORMATNUMBER(amount / 100, 2))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 123456789, // $1,234,567.89
+ date: '2024-03-01',
+ imported_payee: 'Format Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Amount: 1,234,567.89');
+ });
+
+ it('should use FORMATCURRENCY with custom symbols', async () => {
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Euro' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=FORMATCURRENCY(amount / 100, "€", 2)',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -50000, // cents
+ date: '2024-03-05',
+ imported_payee: 'Euro Transaction',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('-€500.00');
+ });
+
+ it('should use FORMATCURRENCY with European format', async () => {
+ // Integration test: Format with European separators (. for thousands, , for decimal)
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [{ field: 'imported_payee', op: 'contains', value: 'EU' }],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=FORMATCURRENCY(amount / 100, "€", 2, ".", ",")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 123456789,
+ date: '2024-03-10',
+ imported_payee: 'EU Payment',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('€1.234.567,89');
+ });
+
+ it('should use FORMATNUMBER without decimals', async () => {
+ // Integration test: Format whole numbers
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Whole' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=FORMATNUMBER(amount / 100, 0)',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 1234500,
+ date: '2024-03-15',
+ imported_payee: 'Whole Number',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('12,345');
+ });
+ });
+
+ describe('Complex Nested Formulas', () => {
+ it('should handle deeply nested calculations', async () => {
+ // Integration test: Complex financial calculation with multiple nested functions
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Loan' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Payment: ", FORMATCURRENCY(amount / 100), " | Principal: ", FORMATCURRENCY((amount / 100) * 0.8), " | Interest: ", FORMATCURRENCY((amount / 100) * 0.2), " | Month: ", MONTH(date))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -100000, // $1000 payment in cents
+ date: '2024-01-15',
+ imported_payee: 'Loan Payment',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe(
+ 'Payment: -$1,000.00 | Principal: -$800.00 | Interest: -$200.00 | Month: 1',
+ );
+ });
+
+ it('should combine multiple function types in one formula', async () => {
+ // Integration test: Mix text, math, date, and logical functions
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Grocery' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE(UPPER(LEFT(imported_payee, 7)), " - ", IF(WEEKDAY(date) = 1, "Weekend", "Weekday"), " - ", FORMATCURRENCY(ABS(amount) / 100), " - ", MONTH(date), "/", DAY(date))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -8500, // cents
+ date: '2024-02-14',
+ imported_payee: 'Grocery Store',
+ notes: '',
+ });
+
+ expect(transaction.notes).toContain('GROCERY');
+ expect(transaction.notes).toContain('$85.00');
+ expect(transaction.notes).toContain('2/14');
+ });
+
+ it('should use CHOOSE for index-based selection', async () => {
+ // Integration test: Select value based on month (season calculation)
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Season' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Season: ", CHOOSE(CEILING(MONTH(date) / 3, 1), "Winter", "Spring", "Summer", "Fall"))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-07-15', // July = month 7, ceiling(7/3) = 3 = Summer
+ imported_payee: 'Season Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Season: Summer');
+ });
+ });
+
+ describe('Multi-line Output with CHAR(10)', () => {
+ it('should create multi-line notes with line breaks', async () => {
+ const payeeId = await db.insertPayee({ name: 'Amazon' });
+
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [{ field: 'payee', op: 'is', value: payeeId }],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Merchant: ", payee_name, CHAR(10), "Amount: ", FORMATCURRENCY(amount / 100), CHAR(10), "Date: ", YEAR(date), "-", MONTH(date), "-", DAY(date))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -25000, // cents
+ date: '2024-03-20',
+ payee: payeeId,
+ payee_name: 'Amazon',
+ _payee_name: 'Amazon',
+ notes: '',
+ });
+
+ expect(transaction.notes).toContain('Merchant: Amazon');
+ expect(transaction.notes).toContain('\n');
+ expect(transaction.notes).toContain('Amount: -$250.00');
+ expect(transaction.notes).toContain('Date: 2024-3-20');
+ });
+
+ it('should create multi-line summary with multiple calculations', async () => {
+ // Integration test: Complex multi-line output with tax calculation
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [{ field: 'imported_payee', op: 'contains', value: 'Tax' }],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Transaction Summary", CHAR(10), "Amount: ", FORMATCURRENCY(amount / 100), CHAR(10), "Tax (10%): ", FORMATCURRENCY((amount / 100) * 0.1), CHAR(10), "Total: ", FORMATCURRENCY((amount / 100) * 1.1))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -10000,
+ date: '2024-04-01',
+ imported_payee: 'Tax Calculation',
+ notes: '',
+ });
+
+ const lines = transaction.notes?.split('\n');
+ expect(lines).toHaveLength(4);
+ expect(lines?.[0]).toBe('Transaction Summary');
+ expect(lines?.[1]).toBe('Amount: -$100.00');
+ expect(lines?.[2]).toBe('Tax (10%): -$10.00');
+ expect(lines?.[3]).toBe('Total: -$110.00');
+ });
+ });
+
+ describe('Information Functions', () => {
+ it('should use ISNUMBER to check value types', async () => {
+ // Integration test: Type checking with ISNUMBER
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Number' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=IF(ISNUMBER(amount), "Valid amount", "Invalid")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 15000,
+ date: '2024-04-10',
+ imported_payee: 'Number Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Valid amount');
+ });
+
+ it('should use ISTEXT to check for text values', async () => {
+ // Integration test: Type checking with ISTEXT
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Text' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=IF(ISTEXT(imported_payee), CONCATENATE("Payee: ", imported_payee), "No payee")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-04-15',
+ imported_payee: 'Text Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Payee: Text Test');
+ });
+
+ it('should use ISEVEN and ISODD for number checks', async () => {
+ // Integration test: Check if amount is even or odd
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Even' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=IF(ISEVEN(ABS(amount)), "Even amount", "Odd amount")',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -10000,
+ date: '2024-04-20',
+ imported_payee: 'Even Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Even amount');
+ });
+
+ it('should use ISBLANK to check for empty values', async () => {
+ // Integration test: Check for blank notes field
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Blank' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=IF(ISBLANK(imported_payee), "No payee", CONCATENATE("Payee: ", imported_payee))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-04-25',
+ imported_payee: 'Blank Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Payee: Blank Test');
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should handle formula errors gracefully', async () => {
+ // Integration test: Invalid formula should not crash
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'DivZero' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula: '=1/0', // Division by zero
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-03-25',
+ imported_payee: 'DivZero Test',
+ notes: 'Original notes',
+ });
+
+ // Should preserve original value on error
+ expect(transaction.notes).toBe('Original notes');
+ });
+
+ it('should validate numeric field output', async () => {
+ // Integration test: String result for numeric field should be rejected
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Invalid' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'amount',
+ value: null,
+ options: {
+ formula: '=UPPER("test")', // Returns string for numeric field
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 10000,
+ date: '2024-03-30',
+ imported_payee: 'Invalid Type',
+ });
+
+ // Should keep original value when formula produces non-numeric result
+ expect(transaction.amount).toBe(10000);
+ });
+ });
+
+ describe('Financial Calculations', () => {
+ it('should calculate compound interest with POWER', async () => {
+ // Integration test: Compound interest formula
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Interest' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Compound: ", FORMATCURRENCY((amount / 100) * POWER(1.05, 12)))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: 100000, // $1000 in cents
+ date: '2024-05-01',
+ imported_payee: 'Interest Calculation',
+ notes: '',
+ });
+
+ expect(transaction.notes).toContain('Compound: $');
+ expect(transaction.notes).toContain('1,795.86');
+ });
+
+ it('should use SUM and PRODUCT for calculations', async () => {
+ // Integration test: Multiple math operations
+ await insertRule({
+ stage: null,
+ conditionsOp: 'and',
+ conditions: [
+ { field: 'imported_payee', op: 'contains', value: 'Calc' },
+ ],
+ actions: [
+ {
+ op: 'set',
+ field: 'notes',
+ value: null,
+ options: {
+ formula:
+ '=CONCATENATE("Sum: ", SUM(100, 200, 300), " | Product: ", PRODUCT(2, 3, 4))',
+ },
+ },
+ ],
+ });
+
+ const transaction = await runRules({
+ amount: -5000,
+ date: '2024-05-05',
+ imported_payee: 'Calc Test',
+ notes: '',
+ });
+
+ expect(transaction.notes).toBe('Sum: 600 | Product: 24');
+ });
+ });
+});
diff --git a/packages/loot-core/src/server/rules/formula-action.test.ts b/packages/loot-core/src/server/rules/formula-action.test.ts
index 43ce5ed2ce..0967932dfa 100644
--- a/packages/loot-core/src/server/rules/formula-action.test.ts
+++ b/packages/loot-core/src/server/rules/formula-action.test.ts
@@ -1,10 +1,25 @@
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it } from 'vitest';
import type { TransactionForRules } from '#server/transactions/transaction-rules';
+import { getCurrency } from '#shared/currencies';
+import { setCachedUserPreferences } from '#shared/formulas/customFunctions';
import { Action } from './action';
describe('Formula-based rule actions', () => {
+ beforeEach(() => {
+ setCachedUserPreferences({
+ currency: getCurrency('USD'),
+ numberFormat: 'comma-dot',
+ decimalPlaces: 2,
+ thousandsSeparator: ',',
+ decimalSeparator: '.',
+ locale: 'en-US',
+ currencySymbolPosition: 'before',
+ currencySpaceBetweenAmountAndSymbol: false,
+ });
+ });
+
it('should execute a simple math formula', () => {
const action = new Action('set', 'amount', null, {});
const transaction: Partial<TransactionForRules> = { amount: 500 };
@@ -210,4 +225,258 @@ describe('Formula-based rule actions', () => {
// Should convert number to string
expect(transaction.notes).toBe('75000');
});
+
+ it('should format numbers with thousands separators using FORMATNUMBER', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATNUMBER(1234567.89, 2)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1,234,567.89');
+ });
+
+ it('should format numbers using number-format preferences with FORMATNUMBER', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('USD'),
+ numberFormat: 'dot-comma',
+ decimalPlaces: 2,
+ thousandsSeparator: '.',
+ decimalSeparator: ',',
+ locale: 'en-US',
+ currencySymbolPosition: 'before',
+ currencySpaceBetweenAmountAndSymbol: false,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATNUMBER(1234567.89, 2)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1.234.567,89');
+ });
+
+ it('should format numbers using decimal-place preferences with FORMATNUMBER', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('JPY'),
+ numberFormat: 'comma-dot',
+ decimalPlaces: 0,
+ thousandsSeparator: ',',
+ decimalSeparator: '.',
+ locale: 'en-US',
+ currencySymbolPosition: 'before',
+ currencySpaceBetweenAmountAndSymbol: false,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATNUMBER(1234567.89)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1,234,568');
+ });
+
+ it('should let FORMATNUMBER decimals override decimal-place preferences', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('JPY'),
+ numberFormat: 'comma-dot',
+ decimalPlaces: 0,
+ thousandsSeparator: ',',
+ decimalSeparator: '.',
+ locale: 'en-US',
+ currencySymbolPosition: 'before',
+ currencySpaceBetweenAmountAndSymbol: false,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATNUMBER(1234567.89, 2)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1,234,567.89');
+ });
+
+ it('should format numbers with custom separators using FORMATNUMBER', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATNUMBER(1234567.89, 2, ".", ",")',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1.234.567,89');
+ });
+
+ it('should format numbers without decimals using FORMATNUMBER', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATNUMBER(1234567, 0)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1,234,567');
+ });
+
+ it('should let IFERROR catch invalid FORMATNUMBER values', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=IFERROR(FORMATNUMBER("not a number"), "fallback")',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('fallback');
+ });
+
+ it('should format currency with default settings using FORMATCURRENCY', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(1234567.89)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('$1,234,567.89');
+ });
+
+ it('should use cached currency preferences when FORMATCURRENCY arguments are omitted', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('BRL'),
+ numberFormat: 'dot-comma',
+ decimalPlaces: 2,
+ thousandsSeparator: '.',
+ decimalSeparator: ',',
+ locale: 'pt-BR',
+ currencySymbolPosition: 'before',
+ currencySpaceBetweenAmountAndSymbol: false,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(SUM(1, 2, 3))',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('R$6,00');
+ });
+
+ it('should use cached currency symbol position and spacing preferences', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('BRL'),
+ numberFormat: 'dot-comma',
+ decimalPlaces: 2,
+ thousandsSeparator: '.',
+ decimalSeparator: ',',
+ locale: 'pt-BR',
+ currencySymbolPosition: 'after',
+ currencySpaceBetweenAmountAndSymbol: true,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(SUM(1, 2, 3))',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('6,00\u202FR$');
+ });
+
+ it('should format currency with custom symbol using FORMATCURRENCY', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(1234567.89, "€")',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('€1,234,567.89');
+ });
+
+ it('should use cached currency position and spacing preferences with custom symbols', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('BRL'),
+ numberFormat: 'dot-comma',
+ decimalPlaces: 2,
+ thousandsSeparator: '.',
+ decimalSeparator: ',',
+ locale: 'pt-BR',
+ currencySymbolPosition: 'after',
+ currencySpaceBetweenAmountAndSymbol: true,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(1234567.89, "€")',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('1.234.567,89\u202F€');
+ });
+
+ it('should override cached currency position and spacing preferences with custom arguments', () => {
+ setCachedUserPreferences({
+ currency: getCurrency('BRL'),
+ numberFormat: 'dot-comma',
+ decimalPlaces: 2,
+ thousandsSeparator: '.',
+ decimalSeparator: ',',
+ locale: 'pt-BR',
+ currencySymbolPosition: 'after',
+ currencySpaceBetweenAmountAndSymbol: true,
+ });
+
+ const action = new Action('set', 'notes', null, {
+ formula:
+ '=FORMATCURRENCY(1234567.89, "€", 2, ".", ",", "before", FALSE())',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('€1.234.567,89');
+ });
+
+ it('should format negative currency correctly using FORMATCURRENCY', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(-1234567.89)',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('-$1,234,567.89');
+ });
+
+ it('should format currency with custom separators using FORMATCURRENCY', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=FORMATCURRENCY(1234567.89, "€", 2, ".", ",")',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('€1.234.567,89');
+ });
+
+ it('should let IFERROR catch invalid FORMATCURRENCY values', () => {
+ const action = new Action('set', 'notes', null, {
+ formula: '=IFERROR(FORMATCURRENCY("not a number"), "fallback")',
+ });
+
+ const transaction = { notes: 'original' };
+ action.exec(transaction);
+
+ expect(transaction.notes).toBe('fallback');
+ });
});
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.ts
index bedea9b7bf..a869f546b3 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts
@@ -12,6 +12,7 @@ import {
} from '#server/db';
import { getMappings } from '#server/db/mappings';
import { RuleError } from '#server/errors';
+import { ensureFormulaPreferencesLoaded } from '#server/formulas/bootstrap';
import { requiredFields, toDateRepr } from '#server/models';
import {
Action,
@@ -321,6 +322,8 @@ export async function runRules(
trans,
accounts: Map<string, db.DbAccount> | null = null,
) {
+ await ensureFormulaPreferencesLoaded();
+
let accountsMap: Map<string, db.DbAccount> = null;
if (accounts === null) {
accountsMap = new Map(
@@ -694,6 +697,8 @@ export async function applyActions(
transactions: TransactionEntity[],
actions: Array<Action | RuleActionEntity>,
) {
+ await ensureFormulaPreferencesLoaded();
+
const parsedActions = actions
.map(action => {
if (action instanceof Action) {
diff --git a/packages/loot-core/src/server/rules/customFunctions.ts b/packages/loot-core/src/shared/formulas/customFunctions.ts
similarity index 52%
rename from packages/loot-core/src/server/rules/customFunctions.ts
rename to packages/loot-core/src/shared/formulas/customFunctions.ts
index 2fc22491f7..80a307e669 100644
--- a/packages/loot-core/src/server/rules/customFunctions.ts
+++ b/packages/loot-core/src/shared/formulas/customFunctions.ts
@@ -10,7 +10,12 @@ import {
import type { InterpreterState } from 'hyperformula/typings/interpreter/InterpreterState';
import type { ProcedureAst } from 'hyperformula/typings/parser';
+import { getCurrency } from '#shared/currencies';
+import type { Currency } from '#shared/currencies';
import { integerToAmount } from '#shared/util';
+import type { NumberFormats } from '#shared/util';
+
+type CurrencySymbolPosition = 'before' | 'after';
export type BudgetQueryRequest = {
dimension: string;
@@ -40,6 +45,44 @@ type CustomFunctionsContext = {
formulaQuery?: FormulaQueryContext;
};
+export type UserPreferences = {
+ currency: Currency;
+ numberFormat: NumberFormats;
+ decimalPlaces: number;
+ thousandsSeparator: string;
+ decimalSeparator: string;
+ locale: string;
+ currencySymbolPosition: CurrencySymbolPosition;
+ currencySpaceBetweenAmountAndSymbol: boolean;
+};
+
+let cachedUserPreferences: UserPreferences | null = null;
+
+export function setCachedUserPreferences(prefs: UserPreferences): void {
+ cachedUserPreferences = prefs;
+}
+
+export function clearCachedUserPreferences(): void {
+ cachedUserPreferences = null;
+}
+
+function getUserPreferences(): UserPreferences {
+ if (!cachedUserPreferences) {
+ // If not loaded, use defaults
+ return {
+ currency: getCurrency('USD'),
+ numberFormat: 'comma-dot',
+ decimalPlaces: 2,
+ thousandsSeparator: ',',
+ decimalSeparator: '.',
+ locale: 'en-US',
+ currencySymbolPosition: 'before',
+ currencySpaceBetweenAmountAndSymbol: false,
+ };
+ }
+ return cachedUserPreferences;
+}
+
export function createBudgetQueryPrefetchKey({
dimension,
categoryIds,
@@ -75,6 +118,54 @@ function categoryIdsToRange(categoryIds: string[]): SimpleRangeValue {
);
}
+function formatCurrencyValue({
+ value,
+ currencySymbol,
+ decimals,
+ thousandsSeparator,
+ decimalSeparator,
+ currencySymbolPosition,
+ currencySpaceBetweenAmountAndSymbol,
+}: {
+ value: number;
+ currencySymbol: string;
+ decimals: number;
+ thousandsSeparator: string;
+ decimalSeparator: string;
+ currencySymbolPosition: CurrencySymbolPosition;
+ currencySpaceBetweenAmountAndSymbol: boolean;
+}): string {
+ const isNegative = value < 0;
+ const absNum = Math.abs(value);
+ const fixedNum = absNum.toFixed(decimals);
+ const [integerPart, decimalPart] = fixedNum.split('.');
+
+ const formattedInteger = integerPart.replace(
+ /\B(?=(\d{3})+(?!\d))/g,
+ thousandsSeparator,
+ );
+
+ const formattedAmount =
+ decimals > 0 && decimalPart
+ ? `${formattedInteger}${decimalSeparator}${decimalPart}`
+ : formattedInteger;
+
+ const space = currencySpaceBetweenAmountAndSymbol ? '\u202F' : '';
+ const formattedCurrency =
+ currencySymbolPosition === 'after'
+ ? `${formattedAmount}${space}${currencySymbol}`
+ : `${currencySymbol}${space}${formattedAmount}`;
+
+ return isNegative ? `-${formattedCurrency}` : formattedCurrency;
+}
+
+function getCurrencySymbolPositionFromArg(
+ value: string | undefined,
+ fallback: CurrencySymbolPosition,
+): CurrencySymbolPosition {
+ return value === 'before' || value === 'after' ? value : fallback;
+}
+
export class CustomFunctionsPlugin extends FunctionPlugin {
private getCustomFunctionsContext(): CustomFunctionsContext | undefined {
return this.config.context as CustomFunctionsContext | undefined;
@@ -230,6 +321,125 @@ export class CustomFunctionsPlugin extends FunctionPlugin {
},
);
}
+
+ formatNumber(ast: ProcedureAst, state: InterpreterState) {
+ const hasDecimalsArg = ast.args.length > 1;
+ const hasThousandsSeparatorArg = ast.args.length > 2;
+ const hasDecimalSeparatorArg = ast.args.length > 3;
+
+ return this.runFunction(
+ ast.args,
+ state,
+ this.metadata('FORMATNUMBER'),
+ (
+ value: number,
+ decimals?: number,
+ thousandsSeparator?: string,
+ decimalSeparator?: string,
+ ) => {
+ const num = Number(value);
+ if (isNaN(num)) {
+ return new CellError(ErrorType.VALUE);
+ }
+
+ const prefs = getUserPreferences();
+
+ const actualThousandsSeparator =
+ hasThousandsSeparatorArg && thousandsSeparator !== undefined
+ ? thousandsSeparator
+ : prefs.thousandsSeparator;
+ const actualDecimalSeparator =
+ hasDecimalSeparatorArg && decimalSeparator !== undefined
+ ? decimalSeparator
+ : prefs.decimalSeparator;
+ const actualDecimals = hasDecimalsArg
+ ? (decimals ?? 2)
+ : prefs.decimalPlaces;
+
+ const fixedNum = num.toFixed(actualDecimals);
+ const [integerPart, decimalPart] = fixedNum.split('.');
+
+ const formattedInteger = integerPart.replace(
+ /\B(?=(\d{3})+(?!\d))/g,
+ actualThousandsSeparator,
+ );
+
+ if (actualDecimals > 0 && decimalPart) {
+ return `${formattedInteger}${actualDecimalSeparator}${decimalPart}`;
+ }
+
+ return formattedInteger;
+ },
+ );
+ }
+
+ formatCurrency(ast: ProcedureAst, state: InterpreterState) {
+ const hasCurrencySymbolArg = ast.args.length > 1;
+ const hasDecimalsArg = ast.args.length > 2;
+ const hasThousandsSeparatorArg = ast.args.length > 3;
+ const hasDecimalSeparatorArg = ast.args.length > 4;
+ const hasCurrencySymbolPositionArg = ast.args.length > 5;
+ const hasCurrencySpaceBetweenAmountAndSymbolArg = ast.args.length > 6;
+
+ return this.runFunction(
+ ast.args,
+ state,
+ this.metadata('FORMATCURRENCY'),
+ (
+ value: number,
+ currencySymbol?: string,
+ decimals?: number,
+ thousandsSeparator?: string,
+ decimalSeparator?: string,
+ currencySymbolPosition?: string,
+ currencySpaceBetweenAmountAndSymbol?: boolean,
+ ) => {
+ const num = Number(value);
+ if (isNaN(num)) {
+ return new CellError(ErrorType.VALUE);
+ }
+
+ const prefs = getUserPreferences();
+
+ const actualCurrencySymbol = hasCurrencySymbolArg
+ ? (currencySymbol ?? '')
+ : prefs.currency.symbol;
+ const actualDecimals = hasDecimalsArg
+ ? (decimals ?? 2)
+ : prefs.currency.decimalPlaces;
+ const actualThousandsSeparator =
+ hasThousandsSeparatorArg && thousandsSeparator !== undefined
+ ? thousandsSeparator
+ : prefs.thousandsSeparator;
+ const actualDecimalSeparator =
+ hasDecimalSeparatorArg && decimalSeparator !== undefined
+ ? decimalSeparator
+ : prefs.decimalSeparator;
+ const actualCurrencySymbolPosition = hasCurrencySymbolPositionArg
+ ? getCurrencySymbolPositionFromArg(
+ currencySymbolPosition,
+ prefs.currencySymbolPosition,
+ )
+ : prefs.currencySymbolPosition;
+ const actualCurrencySpaceBetweenAmountAndSymbol =
+ hasCurrencySpaceBetweenAmountAndSymbolArg &&
+ currencySpaceBetweenAmountAndSymbol !== undefined
+ ? currencySpaceBetweenAmountAndSymbol
+ : prefs.currencySpaceBetweenAmountAndSymbol;
+
+ return formatCurrencyValue({
+ value: num,
+ currencySymbol: actualCurrencySymbol,
+ decimals: actualDecimals,
+ thousandsSeparator: actualThousandsSeparator,
+ decimalSeparator: actualDecimalSeparator,
+ currencySymbolPosition: actualCurrencySymbolPosition,
+ currencySpaceBetweenAmountAndSymbol:
+ actualCurrencySpaceBetweenAmountAndSymbol,
+ });
+ },
+ );
+ }
}
CustomFunctionsPlugin.implementedFunctions = {
@@ -248,15 +458,6 @@ CustomFunctionsPlugin.implementedFunctions = {
},
],
},
- BUDGET_QUERY: {
- method: 'budgetQuery',
- parameters: [
- { argumentType: FunctionArgumentType.STRING },
- { argumentType: FunctionArgumentType.RANGE },
- { argumentType: FunctionArgumentType.STRING },
- { argumentType: FunctionArgumentType.STRING },
- ],
- },
INTEGER_TO_AMOUNT: {
method: 'integerToAmount',
parameters: [
@@ -289,12 +490,77 @@ CustomFunctionsPlugin.implementedFunctions = {
method: 'queryExtractTimeframeStart',
parameters: [{ argumentType: FunctionArgumentType.STRING }],
},
+ BUDGET_QUERY: {
+ method: 'budgetQuery',
+ parameters: [
+ { argumentType: FunctionArgumentType.STRING },
+ { argumentType: FunctionArgumentType.RANGE },
+ { argumentType: FunctionArgumentType.STRING },
+ { argumentType: FunctionArgumentType.STRING },
+ ],
+ },
+ FORMATNUMBER: {
+ method: 'formatNumber',
+ parameters: [
+ { argumentType: FunctionArgumentType.NUMBER },
+ {
+ argumentType: FunctionArgumentType.NUMBER,
+ optionalArg: true,
+ defaultValue: 2,
+ },
+ {
+ argumentType: FunctionArgumentType.STRING,
+ optionalArg: true,
+ defaultValue: ',',
+ },
+ {
+ argumentType: FunctionArgumentType.STRING,
+ optionalArg: true,
+ defaultValue: '.',
+ },
+ ],
+ },
+ FORMATCURRENCY: {
+ method: 'formatCurrency',
+ parameters: [
+ { argumentType: FunctionArgumentType.NUMBER },
+ {
+ argumentType: FunctionArgumentType.STRING,
+ optionalArg: true,
+ defaultValue: '$',
+ },
+ {
+ argumentType: FunctionArgumentType.NUMBER,
+ optionalArg: true,
+ defaultValue: 2,
+ },
+ {
+ argumentType: FunctionArgumentType.STRING,
+ optionalArg: true,
+ defaultValue: ',',
+ },
+ {
+ argumentType: FunctionArgumentType.STRING,
+ optionalArg: true,
+ defaultValue: '.',
+ },
+ {
+ argumentType: FunctionArgumentType.STRING,
+ optionalArg: true,
+ defaultValue: 'before',
+ },
+ {
+ argumentType: FunctionArgumentType.BOOLEAN,
+ optionalArg: true,
+ defaultValue: false,
+ },
+ ],
+ },
};
export const customFunctionsTranslations = {
enUS: {
BALANCE_OF: 'BALANCE_OF',
- BUDGET_QUERY: 'BUDGET_QUERY',
FIXED: 'FIXED',
INTEGER_TO_AMOUNT: 'INTEGER_TO_AMOUNT',
QUERY: 'QUERY',
@@ -302,5 +568,8 @@ export const customFunctionsTranslations = {
QUERY_EXTRACT_CATEGORIES: 'QUERY_EXTRACT_CATEGORIES',
QUERY_EXTRACT_TIMEFRAME_END: 'QUERY_EXTRACT_TIMEFRAME_END',
QUERY_EXTRACT_TIMEFRAME_START: 'QUERY_EXTRACT_TIMEFRAME_START',
+ BUDGET_QUERY: 'BUDGET_QUERY',
+ FORMATNUMBER: 'FORMATNUMBER',
+ FORMATCURRENCY: 'FORMATCURRENCY',
},
};
diff --git a/packages/loot-core/src/types/handlers.ts b/packages/loot-core/src/types/handlers.ts
index c2478c7aef..5921ad3b3a 100644
--- a/packages/loot-core/src/types/handlers.ts
+++ b/packages/loot-core/src/types/handlers.ts
@@ -7,6 +7,7 @@ import type { DashboardHandlers } from '#server/dashboard/app';
import type { EncryptionHandlers } from '#server/encryption/app';
import type { FiltersHandlers } from '#server/filters/app';
import type { ForecastHandlers } from '#server/forecast/app';
+import type { FormulasHandlers } from '#server/formulas/app';
import type { NotesHandlers } from '#server/notes/app';
import type { PayeesHandlers } from '#server/payees/app';
import type { PreferencesHandlers } from '#server/preferences/app';
@@ -27,6 +28,7 @@ export type Handlers = {} & ServerHandlers &
BudgetHandlers &
DashboardHandlers &
FiltersHandlers &
+ FormulasHandlers &
ForecastHandlers &
NotesHandlers &
PreferencesHandlers &
diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.ts
index 20287764fb..eae96ffed0 100644
--- a/packages/loot-core/src/types/models/dashboard.ts
+++ b/packages/loot-core/src/types/models/dashboard.ts
@@ -215,6 +215,7 @@ export type FormulaWidget = AbstractWidget<
fontSize?: number;
fontSizeMode?: 'dynamic' | 'static';
staticFontSize?: number;
+ showTitle?: boolean;
colorFormula?: string;
queriesVersion?: number;
queries?: Record<
diff --git a/upcoming-release-notes/7989.md b/upcoming-release-notes/7989.md
new file mode 100644
index 0000000000..bcd71adb67
--- /dev/null
+++ b/upcoming-release-notes/7989.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [lelemm]
+---
+
+Improve formulas based on user feedback