A local-first personal finance app
[AI] Fix CLI accounts list: compute balances, hide closed, sort by group (#7378)
Matiss Janis Aboltinsedc024220307
diff --git a/packages/api/package.json b/packages/api/package.jsonindex 3847057046..14496c7cf7 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -11,6 +11,7 @@"types": "@types/index.d.ts","exports": {".": {+ "types": "./@types/index.d.ts","development": "./index.ts","default": "./dist/index.js"}diff --git a/packages/cli/README.md b/packages/cli/README.mdindex a368d9a8f6..20d81b7c56 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -98,8 +98,8 @@ Run `actual <command> --help` for subcommands and options.### Examples```bash-# List all accounts (as a table)-actual accounts list --format table+# List all accounts (as a table; excludes closed by default)+actual accounts list [--include-closed] --format table# Find an entity ID by nameactual server get-id --type accounts --name "Checking"@@ -122,13 +122,35 @@ actual query run --table transactions \### Amount Convention-All monetary amounts are **integer cents**:+All monetary amounts are **integer cents** when passed as input (flags, JSON):| CLI Value | Dollar Amount || --------- | ------------- || `5000` | $50.00 || `-12350` | -$123.50 |+**Output formatting:** Table (`--format table`) and CSV (`--format csv`) output automatically converts cent values to decimal (e.g. `1665.00` instead of `166500`). JSON output always returns raw cents for programmatic use.++### Tips & Common Pitfalls++- **Split transactions:** When summing or counting transactions, filter `"is_parent": false` to avoid double-counting. A split parent holds the total amount, and its children hold the individual parts — including both would count the total twice.++- **Avoid rapid sequential requests:** Each CLI invocation opens a new server connection. Running queries in a tight loop (e.g. one per month) may trigger rate limiting or authentication failures. Instead, fetch all data in a single query with a date range filter and process locally:++ ```bash+ # Good: single query for the full year+ actual query run --table transactions \+ --filter '{"$and":[{"date":{"$gte":"2025-01-01"}},{"date":{"$lte":"2025-12-31"}}]}' \+ --limit 5000++ # Bad: one query per month in a loop (may fail with auth errors)+ for month in 01 02 03 ...; do actual query run ...; done+ ```++- **Uncategorized transactions:** `category.name` is `null` for transactions without a category. Account for this when filtering or grouping by category.++- **No date sub-fields in AQL:** `date.month`, `date.year`, etc. are not supported as query fields. To group by month, fetch raw transactions with a date range filter and aggregate locally in a script.+## Running Locally (Development)If you're working on the CLI within the monorepo:diff --git a/packages/cli/src/commands/accounts.test.ts b/packages/cli/src/commands/accounts.test.tsindex 10a622d20d..ab722c7f72 100644--- a/packages/cli/src/commands/accounts.test.ts+++ b/packages/cli/src/commands/accounts.test.ts@@ -62,14 +62,28 @@ describe('accounts commands', () => {});describe('list', () => {- it('calls api.getAccounts and prints result', async () => {- const accounts = [{ id: '1', name: 'Checking' }];+ it('calls api.getAccounts and prints result with computed balance', async () => {+ const accounts = [+ { id: '1', name: 'Checking', offbudget: false, closed: false },+ ];vi.mocked(api.getAccounts).mockResolvedValue(accounts);await run(['accounts', 'list']);expect(api.getAccounts).toHaveBeenCalled();- expect(printOutput).toHaveBeenCalledWith(accounts, undefined);+ expect(api.getAccountBalance).toHaveBeenCalledWith('1');+ expect(printOutput).toHaveBeenCalledWith(+ [+ {+ id: '1',+ name: 'Checking',+ offbudget: false,+ closed: false,+ balance: 10000,+ },+ ],+ undefined,+ );});it('passes format option to printOutput', async () => {@@ -79,6 +93,59 @@ describe('accounts commands', () => {expect(printOutput).toHaveBeenCalledWith([], 'csv');});++ it('filters out closed accounts by default', async () => {+ vi.mocked(api.getAccounts).mockResolvedValue([+ { id: '1', name: 'Open', offbudget: false, closed: false },+ { id: '2', name: 'Closed', offbudget: false, closed: true },+ ]);++ await run(['accounts', 'list']);++ expect(printOutput).toHaveBeenCalledWith(+ [+ {+ id: '1',+ name: 'Open',+ offbudget: false,+ closed: false,+ balance: 10000,+ },+ ],+ undefined,+ );+ });++ it('includes closed accounts when --include-closed is passed', async () => {+ vi.mocked(api.getAccounts).mockResolvedValue([+ { id: '1', name: 'Open', offbudget: false, closed: false },+ { id: '2', name: 'Closed', offbudget: false, closed: true },+ ]);++ await run(['accounts', 'list', '--include-closed']);++ expect(printOutput).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({ id: '2', closed: true }),+ ]),+ undefined,+ );+ });++ it('sorts on-budget accounts before off-budget', async () => {+ vi.mocked(api.getAccounts).mockResolvedValue([+ { id: '1', name: 'OffBudget', offbudget: true, closed: false },+ { id: '2', name: 'OnBudget', offbudget: false, closed: false },+ ]);++ await run(['accounts', 'list']);++ const output = vi.mocked(printOutput).mock.calls[0][0] as Array<{+ id: string;+ }>;+ expect(output[0].id).toBe('2'); // on-budget first+ expect(output[1].id).toBe('1'); // off-budget second+ });});describe('create', () => {diff --git a/packages/cli/src/commands/accounts.ts b/packages/cli/src/commands/accounts.tsindex 4b46d75186..f2a5a170d1 100644--- a/packages/cli/src/commands/accounts.ts+++ b/packages/cli/src/commands/accounts.ts@@ -11,11 +11,28 @@ export function registerAccountsCommand(program: Command) {accounts.command('list').description('List all accounts')- .action(async () => {+ .option('--include-closed', 'Include closed accounts', false)+ .action(async cmdOpts => {const opts = program.opts();await withConnection(opts, async () => {- const result = await api.getAccounts();- printOutput(result, opts.format);+ const allAccounts = await api.getAccounts();+ const accounts = allAccounts.filter(+ a => cmdOpts.includeClosed || !a.closed,+ );+ // Stable sort: on-budget first, off-budget second+ // (preserves API sort_order within each group)+ accounts.sort((a, b) => Number(a.offbudget) - Number(b.offbudget));+ const balances = await Promise.all(+ accounts.map(a => api.getAccountBalance(a.id)),+ );+ const output = accounts.map((a, i) => ({+ id: a.id,+ name: a.name,+ offbudget: a.offbudget,+ closed: a.closed,+ balance: balances[i],+ }));+ printOutput(output, opts.format);});});@@ -24,7 +41,11 @@ export function registerAccountsCommand(program: Command) {.description('Create a new account').requiredOption('--name <name>', 'Account name').option('--offbudget', 'Create as off-budget account', false)- .option('--balance <amount>', 'Initial balance in cents', '0')+ .option(+ '--balance <amount>',+ 'Initial balance in cents (e.g. 50000 = 500.00)',+ '0',+ ).action(async cmdOpts => {const balance = parseIntFlag(cmdOpts.balance, '--balance');const opts = program.opts();diff --git a/packages/cli/src/commands/budgets.ts b/packages/cli/src/commands/budgets.tsindex 6809f30d5f..7f7d5075e0 100644--- a/packages/cli/src/commands/budgets.ts+++ b/packages/cli/src/commands/budgets.ts@@ -82,7 +82,10 @@ export function registerBudgetsCommand(program: Command) {.description('Set budget amount for a category in a month').requiredOption('--month <month>', 'Budget month (YYYY-MM)').requiredOption('--category <id>', 'Category ID')- .requiredOption('--amount <amount>', 'Amount in cents')+ .requiredOption(+ '--amount <amount>',+ 'Amount in cents (e.g. 50000 = 500.00)',+ ).action(async cmdOpts => {const amount = parseIntFlag(cmdOpts.amount, '--amount');const opts = program.opts();@@ -111,7 +114,10 @@ export function registerBudgetsCommand(program: Command) {.command('hold-next-month').description('Hold budget amount for next month').requiredOption('--month <month>', 'Budget month (YYYY-MM)')- .requiredOption('--amount <amount>', 'Amount in cents')+ .requiredOption(+ '--amount <amount>',+ 'Amount in cents (e.g. 50000 = 500.00)',+ ).action(async cmdOpts => {const parsedAmount = parseIntFlag(cmdOpts.amount, '--amount');const opts = program.opts();diff --git a/packages/cli/src/commands/query.test.ts b/packages/cli/src/commands/query.test.tsindex 71e3de03c6..37399e9c7c 100644--- a/packages/cli/src/commands/query.test.ts+++ b/packages/cli/src/commands/query.test.ts@@ -145,6 +145,25 @@ describe('query commands', () => {]);});+ it('outputs unwrapped data array (not the full result envelope)', async () => {+ const mockData = [{ id: '1', amount: -500 }];+ vi.mocked(api.aqlQuery).mockResolvedValueOnce({+ data: mockData,+ dependencies: [],+ });++ await run([+ 'query',+ 'run',+ '--table',+ 'transactions',+ '--select',+ 'id,amount',+ ]);++ expect(printOutput).toHaveBeenCalledWith(mockData, undefined);+ });+it('passes --filter as JSON', async () => {await run(['query',diff --git a/packages/cli/src/commands/query.ts b/packages/cli/src/commands/query.tsindex 45626f5db4..f2fa67b56e 100644--- a/packages/cli/src/commands/query.ts+++ b/packages/cli/src/commands/query.ts@@ -4,11 +4,7 @@ import type { Command } from 'commander';import { withConnection } from '../connection';import { readJsonInput } from '../input';import { printOutput } from '../output';-import { parseIntFlag } from '../utils';--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}+import { isRecord, parseIntFlag } from '../utils';/*** Parse order-by strings like "date:desc,amount:asc,id" into@@ -253,7 +249,17 @@ Available tables: ${AVAILABLE_TABLES}Use "actual query tables" and "actual query fields <table>" for schema info.Common filter operators: $eq, $ne, $lt, $lte, $gt, $gte, $like, $and, $or-See ActualQL docs for full reference: https://actualbudget.org/docs/api/actual-ql/`;+See ActualQL docs for full reference: https://actualbudget.org/docs/api/actual-ql/++Tips:+ - Amounts are stored as integer cents (e.g. 166500 = 1665.00).+ Table and CSV output auto-formats these as decimals; JSON keeps raw cents.+ - Filter "is_parent": false to avoid double-counting split transactions.+ - Fetch all data in a single query with a date range instead of running+ one query per month — rapid sequential requests may cause auth failures.+ - date.month, date.year etc. are not supported as fields in AQL.+ To group by month, fetch raw transactions with a date range filter+ and aggregate locally (e.g. in a script).`;export function registerQueryCommand(program: Command) {const query = program@@ -306,10 +312,14 @@ export function registerQueryCommand(program: Command) {const result = await api.aqlQuery(queryObj);+ if (!isRecord(result) || !('data' in result)) {+ throw new Error('Query result missing data');+ }+if (cmdOpts.count) {printOutput({ count: result.data }, opts.format);} else {- printOutput(result, opts.format);+ printOutput(result.data, opts.format);}});});diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex 1a105b6f0a..ae103d3b91 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -3,6 +3,8 @@ import { join } from 'path';import { cosmiconfig } from 'cosmiconfig';+import { isRecord } from './utils';+export type CliConfig = {serverUrl: string;password?: string;@@ -41,10 +43,6 @@ const configFileKeys: readonly string[] = ['encryptionPassword',];-function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}-function validateConfigFileContent(value: unknown): ConfigFileContent {if (!isRecord(value)) {throw new Error(diff --git a/packages/cli/src/output.test.ts b/packages/cli/src/output.test.tsindex ed0a4e49dd..ac76877d53 100644--- a/packages/cli/src/output.test.ts+++ b/packages/cli/src/output.test.ts@@ -60,6 +60,33 @@ describe('formatOutput', () => {expect(result).toContain('a');expect(result).toContain('b');});++ it('formats amount fields as decimal values', () => {+ const data = [{ name: 'Groceries', amount: -250000 }];+ const result = formatOutput(data, 'table');+ expect(result).toContain('-2500.00');+ expect(result).not.toContain('-250000');+ });++ it('formats balance fields as decimal values', () => {+ const data = [{ id: 'acc1', balance: 166500 }];+ const result = formatOutput(data, 'table');+ expect(result).toContain('1665.00');+ });++ it('formats budgeted and spent fields as decimal values', () => {+ const data = [{ budgeted: 50000, spent: -32150 }];+ const result = formatOutput(data, 'table');+ expect(result).toContain('500.00');+ expect(result).toContain('-321.50');+ });++ it('does not format non-amount numeric fields', () => {+ const data = [{ id: 12345, sort_order: 100 }];+ const result = formatOutput(data, 'table');+ expect(result).toContain('12345');+ expect(result).toContain('100');+ });});describe('csv', () => {@@ -112,6 +139,21 @@ describe('formatOutput', () => {const lines = result.split('\n');expect(lines[0]).toBe('a,b');});++ it('formats amount fields as decimal values', () => {+ const data = [{ name: 'Coffee', amount: -2500 }];+ const result = formatOutput(data, 'csv');+ const lines = result.split('\n');+ expect(lines[0]).toBe('name,amount');+ expect(lines[1]).toBe('Coffee,-25.00');+ });++ it('does not format amount fields in json output', () => {+ const data = [{ amount: 166500 }];+ const result = formatOutput(data, 'json');+ expect(result).toContain('166500');+ expect(result).not.toContain('1665.00');+ });});});diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex 1693885af0..c2b65d9d61 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -2,6 +2,29 @@ import Table from 'cli-table3';export type OutputFormat = 'json' | 'table' | 'csv';+// Fields containing integer-cent values, auto-formatted as decimals in table/csv output.+const AMOUNT_FIELDS = new Set([+ 'amount',+ 'balance',+ 'balance_available',+ 'balance_current',+ 'balance_limit',+ 'budgeted',+ 'spent',+ 'carryover',+]);++function isAmountValue(key: string, value: unknown): value is number {+ return AMOUNT_FIELDS.has(key) && typeof value === 'number';+}++function formatCellValue(key: string, value: unknown): string {+ if (isAmountValue(key, value)) {+ return (value / 100).toFixed(2);+ }+ return String(value ?? '');+}+export function formatOutput(data: unknown,format: OutputFormat = 'json',@@ -23,7 +46,7 @@ function formatTable(data: unknown): string {if (data && typeof data === 'object') {const table = new Table();for (const [key, value] of Object.entries(data)) {- table.push({ [key]: String(value) });+ table.push({ [key]: formatCellValue(key, value) });}return table.toString();}@@ -39,7 +62,7 @@ function formatTable(data: unknown): string {for (const row of data) {const r = row as Record<string, unknown>;- table.push(keys.map(k => String(r[k] ?? '')));+ table.push(keys.map(k => formatCellValue(k, r[k])));}return table.toString();@@ -50,7 +73,9 @@ function formatCsv(data: unknown): string {if (data && typeof data === 'object') {const entries = Object.entries(data);const header = entries.map(([k]) => escapeCsv(k)).join(',');- const values = entries.map(([, v]) => escapeCsv(String(v))).join(',');+ const values = entries+ .map(([k, v]) => escapeCsv(formatCellValue(k, v)))+ .join(',');return header + '\n' + values;}return String(data);@@ -64,7 +89,7 @@ function formatCsv(data: unknown): string {const header = keys.map(k => escapeCsv(k)).join(',');const rows = data.map(row => {const r = row as Record<string, unknown>;- return keys.map(k => escapeCsv(String(r[k] ?? ''))).join(',');+ return keys.map(k => escapeCsv(formatCellValue(k, r[k]))).join(',');});return [header, ...rows].join('\n');diff --git a/packages/cli/src/utils.ts b/packages/cli/src/utils.tsindex 90c305bbb2..57ff07bd85 100644--- a/packages/cli/src/utils.ts+++ b/packages/cli/src/utils.ts@@ -1,3 +1,7 @@+export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}+export function parseBoolFlag(value: string, flagName: string): boolean {if (value !== 'true' && value !== 'false') {throw new Error(diff --git a/packages/docs/docs/api/cli.md b/packages/docs/docs/api/cli.mdindex 5c8e1f07b6..0bb4ed4c0b 100644--- a/packages/docs/docs/api/cli.md+++ b/packages/docs/docs/api/cli.md@@ -89,8 +89,8 @@ actual <command> <subcommand> [options]### Accounts```bash-# List all accounts-actual accounts list+# List all accounts (excludes closed by default)+actual accounts list [--include-closed]# Create an accountactual accounts create --name "Checking" [--offbudget] [--balance 50000]@@ -374,13 +374,15 @@ All monetary amounts are represented as **integer cents**:When providing amounts, always use integer cents. For example, to budget $50, pass `5000`.+**Output formatting:** Table (`--format table`) and CSV (`--format csv`) output automatically converts cent values to decimal (e.g. `1665.00` instead of `166500`). JSON output always returns raw cents for programmatic use.+## Output FormatsThe `--format` flag controls how results are displayed:-- **`json`** (default) — Machine-readable JSON output, ideal for scripting-- **`table`** — Human-readable table format-- **`csv`** — Comma-separated values for spreadsheet import+- **`json`** (default) — Machine-readable JSON output, ideal for scripting. Query results are returned as a bare array of records.+- **`table`** — Human-readable table format. Amount fields are auto-formatted as decimals.+- **`csv`** — Comma-separated values for spreadsheet import. Amount fields are auto-formatted as decimals.Use `--verbose` to enable informational messages on stderr for debugging or visibility into what the CLI is doing.@@ -413,6 +415,13 @@ actual transactions list --account <id> --start 2026-01-01 --end 2026-12-31 --foactual transactions add --account <id> --data '[{"date":"2026-03-14","amount":-2500,"payee_name":"Coffee Shop"}]'```+## Tips & Common Pitfalls++- **Split transactions:** When summing or counting transactions, filter `"is_parent": false` to avoid double-counting. A split parent holds the total amount, and its children hold the individual parts — including both counts the total twice.+- **Avoid rapid sequential requests:** Each CLI invocation opens a new server connection. Running queries in a tight loop (e.g. one per month) may trigger rate limiting or authentication failures. Instead, fetch all data in a single query with a date range filter and process locally.+- **Uncategorized transactions:** `category.name` is `null` for transactions without a category. Account for this when filtering or grouping by category.+- **No date sub-fields in AQL:** `date.month`, `date.year`, etc. are not supported as query fields. To group by month, fetch raw transactions with a date range filter and aggregate locally in a script.+## Self-Signed SSL CertificatesIf your Actual sync server uses a self-signed SSL certificate, the CLI will reject the connection by default. To allow connections with self-signed certificates, set the `NODE_TLS_REJECT_UNAUTHORIZED` environment variable:diff --git a/upcoming-release-notes/7378.md b/upcoming-release-notes/7378.mdnew file mode 100644index 0000000000..6d35e607db--- /dev/null+++ b/upcoming-release-notes/7378.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MatissJanis]+---++cli: account ordering, better agent instructions, fix types