From f3ef2898d73b7cda785f697399a1bd98dd8221c9 Mon Sep 17 00:00:00 2001 From: Grant Charge Date: Sun, 22 Nov 2026 14:23:39 +0000 Subject: [PATCH 1/3] docs: add agent skills setup (issue tracker, triage labels, domain docs) --- CLAUDE.md | 14 ++++++++++ docs/agents/domain.md | 51 ++++++++++++++++++++++++++++++++++++ docs/agents/issue-tracker.md | 50 +++++++++++++++++++++++++++++++++++ docs/agents/triage-labels.md | 15 +++++++++++ 4 files changed, 130 insertions(+) create mode 100644 docs/agents/domain.md create mode 100644 docs/agents/issue-tracker.md create mode 100644 docs/agents/triage-labels.md diff --git a/CLAUDE.md b/CLAUDE.md index 408acba..9cb895d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,3 +22,17 @@ Sentence case. Plain short sentences. No em dashes. - Database changes: add the next numbered file in `supabase/migrations/`. It applies on start, or with `npm run migrate`. - Checks: `npm run lint`, `npx tsc --noEmit`, and pure libraries with `node src/lib/.test.ts`. - `scripts/e2e-sandbox.mjs` runs a throwaway user through every page. + +## Agent skills + +### Issue tracker + +GitHub issues in this repo. See `docs/agents/issue-tracker.md`. + +### Triage labels + +Default five roles, label names equal the role names. See `docs/agents/triage-labels.md`. + +### Domain docs + +Single-context. See `docs/agents/domain.md`. diff --git a/docs/agents/domain.md b/docs/agents/domain.md new file mode 100644 index 0000000..4032de0 --- /dev/null +++ b/docs/agents/domain.md @@ -0,0 +1,51 @@ +# Domain Docs + +How the engineering skills should consume this repo's domain documentation when exploring the codebase. + +## Before exploring, read these + +- **`GLOSSARY.md`** at the repo root, or +- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic. +- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src//docs/adr/` for context-scoped decisions. + +If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved. + +## File structure + +Single-context repo (most repos): + +``` +/ +├── GLOSSARY.md +├── docs/adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +Multi-context repo (presence of `GLOSSARY-MAP.md` at the root): + +``` +/ +├── GLOSSARY-MAP.md +├── docs/adr/ ← system-wide decisions +└── src/ + ├── ordering/ + │ ├── GLOSSARY.md + │ └── docs/adr/ ← context-specific decisions + └── billing/ + ├── GLOSSARY.md + └── docs/adr/ +``` + +## Use the glossary's vocabulary + +When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids. + +If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`). + +## Flag ADR conflicts + +If your output contradicts an existing ADR, surface it explicitly rather than silently overriding: + +> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_ diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md new file mode 100644 index 0000000..95e4213 --- /dev/null +++ b/docs/agents/issue-tracker.md @@ -0,0 +1,50 @@ +# Issue tracker: GitHub + +Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations. + +## Conventions + +- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies. +- **Read an issue**: `gh issue view --json number,title,body,labels,comments`. +- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters. +- **Make an issue a sub-issue of a parent**: `gh issue create --parent ...`, or `gh issue edit --add-sub-issue ` afterwards (`gh` 2.94+). Older `gh`: `gh api --method POST repos///issues//sub_issues -F sub_issue_id=` (database id, as in **Blocking** below). Without sub-issues, put `Part of #` at the top of the child body. +- **Blocking**: GitHub's **native issue dependencies**, the canonical, UI-visible representation. Add an edge with `gh issue create --blocked-by , ...` or `gh issue edit --add-blocked-by ` (`gh` 2.94+). Older `gh`: `gh api --method POST repos///issues//dependencies/blocked_by -F issue_id=`, where `` is the blocker's numeric **database id** (`gh api repos///issues/ --jq .id`, _not_ the `#number` or `node_id`). Where dependencies aren't available, fall back to a `Blocked by: #, #` line at the top of the child body. A ticket is unblocked when every blocker is closed. +- **Count open blockers**: `gh api repos///issues/ --jq .issue_dependencies_summary.blocked_by` (open blockers only; 0 means startable). `gh issue view --json blockedBy` also lists closed blockers, so filter it: `--jq '[.blockedBy.nodes[] | select(.state == "OPEN")] | length'`. +- **Comment on an issue**: `gh issue comment --body "..."` +- **Apply / remove labels**: `gh issue edit --add-label "..."` / `--remove-label "..."` +- **Close**: post the explanation with `gh issue comment --body "..."`, then `gh issue close `. On an already-closed issue, `gh issue close --comment` drops the comment and still exits 0. + +Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone. + +File issues only into the user's own repo. Never file into `GrantCharge/broke` (the repo these skills come from) unless the user owns it. In a fork, `gh` can default to the upstream parent, so before the first `gh issue create` of a session, check the target with `gh repo view --json nameWithOwner` and confirm it with the user if it is not their repo. + +## Pull requests as a triage surface + +**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_ + +When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents: + +- **Read a PR**: `gh pr view `, then `gh pr view --comments` (off a TTY, `--comments` prints only the comments, not the body), and `gh pr diff ` for the diff. +- **List external PRs for triage**: `gh api --paginate 'repos/{owner}/{repo}/pulls?state=open' --jq '.[] | select(.author_association | IN("OWNER","MEMBER","COLLABORATOR") | not) | {number, title, author: .user.login, author_association, labels: [.labels[].name]}'`. +- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`. + +GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`. + +## When a skill says "publish to the issue tracker" + +Create a GitHub issue. + +## When a skill says "fetch the relevant ticket" + +Read it as in **Read an issue** above. + +## Wayfinding operations + +Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets. + +- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`. +- **Child ticket**: an issue linked to the map as a GitHub sub-issue (see **Make an issue a sub-issue of a parent**). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #` at the top of the child body. Labels: `wayfinder:` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev. +- **Blocking**: see **Blocking** under Conventions. +- **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (see **Count open blockers**, or an open issue in the `Blocked by` line) or an assignee; first in map order wins. +- **Claim**: `gh issue edit --add-assignee @me`, the session's first write. +- **Resolve**: `gh issue comment --body ""`, then `gh issue close `, then append a context pointer (gist + link) to the map's Decisions-so-far. diff --git a/docs/agents/triage-labels.md b/docs/agents/triage-labels.md new file mode 100644 index 0000000..4231c91 --- /dev/null +++ b/docs/agents/triage-labels.md @@ -0,0 +1,15 @@ +# Triage Labels + +The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker. + +| Label in GrantCharge/broke | Label in our tracker | Meaning | +| -------------------------- | -------------------- | ---------------------------------------- | +| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue | +| `needs-info` | `needs-info` | Waiting on reporter for more information | +| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent | +| `ready-for-human` | `ready-for-human` | Requires human implementation | +| `wontfix` | `wontfix` | Will not be actioned | + +When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table. + +Edit the "Label in our tracker" column to match whatever vocabulary you actually use. From d06935ae0b264a1c99f4e00111180477f127790f Mon Sep 17 00:00:00 2001 From: Grant Charge Date: Sun, 22 Nov 2026 15:55:26 +0000 Subject: [PATCH 2/3] docs: rename CLAUDE.md to AGENTS.md as the generic agent file --- CLAUDE.md => AGENTS.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CLAUDE.md => AGENTS.md (100%) diff --git a/CLAUDE.md b/AGENTS.md similarity index 100% rename from CLAUDE.md rename to AGENTS.md From 601cedbeb0ccf1dffb169fcce32b8047702ce6c1 Mon Sep 17 00:00:00 2001 From: Grant Charge <14937161+GrantCharge@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:15:36 +0700 Subject: [PATCH 3/3] Thai bank accounts by hand, totals in two currencies - Manual accounts and statement imports can pick their own currency (a Thai bank in THB). - Settings: 'Also show totals in' sets a second currency (profile.currency2). - Home tiles, month spend and Transactions totals show home and second currency. Each transaction converts at its own day's ECB rate. - Migration 0032: account currency grant and check, second_currency(), money_total, money_rows and txn_totals take a currency, second_balance. txn_totals converts again (0028 had dropped the conversion). Co-Authored-By: Claude Sonnet 5.5 --- src/app/(app)/accounts/add/page.tsx | 6 +- src/app/(app)/page.tsx | 31 ++++--- src/app/(app)/settings/Settings.tsx | 16 ++-- src/app/(app)/transactions/page.tsx | 27 ++++--- src/components/AddAccounts.tsx | 22 +++-- src/components/CountryPicker.tsx | 15 ++++ src/components/EmptyBank.tsx | 2 +- src/components/ImportStatement.tsx | 26 ++++-- src/components/ManualTxn.tsx | 4 +- src/lib/format.test.ts | 5 ++ src/lib/format.ts | 10 ++- supabase/migrations/0032_second_currency.sql | 85 ++++++++++++++++++++ 12 files changed, 202 insertions(+), 47 deletions(-) create mode 100644 supabase/migrations/0032_second_currency.sql diff --git a/src/app/(app)/accounts/add/page.tsx b/src/app/(app)/accounts/add/page.tsx index d5644d8..a172c7b 100644 --- a/src/app/(app)/accounts/add/page.tsx +++ b/src/app/(app)/accounts/add/page.tsx @@ -11,8 +11,8 @@ export default async function AddAccountsPage({ searchParams }: { searchParams: const { connect } = await searchParams; const country = countryOf(user?.user_metadata?.profile?.country); const choices = addChoices(country.code, wantsAkahu(user?.user_metadata?.profile)); - const { data: manual } = await supabase.from("accounts").select("id, name, custom_name, mask").eq("manual", true).eq("user_id", user!.id); - const accounts = (manual ?? []).map((a) => ({ id: a.id, label: `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}` })); + const { data: manual } = await supabase.from("accounts").select("id, name, custom_name, mask, currency").eq("manual", true).eq("user_id", user!.id); + const accounts = (manual ?? []).map((a) => ({ id: a.id, label: `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}`, currency: a.currency as string | null })); return (
Back to accounts @@ -21,7 +21,7 @@ export default async function AddAccountsPage({ searchParams }: { searchParams: {connect === "cancelled" &&

The connection was cancelled. Nothing changed.

} {connect === "failed" &&

That bank didn't connect. Try again, or import a statement instead.

} {!choices.bank && !choices.plaidMissing && !choices.feeds.length && !choices.akahuMissing && !choices.alsoAkahu &&

Automatic bank linking isn't available in {country.name} yet. Import a statement from your bank instead: it takes a minute and works with any bank.

} - + {choices.akahuMissing && (

To sync NZ banks automatically, add Akahu keys on the Setup page. Until then, import a statement from your bank.

)} diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 78f9521..850064c 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -12,7 +12,7 @@ import { SyncButton } from "@/components/PlaidButtons"; import { TxnList } from "@/components/TxnList"; import { WeekCard } from "@/components/WeekCard"; import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data"; -import { dateLabel, money0, monthStart, ymd } from "@/lib/format"; +import { dateLabel, money0, monthStart, secondCurrency, ymd } from "@/lib/format"; import { deterministicMoves, ladder } from "@/lib/plan"; import { myPlanFacts } from "@/lib/plan-facts"; import { payGuess } from "@/lib/pay"; @@ -68,30 +68,37 @@ export default async function Dashboard() { const checks = (fetchChecks(supabase, uid, day) as Promise).catch(() => ({ rows: [], total: 0 })); // starts now, beside the queries below // Own rows only: an account a partner shares is on the Accounts page, not in your totals. - const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats] = await Promise.all([ + const two = secondCurrency(); // totals also show in this currency (Settings, migration 0032) + const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats, spent2] = await Promise.all([ supabase.from("transactions").select(TXN_SELECT).eq("user_id", uid).order("date", { ascending: false }).order("id").limit(5), - supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid), + supabase.from("accounts").select("type, subtype, current_balance:home_balance, second:second_balance, included").eq("user_id", uid), supabase.rpc("fx_missing"), supabase.from("recurring").select("id, merchant_name, logo_url, average_amount:home_average, next_date").eq("user_id", uid).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED").gte("next_date", day).lte("next_date", soon).order("next_date").limit(4), moneyByMonth(supabase, ymd(monthStart(now))), categories(), + two ? supabase.rpc("money_total", { start_date: ymd(monthStart(now)), cur: two }).single<{ spend: number }>() : null, ]); if (!accounts?.length) return ; const txns = withAccountNames((recent ?? []) as unknown as Txn[]); type Acct = { type: string; subtype: string | null }; - const bal = (pred: (a: Acct) => boolean) => { + const bal = (pred: (a: Acct) => boolean, col: "current_balance" | "second" = "current_balance") => { const list = accounts.filter((a) => a.included && pred(a)); - return list.length ? list.reduce((s, a) => s + Number(a.current_balance ?? 0), 0) : null; + return list.length ? list.reduce((s, a) => s + Number(a[col] ?? 0), 0) : null; + }; + // Each tile in home currency, and in the second currency underneath when one is set. + const tile = (label: string, href: string, pred: (a: Acct) => boolean, abs = false) => { + const fix = (n: number | null) => (n == null ? null : abs ? Math.abs(n) : n); + return { label, href, value: fix(bal(pred)), value2: two ? fix(bal(pred, "second")) : null }; }; - const owed = bal((a) => a.type === "credit" || a.type === "loan"); const tiles = [ - { label: "In your bank", value: bal((a) => a.type === "depository" && a.subtype !== "savings"), href: "/accounts" }, - { label: "Savings", value: bal((a) => a.type === "depository" && a.subtype === "savings"), href: "/accounts" }, - { label: "Investments", value: bal((a) => a.type === "investment"), href: "/accounts" }, - { label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" }, + tile("In your bank", "/accounts", (a) => a.type === "depository" && a.subtype !== "savings"), + tile("Savings", "/accounts", (a) => a.type === "depository" && a.subtype === "savings"), + tile("Investments", "/accounts", (a) => a.type === "investment"), + tile("You owe", "/debt", (a) => a.type === "credit" || a.type === "loan", true), ].filter((t) => t.value != null); + const spentTwo = spent2?.data ? Number(spent2.data.spend) : null; const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null); const monthName = dateLabel(day, { month: "long" }); @@ -107,6 +114,7 @@ export default async function Dashboard() { {t.label} {money0(t.value!)} + {t.value2 != null && {money0(t.value2, two)}} ))} @@ -122,7 +130,8 @@ export default async function Dashboard() { Spent in {monthName} See all
-

{money0(pic.spent)}

+

{money0(pic.spent)} + {spentTwo != null && {money0(spentTwo, two)}}

{pic.spent > 0 ? ( <>
diff --git a/src/app/(app)/settings/Settings.tsx b/src/app/(app)/settings/Settings.tsx index b971531..48c24be 100644 --- a/src/app/(app)/settings/Settings.tsx +++ b/src/app/(app)/settings/Settings.tsx @@ -6,7 +6,7 @@ import { ClearMyData, ClearTestData, RemoveTest } from "@/components/ClearTestDa import { useRouter } from "next/navigation"; import { useCallback, useEffect, useState } from "react"; import { modelOptions, saveChoice } from "@/components/Assistant"; -import { CountryField } from "@/components/CountryPicker"; +import { CountryField, CurrencyField } from "@/components/CountryPicker"; import { Dropdown } from "@/components/Dropdown"; import { Modal } from "@/components/Modal"; import { ThemeToggle } from "@/components/Nav"; @@ -22,7 +22,7 @@ import { Segmented } from "../../setup/SetupActions"; type Group = "profile" | "banks" | "database" | "ai" | "referrals" | "appearance" | "advanced" | "improve"; type Mode = "sandbox" | "production"; -type Profile = Record & { country?: string; currency?: string }; +type Profile = Record & { country?: string; currency?: string; currency2?: string }; const NAV: { id: Group; label: string; icon: LucideIcon; what: string }[] = [ { id: "profile", label: "Profile", icon: User, what: "Your account, country and money profile." }, @@ -183,10 +183,10 @@ function Card({ title, what, s, children }: { title: string; what?: string; s?: function ProfileCards({ email, profile }: { email: string; profile: Profile }) { const router = useRouter(); - const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency }; + const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency, currency2: profile.currency2 ?? "" }; const [c, setC] = useState(start); const [msg, setMsg] = useState(""); - const dirty = c.country !== start.country || c.currency !== start.currency; + const dirty = c.country !== start.country || c.currency !== start.currency || c.currency2 !== start.currency2; const credit = creditOf(profile); async function save() { const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, ...c } } }); @@ -203,7 +203,13 @@ function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
- (setC({ country, currency }), setMsg(""))} /> + (setC({ ...c, country, currency }), setMsg(""))} /> +
+
+ Also show totals in + (setC({ ...c, currency2 }), setMsg(""))} /> +

