A local-first personal finance app
✨ Feature: Formula card and Formula for rules (#5939)
lelemm002f74a8fa96
diff --git a/packages/desktop-client/index.html b/packages/desktop-client/index.htmlindex 41055b646e..acce9dbc9f 100644--- a/packages/desktop-client/index.html+++ b/packages/desktop-client/index.html@@ -107,6 +107,14 @@min-height: 0;min-width: 0;}++ .cm-theme-dark {+ height: 100%;+ }++ .cm-theme-light {+ height: 100%;+ }</style></head><body>diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex a0b3bff702..9719a701fc 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -7,9 +7,15 @@],"devDependencies": {"@actual-app/components": "workspace:*",+ "@codemirror/autocomplete": "^6.19.0",+ "@codemirror/lang-javascript": "^6.2.4",+ "@codemirror/language": "^6.11.3",+ "@codemirror/state": "^6.5.2",+ "@codemirror/view": "^6.38.6","@emotion/css": "^11.13.5","@fontsource/redacted-script": "^5.2.8","@juggle/resize-observer": "^3.4.0",+ "@lezer/highlight": "^1.2.1","@playwright/test": "1.56.0","@rollup/plugin-inject": "^5.0.5","@swc/core": "^1.13.5",@@ -24,6 +30,7 @@"@types/react-dom": "^19.2.1","@types/react-grid-layout": "^1","@types/react-modal": "^3.16.3",+ "@uiw/react-codemirror": "^4.25.2","@use-gesture/react": "^10.3.1","@vitejs/plugin-basic-ssl": "^2.1.0","@vitejs/plugin-react": "^5.0.4",@@ -33,6 +40,7 @@"cross-env": "^10.1.0","date-fns": "^4.1.0","downshift": "9.0.10",+ "hyperformula": "^3.1.0","i18next": "^25.5.3","i18next-parser": "^9.3.0","i18next-resources-to-backend": "^1.2.1",diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsxindex 64fe710b1f..affb9bacbd 100644--- a/packages/desktop-client/src/components/accounts/Account.tsx+++ b/packages/desktop-client/src/components/accounts/Account.tsx@@ -689,15 +689,35 @@ class AccountInternal extends PureComponent<ids.includes(trans.id),);const changedTransactions: TransactionEntity[] = [];+ const allErrors: string[] = [];+for (const transaction of transactions) {const res: TransactionEntity | null = await send('rules-run', {transaction,});if (res) {changedTransactions.push(...ungroupTransaction(res));++ // Collect formula errors+ if (res._ruleErrors && res._ruleErrors.length > 0) {+ allErrors.push(...res._ruleErrors);+ }}}+ // Show errors if any+ if (allErrors.length > 0) {+ this.props.dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: `Formula errors in rules:\n${allErrors.join('\n')}`,+ sticky: true,+ },+ }),+ );+ }+// If we have changed transactions, update them in the databaseif (changedTransactions.length > 0) {await send('transactions-batch-update', {diff --git a/packages/desktop-client/src/components/formula/FormulaEditor.tsx b/packages/desktop-client/src/components/formula/FormulaEditor.tsxnew file mode 100644index 0000000000..7f6ff58793--- /dev/null+++ b/packages/desktop-client/src/components/formula/FormulaEditor.tsx@@ -0,0 +1,102 @@+import { useMemo } from 'react';++import { EditorView } from '@codemirror/view';+import CodeMirror, {+ EditorState,+ type ReactCodeMirrorProps,+} from '@uiw/react-codemirror';++import { excelFormulaExtension } from './codeMirror-excelLanguage';++import { useTheme } from '@desktop-client/style/theme';++type FormulaMode = 'transaction' | 'query';++type FormulaEditorProps = {+ value: string;+ onChange: (value: string) => void;+ mode: FormulaMode;+ height?: string;+ disabled?: boolean;+ queries?: Record<string, unknown>;+ variables?: Record<string, number | string>;+ singleLine?: boolean;+ showLineNumbers?: boolean;+};++export function FormulaEditor({+ value,+ onChange,+ mode,+ height = '100%',+ disabled = false,+ queries,+ variables,+ singleLine = false,+ showLineNumbers = true,+}: FormulaEditorProps) {+ const [activeTheme] = useTheme();++ const isDarkTheme = useMemo(() => {+ if (activeTheme === 'dark' || activeTheme === 'midnight') {+ return true;+ }+ if (activeTheme === 'auto') {+ return window.matchMedia('(prefers-color-scheme: dark)').matches;+ }+ return false;+ }, [activeTheme]);++ const extensions = useMemo(+ () => [+ ...(singleLine+ ? [+ EditorState.transactionFilter.of(tr =>+ tr.newDoc.lines > 1+ ? [+ tr,+ {+ changes: {+ from: 0,+ to: tr.newDoc.length,+ insert: tr.newDoc.sliceString(0, undefined, ' '),+ },+ sequential: true,+ },+ ]+ : [tr],+ ),+ ]+ : []),+ ...excelFormulaExtension(mode, queries, isDarkTheme, variables),+ EditorView.lineWrapping,+ EditorView.editable.of(!disabled),+ ],+ [mode, queries, isDarkTheme, disabled, singleLine, variables],+ );++ const codeMirrorTheme: ReactCodeMirrorProps['theme'] = isDarkTheme+ ? 'dark'+ : 'light';++ return (+ <CodeMirror+ value={value}+ height={height}+ theme={codeMirrorTheme}+ extensions={extensions}+ onChange={onChange}+ editable={!disabled}+ basicSetup={{+ lineNumbers: showLineNumbers,+ foldGutter: false,+ highlightActiveLine: true,+ highlightActiveLineGutter: false,+ }}+ style={{+ fontSize: '14px',+ border: 'none',+ }}+ />+ );+}diff --git a/packages/desktop-client/src/components/formula/QueryManager.tsx b/packages/desktop-client/src/components/formula/QueryManager.tsxnew file mode 100644index 0000000000..de1f7e6f05--- /dev/null+++ b/packages/desktop-client/src/components/formula/QueryManager.tsx@@ -0,0 +1,860 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import { Dialog, DialogTrigger } from 'react-aria-components';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgCopy, SvgTrash } from '@actual-app/components/icons/v1';+import { SvgDownloadThickBottom } from '@actual-app/components/icons/v2';+import { Input } from '@actual-app/components/input';+import { Menu } from '@actual-app/components/menu';+import { Popover } from '@actual-app/components/popover';+import { Select } from '@actual-app/components/select';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import { parseISO } from 'date-fns';++import { send } from 'loot-core/platform/client/fetch';+import * as monthUtils from 'loot-core/shared/months';+import {+ type RuleConditionEntity,+ type TimeFrame,+} from 'loot-core/types/models';++import { AppliedFilters } from '@desktop-client/components/filters/AppliedFilters';+import { FilterButton } from '@desktop-client/components/filters/FiltersMenu';+import { getLiveRange } from '@desktop-client/components/reports/getLiveRange';+import {+ calculateTimeRange,+ validateEnd,+ validateStart,+ getLatestRange,+} from '@desktop-client/components/reports/reportRanges';+import { fromDateRepr } from '@desktop-client/components/reports/util';+import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';+import { addNotification } from '@desktop-client/notifications/notificationsSlice';+import { useDispatch } from '@desktop-client/redux';+import { type AppDispatch } from '@desktop-client/redux/store';++type QueryConfig = {+ conditions?: RuleConditionEntity[];+ conditionsOp?: 'and' | 'or';+ timeFrame?: TimeFrame;+};++type QueryManagerProps = {+ queries: Record<string, QueryConfig>;+ onQueriesChange: (queries: Record<string, QueryConfig>) => void;+};++export function QueryManager({ queries, onQueriesChange }: QueryManagerProps) {+ const { t } = useTranslation();+ const [newQueryName, setNewQueryName] = useState('');+ const [isAddingQuery, setIsAddingQuery] = useState(false);+ const dispatch = useDispatch();++ function handleAddQuery() {+ if (!newQueryName.trim()) return;++ if (queries[newQueryName]) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Query with this name already exists'),+ },+ }),+ );+ return;+ }++ onQueriesChange({+ ...queries,+ [newQueryName]: {+ conditions: [],+ conditionsOp: 'and',+ timeFrame: {+ start: monthUtils.firstDayOfMonth(monthUtils.currentDay()),+ end: monthUtils.currentDay(),+ mode: 'sliding-window',+ },+ },+ });++ setNewQueryName('');+ setIsAddingQuery(false);+ }++ function handleRemoveQuery(queryName: string) {+ const newQueries = { ...queries };+ delete newQueries[queryName];+ onQueriesChange(newQueries);+ }++ function handleUpdateQuery(queryName: string, config: QueryConfig) {+ onQueriesChange({+ ...queries,+ [queryName]: config,+ });+ }++ return (+ <View style={{ padding: 20, flex: 1, minWidth: 400 }}>+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: 16,+ }}+ >+ <Text style={{ fontSize: 18, fontWeight: 600 }}>+ <Trans>Query Definitions</Trans>+ </Text>+ <Button+ variant="primary"+ onPress={() => setIsAddingQuery(!isAddingQuery)}+ >+ {isAddingQuery ? <Trans>Cancel</Trans> : <Trans>Add Query</Trans>}+ </Button>+ </View>++ {isAddingQuery && (+ <View+ style={{+ padding: 16,+ border: `1px solid ${theme.tableBorder}`,+ borderRadius: 4,+ marginBottom: 16,+ backgroundColor: theme.tableBackground,+ }}+ >+ <View style={{ display: 'flex', flexDirection: 'row', gap: 8 }}>+ <Input+ placeholder={t('Query name (e.g., ‘expenses’, ‘income’)')}+ value={newQueryName}+ onChange={e => setNewQueryName(e.target.value)}+ onKeyDown={e => {+ if (e.key === 'Enter') {+ handleAddQuery();+ }+ }}+ style={{ flex: 1 }}+ />+ <Button variant="primary" onPress={handleAddQuery}>+ <Trans>Create</Trans>+ </Button>+ </View>+ </View>+ )}++ {Object.entries(queries).length === 0 ? (+ <View+ style={{+ padding: 32,+ textAlign: 'center',+ color: theme.pageTextSubdued,+ border: `1px dashed ${theme.tableBorder}`,+ borderRadius: 4,+ maxWidth: 400,+ }}+ >+ <Text>+ <Trans>+ No queries defined. Click ‘Add Query’ to create your first query.+ </Trans>+ </Text>+ <Text style={{ fontSize: 12, marginTop: 8 }}>+ <Trans>+ Queries allow you to reference filtered transaction data in your+ formulas using QUERY(‘queryName’)+ </Trans>+ </Text>+ </View>+ ) : (+ <View style={{ display: 'block' }}>+ {Object.entries(queries).map(([queryName, config]) => (+ <QueryItem+ key={queryName}+ queryName={queryName}+ defaultConfig={config}+ onUpdate={newConfig => handleUpdateQuery(queryName, newConfig)}+ onRemove={() => handleRemoveQuery(queryName)}+ />+ ))}+ </View>+ )}+ </View>+ );+}++type QueryItemProps = {+ queryName: string;+ defaultConfig: QueryConfig;+ onUpdate: (config: QueryConfig) => void;+ onRemove: () => void;+};++function QueryItem({+ queryName,+ defaultConfig,+ onUpdate,+ onRemove,+}: QueryItemProps) {+ const { t } = useTranslation();+ const [importJsonText, setImportJsonText] = useState('');+ const dispatch = useDispatch<AppDispatch>();+ const timeRangeMenuTriggerRef = useRef(null);+ const [timeRangeMenuOpen, setTimeRangeMenuOpen] = useState(false);++ // Time range state+ const [startDate, setStartDate] = useState(+ defaultConfig.timeFrame?.start ||+ monthUtils.dayFromDate(monthUtils.currentMonth()),+ );+ const [endDate, setEndDate] = useState(+ defaultConfig.timeFrame?.end || monthUtils.currentDay(),+ );++ // Months data for range picker+ const [allMonths, setAllMonths] = useState<+ Array<{+ name: string;+ pretty: string;+ }>+ >([]);+ const [_earliestTransaction, setEarliestTransaction] = useState('');+ const [_latestTransaction, setLatestTransaction] = useState('');++ const timeRangeRef = useRef<string>(+ defaultConfig.timeFrame?.mode || 'sliding-window',+ );+ const conditionsRef = useRef<RuleConditionEntity[]>(+ defaultConfig.conditions || [],+ );++ // Accepting null here to detect changes and make rerender work properly:+ const conditionsOpRef = useRef<'and' | 'or' | null>(+ defaultConfig.conditionsOp || null,+ );++ useEffect(() => {+ if (conditionsRef.current.length === 0) {+ conditionsRef.current = defaultConfig.conditions || [];+ }++ if (conditionsOpRef.current === null) {+ conditionsOpRef.current = defaultConfig.conditionsOp || 'and';+ }+ }, [defaultConfig]);++ // Fetch transaction data for month range picker+ useEffect(() => {+ async function run() {+ const earliestTransaction = await send('get-earliest-transaction');+ setEarliestTransaction(+ earliestTransaction+ ? earliestTransaction.date+ : monthUtils.currentDay(),+ );++ const latestTransaction = await send('get-latest-transaction');+ setLatestTransaction(+ latestTransaction ? latestTransaction.date : monthUtils.currentDay(),+ );++ const currentMonth = monthUtils.currentMonth();+ let earliestMonth = earliestTransaction+ ? monthUtils.monthFromDate(+ parseISO(fromDateRepr(earliestTransaction.date)),+ )+ : currentMonth;+ const latestMonth = latestTransaction+ ? monthUtils.monthFromDate(+ parseISO(fromDateRepr(latestTransaction.date)),+ )+ : currentMonth;++ // Make sure the month selects are at least populated with a+ // year's worth of months. We can undo this when we have fancier+ // date selects.+ const yearAgo = monthUtils.subMonths(latestMonth, 12);+ if (earliestMonth > yearAgo) {+ earliestMonth = yearAgo;+ }++ const allMonths = monthUtils+ .rangeInclusive(earliestMonth, latestMonth)+ .map(month => ({+ name: month,+ pretty: monthUtils.format(month, 'MMMM, yyyy'),+ }))+ .reverse();++ setAllMonths(allMonths);+ }+ run();+ }, []);++ const filters = useRuleConditionFilters(+ conditionsRef.current,+ conditionsOpRef.current ?? ('and' as 'and' | 'or'),+ );++ const prevFiltersRef = useRef<{+ conditions: RuleConditionEntity[];+ conditionsOp: 'and' | 'or';+ startDate: string;+ endDate: string;+ }>({+ conditions: filters.conditions,+ conditionsOp: filters.conditionsOp,+ startDate,+ endDate,+ });++ const sendUpdate = useCallback(+ (+ conditions = filters.conditions,+ conditionsOp = filters.conditionsOp,+ newStartDate = startDate,+ newEndDate = endDate,+ mode = timeRangeRef.current as TimeFrame['mode'],+ ) => {+ timeRangeRef.current = mode;+ onUpdate({+ conditions,+ conditionsOp,+ timeFrame: {+ start: newStartDate,+ end: newEndDate,+ mode,+ },+ });+ },+ [+ filters.conditions,+ filters.conditionsOp,+ timeRangeRef,+ startDate,+ endDate,+ onUpdate,+ ],+ );++ useEffect(() => {+ const prev = prevFiltersRef.current;+ const conditionsChanged =+ JSON.stringify(prev.conditions) !== JSON.stringify(filters.conditions);+ const conditionsOpChanged = prev.conditionsOp !== filters.conditionsOp;++ if (conditionsChanged || conditionsOpChanged) {+ prevFiltersRef.current = {+ conditions: filters.conditions,+ conditionsOp: filters.conditionsOp,+ startDate,+ endDate,+ };+ sendUpdate();+ }+ }, [+ filters.conditions,+ filters.conditionsOp,+ startDate,+ endDate,+ sendUpdate,+ ]);++ function handleStartDateChange(newStart: string) {+ setStartDate(monthUtils.dayFromDate(newStart));+ sendUpdate(+ filters.conditions,+ filters.conditionsOp,+ monthUtils.dayFromDate(newStart),+ endDate,+ timeRangeRef.current as TimeFrame['mode'],+ );+ }++ function handleEndDateChange(newEnd: string) {+ setEndDate(monthUtils.dayFromDate(newEnd));+ sendUpdate(+ filters.conditions,+ filters.conditionsOp,+ startDate,+ monthUtils.dayFromDate(newEnd),+ timeRangeRef.current as TimeFrame['mode'],+ );+ }++ async function handleExport() {+ const config = {+ conditions: filters.conditions,+ conditionsOp: filters.conditionsOp,+ timeFrame: {+ start: startDate,+ end: endDate,+ mode: timeRangeRef.current as TimeFrame['mode'],+ },+ };++ const jsonString = JSON.stringify(config, null, 2);++ try {+ await navigator.clipboard.writeText(jsonString);+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Query configuration copied to clipboard'),+ },+ }),+ );+ } catch (error) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Failed to copy to clipboard'),+ },+ }),+ );+ }+ }++ function handleImport() {+ try {+ const config = JSON.parse(importJsonText);+ if (config.conditions && config.conditionsOp && config.timeFrame) {+ // Update refs+ conditionsRef.current = config.conditions;+ conditionsOpRef.current = config.conditionsOp;+ timeRangeRef.current = config.timeFrame.mode;++ setStartDate(+ config.timeFrame.start ||+ monthUtils.dayFromDate(monthUtils.currentMonth()),+ );+ setEndDate(config.timeFrame.end || monthUtils.currentDay());++ // Update the query+ sendUpdate(+ config.conditions,+ config.conditionsOp,+ config.timeFrame.start,+ config.timeFrame.end,+ config.timeFrame.mode,+ );+ setImportJsonText('');+ } else {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Invalid JSON. Please check your input.'),+ },+ }),+ );+ }+ } catch (error) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Invalid JSON. Please check your input.'),+ },+ }),+ );+ }+ }++ return (+ <View+ style={{+ padding: 16,+ marginBottom: 16,+ border: `1px solid ${theme.tableBorder}`,+ borderRadius: 4,+ backgroundColor: theme.tableBackground,+ display: 'block',+ flex: 1,+ }}+ >+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: 12,+ }}+ >+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ gap: 8,+ alignItems: 'center',+ }}+ >+ <Text style={{ fontWeight: 600, fontFamily: 'monospace' }}>+ <Trans>QUERY(‘{queryName}’)</Trans>+ </Text>+ </View>+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ gap: 8,+ justifyContent: 'flex-end',+ alignItems: 'center',+ }}+ >+ <View style={{ display: 'flex', flexDirection: 'row', gap: 4 }}>+ <Button+ variant="bare"+ onPress={handleExport}+ aria-label={t('Export query configuration')}+ >+ <SvgCopy style={{ width: 13, height: 13 }} />+ </Button>+ <DialogTrigger>+ <Button+ variant="bare"+ aria-label={t('Import query configuration')}+ >+ <SvgDownloadThickBottom style={{ width: 13, height: 13 }} />+ </Button>+ <Popover>+ <Dialog>+ <View style={{ padding: 16, minWidth: 400 }}>+ <Text+ style={{+ fontSize: 14,+ fontWeight: 600,+ marginBottom: 12,+ }}+ >+ <Trans>Import Query Configuration</Trans>+ </Text>+ <Text+ style={{+ fontSize: 12,+ color: theme.pageTextSubdued,+ marginBottom: 8,+ }}+ >+ <Trans>Paste the JSON configuration below:</Trans>+ </Text>+ <textarea+ value={importJsonText}+ onChange={e => setImportJsonText(e.target.value)}+ placeholder={JSON.stringify(+ {+ conditions: [],+ conditionsOp: 'and',+ timeFrame: {+ start: '',+ end: '',+ mode: 'sliding-window',+ },+ },+ null,+ 2,+ )}+ style={{+ width: '100%',+ height: 200,+ padding: 8,+ border: `1px solid ${theme.formInputBorder}`,+ borderRadius: 4,+ backgroundColor: theme.tableBackground,+ color: theme.formInputText,+ fontFamily: 'monospace',+ fontSize: 12,+ resize: 'vertical',+ outline: 'none',+ }}+ />+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ gap: 8,+ marginTop: 12,+ justifyContent: 'flex-end',+ }}+ >+ <Button variant="bare" slot="close">+ <Trans>Cancel</Trans>+ </Button>+ <Button+ variant="primary"+ onPress={handleImport}+ slot="close"+ >+ <Trans>Import</Trans>+ </Button>+ </View>+ </View>+ </Dialog>+ </Popover>+ </DialogTrigger>+ <Button variant="bare" onPress={onRemove}>+ <SvgTrash style={{ width: 13, height: 13 }} />+ </Button>+ </View>+ </View>+ </View>++ <View style={{ marginBottom: 12 }}>+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ justifyContent: 'flex-end',+ gap: 8,+ marginTop: 16,+ }}+ >+ <Button+ style={{ width: 50 }}+ variant={timeRangeRef.current === 'static' ? 'normal' : 'primary'}+ onPress={() => {+ const currentMode = timeRangeRef.current as TimeFrame['mode'];+ const newMode =+ currentMode === 'static' ? 'sliding-window' : 'static';+ const [newStart, newEnd] = calculateTimeRange({+ start: startDate,+ end: endDate,+ mode: newMode,+ });++ setStartDate(newStart);+ setEndDate(newEnd);+ timeRangeRef.current = newMode;+ sendUpdate(+ filters.conditions,+ filters.conditionsOp,+ newStart,+ newEnd,+ newMode,+ );+ }}+ >+ {timeRangeRef.current === 'static' ? t('Static') : t('Live')}+ </Button>+ <Button+ ref={timeRangeMenuTriggerRef}+ variant="bare"+ onPress={() => setTimeRangeMenuOpen(true)}+ >+ ⋮+ </Button>+ <Popover+ triggerRef={timeRangeMenuTriggerRef}+ placement="bottom start"+ isOpen={timeRangeMenuOpen}+ onOpenChange={() => setTimeRangeMenuOpen(false)}+ >+ <Menu+ onMenuSelect={item => {+ let start: string, end: string, mode: TimeFrame['mode'];+ const currentMode = timeRangeRef.current as TimeFrame['mode'];+ // For quick selections, use the current toggle state (static vs sliding-window)+ const quickSelectMode = ['static', 'sliding-window'].includes(+ currentMode,+ )+ ? currentMode+ : 'sliding-window';++ switch (item) {+ case '1-month': {+ const [startMonth, endMonth] = getLatestRange(0);+ start = monthUtils.firstDayOfMonth(startMonth);+ end = monthUtils.lastDayOfMonth(endMonth);+ mode = quickSelectMode;+ break;+ }+ case '3-months': {+ const [startMonth, endMonth] = getLatestRange(2);+ start = monthUtils.firstDayOfMonth(startMonth);+ end = monthUtils.lastDayOfMonth(endMonth);+ mode = quickSelectMode;+ break;+ }+ case '6-months': {+ const [startMonth, endMonth] = getLatestRange(5);+ start = monthUtils.firstDayOfMonth(startMonth);+ end = monthUtils.lastDayOfMonth(endMonth);+ mode = quickSelectMode;+ break;+ }+ case '1-year': {+ const [startMonth, endMonth] = getLatestRange(11);+ start = monthUtils.firstDayOfMonth(startMonth);+ end = monthUtils.lastDayOfMonth(endMonth);+ mode = quickSelectMode;+ break;+ }+ case 'year-to-date': {+ [start, end] = getLiveRange(+ 'Year to date',+ _earliestTransaction,+ _latestTransaction,+ true,+ );+ mode = 'yearToDate';+ break;+ }+ case 'last-year': {+ [start, end] = getLiveRange(+ 'Last year',+ _earliestTransaction,+ _latestTransaction,+ false,+ );+ mode = 'lastYear';+ break;+ }+ case 'prior-year-to-date': {+ [start, end] = getLiveRange(+ 'Prior year to date',+ _earliestTransaction,+ _latestTransaction,+ false,+ );+ mode = 'priorYearToDate';+ break;+ }+ case 'all-time': {+ [start, end] = getLiveRange(+ 'All time',+ _earliestTransaction,+ _latestTransaction,+ true,+ );+ mode = 'full';+ break;+ }+ default:+ return;+ }+ setStartDate(start);+ setEndDate(end);+ timeRangeRef.current = mode;+ sendUpdate(+ filters.conditions,+ filters.conditionsOp,+ start,+ end,+ mode,+ );+ setTimeRangeMenuOpen(false);+ }}+ items={[+ { name: '1-month', text: t('1 month') },+ { name: '3-months', text: t('3 months') },+ { name: '6-months', text: t('6 months') },+ { name: '1-year', text: t('1 year') },+ Menu.line,+ { name: 'year-to-date', text: t('Year to date') },+ { name: 'last-year', text: t('Last year') },+ {+ name: 'prior-year-to-date',+ text: t('Prior year to date'),+ },+ { name: 'all-time', text: t('All time') },+ ]}+ />+ </Popover>+ </View>++ {/* Date range selectors */}+ {allMonths.length > 0 && (+ <View+ style={{+ display: 'flex',+ flexDirection: 'row',+ gap: 10,+ marginTop: 8,+ alignItems: 'center',+ }}+ >+ <Select+ value={fromDateRepr(startDate)}+ onChange={newValue => {+ const [validatedStart] = validateStart(+ allMonths[allMonths.length - 1].name,+ allMonths[0].name,+ newValue,+ fromDateRepr(endDate),+ );+ handleStartDateChange(validatedStart);+ }}+ options={allMonths.map(({ name, pretty }) => [name, pretty])}+ style={{ flex: 1 }}+ />+ <Text style={{ fontSize: 12, color: theme.pageTextSubdued }}>+ <Trans>to</Trans>+ </Text>+ <Select+ value={fromDateRepr(endDate)}+ onChange={newValue => {+ const [, validatedEnd] = validateEnd(+ allMonths[allMonths.length - 1].name,+ allMonths[0].name,+ fromDateRepr(startDate),+ newValue,+ );+ handleEndDateChange(validatedEnd);+ }}+ options={allMonths.map(({ name, pretty }) => [name, pretty])}+ style={{ flex: 1 }}+ />+ </View>+ )}+ </View>++ <View style={{ marginBottom: 8, flex: 1 }}>+ <Text+ style={{+ fontSize: 12,+ fontWeight: 500,+ marginBottom: 6,+ color: theme.pageTextSubdued,+ }}+ >+ <Trans>Filters:</Trans>+ </Text>+ <View+ style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: 8,+ maxWidth: 400,+ flex: 1,+ }}+ >+ {filters.conditions.length > 0 && (+ <AppliedFilters+ conditions={filters.conditions}+ onUpdate={filters.onUpdate}+ onDelete={filters.onDelete}+ conditionsOp={filters.conditionsOp}+ onConditionsOpChange={filters.onConditionsOpChange}+ />+ )}+ <FilterButton+ compact={false}+ onApply={filters.onApply}+ hover={false}+ exclude={undefined}+ />+ </View>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsxnew file mode 100644index 0000000000..c3dff985b6--- /dev/null+++ b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx@@ -0,0 +1,686 @@+/* eslint-disable actual/typography */+import React from 'react';++import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import {+ autocompletion,+ type Completion,+ type CompletionContext,+} from '@codemirror/autocomplete';+import {+ syntaxHighlighting,+ HighlightStyle,+ StreamLanguage,+ type StreamParser,+} from '@codemirror/language';+import { type Extension } from '@codemirror/state';+import { hoverTooltip, type Tooltip, EditorView } from '@codemirror/view';+import { tags } from '@lezer/highlight';+import { t } from 'i18next';+import { createRoot } from 'react-dom/client';++import { queryModeFunctions, type FunctionDef } from './queryModeFunctions';+import { transactionModeFunctions } from './transactionModeFunctions';++// Tooltip components using the same styles as Tooltip.tsx+function FunctionTooltip({+ name,+ description,+ parameters,+}: {+ name: string;+ description: string;+ parameters: Array<{ name: string; description: string }>;+}) {+ return (+ <div style={{ maxWidth: '400px' }}>+ <div style={{ fontWeight: 600, marginBottom: '4px' }}>{name}</div>+ <div style={{ marginBottom: '8px' }}>{description}</div>+ <div style={{ fontSize: '0.9em', opacity: 0.8 }}>+ <div style={{ fontWeight: 500, marginBottom: '4px' }}>Parameters:</div>+ {parameters.map((p, i) => (+ <div key={i} style={{ marginBottom: '2px' }}>+ •{' '}+ <code+ style={{+ ...styles.editorPill,+ fontSize: '0.95em',+ }}+ >+ {p.name}+ </code>+ : {p.description}+ </div>+ ))}+ </div>+ </div>+ );+}++function FieldTooltip({ label, info }: { label: string; info: string }) {+ return (+ <div style={{ maxWidth: '400px' }}>+ <div style={{ fontWeight: 600, marginBottom: '4px' }}>{label}</div>+ <div>{info}</div>+ </div>+ );+}++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',+ 'ROUNDDOWN',+ 'CEILING',+ 'FLOOR',+ 'MOD',+ 'POWER',+ 'SQRT',+ 'INT',+ 'TRUNC',+ 'SIGN',+ 'PI',+ 'SIN',+ 'COS',+ 'TAN',+ 'LN',+ 'LOG',+ 'LOG10',+ 'EXP',+ 'PRODUCT',+ 'SUMIF',+ 'SUMIFS',+ 'SUMPRODUCT',+ 'SUMSQ',+ 'MEDIAN',+ 'MODE',+ 'STDEV',+ 'STDEVP',+ 'VAR',+ 'VARP',+ 'PERCENTILE',+ 'QUARTILE',+ 'RANK',+ 'PMT',+ 'FV',+ 'PV',+ 'NPV',+ 'IRR',+ 'RATE',+]);++const LOGICAL_FUNCTIONS = new Set([+ 'IF',+ 'IFS',+ 'AND',+ 'OR',+ 'XOR',+ 'NOT',+ 'TRUE',+ 'FALSE',+ 'IFERROR',+ 'IFNA',+ 'SWITCH',+]);++const TEXT_FUNCTIONS = new Set([+ 'TEXT',+ 'CONCATENATE',+ 'LEFT',+ 'RIGHT',+ 'MID',+ 'LEN',+ 'UPPER',+ 'LOWER',+ 'TRIM',+ 'PROPER',+ 'SUBSTITUTE',+ 'REPLACE',+ 'FIND',+ 'SEARCH',+ 'REPT',+ 'CHAR',+ 'CODE',+ 'EXACT',+ 'CLEAN',+ 'SPLIT',+ 'VALUE',+ 'T',+ 'N',+]);++const DATE_FUNCTIONS = new Set([+ 'DATE',+ 'YEAR',+ 'MONTH',+ 'DAY',+ 'TODAY',+ 'NOW',+ 'WEEKDAY',+ 'EDATE',+ 'EOMONTH',+ 'DAYS',+ 'DATEDIF',+ 'DATEVALUE',+ 'NETWORKDAYS',+ 'WEEKNUM',+ 'ISOWEEKNUM',+]);++const QUERY_FUNCTIONS = new Set([+ 'QUERY',+ 'LOOKUP',+ 'VLOOKUP',+ 'HLOOKUP',+ 'INDEX',+ 'MATCH',+ 'CHOOSE',+ 'ISBLANK',+ 'ISERROR',+ 'ISNA',+ 'ISNUMBER',+ 'ISTEXT',+ 'ISLOGICAL',+ 'ISREF',+ 'ISEVEN',+ 'ISODD',+]);++// Excel formula syntax parser for CodeMirror+const excelFormulaParser: StreamParser<{ inString: boolean }> = {+ startState() {+ return { inString: false };+ },++ token(stream, state) {+ // Handle strings+ if (state.inString) {+ if (stream.skipTo('"')) {+ stream.next();+ state.inString = false;+ } else {+ stream.skipToEnd();+ }+ return 'string';+ }++ if (stream.match('"')) {+ state.inString = true;+ return 'string';+ }++ // Handle numbers+ if (stream.match(/^-?\d+(\.\d+)?/)) {+ return 'number';+ }++ // Handle operators+ if (stream.match(/^[+\-*/=<>(),:]/)) {+ return 'operator';+ }++ // Handle function names (uppercase letters followed by parenthesis)+ if (stream.match(/^[A-Z_][A-Z0-9_]*/)) {+ const word = stream.current();+ // Check if it's a function (next non-whitespace is '(')+ const pos = stream.pos;+ stream.eatSpace();+ if (stream.peek() === '(') {+ stream.pos = pos; // Reset position++ // Categorize the function using different token types+ if (MATH_FUNCTIONS.has(word)) {+ return 'keyword';+ }+ if (LOGICAL_FUNCTIONS.has(word)) {+ return 'className';+ }+ if (TEXT_FUNCTIONS.has(word)) {+ return 'namespace';+ }+ if (DATE_FUNCTIONS.has(word)) {+ return 'typeName';+ }+ if (QUERY_FUNCTIONS.has(word)) {+ return 'propertyName';+ }+ return 'function';+ }+ stream.pos = pos; // Reset position+ return 'variableName';+ }++ // Handle variable names (lowercase or mixed case)+ if (stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)) {+ return 'variableName.special';+ }++ // Skip whitespace+ if (stream.eatSpace()) {+ return null;+ }++ stream.next();+ return null;+ },+};++// Transaction field variables for autocomplete+const transactionFields: Completion[] = [+ {+ label: 'amount',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Transaction amount in cents. Use for calculations and comparisons.\n\nExample: `=amount / 100` to get dollar value',+ ),+ },+ {+ label: 'date',+ type: 'variable',+ 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',+ ),+ },+ {+ label: 'notes',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Transaction notes/memo text. Use for string operations.\n\nExample: `=UPPER(notes)` to convert to uppercase',+ ),+ },+ {+ label: 'imported_payee',+ type: 'variable',+ 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',+ ),+ },+ {+ label: 'payee',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Payee ID (string). The ID of the payee.\n\nExample: `=CONCATENATE("Payment to ", payee)`',+ ),+ },+ {+ label: 'payee_name',+ type: 'variable',+ 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)`',+ ),+ },+ {+ label: 'account',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Account ID (string). The ID of the account.\n\nExample: `=CONCATENATE("Paid from ", account)`',+ ),+ },+ {+ label: 'account_name',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Account name (string). The human-readable name of the account.\n\nExample: `=CONCATENATE("Paid from ", account_name)`',+ ),+ },+ {+ label: 'category',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Category ID (string). The ID of the category.\n\nExample: `=IF(category="Groceries", "Food", "Other")`',+ ),+ },+ {+ label: 'category_name',+ type: 'variable',+ 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")`',+ ),+ },+ {+ label: 'cleared',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Boolean cleared status. TRUE if transaction is cleared, FALSE otherwise.\n\nExample: `=IF(cleared, "Cleared", "Pending")`',+ ),+ },+ {+ label: 'reconciled',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Boolean reconciled status. TRUE if transaction is reconciled, FALSE otherwise.',+ ),+ },+];++// Convert function definitions to completions with grouping+function getFunctionCompletions(mode: FormulaMode): Completion[] {+ const functions =+ mode === 'query' ? queryModeFunctions : transactionModeFunctions;++ // Helper to create completion with section info+ const createCompletion = (+ name: string,+ func: FunctionDef,+ section: string,+ ): Completion => ({+ label: name,+ type: 'function',+ section,+ info: `${func.description}\n\nParameters: ${func.parameters.map(p => p.name).join(', ')}\n\n${func.parameters.map(p => `- ${p.name}: ${p.description}`).join('\n')}`,+ apply: `${name}()`,+ boost: 10, // Boost functions to appear higher+ });++ const completions: Completion[] = [];++ // Group functions by category+ for (const [name, func] of Object.entries(functions)) {+ if (MATH_FUNCTIONS.has(name)) {+ completions.push(createCompletion(name, func, '📊 Math Functions'));+ } else if (LOGICAL_FUNCTIONS.has(name)) {+ completions.push(createCompletion(name, func, '🔀 Logical Functions'));+ } else if (TEXT_FUNCTIONS.has(name)) {+ completions.push(createCompletion(name, func, '📝 Text Functions'));+ } else if (DATE_FUNCTIONS.has(name)) {+ completions.push(createCompletion(name, func, '📅 Date Functions'));+ } else if (QUERY_FUNCTIONS.has(name)) {+ completions.push(createCompletion(name, func, '🔍 Query Functions'));+ } else {+ completions.push(createCompletion(name, func, '⚙️ Other Functions'));+ }+ }++ return completions;+}++// Autocomplete extension+export function excelFormulaAutocomplete(+ mode: FormulaMode,+ queries?: Record<string, unknown>,+ variables?: Record<string, number | string>,+): Extension {+ const functionCompletions = getFunctionCompletions(mode);++ const queryCompletions: Completion[] = queries+ ? Object.keys(queries).map(queryName => ({+ label: `QUERY("${queryName}")`,+ type: 'function',+ section: '🔍 Query Functions',+ info: t('Execute the {{queryName}} query and return the result.', {+ queryName,+ }),+ apply: `QUERY("${queryName}")`,+ boost: 15, // Boost query completions to appear at top of Query Functions section+ }))+ : [];++ const variableCompletions: Completion[] = variables+ ? Object.entries(variables).map(([varName, value]) => ({+ label: varName,+ type: 'variable',+ section: '🔢 Variables',+ info: t('Variable with value: {{value}}', {+ value: String(value),+ }),+ boost: 20, // Boost variable completions to appear at top+ }))+ : [];++ return autocompletion({+ override: [+ (context: CompletionContext) => {+ const word = context.matchBefore(/\w*/);+ if (!word || (word.from === word.to && !context.explicit)) {+ return null;+ }++ const suggestions: Completion[] = [+ ...variableCompletions, // Put variable completions first+ ...queryCompletions, // Put query completions first+ ...functionCompletions,+ ];++ if (mode === 'transaction') {+ suggestions.push(...transactionFields);+ }++ // Sort by section first, then by boost (descending), then by label+ const sortedSuggestions = suggestions.sort((a, b) => {+ // Define section priority order+ const sectionOrder: Record<string, number> = {+ '🔢 Variables': -1,+ '🔍 Query Functions': 0,+ '📊 Math Functions': 1,+ '🔀 Logical Functions': 2,+ '📝 Text Functions': 3,+ '📅 Date Functions': 4,+ '⚙️ Other Functions': 5,+ '💰 Transaction Fields': 6,+ };++ // Get section names+ const sectionA =+ typeof a.section === 'string' ? a.section : a.section?.name || '';+ const sectionB =+ typeof b.section === 'string' ? b.section : b.section?.name || '';++ // Compare by section priority+ const orderA = sectionOrder[sectionA] ?? 999;+ const orderB = sectionOrder[sectionB] ?? 999;+ if (orderA !== orderB) {+ return orderA - orderB;+ }++ // Within same section, sort by boost (higher first)+ const boostA = a.boost || 0;+ const boostB = b.boost || 0;+ if (boostA !== boostB) {+ return boostB - boostA;+ }++ // Finally, sort by label alphabetically+ return a.label.localeCompare(b.label);+ });++ return {+ from: word.from,+ options: sortedSuggestions,+ };+ },+ ],+ });+}++// Hover tooltip for documentation+export function excelFormulaHover(mode: FormulaMode): Extension {+ const functions =+ mode === 'query' ? queryModeFunctions : transactionModeFunctions;++ return hoverTooltip((view, pos) => {+ const word = view.state.wordAt(pos);+ if (!word) return null;+ const w = view.state.doc.sliceString(word.from, word.to);+ const upper = w.toUpperCase();+ const funcDef = functions[upper];+ if (funcDef) {+ return {+ pos: word.from,+ end: word.to,+ above: true,+ create() {+ const dom = document.createElement('div');+ dom.className = 'cm-tooltip-hover';+ Object.assign(dom.style, {+ padding: '8px',+ boxShadow:+ '0 15px 30px 0 rgba(0,0,0,0.11), 0 5px 15px 0 rgba(0,0,0,0.08)',+ borderWidth: '2px',+ borderRadius: '4px',+ borderStyle: 'solid',+ borderColor: theme.tooltipBorder,+ backgroundColor: theme.tooltipBackground,+ color: theme.tooltipText,+ overflow: 'auto',+ });+ const root = createRoot(dom);+ root.render(+ <FunctionTooltip+ name={upper}+ description={funcDef.description}+ parameters={funcDef.parameters}+ />,+ );+ return {+ dom,+ destroy() {+ root.unmount();+ },+ };+ },+ } satisfies Tooltip;+ }++ // Transaction fields+ if (mode === 'transaction') {+ const field = transactionFields.find(f => f.label === w);+ if (field) {+ return {+ pos: word.from,+ end: word.to,+ above: true,+ create() {+ const dom = document.createElement('div');+ dom.className = 'cm-tooltip-hover';+ Object.assign(dom.style, {+ padding: '8px',+ boxShadow:+ '0 15px 30px 0 rgba(0,0,0,0.11), 0 5px 15px 0 rgba(0,0,0,0.08)',+ borderWidth: '2px',+ borderRadius: '4px',+ borderStyle: 'solid',+ borderColor: theme.tooltipBorder,+ backgroundColor: theme.tooltipBackground,+ color: theme.tooltipText,+ overflow: 'auto',+ });+ const root = createRoot(dom);+ const infoText = typeof field.info === 'string' ? field.info : '';+ root.render(<FieldTooltip label={field.label} info={infoText} />);+ return {+ dom,+ destroy() {+ root.unmount();+ },+ };+ },+ } satisfies Tooltip;+ }+ }++ return null;+ });+}++// Excel formula language support+export const excelFormulaLanguage = StreamLanguage.define(excelFormulaParser);++// Custom theme for categorized function highlighting (light)+const functionCategoryTheme = EditorView.baseTheme({+ '&light .cm-keyword': { color: '#0066CC' }, // Math functions in blue+ '&light .cm-className': { color: '#267F99' }, // Logical functions in teal+ '&light .cm-namespace': { color: '#AF00DB' }, // Text functions in purple+ '&light .cm-typeName': { color: '#098658' }, // Date functions in green+ '&light .cm-propertyName': { color: '#D73A49' }, // Query functions in red+});++// Syntax highlighting for Excel formulas+export const excelFormulaHighlighting = syntaxHighlighting(+ HighlightStyle.define([+ { tag: tags.function(tags.variableName), color: '#795E26' }, // Generic functions in brown/gold+ // Other syntax elements+ { tag: tags.string, color: '#A31515' }, // Strings in red+ { tag: tags.number, color: '#098658' }, // Numbers in green+ { tag: tags.operator, color: '#000000' }, // Operators in black+ { tag: tags.variableName, color: '#001080' }, // Variables in dark blue+ { tag: tags.special(tags.variableName), color: '#0070C1' }, // Special variables (transaction fields) in bright blue+ ]),+);++// Custom theme for categorized function highlighting (dark)+const functionCategoryThemeDark = EditorView.baseTheme({+ '&dark .cm-keyword': { color: '#4FC1FF' }, // Math functions in bright cyan+ '&dark .cm-className': { color: '#4EC9B0' }, // Logical functions in teal+ '&dark .cm-namespace': { color: '#C586C0' }, // Text functions in light purple+ '&dark .cm-typeName': { color: '#B5CEA8' }, // Date functions in light green+ '&dark .cm-propertyName': { color: '#F97583' }, // Query functions in light red+});++// Dark theme syntax highlighting+export const excelFormulaDarkHighlighting = syntaxHighlighting(+ HighlightStyle.define([+ { tag: tags.function(tags.variableName), color: '#DCDCAA' }, // Generic functions in light yellow+ // Other syntax elements+ { tag: tags.string, color: '#CE9178' }, // Strings in orange+ { tag: tags.number, color: '#B5CEA8' }, // Numbers in light green+ { tag: tags.operator, color: '#D4D4D4' }, // Operators in light gray+ { tag: tags.variableName, color: '#9CDCFE' }, // Variables in light blue+ { tag: tags.special(tags.variableName), color: '#4FC1FF' }, // Special variables in bright cyan+ ]),+);++// Combined extension for Excel formula support+export function excelFormulaExtension(+ mode: FormulaMode,+ queries?: Record<string, unknown>,+ isDark?: boolean,+ variables?: Record<string, number | string>,+): Extension[] {+ return [+ excelFormulaLanguage,+ excelFormulaAutocomplete(mode, queries, variables),+ excelFormulaHover(mode),+ isDark ? excelFormulaDarkHighlighting : excelFormulaHighlighting,+ isDark ? functionCategoryThemeDark : functionCategoryTheme,+ ];+}diff --git a/packages/desktop-client/src/components/formula/queryModeFunctions.ts b/packages/desktop-client/src/components/formula/queryModeFunctions.tsnew file mode 100644index 0000000000..01826429f1--- /dev/null+++ b/packages/desktop-client/src/components/formula/queryModeFunctions.ts@@ -0,0 +1,775 @@+import { t } from 'i18next';++export type FunctionDef = {+ name: string;+ description: string;+ parameters: Array<{ name: string; description: string }>;+};++// Excel formula functions for CodeMirror (Query Mode) - Complete set+export const queryModeFunctions: Record<string, FunctionDef> = {+ // Math and Aggregation Functions+ SUM: {+ name: 'SUM',+ description: t('Returns the sum of all numbers in a range.'),+ parameters: [+ { name: 'numbers', description: 'Number1, Number2, ...NumberN' },+ ],+ },+ AVERAGE: {+ name: 'AVERAGE',+ description: t('Returns the average of all numbers in a range.'),+ parameters: [+ { 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.'),+ 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.'),+ 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.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ ROUND: {+ name: 'ROUND',+ description: t('Rounds a number to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ ROUNDDOWN: {+ name: 'ROUNDDOWN',+ description: t('Rounds down to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ ROUNDUP: {+ name: 'ROUNDUP',+ description: t('Rounds up to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ FLOOR: {+ name: 'FLOOR',+ description: t('Rounds down to nearest multiple of significance.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'significance', description: 'Significance' },+ ],+ },+ CEILING: {+ name: 'CEILING',+ description: t('Rounds up to nearest multiple of significance.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'significance', description: 'Significance' },+ ],+ },+ POWER: {+ name: 'POWER',+ description: t('Returns base raised to the power of exponent.'),+ parameters: [+ { name: 'base', description: 'Base' },+ { name: 'exponent', description: 'Exponent' },+ ],+ },+ SQRT: {+ name: 'SQRT',+ description: t('Returns the square root.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ MOD: {+ name: 'MOD',+ description: t('Returns the remainder of division.'),+ parameters: [+ { name: 'dividend', description: 'Dividend' },+ { name: 'divisor', description: 'Divisor' },+ ],+ },+ PI: {+ name: 'PI',+ description: t('Returns the value of PI.'),+ parameters: [],+ },+ SIN: {+ name: 'SIN',+ description: t('Returns the sine of an angle.'),+ parameters: [{ name: 'angle', description: 'Angle' }],+ },+ COS: {+ name: 'COS',+ description: t('Returns the cosine of an angle.'),+ parameters: [{ name: 'angle', description: 'Angle' }],+ },+ TAN: {+ name: 'TAN',+ description: t('Returns the tangent of an angle.'),+ parameters: [{ name: 'angle', description: 'Angle' }],+ },+ LN: {+ name: 'LN',+ description: t('Returns the natural logarithm.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ LOG: {+ name: 'LOG',+ description: t('Returns the logarithm to specified base.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'base', description: 'Base' },+ ],+ },+ LOG10: {+ name: 'LOG10',+ description: t('Returns the base-10 logarithm.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ EXP: {+ name: 'EXP',+ description: t('Returns e raised to the power of number.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ PRODUCT: {+ name: 'PRODUCT',+ description: t('Returns the product of all numbers.'),+ parameters: [+ { 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',+ description: t('Returns one value if condition is TRUE, another if FALSE.'),+ parameters: [+ { name: 'condition', description: 'Condition' },+ { name: 'value_if_true', description: 'ValueIfTrue' },+ { name: 'value_if_false', description: 'ValueIfFalse' },+ ],+ },+ IFS: {+ name: 'IFS',+ description: t(+ 'Checks multiple conditions and returns corresponding values.',+ ),+ parameters: [+ { name: 'condition1', description: 'Condition1' },+ { name: 'value1', description: 'Value1' },+ ],+ },+ AND: {+ name: 'AND',+ description: t('Returns TRUE if all arguments are TRUE.'),+ parameters: [+ {+ name: 'conditions',+ description: 'Condition1, Condition2, ...ConditionN',+ },+ ],+ },+ OR: {+ name: 'OR',+ description: t('Returns TRUE if any argument is TRUE.'),+ parameters: [+ {+ name: 'conditions',+ description: 'Condition1, Condition2, ...ConditionN',+ },+ ],+ },+ XOR: {+ name: 'XOR',+ description: t('Returns TRUE if odd number of arguments are TRUE.'),+ parameters: [+ {+ name: 'conditions',+ description: 'Condition1, Condition2, ...ConditionN',+ },+ ],+ },+ NOT: {+ name: 'NOT',+ description: t('Reverses the logical value.'),+ parameters: [{ name: 'condition', description: 'Condition' }],+ },+ TRUE: {+ name: 'TRUE',+ description: t('Returns the logical value TRUE.'),+ parameters: [],+ },+ FALSE: {+ name: 'FALSE',+ description: t('Returns the logical value FALSE.'),+ parameters: [],+ },+ IFERROR: {+ name: 'IFERROR',+ description: t('Returns value if no error, otherwise returns alternative.'),+ parameters: [+ { name: 'value', description: 'Value' },+ { name: 'value_if_error', description: 'ValueIfError' },+ ],+ },+ IFNA: {+ name: 'IFNA',+ description: t(+ 'Returns value if not #N/A error, otherwise returns alternative.',+ ),+ parameters: [+ { name: 'value', description: 'Value' },+ { name: 'value_if_na', description: 'ValueIfNA' },+ ],+ },+ SWITCH: {+ name: 'SWITCH',+ description: t(+ 'Matches expression against values and returns corresponding result.',+ ),+ parameters: [+ { name: 'expression', description: 'Expression' },+ { name: 'value1', description: 'Value1' },+ { name: 'result1', description: 'Result1' },+ ],+ },++ // Text Functions+ CONCATENATE: {+ name: 'CONCATENATE',+ description: t('Combines several text strings into one.'),+ parameters: [{ name: 'texts', description: 'Text1, Text2, ...TextN' }],+ },+ UPPER: {+ name: 'UPPER',+ description: t('Converts text to uppercase.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ LOWER: {+ name: 'LOWER',+ description: t('Converts text to lowercase.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ PROPER: {+ name: 'PROPER',+ description: t('Capitalizes first letter of each word.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ LEFT: {+ name: 'LEFT',+ description: t('Returns leftmost characters from text.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'num_chars', description: 'Number' },+ ],+ },+ RIGHT: {+ name: 'RIGHT',+ description: t('Returns rightmost characters from text.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'num_chars', description: 'Number' },+ ],+ },+ MID: {+ name: 'MID',+ description: t('Returns substring from specified position.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'start_pos', description: 'Start_position' },+ { name: 'length', description: 'Length' },+ ],+ },+ LEN: {+ name: 'LEN',+ description: t('Returns length of text.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ TRIM: {+ name: 'TRIM',+ description: t('Removes extra spaces from text.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ SUBSTITUTE: {+ name: 'SUBSTITUTE',+ description: t('Replaces occurrences of text.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'old_text', description: 'Old_text' },+ { name: 'new_text', description: 'New_text' },+ ],+ },+ REPLACE: {+ name: 'REPLACE',+ description: t('Replaces substring at specified position.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'start_pos', description: 'Start_position' },+ { name: 'length', description: 'Length' },+ { name: 'new_text', description: 'New_text' },+ ],+ },+ FIND: {+ name: 'FIND',+ description: t('Finds text within text (case-sensitive).'),+ parameters: [+ { name: 'find_text', description: 'Text1' },+ { name: 'within_text', description: 'Text2' },+ ],+ },+ SEARCH: {+ name: 'SEARCH',+ description: t(+ 'Finds text within text (case-insensitive, supports wildcards).',+ ),+ parameters: [+ { name: 'search_text', description: 'Search_string' },+ { name: 'text', description: 'Text' },+ ],+ },+ TEXT: {+ name: 'TEXT',+ description: t('Converts number to text with format.'),+ parameters: [+ { name: 'value', description: 'Number' },+ { name: 'format', description: 'Format' },+ ],+ },+ REPT: {+ name: 'REPT',+ description: t('Repeats text specified number of times.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'number', description: 'Number' },+ ],+ },+ CHAR: {+ name: 'CHAR',+ description: t('Converts number to character.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ CODE: {+ name: 'CODE',+ description: t('Returns numeric code for first character.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ EXACT: {+ name: 'EXACT',+ description: t('Returns TRUE if texts are exactly the same.'),+ parameters: [+ { name: 'text1', description: 'Text' },+ { name: 'text2', description: 'Text' },+ ],+ },++ // Date and Time Functions+ DATE: {+ name: 'DATE',+ description: t('Returns date as number of days since null date.'),+ parameters: [+ { name: 'year', description: 'Year' },+ { name: 'month', description: 'Month' },+ { name: 'day', description: 'Day' },+ ],+ },+ TODAY: {+ name: 'TODAY',+ description: t('Returns current date.'),+ parameters: [],+ },+ NOW: {+ name: 'NOW',+ description: t('Returns current date and time.'),+ parameters: [],+ },+ YEAR: {+ name: 'YEAR',+ description: t('Returns the year from a date.'),+ parameters: [{ name: 'date', description: 'Number' }],+ },+ MONTH: {+ name: 'MONTH',+ description: t('Returns the month from a date.'),+ parameters: [{ name: 'date', description: 'Number' }],+ },+ DAY: {+ name: 'DAY',+ description: t('Returns the day from a date.'),+ parameters: [{ name: 'date', description: 'Number' }],+ },+ WEEKDAY: {+ name: 'WEEKDAY',+ description: t('Returns day of week (1-7).'),+ parameters: [+ { name: 'date', description: 'Date' },+ { name: 'type', description: 'Type' },+ ],+ },+ EDATE: {+ name: 'EDATE',+ description: t('Returns date shifted by specified months.'),+ parameters: [+ { name: 'start_date', description: 'Startdate' },+ { name: 'months', description: 'Months' },+ ],+ },+ EOMONTH: {+ name: 'EOMONTH',+ description: t('Returns last day of month after specified months.'),+ parameters: [+ { name: 'start_date', description: 'Startdate' },+ { name: 'months', description: 'Months' },+ ],+ },+ DAYS: {+ name: 'DAYS',+ description: t('Calculates difference between dates in days.'),+ parameters: [+ { name: 'end_date', description: 'Date2' },+ { name: 'start_date', description: 'Date1' },+ ],+ },+ DATEDIF: {+ name: 'DATEDIF',+ description: t('Calculates distance between dates.'),+ parameters: [+ { name: 'start_date', description: 'Date1' },+ { name: 'end_date', description: 'Date2' },+ { name: 'unit', description: 'Unit' },+ ],+ },+ NETWORKDAYS: {+ name: 'NETWORKDAYS',+ description: t('Returns number of working days between dates.'),+ parameters: [+ { name: 'start_date', description: 'Date1' },+ { name: 'end_date', description: 'Date2' },+ ],+ },+ WEEKNUM: {+ name: 'WEEKNUM',+ description: t('Returns week number of year.'),+ parameters: [+ { name: 'date', description: 'Date' },+ { 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: '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' },+ ],+ },++ // Information Functions+ ISBLANK: {+ name: 'ISBLANK',+ description: t('Returns TRUE if value is blank.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISERROR: {+ name: 'ISERROR',+ description: t('Returns TRUE if value is any error.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISNA: {+ name: 'ISNA',+ description: t('Returns TRUE if value is #N/A error.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISNUMBER: {+ name: 'ISNUMBER',+ description: t('Returns TRUE if value is a number.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISTEXT: {+ name: 'ISTEXT',+ description: t('Returns TRUE if value is text.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISLOGICAL: {+ name: 'ISLOGICAL',+ 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' }],+ },++ // Financial Functions+ PMT: {+ name: 'PMT',+ description: t('Calculates payment for a loan.'),+ parameters: [+ { name: 'rate', description: 'Rate' },+ { name: 'nper', description: 'Nper' },+ { name: 'pv', description: 'PV' },+ ],+ },+ FV: {+ name: 'FV',+ description: t('Calculates future value of investment.'),+ parameters: [+ { name: 'rate', description: 'Rate' },+ { name: 'nper', description: 'Nper' },+ { name: 'pmt', description: 'PMT' },+ ],+ },+ PV: {+ name: 'PV',+ description: t('Calculates present value of investment.'),+ parameters: [+ { name: 'rate', description: 'Rate' },+ { name: 'nper', description: 'Nper' },+ { name: 'pmt', description: 'PMT' },+ ],+ },+ NPV: {+ name: 'NPV',+ description: t('Calculates net present value.'),+ parameters: [+ { name: 'rate', description: 'Rate' },+ { name: 'value1', description: 'Value1' },+ { name: 'value2', description: 'Value2' },+ ],+ },+ IRR: {+ name: 'IRR',+ description: t('Calculates internal rate of return.'),+ parameters: [{ name: 'values', description: 'Values' }],+ },+ RATE: {+ name: 'RATE',+ description: t('Calculates interest rate per period.'),+ parameters: [+ { name: 'nper', description: 'Nper' },+ { name: 'pmt', description: 'PMT' },+ { name: 'pv', description: 'PV' },+ ],+ },++ // Query-specific+ QUERY: {+ name: 'QUERY',+ description: t('Execute a query and return the result.'),+ parameters: [+ { name: 'queryName', description: 'Name of the query to execute' },+ ],+ },+};diff --git a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts b/packages/desktop-client/src/components/formula/transactionModeFunctions.tsnew file mode 100644index 0000000000..e0a0ff57bd--- /dev/null+++ b/packages/desktop-client/src/components/formula/transactionModeFunctions.ts@@ -0,0 +1,498 @@+import { t } from 'i18next';++export type FunctionDef = {+ name: string;+ description: string;+ parameters: Array<{ name: string; description: string }>;+};++// Excel formula functions for CodeMirror (Transaction Mode) - Complete set+export const transactionModeFunctions: Record<string, FunctionDef> = {+ // Text Functions (most useful for transaction fields)+ CONCATENATE: {+ name: 'CONCATENATE',+ description: t('Combines several text strings into one.'),+ parameters: [{ name: 'texts', description: 'Text1, Text2, ...TextN' }],+ },+ UPPER: {+ name: 'UPPER',+ description: t('Converts text to uppercase.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ LOWER: {+ name: 'LOWER',+ description: t('Converts text to lowercase.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ PROPER: {+ name: 'PROPER',+ description: t('Capitalizes first letter of each word.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ LEFT: {+ name: 'LEFT',+ description: t('Returns leftmost characters from text.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'num_chars', description: 'Number' },+ ],+ },+ RIGHT: {+ name: 'RIGHT',+ description: t('Returns rightmost characters from text.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'num_chars', description: 'Number' },+ ],+ },+ MID: {+ name: 'MID',+ description: t('Returns substring from specified position.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'start_pos', description: 'Start_position' },+ { name: 'length', description: 'Length' },+ ],+ },+ LEN: {+ name: 'LEN',+ description: t('Returns length of text.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ TRIM: {+ name: 'TRIM',+ description: t('Removes extra spaces from text.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ SUBSTITUTE: {+ name: 'SUBSTITUTE',+ description: t('Replaces occurrences of text.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'old_text', description: 'Old_text' },+ { name: 'new_text', description: 'New_text' },+ ],+ },+ REPLACE: {+ name: 'REPLACE',+ description: t('Replaces substring at specified position.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'start_pos', description: 'Start_position' },+ { name: 'length', description: 'Length' },+ { name: 'new_text', description: 'New_text' },+ ],+ },+ FIND: {+ name: 'FIND',+ description: t('Finds text within text (case-sensitive).'),+ parameters: [+ { name: 'find_text', description: 'Text1' },+ { name: 'within_text', description: 'Text2' },+ ],+ },+ SEARCH: {+ name: 'SEARCH',+ description: t(+ 'Finds text within text (case-insensitive, supports wildcards).',+ ),+ parameters: [+ { name: 'search_text', description: 'Search_string' },+ { name: 'text', description: 'Text' },+ ],+ },+ TEXT: {+ name: 'TEXT',+ description: t('Converts number to text with format.'),+ parameters: [+ { name: 'value', description: 'Number' },+ { name: 'format', description: 'Format' },+ ],+ },+ REPT: {+ name: 'REPT',+ description: t('Repeats text specified number of times.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'number', description: 'Number' },+ ],+ },+ CHAR: {+ name: 'CHAR',+ description: t('Converts number to character.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ CODE: {+ name: 'CODE',+ description: t('Returns numeric code for first character.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ EXACT: {+ name: 'EXACT',+ description: t('Returns TRUE if texts are exactly the same.'),+ parameters: [+ { name: 'text1', description: 'Text' },+ { name: 'text2', description: 'Text' },+ ],+ },+ CLEAN: {+ name: 'CLEAN',+ description: t('Removes non-printable characters from text.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ SPLIT: {+ name: 'SPLIT',+ description: t('Splits text by space and returns part at index.'),+ parameters: [+ { name: 'text', description: 'Text' },+ { name: 'index', description: 'Index' },+ ],+ },++ // Math Functions (for amount calculations)+ SUM: {+ name: 'SUM',+ description: t('Returns the sum of all numbers.'),+ parameters: [+ { name: 'numbers', description: 'Number1, Number2, ...NumberN' },+ ],+ },+ ABS: {+ name: 'ABS',+ description: t('Returns the absolute value of a number.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ ROUND: {+ name: 'ROUND',+ description: t('Rounds a number to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ ROUNDDOWN: {+ name: 'ROUNDDOWN',+ description: t('Rounds down to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ ROUNDUP: {+ name: 'ROUNDUP',+ description: t('Rounds up to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ FLOOR: {+ name: 'FLOOR',+ description: t('Rounds down to nearest multiple of significance.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'significance', description: 'Significance' },+ ],+ },+ CEILING: {+ name: 'CEILING',+ description: t('Rounds up to nearest multiple of significance.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'significance', description: 'Significance' },+ ],+ },+ INT: {+ name: 'INT',+ description: t('Rounds down to nearest integer.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ TRUNC: {+ name: 'TRUNC',+ description: t('Truncates number to specified decimals.'),+ parameters: [+ { name: 'number', description: 'Number' },+ { name: 'decimals', description: 'Decimals' },+ ],+ },+ MOD: {+ name: 'MOD',+ description: t('Returns the remainder of division.'),+ parameters: [+ { name: 'dividend', description: 'Dividend' },+ { name: 'divisor', description: 'Divisor' },+ ],+ },+ POWER: {+ name: 'POWER',+ description: t('Returns base raised to the power of exponent.'),+ parameters: [+ { name: 'base', description: 'Base' },+ { name: 'exponent', description: 'Exponent' },+ ],+ },+ SQRT: {+ name: 'SQRT',+ description: t('Returns the square root.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ SIGN: {+ name: 'SIGN',+ description: t('Returns -1 for negative, 0 for zero, 1 for positive.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },++ // Date and Time Functions+ DATE: {+ name: 'DATE',+ description: t('Returns date as number of days since null date.'),+ parameters: [+ { name: 'year', description: 'Year' },+ { name: 'month', description: 'Month' },+ { name: 'day', description: 'Day' },+ ],+ },+ TODAY: {+ name: 'TODAY',+ description: t('Returns current date.'),+ parameters: [],+ },+ NOW: {+ name: 'NOW',+ description: t('Returns current date and time.'),+ parameters: [],+ },+ YEAR: {+ name: 'YEAR',+ description: t('Returns the year from a date.'),+ parameters: [{ name: 'date', description: 'Number' }],+ },+ MONTH: {+ name: 'MONTH',+ description: t('Returns the month from a date.'),+ parameters: [{ name: 'date', description: 'Number' }],+ },+ DAY: {+ name: 'DAY',+ description: t('Returns the day from a date.'),+ parameters: [{ name: 'date', description: 'Number' }],+ },+ WEEKDAY: {+ name: 'WEEKDAY',+ description: t('Returns day of week (1-7).'),+ parameters: [+ { name: 'date', description: 'Date' },+ { name: 'type', description: 'Type' },+ ],+ },+ EDATE: {+ name: 'EDATE',+ description: t('Returns date shifted by specified months.'),+ parameters: [+ { name: 'start_date', description: 'Startdate' },+ { name: 'months', description: 'Months' },+ ],+ },+ EOMONTH: {+ name: 'EOMONTH',+ description: t('Returns last day of month after specified months.'),+ parameters: [+ { name: 'start_date', description: 'Startdate' },+ { name: 'months', description: 'Months' },+ ],+ },+ DAYS: {+ name: 'DAYS',+ description: t('Calculates difference between dates in days.'),+ parameters: [+ { name: 'end_date', description: 'Date2' },+ { name: 'start_date', description: 'Date1' },+ ],+ },+ DATEDIF: {+ name: 'DATEDIF',+ description: t('Calculates distance between dates.'),+ parameters: [+ { name: 'start_date', description: 'Date1' },+ { name: 'end_date', description: 'Date2' },+ { name: 'unit', description: 'Unit' },+ ],+ },+ DATEVALUE: {+ name: 'DATEVALUE',+ description: t('Parses a date string and returns it as a number.'),+ parameters: [{ name: 'date_string', description: 'Datestring' }],+ },+ WEEKNUM: {+ name: 'WEEKNUM',+ description: t('Returns week number of year.'),+ parameters: [+ { name: 'date', description: 'Date' },+ { name: 'type', description: 'Type' },+ ],+ },+ ISOWEEKNUM: {+ name: 'ISOWEEKNUM',+ description: t('Returns ISO week number.'),+ parameters: [{ name: 'date', description: 'Date' }],+ },++ // Logical Functions+ IF: {+ name: 'IF',+ description: t('Returns one value if condition is TRUE, another if FALSE.'),+ parameters: [+ { name: 'condition', description: 'Condition' },+ { name: 'value_if_true', description: 'ValueIfTrue' },+ { name: 'value_if_false', description: 'ValueIfFalse' },+ ],+ },+ IFS: {+ name: 'IFS',+ description: t(+ 'Checks multiple conditions and returns corresponding values.',+ ),+ parameters: [+ { name: 'condition1', description: 'Condition1' },+ { name: 'value1', description: 'Value1' },+ ],+ },+ AND: {+ name: 'AND',+ description: t('Returns TRUE if all arguments are TRUE.'),+ parameters: [+ {+ name: 'conditions',+ description: 'Condition1, Condition2, ...ConditionN',+ },+ ],+ },+ OR: {+ name: 'OR',+ description: t('Returns TRUE if any argument is TRUE.'),+ parameters: [+ {+ name: 'conditions',+ description: 'Condition1, Condition2, ...ConditionN',+ },+ ],+ },+ XOR: {+ name: 'XOR',+ description: t('Returns TRUE if odd number of arguments are TRUE.'),+ parameters: [+ {+ name: 'conditions',+ description: 'Condition1, Condition2, ...ConditionN',+ },+ ],+ },+ NOT: {+ name: 'NOT',+ description: t('Reverses the logical value.'),+ parameters: [{ name: 'condition', description: 'Condition' }],+ },+ TRUE: {+ name: 'TRUE',+ description: t('Returns the logical value TRUE.'),+ parameters: [],+ },+ FALSE: {+ name: 'FALSE',+ description: t('Returns the logical value FALSE.'),+ parameters: [],+ },+ IFERROR: {+ name: 'IFERROR',+ description: t('Returns value if no error, otherwise returns alternative.'),+ parameters: [+ { name: 'value', description: 'Value' },+ { name: 'value_if_error', description: 'ValueIfError' },+ ],+ },+ IFNA: {+ name: 'IFNA',+ description: t(+ 'Returns value if not #N/A error, otherwise returns alternative.',+ ),+ parameters: [+ { name: 'value', description: 'Value' },+ { name: 'value_if_na', description: 'ValueIfNA' },+ ],+ },+ SWITCH: {+ name: 'SWITCH',+ description: t(+ 'Matches expression against values and returns corresponding result.',+ ),+ parameters: [+ { name: 'expression', description: 'Expression' },+ { name: 'value1', description: 'Value1' },+ { name: 'result1', description: 'Result1' },+ ],+ },++ // Information Functions+ ISBLANK: {+ name: 'ISBLANK',+ description: t('Returns TRUE if value is blank.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISERROR: {+ name: 'ISERROR',+ description: t('Returns TRUE if value is any error.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISNA: {+ name: 'ISNA',+ description: t('Returns TRUE if value is #N/A error.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISNUMBER: {+ name: 'ISNUMBER',+ description: t('Returns TRUE if value is a number.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISTEXT: {+ name: 'ISTEXT',+ description: t('Returns TRUE if value is text.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ ISLOGICAL: {+ name: 'ISLOGICAL',+ 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.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },+ ISODD: {+ name: 'ISODD',+ description: t('Returns TRUE if number is odd.'),+ parameters: [{ name: 'number', description: 'Number' }],+ },++ // Conversion Functions+ VALUE: {+ name: 'VALUE',+ description: t('Converts text to a number.'),+ parameters: [{ name: 'text', description: 'Text' }],+ },+ T: {+ name: 'T',+ description: t('Returns text if value is text, empty string otherwise.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+ N: {+ name: 'N',+ description: t('Converts value to a number.'),+ parameters: [{ name: 'value', description: 'Value' }],+ },+};diff --git a/packages/desktop-client/src/components/reports/FormulaResult.tsx b/packages/desktop-client/src/components/reports/FormulaResult.tsxnew file mode 100644index 0000000000..c27859f4d6--- /dev/null+++ b/packages/desktop-client/src/components/reports/FormulaResult.tsx@@ -0,0 +1,167 @@+import React, {+ type Ref,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';++import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import debounce from 'lodash/debounce';++import { chartTheme } from './chart-theme';+import { LoadingIndicator } from './LoadingIndicator';++import { PrivacyFilter } from '@desktop-client/components/PrivacyFilter';+import { useMergedRefs } from '@desktop-client/hooks/useMergedRefs';+import { useResizeObserver } from '@desktop-client/hooks/useResizeObserver';++const FONT_SIZE_SCALE_FACTOR = 1.6;+const CONTAINER_MARGIN = 8;++type FormulaResultProps = {+ value: number | string | null;+ animate?: boolean;+ loading?: boolean;+ error?: string | null;+ initialFontSize?: number;+ fontSizeChanged?: (fontSize: number) => void;+ fontSizeMode?: 'dynamic' | 'static';+ staticFontSize?: number;+ customColor?: string | null;+};++export function FormulaResult({+ value,+ animate = false,+ loading = true,+ error = null,+ initialFontSize = 14,+ fontSizeChanged,+ fontSizeMode = 'dynamic',+ staticFontSize = 32,+ customColor = null,+}: FormulaResultProps) {+ const [fontSize, setFontSize] = useState<number>(initialFontSize);+ const refDiv = useRef<HTMLDivElement>(null);+ const previousFontSizeRef = useRef<number>(initialFontSize);++ // Format the display value - just show what we got+ const displayValue = useMemo(() => {+ if (error) {+ return error;+ } else if (value === null || value === undefined) {+ return '';+ } else {+ return String(value);+ }+ }, [error, value]);++ const calculateFontSize = useCallback(() => {+ if (!refDiv.current) return;++ const { clientWidth, clientHeight } = refDiv.current;+ const width = clientWidth; // no margin required on left and right+ const height = clientHeight - CONTAINER_MARGIN * 2; // account for margin top and bottom++ // Get the actual display value length at calculation time+ const valueLength = displayValue.length || 1; // Avoid division by zero++ const calculatedFontSize = Math.min(+ (width * FONT_SIZE_SCALE_FACTOR) / valueLength,+ height, // Ensure the text fits vertically by using the height as the limiting factor+ );++ setFontSize(calculatedFontSize);++ // Only call fontSizeChanged if the font size actually changed+ if (+ fontSizeChanged &&+ Math.abs(calculatedFontSize - previousFontSizeRef.current) > 0.5+ ) {+ previousFontSizeRef.current = calculatedFontSize;+ fontSizeChanged(calculatedFontSize);+ }+ }, [displayValue, fontSizeChanged]);++ // Debounce the calculation to avoid too many recalculations+ const debouncedCalculateFontSize = useRef(+ debounce(() => {+ calculateFontSize();+ }, 100),+ );++ // Update the debounced function when calculateFontSize changes+ useEffect(() => {+ debouncedCalculateFontSize.current.cancel?.();+ debouncedCalculateFontSize.current = debounce(() => {+ calculateFontSize();+ }, 100);++ return () => {+ debouncedCalculateFontSize.current.cancel?.();+ };+ }, [calculateFontSize]);++ const ref = useResizeObserver(() => {+ if (fontSizeMode === 'dynamic') {+ debouncedCalculateFontSize.current();+ }+ });+ const mergedRef = useMergedRefs(ref, refDiv);++ // Recalculate font size when displayValue changes (non-debounced for immediate update)+ // Only for dynamic mode+ useEffect(() => {+ if (fontSizeMode === 'dynamic') {+ calculateFontSize();+ }+ }, [displayValue, calculateFontSize, fontSizeMode]);++ // Use static font size when in static mode+ useEffect(() => {+ if (fontSizeMode === 'static') {+ setFontSize(staticFontSize);+ }+ }, [fontSizeMode, staticFontSize]);++ // Determine color+ const color = customColor+ ? customColor+ : error+ ? chartTheme.colors.red+ : theme.pageText;++ return (+ <>+ {loading && <LoadingIndicator />}+ {!loading && (+ <View+ ref={mergedRef as Ref<HTMLDivElement>}+ role="text"+ aria-label={displayValue}+ style={{+ alignItems: 'center',+ flexGrow: 1,+ flexShrink: 1,+ width: '100%',+ height: '100%',+ maxWidth: '100%',+ fontSize,+ lineHeight: 1,+ margin: `${CONTAINER_MARGIN}px 0`,+ justifyContent: 'center',+ transition: animate ? 'font-size 0.3s ease' : '',+ color,+ }}+ >+ <span aria-hidden="true">+ <PrivacyFilter>{displayValue}</PrivacyFilter>+ </span>+ </View>+ )}+ </>+ );+}diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsxindex 94d943e50b..e7a04faa66 100644--- a/packages/desktop-client/src/components/reports/Overview.tsx+++ b/packages/desktop-client/src/components/reports/Overview.tsx@@ -26,6 +26,7 @@ import { LoadingIndicator } from './LoadingIndicator';import { CalendarCard } from './reports/CalendarCard';import { CashFlowCard } from './reports/CashFlowCard';import { CustomReportListCards } from './reports/CustomReportListCards';+import { FormulaCard } from './reports/FormulaCard';import { MarkdownCard } from './reports/MarkdownCard';import { NetWorthCard } from './reports/NetWorthCard';import { SpendingCard } from './reports/SpendingCard';@@ -40,6 +41,7 @@ import {} from '@desktop-client/components/Page';import { useAccounts } from '@desktop-client/hooks/useAccounts';import { useDashboard } from '@desktop-client/hooks/useDashboard';+import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useReports } from '@desktop-client/hooks/useReports';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';@@ -62,6 +64,8 @@ export function Overview() {const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';+ const formulaMode = useFeatureFlag('formulaMode');+const [isImporting, setIsImporting] = useState(false);const [isEditing, setIsEditing] = useState(false);const [currentBreakpoint, setCurrentBreakpoint] = useState<@@ -432,6 +436,14 @@ export function Overview() {name: 'calendar-card' as const,text: t('Calendar card'),},+ ...(formulaMode+ ? [+ {+ name: 'formula-card' as const,+ text: t('Formula card'),+ },+ ]+ : []),{name: 'custom-report' as const,text: t('New custom report'),@@ -598,6 +610,14 @@ export function Overview() {onMetaChange={newMeta => onMetaChange(item, newMeta)}onRemove={() => onRemoveWidget(item.i)}/>+ ) : item.type === 'formula-card' && formulaMode ? (+ <FormulaCard+ widgetId={item.i}+ isEditing={isEditing}+ meta={item.meta}+ onMetaChange={newMeta => onMetaChange(item, newMeta)}+ onRemove={() => onRemoveWidget(item.i)}+ />) : null}</div>))}diff --git a/packages/desktop-client/src/components/reports/ReportRouter.tsx b/packages/desktop-client/src/components/reports/ReportRouter.tsxindex 2815ce66f6..00ec41b8ae 100644--- a/packages/desktop-client/src/components/reports/ReportRouter.tsx+++ b/packages/desktop-client/src/components/reports/ReportRouter.tsx@@ -5,6 +5,7 @@ import { Overview } from './Overview';import { Calendar } from './reports/Calendar';import { CashFlow } from './reports/CashFlow';import { CustomReport } from './reports/CustomReport';+import { Formula } from './reports/Formula';import { NetWorth } from './reports/NetWorth';import { Spending } from './reports/Spending';import { Summary } from './reports/Summary';@@ -25,6 +26,8 @@ export function ReportRouter() {<Route path="/summary/:id" element={<Summary />} /><Route path="/calendar" element={<Calendar />} /><Route path="/calendar/:id" element={<Calendar />} />+ <Route path="/formula" element={<Formula />} />+ <Route path="/formula/:id" element={<Formula />} /></Routes>);}diff --git a/packages/desktop-client/src/components/reports/reports/Formula.tsx b/packages/desktop-client/src/components/reports/reports/Formula.tsxnew file mode 100644index 0000000000..9ab74ffec0--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/Formula.tsx@@ -0,0 +1,437 @@+import {+ useState,+ useRef,+ useCallback,+ Suspense,+ lazy,+ type ChangeEvent,+} from 'react';+import { Trans, useTranslation } from 'react-i18next';+import { useParams } from 'react-router';++import { Button } from '@actual-app/components/button';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { Input } from '@actual-app/components/input';+import { Select } from '@actual-app/components/select';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { send } from 'loot-core/platform/client/fetch';+import { type FormulaWidget } from 'loot-core/types/models';++import { EditablePageHeaderTitle } from '@desktop-client/components/EditablePageHeaderTitle';+import { QueryManager } from '@desktop-client/components/formula/QueryManager';+import { MobileBackButton } from '@desktop-client/components/mobile/MobileBackButton';+import {+ MobilePageHeader,+ Page,+ PageHeader,+} from '@desktop-client/components/Page';+import { FormulaResult } from '@desktop-client/components/reports/FormulaResult';+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';+import { useFormulaExecution } from '@desktop-client/hooks/useFormulaExecution';+import { useNavigate } from '@desktop-client/hooks/useNavigate';+import { useThemeColors } from '@desktop-client/hooks/useThemeColors';+import { useWidget } from '@desktop-client/hooks/useWidget';+import { addNotification } from '@desktop-client/notifications/notificationsSlice';+import { useDispatch } from '@desktop-client/redux';++const FormulaEditor = lazy(() =>+ import('../../formula/FormulaEditor').then(module => ({+ default: module.FormulaEditor,+ })),+);++export function Formula() {+ const params = useParams();+ const { data: widget, isLoading } = useWidget<FormulaWidget>(+ params.id ?? '',+ 'formula-card',+ );++ if (isLoading) {+ return <LoadingIndicator />;+ }++ return <FormulaInner widget={widget} />;+}++type FormulaInnerProps = {+ widget?: FormulaWidget;+};++function FormulaInner({ widget }: FormulaInnerProps) {+ const { t } = useTranslation();+ const dispatch = useDispatch();+ const navigate = useNavigate();+ const { isNarrowWidth } = useResponsive();+ const themeColors = useThemeColors();++ const queriesRef = useRef(widget?.meta?.queries || {});+ const [queriesVersion, setQueriesVersion] = useState(0);++ const [formula, setFormula] = useState(+ widget?.meta?.formula || '=SUM(1, 2, 3)',+ );++ const [fontSizeMode, setFontSizeMode] = useState<'dynamic' | 'static'>(+ widget?.meta?.fontSizeMode || 'dynamic',+ );+ const [staticFontSize, setStaticFontSize] = useState<number>(+ widget?.meta?.staticFontSize || 32,+ );+ const [colorFormula, setColorFormula] = useState(+ widget?.meta?.colorFormula || '',+ );++ const title = widget?.meta?.name || t('Formula');++ const {+ result,+ isLoading: isExecuting,+ error,+ } = useFormulaExecution(formula, queriesRef.current, queriesVersion);++ // Execute color formula with access to main result via named expression+ const { result: colorResult, error: colorError } = useFormulaExecution(+ colorFormula,+ queriesRef.current,+ queriesVersion,+ {+ RESULT: result ?? 0,+ ...Object.entries(themeColors).reduce(+ (acc, [key, value]) => {+ acc[`theme_${key}`] = value;+ return acc;+ },+ {} as Record<string, string>,+ ),+ },+ );++ const handleQueriesChange = useCallback(+ (newQueries: typeof queriesRef.current) => {+ queriesRef.current = newQueries;+ setQueriesVersion(v => v + 1);+ },+ [],+ );++ const onSaveWidgetName = async (newName: string) => {+ if (!widget) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Cannot save: No widget available.'),+ },+ }),+ );+ return;+ }++ const name = newName || t('Formula');+ await send('dashboard-update-widget', {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ formula,+ queries: queriesRef.current,+ fontSizeMode,+ staticFontSize,+ colorFormula,+ },+ });+ };++ async function onSaveWidget() {+ if (!widget) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Cannot save: No widget available.'),+ },+ }),+ );+ return;+ }++ await send('dashboard-update-widget', {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ formula,+ queries: queriesRef.current,+ fontSizeMode,+ staticFontSize,+ colorFormula,+ },+ });++ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );+ }++ // Determine the custom color from color formula result+ const customColor =+ colorFormula && !colorError && colorResult ? String(colorResult) : null;++ return (+ <Page+ header={+ isNarrowWidth ? (+ <MobilePageHeader+ title={title}+ leftContent={+ <MobileBackButton onPress={() => navigate('/reports')} />+ }+ />+ ) : (+ <PageHeader+ title={+ widget ? (+ <EditablePageHeaderTitle+ title={title}+ onSave={onSaveWidgetName}+ />+ ) : (+ title+ )+ }+ />+ )+ }+ padding={0}+ >+ {widget && (+ <View+ style={{+ padding: 20,+ display: 'flex',+ justifyContent: 'flex-end',+ flexDirection: 'row',+ background: theme.pageBackground,+ }}+ >+ <Button+ variant="primary"+ onPress={onSaveWidget}+ style={{ width: 100 }}+ >+ <Trans>Save widget</Trans>+ </Button>+ </View>+ )}+ <View+ style={{+ width: '100%',+ height: '100%',+ background: theme.pageBackground,+ display: 'flex',+ flexDirection: 'row',+ }}+ >+ <View+ style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ }}+ >+ <View+ style={{+ padding: 20,+ }}+ >+ <div+ style={{+ fontSize: 14,+ color: theme.pageTextSubdued,+ marginBottom: 8,+ }}+ >+ <Trans>Result:</Trans>+ </div>+ <View+ style={{+ height: 120,+ width: '100%',+ }}+ >+ <FormulaResult+ value={result}+ error={error}+ loading={isExecuting}+ fontSizeMode={fontSizeMode}+ staticFontSize={staticFontSize}+ customColor={customColor}+ />+ </View>+ </View>++ <View+ style={{+ flex: 1,+ minHeight: 300,+ margin: 20,+ overflow: 'hidden',+ }}+ >+ <div+ style={{+ fontSize: 13,+ color: theme.pageTextSubdued,+ marginBottom: 5,+ }}+ >+ <Trans>Formula:</Trans>+ </div>+ <Suspense fallback={<div style={{ padding: 10 }}>Loading...</div>}>+ <FormulaEditor+ value={formula}+ onChange={setFormula}+ mode="query"+ queries={queriesRef.current}+ singleLine={false}+ showLineNumbers={true}+ />+ </Suspense>+ </View>++ <View+ style={{+ padding: '0 20px 20px 20px',+ display: 'flex',+ flexDirection: 'row',+ gap: 20,+ alignItems: 'flex-end',+ }}+ >+ <View>+ <div+ style={{+ fontSize: 13,+ color: theme.pageTextSubdued,+ marginBottom: 5,+ }}+ >+ <Trans>Font size:</Trans>+ </div>+ <Select+ value={fontSizeMode}+ onChange={(value: 'dynamic' | 'static') =>+ setFontSizeMode(value)+ }+ options={[+ ['dynamic', t('Dynamic')],+ ['static', t('Static')],+ ]}+ />+ </View>++ {fontSizeMode === 'static' && (+ <View>+ <div+ style={{+ fontSize: 13,+ color: theme.pageTextSubdued,+ marginBottom: 5,+ }}+ >+ <Trans>Font size (px):</Trans>+ </div>+ <Input+ type="number"+ value={String(staticFontSize)}+ onChange={(e: ChangeEvent<HTMLInputElement>) =>+ setStaticFontSize(Number(e.target.value))+ }+ min="8"+ max="200"+ />+ </View>+ )}+ </View>++ <View+ style={{+ padding: 20,+ marginBottom: 20,+ }}+ >+ <div+ style={{+ fontSize: 13,+ color: theme.pageTextSubdued,+ marginBottom: 5,+ }}+ >+ <Trans>Conditional color (optional):</Trans>+ </div>+ <View+ style={{+ border: `1px solid ${theme.formInputBorder}`,+ borderRadius: 4,+ overflow: 'hidden',+ backgroundColor: theme.tableBackground,+ }}+ >+ <Suspense fallback={<div style={{ height: 32 }} />}>+ <FormulaEditor+ value={colorFormula}+ variables={{+ RESULT: result ?? 0,+ ...Object.entries(themeColors).reduce(+ (acc, [key, value]) => {+ acc[`theme_${key}`] = value;+ return acc;+ },+ {} as Record<string, string>,+ ),+ }}+ onChange={setColorFormula}+ mode="query"+ queries={queriesRef.current}+ singleLine={true}+ showLineNumbers={false}+ />+ </Suspense>+ </View>+ <div+ style={{+ fontSize: 11,+ color: theme.pageTextSubdued,+ marginTop: 5,+ }}+ >+ <Trans>+ Formula that returns a color (e.g., “red”,+ “#ff0000”). Leave blank for default. Use RESULT+ variable to access the main formula result.+ </Trans>+ </div>+ </View>+ </View>++ <View+ style={{+ overflowY: 'auto',+ }}+ >+ <QueryManager+ queries={queriesRef.current}+ onQueriesChange={handleQueriesChange}+ />+ </View>+ </View>+ </Page>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsxnew file mode 100644index 0000000000..a0d74c3f08--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx@@ -0,0 +1,138 @@+import React, { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { View } from '@actual-app/components/view';++import { type FormulaWidget } from 'loot-core/types/models';++import { FormulaResult } from '@desktop-client/components/reports/FormulaResult';+import { ReportCard } from '@desktop-client/components/reports/ReportCard';+import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';+import { useFormulaExecution } from '@desktop-client/hooks/useFormulaExecution';+import { useThemeColors } from '@desktop-client/hooks/useThemeColors';++type FormulaCardProps = {+ widgetId: string;+ isEditing?: boolean;+ meta?: FormulaWidget['meta'];+ onMetaChange: (newMeta: FormulaWidget['meta']) => void;+ onRemove: () => void;+};++export function FormulaCard({+ widgetId,+ isEditing,+ meta = {},+ onMetaChange,+ onRemove,+}: FormulaCardProps) {+ const { t } = useTranslation();+ const [nameMenuOpen, setNameMenuOpen] = useState(false);+ const themeColors = useThemeColors();++ const formula = meta?.formula || '=SUM(1, 2, 3)';+ const fontSize = meta?.fontSize;+ const fontSizeMode = meta?.fontSizeMode || 'dynamic';+ const staticFontSize = meta?.staticFontSize || 32;+ const colorFormula = meta?.colorFormula || '';++ const { result, isLoading, error } = useFormulaExecution(+ formula,+ meta?.queries || {},+ meta?.queriesVersion,+ );++ // Execute color formula with access to main result via named expression+ const { result: colorResult, error: colorError } = useFormulaExecution(+ colorFormula,+ meta?.queries || {},+ meta?.queriesVersion,+ {+ RESULT: result ?? 0,+ ...Object.entries(themeColors).reduce(+ (acc, [key, value]) => {+ acc[`theme.${key}`] = value;+ return acc;+ },+ {} as Record<string, string>,+ ),+ },+ );++ // Determine the custom color from color formula result+ const customColor =+ colorFormula && !colorError && colorResult ? String(colorResult) : null;++ return (+ <ReportCard+ isEditing={isEditing}+ disableClick={nameMenuOpen}+ to={`/reports/formula/${widgetId}`}+ menuItems={[+ {+ name: 'rename',+ text: t('Rename'),+ },+ {+ name: 'remove',+ text: t('Remove'),+ },+ ]}+ onMenuSelect={item => {+ switch (item) {+ case 'rename':+ setNameMenuOpen(true);+ break;+ case 'remove':+ onRemove();+ break;+ default:+ console.warn(`Unrecognized menu selection: ${item}`);+ break;+ }+ }}+ >+ <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>+ <View+ style={{+ justifyContent: 'center',+ alignItems: 'center',+ flexGrow: 1,+ flexShrink: 1,+ }}+ >+ <FormulaResult+ value={result}+ error={error}+ loading={isLoading}+ initialFontSize={fontSize}+ fontSizeChanged={newSize => {+ onMetaChange({+ ...meta,+ fontSize: newSize,+ });+ }}+ fontSizeMode={fontSizeMode}+ staticFontSize={staticFontSize}+ customColor={customColor}+ animate={isEditing ?? false}+ />+ </View>+ </View>+ </ReportCard>+ );+}diff --git a/packages/desktop-client/src/components/rules/ActionExpression.tsx b/packages/desktop-client/src/components/rules/ActionExpression.tsxindex dad5218bf2..188275a381 100644--- a/packages/desktop-client/src/components/rules/ActionExpression.tsx+++ b/packages/desktop-client/src/components/rules/ActionExpression.tsx@@ -76,7 +76,12 @@ function SetActionExpression({<Text>{friendlyOp(op)}</Text>{' '}<Text style={valueStyle}>{mapField(field, options)}</Text>{' '}<Text>{t('to ')}</Text>- {options?.template ? (+ {options?.formula ? (+ <>+ <Text>{t('formula ')}</Text>+ <Text style={valueStyle}>{options.formula}</Text>+ </>+ ) : options?.template ? (<><Text>{t('template ')}</Text><Text style={valueStyle}>{options.template}</Text>diff --git a/packages/desktop-client/src/components/rules/FormulaActionEditor.tsx b/packages/desktop-client/src/components/rules/FormulaActionEditor.tsxnew file mode 100644index 0000000000..b118244acb--- /dev/null+++ b/packages/desktop-client/src/components/rules/FormulaActionEditor.tsx@@ -0,0 +1,54 @@+import React, { Suspense, lazy } from 'react';++import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++const FormulaEditor = lazy(() =>+ import('@desktop-client/components/formula/FormulaEditor').then(module => ({+ default: module.FormulaEditor,+ })),+);++type FormulaActionEditorProps = {+ value: string;+ onChange: (value: string) => void;+ disabled?: boolean;+};++export function FormulaActionEditor({+ value,+ onChange,+ disabled = false,+}: FormulaActionEditorProps) {+ // Enforce single-line: replace newlines with spaces+ const handleChange = (newValue: string) => {+ const singleLineValue = newValue.replace(/[\r\n]+/g, ' ');+ onChange(singleLineValue);+ };++ return (+ <View+ style={{+ flex: 1,+ border: `1px solid ${theme.formInputBorder}`,+ borderRadius: 4,+ overflow: 'hidden',+ backgroundColor: disabled+ ? theme.formInputBackgroundSelection+ : theme.tableBackground,+ opacity: disabled ? 0.6 : 1,+ }}+ >+ <Suspense fallback={<div style={{ height: 32 }} />}>+ <FormulaEditor+ value={value}+ onChange={handleChange}+ mode="transaction"+ disabled={disabled}+ singleLine={true}+ showLineNumbers={false}+ />+ </Suspense>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsxindex 17f073631b..f38b7f2503 100644--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx@@ -17,7 +17,6 @@ import {SvgSubtract,} from '@actual-app/components/icons/v0';import {- SvgAlignLeft,SvgCode,SvgInformationOutline,} from '@actual-app/components/icons/v1';@@ -54,6 +53,8 @@ import {type RuleActionEntity,} from 'loot-core/types/models';+import { FormulaActionEditor } from './FormulaActionEditor';+import { StatusBadge } from '@desktop-client/components/schedules/StatusBadge';import { SimpleTransactionsTable } from '@desktop-client/components/transactions/SimpleTransactionsTable';import { BetweenAmountInput } from '@desktop-client/components/util/AmountInput';@@ -70,6 +71,7 @@ import {useSelected,SelectedProvider,} from '@desktop-client/hooks/useSelected';+import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { getPayees } from '@desktop-client/payees/payeesSlice';import { aqlQuery } from '@desktop-client/queries/aqlQuery';import { useDispatch } from '@desktop-client/redux';@@ -466,7 +468,11 @@ type ActionEditorProps = {inputKey?: string;};editorStyle: CSSProperties;- onChange: (name: string, value: unknown) => void;+ onChange: (+ name: string,+ value: unknown,+ extraOptions?: Record<string, unknown>,+ ) => void;onDelete: () => void;onAdd: () => void;};@@ -490,14 +496,20 @@ function ActionEditor({} = action;const templated = options?.template !== undefined;+ const hasFormula = options?.formula !== undefined;// Even if the feature flag is disabled, we still want to be able to turn off templatingconst actionTemplating = useFeatureFlag('actionTemplating');+ const formulaMode = useFeatureFlag('formulaMode');const isTemplatingEnabled = actionTemplating || templated;+ const isFormulaEnabled = formulaMode || hasFormula;const fields = (options?.splitIndex ? getSplitActionFields() : getActionFields()- ).filter(([s]) => actionTemplating || !s.includes('_name') || field === s);+ ).filter(+ ([s]) =>+ actionTemplating || formulaMode || !s.includes('_name') || field === s,+ );return (<Editor style={editorStyle} error={error}>@@ -517,41 +529,96 @@ function ActionEditor({/><View style={{ flex: 1 }}>- {/* @ts-expect-error fix this */}- <GenericInput- key={inputKey}- field={field}- type={templated ? 'string' : type}- op={op}- value={options?.template ?? value}- onChange={v => onChange('value', v)}- numberFormatType="currency"- />+ <View style={{ flex: 1 }}>+ {hasFormula ? (+ <FormulaActionEditor+ value={options?.formula || ''}+ onChange={v => onChange('formula', v, { formula: true })}+ />+ ) : (+ // @ts-expect-error fix this+ <GenericInput+ key={inputKey}+ field={field}+ type={templated ? 'string' : type}+ op={op}+ value={options?.template ?? value}+ onChange={v => onChange('value', v)}+ numberFormatType="currency"+ inputStyle={{ height: 30 }}+ />+ )}+ </View></View>{/*Due to that these fields have id's as value it is not helpful to have templating here*/}- {isTemplatingEnabled &&+ {isFormulaEnabled &&['payee', 'category', 'account'].indexOf(field) === -1 && (<Buttonvariant="bare"+ isDisabled={templated}style={{padding: 5,+ backgroundColor: hasFormula+ ? theme.buttonPrimaryBackground+ : undefined,+ height: 24,+ width: 24,}}aria-label={- templated ? t('Disable templating') : t('Enable templating')+ hasFormula ? t('Disable formula') : t('Enable formula')+ }+ onPress={() =>+ hasFormula+ ? onChange('formula', undefined)+ : onChange('formula', options.formula || value || '=')}- onPress={() => onChange('template', !templated)}>- {templated ? (+ {hasFormula ? (+ <span+ style={{+ fontSize: 14,+ fontFamily: 'serif',+ textAlign: 'center',+ }}+ >+ ƒ+ </span>+ ) : hasFormula ? (<SvgCodestyle={{ width: 12, height: 12, color: 'inherit' }}/>) : (- <SvgAlignLeft- style={{ width: 12, height: 12, color: 'inherit' }}- />+ <span+ style={{+ fontSize: 14,+ fontFamily: 'serif',+ textAlign: 'center',+ }}+ >+ ƒ+ </span>)}</Button>)}+ {isTemplatingEnabled &&+ ['payee', 'category', 'account'].indexOf(field) === -1 && (+ <Button+ variant="bare"+ isDisabled={hasFormula}+ style={{+ padding: 5,+ backgroundColor: templated+ ? theme.buttonPrimaryBackground+ : undefined,+ }}+ aria-label={+ templated ? t('Disable templating') : t('Enable templating')+ }+ onPress={() => onChange('template', !templated)}+ >+ <SvgCode style={{ width: 12, height: 12, color: 'inherit' }} />+ </Button>+ )}</>) : op === 'set-split-amount' ? (<>@@ -1038,7 +1105,7 @@ export function RuleEditor({setActionSplits(copy);}- function onChangeAction(action, field, value) {+ function onChangeAction(action, field, value, extraOptions?) {setActionSplits(actionSplits.map(({ id, actions }) => ({id,@@ -1054,19 +1121,42 @@ export function RuleEditor({a.options = { ...a.options, template: undefined };if (a.type !== 'string') a.value = null;}+ } else if (field === 'formula') {+ if (value === undefined) {+ // Disable formula mode+ a.options = { ...a.options, formula: undefined };+ if (a.type !== 'string') a.value = null;+ } else {+ // Keep formula mode; allow empty string while editing+ a.options = { ...a.options, formula: String(value) };+ }} else {- a[field] = value;- if (a.options?.template !== undefined) {+ // Handle formula updates+ if (extraOptions?.formula && a.options?.formula !== undefined) {+ // Only update formula, not the value field+ a.options = {+ ...a.options,+ formula: value,+ };+ } else if (a.options?.template !== undefined) {+ // Only update template, not the value fielda.options = {...a.options,template: value,};+ } else {+ // Normal value update+ a[field] = value;}if (field === 'field') {a.type = FIELD_TYPES.get(a.field);a.value = null;- a.options = { ...a.options, template: undefined };+ a.options = {+ ...a.options,+ template: undefined,+ formula: undefined,+ };return newInput(a);} else if (field === 'op') {a.value = null;@@ -1133,8 +1223,18 @@ export function RuleEditor({send('rule-apply-actions', {transactions: selectedTransactions,actions: getUnparsedActions(actionSplits),- }).then(() => {+ }).then(content => {// This makes it refetch the transactions+ content.errors.forEach(error => {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: error,+ },+ }),+ );+ });setActionSplits([...actionSplits]);});}@@ -1331,9 +1431,9 @@ export function RuleEditor({<ActionEditoraction={action}editorStyle={styles.editorPill}- onChange={(name, value) => {- onChangeAction(action, name, value);- }}+ onChange={(name, value, extraOptions) =>+ onChangeAction(action, name, value, extraOptions)+ }onDelete={() => onRemoveAction(action)}onAdd={() =>addActionToSplitAfterIndex(splitIndex, actionIndex)diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsxindex 25d695d7cc..618767f0c5 100644--- a/packages/desktop-client/src/components/settings/Experimental.tsx+++ b/packages/desktop-client/src/components/settings/Experimental.tsx@@ -152,6 +152,12 @@ export function ExperimentalFeatures() {><Trans>Rule action templating</Trans></FeatureToggle>+ <FeatureToggle+ flag="formulaMode"+ feedbackLink="https://github.com/actualbudget/actual/issues/5949"+ >+ <Trans>Excel formula mode (Formula cards & Rule formulas)</Trans>+ </FeatureToggle><FeatureToggleflag="currency"feedbackLink="https://github.com/actualbudget/actual/issues/5191"@@ -161,7 +167,7 @@ export function ExperimentalFeatures() {<GlobalFeatureToggleprefName="plugins"disableToggle={true}- feedbackLink="https://github.com/actualbudget/actual/pull/4049"+ feedbackLink="https://github.com/actualbudget/actual/issues/5950"><Trans>Client-Side plugins (soon)</Trans></GlobalFeatureToggle>diff --git a/packages/desktop-client/src/components/transactions/TransactionList.tsx b/packages/desktop-client/src/components/transactions/TransactionList.tsxindex 67928e73fd..e824f83ba8 100644--- a/packages/desktop-client/src/components/transactions/TransactionList.tsx+++ b/packages/desktop-client/src/components/transactions/TransactionList.tsx@@ -32,6 +32,7 @@ import { type TableHandleRef } from '@desktop-client/components/table';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';import { pushModal } from '@desktop-client/modals/modalsSlice';+import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';// When data changes, there are two ways to update the UI:@@ -249,6 +250,20 @@ export function TransactionList({updatedFieldName: string | null = null,) => {const afterRules = await send('rules-run', { transaction });++ // Show formula errors if any+ if (afterRules._ruleErrors && afterRules._ruleErrors.length > 0) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: `Formula errors in rules:\n${afterRules._ruleErrors.join('\n')}`,+ sticky: true,+ },+ }),+ );+ }+const diff = getChangedValues(transaction, afterRules);const newTransaction: TransactionEntity = { ...transaction };@@ -282,7 +297,7 @@ export function TransactionList({}return newTransaction;},- [],+ [dispatch],);const onManagePayees = useCallback(diff --git a/packages/desktop-client/src/components/util/GenericInput.jsx b/packages/desktop-client/src/components/util/GenericInput.jsxindex b1f971c581..cf8e13719e 100644--- a/packages/desktop-client/src/components/util/GenericInput.jsx+++ b/packages/desktop-client/src/components/util/GenericInput.jsx@@ -37,6 +37,7 @@ export function GenericInput({onChange,op = undefined,options = undefined,+ inputStyle = undefined,}) {const dispatch = useDispatch();const { isNarrowWidth } = useResponsive();@@ -70,6 +71,7 @@ export function GenericInput({value={value}onUpdate={v => onChange(v)}sign={options?.inflow || options?.outflow ? '+' : undefined}+ inputStyle={inputStyle}/>);case 'percentage':@@ -78,6 +80,7 @@ export function GenericInput({inputRef={ref}value={value}onUpdatePercent={onChange}+ inputStyle={inputStyle}/>);default:@@ -87,6 +90,7 @@ export function GenericInput({value={value || ''}placeholder={t('nothing')}onChangeValue={onChange}+ style={inputStyle}/>);}@@ -305,6 +309,7 @@ export function GenericInput({value={value || ''}placeholder={t('nothing')}onChangeValue={onChange}+ style={inputStyle}/>);}diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.tsindex a7872b7dd2..e8d4af29b0 100644--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts@@ -6,6 +6,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {goalTemplatesEnabled: false,goalTemplatesUIEnabled: false,actionTemplating: false,+ formulaMode: false,currency: false,plugins: false,};diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsnew file mode 100644index 0000000000..179c86092f--- /dev/null+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -0,0 +1,283 @@+import { useState, useEffect } from 'react';++import { send } from 'loot-core/platform/client/fetch';+import * as monthUtils from 'loot-core/shared/months';+import { q } from 'loot-core/shared/query';+import { integerToAmount } from 'loot-core/shared/util';+import {+ type RuleConditionEntity,+ type TimeFrame,+} from 'loot-core/types/models';++import { useLocale } from './useLocale';++import { getLiveRange } from '@desktop-client/components/reports/getLiveRange';++type QueryConfig = {+ conditions?: RuleConditionEntity[];+ conditionsOp?: 'and' | 'or';+ timeFrame?: TimeFrame;+};++type QueriesMap = Record<string, QueryConfig>;++function escapeRegExp(s: string) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++export function useFormulaExecution(+ formula: string,+ queries: QueriesMap,+ queriesVersion?: number,+ namedExpressions?: Record<string, number | string>,+) {+ const locale = useLocale();+ const [result, setResult] = useState<number | string | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ async function executeFormula() {+ const { HyperFormula } = await import('hyperformula');+ let hfInstance: ReturnType<typeof HyperFormula.buildEmpty> | null = null;++ if (!formula || !formula.startsWith('=')) {+ setResult(null);+ setError('Formula must start with =');+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ // Extract QUERY() function calls+ const queryMatches = Array.from(+ formula.matchAll(/QUERY\s*\(\s*["']([^"']+)["']\s*\)/gi),+ );++ // Fetch data for each query+ const queryData: Record<string, number> = {};++ for (const match of queryMatches) {+ const queryName = match[1];+ const queryConfig = queries[queryName];++ if (!queryConfig) {+ console.warn(`Query “${queryName}” not found in queries config`);+ queryData[queryName] = 0;+ continue;+ }++ // Fetch the actual transaction data based on the query config+ // For now, we'll use a simplified approach+ // In a real implementation, this would call a backend API+ const data = await fetchQueryData(queryConfig);+ queryData[queryName] = integerToAmount(data, 2);+ }++ // Replace QUERY() calls with actual values in the formula+ let processedFormula = formula;+ for (const [queryName, value] of Object.entries(queryData)) {+ const regex = new RegExp(+ `QUERY\\s*\\(\\s*["']${escapeRegExp(queryName)}["']\\s*\\)`,+ 'gi',+ );+ processedFormula = processedFormula.replace(regex, String(value));+ }++ // Create HyperFormula instance+ hfInstance = HyperFormula.buildEmpty({+ licenseKey: 'gpl-v3',+ localeLang: typeof locale === 'string' ? locale : 'en-US',+ });++ // Add a sheet and set the formula in cell A1+ const sheetName = hfInstance.addSheet('Sheet1');+ const sheetId = hfInstance.getSheetId(sheetName);++ if (sheetId === undefined) {+ throw new Error('Failed to create sheet');+ }++ // Add named expressions if provided+ if (namedExpressions) {+ for (const [name, value] of Object.entries(namedExpressions)) {+ hfInstance.addNamedExpression(+ name,+ typeof value === 'number' ? value : String(value),+ );+ }+ }++ // Set the formula+ hfInstance.setCellContents({ sheet: sheetId, col: 0, row: 0 }, [+ [processedFormula],+ ]);++ // Get the result+ const cellValue = hfInstance.getCellValue({+ sheet: sheetId,+ col: 0,+ row: 0,+ });++ if (cancelled) return;++ // Check if there's an error+ if (cellValue && typeof cellValue === 'object' && 'type' in cellValue) {+ setError(`Formula error: ${cellValue.type}`);+ setResult(null);+ } else {+ setResult(cellValue as number | string);+ setError(null);+ }+ } catch (err) {+ if (cancelled) return;+ console.error('Formula execution error:', err);+ setError(err instanceof Error ? err.message : 'Unknown error');+ setResult(null);+ } finally {+ if (!cancelled) {+ setIsLoading(false);+ }++ try {+ hfInstance?.destroy();+ } catch (err) {+ console.error('Error destroying HyperFormula instance:', err);+ setError('Error destroying HyperFormula instance');+ setResult(null);+ }+ }+ }++ executeFormula();++ return () => {+ cancelled = true;+ };+ }, [formula, queriesVersion, locale, queries, namedExpressions]);++ return { result, isLoading, error };+}++// Helper function to convert timeFrame mode to condition string for getLiveRange+function timeFrameModeToCondition(mode: TimeFrame['mode']): string | null {+ // Map timeFrame modes to ReportOptions condition strings+ switch (mode) {+ case 'full':+ return 'All time';+ case 'lastYear':+ return 'Last year';+ case 'yearToDate':+ return 'Year to date';+ case 'priorYearToDate':+ return 'Prior year to date';+ case 'sliding-window':+ // sliding-window requires actual start/end dates, not a condition+ return null;+ case 'static':+ // static mode uses manually set start/end dates, not a condition+ return null;+ default:+ return null;+ }+}++// Helper function to fetch query data+async function fetchQueryData(config: QueryConfig): Promise<number> {+ try {+ const conditions = config.conditions || [];+ const conditionsOp = config.conditionsOp || 'and';+ const timeFrame = config.timeFrame;++ // Convert conditions to query filters+ const { filters: queryFilters } = await send(+ 'make-filters-from-conditions',+ {+ conditions,+ },+ );++ const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';++ // Start building the query+ let transQuery = q('transactions');++ // Add date range filter if provided+ if (timeFrame && timeFrame.mode) {+ let startDate: string | undefined;+ let endDate: string | undefined;++ if (+ (timeFrame.mode === 'sliding-window' || timeFrame.mode === 'static') &&+ timeFrame.start &&+ timeFrame.end+ ) {+ // For sliding-window and static modes, use the actual start/end dates from timeFrame+ // Convert month format (YYYY-MM) to full date format (YYYY-MM-DD) if needed+ startDate =+ timeFrame.start.includes('-') &&+ timeFrame.start.split('-').length === 2+ ? timeFrame.start + '-01'+ : timeFrame.start;+ endDate =+ timeFrame.end.includes('-') && timeFrame.end.split('-').length === 2+ ? monthUtils.getMonthEnd(timeFrame.end + '-01')+ : timeFrame.end;+ } else {+ // For other modes, use getLiveRange with the appropriate condition+ const condition = timeFrameModeToCondition(timeFrame.mode);+ if (condition) {+ // Get earliest and latest transactions for getLiveRange+ const earliestTransaction = await send('get-earliest-transaction');+ const latestTransaction = await send('get-latest-transaction');++ const earliestDate = earliestTransaction+ ? earliestTransaction.date+ : monthUtils.currentDay();+ const latestDate = latestTransaction+ ? latestTransaction.date+ : monthUtils.currentDay();++ const [calculatedStart, calculatedEnd] = getLiveRange(+ condition,+ earliestDate,+ latestDate,+ true, // includeCurrentInterval+ );++ startDate = calculatedStart;+ endDate = calculatedEnd;+ } else {+ // No valid condition found, skip date filtering entirely+ // Continue without adding date filter+ }+ }++ // Apply the date filter only if we have valid dates+ if (startDate && endDate) {+ transQuery = transQuery.filter({+ $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }],+ });+ }+ }++ // Add user-defined filters+ if (queryFilters.length > 0) {+ transQuery = transQuery.filter({ [conditionsOpKey]: queryFilters });+ }++ // Calculate sum+ transQuery = transQuery.calculate({ $sum: '$amount' });++ const { data } = await send('query', transQuery.serialize());+ return data || 0;+ } catch (err) {+ console.error('Error fetching query data:', err);+ return 0;+ }+}diff --git a/packages/desktop-client/src/hooks/useThemeColors.ts b/packages/desktop-client/src/hooks/useThemeColors.tsnew file mode 100644index 0000000000..1931a7ed60--- /dev/null+++ b/packages/desktop-client/src/hooks/useThemeColors.ts@@ -0,0 +1,33 @@+import { useMemo } from 'react';++import { theme } from '@actual-app/components/theme';++const VAR_STRING_REGEX = /^var\((--.*)\)$/;++function getPropertyValueFromVarString(varString: string): string {+ if (VAR_STRING_REGEX.test(varString)) {+ const match = varString.match(VAR_STRING_REGEX);+ if (match) {+ return window+ .getComputedStyle(document.documentElement)+ .getPropertyValue(match[1])+ .trim();+ }+ }+ return varString;+}++export function useThemeColors(): Record<string, string> {+ return useMemo(() => {+ const colors: Record<string, string> = {};++ for (const [key, value] of Object.entries(theme)) {+ const computedValue = getPropertyValueFromVarString(value);+ if (computedValue) {+ colors[key] = computedValue;+ }+ }++ return colors;+ }, []);+}diff --git a/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts b/packages/desktop-client/src/hooks/useTransactionFormulaExecution.tsnew file mode 100644index 0000000000..fd58c1d08b--- /dev/null+++ b/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts@@ -0,0 +1,124 @@+import { useState, useEffect } from 'react';++import { useLocale } from './useLocale';++type TransactionContext = {+ amount?: number;+ date?: string;+ notes?: string;+ imported_payee?: string;+ account?: string;+ category?: string;+ payee?: string;+ cleared?: boolean;+ reconciled?: boolean;+ [key: string]: string | number | boolean | undefined;+};++export function useTransactionFormulaExecution(+ formula: string,+ transaction: TransactionContext,+) {+ const locale = useLocale();+ const [result, setResult] = useState<number | string | boolean | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ async function executeFormula() {+ const { HyperFormula } = await import('hyperformula');+ let hfInstance: ReturnType<typeof HyperFormula.buildEmpty> | null = null;++ if (!formula || !formula.startsWith('=')) {+ setResult(null);+ setError('Formula must start with =');+ return;+ }++ try {+ // Create HyperFormula instance+ hfInstance = HyperFormula.buildEmpty({+ licenseKey: 'gpl-v3',+ localeLang: typeof locale === 'string' ? locale : 'en-US',+ });++ // Add a sheet+ const sheetName = hfInstance.addSheet('Sheet1');+ const sheetId = hfInstance.getSheetId(sheetName);++ if (sheetId === undefined) {+ throw new Error('Failed to create sheet');+ }++ // Add named ranges for each transaction field+ let row = 1;+ const fieldValues: Record<string, number | string | boolean> = {+ today: new Date().toISOString().split('T')[0],+ ...transaction,+ };++ for (const [key, value] of Object.entries(fieldValues)) {+ if (value !== undefined && value !== null) {+ // Set the value in a cell+ hfInstance.setCellContents({ sheet: sheetId, col: 0, row }, [+ [value],+ ]);++ // Create a named range for this field+ hfInstance.addNamedExpression(+ key,+ `=Sheet1!$A$${row + 1}`, // +1 because HyperFormula uses 0-based rows but formulas use 1-based+ );++ row++;+ }+ }++ // Set the formula in row 0+ hfInstance.setCellContents({ sheet: sheetId, col: 0, row: 0 }, [+ [formula],+ ]);++ // Get the result+ const cellValue = hfInstance.getCellValue({+ sheet: sheetId,+ col: 0,+ row: 0,+ });++ if (cancelled) return;++ // Check if there's an error+ if (cellValue && typeof cellValue === 'object' && 'type' in cellValue) {+ setError(`Formula error: ${cellValue.type}`);+ setResult(null);+ } else {+ setResult(cellValue as number | string | boolean);+ setError(null);+ }+ } catch (err) {+ if (cancelled) return;+ console.error('Formula execution error:', err);+ setError(err instanceof Error ? err.message : 'Unknown error');+ setResult(null);+ } finally {+ try {+ hfInstance?.destroy();+ } catch (err) {+ console.error('Error destroying HyperFormula instance:', err);+ setError('Error destroying HyperFormula instance');+ setResult(null);+ }+ }+ }++ executeFormula();++ return () => {+ cancelled = true;+ };+ }, [formula, transaction, locale]);++ return { result, error };+}diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.tsindex 4e3e68ef35..f03c630c1a 100644--- a/packages/loot-core/src/server/db/index.ts+++ b/packages/loot-core/src/server/db/index.ts@@ -543,6 +543,10 @@ export async function getAccount(id: DbAccount['id']) {return first<DbAccount>(`SELECT * FROM accounts WHERE id = ?`, [id]);}+export async function getCategory(id: DbCategory['id']) {+ return first<DbCategory>(`SELECT * FROM categories WHERE id = ?`, [id]);+}+export async function insertPayee(payee: WithRequired<Partial<DbPayee>, 'name'>,) {diff --git a/packages/loot-core/src/server/rules/action.ts b/packages/loot-core/src/server/rules/action.tsindex 194b6b1497..5a78c53368 100644--- a/packages/loot-core/src/server/rules/action.ts+++ b/packages/loot-core/src/server/rules/action.ts@@ -1,10 +1,12 @@// @ts-strict-ignoreimport * as dateFns from 'date-fns';import * as Handlebars from 'handlebars';+import { HyperFormula } from 'hyperformula';import { logger } from '../../platform/server/log';import { parseDate, format, currentDay } from '../../shared/months';import { FIELD_TYPES } from '../../shared/rules';+import { TransactionForRules } from '../transactions/transaction-rules';import { assert } from './rule-utils';@@ -75,7 +77,60 @@ export class Action {exec(object) {switch (this.op) {case 'set':- if (this.handlebarsTemplate) {+ if (this.options?.formula) {+ try {+ if (!object._ruleErrors) {+ object._ruleErrors = [];+ }++ const result = this.executeFormulaSync(+ this.options.formula,+ object,+ );++ switch (this.type) {+ case 'number': {+ const numValue =+ typeof result === 'number'+ ? result+ : parseFloat(String(result));++ if (isNaN(numValue)) {+ const error = `Formula for “${this.field}” must produce a numeric value. Got: ${JSON.stringify(result)}`;+ object._ruleErrors.push(error);+ } else {+ object[this.field] = numValue;+ }+ break;+ }+ case 'date': {+ const parsed = parseDate(String(result));+ if (parsed && dateFns.isValid(parsed)) {+ object[this.field] = format(parsed, 'yyyy-MM-dd');+ } else {+ const error = `Formula for “${this.field}” must produce a valid date. Got: ${JSON.stringify(result)}`;+ object._ruleErrors.push(error);+ }+ break;+ }+ case 'boolean': {+ object[this.field] =+ typeof result === 'boolean'+ ? result+ : String(result).toLowerCase() === 'true';+ break;+ }+ case 'string': {+ object[this.field] = String(result);+ break;+ }+ }+ } catch (err) {+ const error = `Error executing formula for “${this.field}”: ${err instanceof Error ? err.message : String(err)}`;+ object._ruleErrors.push(error);+ break;+ }+ } else if (this.handlebarsTemplate) {object[this.field] = this.handlebarsTemplate({...object,today: currentDay(),@@ -144,6 +199,143 @@ export class Action {}}+ extractVariablesFromAST(ast: unknown): Set<string> {+ const variables = new Set<string>();++ const walk = (node: unknown): void => {+ if (!node || typeof node !== 'object') {+ return;+ }++ const typedNode = node as {+ type?: string;+ value?: string;+ args?: unknown[];+ };++ if (+ typedNode.type === 'CELL_REFERENCE' &&+ typeof typedNode.value === 'string'+ ) {+ variables.add(typedNode.value);+ }++ if (Array.isArray(typedNode.args)) {+ for (const arg of typedNode.args) {+ walk(arg);+ }+ }++ for (const value of Object.values(typedNode)) {+ if (typeof value === 'object' && value !== null) {+ walk(value);+ }+ }+ };++ walk(ast);+ return variables;+ }++ executeFormulaSync(+ formula: string,+ transaction: Partial<TransactionForRules>,+ ): unknown {+ let hfInstance: ReturnType<typeof HyperFormula.buildEmpty> | null = null;++ if (!formula || !formula.startsWith('=')) {+ throw new Error('Formula must start with =');+ }++ try {+ hfInstance = HyperFormula.buildEmpty({+ licenseKey: 'gpl-v3',+ });++ const sheetName = hfInstance.addSheet('Sheet1');+ const sheetId = hfInstance.getSheetId(sheetName);++ if (sheetId === undefined) {+ throw new Error('Failed to create sheet');+ }++ const fieldValues: Partial<TransactionForRules> & {+ today: string;+ account_name: string;+ category_name: string;+ } = {+ ...transaction,+ today: currentDay(),+ account_name: transaction._account_name || '',+ category_name: transaction._category_name || '',+ };++ let row = 1;+ for (const key of Object.keys(fieldValues)) {+ hfInstance.setCellContents({ sheet: sheetId, col: 0, row }, [['']]);+ hfInstance.addNamedExpression(key, `=Sheet1!$A$${row + 1}`);++ row++;+ }++ hfInstance.setCellContents({ sheet: sheetId, col: 0, row: 0 }, [+ [formula],+ ]);++ const parserCache = (+ hfInstance as unknown as {+ _parser: { cache: { cache: Map<string, { ast: unknown }> } };+ }+ )._parser.cache.cache;+ const cacheEntry = parserCache.get(formula);+ const usedVariables = new Set<string>();++ if (cacheEntry && cacheEntry.ast) {+ const extractedVars = this.extractVariablesFromAST(cacheEntry.ast);+ for (const variable of extractedVars) {+ usedVariables.add(variable);+ }+ }++ row = 1;+ for (const [, value] of Object.entries(fieldValues)) {+ let cellValue: string | number | boolean;+ if (+ value === undefined ||+ value === null ||+ typeof value === 'object'+ ) {+ cellValue = '';+ } else {+ cellValue = value;+ }++ hfInstance.setCellContents({ sheet: sheetId, col: 0, row }, [+ [cellValue],+ ]);+ row++;+ }++ const cellAddress = { sheet: sheetId, col: 0, row: 0 };+ const cellValue = hfInstance.getCellValue(cellAddress);++ if (cellValue && typeof cellValue === 'object' && 'type' in cellValue) {+ throw new Error(`Formula error: ${cellValue.message}`);+ }++ return cellValue;+ } catch (err) {+ logger.error('Formula execution error:', err);+ throw err;+ } finally {+ try {+ hfInstance?.destroy();+ } catch (err) {+ logger.error('Error destroying HyperFormula instance:', err);+ }+ }+ }+serialize() {return {op: this.op,diff --git a/packages/loot-core/src/server/rules/app.ts b/packages/loot-core/src/server/rules/app.tsindex c99dc44358..a3fc38245b 100644--- a/packages/loot-core/src/server/rules/app.ts+++ b/packages/loot-core/src/server/rules/app.ts@@ -153,7 +153,11 @@ async function applyRuleActions({}: {transactions: TransactionEntity[];actions: Array<Action | RuleActionEntity>;-}): Promise<null | { added: TransactionEntity[]; updated: unknown[] }> {+}): Promise<null | {+ added: TransactionEntity[];+ updated: unknown[];+ errors: string[];+}> {return rules.applyActions(transactions, actions);}diff --git a/packages/loot-core/src/server/rules/formula-action.test.ts b/packages/loot-core/src/server/rules/formula-action.test.tsnew file mode 100644index 0000000000..90114c223c--- /dev/null+++ b/packages/loot-core/src/server/rules/formula-action.test.ts@@ -0,0 +1,194 @@+import { describe, it, expect } from 'vitest';++import { TransactionForRules } from '../transactions/transaction-rules';++import { Action } from './action';++describe('Formula-based rule actions', () => {+ describe('executeFormulaSync', () => {+ it('should execute a simple math formula', () => {+ const action = new Action('set', 'amount', null, {+ formula: '=100 + 200',+ });++ const transaction: Partial<TransactionForRules> = { amount: 500 };+ const result = action.executeFormulaSync('=100 + 200', transaction);++ expect(result).toBe(300);+ });++ it('should use transaction field variables', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=amount / 100',+ });++ const transaction = { amount: 5000 };+ const result = action.executeFormulaSync('=amount / 100', transaction);++ expect(result).toBe(50);+ });++ it('should support IF function with transaction fields', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=IF(amount > 0, "Income", "Expense")',+ });++ const transaction1 = { amount: 1000 };+ const result1 = action.executeFormulaSync(+ '=IF(amount > 0, "Income", "Expense")',+ transaction1,+ );+ expect(result1).toBe('Income');++ const transaction2 = { amount: -1000 };+ const result2 = action.executeFormulaSync(+ '=IF(amount > 0, "Income", "Expense")',+ transaction2,+ );+ expect(result2).toBe('Expense');+ });++ it('should support UPPER string function', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=UPPER(notes)',+ });++ const transaction = { notes: 'hello world' };+ const result = action.executeFormulaSync('=UPPER(notes)', transaction);++ expect(result).toBe('HELLO WORLD');+ });++ it('should support CONCATENATE function', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=CONCATENATE(imported_payee, " - ", notes)',+ });++ const transaction = {+ imported_payee: 'Store Name',+ notes: 'Purchase',+ };+ const result = action.executeFormulaSync(+ '=CONCATENATE(imported_payee, " - ", notes)',+ transaction,+ );++ expect(result).toBe('Store Name - Purchase');+ });++ it('should support LEFT function', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=LEFT(imported_payee, 5)',+ });++ const transaction = { imported_payee: 'Store Name' };+ const result = action.executeFormulaSync(+ '=LEFT(imported_payee, 5)',+ transaction,+ );++ expect(result).toBe('Store');+ });++ it('should provide today variable', () => {+ const action = new Action('set', 'date', null, {+ formula: '=today',+ });++ const transaction = { date: '2024-01-01' };+ const result = action.executeFormulaSync('=today', transaction);++ // Should be a date string in YYYY-MM-DD format+ expect(typeof result).toBe('string');+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });++ it('should throw error for invalid formula', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=INVALID_FUNCTION()',+ });++ const transaction = { amount: 100 };++ expect(() => {+ action.executeFormulaSync('=INVALID_FUNCTION()', transaction);+ }).toThrow();+ });++ it('should throw error for formula without = prefix', () => {+ const action = new Action('set', 'notes', null, {+ formula: 'amount + 100',+ });++ const transaction = { amount: 100 };++ expect(() => {+ action.executeFormulaSync('amount + 100', transaction);+ }).toThrow('Formula must start with =');+ });+ });++ describe('Action.exec with formula option', () => {+ it('should execute formula and convert to number type', () => {+ const action = new Action('set', 'amount', null, {+ formula: '=500 + 250',+ });++ const transaction = { amount: 100 };+ action.exec(transaction);++ expect(transaction.amount).toBe(750);+ });++ it('should execute formula and convert to string type', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=UPPER("hello")',+ });++ const transaction = { notes: 'original' };+ action.exec(transaction);++ expect(transaction.notes).toBe('HELLO');+ });++ it('should handle formula errors gracefully', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=1/0', // Division by zero+ });++ const transaction = { notes: 'original' };++ // Should not throw, but keep original value on error+ expect(() => {+ action.exec(transaction);+ }).not.toThrow();++ // Original value should be preserved+ expect(transaction.notes).toBe('original');+ });++ it('should validate numeric field output', () => {+ const action = new Action('set', 'amount', null, {+ formula: '=UPPER("test")', // Returns string for numeric field+ });++ const transaction = { amount: 100 };+ action.exec(transaction);++ // Should keep original value when formula produces non-numeric result+ expect(transaction.amount).toBe(100);+ });++ it('should convert non-string results to string for text fields', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=500 + 250', // Returns number+ });++ const transaction = { notes: 'original' };+ action.exec(transaction);++ // Should convert number to string+ expect(transaction.notes).toBe('750');+ });+ });+});diff --git a/packages/loot-core/src/server/transactions/index.ts b/packages/loot-core/src/server/transactions/index.tsindex 7ef4ab5d11..e96ff895e1 100644--- a/packages/loot-core/src/server/transactions/index.ts+++ b/packages/loot-core/src/server/transactions/index.ts@@ -189,5 +189,8 @@ export async function batchUpdateTransactions({added: resultAdded,updated: runTransfers ? transfersUpdated : resultUpdated,deleted: allDeleted,+ errors: ((added || []) as Partial<TransactionEntity>[])+ .concat(updated || [])+ .flatMap(t => t._ruleErrors || []),};}diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.tsindex 7ad5098f14..ad25032e16 100644--- a/packages/loot-core/src/server/transactions/transaction-rules.ts+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts@@ -19,7 +19,13 @@ import {} from '../../types/models';import { aqlQuery, schemaConfig } from '../aql';import * as db from '../db';-import { getPayee, getPayeeByName, insertPayee, getAccount } from '../db';+import {+ getPayee,+ getPayeeByName,+ insertPayee,+ getAccount,+ getCategory,+} from '../db';import { getMappings } from '../db/mappings';import { RuleError } from '../errors';import { requiredFields, toDateRepr } from '../models';@@ -927,6 +933,8 @@ export type TransactionForRules = TransactionEntity & {payee_name?: string;_account?: db.DbAccount;balance?: number;+ _category_name?: string;+ _account_name?: string;};export async function prepareTransactionForRules(@@ -946,8 +954,17 @@ export async function prepareTransactionForRules(if (trans.account) {if (accounts !== null && accounts.has(trans.account)) {r._account = accounts.get(trans.account);+ r._account_name = r._account?.name || '';} else {r._account = await getAccount(trans.account);+ r._account_name = r._account?.name || '';+ }+ }++ if (trans.category) {+ const category = await getCategory(trans.category);+ if (category) {+ r._category_name = category.name;}const dateBoundary = trans.date ?? currentDay();diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 511029b544..d8b0b98414 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -74,7 +74,8 @@ type SpecializedWidget =| SpendingWidget| MarkdownWidget| SummaryWidget- | CalendarWidget;+ | CalendarWidget+ | FormulaWidget;export type Widget = SpecializedWidget | CustomReportWidget;export type NewWidget = Omit<Widget, 'id' | 'tombstone'>;@@ -133,3 +134,24 @@ export type CalendarWidget = AbstractWidget<timeFrame?: TimeFrame;} | null>;++export type FormulaWidget = AbstractWidget<+ 'formula-card',+ {+ name?: string;+ formula?: string;+ fontSize?: number;+ fontSizeMode?: 'dynamic' | 'static';+ staticFontSize?: number;+ colorFormula?: string;+ queriesVersion?: number;+ queries?: Record<+ string,+ {+ conditions?: RuleConditionEntity[];+ conditionsOp?: 'and' | 'or';+ timeFrame?: TimeFrame;+ }+ >;+ } | null+>;diff --git a/packages/loot-core/src/types/models/rule.ts b/packages/loot-core/src/types/models/rule.tsindex ad2f8d2d14..e59f9eee99 100644--- a/packages/loot-core/src/types/models/rule.ts+++ b/packages/loot-core/src/types/models/rule.ts@@ -150,6 +150,7 @@ export interface SetRuleActionEntity {value: unknown;options?: {template?: string;+ formula?: string;splitIndex?: number;};type?: string;diff --git a/packages/loot-core/src/types/models/transaction.ts b/packages/loot-core/src/types/models/transaction.tsindex 3bb0c3e2df..0b5d9e6fcf 100644--- a/packages/loot-core/src/types/models/transaction.ts+++ b/packages/loot-core/src/types/models/transaction.ts@@ -35,4 +35,5 @@ export interface TransactionEntity {difference: number;} | null;raw_synced_data?: string | undefined;+ _ruleErrors?: string[];}diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.tsindex 4d08e5582c..e90da97ea5 100644--- a/packages/loot-core/src/types/prefs.ts+++ b/packages/loot-core/src/types/prefs.ts@@ -2,6 +2,7 @@ export type FeatureFlag =| 'goalTemplatesEnabled'| 'goalTemplatesUIEnabled'| 'actionTemplating'+ | 'formulaMode'| 'currency'| 'plugins';diff --git a/upcoming-release-notes/5939.md b/upcoming-release-notes/5939.mdnew file mode 100644index 0000000000..4e0646b711--- /dev/null+++ b/upcoming-release-notes/5939.md@@ -0,0 +1,7 @@+---+category: Features+authors: [lelemm]+---++Add a Formula card and Formula for rules for enhanced report generation and rules.+diff --git a/yarn.lock b/yarn.lockindex b5c9d8881d..dfb38e30db 100644--- a/yarn.lock+++ b/yarn.lock@@ -129,9 +129,15 @@ __metadata:resolution: "@actual-app/web@workspace:packages/desktop-client"dependencies:"@actual-app/components": "workspace:*"+ "@codemirror/autocomplete": "npm:^6.19.0"+ "@codemirror/lang-javascript": "npm:^6.2.4"+ "@codemirror/language": "npm:^6.11.3"+ "@codemirror/state": "npm:^6.5.2"+ "@codemirror/view": "npm:^6.38.6""@emotion/css": "npm:^11.13.5""@fontsource/redacted-script": "npm:^5.2.8""@juggle/resize-observer": "npm:^3.4.0"+ "@lezer/highlight": "npm:^1.2.1""@playwright/test": "npm:1.56.0""@rollup/plugin-inject": "npm:^5.0.5""@swc/core": "npm:^1.13.5"@@ -146,6 +152,7 @@ __metadata:"@types/react-dom": "npm:^19.2.1""@types/react-grid-layout": "npm:^1""@types/react-modal": "npm:^3.16.3"+ "@uiw/react-codemirror": "npm:^4.25.2""@use-gesture/react": "npm:^10.3.1""@vitejs/plugin-basic-ssl": "npm:^2.1.0""@vitejs/plugin-react": "npm:^5.0.4"@@ -155,6 +162,7 @@ __metadata:cross-env: "npm:^10.1.0"date-fns: "npm:^4.1.0"downshift: "npm:9.0.10"+ hyperformula: "npm:^3.1.0"i18next: "npm:^25.5.3"i18next-parser: "npm:^9.3.0"i18next-resources-to-backend: "npm:^1.2.1"@@ -1400,7 +1408,7 @@ __metadata:languageName: nodelinkType: hard-"@babel/runtime@npm:^7.11.2, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.18.3, @babel/runtime@npm:^7.23.2, @babel/runtime@npm:^7.24.5, @babel/runtime@npm:^7.25.0, @babel/runtime@npm:^7.26.10, @babel/runtime@npm:^7.27.6, @babel/runtime@npm:^7.9.2":+"@babel/runtime@npm:^7.11.2, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.18.3, @babel/runtime@npm:^7.18.6, @babel/runtime@npm:^7.23.2, @babel/runtime@npm:^7.24.5, @babel/runtime@npm:^7.25.0, @babel/runtime@npm:^7.26.10, @babel/runtime@npm:^7.27.6, @babel/runtime@npm:^7.9.2":version: 7.28.4resolution: "@babel/runtime@npm:7.28.4"checksum: 10/6c9a70452322ea80b3c9b2a412bcf60771819213a67576c8cec41e88a95bb7bf01fc983754cda35dc19603eef52df22203ccbf7777b9d6316932f9fb77c25163@@ -1450,6 +1458,114 @@ __metadata:languageName: nodelinkType: hard+"@codemirror/autocomplete@npm:^6.0.0, @codemirror/autocomplete@npm:^6.19.0":+ version: 6.19.0+ resolution: "@codemirror/autocomplete@npm:6.19.0"+ dependencies:+ "@codemirror/language": "npm:^6.0.0"+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.17.0"+ "@lezer/common": "npm:^1.0.0"+ checksum: 10/791def23bcf5cc278e821a15462f73233b74c2c40db52a95c41f8b3bff693276e2ebaf0fdac892a44d86a6697a55c352efe3a608ccdf25ee7bbf7ac6cce179ea+ languageName: node+ linkType: hard++"@codemirror/commands@npm:^6.0.0, @codemirror/commands@npm:^6.1.0":+ version: 6.9.0+ resolution: "@codemirror/commands@npm:6.9.0"+ dependencies:+ "@codemirror/language": "npm:^6.0.0"+ "@codemirror/state": "npm:^6.4.0"+ "@codemirror/view": "npm:^6.27.0"+ "@lezer/common": "npm:^1.1.0"+ checksum: 10/4664b37ed233c5c2bfa045a9084fb120f694964e326bd9db0e9762f6a077e8f228d04025d2e9aff03c3537d7aa4bb82cdda3c8ef65fa896a3525fe5fd5860edd+ languageName: node+ linkType: hard++"@codemirror/lang-javascript@npm:^6.2.4":+ version: 6.2.4+ resolution: "@codemirror/lang-javascript@npm:6.2.4"+ dependencies:+ "@codemirror/autocomplete": "npm:^6.0.0"+ "@codemirror/language": "npm:^6.6.0"+ "@codemirror/lint": "npm:^6.0.0"+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.17.0"+ "@lezer/common": "npm:^1.0.0"+ "@lezer/javascript": "npm:^1.0.0"+ checksum: 10/7d0b7fdacc90f89d1a5f2b9c575c61b6ee7813005cde32c1f35aedb0da71ad298998e116126ba19ca0bb02cdb14064945c31e24c57ef60bcbd5c19dae955ccb6+ languageName: node+ linkType: hard++"@codemirror/language@npm:^6.0.0, @codemirror/language@npm:^6.11.3, @codemirror/language@npm:^6.6.0":+ version: 6.11.3+ resolution: "@codemirror/language@npm:6.11.3"+ dependencies:+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.23.0"+ "@lezer/common": "npm:^1.1.0"+ "@lezer/highlight": "npm:^1.0.0"+ "@lezer/lr": "npm:^1.0.0"+ style-mod: "npm:^4.0.0"+ checksum: 10/8538a2835c1de6ca2d520ff66449185f2ea3a93e7d69382d9db3b4db6460f4c46b44f19724458c50230abfa87cf2c225834d39c3fe3119c48370db6b3de0b772+ languageName: node+ linkType: hard++"@codemirror/lint@npm:^6.0.0":+ version: 6.9.0+ resolution: "@codemirror/lint@npm:6.9.0"+ dependencies:+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.35.0"+ crelt: "npm:^1.0.5"+ checksum: 10/887cab59b56a2a16cd60df03f271664b8f4e46881f34f8291dcd4d2a7ff31107d0f3e0cb0d3c6dab6563271288316b0ed957a215e4377afa3bfc9768649899da+ languageName: node+ linkType: hard++"@codemirror/search@npm:^6.0.0":+ version: 6.5.11+ resolution: "@codemirror/search@npm:6.5.11"+ dependencies:+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.0.0"+ crelt: "npm:^1.0.5"+ checksum: 10/d057f37cb369460b25625d7eb72f40636bf78ecd140608da53010cf3660f982a9e613826e38d85d87c9c2ff11e45c9482429987bfd4f29cbbd192f1ee3fd2695+ languageName: node+ linkType: hard++"@codemirror/state@npm:^6.0.0, @codemirror/state@npm:^6.1.1, @codemirror/state@npm:^6.4.0, @codemirror/state@npm:^6.5.0, @codemirror/state@npm:^6.5.2":+ version: 6.5.2+ resolution: "@codemirror/state@npm:6.5.2"+ dependencies:+ "@marijn/find-cluster-break": "npm:^1.0.0"+ checksum: 10/5ccd3acb0c0a5b88e83fb91be39099fceb9f44a5047cc41a75d53f160e736851f65c8de40950b90c6519e6d2828e12f468db0af658dde30e938896f1c39eec91+ languageName: node+ linkType: hard++"@codemirror/theme-one-dark@npm:^6.0.0":+ version: 6.1.3+ resolution: "@codemirror/theme-one-dark@npm:6.1.3"+ dependencies:+ "@codemirror/language": "npm:^6.0.0"+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.0.0"+ "@lezer/highlight": "npm:^1.0.0"+ checksum: 10/f62c2393aad715626a1fe3a766c87f3f835bfdae7c56f738601cdee56f02417d56b203cfbbaffbd601887865ce0b1a662c1473296a107616adb311d63fc81146+ languageName: node+ linkType: hard++"@codemirror/view@npm:^6.0.0, @codemirror/view@npm:^6.17.0, @codemirror/view@npm:^6.23.0, @codemirror/view@npm:^6.27.0, @codemirror/view@npm:^6.35.0, @codemirror/view@npm:^6.38.6":+ version: 6.38.6+ resolution: "@codemirror/view@npm:6.38.6"+ dependencies:+ "@codemirror/state": "npm:^6.5.0"+ crelt: "npm:^1.0.6"+ style-mod: "npm:^4.1.0"+ w3c-keyname: "npm:^2.2.4"+ checksum: 10/5a047337a98de111817ce8c8d39e6429c90ca0b0a4d2678d6e161e9e5961b1d476a891f447ab7a05cac395d4a93530e7c68bedd93191285265f0742a308ad00b+ languageName: node+ linkType: hard+"@colors/colors@npm:1.6.0, @colors/colors@npm:^1.6.0":version: 1.6.0resolution: "@colors/colors@npm:1.6.0"@@ -2416,6 +2532,42 @@ __metadata:languageName: nodelinkType: hard+"@lezer/common@npm:^1.0.0, @lezer/common@npm:^1.1.0, @lezer/common@npm:^1.2.0":+ version: 1.2.3+ resolution: "@lezer/common@npm:1.2.3"+ checksum: 10/dad24e353e4e67d88b203191361ca1dff26c01c2b7b4ae829b668a1d115929334d077217367683e39180c0556510ed2066ea8ddba2b079be7c08a7152208cc87+ languageName: node+ linkType: hard++"@lezer/highlight@npm:^1.0.0, @lezer/highlight@npm:^1.1.3, @lezer/highlight@npm:^1.2.1":+ version: 1.2.1+ resolution: "@lezer/highlight@npm:1.2.1"+ dependencies:+ "@lezer/common": "npm:^1.0.0"+ checksum: 10/fec3082419ee87fb265039b680fbac6796f862d8e3042dcb860e8c5a34291503a74927302b568ff1a626f0d2b5cf8dae02a51cfd200084eb329e5fd1236c3163+ languageName: node+ linkType: hard++"@lezer/javascript@npm:^1.0.0":+ version: 1.5.4+ resolution: "@lezer/javascript@npm:1.5.4"+ dependencies:+ "@lezer/common": "npm:^1.2.0"+ "@lezer/highlight": "npm:^1.1.3"+ "@lezer/lr": "npm:^1.3.0"+ checksum: 10/e3cf0b57b131e163aa6ce8a66469e5c39da4db6e83cbefa3bc864575f999229ad02d5d69af56d8aa05b21db22de284c13cfbc9b8b5bb7a628b5599330cf1ef39+ languageName: node+ linkType: hard++"@lezer/lr@npm:^1.0.0, @lezer/lr@npm:^1.3.0":+ version: 1.4.2+ resolution: "@lezer/lr@npm:1.4.2"+ dependencies:+ "@lezer/common": "npm:^1.0.0"+ checksum: 10/f7b505906c8d8df14c07866553cf3dae1e065b1da8b28fbb4193fd67ab8d187eb45f92759e29a2cfe4283296f0aa864b38a0a91708ecfc3e24b8f662d626e0c6+ languageName: node+ linkType: hard+"@malept/cross-spawn-promise@npm:^2.0.0":version: 2.0.0resolution: "@malept/cross-spawn-promise@npm:2.0.0"@@ -2437,6 +2589,13 @@ __metadata:languageName: nodelinkType: hard+"@marijn/find-cluster-break@npm:^1.0.0":+ version: 1.0.2+ resolution: "@marijn/find-cluster-break@npm:1.0.2"+ checksum: 10/92fe7ba43ce3d3314f593e4c2fd822d7089649baff47a474fe04b83e3119931d7cf58388747d429ff65fa2db14f5ca57e787268c482e868fc67759511f61f09b+ languageName: node+ linkType: hard+"@napi-rs/wasm-runtime@npm:^0.2.11":version: 0.2.12resolution: "@napi-rs/wasm-runtime@npm:0.2.12"@@ -6584,6 +6743,51 @@ __metadata:languageName: nodelinkType: hard+"@uiw/codemirror-extensions-basic-setup@npm:4.25.2":+ version: 4.25.2+ resolution: "@uiw/codemirror-extensions-basic-setup@npm:4.25.2"+ dependencies:+ "@codemirror/autocomplete": "npm:^6.0.0"+ "@codemirror/commands": "npm:^6.0.0"+ "@codemirror/language": "npm:^6.0.0"+ "@codemirror/lint": "npm:^6.0.0"+ "@codemirror/search": "npm:^6.0.0"+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.0.0"+ peerDependencies:+ "@codemirror/autocomplete": ">=6.0.0"+ "@codemirror/commands": ">=6.0.0"+ "@codemirror/language": ">=6.0.0"+ "@codemirror/lint": ">=6.0.0"+ "@codemirror/search": ">=6.0.0"+ "@codemirror/state": ">=6.0.0"+ "@codemirror/view": ">=6.0.0"+ checksum: 10/b743d7ad667c9bbd563e9be643e75636da1b69e62892edfb0b521296993139b8a384432318da9df17d268918f6f80e9defb98d9b94f57e771cbea28fb39fe8a7+ languageName: node+ linkType: hard++"@uiw/react-codemirror@npm:^4.25.2":+ version: 4.25.2+ resolution: "@uiw/react-codemirror@npm:4.25.2"+ dependencies:+ "@babel/runtime": "npm:^7.18.6"+ "@codemirror/commands": "npm:^6.1.0"+ "@codemirror/state": "npm:^6.1.1"+ "@codemirror/theme-one-dark": "npm:^6.0.0"+ "@uiw/codemirror-extensions-basic-setup": "npm:4.25.2"+ codemirror: "npm:^6.0.0"+ peerDependencies:+ "@babel/runtime": ">=7.11.0"+ "@codemirror/state": ">=6.0.0"+ "@codemirror/theme-one-dark": ">=6.0.0"+ "@codemirror/view": ">=6.0.0"+ codemirror: ">=6.0.0"+ react: ">=17.0.0"+ react-dom: ">=17.0.0"+ checksum: 10/bf5387a440b366f3e72060e9f4df85b95d8a232754290a093ec4c56bd3979cb16eecb4c2da1f5e0612b7bcb62da96b7808ae7de76e19a9d8b94c281a91a08d51+ languageName: node+ linkType: hard+"@ungap/structured-clone@npm:^1.0.0":version: 1.3.0resolution: "@ungap/structured-clone@npm:1.3.0"@@ -8245,6 +8449,15 @@ __metadata:languageName: nodelinkType: hard+"chevrotain@npm:^6.5.0":+ version: 6.5.0+ resolution: "chevrotain@npm:6.5.0"+ dependencies:+ regexp-to-ast: "npm:0.4.0"+ checksum: 10/e98f7cc12bea6732246a0a2c25028bc076d5ed7dda470403599c595e5eece5d60fe808a7cdb187b938ad3364c308c03f9eb603e2743871c861db497186776efb+ languageName: node+ linkType: hard+"chokidar@npm:^3.5.2, chokidar@npm:^3.5.3":version: 3.6.0resolution: "chokidar@npm:3.6.0"@@ -8456,6 +8669,21 @@ __metadata:languageName: nodelinkType: hard+"codemirror@npm:^6.0.0":+ version: 6.0.2+ resolution: "codemirror@npm:6.0.2"+ dependencies:+ "@codemirror/autocomplete": "npm:^6.0.0"+ "@codemirror/commands": "npm:^6.0.0"+ "@codemirror/language": "npm:^6.0.0"+ "@codemirror/lint": "npm:^6.0.0"+ "@codemirror/search": "npm:^6.0.0"+ "@codemirror/state": "npm:^6.0.0"+ "@codemirror/view": "npm:^6.0.0"+ checksum: 10/bd73c9ebbd8cb709a697fa4e2484c188c44aafce4b4d2a342807a5648c6be5bd5876f0caac47db0c1181f1ec8d86e38bd2b6efe51b971bf240fd3382bef0b371+ languageName: node+ linkType: hard+"color-convert@npm:^1.9.0":version: 1.9.3resolution: "color-convert@npm:1.9.3"@@ -8863,6 +9091,13 @@ __metadata:languageName: nodelinkType: hard+"crelt@npm:^1.0.5, crelt@npm:^1.0.6":+ version: 1.0.6+ resolution: "crelt@npm:1.0.6"+ checksum: 10/5ed326ca6bd243b1dba6b943f665b21c2c04be03271824bc48f20dba324b0f8233e221f8c67312526d24af2b1243c023dc05a41bd8bd05d1a479fd2c72fb39c3+ languageName: node+ linkType: hard+"cross-env@npm:^10.1.0":version: 10.1.0resolution: "cross-env@npm:10.1.0"@@ -12062,6 +12297,16 @@ __metadata:languageName: nodelinkType: hard+"hyperformula@npm:^3.1.0":+ version: 3.1.0+ resolution: "hyperformula@npm:3.1.0"+ dependencies:+ chevrotain: "npm:^6.5.0"+ tiny-emitter: "npm:^2.1.0"+ checksum: 10/d0c03ae7398a2fe3717b07194402df327b7ae9d9c09678f422a68dce2a4a90e29c4d3e3ba3776928a7ab64cbcfee3e13e8c6972b6cfe7b0a68189e39a4e3071a+ languageName: node+ linkType: hard+"i18next-parser@npm:^9.3.0":version: 9.3.0resolution: "i18next-parser@npm:9.3.0"@@ -16855,6 +17100,13 @@ __metadata:languageName: nodelinkType: hard+"regexp-to-ast@npm:0.4.0":+ version: 0.4.0+ resolution: "regexp-to-ast@npm:0.4.0"+ checksum: 10/381f57fa4d056056a50d7bc1365ece93434e1eea87bd3d60144ef6fd85bc4875410757908000c06fbe99ef9554c930c9890e695292b8e49756dfc0762890e777+ languageName: node+ linkType: hard+"regexp.prototype.flags@npm:^1.5.1, regexp.prototype.flags@npm:^1.5.3, regexp.prototype.flags@npm:^1.5.4":version: 1.5.4resolution: "regexp.prototype.flags@npm:1.5.4"@@ -18374,6 +18626,13 @@ __metadata:languageName: nodelinkType: hard+"style-mod@npm:^4.0.0, style-mod@npm:^4.1.0":+ version: 4.1.2+ resolution: "style-mod@npm:4.1.2"+ checksum: 10/9da37909d6dbc3c043ab6d18da5d997073a4698c91e86058293252493eb18aca4e44e3fb18f32fcee26dcee8785f393c6c95f3c96cc722a0dd6b8de622b5b293+ languageName: node+ linkType: hard+"style-to-js@npm:^1.0.0":version: 1.1.17resolution: "style-to-js@npm:1.1.17"@@ -18676,6 +18935,13 @@ __metadata:languageName: nodelinkType: hard+"tiny-emitter@npm:^2.1.0":+ version: 2.1.0+ resolution: "tiny-emitter@npm:2.1.0"+ checksum: 10/75633f4de4f47f43af56aff6162f25b87be7efc6f669fda256658f3c3f4a216f23dc0d13200c6fafaaf1b0c7142f0201352fb06aec0b77f68aea96be898f4516+ languageName: node+ linkType: hard+"tiny-invariant@npm:^1.3.3":version: 1.3.3resolution: "tiny-invariant@npm:1.3.3"@@ -20015,6 +20281,13 @@ __metadata:languageName: nodelinkType: hard+"w3c-keyname@npm:^2.2.4":+ version: 2.2.8+ resolution: "w3c-keyname@npm:2.2.8"+ checksum: 10/95bafa4c04fa2f685a86ca1000069c1ec43ace1f8776c10f226a73296caeddd83f893db885c2c220ebeb6c52d424e3b54d7c0c1e963bbf204038ff1a944fbb07+ languageName: node+ linkType: hard+"w3c-xmlserializer@npm:^5.0.0":version: 5.0.0resolution: "w3c-xmlserializer@npm:5.0.0"