diff --git a/src/__tests__/integration/auto-reconcile.test.ts b/src/__tests__/integration/auto-reconcile.test.ts index 126a622..61222f9 100644 --- a/src/__tests__/integration/auto-reconcile.test.ts +++ b/src/__tests__/integration/auto-reconcile.test.ts @@ -15,11 +15,18 @@ import { createPool, resetDB, seedParticipants, insertTransaction } from "./help * purchase's row. So most of what follows is about refusal. */ +const MACHINE_TOKEN = "test-wallet-token"; let pool: Pool; let ownerId: number; let autoReconcile: typeof import("../../app/api/transactions/reconcile/route").PATCH; -const userReq = (url = "http://x/api/transactions/reconcile") => ({ url }) as never; +/** Browser-session caller: no machine token, auth comes from the mocked session. */ +const userReq = (url = "http://x/api/transactions/reconcile") => + ({ url, headers: { get: () => null } }) as never; + +/** Scheduled caller: machine token, no session, sweeps every owner. */ +const machineReq = (url = "http://x/api/transactions/reconcile") => + ({ url, headers: { get: (h: string) => (h === "x-ingest-token" ? MACHINE_TOKEN : null) } }) as never; async function statementLine( amount: number, @@ -29,9 +36,12 @@ async function statementLine( ) { const owner = opts.owner ?? ownerId; const st = await pool.query( + // Account number varies by owner: uq_statement_identity is + // (bank_name, account_number, billing_end_date), so two owners sharing one + // account collide rather than modelling two real cards. `INSERT INTO statements (filename, account_number, bank_name, billing_start_date, billing_end_date, owner_id) - VALUES ('s.pdf', '1234-5678-9012-3302', 'Test Bank', $1::date - 20, $1::date + 10, $2) RETURNING id`, - [date, owner] + VALUES ('s.pdf', $3, 'Test Bank', $1::date - 20, $1::date + 10, $2) RETURNING id`, + [date, owner, `1234-5678-9012-${String(owner).padStart(4, "0")}`] ); const t = await pool.query( `INSERT INTO transactions @@ -66,6 +76,7 @@ const reconciledWith = async (id: number) => .rows[0].reconciled_with_id as number | null; beforeAll(async () => { + process.env.WALLET_INGEST_TOKEN = MACHINE_TOKEN; pool = createPool(); vi.doMock("@/lib/auth", () => ({ getCurrentUser: async () => ({ id: ownerId, name: "Alice", email: "alice@example.com" }), @@ -216,3 +227,45 @@ describe("dry run", () => { expect(await reconciledWith(manual)).toBeNull(); }); }); + +describe("the scheduled sweep", () => { + it("runs on the machine token with no session at all", async () => { + const manual = await walletRow(13.5, "2026-08-13"); + const stmt = await statementLine(13.5, "2026-08-14", "BREADWORLD BAKERY"); + + const body = await (await autoReconcile(machineReq())).json(); + expect(body.reconciled).toBe(1); + expect(await reconciledWith(manual)).toBe(stmt); + }); + + it("covers EVERY owner, not just one", async () => { + // 169 of the 177 rows outstanding belong to the second participant, so a + // sweep scoped to a single user would leave almost all of the queue alone. + const other = (await pool.query( + `INSERT INTO participants (name) VALUES ('Carol') RETURNING id` + )).rows[0].id as number; + + const mine = await walletRow(11, "2026-08-13"); + const theirTx = (await pool.query( + `INSERT INTO transactions (owner_id, statement_id, transaction_date, description, + amount, transaction_type, category, row_index) + VALUES ($1, NULL, '2026-08-13', 'Theirs', 22, 'debit', 'other', 0) RETURNING id`, [other] + )).rows[0].id as number; + + await statementLine(11, "2026-08-14", "MINE"); + await statementLine(22, "2026-08-14", "THEIRS", { owner: other }); + + const body = await (await autoReconcile(machineReq())).json(); + expect(body.reconciled).toBe(2); + expect(await reconciledWith(mine)).not.toBeNull(); + expect(await reconciledWith(theirTx)).not.toBeNull(); + }); + + it("rejects a wrong machine token and falls through to session auth", async () => { + const bad = ({ url: "http://x/", headers: { get: () => "not-the-token" } }) as never; + // Session is mocked, so this still succeeds -- but as the session user only, + // proving the bad token did not grant the all-owner sweep. + const body = await (await autoReconcile(bad)).json(); + expect(body.reconciled).toBe(0); + }); +}); diff --git a/src/app/api/transactions/reconcile/route.ts b/src/app/api/transactions/reconcile/route.ts index 1a24c20..840907d 100644 --- a/src/app/api/transactions/reconcile/route.ts +++ b/src/app/api/transactions/reconcile/route.ts @@ -51,11 +51,29 @@ export async function POST(req: NextRequest) { * be run the first time after any change to the matching rule. */ export async function PATCH(req: NextRequest) { - const user = await getCurrentUser(req); - if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); + // Two callers, two auth modes. A person in the browser reconciles their own + // queue; the scheduled sweep has no session and carries the machine token, + // and must cover EVERY owner with a queue -- 169 of the 177 rows outstanding + // belong to the second participant, so a sweep scoped to one user would leave + // almost all of it untouched. + const machineToken = req.headers.get("x-ingest-token"); + const machineOk = !!machineToken && machineToken === process.env.WALLET_INGEST_TOKEN; + + let ownerIds: number[]; + if (machineOk) { + ownerIds = (await queryRaw<{ owner_id: number }>( + `SELECT DISTINCT owner_id FROM transactions + WHERE statement_id IS NULL AND owner_id IS NOT NULL + AND reconciled_with_id IS NULL AND superseded_by_id IS NULL` + )).map((r) => r.owner_id); + } else { + const user = await getCurrentUser(req); + if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); + ownerIds = [user.id]; + } const dry = new URL(req.url).searchParams.get("dry") === "1"; - const matches = await findAutoMatches(user.id); + const matches = (await Promise.all(ownerIds.map((id) => findAutoMatches(id)))).flat(); if (dry) { return NextResponse.json({ dry_run: true, would_reconcile: matches.length, matches });