For money in two countries. Each amount converts at that day's exchange rate.

diff --git a/src/app/(app)/transactions/page.tsx b/src/app/(app)/transactions/page.tsx index 50b095c..008e021 100644 --- a/src/app/(app)/transactions/page.tsx +++ b/src/app/(app)/transactions/page.tsx @@ -8,7 +8,7 @@ import { TxnRow } from "@/components/TxnRow"; import { pairTransfers } from "@/lib/transfers"; import { countryOf } from "@/lib/countries"; import { accountName, allTags, categories, getUser, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data"; -import { money, plural, ymd } from "@/lib/format"; +import { homeCurrency, money, plural, secondCurrency, ymd } from "@/lib/format"; import { fetchChecks } from "@/lib/unsure"; type Search = { q?: string; category?: string; account?: string; range?: string; from?: string; to?: string; tag?: string; limit?: string }; @@ -43,31 +43,39 @@ export default async function Transactions({ searchParams }: { searchParams: Pro if (since) query = query.gte("date", since); if (to) query = query.lte("date", to); - const [{ data, count, error }, cats, { data: accounts, error: acctError }, tags, totals, checks] = await Promise.all([ + const two = secondCurrency(); // also show totals in this currency (Settings), set by getUser above + const filter = { q: q ?? null, cat: category ?? null, acct: account ?? null, tag: tag ?? null, start_date: since ?? null, end_date: to ?? null }; + const [{ data, count, error }, cats, { data: accounts, error: acctError }, tags, totals, checks, totals2] = await Promise.all([ query, categories(), - supabase.from("accounts").select("id, name, custom_name, mask, owner_label, manual").order("name"), + supabase.from("accounts").select("id, name, custom_name, mask, owner_label, manual, currency").order("name"), allTags(), // Out and in over the whole filter, not just the loaded page: own rows, no transfers, no ignored (migration 0014). - supabase.rpc("txn_totals", { q: q ?? null, cat: category ?? null, acct: account ?? null, tag: tag ?? null, start_date: since ?? null, end_date: to ?? null }).single<{ money_out: number; money_in: number }>(), + supabase.rpc("txn_totals", filter).single<{ money_out: number; money_in: number }>(), // "Is this right?" rows at the top, own rows from the last 90 days (lib/unsure.ts). fetchChecks(supabase, user!.id, ymd(now)), + // The same totals in the second currency, each row at its own day's rate (migration 0032). + two ? supabase.rpc("txn_totals", { ...filter, cur: two }).single<{ money_out: number; money_in: number }>() : null, ]); if (error || acctError || totals.error) throw new Error((error ?? acctError ?? totals.error)!.message); const txns = withAccountNames((data ?? []) as unknown as Txn[]); const pairs = pairTransfers(txns); // a card payment shows once, on the account it left const out = Number(totals.data?.money_out ?? 0); const inn = Number(totals.data?.money_in ?? 0); + const out2 = totals2?.data ? Number(totals2.data.money_out) : null; + const inn2 = totals2?.data ? Number(totals2.data.money_in) : null; + // Accounts in another currency say which, so a baht account is easy to pick when adding by hand. + const curTag = (c: string | null) => (c && c !== homeCurrency() ? ` (${c})` : ""); const shared = (accounts ?? []).some((a) => a.owner_label); - const own = (accounts ?? []).filter((a) => !a.owner_label).map((a) => ({ id: a.id, label: `${accountName(a)}${a.mask ? ` ··${a.mask}` : ""}` })); - const ownManual = (accounts ?? []).filter((a) => !a.owner_label && a.manual).map((a) => ({ id: a.id, label: accountName(a) })); + const own = (accounts ?? []).filter((a) => !a.owner_label).map((a) => ({ id: a.id, label: `${accountName(a)}${a.mask ? ` ··${a.mask}` : ""}${curTag(a.currency)}`, currency: a.currency as string | null })); + const ownManual = (accounts ?? []).filter((a) => !a.owner_label && a.manual).map((a) => ({ id: a.id, label: `${accountName(a)}${curTag(a.currency)}`, currency: a.currency as string | null })); const more = new URLSearchParams(Object.entries({ q: sp.q, category, account, range, from, to, tag, limit: String(limit + PAGE) }).filter(([, v]) => v) as [string, string][]); if (!count && !q && !category && !account && !range && !from && !to && !tag) return ( - + ); @@ -84,9 +92,10 @@ export default async function Transactions({ searchParams }: { searchParams: Pro
{plural(count ?? 0, "transaction")}{count && count > txns.length ? `, showing ${txns.length}` : ""} - {!!txns.length && {shared ? "Yours: " : ""}{money(out)} out · {money(inn)} in} + {!!txns.length && {shared ? "Yours: " : ""}{money(out)} out · {money(inn)} in + {out2 != null && inn2 != null && ({money(out2, two)} out · {money(inn2, two)} in)}} - + Rules
diff --git a/src/components/AddAccounts.tsx b/src/components/AddAccounts.tsx index c30999f..5210747 100644 --- a/src/components/AddAccounts.tsx +++ b/src/components/AddAccounts.tsx @@ -19,6 +19,7 @@ import { X } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; +import { CurrencyField } from "@/components/CountryPicker"; import { Dropdown } from "@/components/Dropdown"; import { ImportStatement } from "@/components/ImportStatement"; import { Modal } from "@/components/Modal"; @@ -29,7 +30,7 @@ import { toast } from "@/components/Toast"; import type { AddChoices } from "@/lib/providers"; import { createClient } from "@/utils/supabase/client"; -type Acct = { id: string; label: string }; +type Acct = { id: string; label: string; currency?: string | null }; // Overlapping circles. Soft = brand tint, dark = ink with light icons. function Cluster({ icons, dark = false }: { icons: Icon[]; dark?: boolean }) { @@ -138,6 +139,7 @@ const KINDS = [ { value: "vehicle", label: "Car or other vehicle", type: "other", placeholder: "e.g. 2019 Corolla" }, { value: "property", label: "Home or property", type: "other", placeholder: "e.g. Our house" }, { value: "crypto", label: "Crypto", type: "investment", placeholder: "e.g. Bitcoin wallet" }, + { value: "checking", label: "Bank account you update by hand", type: "depository", placeholder: "e.g. Kasikorn everyday" }, { value: "cash", label: "Cash", type: "depository", placeholder: "e.g. Cash at home" }, { value: "other", label: "Something else you own", type: "other", placeholder: "e.g. Watch" }, { value: "owed", label: "Something you owe", type: "loan", placeholder: "e.g. Car loan" }, @@ -145,9 +147,9 @@ const KINDS = [ function AddAsset() { const router = useRouter(); - const { money, parseAmount } = useMoney(); + const { money, parseAmount, currency: home, currency2 } = useMoney(); const [open, setOpen] = useState(false); - const [f, setF] = useState({ kind: KINDS[0].value, name: "", value: "" }); + const [f, setF] = useState({ kind: KINDS[0].value, name: "", value: "", currency: home }); const [busy, setBusy] = useState(false); const [err, setErr] = useState(""); const kind = KINDS.find((k) => k.value === f.kind)!; @@ -161,6 +163,8 @@ function AddAsset() { setErr(""); const { error } = await createClient().from("accounts").insert({ name: f.name.trim(), type: kind.type, subtype: kind.value === "owed" ? "other" : kind.value, current_balance: value, manual: true, + // Home stays null so it follows home if that changes (migration 0015). Another currency is kept (0032). + ...(f.currency !== home ? { currency: f.currency } : {}), }); setBusy(false); if (error) return setErr(/manual/.test(error.message) ? "Manual accounts need a database update. Open Setup to run it." : "Couldn't save that account."); @@ -172,7 +176,7 @@ function AddAsset() { return ( <> - setOpen(true)} /> + setOpen(true)} /> {open && ( setOpen(false)}>
@@ -190,8 +194,12 @@ function AddAsset() { +
+ Currency + setF({ ...f, currency })} /> +
{err &&

{err}

}
@@ -201,7 +209,7 @@ function AddAsset() { ); } -export function AddAccounts({ choices, accounts, locale, currency, country }: { choices: AddChoices; accounts: Acct[]; locale: string; currency: string; country: string }) { +export function AddAccounts({ choices, accounts, locale, country }: { choices: AddChoices; accounts: Acct[]; locale: string; country: string }) { // One link at a time, so every button shares one hook and one status card. const link = useLinkBank(undefined, { quiet: true }); return ( @@ -214,7 +222,7 @@ export function AddAccounts({ choices, accounts, locale, currency, country }: { {choices.plaidMissing && window.location.assign("/setup")} />} {(choices.bank === "akahu" || choices.alsoAkahu) && } {choices.investments && } - ( + ( )} /> diff --git a/src/components/CountryPicker.tsx b/src/components/CountryPicker.tsx index 5628042..62ac247 100644 --- a/src/components/CountryPicker.tsx +++ b/src/components/CountryPicker.tsx @@ -27,6 +27,21 @@ export function CountryField({ country, currency, onChange }: { country: string; ); } +// Any currency, with the ones you use most (home, second) at the top. Used for a second currency and for +// manual accounts kept in another currency, like a Thai bank account in baht. +export function CurrencyField({ label, value, onChange, first = [], none }: { label: string; value: string; onChange: (c: string) => void; first?: string[]; none?: string }) { + const options = useMemo(() => { + const name = new Intl.DisplayNames(["en"], { type: "currency" }); + const top = [...new Set(first.filter(Boolean))]; + const all = Intl.supportedValuesOf("currency").filter((c) => !top.includes(c)); + return [ + ...(none ? [{ value: "", label: none }] : []), + ...[...top, ...all].map((c) => ({ value: c, label: `${name.of(c)} (${c})` })), + ]; + }, [first, none]); + return ; +} + // Saves country and home currency into the money profile (user_metadata.profile), keeping the rest of it. async function saveCountry(profile: Profile, country: string, currency: string) { const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, country, currency } } }); diff --git a/src/components/EmptyBank.tsx b/src/components/EmptyBank.tsx index 8ce4c8e..742447b 100644 --- a/src/components/EmptyBank.tsx +++ b/src/components/EmptyBank.tsx @@ -29,7 +29,7 @@ export async function EmptyBank({ title = "Link an account to get started", body {choices.sandbox && } {choices.sandbox && } {choices.demo && } - + {children ?? (investOnly && Add a transaction by hand)} More ways to add an account
diff --git a/src/components/ImportStatement.tsx b/src/components/ImportStatement.tsx index 5a94e99..9bfd7b7 100644 --- a/src/components/ImportStatement.tsx +++ b/src/components/ImportStatement.tsx @@ -3,7 +3,9 @@ import { Upload, X } from "lucide-react"; import { useRouter } from "next/navigation"; import { useMemo, useState } from "react"; +import { CurrencyField } from "@/components/CountryPicker"; import { Dropdown } from "@/components/Dropdown"; +import { useMoney } from "@/components/Money"; import { Modal } from "@/components/Modal"; import { toast } from "@/components/Toast"; import { applyRules, RULE_COLS, type Rule } from "@/lib/rules"; @@ -11,7 +13,7 @@ import { applyMapping, categoryKey, parseStatement, type DateOrder, type Mapping import { pdfToTable, type PdfItem } from "@/lib/statement-pdf"; import { createClient } from "@/utils/supabase/client"; -type Acct = { id: string; label: string }; +type Acct = { id: string; label: string; currency?: string | null }; const NEW = "__new"; const ORDERS: { value: DateOrder; label: string }[] = [ { value: "dmy", label: "Day first (31/12/2026)" }, @@ -22,14 +24,16 @@ const ORDERS: { value: DateOrder; label: string }[] = [ // "Import a bank statement": CSV, OFX or QIF from any bank. Rows are manual, keyed so a second import of the // same file adds nothing (transactions.import_key, migration 0016). Goes into a manual account or a new one. // trigger: draw your own opener (the Add accounts card) instead of the button. -export function ImportStatement({ accounts, locale, currency, link = false, trigger }: { accounts: Acct[]; locale: string; currency: string; link?: boolean; trigger?: (open: () => void) => React.ReactNode }) { +export function ImportStatement({ accounts, locale, link = false, trigger }: { accounts: Acct[]; locale: string; link?: boolean; trigger?: (open: () => void) => React.ReactNode }) { const router = useRouter(); + const { currency: home, currency2 } = useMoney(); // the profile's home currency, which may differ from the country's const [open, setOpen] = useState(false); const [file, setFile] = useState(""); const [parsed, setParsed] = useState(null); const [m, setM] = useState(null); const [account, setAccount] = useState(accounts[0]?.id ?? NEW); const [newName, setNewName] = useState(""); + const [newCur, setNewCur] = useState(home); // a new account can be in another currency, like a Thai bank in THB const [busy, setBusy] = useState(false); const [err, setErr] = useState(""); const [pdfFile, setPdfFile] = useState(null); // a locked PDF waiting for its password @@ -40,7 +44,8 @@ export function ImportStatement({ accounts, locale, currency, link = false, trig if (parsed.kind !== "csv") return { rows: parsed.rows, skipped: 0 }; return m ? applyMapping(parsed.table, m, locale) : { rows: [], skipped: 0 }; }, [parsed, m, locale]); - const fmt = useMemo(() => new Intl.NumberFormat(locale, { style: "currency", currency }), [locale, currency]); + const shown = account === NEW ? newCur : accounts.find((a) => a.id === account)?.currency || home; + const fmt = useMemo(() => new Intl.NumberFormat(locale, { style: "currency", currency: shown }), [locale, shown]); function reset() { setOpen(false); @@ -107,8 +112,11 @@ export function ImportStatement({ accounts, locale, currency, link = false, trig const supabase = createClient(); let acct = account; if (acct === NEW) { - // Currency left empty: a manual account is in the home currency (migration 0015). - const { data, error } = await supabase.from("accounts").insert({ name: newName.trim() || "Imported account", type: "depository", subtype: "checking", current_balance: 0, manual: true }).select("id").single(); + // Home currency stays empty, so it follows home (migration 0015). Any other currency is kept (0032). + const { data, error } = await supabase.from("accounts").insert({ + name: newName.trim() || "Imported account", type: "depository", subtype: "checking", current_balance: 0, manual: true, + ...(newCur !== home ? { currency: newCur } : {}), + }).select("id").single(); if (error) return setBusy(false), setErr("Couldn't create the account."); acct = data.id; } @@ -232,7 +240,7 @@ export function ImportStatement({ accounts, locale, currency, link = false, trig
Into account ({ value: a.id, label: a.label })), { value: NEW, label: "New account", hint: `In ${currency}` }]} /> + options={[...accounts.map((a) => ({ value: a.id, label: a.label })), { value: NEW, label: "New account", hint: `In ${newCur}` }]} />
{account === NEW && ( )} + {account === NEW && ( +
+ Currency + +
+ )}
)} diff --git a/src/components/ManualTxn.tsx b/src/components/ManualTxn.tsx index 5e23b8a..c6e6b30 100644 --- a/src/components/ManualTxn.tsx +++ b/src/components/ManualTxn.tsx @@ -12,7 +12,7 @@ import type { Category } from "@/lib/data"; import { createClient } from "@/utils/supabase/client"; import { useMoney } from "@/components/Money"; -type Acct = { id: string; label: string }; +type Acct = { id: string; label: string; currency?: string | null }; const NEW_CASH = "__cash"; const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time @@ -79,7 +79,7 @@ export function AddTransaction({ accounts, cats, allTags }: { accounts: Acct[];