Files
KomediruzeckiandGitHub 08ad641383 feat(forms): housing, portfolio, tags, recurring and onboarding say what is wrong at the field (slice 5 of 6) (#614)
Housing, Portfolio, Tags, the Recurring dialog, the subscription catalog and scan, and the setup
wizard move onto the form kit from #602: a refused entry is said under the field that is wrong, in
the same words in cloud and local-first. Both runtimes run one set of rules from shared/ for a
tag, a housing expense, a holding and a recurring rule, and answer a refusal with 400
{ error, fields }. An edit checks and writes only what it changes, so a row an older version
stored can still be edited.

- A tag name that is blank, over 50 characters, or another tag's in other case is refused at name.
  A colour must be #RRGGBB; a tag created without one takes the palette's next colour, and an edit
  without one keeps it.
- A housing expense is refused at the field: a name up to 100 characters, six types, an amount to
  the cent, a real due month and a day that month has (29 February taken). One posted without a
  due month falls due this month.
- A holding needs a ticker up to 20 characters, stored in capitals, shares and a price above zero
  and below one trillion, and a real date. The edit dialog sends back what is stored, and a buy
  merges only into the open profile's holding.
- A recurring rule needs a description, an amount to the cent, a type, a frequency and a next date.
  Deleting one the profile does not have is a 404. A rule's period is added once, and a second add
  of it is a 409 in both runtimes. Local-first's upcoming list is the Worker's.
- Another profile's tag, category or account is a 400 at the field it names.
- A new tag and a new recurring rule answer 201 in both runtimes, as housing does.
- Deleting a housing expense, holding, tag or recurring rule another tab already deleted says so
  and reloads the list.
- MCP's upsert_tag_rule finds and creates tags by the tag rules.
- The contract suite settles 12 pins (31 to 19).

Slice 5 of 6 in docs/plans/2026-10-07-form-errors.md.
2026-10-10 09:19:28 +02:00

133 lines
4.8 KiB
TypeScript

/**
* Small helpers the scenarios share: dates, money, and reading a list either runtime answers.
* Like the rest of shared/contract, nothing here imports vitest; `expect` is handed in.
*/
import { added, expectOk } from './types';
import type { ContractApi, Expect, Json, Reply } from './types';
/** `YYYY-MM-DD` for a date, in UTC as the Worker reads it. */
export function isoDay(date: Date): string {
return date.toISOString().slice(0, 10);
}
/** The first day of the month `offset` months from this one, as `YYYY-MM-DD`. */
export function monthStart(offset = 0, from = new Date()): string {
const d = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + offset, 1));
return isoDay(d);
}
/** The last day of the month `offset` months from this one, as `YYYY-MM-DD`. */
export function monthEnd(offset = 0, from = new Date()): string {
const d = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + offset + 1, 0));
return isoDay(d);
}
/** A day of the month `offset` months from this one, as `YYYY-MM-DD`. */
export function dayOf(offset: number, day: number, from = new Date()): string {
return `${monthStart(offset, from).slice(0, 8)}${String(day).padStart(2, '0')}`;
}
/**
* This month as `MM`, on the person's calendar: the device's, which local-first reads and the app
* sends the Worker as X-Time-Zone. A runner that sends no zone runs where the Worker does, on UTC.
*/
export function personMonth(now = new Date()): string {
return String(now.getMonth() + 1).padStart(2, '0');
}
/** Money compared to the cent, whether the runtime answered a number or a numeric string. */
export function expectMoney(expect: Expect, actual: unknown, cents: number, what = 'amount'): void {
expect(Number(actual), `${what} was ${JSON.stringify(actual)}`).toBeCloseTo(cents, 2);
}
/**
* The rows a list route answered: a 2xx answer whose body is a list. A check on what a list lacks
* (`not.toContainEqual`) passes on an error body such as `{ error }`, so it reads the rows first.
*/
export async function rowsOf(api: ContractApi, expect: Expect, path: string): Promise<Json[]> {
const reply = await api.get(path);
expectOk(expect, reply, `GET ${path}`);
expect(
Array.isArray(reply.body),
`GET ${path} answers a list: ${JSON.stringify(reply.body)}`
).toBe(true);
return reply.body as Json[];
}
/**
* The rows of `GET /api/transactions`.
*
* DIFFERENCE transactions-list-shape: the Worker answers `{ rows, total, limit, offset }`, local-first
* a bare array. The app reads both through `listRows()` (core/api.ts).
*/
export function transactionRows(api: ContractApi, expect: Expect, reply: Reply): Json[] {
expectOk(expect, reply, 'GET /api/transactions');
if (api.runtime === 'worker') {
expect(Array.isArray(reply.body?.rows), 'the Worker answers { rows }').toBe(true);
return reply.body.rows as Json[];
}
expect(Array.isArray(reply.body), 'local-first answers an array').toBe(true);
return reply.body as Json[];
}
/** `GET /api/transactions` with a query, as rows. */
export async function listTransactions(
api: ContractApi,
expect: Expect,
query = ''
): Promise<Json[]> {
return transactionRows(api, expect, await api.get(`/api/transactions${query}`));
}
/** A row's id list, for comparing sets and orders. */
export function idsOf(rows: readonly Json[]): number[] {
return rows.map((row) => Number(row.id));
}
/** One account's stored balance, read back through `GET /api/accounts/:id`. */
export async function balanceOf(api: ContractApi, expect: Expect, id: number): Promise<number> {
const reply = await api.get(`/api/accounts/${id}`);
expectOk(expect, reply, `GET /api/accounts/${id}`);
return Number(reply.body.balance);
}
/** A category, as the Categories form adds it. */
export async function addCategory(
api: ContractApi,
expect: Expect,
name: string,
type = 'expense'
): Promise<number> {
return added(api, expect, '/api/categories', { name, type, color: '#aa5500', icon: 'tag' });
}
/**
* A new transaction's body as the Transactions form builds it (features/transactionForm.ts,
* transactionBody): every field the form shows, the ones left blank as empty text, and an
* exchange rate of 1. `fields` are what a person filled in or picked.
*/
export function transactionForm(fields: Record<string, unknown> = {}) {
return {
type: 'expense',
description: 'Groceries',
amount: 10,
currency: 'EUR',
date: '2026-03-10',
category_id: null,
beneficiary: '',
payor: '',
exchange_rate: 1,
notes: '',
...fields,
};
}
/** Adds a transaction as the Transactions form does and answers its id. */
export async function addTransaction(
api: ContractApi,
expect: Expect,
fields: Record<string, unknown>
): Promise<number> {
return added(api, expect, '/api/transactions', transactionForm(fields));
}