Author SHA1 Message Date
siddharthd 1103397397 fix(orders): three defects found reviewing my own branch
ci / lint-test (push) Failing after 1m27s
None of these were caught by 105 green tests, because the code they live in was
barely tested and the HTTP path was not tested at all.

1. reconcilePendingOrders hardcoded category 'dining', so any order resolved
   through the deferred path booked as dining regardless of merchant — a
   Woolworths grocery order that parks and later reconciles was misfiled.
   That reintroduced, through the back door, exactly the misfiling
   resolveCategory() exists to prevent. Now calls it.

2. reconcileCardLeg never marked a statement line as consumed, so two orders on
   the same card inside the +/-4 day window both bound to the same charge and
   each booked its own credits remainder — double-counting spend. At 10-15
   orders a month on one card that is not a corner case. Migration 0020 adds
   matched_transaction_id with a unique index; the matcher now excludes lines
   already claimed.

3. The ingest API returned HTTP 200 for every parse failure, and the Slack
   alert fires only on non-200. So the single most likely production failure —
   a provider template change breaking every order at once — was completely
   silent. Split into NotAReceiptError (promotions, delivery updates, refund
   and adjustment notices: 200, silent, expected traffic) and OrderParseError
   (it IS a receipt and would not parse: 422, alerts).

Also: order_reference now anchors on Uber's own tripReference cell rather than
'first UUID in the document'. I had claimed to verify that the first UUID was
always the order UUID; that check compared against zero samples and was
vacuous. tripReference is present in all 29 captured receipts and, for ue-00,
equals the UUID the PDF redirect resolves to. The positional fallback remains
but only flags when there is genuine ambiguity.

Adds the API route's first tests — auth gate and error taxonomy — plus
anchoring regressions. 63 unit + 53 integration green on five consecutive runs;
corpus holds at 63/65.
2026-07-27 01:15:39 +10:00
siddharthd a9e251d969 feat(orders): amendments, family imports, and the ingest API
Closes the three gaps left after the parser rebuild.

Refund amendments. ue-05 is a real refund: 'Previous total $49.94 / Refund
-$4.21 / New Total $45.73'. Uber reuses the order UUID across the receipt and
the amendment, so the two can be matched. The transaction is reduced in place
rather than offset with a second row — the order is one event whose cost
changed, and a compensating row would misreport both the meal count and the
merchant's spend. When the original was never ingested, nothing is invented.

[Family] orders now import instead of parking. Their payment line names the
payer, not an instrument ('Payments Siddharth LKR 3,783.20'), so no split is
recoverable and there is no card leg to reconcile against — they would have sat
pending forever, which fails the actual requirement to import and tag them.
Treated as credits, flagged as an assumption. Safe because the family tag
removes them from every budget regardless of instrument, and the LKR amount is
preserved with amount_aud left NULL rather than asserting an FX rate.

Ingest API. n8n now POSTs each message to /api/orders/ingest instead of parsing
in a Code node — the n8n sandbox has no require or fs, so a parser there cannot
be tested against the fixture corpus, which is the one thing that makes this
parser trustworthy. Auth is a shared secret, since machine callers have no
Traefik session header. Rejections return 422 and record nothing.

60 unit + 45 integration green on three consecutive runs; 63/65 corpus holds.
2026-07-27 00:48:20 +10:00
siddharthd c82a22767f feat(orders): wire the real parser in, defer card reconciliation
Ingestion now runs on the rebuilt parser. Three substantive changes.

Deferred card reconciliation. A 'MasterCard 8032 and/or credits' receipt never
states the split, but the card leg lands on the statement — Subway's $29.08
order shows $13.06 on 8032, so $16.02 was credits. For a live order that
statement is weeks away, so the split cannot be settled at ingest time. Such
orders are now parked with provenance and no transaction, and
reconcilePendingOrders() resolves them once the statement arrives. Backfill
takes the same path and resolves immediately. Migration 0019 adds the columns
that make an order resumable; applied to personal_test only, prod untouched.

Payment detection bug, found by the new tests: the old regex delimited the
'Paid with' line on a double space, which whitespace collapsing removes. Every
card and mixed receipt fell through to the credits branch — the Woolworths
receipt booked $60.93 of credits spend that never happened.

Category resolution reversed deliberately. Correction 1 said never default to
dining; the implementation of that sent everything unrecognised to 'other', and
knowing six merchants meant Carl's Jr, Taco Bell, Chilli India, Oporto, Schnitz
and Souvlaki GR all landed there. Grocers are an enumerable set and restaurants
are not, so match groceries explicitly and let the residual be dining.

Tests rebuilt on real captured receipts; the synthetic fixtures are deleted.
60 unit + 41 integration green on three consecutive runs.
2026-07-26 22:43:10 +10:00
siddharthd 33db7d05ef feat(orders): rebuild the receipt parser against real captured email
The previous parser was written against synthetic fixtures shaped to match the
code. It invented a table layout DoorDash does not send, generated
order_reference from Math.random(), read the order date from a 'Date:' string
present in no real message, and detected [Family] by searching the body for the
substring 'family'. Its tests passed because the fixtures were built to satisfy
it. Against 36 real DoorDash and 29 real Uber Eats receipts it does not work.

Rebuilt from the real corpus. 63 of 65 now parse and validate; the 2 rejected
are correctly rejected — one is an order-adjustment notice and one a refund,
neither of which is a receipt.

Corrects an inherited diagnosis: the Mad Mex 'Discounts -$24.09' was recorded
as an HTML-flattening artefact masking a 'true discount of $9.45'. Parsing the
table cells structurally returns the same figures and no $9.45 exists anywhere
in the message — DoorDash genuinely prints a Discounts line that equals subtotal
plus service fee, and the components fail to reconcile on 32 of 36 receipts. So
the breakdown is stored as provenance and never gated on; validation instead
cross-checks the two independently stated totals and the payment line, which is
the number that becomes money.

Real-world cases the corpus forced, none of which were in the spec: [Family]
orders are LKR purchases for family in Sri Lanka (reading them as dollars
inflates ~200x), Swiss orders arrive in CHF, grocery 'Final receipt' mails carry
no Total Charged row, and a declined payment is printed alongside the successful
retry and must be skipped or it records money that never moved.

order_reference now comes from the Uber order UUID embedded in the body, or the
provider message id where DoorDash supplies no order id at all — never random,
so re-ingestion is genuinely idempotent.
2026-07-26 22:25:26 +10:00
siddharthd 6d3b6e1a9d feat(orders): withdraw the ShopBack transfer guard
Tests 12 & 13 asserted that every 'ShopBack Gift Cards' row becomes a transfer.
Resolved against the ShopBack purchase emails, 3 of the 14 matching rows are
Airbnb, 1 Shell, 1 Amazon — the bank descriptor's trailing token is a sequence
counter, not a brand code, so the description cannot identify what was bought.
Only $313.66 of $3,411.16 was ever reclassifiable.

Withdrawn rather than narrowed: making it safe needs ShopBack purchase-email
ingestion, brand resolution and an approval gate, to correctly handle 2
transactions in 20 months. Those two rows get handled by hand.
2026-07-26 22:09:31 +10:00
siddharthd 9f168cf4c8 test(orders): stop integration files racing on the shared test database
The integration suite shares one personal_test database and helpers.resetDB()
TRUNCATEs it with CASCADE, which reaches expense_metadata via the transactions
FK. With file parallelism on, queries.test.ts and participants.test.ts were
truncating rows out from under order-ingestion.test.ts mid-test, so a different
set of assertions failed on every run — including I6 (credits), I7
(idempotency) and I11 ([Family]), the three invariants the suite exists to
prove. Serialise the files.

Suite was reported 31/31 green; observed 29/31 then 28/31 on consecutive runs.
Now 31/31 on three consecutive runs.
2026-07-26 19:50:21 +10:00
siddharthd 775e5cc08f feat(orders): add Uber Eats and Uber Rides support, fare parsing, and category resolution 2026-07-26 19:00:59 +10:00
siddharthd bbb90238e4 feat(orders): implement order ingestion pipeline, review ratings schema, and [Family] exclusion 2026-07-26 18:52:34 +10:00
siddharthd d06088fe34 docs: monthly expense baseline and emergency reserve analysis
ci / lint-test (push) Successful in 37s
One-off analysis, nothing built. Realistic baseline $4,140/mo -> $24,800 for
six months, against $89,770 already accessible ($81,017 loan redraw + $8,753
offset).

Records four corrections the raw data needs before any restatement:
misfiled Raiz/Vanguard/moomoo debits counted as spend, `other` credits read as
negative spend, `government` conflating ATO with rates/rego, and `fees` being
mostly annual.

CLAUDE.md gains two traps found while doing it: partial split coverage inside a
category is usually correct rather than a gap (only shared utilities and
subscriptions are split), and the loan repayment is voluntarily above contracted
($2,500 vs $1,190.54 per fortnight) with the difference recoverable via redraw.
2026-07-26 16:57:23 +10:00
siddharthd c465742635 docs: capture this session's learnings for a future pickup
ci / lint-test (push) Successful in 40s
CLAUDE.md gains the traps a new session would otherwise re-discover:

- Rules: a zero-condition rule matches everything (rule 43 would split all ~3,700
  transactions); preview-then-apply-by-id is the safe pattern and why it beats
  auto-applying on ingestion; how run provenance works.
- Shared expenses: transaction_splits.settled is dead data; getParticipantBalances
  is correct and must not be 'fixed'; settlement cannot be attributed per trip.
- The shared loan: separate ledger, fixed 50% with a tracked receivable, why the
  share must not be derived from actual payments, and why interest stays as spend.
- Extraction: balance assertions are the check that works, do not derive
  opening_balance or add a totals assertion (both would be tautological), Gemini
  invents summary fields it was not given, empty statements must not throw, FX is
  per-date, and CSV comparisons need millisecond ordering.

The design doc records Phase 0 as done - including that the original Phase 0 plan
was wrong, since reading the code first is what prevented breaking a working
balance page.

Known Gaps lists what is open: the unbuilt phases, 11 failing assertions, the
uncategorised Up rows, and the CSVs sitting in 030490e's history.
2026-07-26 16:19:02 +10:00
siddharthd 3f04cbd5e7 fix(trips): stop reporting a settlement breakdown that cannot be computed
ci / lint-test (push) Successful in 35s
The trip view showed Total Owed / Settled / Unsettled per participant, with the
last two derived from transaction_splits.settled. Nothing sets that flag - its
only writer was /api/splits/settle, which no UI calls - so it is false on all 673
splits and every trip reported 100% unsettled, including trips already paid in
full. Molina has paid $20,782.79 against $19,556.07 of splits and the Europe trip
still showed her entire share outstanding.

A correct per-trip figure is not computable either: split_payments records only
from, to, amount and date, so a payment cannot be attributed to a trip. The trip
view now shows each participant's share and points at Shared for what is actually
owed, which is where settlement genuinely lives.

Also removes /api/splits/settle. It was unreachable from the UI but live on its
URL, and a single call with participant_id would mark every one of that person's
splits settled - writing a flag nothing reads. Settlement will be reintroduced
against settlement contexts (docs/shared-expenses-design.md).

getParticipantBalances is deliberately untouched: it computes splits minus
payments, which is coherent. Excluding settled splits there while still
subtracting the payments that settled them would double-count.
2026-07-26 16:13:20 +10:00
siddharthd ba87ff86e7 docs: record loan decisions — separate ledger, 50/50 fixed, $4,000 receivable
ci / lint-test (push) Successful in 35s
The loan is a separate ledger, not a settlement context: a contribution must
never be able to settle a dinner.

The share is fixed at 50%, not derived from actual payments. During Sonu's leave
the obligation did not change, only the payment did - a percentage-of-actual
model would silently redefine her share as 30% and make the shortfall vanish. So
the model needs an expected schedule alongside actual contributions, with the
difference as a tracked receivable. Currently $4,000.00 over Jul 2025 - Jun 2026.

On interest: recorded the mechanics (it is debited to the loan and repaid as part
of the balance - the reconciliation is exact) alongside the counter-argument that
$16,523.64 left and bought nothing, which is what an expense is. Recommends
keeping it as spend with a fixed/discretionary grouping to address the real
concern, but flags it as a judgement call rather than settling it.
2026-07-26 16:03:53 +10:00
siddharthd 4b7a7e5d9c docs: design proposal for shared expenses, settlement and the shared loan
ci / lint-test (push) Successful in 35s
Three problems that look separate are one: the app records money moving, and
separately records who owes whom, and the two never meet.

Documents what is broken with evidence - two half-built settlement models,
settlements existing twice unlinked, and Sonu's $37,980 of loan contributions
sitting unrecognised as generic transfers - then proposes settlement contexts,
payments as transactions rather than a side table, and loan co-ownership.

Nothing built. Five open questions, two of which are decisions about the
arrangement rather than the software.
2026-07-26 15:57:03 +10:00
siddharthd 3778bfe836 feat(rules): show what an apply run changed, and which rule ran
ci / lint-test (push) Successful in 38s
Apply History listed only counts - '13 matches · 13 transactions' - which reads
identically whether the run renamed a merchant or split every transaction with
another participant. Revert is destructive, so that is not enough to decide on.

Two additions. Migration 0017 records rule_id, rule_name and source on each run:
rule_name is denormalised so history stays readable after a rule is edited or
deleted, and there is no FK so deleting a rule cannot cascade away the audit
trail. Both write paths now populate it - the condition-matched run and the
selection-based quick action.

And rows expand to show the run's snapshot set against current values: which
transactions were touched and what changed on each. Rows changed by something
else since the run are called out, because reverting restores the pre-run value
and would discard that later edit.

Runs recorded before this show 'Unknown rule' - the rule they came from is not
recoverable.
2026-07-26 15:20:56 +10:00
siddharthd cc852e7c6f feat(rules): preview what a rule would change before applying it
ci / lint-test (push) Successful in 34s
Selecting a rule now shows the transactions it would alter, so a subset can be
ticked and applied rather than trusting a bulk run. The apply step takes explicit
transaction ids (the existing bulk apply_rule path), so what you tick is exactly
what changes - a rule whose conditions are too broad cannot reach further than
the preview showed.

Matches are split into 'would change' and 'already correct'. A merchant
normalisation rule matching 400 rows where 380 already hold the right value is 20
changes and 380 rows of noise; only the 20 are listed.

Preview is offered for every rule including manual_only quick actions, which
previously had no way to see their reach at all. A rule with no conditions
matches every transaction - that is how apply already behaves, so the preview
reports it prominently rather than hiding it.

Applies still snapshot to rule_apply_runs, so they remain revertable.
2026-07-26 15:08:29 +10:00
siddharthd 31a8177958 chore: untrack dump/ — raw statement exports must never be committed
A git add -A in 030490e swept the Wise CSV exports into the repo and they were
pushed. They contain account numbers, an IBAN, payer and payee names and full
transaction detail.

This removes them from HEAD and ignores the directory. It does NOT purge them
from history — 030490e still contains them.
2026-07-26 14:49:47 +10:00
siddharthd 030490efa3 feat(cash): mark how a transaction was paid, exclude cash from reconciliation
ci / lint-test (push) Successful in 41s
getPendingReconciliations treated every unreconciled manual transaction as
awaiting a matching statement row. Cash never appears on a statement, so a cash
entry sat in the queue indefinitely being offered matches within 3 days and 1%
on amount - and accepting one is silently destructive: reconciled manual rows
are filtered out of every query, so the cash spend disappears while the card
transaction it matched claims to be that same spend.

Migration 0016 adds transactions.payment_method (card | cash | bank_transfer |
other, NULL = unknown) with a CHECK constraint and a partial index. The notCash()
fragment excludes cash from both halves of the reconciliation query - the pending
list and the candidate match subquery, which aliases the manual row as m.

Only cash is excluded. Bank transfers do appear on a statement now that
transaction accounts are imported, and NULL means unknown, so both stay
candidates and every pre-existing row behaves exactly as before.

ATM withdrawals deliberately stay categorised as spend rather than transfers.
Treating them as transfers is only correct if every cash purchase is logged;
with partial logging it silently deletes the unlogged remainder from spend.
2026-07-26 14:38:47 +10:00
siddharthd d6b4ec84f6 feat(integrity): balance assertions, category constraint, refund netting
ci / lint-test (push) Successful in 39s
Four related fixes to spend correctness.

Balance assertions. Nothing checked that a statement's transactions add up to
its closing balance. getStatements now computes opening + movement - closing
and the statements page flags any statement that does not reconcile. Sign
depends on what the balance means: on a credit card or loan it is what you owe,
so spending increases it; on a transaction or offset account it is what you
hold. 11 statements currently fail, $4,177 unexplained - including two adjacent
ANZ statements off by exactly +/-$230.38, a transaction filed against the wrong
one.

Category normalisation (migration 0015). Categories arrive from Gemini (which
writes straight to Postgres from N8N), CSV import and manual edits, so the rule
belongs in the database - same reasoning as normalize_statement_type in 0013.
Adds normalize_category(), triggers on transactions and transaction_overrides,
and CHECK constraints. Backfilled 122 rows: 19 'payment' ($42,569) to transfers,
14 'refund' recovered to the merchant's usual category, and title-case duplicates
folded into their canonical spelling - 'Shopping' and 'shopping' had been
counted as separate categories by every GROUP BY.

Refund netting. Monthly analytics counted only debits, so a refund was counted
nowhere: excluded from spend by type, and not income by category. A $2,888.92
Expedia purchase refunded in full eight days later still read as $2,888.92 of
spend. SPEND_SIGNED and NET_SPEND_ROWS bring refunds in as negatives; 'income'
joins the excluded categories so incoming money cannot leak in as negative
spend. $36,773 across 93 rows now nets correctly.

Drill-down share. The insights drill-down used my_share_percent ?? 100, which
ignored transaction_splits entirely and repeated the bug fixed in ab00f8c one
layer up. getTransactions now returns my_share_pct and my_amount resolved
server-side, and the table shows gross alongside your share.
2026-07-26 10:35:59 +10:00
siddharthd ab00f8c592 fix(analytics): my share is what is left over, not 100%
ci / lint-test (push) Successful in 41s
The split-adjusted spend expression assumed a transaction with no split row for
me was entirely mine. That is wrong when a transaction is allocated fully to
someone else: I paid, they owe all of it, and there is no row for me to match.
Both branches of the CASE missed and the ELSE charged me the full amount.

24 transactions were affected, all travel bookings between 2026-01-09 and
2026-06-26, overstating my spend by $8,579.07 across every analytics view.

Adds myShare/mySplitOf to analytics-sql.ts, which fall back to
100 - (sum of everyone else's shares) instead of 100, and applies them to all
five analytics routes. Centralised for the same reason as EXCLUDE_NON_SPEND:
the expression was duplicated five times and had already drifted.
2026-07-26 10:05:09 +10:00
siddharthd 02495e4173 fix(currency): show and settle foreign transactions in AUD
ci / lint-test (push) Successful in 1m24s
The transactions page rendered the statement's native amount through a
formatter hardcoded to AUD, so a USD row displayed its USD figure labelled as
dollars while every analytics query counted the converted amount_aud. Same
transaction, two different numbers depending on the page.

getTransactions now returns the statement currency, the amount column shows
amount_aud with the native figure beneath it when the two differ, and the split
and duplicate modals seed from the converted amount (a duplicate becomes a
manual AUD row, so the native figure would be wrong there).

Settlement balances had the same split: getParticipantBalances and the
per-participant balance route summed raw amount while trip totals summed
amount_aud, so a shared foreign expense would net a USD figure against AUD
ones. All three now agree on amount_aud. No change to current balances - every
statement in the database is AUD today - but correct once Wise data lands.
2026-07-26 10:00:15 +10:00
siddharthd 315bc06d0d fix(merchants): page crashed on an uncategorised transaction
ci / lint-test (push) Successful in 38s
Regression from the analytics scoping work. Chain:

1. Three transactions have a NULL category. The old WHERE clause
   `COALESCE(o.category_override, t.category) NOT IN ('transfers','investment')`
   evaluated to NULL for those rows, so they were silently dropped — which is
   the bug EXCLUDE_NON_SPEND fixed by defaulting to 'other'.
2. Including them exposed that the SELECT still used the non-null-safe
   COALESCE, so MODE() returned NULL for the affected merchant
   ("Shared expenses carryover (SplitMyExpenses)", a manual transaction that
   the LEFT JOIN fix also newly included).
3. formatCategory(null) threw "Cannot read properties of null (reading
   'split')" and took down the whole page render.

Fixed at both layers:
- Both merchants routes now use the EFFECTIVE_CATEGORY fragment, so the API
  cannot emit a null category.
- formatCategory tolerates null/undefined and returns "Uncategorised". An
  uncategorised transaction should never be able to crash a page.

Verified against the live DB: 200 merchants, zero null categories, and
/merchants /transactions /insights /budget /statements all render 200.
2026-07-26 01:35:50 +10:00
siddharthd 76db9dddb4 feat(loans): principal/interest split so repayments stop distorting spend
ci / lint-test (push) Successful in 41s
A loan repayment is not an expense. A $3,000 mortgage repayment is roughly
$1,200 of principal (equity — a balance-sheet move) and $1,800 of interest (the
only part that is genuinely spend).

Migration 0014:
- transactions.principal_amount / interest_amount, populated only when the lender
  itemises the split on the repayment row
- statements.interest_rate, scheduled_repayment, repayment_frequency,
  redraw_available, loan_term_months
- normalize_repayment_frequency() + trigger, so "Fortnightly", "Bi-Weekly" and
  "Every 2 weeks" all land on 'fortnightly'

Two statement shapes are handled. Where the loan statement lists repayments and
"Interest Charged" as separate rows (the common Australian case), transaction_type
already does the work. Where a lender itemises the split on the repayment row,
that row is typed 'payment' and would be skipped entirely — losing the interest.
New SPEND_ROWS / SPEND_BASE fragments in analytics-sql.ts count such rows at
interest_amount instead of amount.

Adds the loan_interest category (+ colour, and the missing fees colour).

Verified against the live DB with a synthetic ANZ home loan statement: a $3,000
itemised repayment plus a $10 service fee moved April spend by exactly $1,810,
with the $1,200 principal excluded and still retained on the row. Test data
removed and the figure confirmed back at its original value.
2026-07-26 00:21:01 +10:00
siddharthd 25ef504574 feat(statements+analytics): normalise statement_type; fix analytics scoping
ci / lint-test (push) Successful in 38s
Groundwork for importing bank and loan statements alongside credit cards.

statement_type was whatever free text Gemini put in account_type ('Credit Card',
'credit card', 'credit_card', 'Business Card', 'ACCESS ADVANTAGE',
'multi-currency account'). The UI coped only by doing .includes("card"), which
breaks as soon as bank and loan statements arrive.

- Migration 0013 adds normalize_statement_type() + a BEFORE INSERT/UPDATE
  trigger and a CHECK constraint over credit_card|transaction|savings|loan|
  offset|investment|other. The trigger means the N8N workflow keeps working
  unchanged while it still sends free text. Raw value stays in account_type.
  Backfilled 99 existing rows.
- src/lib/statement-types.ts mirrors the vocabulary for the UI; statements page
  now filters by the real types and headlines balance vs amount due per type.

Analytics were scoped with INNER JOIN statements + s.owner_id, which silently
dropped all 180 manual/CSV transactions (statement_id IS NULL) from every
report. Switched all six routes to LEFT JOIN + COALESCE(t.owner_id, s.owner_id)
via shared fragments in src/lib/analytics-sql.ts, so the transfers/investment
exclusion that stops card-payment double counting stays consistent. Also
extended that exclusion to trip analytics, which had none.

Drive-by: /api/analytics/subscriptions was returning 500 on an unserialisable
BigInt from COUNT(*) + 1.

Verified against the live DB: monthly spend picks up the previously invisible
manual transactions (Apr 9,849.91 -> 14,286.70) and all four analytics
endpoints return 200.
2026-07-26 00:00:55 +10:00
siddharthd e0b0fc91e0 feat(rules): manual-only rules as one-click quick actions on selected transactions
ci / lint-test (push) Successful in 52s
A rule flagged manual_only never runs in the apply-all pass; instead it shows
as a button in the transactions bulk bar and applies its actions to the current
selection (conditions ignored — the selection is the condition). Recorded as a
rule_apply_run, so it reverts from Rules -> Apply History like any other run.

Motivation: tagging Home + splitting 50/50 with Sonu was two bulk actions every
time. Now it is one click, and any other combo can be defined the same way.

Extracts the action-application and snapshot logic from the apply route into
src/lib/rule-actions.ts so both callers share one implementation — splits upsert
rather than delete+reinsert, so settled flags survive.
2026-07-25 23:02:26 +10:00
siddharthd 856e1a51ab docs: agent/MCP access guide — connect + query finance data from any MCP client
ci / lint-test (push) Successful in 38s
2026-07-25 22:27:19 +10:00
siddharthd 831d30669b feat(ui): ink & copper ledger retheme + analytics redesign
ci / lint-test (push) Successful in 43s
App-wide retheme done at the token layer: Tailwind's zinc scale is remapped
to warm ink/paper neutrals and indigo to copper in globals.css, so every
page inherits the palette. Fraunces (serif display) added for page titles
and hero figures; all figures now render in mono with tabular numerals.

Analytics page redesigned around a month spine — twelve clickable columns
scaled to each month's spend that act as hero, context, and period
navigation. Adds a 'What changed' top-movers panel vs the previous month,
replaces the 8-line category trend chart with per-category sparkline small
multiples, heat-tints the six-month ledger table, and restyles the Pareto,
pace chart, and cashflow strip. Kept: Pareto, cumulative-vs-typical pace,
drill-downs, regular/occasional split.

Insights and Merchants restyled to the same kit; chart tokens centralised
in category-colors.ts (CHART). Cleared the pre-existing lint errors in
insights (typed tooltip, removed any-casts).
2026-07-19 20:37:49 +10:00
siddharthd 99af10f9ea chore: trips catch-up migration (0011) + docs for Komodo push-to-deploy
ci / lint-test (push) Successful in 43s
- prisma/migrations/0011_trips: trips table, trip_id on overrides, partial
  index — idempotent; matches DDL already applied to prod. Applied to
  personal_test (integration suite was failing on missing trips relation).
- README/CLAUDE.md: deployment is now push-to-deploy via Komodo
  (deploy-finance Procedure, Gitea webhook); compose command is fallback.
- README: migrations table completed through 0011; note that the container
  must only be reachable via Traefik (header-trust auth).
2026-07-19 20:07:09 +10:00
siddharthd 0b40924af0 fix(security+trips): auth/ownership on all API routes; trip analytics in AUD
Ten routes accepted requests with no getCurrentUser check (transactions/[id],
bulk, splits, tags-on-tx, splits/settle, statements/[id], tags, tags/[id],
merchants, participants/[id]/balance), and by-id routes did no ownership
check at all — any participant could read or modify another's data.

Adds canAccessTransactions() (owner via statement/direct, or split
participant), applies it to every transaction-scoped route, owner-scopes
statements/[id], and rescopes splits/settle in raw SQL so settlement only
touches splits the caller is party to.

Also: all trip analytics now sum COALESCE(amount_aud, amount) instead of raw
amount, matching every other analytics query — trip totals previously added
foreign-currency amounts to AUD ones unit-less.

And rules apply_split no longer delete+reinserts splits (which reset settled
flags on every run) — it upserts share_percent and removes only participants
no longer in the rule.
2026-07-19 20:07:09 +10:00
siddharthd 48ec151c15 feat(trips): trip tracking with analytics, tag conversion, and transaction assignment
Adds trips table usage across API and UI: trip CRUD, per-trip analytics
(category/daily/merchant/tag/participant breakdowns), tag-to-trip
conversion, trip assignment via transaction overrides, and trip filter
in the transactions view. Recovered from working tree after local git
corruption; feature was already live via host-context Docker builds.
2026-07-19 20:00:51 +10:00
93 changed files with 11320 additions and 596 deletions
+20
View File
@@ -0,0 +1,20 @@
{
"permissions": {
"allow": [
"Bash(npx next:*)",
"Read(//mnt/m2cache/appdata/smarthome/**)",
"Bash(docker compose:*)",
"Bash(curl -s http://localhost:4100/ -I)",
"Bash(grep:*)",
"Bash(docker port:*)",
"Bash(docker inspect:*)",
"Bash(python3 -c \"import sys,json; d=json.load\\(sys.stdin\\); [print\\(k, v['IPAddress']\\) for k,v in d.items\\(\\)]\")",
"Bash(npm install:*)",
"Bash(node_modules/.bin/vitest:*)",
"Bash(find:*)",
"Bash(xargs ls:*)",
"Bash(npm run:*)",
"Bash(docker exec postgres-personal:*)"
]
}
}
+3
View File
@@ -42,3 +42,6 @@ yarn-error.log*
next-env.d.ts
/src/generated/prisma
# Raw statement exports — real financial data, never commit
dump/
+263 -3
View File
@@ -13,12 +13,17 @@ Personal finance tracker. Bank statements are ingested via an N8N workflow (in t
## Common Commands
**Deployment is push-to-deploy via Komodo** (since 2026-07-19): pushing to `main` on
Gitea triggers the `deploy-finance` Procedure, which runs DeployStack `--build` on the
`finance` stack (files_on_host over `docker/finance/` in the smarthome repo). Just
commit and push — no manual deploy needed.
```bash
# Build and deploy (from smarthome repo root)
# Manual fallback only (from smarthome repo root), e.g. if Komodo is down
docker compose --env-file docker/common.env --env-file docker/finance/.env \
-f docker/finance/docker-compose.yml up -d --build
# IMPORTANT: docker restart does NOT pick up a new image — always use the compose command above
# IMPORTANT: docker restart does NOT pick up a new image — push to main (or use the compose command above)
# DB access
docker exec postgres-personal psql -U personal -d personal
@@ -76,7 +81,24 @@ docker exec postgres-personal psql -U personal -d personal < prisma/migrations/<
### Key Tables
- `statements` — one row per billing period per bank account
- `transactions` — line items; `statement_id` is nullable (NULL = manual entry); `reconciled_with_id` links a manual tx to its matched statement tx
- `transactions` — line items; `statement_id` is nullable (NULL = manual entry); `reconciled_with_id` links a manual tx to its matched statement tx; `payment_method` (migration 0016) is `card | cash | bank_transfer | other`, NULL = unknown
### Cash and reconciliation
`payment_method = 'cash'` excludes a transaction from reconciliation via the
`notCash()` fragment in `queries.ts`. Cash never appears on a statement, so
without it a cash entry sits in the pending queue forever being offered matches
within 3 days and 1% on amount — and accepting one is silently destructive:
reconciled manual rows are filtered out of every query, so the cash spend
disappears while the card transaction it matched claims to be that same spend.
Only cash is excluded. Bank transfers *do* appear on a statement now that
transaction accounts are imported, and NULL means unknown — both stay
candidates, preserving the behaviour of every pre-existing row.
ATM withdrawals stay categorised as spend rather than `transfers`. Treating them
as transfers only works if every cash purchase is logged; with partial logging
it silently deletes the unlogged remainder from spend totals.
- `transaction_overrides` — user corrections to AI-extracted data (category, merchant, notes)
- `transaction_splits` — shared expense tracking (participant, share_percent, settled)
- `split_payments` — recorded cash settlements between participants
@@ -87,6 +109,75 @@ docker exec postgres-personal psql -U personal -d personal < prisma/migrations/<
- `participants` — people; `id=1` is "Me" (the primary user)
- `account_owner_mappings` — persists bank+account → owner assignments
### Shared expenses and settlement — read before touching
The model is under active redesign. See `docs/shared-expenses-design.md` for the
proposal and what is already decided. Three traps:
**`transaction_splits.settled` is dead data.** It is `false` on every row. Its
only writer was `/api/splits/settle`, removed in `3f04cbd` because nothing called
it and one request could mark all of a participant's splits settled. Do not build
on this flag until settlement contexts exist.
**`getParticipantBalances` computes `splits − payments` and is correct.** Do not
"fix" it to exclude settled splits — the payments that settled them are still
subtracted, so you would double-count. The two settlement models (running tab vs
per-split flag) must not be mixed.
**Settlement cannot be attributed per trip.** `split_payments` records only
from/to/amount/date. Any per-trip settled/unsettled figure is fabricated; the
trip view used to show one and always reported 100% unsettled. Trips show share
only, and point at `/shared` for real balances.
Also: settlements already exist twice. Four of eight `split_payments` match an
offset-account credit exactly on amount and date, with `linked_transaction_id`
populated on only one. And Sonu's loan contributions (`…emi` in the offset
account, 39 rows, $37,980.24) are categorised `transfers`, indistinguishable from
ordinary internal transfers.
**Partial split coverage inside a category is usually correct, not a gap.** Only
*shared* items are split. `utilities` sits at 69% yours because Globird, OVO, GWW
and home telecoms are split while Telstra, Vodafone, Optus and JB Hi-Fi Mobile
are personal. `subscriptions` is 91% because Uber One, Amazon Prime and OnePass
are shared while Claude, OpenAI, Anthropic, OpenRouter, You.com, LinkedIn, Xero,
Billdu, Spotify and Patreon are not. `fees` and `charity` are 100% yours and
correct. Check the merchants before concluding a rule was never applied — a
category-level ratio that "looks wrong" usually is not.
Splits exist in this app from **2026-01-09** only; earlier splits lived in
SplitMyExpenses. So a trailing-12-month per-person series splices six months of
gross onto six months of net. Use Feb–Jun 2026 for anything per-person.
### The shared loan
The loan is a **separate ledger**, not a shared expense and not a settlement
context — a contribution must never be able to settle a dinner. Sonu's obligation
is a fixed 50% of the repayment; actual contributions vary, and the difference is
a tracked receivable ($4,000.00 over 2025-07 → 2026-06).
Do not derive the share from actual payments. During her leave the obligation did
not change, only the payment did — a percentage-of-actual model would silently
redefine her share as 30% and make the shortfall vanish.
Loan interest reconciles exactly: `repayments − interest − fees = balance
reduction`. It stays categorised `loan_interest` and counts as spend — over 12
months $63,500 of cash left and debt fell $44,127.36, and the $16,523.64
difference bought nothing. Excluding it would leave the balance sheet unable to
reconcile cash out against equity gained.
**The repayment is voluntarily above contracted, and the gap is the largest
flexible cost in the whole picture.** Contracted is $1,190.54/fortnight
($2,579.50/mo annualised); the actual direct debit is $2,500.00/fortnight
($5,416.67/mo). That is $2,837.17/mo of overpayment, and it is *not* sunk — it
shows up as `statements.redraw_available`, which grew $62,387.17 → $81,017.42
across the two most recent loan statements. Sonu returned to $1,250/fortnight in
July 2026 after the reduced $750 period during her leave.
Treat the repayment as two figures whenever asking "what does this cost me":
the contracted floor and the actual. `scheduled_repayment` holds the actual
($2,500), not the contracted minimum — the contracted figure is not in the DB at
all. See `docs/expense-baseline.md`.
### Import Date (`created_at`)
`transactions.created_at` is the import timestamp (DB default `now()`). In the transactions and shared views, the "Imported" column shows:
@@ -101,6 +192,80 @@ Conditions are AND-evaluated. Fields: `merchant_normalized`, `description`, `cat
`contains` and `equals` operators are case-insensitive (both sides `.toLowerCase()`).
**A rule with zero conditions matches every transaction.** Both apply paths use
`conditions.length === 0 || conditions.every(...)`. Rule 43 "Home 50/50 Sonu" has
no conditions and a 50/50 split action — applying it blindly would split all
~3,700 transactions with another participant. That is what `manual_only` is for:
those rules are excluded from bulk runs and fire from the transactions page
against a hand-picked selection.
### Previewing a rule before applying it
`GET /api/rules/[id]/matches` is a dry run — it writes nothing and returns only
the transactions a rule would actually *change*, with already-correct rows
summarised as a count. The Preview button on the rules page uses it.
Apply then goes through `POST /api/transactions/bulk` with `action: "apply_rule"`
and **explicit transaction ids**, not the conditions. That is the safety
property: a rule whose conditions are too broad cannot reach further than what
the preview showed and the user ticked.
Prefer this over auto-applying rules on ingestion. It fails safe, works
retroactively, and tells you which rules are consistent enough to automate later.
### Rule apply history
`rule_apply_runs` snapshots the before-state so a run can be reverted, and since
migration 0017 also records `rule_id`, `rule_name` and `source`
(`all` | `rule` | `selection`). `rule_name` is denormalised deliberately and
there is no FK to `rules` — history must stay readable after a rule is renamed or
deleted, and deleting a rule must not cascade away the audit trail.
`GET /api/rules/runs/[id]` diffs that snapshot against current values. Rows
changed by something else since the run are flagged, because reverting restores
the pre-run value and discards the later edit.
### Trusting extracted statement data
**Balance assertions are the check that works.** `getStatements` computes
`opening + movement − closing`; the statements page flags any statement that does
not reconcile. Sign depends on what the balance means — on a credit card or loan
it is what you owe, so spending increases it; on a transaction or offset account
it is what you hold. 11 pre-existing statements currently fail, ~$4,177
unexplained, including two adjacent ANZ statements off by exactly ±$230.38 (a
transaction filed against the wrong one).
**Do not derive `opening_balance` from `closing − movement`.** It is an accounting
identity, so every statement would reconcile and the check would go permanently
green. A null that reads "unverified" is worth more than a number that is right
by construction. For the same reason, do not add a totals assertion comparing
`total_debits` to the summed rows — those totals are now *computed* from the rows
(see the N8N `Parse Gemini Result` node), so that check can never fail.
**Gemini invents summary fields the statement does not print.** Wise PDFs show
only a closing balance; asked for an opening balance anyway, the model produced
11,277.08 against a truth of 0.00, and on another statement read the running
balance of the oldest row. Every transaction was extracted perfectly in both
cases — verified row for row against the CSV exports. When a balance assertion
fails, suspect the summary before the transactions.
**Gemini drops rows silently on long tables.** `finishReason` was `STOP`, not
`MAX_TOKENS`, so raising `maxOutputTokens` does not help. This did *not* actually
occur on the Wise imports (that was the summary bug above), but it is why an
empty statement must not throw: a document that errors never gets tagged, so it
is re-fetched every poll forever and blocks everything behind it in the queue
(`ordering=-created`, `page_size=1`).
**FX is per transaction date**, via Frankfurter (ECB daily, free, no key), with
weekends resolving to the prior publication. A single spot rate across a 15-month
statement is wrong by up to 20%. Wise's own rates are more accurate in principle
but differ by only 0.05% and exist on 44 of 194 rows, so mixing bases is not
worth it.
**When comparing CSV exports to extracted data, order by full timestamp
including milliseconds.** Two of one statement's rows are 1ms apart; dropping the
fraction reversed them and produced a bogus opening balance.
## Development Patterns
### Adding a new API route
@@ -122,6 +287,62 @@ Two files only:
- Owner filter pattern: `WHERE COALESCE(t.owner_id, s.owner_id) = $1`
- Bank name pattern: `COALESCE(s.bank_name, 'Manual') as bank_name`
Analytics queries must import the fragments from `src/lib/analytics-sql.ts`
(`STATEMENTS_JOIN`, `OWNER_SCOPE`, `EFFECTIVE_CATEGORY`, `EXCLUDE_NON_SPEND`)
rather than hand-rolling them. Two failure modes they exist to prevent:
- An `INNER JOIN statements` + `WHERE s.owner_id = $1` silently drops every
manual/CSV transaction (`statement_id IS NULL`).
- Spend must exclude the `transfers` and `investment` categories. Once bank
statements are imported alongside card statements, a credit-card payment
appears twice — as a debit leaving the bank account and as the underlying
purchases on the card statement. Excluding `transfers` is what nets it out.
Use the `EXCLUDE_NON_SPEND` fragment: a bare `category NOT IN (...)` evaluates
to NULL for uncategorised rows and drops them from totals.
### Statement types
`statements.statement_type` is constrained to `credit_card | transaction |
savings | loan | offset | investment | other`. Migration 0013 added a
`normalize_statement_type()` SQL function plus a BEFORE INSERT/UPDATE trigger, so
the N8N workflow can keep sending raw free text (`'ACCESS ADVANTAGE'`, `'Business
Card'`) and the DB normalises it on write. The raw extracted value is preserved in
`account_type`.
The TypeScript mirror is `src/lib/statement-types.ts` — keep the list, the SQL
function, and the CHECK constraint in sync when adding a type.
### Loans
A loan repayment is **not** an expense. It is part principal (equity, a
balance-sheet move) and part interest (the only part that is spend). Migration
0014 adds:
- `transactions.principal_amount` / `interest_amount` — populated only when the
lender itemises the split on the repayment row itself
- `statements.interest_rate`, `scheduled_repayment`, `repayment_frequency`,
`redraw_available`, `loan_term_months`
Two statement shapes, both handled:
1. **Separate rows** (the common Australian case) — the loan statement lists
repayments and "Interest Charged" separately. `transaction_type` alone is
enough: `interest` rows count as spend, `payment` rows don't. No split columns
needed.
2. **Itemised repayment row** — some lenders print principal and interest on the
repayment line. That row is typed `payment`, so it would be skipped entirely
and its interest lost. The `SPEND_ROWS` / `SPEND_BASE` fragments in
`analytics-sql.ts` handle it: a row with a non-null `interest_amount` counts
as spend, valued at `interest_amount` rather than `amount`.
The N8N `Parse Gemini Result` node only accepts a split when both parts are
present *and* they sum to the row amount (±2c) — a half-extracted split would
silently misreport spend, so it is discarded rather than trusted.
Loan interest uses the `loan_interest` category; principal repayments use
`investment` (excluded from spend, surfaced on the investments line in monthly
analytics).
### Prisma
The schema at `prisma/schema.prisma` covers all tables. The generated client (gitignored) must be regenerated after schema changes:
@@ -130,8 +351,47 @@ cd /mnt/m2cache/appdata/finance-app && npx prisma generate
```
Docker builds run `npx prisma generate` automatically. Do not commit `src/generated/prisma/` — it is gitignored.
## Agent / MCP Access
Agents read this DB through the read-only `postgres-personal` MCP server (lives in the
`personal-agent-gateway` repo, not here): `agent_ro` role, SELECT-only, SQLGlot guardrail,
100-row cap, every call audited to `mcp_query_log`. See `docs/agent-access.md` for the tool
list, the five analysis views, and per-client setup (Claude Code, Codex, Hermes).
Two things to remember when changing the schema: the agent views are created by
`smarthome/personal-agent/migrations/006_agent_read_role_views.sql` (not Prisma) and read
`transactions`/`statements`/`expense_metadata` columns directly — rename a column and they
break or go stale. And the views are **not** owner-scoped and do **not** merge
`transaction_overrides`, so agent numbers can differ from the UI.
## Known Gaps / TODOs
See `README.md` → **Known Gaps / TODOs** for full details.
**Payment provider tracking**: `merchant_normalized` currently conflates payment provider (PayPal, Afterpay, Zip) with the actual merchant. Plan: add `payment_provider` column, update Gemini prompt to extract it separately, backfill from `merchant_name` patterns, surface in UI filters.
### Open as of 2026-07-26
- **Shared expenses redesign** — `docs/shared-expenses-design.md`. Phase 0 done;
Phases 1–4 unbuilt. Deliberately paused to live with the current behaviour
before committing to a model designed in one session.
- **Expense baseline / emergency reserve** — `docs/expense-baseline.md`. One-off
analysis, nothing built. Records four data corrections the raw numbers need
(misfiled Raiz/super/brokerage debits, `other` credits read as negative spend,
`government` conflating ATO with rates/rego, `fees` being mostly annual) and
why only Feb–Jun 2026 is trustworthy for per-person figures.
- **11 statements fail the balance assertion**, ~$4,177 unexplained. Predates
this work. One ANZ statement is off by exactly $0.50, traced to a misread digit
in fee rows ($5.00 vs $5.50).
- **28 Up Bank debits are categorised `other`** ($3,760.74). Up only categorised
16 of 88 rows. The `Payee` field is populated throughout, so merchant rules plus
the rule preview should clear most of it.
- **Up item sales are categorised `income`** ($4,238.04 across 19 credits — iPad,
drone, camera). Correct in that they are excluded from spend, but it mixes
asset disposals into the income line alongside salary.
- **`payment_method` is not shown in the transactions list** — settable on create
and edit only. Worth a column or filter if cash becomes routine.
- **Raw statement exports live in `dump/`**, gitignored since `31a8177`. They were
committed by accident in `030490e` and remain in that commit's history; the repo
has no GitHub remote, so exposure is limited to the local Gitea. Purging history
was offered and not actioned.
+28 -1
View File
@@ -343,6 +343,10 @@ docker exec postgres-personal psql -U personal -d personal \
| `0005_rules` | `rules` |
| `0006_budgets` | `budgets` |
| `0007_cashflow` | `amount_aud`, `exchange_rate_to_aud` on transactions; `exchange_rate_to_aud` on statements |
| `0008_my_share_percent` | `my_share_percent` on `transaction_overrides` |
| `0009_split_payments` | `split_payments` |
| `0010_csv_import_reconcile` | `reconciled_with_id`, CSV import support |
| `0011_trips` | `trips`, `trip_id` on `transaction_overrides` (catch-up — was applied directly) |
> `paperless_doc_id` on statements and the `uq_statements_paperless_doc_id` index were added directly (not tracked in a migration file).
> `owner_id` on transactions and `statement_id` made nullable were applied directly (March 2026) to support manual transaction entry without a fake statement.
@@ -369,9 +373,27 @@ Currently `merchant_normalized` conflates the *payment provider* with the *merch
---
## Agent Access (MCP)
LLM agents read this data through the read-only `postgres-personal` MCP server (7 typed
finance tools + guarded `adhoc_query`, `agent_ro` role, 100-row cap, `mcp_query_log`
audit). It's a stdio server, so any MCP client can use it — Hermes, Claude Code, Codex,
Claude Desktop — locally via `docker exec` or remotely over SSH.
**→ [docs/agent-access.md](docs/agent-access.md)** — architecture, tool + view reference,
per-client setup, and what changing the schema means for the agent views.
---
## Deployment
Runs as a Docker container alongside the rest of the home lab stack. Build and deploy:
Runs as a Docker container alongside the rest of the home lab stack.
**Push-to-deploy (default, since 2026-07-19)**: pushing to `main` on Gitea fires a
webhook to Komodo's `deploy-finance` Procedure, which redeploys the `finance` stack
with `--build`. CI (Gitea Actions) runs lint + unit tests on the same push.
**Manual fallback** if Komodo is unavailable:
```bash
# From smarthome repo root
@@ -379,4 +401,9 @@ docker compose --env-file docker/common.env --env-file docker/finance/.env \
-f docker/finance/docker-compose.yml up -d --build
```
The container is only reachable via Traefik (`https://finance.bosecamp.com`, forward-auth
sets `X-Forwarded-User`) plus a `127.0.0.1`-bound host port for on-box debugging — the
app trusts the `X-Forwarded-User` header, so it must never be directly reachable from
the LAN.
The container uses Next.js standalone output. `@prisma/adapter-pg` and `pg` are listed in `serverExternalPackages` in `next.config.ts` to ensure they are included in the standalone bundle.
+238
View File
@@ -0,0 +1,238 @@
# Agent Access — querying the finance data from an LLM agent
How an AI agent (Hermes, Claude Code, Codex, Claude Desktop, …) reads the finance
database. **Read-only, audited, row-capped.** Agents never write to `personal`.
The read path is an MCP server — `postgres-personal` — that lives in the
[`personal-agent-gateway`](ssh://git@localhost:2222/siddharthd/personal-agent-gateway.git)
repo at `mcp-servers/postgres-personal/`. This app owns the data; that repo owns the
server. Keep both in mind when changing the schema (see [Schema changes](#schema-changes-that-affect-agents)).
---
## Architecture
```
agent client (Hermes / Claude Code / Codex)
│ stdio (JSON-RPC, MCP)
▼
server.py ── guardrails.validate_select (SQLGlot: single SELECT, LIMIT ≤ 100)
├── PG_DSN_RO → role agent_ro (SELECT only, statement_timeout 5s) → queries
└── PG_DSN_LOG → role agent_log (INSERT into mcp_query_log only) → audit
```
Both roles, the audit table, and the five analysis views are created by
`smarthome/personal-agent/migrations/006_agent_read_role_views.sql` — **not** by this
repo's Prisma migrations. Passwords are supplied at apply time from Infisical
(`homelab-w-ae9 / prod / /agent-gateway`), never stored in the SQL file.
Defence in depth, in order:
1. `agent_ro` has no write grants at all — the DB refuses writes regardless of the SQL.
2. `validate_select` parses every SQL string (typed tools and `adhoc_query` alike) and
rejects anything that isn't one plain `SELECT`, plus `pg_sleep`/`pg_read_file`/
`dblink`/`lo_import`/`lo_export`. It rewrites `LIMIT` to ≤ 100.
3. Third-party text columns (`description`, `location`, `order_reference`, `line_items`)
come back wrapped in `<<untrusted-data>>…<</untrusted-data>>` so the runtime's system
prompt can treat statement/receipt text as data, never instructions.
4. Every call — accepted or rejected — is inserted into `mcp_query_log`
(`tool, args, sql, row_count, duration_ms, error`).
Audit review:
```bash
docker exec postgres-personal psql -U personal -d personal -c \
"SELECT at, tool, row_count, duration_ms, error FROM mcp_query_log ORDER BY at DESC LIMIT 20"
```
---
## Tools
| Tool | What it answers |
|---|---|
| `query_statements` | Statements by bank / account number / `billing_end_date` range |
| `query_transactions` | Transaction search: merchant, category, date range, amount range, description substring |
| `get_spending_summary` | Outflow for one month (`YYYY-MM`) or date range, grouped by category or merchant |
| `get_spending_comparison` | Two months side by side, sorted by absolute delta — what drove the change |
| `get_upcoming_payments` | Statements with `payment_due_date` in the next N days (1–90, default 14) |
| `get_recurring_spend` | Recurring-payment candidates (heuristic — expect false positives) |
| `adhoc_query` | One read-only `SELECT` when the typed tools can't express the question |
Views available to `adhoc_query` (all `SELECT`-granted to `agent_ro`):
| Relation | Grain |
|---|---|
| `transaction_search` | Flat per-transaction surface: transaction ⟕ statement identity ⟕ `expense_metadata`. The right default for search. |
| `merchant_monthly_spend` | month × merchant → txn_count, total_spend, avg_amount |
| `category_monthly_spend` | month × category → txn_count, total_spend |
| `cashflow_monthly` | month → total_outflow, total_inflow, net, txn_count |
| `recurring_candidates` | merchant × amount bucket → occurrences, cadence, last_seen, next_expected |
Base tables (`transactions`, `statements`, `transaction_splits`, …) are also readable —
see [README → Data Model](../README.md#data-model).
Semantics baked into the views:
- outflows = `transaction_type IN ('debit','fee','interest')`; inflows = `('payment','credit','refund')`
- amount prefers `amount_aud` (FX-normalised) over `amount`
- merchant prefers `merchant_normalized` → `merchant_name` → first 60 chars of `description`
### Two caveats worth knowing
- **No owner scoping.** Unlike the app's API routes (`COALESCE(t.owner_id, s.owner_id) = $1`),
the agent views expose *all* owners' rows. Fine while the only consumer is the household's
own assistant; it must change before any agent is exposed to a second person.
- **No `transaction_overrides` merge.** The views read `t.category` / `t.merchant_normalized`
directly, so manual corrections made in the UI are not reflected. The app's own queries use
`COALESCE(o.category_override, t.category)`. Numbers from an agent can therefore differ
slightly from the same figure in the UI.
---
## Connecting a client
The server speaks **stdio MCP**. There is no network listener, so a client connects by
*executing* it. The easiest correct way is to exec it inside the `hermes` container: the
repo is bind-mounted there (`/mnt/user/projects/personal-agent-gateway` → `/opt/data/repo`),
the venv and deps already exist, `PG_DSN_RO`/`PG_DSN_LOG` are already in the container env,
and `postgres-personal` resolves on `networks_internal`.
The canonical command, used by every recipe below:
```bash
docker exec -i hermes /opt/data/venvs/pgp/bin/python \
/opt/data/repo/mcp-servers/postgres-personal/server.py
```
Smoke-test it before wiring a client in:
```bash
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}' \
'{"jsonrpc":"2.0","method":"notifications/initialized"}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
| docker exec -i hermes /opt/data/venvs/pgp/bin/python \
/opt/data/repo/mcp-servers/postgres-personal/server.py 2>/dev/null | head -2
```
### Claude Code (on the Unraid host)
```bash
claude mcp add postgres-personal -s user -- \
docker exec -i hermes /opt/data/venvs/pgp/bin/python \
/opt/data/repo/mcp-servers/postgres-personal/server.py
```
Then `/mcp` in a session to confirm the seven tools are listed.
### Claude Code / Claude Desktop (from a laptop, over SSH)
Same command, tunnelled — stdio doesn't care what carries it:
```bash
claude mcp add postgres-personal -s user -- \
ssh unraid docker exec -i hermes /opt/data/venvs/pgp/bin/python \
/opt/data/repo/mcp-servers/postgres-personal/server.py
```
Needs key-based SSH to the host (Tailscale or LAN) and a non-interactive shell. For
Claude Desktop, the same `command` / `args` go in `claude_desktop_config.json` under
`mcpServers`.
### Codex CLI
`~/.codex/config.toml`:
```toml
[mcp_servers.postgres-personal]
command = "docker"
args = [
"exec", "-i", "hermes",
"/opt/data/venvs/pgp/bin/python",
"/opt/data/repo/mcp-servers/postgres-personal/server.py",
]
```
(Prefix `args` with `["unraid", "docker", …]` and set `command = "ssh"` for the remote case.)
### Hermes
Already wired — `mcp_servers.postgres-personal` in `/mnt/user/appdata/docker/hermes/config.yaml`
(template: `personal-agent-gateway/spike/hermes/config.yaml.example`). It runs the same
venv and script directly rather than via `docker exec`, since it *is* the container.
### Running the server outside `hermes`
Only needed if `hermes` is down or you want isolation. Two constraints: Python ≥ 3.11 with
`mcp`, `psycopg[binary]`, `sqlglot`; and network reach to `postgres-personal`, which is
**not** published to the host — it only resolves on the `networks_internal` Docker network.
So run it in a container on that network, passing the DSNs:
```bash
docker run -i --rm --network networks_internal \
--env-file /mnt/user/appdata/docker/hermes/.env \
-v /mnt/user/projects/personal-agent-gateway:/app \
personal-agent-gateway python /app/mcp-servers/postgres-personal/server.py
```
A bare host venv would need the container's current bridge IP in the DSN instead of the
hostname, which breaks on every recreate — don't.
### Secrets
`PG_DSN_RO` and `PG_DSN_LOG` live in `/mnt/user/appdata/docker/hermes/.env` (canonical
copies in Infisical `/agent-gateway`). Never paste them into a client config, a
`claude mcp add` command line, or this repo — the `docker exec` recipes above inherit them
from the container, which is precisely why they're preferred.
---
## Direct SQL (humans and one-off scripts)
For ad-hoc analysis where an agent isn't in the loop, skip MCP:
```bash
docker exec postgres-personal psql -U personal -d personal -c \
"SELECT * FROM cashflow_monthly ORDER BY month DESC LIMIT 12"
```
That's the full-privilege `personal` role — no guardrail, no row cap, no audit row. Use
`agent_ro` if you want the same safety envelope an agent gets.
---
## Making this available more widely
Today: any MCP client that can run a subprocess can use it (all of the above), and any
machine that can SSH to the host can too. That covers Claude Code, Claude Desktop, Codex,
and Hermes without a code change.
What it would take to go further:
- **Remote clients without SSH** — FastMCP supports `streamable-http`; `mcp.run()` in
`server.py` would become `mcp.run(transport="streamable-http")` behind Traefik with
forward-auth. Small code change, real security decision: it puts the household's
financial history behind a network listener. Not done, deliberately.
- **A second user** — requires owner scoping in the views (see caveats above) plus an
identity the server can bind to; the DSN carries no user identity today.
- **Write access** — out of scope. The write path is the app's API routes with
`getCurrentUser()`; `agent_ro` should stay SELECT-only.
---
## Schema changes that affect agents
The views in `006_agent_read_role_views.sql` read `transactions`, `statements`, and
`expense_metadata` directly. If you rename or drop a column those views use, re-apply the
migration in the smarthome repo — a Prisma migration here won't do it, and the views will
either break or silently go stale:
The file is idempotent (`CREATE OR REPLACE VIEW`, guarded role creation) — re-applying is
safe. It needs the `agent.ro_password` / `agent.log_password` settings supplied at apply
time from Infisical; follow the apply instructions in the header of the SQL file itself
(`/mnt/user/appdata/smarthome/personal-agent/migrations/006_agent_read_role_views.sql`)
rather than piping it in blind.
New tables are readable by `agent_ro` automatically (`ALTER DEFAULT PRIVILEGES`), but new
*views* need an explicit `GRANT SELECT … TO agent_ro`.
+211
View File
@@ -0,0 +1,211 @@
# Monthly expense baseline and emergency reserve
Analysis run 2026-07-26. **One-off analysis, not a feature** — nothing in the app
computes these numbers. Read "Reproducing this" before trusting a restated figure.
The question: how much should be held in reserve to cover 6–12 months of expenses?
## Answer
| Scenario | $/mo | 6 months | 12 months |
|---|---:|---:|---:|
| Survival — contracted loan repayment, essentials only | 3,040 | 18,250 | 36,500 |
| **Realistic — contracted loan, + dining and charity** | **4,140** | **24,800** | **49,600** |
| Status quo — keep overpaying the loan, normal life ex-travel | 5,557 | 33,500 | 67,000 |
Use the middle row. The survival row assumes dining is cut to zero and stays
there, which is not a plan anyone executes for six months.
Against that, liquidity already available (statements 133 and 131, 2026-06-30):
| | |
|---|---:|
| Loan redraw | 81,017.42 |
| Offset balance | 8,753.00 |
| **Accessible** | **89,770.42** |
That is 3.6× the six-month target and 1.8× the twelve-month one. Redraw grew
$62,387.17 → $81,017.42 across the last two loan statements, matching the
overpayment rate — the money spent killing the loan faster is still reachable.
**Caveat on counting redraw as the reserve.** It is available at AMP's
discretion, and lenders reduce or freeze it exactly when a borrower looks
distressed — which is when it would be needed. The rate also moved 5.54% → 6.29%
between the two statements, so redrawn funds cost more than they did. Hold some
genuine cash; it does not need to be $50,000.
## This is *your* outgoings, not household spend
The app only sees accounts that get imported. Sonu's own spending on the
household is invisible to it. Grocery spend reads as ~$300/mo gross on 4–10
transactions, which is implausible for a household and is partly explained by her
paying from her own account.
For "how much reserve do **I** need" that blind spot does not matter — your own
outgoings is the correct measure. Do not relabel these figures as household
totals; they are not, and they would be wrong by an unknown amount.
## The loan has two floors
This is the largest single lever and the reason there are three scenarios.
| | $/fortnight | $/mo annualised | Your 50% |
|---|---:|---:|---:|
| Contracted minimum | 1,190.54 | 2,579.50 | **1,290** |
| Actual direct debit | 2,500.00 | 5,416.67 | **2,708** |
| Voluntary overpayment | 1,309.46 | 2,837.17 | 1,419 |
Dropping to contracted cuts your loan cost by $1,418/mo. Sonu's obligation is a
fixed 50% of the repayment (see CLAUDE.md → "The shared loan"), so it falls with
it. Her rate returned to $1,250/fortnight in July 2026 after the reduced $750
period during her leave.
## Baseline composition
Built from **Feb–Jun 2026** — the months where split data is trustworthy — with
annual items annualised over 12 rather than divided by the 5-month sample.
| Essential | $/mo | Note |
|---|---:|---|
| Loan (contracted, your 50%) | 1,290 | 2,708 at the current actual rate |
| Transport | 326 | |
| Insurance | 280 | annualised; your 55% |
| Utilities | 278 | shared energy/water + personal mobile |
| Subscriptions | 204 | shared household + personal/AI |
| Groceries | 200 | see the blind-spot note above |
| Card + package fees | 175 | annualised — see below |
| Health | 167 | |
| Rates + rego | 122 | annualised, your share |
| **Essential** | **3,042** | |
| + dining 675, charity 422 | 4,139 | charity is a Smith Family sponsorship commitment |
| + typical shopping | ~4,800 | median 657, **not** the 1,709 mean |
**Travel is excluded throughout.** At $3,153/mo of your share even post-cutover it
would roughly double every figure, and it is the first thing that stops.
## Four corrections the raw data needed
Any restatement that skips these will be wrong. None are fixed in the data yet.
**Micro-investing counted as spend.** Raiz ($9,406 / 27 rows), Vanguard Super
($500) and moomoo ($300) sit in `other` as debits — $10,206/yr, ~$850/mo of
phantom spend. These belong in `investment`, which is already excluded.
**Incoming money counted as negative spend.** 17 rows in `other` typed `credit`
($5,622 in the window). `SPEND_SIGNED` negates credits so refunds cancel
purchases, but these are not refunds — they are money arriving. June 2025 shows
*minus* $7,814 of total spend because two Wise credits of ~$16.7k each landed in
`other`.
**`government` is two unrelated things.** $25,554 of ATO payments (one annual
bill, routed through Zen B2B and RewardPay to earn points) versus $2,054 council
rates and $875 rego. Tax is not a monthly living cost and falls with income
anyway; rates and rego are non-negotiable. Splitting them moves this line from
$2,411/mo to $244/mo.
**`fees` is mostly annual.** Of $2,599 post-cutover, $1,750 is an annual card fee
and $349 a loan package annual fee. Recurring is ~$175/mo annualised, not the
$520/mo the 5-month mean implies.
## Splits: what is trustworthy and what is not
Splits exist in this app from **2026-01-09** only; before that they were tracked
in SplitMyExpenses. So a trailing-12-month per-person series splices six months
of *gross* onto six months of *net* and is not a series at all. Use Feb–Jun 2026.
**Partial split coverage within a category is usually correct, not a gap.** This
was misdiagnosed once during the analysis. Verified composition:
| Category | Your share | Split | Unsplit |
|---|---:|---|---|
| utilities | 69% | Globird, OVO, GWW, home telecoms | Telstra, Vodafone, Optus, JB Hi-Fi Mobile |
| subscriptions | 91% | Uber One, Amazon Prime, OnePass | Claude, OpenAI, Anthropic, OpenRouter, You.com, LinkedIn, Xero, Billdu, Spotify, Patreon |
| fees | 100% | — | credit card fees are personal |
| charity | 100% | — | personal commitment |
Only *shared* utilities and subscriptions are split. Mobile bills, AI
subscriptions and card fees are personal and correctly sit at 100%. Do not
"fix" these ratios.
## Known weak spots
- **`other` is $424–773/mo of your share and unclassified.** The single biggest
lever on accuracy. Clearing it with the rule preview
(`GET /api/rules/[id]/matches`) improves every other view at the same time.
- **Five months is a short sample**, and it contains the Europe trip and the ATO
bill. Both are excluded, but they crowd out the ordinary months. The
SplitMyExpenses CSVs would stretch it to 18 months — worth having, not
blocking, since only an *aggregate ratio per category* is needed, not row
matching, so the combined-transaction problem does not bite.
- **`/api/analytics/monthly` does not filter `reconciled_with_id IS NOT NULL`.**
48 rows are double-counted app-wide. Small, but real, and unrelated to this
analysis. The queries below do filter it.
## Reproducing this
Working queries are not checked in; they were run ad hoc against
`postgres-personal`. The shape that matters:
```sql
-- Per-category monthly distribution, your share, Feb-Jun 2026.
-- Mirrors src/lib/analytics-sql.ts, plus the corrections above.
WITH s AS (
SELECT to_char(t.transaction_date,'YYYY-MM') m,
COALESCE(o.category_override, t.category, 'other') cat,
SUM((CASE WHEN t.transaction_type IN ('refund','credit') THEN -1 ELSE 1 END)
* (CASE WHEN t.interest_amount IS NOT NULL
THEN t.interest_amount ELSE COALESCE(t.amount_aud, t.amount) END)
* COALESCE(ts.share_percent, o.my_share_percent,
100 - COALESCE((SELECT SUM(x.share_percent) FROM transaction_splits x
WHERE x.transaction_id = t.id
AND x.participant_id <> 1), 0)) / 100)::numeric(12,2) amt
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = 1
LEFT JOIN statements st ON st.id = t.statement_id
WHERE COALESCE(t.owner_id, st.owner_id) = 1
AND t.reconciled_with_id IS NULL -- see weak spots
AND ((t.transaction_type IN ('debit','fee','interest')
OR t.interest_amount IS NOT NULL)
OR t.transaction_type IN ('refund','credit'))
AND COALESCE(o.category_override, t.category, 'other')
NOT IN ('transfers','investment','income')
-- correction 1: misfiled investments
AND COALESCE(t.merchant_normalized, t.merchant_name, '')
!~* '^(Raiz|Vanguard Super|moomoo)'
-- correction 2: incoming money miscategorised as 'other' credits
AND NOT (COALESCE(o.category_override, t.category, 'other') = 'other'
AND t.transaction_type = 'credit')
AND t.transaction_date >= '2026-02-01' AND t.transaction_date < '2026-07-01'
GROUP BY 1, 2
)
SELECT cat, count(*) mths, round(avg(amt),0) mean,
round(percentile_cont(0.5) WITHIN GROUP (ORDER BY amt)::numeric, 0) median
FROM s GROUP BY cat ORDER BY mean DESC;
```
Use the **median** for anything recurring monthly and the **annualised total** for
lumpy-but-certain items (insurance, rates, rego, annual card fees). Means are
badly skewed here — shopping is 1,709 mean against 657 median.
Corrections 3 and 4 (`government`, `fees`) are not expressible as filters; they
need the category split by merchant, done by hand above.
## If this becomes a feature
The blocker is `other`, not the split model — the split data held up under
scrutiny. Sequence:
1. Recategorise Raiz / Vanguard Super / moomoo to `investment` (27 rows,
unambiguous) via the rule preview.
2. Split `government` so rates and rego separate from ATO. Probably a new
category or a tag; `government` conflates a recurring obligation with an
annual tax bill.
3. Work `other` down with the rule preview.
4. Then a baseline panel on Insights, which already carries the
Regular/Occasional split this analysis is a stricter version of
(`REGULAR_CATEGORIES` in `src/lib/categories.ts`).
A **liquidity vs baseline** view would be genuinely new rather than a restatement:
`statements.redraw_available`, offset closing balance, and the
contracted-vs-actual repayment gap are all in the schema and nothing reads them.
+287
View File
@@ -0,0 +1,287 @@
# Shared expenses, settlement, and the shared loan — design proposal
Status: **proposal, nothing built**. Written 2026-07-26 for review.
## Why this exists
Three questions have no answer in the current model:
1. Which splits does a settlement payment settle?
2. Is the Europe trip settled, separately from the ongoing household tab?
3. Whose expense is a $2,500 loan repayment when Sonu funds part of it?
They look like three problems. They are one: **the app records money moving, and
separately records who owes whom, and the two never meet.**
---
## What is actually broken
### Two settlement models, neither finished
| Model | Where | State |
|---|---|---|
| Running tab | `split_payments` (from, to, amount, date) | **in use** — 8 payments, $37,881.10 |
| Per-split flag | `transaction_splits.settled` | **never used** — all 673 splits are `false` |
They are honoured inconsistently:
- `getParticipantBalances` (the shared page) ignores `settled` entirely
- `/api/participants/[id]/balance` filters on `settled = false`
- `getTripAnalytics` reports settled/unsettled **from the unused flag**
The third is a live bug. Every trip shows 100% unsettled forever, even though
Molina has paid $20,782.79 against $19,556.07 of splits and is square.
### Settlements exist twice, unlinked
Four of the eight recorded payments match an offset-account credit exactly:
| Payment date | From | Amount | Offset transaction |
|---|---|---:|---|
| 2026-02-02 | Molina | 7,500.00 | `Transfer from - MEGHALEE BOSE mummy Pa…` |
| 2026-04-12 | Sonu | 3,779.33 | `Transfer from - MEGHALEE BOSE transfer` |
| 2026-04-21 | Molina | 1,685.24 | `Transfer from - MEGHALEE BOSE mummy split` |
| 2026-05-16 | Sonu | 4,794.06 | `Transfer from - MEGHALEE BOSE transfer` |
The same money is a `split_payments` row *and* a `transactions` row.
`split_payments.linked_transaction_id` exists but only 1 of 8 rows uses it. So a
settlement is bookkeeping that happens to resemble a bank credit, rather than
being that credit.
### The shared loan is invisible
Sonu's contributions are already in the ledger and unrecognised:
| Pattern in offset credits | Rows | Total | Meaning |
|---|---:|---:|---|
| `…emi` | 39 | $37,980.24 | Sonu's loan contribution |
| `…mummy…` | 6 | $29,721.24 | Molina's money, forwarded by Sonu |
| other Meghalee | 15 | $71,130.27 | Sonu's own settlements |
All are categorised `transfers` — correct for spend purposes, but it means a
loan contribution and an expense settlement are indistinguishable.
Meanwhile the loan itself, over the 12 imported months:
| | |
|---|---:|
| Principal repaid (`investment`, excluded from spend) | $63,500.00 |
| Interest charged (`loan_interest`, the only part counted as spend) | $16,523.64 |
At roughly $25,000/year of `emi` against ~$80,000 of annual repayments, Sonu
funds about **31%** — of both the equity being built and the interest being paid.
Today 100% of the interest counts as your spend and 100% of the equity as yours.
---
## The core problem
The model conflates two different things:
- **Money movement** — a credit landed in the offset account
- **Obligation** — someone owed someone else, and now owes less
A settlement is both. A loan contribution is both. Right now movement lives in
`transactions` and obligation lives in `transaction_splits` / `split_payments`,
with nothing joining them. That is why a payment cannot say what it settles: it
was never attached to anything in the first place.
---
## Proposed model
### 1. Settlement contexts
Splits belong to something that is settled **as a unit**. Payments name which
unit they settle. Balance is computed per context, not globally.
| Context | Splits | Settled by | State |
|---|---|---|---|
| Household (default) | ongoing | periodic payments | running tab |
| Europe 2026 | trip-bound | lump sum | closeable |
| Pre-2026 (SplitMyExpenses) | historical | settled elsewhere | **born closed** |
A closed context still contributes to analytics — you see your true share — but
contributes nothing to what anyone owes.
This answers all three opening questions, and it dissolves the `splitFrom` date
cutoff: pre-2026 splits can be applied retroactively **because they are born
into a closed context**, so they fix the analytics without creating debt. No date
guard needed, no risk of resurrecting settled obligations.
Mechanically: `settlement_contexts` table; `transaction_splits.context_id`;
`split_payments.context_id`. `transaction_splits.settled` becomes derived
("is my context closed?") or is dropped.
### 2. Payments are transactions, not a side table
A settlement is the offset-account credit. `split_payments` becomes a thin
attribution layer over a real transaction rather than a parallel record of it:
- Populate `linked_transaction_id` on all existing payments where a match exists
- On ingestion, an incoming credit that looks like a settlement is *proposed* as
one for confirmation, rather than silently becoming `transfers`
- A payment with no matching transaction (cash, or an account not imported)
stays as a manual row — the model must tolerate that
### 3. The shared loan — a separate ledger
Not a settlement context. The loan is a jointly funded asset with its own
obligation, and mixing it with expense settlement would let a contribution
accidentally settle a dinner.
- `emi` credits are recognised as **contributions**, not generic transfers
- A **contribution schedule** states what is owed per period (50% of the
repayment), independent of what was actually paid
- The running difference is a **receivable** — currently $4,000.00
The schedule matters: during Sonu's leave the obligation did not change, only the
payment did. A percentage-of-actual model would silently redefine her share as
30% and make the shortfall disappear.
---
## Migration path
### Phase 0 — DONE (2026-07-26, commit `3f04cbd`)
Stop the trip view reporting a settlement breakdown it cannot compute.
The original plan was "make `getTripAnalytics` and `getParticipantBalances`
agree". **That plan was wrong** and reading the code before building is what
caught it:
- `getParticipantBalances` is *not* buggy. It computes `splits − payments`,
which is coherent. Excluding settled splits there while still subtracting the
payments that settled them would have double-counted and broken a working page.
- The real defect was narrower: the trip view showed Settled/Unsettled from
`transaction_splits.settled`, which nothing sets. A correct per-trip figure is
not computable at all, because `split_payments` has no trip attribution.
So the fix was **subtractive**: the trip view now shows each participant's share
and points at Shared for what is actually owed.
Also removed `/api/splits/settle` — unreachable from the UI but live on its URL,
where one call with `participant_id` would mark every one of that person's splits
settled, writing a flag nothing reads.
`transaction_splits.settled` / `settled_at` still exist and are now pure dead
data. Phase 1 either repurposes them ("is my context closed?") or drops them.
### Phase 1 — settlement contexts
Add contexts; put every existing split in "Household"; every payment likewise.
Balance queries group by context. Touches `queries.ts` (both balance CTEs),
`shared/page.tsx`, `trips/[id]/page.tsx`, `split-payments/route.ts`. ~1 day.
### Phase 2 — link payments to transactions
Backfill `linked_transaction_id` for the four exact matches; flag the other four
for manual linking. On ingestion, propose a matching credit as a settlement
rather than silently categorising it `transfers`. ~half a day.
### Phase 3 — retroactive pre-2026 split
Create the "Pre-2026" closed context. Apply household split rules into it via the
rule preview (`/api/rules/[id]/matches`, built 2026-07-26) — fixes ~$97,627 of
the trailing 12 months currently shown as 100% yours. Then delete the `splitFrom`
cutoff entirely.
**Validate the ratio first.** This assumes today's 50/50 held through 2025. The
SplitMyExpenses CSVs should be used to *check* that assumption — not to
reconcile, since transactions were sometimes combined and exact matching is
impossible.
### Phase 4 — loan ledger
Contribution schedule, contributions recognised from `emi` credits, running
receivable. Independent of contexts — the loan is a separate ledger. ~1–2 days.
---
## Decisions taken (2026-07-26)
### The loan is separate from shared expenses
Different obligations, different rhythms, different nature: one funds an asset,
the other funds consumption. They do not share a settlement context and a
contribution is never a settlement.
### The share is 50/50, fixed — with the shortfall tracked
Not derived from actual payments, which fluctuate. Sonu's obligation is half the
repayment; the difference between obligation and actual is a **receivable**, and
it is the interesting number.
Over 2025-07-01 → 2026-06-30:
| | |
|---|---:|
| Repayments | $63,500.00 |
| Sonu's 50% obligation | $31,750.00 |
| Actually contributed (26 payments) | $27,750.00 |
| **Shortfall** | **$4,000.00** |
She never missed a fortnight; the rate changed:
| Rate | Payments | Period |
|---|---:|---|
| $1,250 | 15 | Aug 2025 – Feb 2026 (the correct 50%) |
| $1,000 | 3 | Jul 2025 (pre-adjustment) |
| $750 | 8 | Mar – Jun 2026 (leave) |
So the model needs a **contribution schedule** (expected per period) alongside
actual contributions, with the running difference as a tracked balance. A flat
percentage cannot express "obligation unchanged, payment temporarily reduced,
difference owed".
### Interest: recommended as expense, pending final call
The mechanics are as described — interest is debited to the loan and repayments
pay down the combined balance. Reconciles exactly:
134: 31,000.00 − 8,553.27 = 22,446.73 = balance reduction
133: 32,500.00 − 7,970.37 − 2,849.00 = 21,680.63 = balance reduction
But mechanics are not the same as economics. Over 12 months $63,500 of cash left
and debt fell by $44,127.36. The $16,523.64 difference bought nothing and is not
recoverable — that is an expense by definition. Excluding it leaves the balance
sheet unable to reconcile cash out against equity gained, and understates annual
cost by ~10%.
The legitimate concern is that interest is **non-discretionary**. The answer to
that is a fixed-commitments grouping alongside rent, insurance and utilities —
a presentation change, not an exclusion.
**Recommendation: keep `loan_interest` as spend, add a fixed/discretionary
split.** Flagged rather than settled: it is a judgement about what "spend" means
in your own reporting.
## Open questions
1. **Does equity need tracking per person?** If Sonu accrues a share of the
principal, that is a balance-sheet item the app has no concept of. Probably
belongs in the net-worth view rather than here.
4. **Attribution of forwarded payments.** `mummy` in the description reliably
marks Molina's money in all six known cases, but it is a description match on
a free-text field. Acceptable as a *suggestion* requiring confirmation; not as
an automatic rule.
5. **Retroactive split ratios.** Applying today's household rules to 2025
assumes the arrangement has not changed. The SplitMyExpenses CSVs could give
real historical shares, but transactions were sometimes combined, so matching
is imperfect. Recommendation: use today's ratios, accept the approximation —
the goal is a truer analytics picture, not a restated ledger.
---
## What I would not do
- **Do not** restate history from the SplitMyExpenses CSVs. The combining problem
makes exact reconciliation impossible, and the value is low: those balances are
settled and will not change.
- **Do not** make the loan a shared *expense*. It is a funded asset. Modelling it
as a recurring split would put $2,500 a fortnight of principal into spend,
which is the error migration 0014 was written to prevent.
+342
View File
@@ -0,0 +1,342 @@
# Europe 2026 — Expense Report
**Trip:** 22 days · Mar 21 – Apr 12, 2026
**Route:** Rome → Venice → Ortisei (Dolomites) → Varenna (Lake Como) → St Moritz → Lucerne → Paris
**Group:** 5 travellers — Siddharth & Meghalee (Melbourne), Molina, Sibnath & Rumna (Delhi)
**Data:** 212 tagged transactions across all cards
---
## Group Breakdown — AU vs India
The two groups fly different routes and airlines. Everything else (accommodation, trains, on-trip spending) is shared across all 5 travellers.
| | AU Group (Siddharth + Meghalee) | India Group (Molina + Sibnath + Rumna) |
|---|---:|---:|
| Flights | $2,164 | $6,151 |
| Share of shared costs | $12,577 | $18,866 |
| **Group total** | **$14,741** | **$25,017** |
| Per person | $7,371 | $8,339 |
**Shared costs (accommodation + trains + all on-trip):** $31,443
Apportioned 2:3 by headcount — AU group (2 pax) = 40% · India group (3 pax) = 60%
| Scenario | Amount |
|---|---:|
| Total trip | $39,757 |
| **Excl. all flights** | **$31,443** |
| Excl. AU flights only (what India group is responsible for) | $37,593 |
| Excl. India flights only (what AU group is responsible for) | $33,607 |
> Australia group flights: China Eastern MEL→PVG→FCO × 2 ($1,885) + Qatar cancellation fee ($279) = **$2,164**
> India group flights: ITA Airways DEL→FCO × 3 (Azwebin, $2,696) + Air India CDG→DEL→GAU × 3 ($3,454) = **$6,151**
> India group flights are ~3× the AU group total despite flying a similar number of legs — driven by 3 pax vs 2, plus the ITA outbound on top of Air India return.
---
## Overall Summary
| | AUD |
|---|---:|
| Gross charged | $42,696.73 |
| Refunds received | −$2,939.22 |
| **Net total spend** | **$39,757.51** |
| Phase | Net Spend | % of Total |
|---|---:|---:|
| Pre-trip bookings | $23,730.02 | 60% |
| On-trip (22 days) | $16,027.49 | 40% |
**On-trip daily average:** $729/day for the group · $146/person/day
---
## Refunds & Cancellations
| Merchant | Charged | Refunded | Net | Detail |
|---|---:|---:|---:|---|
| Qatar Airways | $2,396.90 | −$2,118.10 | **$278.80** | Cancelled. Replaced with China Eastern MEL→PVG→FCO. |
| Luxury Escapes | $3,283.80 | −$820.95 | **$2,462.85** | Partial refund on Paris Adagio Montmartre. |
| FreeNow | $43.32 | −$0.17 | $43.15 | Hold reversal. |
---
## Pre-Trip Bookings — $23,730 net
### Flights
| Carrier | Passengers | Gross | Refund | Net |
|---|---|---:|---:|---:|
| ITA Airways (via Azwebin) | Delhi group (3) DEL → FCO | $2,696.34 | — | $2,696.34 |
| Air India | Delhi group (3) CDG → DEL → GAU (return) | $3,454.32 | — | $3,454.32 |
| China Eastern | Siddharth MEL → PVG → FCO | $849.05 | — | $849.05 |
| China Eastern | Meghalee MEL → PVG → FCO | $849.05 | — | $849.05 |
| China Eastern (ancillary) | Seat/baggage fees | $187.14 | — | $187.14 |
| Qatar Airways | Siddharth + Meghalee (cancelled) | $2,396.90 | −$2,118.10 | $278.80 |
| **Flights total** | | **$10,432.80** | **−$2,118.10** | **$8,314.70** |
> ITA Airways (billed as Azwebin Fiumicino) — 3 outbound tickets Delhi → Rome plus 3 sets of ancillary fees, all charged Jan 17.
> Qatar was booked first (Jan 17) and then cancelled; refund of $2,118.10 processed Mar 24 (during Rome stay). Net cancellation penalty: **$278.80**. China Eastern replaced it at $1,885.24 total — slightly cheaper.
### Accommodation
| Property | Destination | Nights | Booked via | Net Cost |
|---|---|---|---|---:|
| Fontana di Trevi area (Vrbo HA-XTP24R) | Rome | 4 | Vrbo | $2,221.66 |
| Apartment Moro 4 — Rialto | Venice | 3 | Direct | $1,410.11 |
| 174A Apartments Murata | Ortisei | 4 | Muse Holiday | $1,815.06 |
| In the heart of Varenna (Vrbo HA7B9C9J) | Varenna | 2 | Vrbo | $2,274.46 |
| Cozy Central Duplex | St Moritz | 2 | Agoda | $2,560.45 |
| Hotel Luzernerhof | Lucerne | 3 | Agoda | $1,930.07 |
| Adagio Paris Montmartre | Paris | 4 | Luxury Escapes | $2,745.24 |
| **Accommodation total** | | **22 nights** | | **$14,957.05** |
> Paris: Luxury Escapes $3,283.80 − $820.95 refund + $282.39 extra charge = $2,745.24 net.
> **Average cost per night (5 pax):** $680 · **per person per night:** $136
### Pre-booked Transport
| Date | Merchant | Route | Amount |
|---|---|---|---:|
| Jan 26 | Trenitalia (Frecciarossa Business) | Rome → Venice (5 pax) | $468.55 |
| Mar 4 | Rail Europe | Various European routes | $372.40 |
| | **Total** | | **$840.95** |
---
## On-Trip Spending — $16,027 net
### By Destination
| Destination | Dates | Net Spend | Txns | Daily Avg |
|---|---|---:|---:|---:|
| Rome *(inc. transit days Mar 19–20)* | Mar 19–24 | $2,955 | 46 | $493 |
| Venice | Mar 25–27 | $960 | 21 | $320 |
| Ortisei / Dolomites | Mar 28–31 | $3,595 | 19 | $899 |
| Varenna / Lake Como | Apr 1–2 | $863 | 16 | $432 |
| St Moritz | Apr 3–4 | $355 | 10 | $178 |
| Lucerne | Apr 5–7 | $3,422 | 22 | $1,141 |
| Paris | Apr 8–12 | $3,878 | 46 | $970 |
| **Total on-trip** | **22 days** | **$16,027** | **180** | **$729** |
---
### Rome & Transit (Mar 19–24) — $2,955
**Mar 19–20 (transit via Shanghai → Milan → Rome):**
- Glovo Milan × 4 deliveries: $93 — feeding the group across airport transit days
- Shanghai Sunny restaurant: $16 (CNY 78)
- Todis Roma groceries: $55 (manual, likely night of arrival)
**On ground in Rome:**
| Category | Key Items | Total |
|---|---|---:|
| Dining | Lione 21 EUR 90 ($148) · Suresh EUR 52 ($85) · Glovo × 4 ($179) · Faro Café ($40) · Bap Vaschette ($29) · various | ~$780 |
| Transport | FreeNow × 2 ($43) · Uber × 6 ($151) · ATAC bus ($2) · Radiotaxi ($11) | ~$210 |
| Travel | Trenitalia local ($23) · Roma Termini station tickets EUR 300 ($493) · Trenitalia EUR 275 ($452) · Trenitalia EUR 165 ($274) | ~$1,242 |
| Entertainment | St Peter's Basilica tickets: $58 | $58 |
| Groceries | Todis × 2 ($12) · F.Lli Casali ($17) · SumUp ($12) | $41 |
| Shopping | Scudieri International Florence EUR 51: $84 | $84 |
| Cash | Mar 21 cash transactions lump sum | $337 |
> **Florence day trip (Mar 22):** Trenitalia tickets $452 + $274 bought at Roma Termini ($493) and online, plus Scudieri shopping EUR 51.
> The two large Trenitalia charges on Mar 22–23 suggest additional train legs beyond Rome–Venice (possibly Florence or Naples day trip and ticket changes).
---
### Venice (Mar 25–27) — $960
| Item | Amount |
|---|---:|
| Water taxi Ferrovia → accommodation | $79 |
| Caffe Rialto Venezia (dinner) | $109 |
| Fresh pasta restaurant (Sum Dal) | $96 |
| Baci Pasta | $70 |
| Dolcemente Salato (pastries/café) | $67 |
| Farini Pizza × 3 visits | $92 |
| Tvm Rialto Diretti 2 — shopping EUR 125 | $209 |
| Muse Holiday extra charge EUR 60 | $100 |
| Uber × 2 | $48 |
| Despar groceries | $19 |
| Gelatoteca Suso + Bar Americano | $17 |
| Pasticceria Ballarin + Bar Filovia × 2 | $28 |
> Grand Canal water taxi arrival ($79) was the planned "wow moment".
> Tvm Rialto Diretti 2 (EUR 125) — likely Murano glass or quality Venetian craft souvenirs, the largest single on-trip discretionary purchase outside of gear/activities.
---
### Ortisei / Dolomites (Mar 28–31) — $3,595
The most expensive on-trip leg. Five major items account for $2,857 of it:
| Item | Amount | Detail |
|---|---:|---|
| Erich Perathon (gear shop, Val Gardena) | **$1,477** | EUR 880 — outdoor/ski clothing or equipment in Santa Cristina |
| Funivie Seceda cable car | **$441** | EUR 236+27 — the centrepiece cable car to 2,519m above Ortisei |
| Trenitalia Venice → Bolzano (5 pax) | **$528** | EUR 259.50 + EUR 55 split across two bookings |
| Taxi Demez Gregor (into valley) | **$238** | EUR 142 — private taxi from Bolzano to Ortisei (no public option for 5 with bags) |
| Funivia Lagazuoi, Cortina | **$222** | EUR 132.50 — Cortina d'Ampezzo day trip cable car |
| Despar Dolomiti (groceries) | **$201** | EUR 97.59 + EUR 22.30 across two shops |
| Ristorante Meuble Pont, Cortina | **$180** | EUR 107.50 — group dinner on Cortina day trip |
| Turonda Pizza Ortisei | $93 | |
| Istanbul Kebab + Buffet Bolzano × 2 | $111 | Transit + local meals |
| Lago di Braies chocolate stop | $21 | |
| Café Adler + Caffe Corso | $34 | |
---
### Varenna / Lake Como (Apr 1–2) — $863
| Item | Amount |
|---|---:|
| Taxi Demez Gregor (out of valley) | $239 |
| Trenitalia (onward journey) | $101 |
| Pizza e Sfizi × 2 dinners | $113 |
| Mr Panino Bellagio (lunch) | $67 |
| Bernasconi Claudia Varenna | $55 |
| Varenna 1 shop EUR 55 | $92 |
| Valli Mara Bellagio souvenirs | $71 |
| Bistro di Corti × 2 | $50 |
| Lake Bakery × 2 | $30 |
| Ristorante Liberty, Tirano | $44 |
| Groceries (Despar, Macelleria × 2) | $49 |
| Gelato + bakery | $28 |
> Bellagio day trip from Varenna was a highlight — lunch at Mr Panino, ice cream at Gilardoni Stefania, souvenirs.
> Taxi Demez again for the exit from Val Gardena (charged Apr 1, same driver/company as arrival).
---
### St Moritz (Apr 3–4) — $355
Almost entirely self-catered:
| Item | Amount |
|---|---:|
| Coop supermarket (big shop) | $114 |
| Pizzaway × 2 orders | $89 |
| Bäckerei Bad × 3 visits | $58 |
| Coop (additional) | $14 |
| Bus und Service | $22 |
| Taxi St Moritz CHF 30 | $55 |
| SBB WC | $3 |
> Despite being the highest accommodation cost per night ($1,280/night), almost nothing was spent on-trip. The group self-catered using Coop and relied on the bakery.
---
### Lucerne (Apr 5–7) — $3,422
Three large purchases dominate:
| Item | Amount | Detail |
|---|---:|---|
| Rail Europe (last-minute) | **$1,526** | EUR 911.95 — Swiss Travel Pass or multi-city rail tickets; bought while already in Lucerne |
| Daytrip.com private tour | **$1,078** | EUR 642 — private guided day tour (description: "Prague" but likely Rhine Falls or day excursion from Lucerne) |
| Rigi Bahnen (cog railway) | **$844** | CHF 461.60 — historic Rigi mountain railway, 5 pax round trip (charged Apr 10 but relates to Lucerne stay) |
| Hotel Rigi Kaltbad dining | $47 | Lunch at mountain hotel summit |
| Rigi Dorfladen shop | $37 | CHF 20 at Rigi summit village |
| Uber Eats | $94 | CHF 51.23 |
| WAL*TENZ GMBH Zurich | $82 | CHF 45.10 — dining/café in Zurich |
| QUZGYXOO-2 | $150 | CHF 82.50 — unidentified Lucerne charge |
| GO4T Luzern | $114 | CHF 62.40 — likely a guided activity or boat tour |
| Amorino Gelato + Alpineum Café | $51 | |
| Juice Paradise bubble tea | $29 | |
| SBB toilets × 4 | $11 | CHF 1.50 each — Swiss public toilets |
> The Rail Europe purchase last-minute cost $1,526 vs booking pre-trip where Swiss Travel Passes are generally cheaper. Worth pre-purchasing on future Swiss trips.
---
### Paris (Apr 8–12) — $3,878
The return leg via Basel with 4 nights in Paris:
**Transit Basel (Apr 8):**
Bahn Mi Pho CHF 69 ($126) + McDonald's CHF 51 ($93) + Weber1s bagels ($66) + Kaffeemacher coffee ($17) + Confiseur Bachmann ($22) + Acento Argentino ($26) = **$350 in Basel** for the group during travel day
**Paris spending:**
| Item | Amount | Detail |
|---|---:|---|
| Viator/TripAdvisor guided tour | $296 | USD 203.70 — skip-the-line or guided Versailles/Paris tour |
| Palace of Versailles tickets | $292 | Full group |
| Louvre Museum tickets | $277 | Full group |
| Adagio Paris hotel extra charge | $282 | EUR 169 — extra night or room upgrade |
| FC Soleil restaurant | $207 | EUR 125 — group dinner |
| Uber airport transfer (Apr 12) | $126 | EUR 75.98 — departure to CDG |
| Deliveroo × 2 | $123 | EUR 52.49 + EUR 21.90 |
| Yak and Yeti restaurant | $83 | EUR 49.90 |
| Uber Eats | $65 | |
| Wild Deer restaurant | $64 | EUR 38.20 |
| Uber trips × 5 | $192 | Multiple rides across Paris |
| Fric Frac Montmartre | $55 | EUR 33 |
| Mitao | $56 | |
| Navigo transit pass | $61 | Group metro/bus |
| Little Versailles coffeeshop | $36 | |
| Pain Pain bakery × 2 | $29 | |
| Sarl by Orsel (groceries) × 2 | $35 | |
| Various small | $49 | |
> Museums + guided tour = **$865 on Paris attractions** (Versailles, Louvre, Viator).
> Uber was heavily used in Paris — 5+ trips totalling $254 including the CDG airport transfer.
---
## Spend by Category (Net)
| Category | Net Spend | Txns | Notes |
|---|---:|---:|---|
| Travel | $31,290 | 51 | Flights, accommodation, trains, cable cars |
| Dining | $4,241 | 95 | 95 restaurant/café/delivery transactions |
| Transport | $2,636 | 35 | Uber, taxis, buses, metro passes |
| Shopping | $2,053 | 6 | Erich Perathon $1,477 + Venice/Varenna/Florence |
| Entertainment | $698 | 4 | Versailles, Louvre, Basilica, Bellagio souvenirs |
| Groceries | $589 | 15 | Despar, Coop, Todis, Macelleria |
| Other (net) | −$1,751 | 4 | Qatar refund exceeds "other" debits |
| Uncategorised | $42 | 2 | Residual |
| **Total** | **$39,757** | **212** | |
> The negative "Other" figure reflects the Qatar Airways refund ($2,118) offsetting the ITA/Azwebin ancillary fees charged in the same category.
---
## Top 15 On-Trip Transactions
| Date | Merchant | AUD | Category |
|---|---|---:|---|
| Mar 28 | Erich Perathon, Val Gardena | $1,477 | Shopping — EUR 880 gear |
| Apr 6 | Rail Europe | $1,526 | Travel — EUR 912 rail passes |
| Apr 7 | Daytrip.com | $1,078 | Transport — EUR 642 private tour |
| Apr 10 | Rigi Bahnen | $844 | Travel — CHF 462 mountain railway |
| Mar 22 | Roma Termini (train tickets) | $493 | Travel — EUR 300 |
| Mar 22 | Trenitalia | $452 | Travel — EUR 275 |
| Mar 28 | Trenitalia | $435 | Travel — EUR 260 |
| Mar 30 | Funivie Seceda | $396 | Travel — EUR 236 cable car |
| Apr 9 | Viator/TripAdvisor | $296 | Travel — USD 204 Paris tour |
| Apr 8 | Palace of Versailles | $292 | Entertainment |
| Apr 10 | Adagio Paris extra | $282 | Travel |
| Apr 8 | Louvre Museum | $277 | Entertainment |
| Mar 23 | Trenitalia | $274 | Travel — EUR 165 |
| Mar 21 | Cash transactions (Rome) | $337 | Various |
| Apr 1 | Taxi Demez Gregor | $239 | Transport — EUR 142 |
---
## Key Observations
**Flight changes cost $278.80.** Qatar was booked first (Jan 17, $2,396.90) and later cancelled; the refund of $2,118.10 came through during the Rome stay on Mar 24. China Eastern (MEL→PVG→FCO) replaced it at $1,885.24 — marginally cheaper but via Shanghai with a longer travel time.
**60% of spend was locked in before leaving Australia.** Pre-trip bookings (flights for all 5, accommodation across 7 cities, and pre-purchased trains) totalled $23,730 vs $16,027 spent on the ground.
**Dolomites was the most expensive on-trip leg** despite only 4 days — Erich Perathon EUR 880 gear purchase in Val Gardena accounts for $1,477 alone. Without it, Dolomites would be the cheapest destination per day.
**Rail spend ballooned in Lucerne.** Rail Europe EUR 912 ($1,526) bought last-minute in Lucerne was the single largest on-trip travel cost. Swiss Travel Passes are considerably cheaper when purchased outside Switzerland before travel.
**Dining: 95 transactions, $4,241 net.** The group averaged $193/day on food across 22 days ($39/person/day). Glovo delivery was the primary dining mode during transit days and in Rome (10+ orders). Paris had the most sit-down restaurant spending — FC Soleil EUR 125, Yak and Yeti EUR 50, plus multiple delivery orders.
**St Moritz: highest accommodation cost, lowest on-trip spend.** Agoda charged $2,560 for 2 nights but the group spent only $355 on-trip — almost entirely groceries and the local bakery.
**Paris Uber spend: $254 across 6+ trips** including a $126 CDG airport transfer (EUR 76). Combined with 2 Deliveroo orders and Uber Eats, rideshare/delivery accounted for ~$380 of Paris on-trip costs.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

@@ -0,0 +1,21 @@
-- Trips: group transactions (via transaction_overrides.trip_id) into named
-- trips with analytics. Catch-up migration — this DDL was applied directly to
-- the live DB when the feature shipped; idempotent so re-running is safe.
CREATE TABLE IF NOT EXISTS trips (
id SERIAL PRIMARY KEY,
owner_id INTEGER NOT NULL REFERENCES participants(id),
name VARCHAR(255) NOT NULL,
description TEXT,
start_date DATE,
end_date DATE,
color VARCHAR(20) NOT NULL DEFAULT '#6366f1',
archived BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE transaction_overrides
ADD COLUMN IF NOT EXISTS trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_tx_overrides_trip_id
ON transaction_overrides (trip_id) WHERE trip_id IS NOT NULL;
@@ -0,0 +1,10 @@
-- Manual-only rules ("quick actions"): a rule flagged manual_only is never
-- picked up by the bulk apply-all run. It exists to be fired by hand against a
-- selection of transactions from the transactions page, so its conditions are
-- irrelevant — the selection is the condition.
ALTER TABLE rules
ADD COLUMN IF NOT EXISTS manual_only BOOLEAN NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS idx_rules_manual_only
ON rules (owner_id, manual_only) WHERE manual_only = true;
@@ -0,0 +1,99 @@
-- Normalise statements.statement_type to a fixed vocabulary.
--
-- Before this migration the column held whatever free text Gemini put in
-- `account_type` ('Credit Card', 'credit card', 'credit_card', 'Business Card',
-- 'ACCESS ADVANTAGE', 'multi-currency account', ...). The UI coped only by
-- doing `.includes("card")`, which breaks as soon as bank and loan statements
-- arrive.
--
-- The raw extracted text is preserved in `account_type` — this only touches
-- `statement_type`. A BEFORE trigger normalises on write, so the N8N ingestion
-- workflow keeps working unchanged while it still sends free text.
--
-- Idempotent: safe to re-run.
CREATE OR REPLACE FUNCTION normalize_statement_type(raw TEXT)
RETURNS TEXT AS $$
DECLARE
v TEXT := lower(trim(coalesce(raw, '')));
BEGIN
IF v = '' THEN
RETURN 'other';
END IF;
-- Already canonical
IF v IN ('credit_card', 'transaction', 'savings', 'loan', 'offset', 'investment', 'other') THEN
RETURN v;
END IF;
-- Offset before loan: "Mortgage Offset" is an offset account, not a loan.
IF v LIKE '%offset%' THEN
RETURN 'offset';
END IF;
-- Loans before transaction: "home loan account" must not match '%account%'.
IF v LIKE '%loan%' OR v LIKE '%mortgage%' THEN
RETURN 'loan';
END IF;
-- Cards: covers 'Credit Card', 'credit card', 'Business Card', 'Charge Card'
IF v LIKE '%card%' THEN
RETURN 'credit_card';
END IF;
IF v LIKE '%saving%' OR v LIKE '%term deposit%' THEN
RETURN 'savings';
END IF;
IF v LIKE '%invest%' OR v LIKE '%share%' OR v LIKE '%broker%' THEN
RETURN 'investment';
END IF;
-- Everyday transaction accounts. Bank-specific product names go here; the
-- generic keywords catch the rest.
IF v LIKE '%access advantage%' -- ANZ
OR v LIKE '%complete access%' -- Westpac
OR v LIKE '%smart access%' -- CommBank
OR v LIKE '%netbank%' -- CommBank
OR v LIKE '%classic banking%' -- NAB
OR v LIKE '%multi-currency%' -- Wise
OR v LIKE '%multi currency%'
OR v LIKE '%transaction%'
OR v LIKE '%everyday%'
OR v LIKE '%cheque%'
OR v LIKE '%current account%'
OR v LIKE '%debit%'
THEN
RETURN 'transaction';
END IF;
RETURN 'other';
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-- Normalise on write so the N8N workflow can keep sending raw account_type.
CREATE OR REPLACE FUNCTION statements_normalize_type_trigger()
RETURNS TRIGGER AS $$
BEGIN
NEW.statement_type := normalize_statement_type(NEW.statement_type);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_statements_normalize_type ON statements;
CREATE TRIGGER trg_statements_normalize_type
BEFORE INSERT OR UPDATE OF statement_type ON statements
FOR EACH ROW EXECUTE FUNCTION statements_normalize_type_trigger();
-- Backfill existing rows.
UPDATE statements
SET statement_type = normalize_statement_type(statement_type)
WHERE statement_type IS DISTINCT FROM normalize_statement_type(statement_type);
-- Guard the vocabulary. Safe because the trigger runs first on every write.
ALTER TABLE statements DROP CONSTRAINT IF EXISTS statements_statement_type_check;
ALTER TABLE statements
ADD CONSTRAINT statements_statement_type_check
CHECK (statement_type IN ('credit_card', 'transaction', 'savings', 'loan', 'offset', 'investment', 'other'));
ALTER TABLE statements ALTER COLUMN statement_type SET DEFAULT 'other';
@@ -0,0 +1,85 @@
-- Loan statement support.
--
-- Migration 0013 taught the system that a statement can be a loan; this gives
-- loans somewhere to put the data that only loans have.
--
-- The core accounting problem: a loan repayment is not an expense. A $3,000
-- mortgage repayment is roughly $1,200 of principal (a balance-sheet move that
-- builds equity) and $1,800 of interest (the only part that is genuinely spend).
-- Counting the whole repayment as spending overstates expenses badly.
--
-- Two statement shapes are handled:
-- (a) The common Australian case — the loan statement lists repayments and
-- "Interest Charged" as separate rows. transaction_type already carries
-- this: 'interest' rows count as spend, 'payment' rows do not.
-- (b) Some lenders itemise principal and interest on the repayment row itself.
-- That's what principal_amount / interest_amount are for: when
-- interest_amount is set, analytics count that instead of the full amount.
--
-- Idempotent: safe to re-run.
-- Per-transaction principal/interest split (shape (b) above).
ALTER TABLE transactions
ADD COLUMN IF NOT EXISTS principal_amount NUMERIC(12,2),
ADD COLUMN IF NOT EXISTS interest_amount NUMERIC(12,2);
COMMENT ON COLUMN transactions.principal_amount IS
'Principal portion of a loan repayment, when the statement itemises it. Not spend.';
COMMENT ON COLUMN transactions.interest_amount IS
'Interest portion of a loan repayment, when the statement itemises it. This is the part that counts as spend.';
-- Partial index: only loan repayment rows carry a split.
CREATE INDEX IF NOT EXISTS idx_transactions_interest_amount
ON transactions (interest_amount)
WHERE interest_amount IS NOT NULL;
-- Loan-level terms, read off the statement header.
ALTER TABLE statements
ADD COLUMN IF NOT EXISTS interest_rate NUMERIC(6,3),
ADD COLUMN IF NOT EXISTS scheduled_repayment NUMERIC(12,2),
ADD COLUMN IF NOT EXISTS repayment_frequency TEXT,
ADD COLUMN IF NOT EXISTS redraw_available NUMERIC(12,2),
ADD COLUMN IF NOT EXISTS loan_term_months INTEGER;
COMMENT ON COLUMN statements.interest_rate IS 'Annual interest rate as a percentage, e.g. 6.140';
COMMENT ON COLUMN statements.redraw_available IS 'Funds available to redraw (loans) — not the same as available_credit on a card.';
-- Free text varies by lender ("Monthly", "Fortnightly"); normalise the common
-- spellings rather than constraining, so an unexpected value never blocks an import.
ALTER TABLE statements DROP CONSTRAINT IF EXISTS statements_repayment_frequency_check;
CREATE OR REPLACE FUNCTION normalize_repayment_frequency(raw TEXT)
RETURNS TEXT AS $$
DECLARE
v TEXT := lower(trim(coalesce(raw, '')));
BEGIN
IF v = '' THEN RETURN NULL; END IF;
-- Check fortnightly spellings before the bare '%week%' match below.
IF v LIKE '%fortnight%' OR v LIKE '%bi-week%' OR v LIKE '%biweek%'
OR v LIKE '%2 week%' OR v LIKE '%two week%' OR v LIKE '%14 day%'
THEN RETURN 'fortnightly'; END IF;
IF v LIKE '%month%' THEN RETURN 'monthly'; END IF;
IF v LIKE '%week%' THEN RETURN 'weekly'; END IF;
IF v LIKE '%quarter%' THEN RETURN 'quarterly'; END IF;
IF v LIKE '%annual%' OR v LIKE '%year%' THEN RETURN 'annually'; END IF;
RETURN v;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION statements_normalize_loan_fields_trigger()
RETURNS TRIGGER AS $$
BEGIN
NEW.repayment_frequency := normalize_repayment_frequency(NEW.repayment_frequency);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_statements_normalize_loan_fields ON statements;
CREATE TRIGGER trg_statements_normalize_loan_fields
BEFORE INSERT OR UPDATE OF repayment_frequency ON statements
FOR EACH ROW EXECUTE FUNCTION statements_normalize_loan_fields_trigger();
UPDATE statements
SET repayment_frequency = normalize_repayment_frequency(repayment_frequency)
WHERE repayment_frequency IS NOT NULL
AND repayment_frequency IS DISTINCT FROM normalize_repayment_frequency(repayment_frequency);
@@ -0,0 +1,137 @@
-- Canonical category vocabulary, enforced at the database.
--
-- Categories arrive from three places: the Gemini extraction (which writes
-- straight to Postgres from N8N, bypassing the app entirely), CSV import, and
-- manual edits. Only the DB sits under all three, so that is where the rule has
-- to live -- the same reasoning as normalize_statement_type() in 0013.
--
-- What had leaked in without it:
-- payment 19 rows $42,569.42 transaction_type written into the category
-- refund 15 rows $8,558.99 ditto
-- Shopping 13 rows $2,917.44 title-case duplicates of real categories,
-- Dining 10 rows $127.30 which every GROUP BY counted separately
-- (NULL) 3 rows $1,135.05
CREATE OR REPLACE FUNCTION normalize_category(raw TEXT)
RETURNS TEXT AS $$
DECLARE
v TEXT;
BEGIN
IF raw IS NULL OR btrim(raw) = '' THEN RETURN 'other'; END IF;
-- Title-case and spaced variants collapse onto the canonical spelling:
-- 'Home Goods' -> 'home_goods', 'Shopping' -> 'shopping'.
v := replace(replace(lower(btrim(raw)), ' ', '_'), '-', '_');
IF v IN ('groceries','dining','transport','fuel','shopping','utilities',
'entertainment','travel','health','insurance','subscriptions',
'cash_advance','government','education','rent','home_goods',
'home_maintenance','transfers','income','investment','loan_interest',
'personal_care','pets','gifts','charity','fees','other')
THEN RETURN v; END IF;
-- transaction_type leaking into the category field. A payment is money moving
-- to a card or account, which is exactly what 'transfers' means here.
IF v IN ('payment','payments','transfer') THEN RETURN 'transfers'; END IF;
-- Bare 'interest' is credit-card interest; loan interest is categorised
-- loan_interest by the extraction prompt and matches the list above.
IF v IN ('fee','bank_fees','interest') THEN RETURN 'fees'; END IF;
-- Singular/plural and common synonyms.
IF v IN ('grocery','supermarket') THEN RETURN 'groceries'; END IF;
IF v IN ('subscription') THEN RETURN 'subscriptions'; END IF;
IF v IN ('utility','bills') THEN RETURN 'utilities'; END IF;
IF v IN ('gift') THEN RETURN 'gifts'; END IF;
IF v IN ('pet') THEN RETURN 'pets'; END IF;
IF v IN ('restaurant','restaurants','food','takeaway') THEN RETURN 'dining'; END IF;
IF v IN ('petrol','gas','gasoline') THEN RETURN 'fuel'; END IF;
IF v IN ('medical','pharmacy') THEN RETURN 'health'; END IF;
IF v IN ('donation','donations') THEN RETURN 'charity'; END IF;
IF v IN ('salary','wages') THEN RETURN 'income'; END IF;
IF v IN ('investments','savings') THEN RETURN 'investment'; END IF;
IF v IN ('housing','mortgage') THEN RETURN 'rent'; END IF;
-- A 'refund' is not a category -- it says nothing about what was bought. The
-- backfill below recovers the real category from the merchant where it can;
-- anything still unknown lands in 'other' rather than inventing a category.
RETURN 'other';
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-- Recover categories for rows typed as refunds before collapsing them to
-- 'other': use the most common category that merchant has on ordinary spend.
UPDATE transactions t
SET category = m.mode_category
FROM (
SELECT merchant_normalized,
MODE() WITHIN GROUP (ORDER BY category) AS mode_category
FROM transactions
WHERE merchant_normalized IS NOT NULL
AND category IS NOT NULL
AND category NOT IN ('payment','refund','fee','interest')
AND transaction_type IN ('debit','fee','interest')
GROUP BY merchant_normalized
) m
WHERE t.merchant_normalized = m.merchant_normalized
AND t.category = 'refund'
AND m.mode_category IS NOT NULL;
-- Backfill everything else through the function.
UPDATE transactions
SET category = normalize_category(category)
WHERE category IS NULL OR category <> normalize_category(category);
UPDATE transaction_overrides
SET category_override = normalize_category(category_override)
WHERE category_override IS NOT NULL
AND category_override <> normalize_category(category_override);
CREATE OR REPLACE FUNCTION transactions_normalize_category()
RETURNS TRIGGER AS $$
BEGIN
NEW.category := normalize_category(NEW.category);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_transactions_normalize_category ON transactions;
CREATE TRIGGER trg_transactions_normalize_category
BEFORE INSERT OR UPDATE OF category ON transactions
FOR EACH ROW EXECUTE FUNCTION transactions_normalize_category();
-- Overrides keep NULL meaning "no override"; only a set value is normalised.
CREATE OR REPLACE FUNCTION overrides_normalize_category()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.category_override IS NOT NULL THEN
NEW.category_override := normalize_category(NEW.category_override);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_overrides_normalize_category ON transaction_overrides;
CREATE TRIGGER trg_overrides_normalize_category
BEFORE INSERT OR UPDATE OF category_override ON transaction_overrides
FOR EACH ROW EXECUTE FUNCTION overrides_normalize_category();
ALTER TABLE transactions DROP CONSTRAINT IF EXISTS transactions_category_check;
ALTER TABLE transactions ADD CONSTRAINT transactions_category_check
CHECK (category IS NULL OR category IN (
'groceries','dining','transport','fuel','shopping','utilities','entertainment',
'travel','health','insurance','subscriptions','cash_advance','government',
'education','rent','home_goods','home_maintenance','transfers','income',
'investment','loan_interest','personal_care','pets','gifts','charity','fees','other'));
ALTER TABLE transaction_overrides DROP CONSTRAINT IF EXISTS overrides_category_check;
ALTER TABLE transaction_overrides ADD CONSTRAINT overrides_category_check
CHECK (category_override IS NULL OR category_override IN (
'groceries','dining','transport','fuel','shopping','utilities','entertainment',
'travel','health','insurance','subscriptions','cash_advance','government',
'education','rent','home_goods','home_maintenance','transfers','income',
'investment','loan_interest','personal_care','pets','gifts','charity','fees','other'));
@@ -0,0 +1,35 @@
-- How a transaction was paid for, so cash can be told apart from everything else.
--
-- The problem this solves: getPendingReconciliations treats every unreconciled
-- manual transaction as awaiting a matching statement row. A cash purchase never
-- appears on a statement, so it sits in the queue forever and is offered matches
-- within 3 days and 1% on amount. Accepting one is silently destructive --
-- reconciled manual rows are excluded from every query, so the cash spend
-- disappears while the card transaction it matched claims to be that same spend.
--
-- NULL means unknown, which is treated as reconcilable -- the existing behaviour
-- for every row already in the table.
--
-- Only 'cash' is excluded from reconciliation. A bank transfer DOES appear on a
-- statement now that transaction accounts are being imported, so it stays a
-- reconciliation candidate.
ALTER TABLE transactions
ADD COLUMN IF NOT EXISTS payment_method TEXT;
ALTER TABLE transactions DROP CONSTRAINT IF EXISTS transactions_payment_method_check;
ALTER TABLE transactions ADD CONSTRAINT transactions_payment_method_check
CHECK (payment_method IS NULL
OR payment_method IN ('card', 'cash', 'bank_transfer', 'other'));
-- Partial index: the reconciliation query filters on this, and cash is expected
-- to stay a small minority of rows.
CREATE INDEX IF NOT EXISTS idx_transactions_payment_method
ON transactions (payment_method) WHERE payment_method IS NOT NULL;
-- Backfill the one row that is unambiguously cash. Statement-linked rows are
-- left NULL: they came from a statement, so by definition they are not cash.
UPDATE transactions
SET payment_method = 'cash'
WHERE statement_id IS NULL
AND description ILIKE '%cash transaction%';
@@ -0,0 +1,28 @@
-- Record which rule a run came from.
--
-- rule_apply_runs stored only counts ("13 matches · 13 transactions"), which is
-- not enough to decide whether to revert: you cannot tell a merchant rename from
-- a 50/50 split of your entire history. The snapshot column already holds the
-- before-state, but nothing said what was applied or why.
--
-- rule_name is denormalised deliberately. A run must stay readable after the
-- rule it came from is edited or deleted -- the history is a record of what
-- happened, not a pointer to what the rule says today.
ALTER TABLE rule_apply_runs
ADD COLUMN IF NOT EXISTS rule_id INTEGER,
ADD COLUMN IF NOT EXISTS rule_name TEXT,
-- 'all' = bulk run over every enabled rule; 'rule' = one rule by conditions;
-- 'selection' = one rule against hand-picked transactions (preview → apply).
ADD COLUMN IF NOT EXISTS source TEXT;
ALTER TABLE rule_apply_runs DROP CONSTRAINT IF EXISTS rule_apply_runs_source_check;
ALTER TABLE rule_apply_runs ADD CONSTRAINT rule_apply_runs_source_check
CHECK (source IS NULL OR source IN ('all', 'rule', 'selection'));
-- No FK to rules: deleting a rule must not cascade away the audit trail.
CREATE INDEX IF NOT EXISTS idx_rule_apply_runs_rule
ON rule_apply_runs (rule_id) WHERE rule_id IS NOT NULL;
-- Existing rows stay NULL. There is no way to recover which rule they ran;
-- the UI shows them as "unknown rule" rather than guessing.
@@ -0,0 +1,40 @@
-- Create order_reviews table
CREATE TABLE IF NOT EXISTS order_reviews (
id SERIAL PRIMARY KEY,
transaction_id INTEGER NOT NULL UNIQUE REFERENCES transactions(id) ON DELETE CASCADE,
rating TEXT,
order_again BOOLEAN,
note TEXT,
item_verdicts JSONB NOT NULL DEFAULT '[]',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Add source_message_id to expense_metadata
ALTER TABLE expense_metadata ADD COLUMN IF NOT EXISTS source_message_id TEXT;
-- 1. Admit 'credits' as a payment method.
ALTER TABLE transactions DROP CONSTRAINT IF EXISTS transactions_payment_method_check;
ALTER TABLE transactions ADD CONSTRAINT transactions_payment_method_check
CHECK (payment_method IS NULL OR payment_method IN
('card','cash','bank_transfer','credits','other'));
-- 2. Idempotency key (I7). Partial: rows without an order_reference
-- (manual entries) are unaffected.
CREATE UNIQUE INDEX IF NOT EXISTS uq_expense_source_order
ON expense_metadata (source, order_reference)
WHERE order_reference IS NOT NULL;
-- 3. I1 as a database-level guard, not just workflow logic.
-- Scoped to pipeline-created rows so manual/statement rows are untouched.
ALTER TABLE transactions DROP CONSTRAINT IF EXISTS chk_ingested_orders_after_cutover;
ALTER TABLE transactions ADD CONSTRAINT chk_ingested_orders_after_cutover
CHECK (
payment_method IS DISTINCT FROM 'credits'
OR transaction_date >= DATE '2026-01-09'
);
-- 4. Constrain the review verdict (§6.1).
ALTER TABLE order_reviews DROP CONSTRAINT IF EXISTS chk_order_review_rating;
ALTER TABLE order_reviews ADD CONSTRAINT chk_order_review_rating
CHECK (rating IS NULL OR rating IN ('again','fine','never'));
@@ -0,0 +1,17 @@
-- Deferred card reconciliation.
--
-- An order paid "MasterCard Ending in 8032 and/or credits" does not state the
-- split. The split is recoverable from the card statement -- but for a live
-- order that statement is weeks away, so the split cannot be resolved at ingest
-- time. These columns let an order be parked and revisited.
ALTER TABLE expense_metadata ADD COLUMN IF NOT EXISTS card_last4 TEXT;
ALTER TABLE expense_metadata ADD COLUMN IF NOT EXISTS currency TEXT;
ALTER TABLE expense_metadata ADD COLUMN IF NOT EXISTS flags JSONB NOT NULL DEFAULT '[]';
ALTER TABLE expense_metadata ADD COLUMN IF NOT EXISTS reconciled_at TIMESTAMPTZ;
-- The pending set: provenance recorded, no transaction yet, still waiting on a
-- statement line. Partial so it stays small regardless of table growth.
CREATE INDEX IF NOT EXISTS idx_expense_metadata_pending
ON expense_metadata (transaction_date)
WHERE transaction_id IS NULL AND reconciled_at IS NULL;
@@ -0,0 +1,13 @@
-- Which statement line settled an order's card leg.
--
-- Without this, reconcileCardLeg has no way to know a charge has already been
-- consumed, so two orders on the same card inside the match window both bind to
-- it and each books its own credits remainder -- double-counting spend.
ALTER TABLE expense_metadata
ADD COLUMN IF NOT EXISTS matched_transaction_id INTEGER
REFERENCES transactions(id) ON DELETE SET NULL;
-- One statement line settles at most one order.
CREATE UNIQUE INDEX IF NOT EXISTS uq_expense_matched_txn
ON expense_metadata (matched_transaction_id)
WHERE matched_transaction_id IS NOT NULL;
+50 -10
View File
@@ -7,6 +7,19 @@ datasource db {
provider = "postgresql"
}
model trips {
id Int @id @default(autoincrement())
owner_id Int
name String
description String?
start_date DateTime? @db.Date
end_date DateTime? @db.Date
color String @default("#6366f1")
archived Boolean @default(false)
created_at DateTime @default(now())
overrides transaction_overrides[]
}
model transaction_overrides {
id Int @id @default(autoincrement())
transaction_id Int @unique
@@ -15,6 +28,8 @@ model transaction_overrides {
notes String?
my_share_percent Decimal? @db.Decimal(5, 2)
updated_at DateTime @default(now()) @updatedAt
trip_id Int?
trip trips? @relation(fields: [trip_id], references: [id], onDelete: SetNull)
}
model participants {
@@ -83,15 +98,16 @@ model transaction_tags {
}
model rules {
id Int @id @default(autoincrement())
owner_id Int
name String
conditions Json @default("[]")
actions Json @default("{}")
enabled Boolean @default(true)
priority Int @default(0)
created_at DateTime @default(now())
updated_at DateTime @default(now()) @updatedAt
id Int @id @default(autoincrement())
owner_id Int
name String
conditions Json @default("[]")
actions Json @default("{}")
enabled Boolean @default(true)
manual_only Boolean @default(false)
priority Int @default(0)
created_at DateTime @default(now())
updated_at DateTime @default(now()) @updatedAt
}
model budgets {
@@ -121,7 +137,7 @@ model statements {
event_created Boolean? @default(false)
tier_used String?
created_at DateTime? @default(now())
statement_type String @default("credit_card")
statement_type String @default("other")
currency String? @default("AUD")
opening_balance Decimal? @db.Decimal(12, 2)
closing_balance Decimal? @db.Decimal(12, 2)
@@ -135,6 +151,11 @@ model statements {
account_holder_name String?
exchange_rate_to_aud Decimal? @db.Decimal(10, 6)
paperless_doc_id Int? @unique
interest_rate Decimal? @db.Decimal(6, 3)
scheduled_repayment Decimal? @db.Decimal(12, 2)
repayment_frequency String?
redraw_available Decimal? @db.Decimal(12, 2)
loan_term_months Int?
transactions transactions[]
}
@@ -154,12 +175,16 @@ model transactions {
row_index Int?
merchant_normalized String?
amount_aud Decimal? @db.Decimal(12, 2)
payment_method String? // card | cash | bank_transfer | other; NULL = unknown (migration 0016)
owner_id Int?
reconciled_with_id Int?
principal_amount Decimal? @db.Decimal(12, 2)
interest_amount Decimal? @db.Decimal(12, 2)
statement statements? @relation(fields: [statement_id], references: [id], onDelete: Cascade)
reconciled_with transactions? @relation("reconciled", fields: [reconciled_with_id], references: [id], onDelete: SetNull)
reconciled_by transactions[] @relation("reconciled")
expense_metadata expense_metadata?
order_review order_reviews?
}
model expense_metadata {
@@ -169,6 +194,7 @@ model expense_metadata {
paperless_doc_id Int? @unique
source_email_subject String?
source_email_from String?
source_message_id String?
payment_method String?
payment_method_detail String?
order_reference String?
@@ -181,6 +207,20 @@ model expense_metadata {
extraction_model String? @default("gemini-2.5-flash")
created_at DateTime? @default(now())
transaction transactions? @relation(fields: [transaction_id], references: [id], onDelete: Cascade)
@@unique([source, order_reference], name: "uq_expense_source_order")
}
model order_reviews {
id Int @id @default(autoincrement())
transaction_id Int @unique
rating String?
order_again Boolean?
note String?
item_verdicts Json @default("[]")
created_at DateTime @default(now())
updated_at DateTime @updatedAt
transaction transactions @relation(fields: [transaction_id], references: [id], onDelete: Cascade)
}
model rule_apply_runs {
+111
View File
@@ -0,0 +1,111 @@
# Personal Finance Tracker — Project Context
## What Is This?
A self-hosted personal finance tracker built from scratch. It automatically ingests bank statements, categorises transactions using AI, and provides a web UI for reviewing spending, managing shared expenses, and running analytics.
---
## How It Works (High Level)
### Automatic Statement Ingestion
Bank statements (PDFs) are uploaded to a document management system (Paperless-NGX). An automation workflow (N8N) polls for new documents every 5 minutes and:
1. Sends the PDF to Google Gemini (AI) for structured data extraction
2. Normalises the extracted data (merchant names, currencies, account numbers)
3. Inserts the statement summary and individual transactions into a PostgreSQL database
4. Creates a Google Calendar reminder for credit card payment due dates
5. For new/unknown bank accounts, requires a human approval before inserting
---
## Core Features
### Transactions View
- Full paginated list of all transactions across all bank accounts
- Filters: date range, category, bank, tags, transaction type, amount range, split status, free-text search
- Sortable columns including transaction date, amount, and import date
- Inline editing of category, merchant name, and notes
- Tagging system with user-defined coloured labels
### Statements View
- One row per billing period per account
- Filters by bank, statement type, owner, year
- Click a statement to see only its transactions
### Analytics / Insights
- Monthly spend breakdown by category (stacked bar chart)
- Category trend lines over time
- Pareto chart (which categories drive the most spend)
- Cumulative spend curve
- Savings rate over time
- Recurring charge detection (subscriptions/recurring merchants)
- Fees and interest audit (tracks what's been paid in bank fees and interest charges)
- Committed vs discretionary spend split
### Merchant Profiles
- Per-merchant transaction history and net spend
- Scatter plot of spend over time
- Accounts for refunds/credits
### Shared Expenses
- Split transactions between multiple people (by percentage)
- Tracks who owes what with a running balance
- Record cash settlements between participants
- Tag filter on shared view to track specific projects/events
### Rules Engine
- Create saved rules that auto-apply categories, merchant names, tags, or splits to matching transactions
- Conditions: merchant name, description, category, bank, amount, transaction type
- Operators: contains, equals, starts with, greater/less than, not equals
- Bulk-apply all rules at once with full revert support (snapshot stored before each run)
### Manual Transactions + Reconciliation
- Enter transactions manually (cash, receipts not on a statement)
- CSV import for bulk entry
- Reconcile manual transactions against statement transactions when the statement arrives — merges tags, splits, and notes onto the statement version
### Multi-Owner Support
- Multiple people's accounts can be tracked in the one app
- Each statement/transaction is scoped to an owner
- The logged-in user only sees their own data
---
## Technology
- **Frontend**: Next.js (React), TypeScript, Tailwind CSS, Recharts for charts
- **Backend**: Next.js API routes with raw PostgreSQL queries (no ORM at query time)
- **Database**: PostgreSQL
- **AI extraction**: Google Gemini 2.5 Flash (PDF → structured JSON)
- **Automation**: N8N workflow orchestrates the ingestion pipeline
- **Auth**: Users are authenticated by the reverse proxy before reaching the app
- **Hosting**: Self-hosted Docker container on a home server
---
## Data Structure (Summary)
| Concept | Description |
|---------|-------------|
| **Statement** | One billing period for one bank account. Has summary totals (closing balance, fees, interest, credit limit, etc.) |
| **Transaction** | A line item. Has date, amount, merchant, category, transaction type (debit/credit/refund/fee/etc.) |
| **Override** | User correction to AI-extracted merchant name or category. Stored separately to preserve the original AI output |
| **Split** | A transaction shared with another person — records their percentage share and whether it's been settled |
| **Tag** | A free-form label applied to transactions (e.g. "Europe Trip 2026", "Home Reno") |
| **Rule** | A saved condition→action pair applied in bulk to auto-categorise/tag/split transactions |
| **Participant** | A person (account owner or expense-sharing partner) |
| **Split Payment** | A recorded cash settlement between two participants |
### Category Taxonomy
Fixed set used by AI and overridable by the user:
`groceries`, `dining`, `transport`, `fuel`, `shopping`, `utilities`, `entertainment`, `travel`, `health`, `insurance`, `subscriptions`, `cash_advance`, `government`, `education`, `rent`, `home_goods`, `home_maintenance`, `transfers`, `income`, `investment`, `personal_care`, `pets`, `gifts`, `charity`, `other`
---
## Known Limitations / Planned Work
- **Payment provider conflation**: Transactions processed through PayPal, Afterpay, Zip etc. sometimes show the payment provider as the merchant rather than the actual store. Plan is to extract `payment_provider` as a separate field so the real merchant is preserved.
- **Budgets**: The database has a budget table but it's not currently surfaced in the UI (the analytics/insights views replaced it for now).
@@ -0,0 +1,549 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
<head><!--[if gte mso 9]><xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml><![endif]-->
<title>DoorDash</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0 ">
<meta name="format-detection" content="telephone=no">
<style type="text/css">body {
margin: 0 auto;
padding: 0;
-webkit-text-size-adjust: 100%!important;
-ms-text-size-adjust: 100%!important;
-webkit-font-smoothing: antialiased!important;
}
img {
border: 0!important;
outline: none!important;
}
p {
Margin: 0px!important;
Padding: 0px!important;
}
table {
border-collapse: collapse;
mso-table-lspace: 0px;
mso-table-rspace: 0px;
}
td, a, span {
border-collapse: collapse;
mso-line-height-rule: exactly;
}
.ExternalClass * {
line-height: 100%;
}
.em_defaultlink a {
color: inherit;
text-decoration: none;
}
a[x-apple-data-detectors], u+.em_body a {
color: inherit;
text-decoration: none;
font-size: inherit;
font-family: inherit;
font-weight: inherit;
line-height: inherit;
}
@media only screen and (max-width:667px) {
.em_main_table {
width: 100%!important;
}
.em_wrapper {
width: 100%!important;
}
.em_hide {
display: none!important;
}
.em_hauto {
height: auto !important;
}
.em_full_img img {
width: 100%!important;
height: auto!important;
}
.em_pad1 {
padding-right: 10px!important;
}
.em_hauto {
height: auto!important;
}
.em_side15 {
width: 40px!important;
}
.em_h20 {
height: 40px!important;
font-size: 1px!important;
line-height: 1px!important;
}
.em_h10 {
height: 10px!important;
font-size: 1px!important;
line-height: 1px!important;
}
.em_h30 {
height: 30px!important;
}
u+.em_body .em_full_wrap {
width: 100%!important;
width: 100vw!important;
}
.em_side30 {
width: 26px!important;
}
.em_cta {
width: 190px !important;
height: 40px!important;
}
.em_cta a {
font-size: 17px !important;
line-height: 40px!important;
}
.em_h90 {
height: 140px !important;
}
.em_font_58 {
font-size: 40px!important;
line-height: 44px!important;
}
.em_pad1 {
padding: 0px 15px !important;
}
.en_icon {
width: 30px !important;
padding-bottom:10px !important;
}
.em_rounded {
border-top-left-radius: 25px !important;
border-top-right-radius: 25px !important;
}
.em_bold {
letter-spacing: -1px !important;
}
}
@media screen and (max-width:480px) {
.em_side30 {
width: 26px!important;
}
.ft_16 {
font-size: 14px!important;
line-height: 18px!important;
}
.em_side15 {
width: 40px!important;
}
.em_font_58 {
font-size: 35px!important;
line-height: 42px!important;
}
.em_cta {
width: 165px !important;
height: 38px!important;
}
.em_cta a {
font-size: 15px !important;
line-height: 38px!important;
}
.em_h90 {
height: 105px !important;
}
}
@media screen and (max-width:374px) {
.ft_16 {
font-size: 12px!important;
line-height: 16px!important;
}
.em_side15 {
width: 40px!important;
}
.em_side30 {
width: 20px!important;
}
.em_font_58 {
font-size: 30px!important;
line-height: 38px!important;
}
.em_cta {
width: 160px !important;
height: 38px!important;
}
.em_cta a {
font-size: 15px !important;
line-height: 38px!important;
}
.em_h90 {
height: 95px !important;
}
}
@media screen {
@font-face {
font-family: 'TTNorms-Regular';
src: url('https://typography.doordash.com/TTNorms-Regular.woff') format('woff'), url('https://typography.doordash.com/TTNorms-Regular.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
@font-face {
font-family: 'TTNorms-Medium';
src: url('https://typography.doordash.com/TTNorms-Medium.woff') format('woff'), url('https://typography.doordash.com/TTNorms-Medium.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
@font-face {
font-family: 'TTNorms-Bold';
src: url('https://typography.doordash.com/TTNorms-Bold.woff') format('woff'), url('https://typography.doordash.com/TTNorms-Bold.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
@font-face {
font-family: 'TTNorms-ExtraBold';
src: url('https://typography.doordash.com/TTNorms-ExtraBold.woff') format('woff'), url('https://typography.doordash.com/TTNorms-ExtraBold.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
}
</style>
</head>
<body bgcolor="#ffffff" class="em_body" data-gr-c-s-loaded="true" style="margin:0px auto; padding:0px;">
<span style="color:transparent;visibility:hidden;display:none;opacity:0;height:0;width:0;font-size:0;"></span> <!-- == Body Section == -->
<table bgcolor="#ffffff" border="0" cellpadding="0" cellspacing="0" class="em_full_wrap" width="100%">
<tbody>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="em_main_table" style="width:700px;" width="700">
<tbody>
<tr>
<td align="center" valign="top"><!---->
<table align="center" bgcolor="#ededed" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h30" height="62" style="height:62px; line-height:0px; font-size:0px;"></td>
</tr> <!-- banner Section -->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="center" bgcolor="#ededed" class="em_hauto" valign="top"><!---->
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side30" style="width:60px;" width="60"></td>
<td align="center" class="em_hauto" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" valign="top"><a style="text-decoration:none;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiX9NQvXQ9aE-2FeLMhxL9C-2FAEkIYH_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniDohab0lVqyyqLUGGGtDfKri8s0BPbLw2Kta64VgtBfCarELB9jSoY9mQzB-2FDOSk7-2FtMWjohoN3uf5f2rLrFhl33mtjWZ53lXvtDO4wQsmVDJSCEfVON02MQaDh-2BmTLPN5Vxq7DH8UlIbETnDVF4Df7l7njadHPDZB2aHMoBR9nS93-2B-2FrbnWmdM0cdfetMj3RGMa8Yk-2Fgyfj6ZKM2CqlUxqNZhbHVjZo1bFR4YvyxsTPc56A8ujeF0vzPIUM4yXtdY-2BtGKNvO-2F2momIcFB8TCK6k39zWYllF-2FQub6BRW64qF3OwcOA8Qi4U05aRe966x3Bpi5mkgpGuXH0X2CslH23bljSHOl2uOmwPSt23EvYS0CPbrX4YRtgLnEmHgYYbokWIuo5wjdIr3VkCFPni8ollM9GFO6AXsUeSwZAvhq6oZY-2FetynINJjWZRmZA3FqSomogDxHnQi04e6CHFKy-2BGOn5XT6stPkmBsFDgIMFmy1Jd3aVxMduJiqTN-2FrgtJfvcZfTHhj5HcBZymhPVxScgd1TCe4E2-2FYMFqXzB9Or-2FAP5yIgF2yNJhy8OA3CMlV8LdA8Rd-2Fsxt1caI8cPn9hyYypY-2FLckUNAxRzwuBCAQ1buubQlldewgQiuToSUsejOOxk-3D" universal="true"><img alt="DOORDASH" border="0" class="en_icon" style="display:block; max-width:45px;font-family:Arial, sans-serif;font-size:20px; line-height:30px; color:#ee3623; font-weight:bold;" width="45" src="https://assets.doordash.team/m/835d1d775f776ef/original/-04_April-MX_Winback_Campaign-logo_img.png"> </a></td>
</tr>
<tr>
<td class="em_h20" height="50" style="height:50px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink em_font_58 em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:51px; line-height:60px; font-weight: bold;" valign="top"><!---->Thanks for your<br> order, Siddharth<!----></td>
</tr>
<tr>
<td class="em_h10" height="20" style="height:20px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#000000;font-size:16px; line-height:20px;" valign="top"><!---->The estimated delivery time for your order<br class="em_hide"> is <strong>2:00 pm - 2:15 pm</strong>. Track your order in<br class="em_hide"> the DoorDash app or website.<!----></td>
</tr>
<tr>
<td class="em_h10" height="20" style="height:20px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" valign="top">
<table align="left" border="0" cellpadding="0" cellspacing="0" class="em_cta" style="width:220px; max-width:220px;" width="220">
<tbody>
<tr>
<td align="center" class="em_defaultlink em_cta em_bold" height="45" style="font-family:'TTNorms-Bold', Arial, sans-serif;color:#ffffff;font-size:18px; background-color:#eb1700; border-radius:25px; font-weight: bold; " valign="middle"><a style="text-decoration:none; display:block; color:#ffffff; line-height:45px;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiUYpjiz5uS6IJixGXj3UHbTD93pKefx1-2F0xnbLGDGm-2F-2BQiJu-2BjCmmrEKOYlPr7srvk-3D8BvI_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniDohab0lVqyyqLUGGGtDfKri8s0BPbLw2Kta64VgtBfCarELB9jSoY9mQzB-2FDOSk7-2FtMWjohoN3uf5f2rLrFhl33mtjWZ53lXvtDO4wQsmVDJSCEfVON02MQaDh-2BmTLPN5Vxq7DH8UlIbETnDVF4Df7l7njadHPDZB2aHMoBR9nS93-2B-2FrbnWmdM0cdfetMj3RGMa8Yk-2Fgyfj6ZKM2CqlUxqNZhbHVjZo1bFR4YvyxsTPc56A8ujeF0vzPIUM4yXtdY-2BtGKNvO-2F2momIcFB8TCK6k39zWYllF-2FQub6BRW64qF3OwcOA8Qi4U05aRe966x3Bpi5mkgpGuXH0X2CslH23bljSHOl2uOmwPSt23EvYS0CPbrX4YRtgLnEmHgYYbokWIuo5wjdIr3VkCFPni8ollM9GFO6AXsUeSwZAvhq6oZY-2FetynINJjWZRmZA3FqSomogDxHnQi04e6CHFKy-2BGOn5XT6stPkmBsFDgIMFmy1JaOMC6-2F6zNNGOii9obOCSUz236yIB4gCzgF-2BEE7DFN-2BzWJDOZETyK2c-2BdBr5QJMquOChmyoid171OpGSki94P-2Br-2FT5mkOXMUdSuXDA9B2zx9bfVlZsW1KYw6NBNiJ3c-2F9p-2FTFh6SVp-2Ferm15pDsGPoc-3D" universal="true">Track Your Order</a></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
<td class="em_side15" style="width:20px;" width="20"></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr> <!----><!--Illustration 1-->
<tr>
<td align="center" class="em_full_img" valign="top"><a style="text-decoration:none;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiX9NQvXQ9aE-2FeLMhxL9C-2FAEGC0g_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniDohab0lVqyyqLUGGGtDfKri8s0BPbLw2Kta64VgtBfCarELB9jSoY9mQzB-2FDOSk7-2FtMWjohoN3uf5f2rLrFhl33mtjWZ53lXvtDO4wQsmVDJSCEfVON02MQaDh-2BmTLPN5Vxq7DH8UlIbETnDVF4Df7l7njadHPDZB2aHMoBR9nS93-2B-2FrbnWmdM0cdfetMj3RGMa8Yk-2Fgyfj6ZKM2CqlUxqNZhbHVjZo1bFR4YvyxsTPc56A8ujeF0vzPIUM4yXtdY-2BtGKNvO-2F2momIcFB8TCK6k39zWYllF-2FQub6BRW64qF3OwcOA8Qi4U05aRe966x3Bpi5mkgpGuXH0X2CslH23bljSHOl2uOmwPSt23EvYS0CPbrX4YRtgLnEmHgYYbokWIuo5wjdIr3VkCFPni8ollM9GFO6AXsUeSwZAvhq6oZY-2FetynINJjWZRmZA3FqSomogDxHnQi04e6CHFKy-2BGOn5XT6stPkmBsFDgIMFmy1JaZrmPxM5tO3MVqwpeuZtxlipSYowDluqjEhtng6OZ1tiReEtrMZSXfyizE8Z-2BoYl-2FOhh2mVbKh8Ag8sj-2FY0Dr5fXcralZiuXdtrszdPSlbYpbbdCWJgW2Mvx4JTup-2Be7s2F323Q0hdUfWlDu1kXlV0-3D" universal="true"><img alt="" border="0" class="em_full_img" style="display:block; max-width:700px; font-family:Arial, sans-serif; font-size:22px; line-height:25px; color:#ffffff; font-weight:bold;" width="700" src="https://assets.doordash.team/m/2f9c7fde7cfed840/original/-template-OrderConfirmation-foodbag.png"></a></td>
</tr> <!--//Illustration 1--><!----><!-- //banner Section -->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td style="width:6%;" width="6%"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="center" class="em_rounded" style="border-top-left-radius: 40px; border-top-right-radius: 40px; background-color: #ffffff;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side15" style="width: 40px;" width="40"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h20" height="50" style="height:50px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:17px; line-height:24px;" valign="top">Paid with credits<br> Mad Mex</td>
</tr>
<tr>
<td align="left" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#767676;font-size:17px; line-height:24px; font-weight:bold; color:#000000;" valign="top">Total: $14.64</td>
</tr>
<tr>
<td class="em_h20" height="35" style="height:35px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:26px; line-height:36px; font-weight: bold;" valign="top">Your receipt</td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:21px;" valign="top">19 Lady Penrhyn Dr, Wyndham Vale VIC 3024, Australia</td>
</tr>
<tr>
<td class="em_h20" height="45" style="height:45px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:17px; line-height:24px;" valign="top"><font size="2" color="#666666"><b>- For: Siddharth Bose -</b></font><br><br>
<table width="100%" style="margin: auto; margin-bottom: 20px">
<tbody>
<tr style="text-align: left;">
<td valign="top" width="10%" style="color: #666666; font-size: 18px; line-height: 24px">1x</td>
<td valign="top" width="75%" style="color: #666666; font-size: 18px; line-height: 24px"><b>Burrito</b> (Mains)<br><font color="dimgrey">• Slow Cooked Beef (GF)</font><br><font color="dimgrey">• Fresh Guacamole (GF, VG)</font><br><font color="dimgrey">• Spicy Salsa</font><br><font color="dimgrey">• No Beans (GF,V)</font><br><br></td>
<td valign="top" width="15%" style="color: #666666; font-size: 18px; line-height: 24px text-align: right">$22.10</td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td class="em_h20" height="22" style="height:22px; line-height:0px; font-size:0px;"></td>
</tr>
</tbody>
</table></td>
<td class="em_side15" style="width: 40px;" width="40"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" bgcolor="#ffffff" class="em_pad1" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="em_wrapper" style="width:530px;" width="530">
<tbody>
<tr>
<td bgcolor="#e5e5e5" height="2" style="line-height:0px; font-size:0px; height: 2px;"><img alt="" border="0" height="1" style="display:block;" width="1" src="https://assets.doordash.team/m/1b5c04bd5b887a06/original/-05_May-90D_Resurrection_Campaign_Refresh_T2-spacer.gif"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" style="background-color: #ffffff;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side15" style="width: 40px;" width="40"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h20" height="10" style="height:10px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr><!---->
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Subtotal</td> <!---->
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$22.10</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr><!---->
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Taxes</td> <!---->
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$0.00</td>
</tr>
</tbody>
</table></td>
</tr> <!----><!---->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Delivery Fee</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$0.00</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Service Fee</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$1.99</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Tip</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$0.00</td>
</tr>
</tbody>
</table></td>
</tr> <!---->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Discounts</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">-$24.09</td>
</tr>
</tbody>
</table></td>
</tr> <!---->
<tr>
<td class="em_h20" height="18" style="height:18px; line-height:0px; font-size:0px;"></td>
</tr>
</tbody>
</table></td>
<td class="em_side15" style="width: 40px;" width="40"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" bgcolor="#ffffff" class="em_pad1" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="em_wrapper" style="width:530px;" width="530">
<tbody>
<tr>
<td bgcolor="#e5e5e5" height="2" style="line-height:0px; font-size:0px; height: 2px;"><img alt="" border="0" height="1" style="display:block;" width="1" src="https://assets.doordash.team/m/1b5c04bd5b887a06/original/-05_May-90D_Resurrection_Campaign_Refresh_T2-spacer.gif"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" style="background-color: #ffffff;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side15" style="width: 40px;" width="40"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h20" height="12" style="height:12px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr><!---->
<td align="left" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:17px; line-height:24px; font-weight: bold;" valign="top">Total Charged</td> <!---->
<td align="right" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:17px; line-height:24px; font-weight: bold;" valign="top">$14.64</td>
</tr>
</tbody>
</table></td>
</tr> <!----><!----><!----><!----><!----><!----><!----> <!---->
<tr>
<td class="em_h20" height="15" style="height:15px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#ff2f07;font-size:14px; line-height:21px; font-weight: bold;" valign="top"><a style="color:#ff2f07; text-decoration:none;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiUYpjiz5uS6IJixGXj3UHbTD93pKefx1-2F0xnbLGDGm-2F-2BQiJu-2BjCmmrEKOYlPr7srvk-3DZM8O_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniDohab0lVqyyqLUGGGtDfKri8s0BPbLw2Kta64VgtBfCarELB9jSoY9mQzB-2FDOSk7-2FtMWjohoN3uf5f2rLrFhl33mtjWZ53lXvtDO4wQsmVDJSCEfVON02MQaDh-2BmTLPN5Vxq7DH8UlIbETnDVF4Df7l7njadHPDZB2aHMoBR9nS93-2B-2FrbnWmdM0cdfetMj3RGMa8Yk-2Fgyfj6ZKM2CqlUxqNZhbHVjZo1bFR4YvyxsTPc56A8ujeF0vzPIUM4yXtdY-2BtGKNvO-2F2momIcFB8TCK6k39zWYllF-2FQub6BRW64qF3OwcOA8Qi4U05aRe966x3Bpi5mkgpGuXH0X2CslH23bljSHOl2uOmwPSt23EvYS0CPbrX4YRtgLnEmHgYYbokWIuo5wjdIr3VkCFPni8ollM9GFO6AXsUeSwZAvhq6oZY-2FetynINJjWZRmZA3FqSomogDxHnQi04e6CHFKy-2BGOn5XT6stPkmBsFDgIMFmy1JaVyVX-2BN0rfrZb4gqsyh-2FPhwDCNS7-2Fr19T2GWsMfiRQ3UNw3buP-2FdHaE5XAo30Zx73XG0x2-2Bj9CkYTdbTkYtPKndOo8C-2Frr-2BJqyRFJZMfQUP1ZV-2F2Ey3WNBzbwVr6SxafeujsUnxXrbM6VJ3DMYac3E-3D" universal="true">Get Order Help</a></td>
</tr> <!-- -->
<tr>
<td class="em_h20" height="58" style="height:58px; line-height:0px; font-size:0px;"></td>
</tr>
</tbody>
</table> <!-- == //Body Section == --><!-- == Footer Section == --><!-- == //Footer Section == --></td>
<td class="em_side15" style="width: 40px;" width="40"></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
<td style="width:6%;" width="6%"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top"><!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:620px;">
<tr>
<td align="center">
<![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" id="Footer" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width: 100%; max-width: 700px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="center" style="padding: 0 24px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width:100%;max-width:572px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding:0 0 48px 0;border-bottom: 1px solid #E7E7E7;"></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 32px 0 16px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;">©2026 <a style="color: #9A9A9A; text-decoration: none;">DoorDash Technologies Australia Pty Ltd <br>401 Collins St. <br>Melbourne, VIC 3000 Australia</a></p> <p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYCzx-2Br1lrYaof6JiBiFLOVfEOgDjXh7OOs7yReUnPIfAQpor-2FGsJy8J81hADh-2FLb3M-3Dcz1D_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniDohab0lVqyyqLUGGGtDfKri8s0BPbLw2Kta64VgtBfCarELB9jSoY9mQzB-2FDOSk7-2FtMWjohoN3uf5f2rLrFhl33mtjWZ53lXvtDO4wQsmVDJSCEfVON02MQaDh-2BmTLPN5Vxq7DH8UlIbETnDVF4Df7l7njadHPDZB2aHMoBR9nS93-2B-2FrbnWmdM0cdfetMj3RGMa8Yk-2Fgyfj6ZKM2CqlUxqNZhbHVjZo1bFR4YvyxsTPc56A8ujeF0vzPIUM4yXtdY-2BtGKNvO-2F2momIcFB8TCK6k39zWYllF-2FQub6BRW64qF3OwcOA8Qi4U05aRe966x3Bpi5mkgpGuXH0X2CslH23bljSHOl2uOmwPSt23EvYS0CPbrX4YRtgLnEmHgYYbokWIuo5wjdIr3VkCFPni8ollM9GFO6AXsUeSwZAvhq6oZY-2FetynINJjWZRmZA3FqSomogDxHnQi04e6CHFKy-2BGOn5XT6stPkmBsFDgIMFmy1JRYFdI4rWGqZbwcwPjA-2FfGSpVNEJe6-2BhKqFbWrIPgphG2UaqzMu-2FrPVVEEnOy-2F7K7l-2Fiy9DJuVosOT1N6tV6enGQ9g8qH2bVpDkJgmaqxnNTS4xf9s7LwM3H-2FEquZm-2By-2FmUkLGnDPlpUJFzu1om-2F4mY-3D" target="_blank" style="color: #9A9A9A; text-decoration: none;">Privacy Policy</a></p></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 0 0 24px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:500;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYC9Fbd7OtaSznXr4XXA8cVP-2BJHCjKWkCwgvETCnlfYzgA-3D-3D9VgN_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniDohab0lVqyyqLUGGGtDfKri8s0BPbLw2Kta64VgtBfCarELB9jSoY9mQzB-2FDOSk7-2FtMWjohoN3uf5f2rLrFhl33mtjWZ53lXvtDO4wQsmVDJSCEfVON02MQaDh-2BmTLPN5Vxq7DH8UlIbETnDVF4Df7l7njadHPDZB2aHMoBR9nS93-2B-2FrbnWmdM0cdfetMj3RGMa8Yk-2Fgyfj6ZKM2CqlUxqNZhbHVjZo1bFR4YvyxsTPc56A8ujeF0vzPIUM4yXtdY-2BtGKNvO-2F2momIcFB8TCK6k39zWYllF-2FQub6BRW64qF3OwcOA8Qi4U05aRe966x3Bpi5mkgpGuXH0X2CslH23bljSHOl2uOmwPSt23EvYS0CPbrX4YRtgLnEmHgYYbokWIuo5wjdIr3VkCFPni8ollM9GFO6AXsUeSwZAvhq6oZY-2FetynINJjWZRmZA3FqSomogDxHnQi04e6CHFKy-2BGOn5XT6stPkmBsFDgIMFmy1JePrOHq5c5aW6evBo1DEdQJNXu-2BX-2FLP1H7ZXkSsghQ0EUu5Q6HYBtkMij3hyHvfxKdfDvfPKun4porDdzU27HkbjUwffVpDDk5SZimtlGs-2B8re-2FwuFPMI9TFYPc8JMXjGAWJTpoqf-2BcFT1RgPBXiW4Y-3D" target="_blank" style="color:#9A9A9A;text-decoration:none;">Help Center</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!--[if (gte mso 9)|(IE)]>
</td>
</tr>
</table>
<![endif]--></td>
</tr>
<tr>
<td class="em_hide" style="line-height:1px;min-width:700px;background-color:#f4f4f4;"><img alt="" border="0" height="1" style="max-height:1px; min-height:1px; display:block; width:700px; min-width:700px;" width="700" src="https://assets.doordash.team/m/1b5c04bd5b887a06/original/-05_May-90D_Resurrection_Campaign_Refresh_T2-spacer.gif"></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
<img src="https://tracksg.doordash.com/wf/open?upn=u001.EBL2ug8kstebd25Xirrl3olMckTI261ldPjJ39bNHcC7U6EKGAOA4dSVB97lcv3b8qsQRq6LwkHED6F3X4gqaODB2b1wZFk4or4JbrThItr6lxxhe0ghxdjbmj40V9NR2q6sVlDPfArvtaJbtCejz-2BJxmNDpj6cBZjf16jHN3-2B2-2FBNoONAVXEROMy-2FebOh-2BiIcflH-2B33fKp22eXYo6U8vHb6sK-2FhKm1eTZq8fP2ZliSW-2FDJ4KPJHZKnoxb-2FEyRvVNj8NRt3Z7VhrxSD83L-2BD-2Fg-2BYQJkcfBPsJzteuA7jtfPftcKLG1twN4g1gQQZHw9OGtsD1rLq9iXJ6ZzaVdWLEzmjDcZ7g3fTMixrMzH4oIIOEair3v0qOMD-2BV-2BHU7ncYtO-2FnD0bk1O9XI94PBy9e9JXZDgi2OxIT84h7X7b83MwQfHv6Y0eFjKVrvu0wzSlch7hpGzIv6v9RQGcCePKn-2BQ-2B85mf3KcKtUiyQ-2Bcvh-2BNe6ZHrHZAucV3pF0Fdo4Yn1-2Fie3uN1peu4VputGOf9gYSRqzfDIxJ-2BpD9KcAQghrRgZ08n7rFpdtIeHrI0J-2BsvQ0YqnprMwzKBgarmyWY4Ll6vo-2B-2FQLHQVXWlGWqomUtaBIY1wIPtH3sUn48aYCsuzz9tPifFXGPqgruVpD2mpi3C41MG8rFgUFQwfp4xV7SLCp8axKXY3t7WsYtRFw04WcnX-2FJMSRUrn8bq8PbEHq3Hjikf10MnkiyW7GobtuKhHdBL4F6ntalNVUHk3neSbhFBHGlJJQUA2Kfxt1bsI5eAQoX-2FRsU2BYtChgxaMUD53E-3D" alt="" width="1" height="1" border="0" style="height:1px !important;width:1px !important;border-width:0 !important;margin-top:0 !important;margin-bottom:0 !important;margin-right:0 !important;margin-left:0 !important;padding-top:0 !important;padding-bottom:0 !important;padding-right:0 !important;padding-left:0 !important;"/></body>
</html>
@@ -0,0 +1,817 @@
<!doctype html>
<html lang="en" dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1 user-scalable=yes">
<meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
<meta name="x-apple-disable-message-reformatting">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<title>DoorDash</title> <!-- WEB FONTS --> <!--[if !mso]>-->
<style type="text/css">
@font-face{font-family:'TTNorms';font-style:normal;font-weight:700;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Bold.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:600;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-DemiBold.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:500;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Medium.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:450;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Normal.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:400;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Regular.woff2')format('woff2');}
</style> <!--<![endif]--> <!-- STYLE RESETS -->
<style type="text/css">a[href^="tel"],a[href^="sms"]{color:inherit;cursor:default;font-weight:inherit;text-decoration:none}body{-ms-text-size-adjust:100%;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;mso-line-height-rule:exactly;}html,body{width:100%;margin:0;padding:0}img{border:0;display:block;height:auto;line-height:100%;outline:none;text-decoration:none}table{border:0 !important;padding:0 !important; border-collapse:collapse !important;mso-table-lspace:0pt;mso-table-rspace:0pt;}u + .body a{color:inherit;font-family:inherit;font-size:inherit;font-weight:inherit;line-height:inherit}u ~ img + div > div{display:none;}u + .body{width:100%;}.body a[x-apple-data-detectors=true]{color:inherit!important;text-decoration:inherit!important}span.MsoHyperlink{color:inherit !important;mso-style-priority:99 !important}span.MsoHyperlinkFollowed{color:inherit !important;mso-style-priority:99 !important}
</style> <!-- BACKGROUND COLORS -->
<style type="text/css">
body,#MainTable{background-color:#F4F4F4;}
#Basic000{background-color:#FEFFFF;}
#Sky200{background-color:#DDF4F4;}
</style> <!-- FONT STYLES -->
<style type="text/css">
h1,h2,h3,h4,h5,h6{font-family:'TTNorms',system-ui,sans-serif;font-weight:700;margin:0 0 8px 0;}
p,ol,ul{font-family:'TTNorms',system-ui,sans-serif;font-weight:450;margin:0 0 8px 0;}
ul,ol{padding:0 0 0 20px;}
li{font-weight:450;margin:0 0 8px 0;}
h1{font-size:50px;line-height:50px;letter-spacing:-0.03em;}
h2{font-size:40px;line-height:40px;letter-spacing:-0.02em;}
h3{font-size:32px;line-height:32px;letter-spacing:-0.02em;}
h4{font-size:24px;line-height:24px;letter-spacing:-0.01em;}
h5{font-size:20px;line-height:22px;letter-spacing:-0.01em;}
h6{font-size:16px;line-height:18px;}
p.p1{font-size:20px;line-height:26px;}
p.p2{font-size:16px;line-height:22px;}
p.p4{font-size:12px;line-height:14px;}
sup{font-size:11px;line-height:11px;}
</style> <!-- FONT COLORS -->
<style type="text/css">
#MainTable table td{color:#191919;}
#MainTable table td a{color:inherit;}
#MainTable table td p a{text-decoration:underline;}
.Red200{color:#EB1700 !important;}
</style> <!-- CTAs --> <!-- MOBILE STYLES -->
<style type="text/css">
@media only screen and (max-width:699px){
#MainTable > table {max-width:410px!important;}
.full{width:100%!important;height:auto!important;}
.pad0{padding-left:0!important;padding-right:0!important;}
.pad8{padding-left:8px!important;padding-right:8px!important;}
.pad24{padding-left:24px!important;padding-right:24px!important;}
.logo{padding-top:40px!important;padding-bottom:40px!important;}
h1{font-size:40px!important;line-height:40px!important;letter-spacing:-0.02em!important;}
h2{font-size:32px!important;line-height:32px!important;}
h3{font-size:24px!important;line-height:24px!important;letter-spacing:-0.01em!important;}
}
</style> <!-- DARK MODE STYLES -->
<style type="text/css">
@media (prefers-color-scheme:dark){
body,#MainTable,#Footer{background-color:#000000!important;background-image:linear-gradient(#000000,#000000)!important;}
table[id^="Basic"]{background-color:#191919!important;background-image:linear-gradient(#191919,#191919)!important;}
table[id^="Sky"],table[id^="Blue"]{background-color:#002629!important;background-image:linear-gradient(#002629,#002629)!important;}
#MainTable table td{color:#FFFFFF!important;}
#MainTable #Footer table td a{color:#FFFFFF!important;}
#MainTable .Red200{color:#FF3008!important;}
#MainTable .label span{color:#494949!important;background-color:#FEFFFF!important;}
#MainTable .grayCopy p{color:#A6A6A6!important;}
}
</style>
<style type="text/css">
:root{color-scheme:light dark;supported-color-schemes:light dark;}
</style> <!-- GMAIL APP DARK MODE FIX --> <!-- OUTLOOK SPECIFIC CSS --> <!--[if gte mso 9]>
<style type="text/css">
#MainTable td a{color:#191919;}
ol,ul{margin-left:20px !important;}
li{text-indent:-1em;}
</style>
<noscript>
<xml>
<o:OfficeDocumentSettings>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
</noscript>
<![endif]-->
</head>
<body class="body" style="width:100%;margin:0;padding:0;">
<span style="color:transparent;visibility:hidden;display:none;opacity:0;height:0;width:0;font-size:0;"></span>
<div role="article" aria-roledescription="email" aria-label="DoorDash Email" lang="en" dir="ltr" style="font-size:medium; font-size:max(16px, 1rem);">
<div style="display: none; max-height: 0px; overflow: hidden;">
 ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏
</div>
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="center" id="MainTable" style="background-color:#F4F4F4;">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="full" id="Sky200" role="presentation" style="width:700px;">
<tbody>
<tr>
<td align="left" class="pad24" style="padding: 0 64px;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" class="logo" style="padding: 48px 0;"><a href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiX9NQvXQ9aE-2FeLMhxL9C-2FAEerk2_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dT8hiOQ5EDRx3fHM-2BeYkU4qHqDyPFxUwZuSfyRj0SIOTkg-2B18lVSaIyNV-2FYADATgkv5vXH4igP0Invu4xOPQBpgg16ckbsIS8IRV3mGaj1X5KhMT-2FuLlWkyJ0vYYtn7DRdGkRIV8GNdbKAWhFWQmTP4s1sfO-2BmfVk1PxO2rjtA0ZfcEcAKhCAzKFEEbQ9BWgK39Qvkt47rpQjykYZ9iiQAGWQLAjcs6P4DIPoAa8QmGrMb0TkMbrHUuWzG3I6o6QTpKFhzWbXT1TXbl0tj9rUZeGPY7Gxx-2FjDpfuEqSvOXz4YCMEoeSAPy7cIWp2wjaTin6ux0N-2Fsxe4v-2FsCd7o-2F1uCwW4EEDetpthuIuYYkeIXQlzypqy8rrJ5Czz-2F9QxvlX7Rurh5UPO-2FSnnEWnQNj-2Bby-2BmuZiFMapcD3VfIVucgG0YgY0q8krauzK38sC-2Bo3p3uvmDObIONy9moqGQopWgFpL5Oy8bXmdxo1-2FRjNsrDbsLgM1km0RQLa4WV7Y99oaIhdT35ahysXpZwozejK1qEgOqrm8WZjgms1TsVagTaVDuAieGpWb-2FQlcU9t3Vh8TCZEmOz2Loi3CvHDdReh6E5oaG4UkH-2BbB80dFEw5AwJF-2B0-3D" target="_blank" universal="true"><img alt="DoorDash" border="0" src="https://assets.doordash.team/m/5e68fa5cbbc50c32/original/DoorDash-Logo-Red100.png" style="color: #FF3008;font-family:'TTNorms',system-ui,sans-serif;font-weight:bold;font-size:18px;text-decoration:none;" width="50"></a></td>
</tr>
<tr>
<td align="left" class="pad0" style="padding:0 64px 0 0;"><h1 style="margin:0 0 16px 0;">There are adjustments to your order.</h1></td>
</tr>
<tr>
<td align="right" style="padding: 0 0 40px 0;"><img alt="" src="https://img.cdn4dd.com/s/convenience/images/adjustments_eml_grocery.png" width="380" style="width:100%;max-width:380px;"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="left" class="pad8" style="padding: 0 40px 40px;">
<table align="left" border="0" cellpadding="0" cellspacing="0" id="Basic000" role="presentation" style="width:100%;border-radius:25px;">
<tbody>
<tr>
<td align="left" class="pad24" style="padding:40px 40px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 32px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 24px 0;"><!----> <p class="p2" style="margin:0 0 4px 0;">Paid with credits</p> <p class="p2" style="margin:0 0 4px 0;">ALDI</p> <p class="p2" style="margin:0 0 4px 0;"></p> <p class="p2"><strong>Total: $0.00</strong></p></td>
</tr>
<tr>
<td align="left" style="padding:0 0 24px 0;border-bottom:1px solid #C4C4C4;"><h4>Your receipt</h4> <!----> <p class="p2" style="margin:0 0 4px 0;"></p> <!----> <p class="p2"><a href="" style="color:#191919;text-decoration:none;">19 Lady Penrhyn Dr, Wyndham Vale VIC 3024, Australia</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!---->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 16px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><h4>Items that were adjusted</h4></td>
</tr>
<tr>
<td align="left"><!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- -->
<tbody>
<tr>
<td align="left" class="label" style="padding: 0 0 8px 0;"><!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <span style="font-family:'TTNorms',system-ui,sans-serif;font-size:12px;line-height:18px;color:#FEFFFF;background-color:#494949;display:inline-block;padding:1px 4px;border-radius:4px;font-weight:700;white-space:nowrap;">Out of Stock</span></td>
</tr> <!-- --> <!-- -->
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class="grayCopy"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:#767676;"><strong>5x</strong> Coca-Cola Coke Zero Sugar Soft Drink (1.5 L)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: line-through; margin: 0 0 4px 0;color:#767676;white-space:nowrap;">&nbsp;$16.45&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- -->
<tbody>
<tr>
<td align="left" class="label" style="padding: 0 0 8px 0;"><!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <span style="font-family:'TTNorms',system-ui,sans-serif;font-size:12px;line-height:18px;color:#FEFFFF;background-color:#494949;display:inline-block;padding:1px 4px;border-radius:4px;font-weight:700;white-space:nowrap;">Substituted</span></td>
</tr> <!-- --> <!-- --> <!-- -->
<tr>
<td align="left"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" valign="top" class="grayCopy"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color: #767676;"><strong>2x</strong> Specially Selected Beef Wagyu Burger (150 g)</p></td>
<td align="right" valign="top" class="grayCopy" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: line-through; margin: 0 0 4px 0;color: #767676;white-space:nowrap;">&nbsp;$8.58&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr>
<tr>
<td align="left" style="color: #191919;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; margin: 0 0 8px 0; font-size: 16px; line-height: 20px; font-weight: 700;">Substituted with:</p></td>
</tr>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" valign="top" style="color: #191919;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;"><strong>1x</strong> Ready, Set...Cook! Wagyu Beef Burgers (400 g)</p></td>
<td align="right" valign="top" style="color: #191919; padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;white-space:nowrap;">$9.39</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: none;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- -->
<tbody>
<tr>
<td align="left" class="label" style="padding: 0 0 8px 0;"><!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <span style="font-family:'TTNorms',system-ui,sans-serif;font-size:12px;line-height:18px;color:#FEFFFF;background-color:#494949;display:inline-block;padding:1px 4px;border-radius:4px;font-weight:700;white-space:nowrap;">Substituted</span></td>
</tr> <!-- --> <!-- --> <!-- -->
<tr>
<td align="left"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" valign="top" class="grayCopy"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color: #767676;"><strong>1x</strong> Bon Appetit Sliced Brioche Burger Buns with Sesame Seeds (200 g)</p></td>
<td align="right" valign="top" class="grayCopy" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: line-through; margin: 0 0 4px 0;color: #767676;white-space:nowrap;">&nbsp;$3.89&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr>
<tr>
<td align="left" style="color: #191919;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; margin: 0 0 8px 0; font-size: 16px; line-height: 20px; font-weight: 700;">Substituted with:</p></td>
</tr>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" valign="top" style="color: #191919;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;"><strong>1x</strong> Bon Appetit Sliced Brioche Burger Buns (200 g)</p></td>
<td align="right" valign="top" style="color: #191919; padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;white-space:nowrap;">$3.89</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!---->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 32px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><h4>Items you ordered</h4></td>
</tr>
<tr>
<td align="left" style="padding:0 0 16px 0;border-bottom:1px solid #C4C4C4;"><!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Ironbark Pork Belly Pack</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$24.21&nbsp;</p></td>
</tr> <!-- -->
<tr>
<td colspan="2" align="left" class="grayCopy"><p class="para-md" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 14px; line-height: 18px; margin: 0 0 4px 0;color: #767676;">$18.99/kg • Purchased 1.275 kg</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Green Capsicum Loose (each) (each)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$1.54&nbsp;</p></td>
</tr> <!-- -->
<tr>
<td colspan="2" align="left" class="grayCopy"><p class="para-md" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 14px; line-height: 18px; margin: 0 0 4px 0;color: #767676;">$5.99/kg • Purchased 0.257 kg</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>2x</strong> Broccoli Loose (each)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.08&nbsp;</p></td>
</tr> <!-- -->
<tr>
<td colspan="2" align="left" class="grayCopy"><p class="para-md" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 14px; line-height: 18px; margin: 0 0 4px 0;color: #767676;">$4.49/kg • Purchased 0.685 kg</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Ginger Loose (each)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$4.47&nbsp;</p></td>
</tr> <!-- -->
<tr>
<td colspan="2" align="left" class="grayCopy"><p class="para-md" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 14px; line-height: 18px; margin: 0 0 4px 0;color: #767676;">$29.99/kg • Purchased 0.149 kg</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Berg Streaky Bacon (200 g)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$4.69&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Emporium Selection Burrata (150 g)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$7.09&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Anco Soft Anco Soft Fabric Softener Concentrate - Cashmere Touch (1 L)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.99&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Pure Vita Canola Oil (2 L)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$6.49&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> The Herb Garden Jalapeno Chillies (80 g)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.49&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Farmdale Thickened Cream (300 ml)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.69&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Mandarins (1 kg)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.49&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Sweet Valley Fruit Salad in Syrup (825 g)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.89&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>3x</strong> Hass Avocado</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$5.37&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Spring Onion Bunch</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$2.69&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: none;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> The Herb Garden Coriander Bunch</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$2.99&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!---->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 32px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 24px 0;border-bottom:1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><p class="p2">Subtotal</p></td>
<td align="right" valign="bottom"><p class="p2">$94.45</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Bag Fee</p></td>
<td align="right" valign="top"><p class="p2">$0.75</p></td>
</tr> <!----> <!----> <!---->
<tr>
<td align="left"><p class="p2">Tax</p></td>
<td align="right" valign="top"><p class="p2">$0.00</p></td>
</tr> <!----> <!----> <!---->
<tr>
<td align="left"><p class="p2">Delivery fee</p></td>
<td align="right" valign="top"><p class="p2">$0.00</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Service&nbsp;fee</p></td>
<td align="right" valign="top"><p class="p2">$8.95</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Dasher&nbsp;tip</p></td>
<td align="right" valign="top"><p class="p2">$0.00</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Discount</p></td>
<td align="right" valign="top"><p class="p2">-$25.00</p></td>
</tr> <!----> <!----> <!----> <!---->
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><p class="p1" style="font-weight:700;">Final total charged</p></td>
<td align="right" valign="bottom"><p class="p1" style="font-weight:700;">$0.00</p></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="left" style="padding:16px 0 24px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><!----> <!----> <!----> <p class="p4" style="margin:0 0 16px;font-weight:400;">This email confirms revisions made to your original DoorDash order and reflects the final amount charged. The new total cost of your order is above and includes all taxes and fees. Payment processing adjustments to the original charge may take up to 5-7 business days to process.</p> <!----> <p class="p2" style="margin:0 0 16px;"><a class="Red200" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiUYUIJyXMOWcKUkQoS6w1cidTUBltD9gsdDsG54KhCqi0TpTxXlRftLSD-2F0zchmY726xMeqb-2BYjhquRL7EwEUa-2B-C1a_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dT8hiOQ5EDRx3fHM-2BeYkU4qHqDyPFxUwZuSfyRj0SIOTkg-2B18lVSaIyNV-2FYADATgkv5vXH4igP0Invu4xOPQBpgg16ckbsIS8IRV3mGaj1X5KhMT-2FuLlWkyJ0vYYtn7DRdGkRIV8GNdbKAWhFWQmTP4s1sfO-2BmfVk1PxO2rjtA0ZfcEcAKhCAzKFEEbQ9BWgK39Qvkt47rpQjykYZ9iiQAGWQLAjcs6P4DIPoAa8QmGrMb0TkMbrHUuWzG3I6o6QTpKFhzWbXT1TXbl0tj9rUZeGPY7Gxx-2FjDpfuEqSvOXz4YCMEoeSAPy7cIWp2wjaTin6ux0N-2Fsxe4v-2FsCd7o-2F1uCwW4EEDetpthuIuYYkeIXQlzypqy8rrJ5Czz-2F9QxvlX7Rurh5UPO-2FSnnEWnQNj-2Bby-2BmuZiFMapcD3VfIVucgG0YgY0q8krauzK38sC-2Bo3p3uvmDObIONy9moqGQopWgFpL5Oy8bXmdxo1-2FRjNsrDbsIzcz91FpNoAfjDMq4Z1wpXHGTMPHfVoKcReXA-2FJ6jaKo-2B6xGAG-2Bp5h6Him0z2xNQVc2hNO8YatcJsnFfudME5OtlTe61-2Bq439PkYJf0JqaFj1iwRjZNlhThyTmY7ccTBU-3D" target="_blank" style="font-weight:700;text-decoration:none;" universal="true">Get Order Help</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
<table align="center" border="0" cellpadding="0" cellspacing="0" class="full" id="Footer" role="presentation" style="width:700px;">
<tbody>
<tr>
<td valign="top" align="center" style="padding:0 0 24px 0;"><!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:620px;">
<tr>
<td align="center">
<![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" id="Footer" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width: 100%; max-width: 700px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="center" style="padding: 0 24px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width:100%;max-width:572px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding:0 0 48px 0;border-bottom: 1px solid #E7E7E7;"></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 32px 0 16px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;">©2026 <a style="color: #9A9A9A; text-decoration: none;">DoorDash Technologies Australia Pty Ltd <br>401 Collins St. <br>Melbourne, VIC 3000 Australia</a></p> <p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYAqF1KGCKTTTznL6MvOfulOsmFa2kqsuG7LjgY0AllZKBKWegcAPOx5sr25l15pnWbLZL6VnVCDFc3hEnP4sDnrjJH9_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dT8hiOQ5EDRx3fHM-2BeYkU4qHqDyPFxUwZuSfyRj0SIOTkg-2B18lVSaIyNV-2FYADATgkv5vXH4igP0Invu4xOPQBpgg16ckbsIS8IRV3mGaj1X5KhMT-2FuLlWkyJ0vYYtn7DRdGkRIV8GNdbKAWhFWQmTP4s1sfO-2BmfVk1PxO2rjtA0ZfcEcAKhCAzKFEEbQ9BWgK39Qvkt47rpQjykYZ9iiQAGWQLAjcs6P4DIPoAa8QmGrMb0TkMbrHUuWzG3I6o6QTpKFhzWbXT1TXbl0tj9rUZeGPY7Gxx-2FjDpfuEqSvOXz4YCMEoeSAPy7cIWp2wjaTin6ux0N-2Fsxe4v-2FsCd7o-2F1uCwW4EEDetpthuIuYYkeIXQlzypqy8rrJ5Czz-2F9QxvlX7Rurh5UPO-2FSnnEWnQNj-2Bby-2BmuZiFMapcD3VfIVucgG0YgY0q8krauzK38sC-2Bo3p3uvmDObIONy9moqGQopWgFpL5Oy8bXmdxo1-2FRjNsrDbsIjwoUCSEKvO5n-2Bj16PIPm9vylVUKXBAg-2Fy62EoW7wAeLOkv7ljadn2lJdO1Z8YyTZVsg50XPfub07LBUsUSDmpWsvorrlalMazpGr6pIsnVp6l5lDVPbZ82aaASmCqGBc-3D" target="_blank" style="color: #9A9A9A; text-decoration: none;">Privacy Policy</a></p></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 0 0 24px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:500;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYABnncKv1afIihr5Gt6bkMj2LIo_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dT8hiOQ5EDRx3fHM-2BeYkU4qHqDyPFxUwZuSfyRj0SIOTkg-2B18lVSaIyNV-2FYADATgkv5vXH4igP0Invu4xOPQBpgg16ckbsIS8IRV3mGaj1X5KhMT-2FuLlWkyJ0vYYtn7DRdGkRIV8GNdbKAWhFWQmTP4s1sfO-2BmfVk1PxO2rjtA0ZfcEcAKhCAzKFEEbQ9BWgK39Qvkt47rpQjykYZ9iiQAGWQLAjcs6P4DIPoAa8QmGrMb0TkMbrHUuWzG3I6o6QTpKFhzWbXT1TXbl0tj9rUZeGPY7Gxx-2FjDpfuEqSvOXz4YCMEoeSAPy7cIWp2wjaTin6ux0N-2Fsxe4v-2FsCd7o-2F1uCwW4EEDetpthuIuYYkeIXQlzypqy8rrJ5Czz-2F9QxvlX7Rurh5UPO-2FSnnEWnQNj-2Bby-2BmuZiFMapcD3VfIVucgG0YgY0q8krauzK38sC-2Bo3p3uvmDObIONy9moqGQopWgFpL5Oy8bXmdxo1-2FRjNsrDbsIrFQJW5Yztgt2Jh362zEdlWVE33xdgG5SV98hQgmujo0E4JvhCRaOchZGxbbbqba5s49iSoOH1uA1snY7iHXvSUNUHWVknLjLn6FaOweBoSS4nrQXEl0UQpbIiLKqwLeM-3D" target="_blank" style="color:#9A9A9A;text-decoration:none;">Help Center</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!--[if (gte mso 9)|(IE)]>
</td>
</tr>
</table>
<![endif]--></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
</div>
<img src="https://tracksg.doordash.com/wf/open?upn=u001.EBL2ug8kstebd25Xirrl3olMckTI261ldPjJ39bNHcC7U6EKGAOA4dSVB97lcv3b8qsQRq6LwkHED6F3X4gqaFe59-2BHz9QfrDL7jp-2BN3jX4WgiXvlTBIakpalIO3JdserrDEfSsXb7VYNi8XmPfj32D9Xcsg-2BKnH54BOn83XeKSYsMOiCB2O7NlyiRLKTOp-2FBccW4vEHOV-2FHaLf-2FAjylTtey6rU4sqCD635svGzB8KNIeJlLUHQHFm36Lriv1GKTHI0TRmME0InLq-2F8D2jWE2PvL5vl2AuTCSyofMbb8v6F0-2Fp2tKFfRS7SLHGABa-2BiIEO0Cj-2B51-2BCj8vI17Ej73lSLlLpOQjZQ5w6Xjpy94GXTJoyFOgOCkMe1dYoozgKu053kwmU-2FQgzvTvZvWljLEAh8AKZgpttD0qf9fwmzT-2FfbmEACAx1lYnUbMQSEnKVrq-2BN93H5GudoxrcNAH5xj7CeRBdn-2B-2Fm2uq78KkVh9j7d2poYBFM-2F0phg4yfzMJ8HenyMNPoDsxTYF2uwr9FPYHeHB92FdN-2FyMNtbhWu3f2Bj2Jp32hssVlE8ypjMbIy3F8Z4K8hxnzYgtXhQn9f7NJRAIR6ZxzgEYOW9gIQ1FDvzuTPT-2BOgXirIYJd7VNW1ls-2F33I09NUJXDzuQt6FpCbkzrw5rMFL9uAjGdsCzWAwAdtI0Vpj9QHVbFrQ7V0Km2o1xng4pDAf2zzOoVcOfy6Llv7NL5VR958SiCNPk-2FivSDJKGbqADXQIiUAHJEWxjJh9" alt="" width="1" height="1" border="0" style="height:1px !important;width:1px !important;border-width:0 !important;margin-top:0 !important;margin-bottom:0 !important;margin-right:0 !important;margin-left:0 !important;padding-top:0 !important;padding-bottom:0 !important;padding-right:0 !important;padding-left:0 !important;"/></body>
</html>
@@ -0,0 +1,592 @@
<!doctype html>
<html lang="en" dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1 user-scalable=yes">
<meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
<meta name="x-apple-disable-message-reformatting">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<title>DoorDash</title> <!-- WEB FONTS --> <!--[if !mso]>-->
<style type="text/css">
@font-face{font-family:'TTNorms';font-style:normal;font-weight:700;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Bold.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:600;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-DemiBold.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:500;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Medium.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:450;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Normal.woff2')format('woff2');}
@font-face{font-family:'TTNorms';font-style:normal;font-weight:400;src:url('https://typography.doordash.com/TTNorms-Pro/TTNormsPro-Regular.woff2')format('woff2');}
</style> <!--<![endif]--> <!-- STYLE RESETS -->
<style type="text/css">a[href^="tel"],a[href^="sms"]{color:inherit;cursor:default;font-weight:inherit;text-decoration:none}body{-ms-text-size-adjust:100%;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;mso-line-height-rule:exactly;}html,body{width:100%;margin:0;padding:0}img{border:0;display:block;height:auto;line-height:100%;outline:none;text-decoration:none}table{border:0 !important;padding:0 !important; border-collapse:collapse !important;mso-table-lspace:0pt;mso-table-rspace:0pt;}u + .body a{color:inherit;font-family:inherit;font-size:inherit;font-weight:inherit;line-height:inherit}u ~ img + div > div{display:none;}u + .body{width:100%;}.body a[x-apple-data-detectors=true]{color:inherit!important;text-decoration:inherit!important}span.MsoHyperlink{color:inherit !important;mso-style-priority:99 !important}span.MsoHyperlinkFollowed{color:inherit !important;mso-style-priority:99 !important}
</style> <!-- BACKGROUND COLORS -->
<style type="text/css">
body,#MainTable{background-color:#F4F4F4;}
#Basic000{background-color:#FEFFFF;}
#Sky200{background-color:#DDF4F4;}
</style> <!-- FONT STYLES -->
<style type="text/css">
h1,h2,h3,h4,h5,h6{font-family:'TTNorms',system-ui,sans-serif;font-weight:700;margin:0 0 8px 0;}
p,ol,ul{font-family:'TTNorms',system-ui,sans-serif;font-weight:450;margin:0 0 8px 0;}
ul,ol{padding:0 0 0 20px;}
li{font-weight:450;margin:0 0 8px 0;}
h1{font-size:50px;line-height:50px;letter-spacing:-0.03em;}
h2{font-size:40px;line-height:40px;letter-spacing:-0.02em;}
h3{font-size:32px;line-height:32px;letter-spacing:-0.02em;}
h4{font-size:24px;line-height:24px;letter-spacing:-0.01em;}
h5{font-size:20px;line-height:22px;letter-spacing:-0.01em;}
h6{font-size:16px;line-height:18px;}
p.p1{font-size:20px;line-height:26px;}
p.p2{font-size:16px;line-height:22px;}
p.p4{font-size:12px;line-height:14px;}
sup{font-size:11px;line-height:11px;}
</style> <!-- FONT COLORS -->
<style type="text/css">
#MainTable table td{color:#191919;}
#MainTable table td a{color:inherit;}
#MainTable table td p a{text-decoration:underline;}
.Red200{color:#EB1700 !important;}
</style> <!-- CTAs --> <!-- MOBILE STYLES -->
<style type="text/css">
@media only screen and (max-width:699px){
#MainTable > table {max-width:410px!important;}
.full{width:100%!important;height:auto!important;}
.pad0{padding-left:0!important;padding-right:0!important;}
.pad8{padding-left:8px!important;padding-right:8px!important;}
.pad24{padding-left:24px!important;padding-right:24px!important;}
.logo{padding-top:40px!important;padding-bottom:40px!important;}
h1{font-size:40px!important;line-height:40px!important;letter-spacing:-0.02em!important;}
h2{font-size:32px!important;line-height:32px!important;}
h3{font-size:24px!important;line-height:24px!important;letter-spacing:-0.01em!important;}
}
</style> <!-- DARK MODE STYLES -->
<style type="text/css">
@media (prefers-color-scheme:dark){
body,#MainTable,#Footer{background-color:#000000!important;background-image:linear-gradient(#000000,#000000)!important;}
table[id^="Basic"]{background-color:#191919!important;background-image:linear-gradient(#191919,#191919)!important;}
table[id^="Sky"],table[id^="Blue"]{background-color:#002629!important;background-image:linear-gradient(#002629,#002629)!important;}
#MainTable table td{color:#FFFFFF!important;}
#MainTable #Footer table td a{color:#FFFFFF!important;}
#MainTable .Red200{color:#FF3008!important;}
#MainTable .label span{color:#494949!important;background-color:#FEFFFF!important;}
#MainTable .grayCopy p{color:#A6A6A6!important;}
}
</style>
<style type="text/css">
:root{color-scheme:light dark;supported-color-schemes:light dark;}
</style> <!-- GMAIL APP DARK MODE FIX --> <!-- OUTLOOK SPECIFIC CSS --> <!--[if gte mso 9]>
<style type="text/css">
#MainTable td a{color:#191919;}
ol,ul{margin-left:20px !important;}
li{text-indent:-1em;}
</style>
<noscript>
<xml>
<o:OfficeDocumentSettings>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
</noscript>
<![endif]-->
</head>
<body class="body" style="width:100%;margin:0;padding:0;">
<span style="color:transparent;visibility:hidden;display:none;opacity:0;height:0;width:0;font-size:0;"></span>
<div role="article" aria-roledescription="email" aria-label="DoorDash Email" lang="en" dir="ltr" style="font-size:medium; font-size:max(16px, 1rem);">
<div style="display: none; max-height: 0px; overflow: hidden;">
 ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏  ­͏
</div>
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="center" id="MainTable" style="background-color:#F4F4F4;">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="full" id="Sky200" role="presentation" style="width:700px;">
<tbody>
<tr>
<td align="left" class="pad24" style="padding: 0 64px;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" class="logo" style="padding: 48px 0;"><a href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiX9NQvXQ9aE-2FeLMhxL9C-2FAEa1Qb_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dTef2rlCVIu36es-2FxRXYDPOLHXG7qitIbeuwICQOtiAiJyF0XW5mYCg4EenXQa5FiPOrlqnzXCXafNC5mlJGvxOlPnGz4KG6-2FibY4F4HrGTkxRoVpyf9CEBWQB3h4B6-2F1vV34umJj7-2FLlLpcjkRso-2FZrw9zD-2FDCCnEzAJ9b7RCYUIm4jyKucNAH6Fj2kRAnALL6-2FL0QY3vFFztXGwYqrzLSreyQBjHZ9aQwUSam7UJYCAaq48Y50TUgS9EuM1bSw4Twf5p6fp3H4FoRGPMueME-2FSTdpWyR6zn70BPVqAFezHiorOMilHHsOq6nk1-2FqORI-2F0veiu3RW2zrCwnVrabBGigtiGnhurr7p9nOs1AjdyZa-2Fy5Uh8bX3CPB4wzCMXE7O-2FOmAxPQkFoB0-2BgXl8YJlxRNDOaueR-2BgqPA2uYZxr4-2BQtI4L0YynseA3NMscHGJNGN88RJHrH4CqPbPBkbpXelO-2Ftz4qkPn2adhNtmCgMrl4mfF5lxevUpoJQJ7UmMxollJfoLEGLjLhrl7sdZrHH5YHZ8O6My471AKWPRD9-2Fi1Gj5kDczANohQUl0hqEmYQa58AnEUM4SbTghHAzOx2-2FdIewmuvSy5w0lyALMIuqj5OPNSb0LQsZWNIEFVG8SDXp" target="_blank" universal="true"><img alt="DoorDash" border="0" src="https://assets.doordash.team/m/5e68fa5cbbc50c32/original/DoorDash-Logo-Red100.png" style="color: #FF3008;font-family:'TTNorms',system-ui,sans-serif;font-weight:bold;font-size:18px;text-decoration:none;" width="50"></a></td>
</tr>
<tr>
<td align="left" class="pad0" style="padding:0 64px 0 0;"><h1 style="margin:0 0 16px 0;">Final receipt.</h1></td>
</tr>
<tr>
<td align="right" style="padding: 0 0 40px 0;"><img alt="" src="https://img.cdn4dd.com/s/convenience/images/adjustments_eml_grocery.png" width="380" style="width:100%;max-width:380px;"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="left" class="pad8" style="padding: 0 40px 40px;">
<table align="left" border="0" cellpadding="0" cellspacing="0" id="Basic000" role="presentation" style="width:100%;border-radius:25px;">
<tbody>
<tr>
<td align="left" class="pad24" style="padding:40px 40px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 32px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 24px 0;"><!--
--> <p class="p2" style="margin:0 0 4px 0;">Paid with MasterCard Ending in 8032&nbsp;and/or&nbsp;credits</p> <p class="p2" style="margin:0 0 4px 0;">Woolworths</p> <p class="p2" style="margin:0 0 4px 0;"></p> <p class="p2"><strong>Total: $60.93</strong></p></td>
</tr>
<tr>
<td align="left" style="padding:0 0 24px 0;border-bottom:1px solid #C4C4C4;"><h4>Your receipt</h4> <!----> <p class="p2" style="margin:0 0 4px 0;"></p> <!----> <p class="p2"><a href="" style="color:#191919;text-decoration:none;">19 Lady Penrhyn Dr, Wyndham Vale VIC 3024, Australia</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!---->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 32px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><h4>Items you ordered</h4></td>
</tr>
<tr>
<td align="left" style="padding:0 0 16px 0;border-bottom:1px solid #C4C4C4;"><!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Woolworths Corned Beef Silverside (each)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$15.54&nbsp;</p></td>
</tr> <!-- -->
<tr>
<td colspan="2" align="left" class="grayCopy"><p class="para-md" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 14px; line-height: 18px; margin: 0 0 4px 0;color: #767676;">$11.50/kg • Purchased 1.351 kg</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>2x</strong> Jalapeno Chilli (1 ea)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$2.30&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>2x</strong> Coca-Cola Zero Sugar Soft Drink Bottle (2 L)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$9.00&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Kewpie Sriracha Mayonnaise (300 g)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$6.11&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Woolworths Angus Quarter Pound Beef Burgers (454 g × 4 pk)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$9.00&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Green Capsicum (1 ea)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$1.40&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Brioche Gourmet Sesame Brioche Burger Buns (4 pk)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$7.30&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>2x</strong> Hass Avocado</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$4.10&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Helga's Light Rye Bread (680 g)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$5.95&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Red Capsicum (1 ea)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$1.40&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: 1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Garlic Head</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$2.15&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----> <!-- -->
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding: 16px 0 0 0; border-bottom: none;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!-- --> <!-- -->
<tbody>
<tr>
<td align="left" style="padding: 0 0 12px 0;"><!-- --> <!-- --> <!-- -->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width: 100%; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<!--
-->
<tbody>
<tr>
<td align="left" valign="top" class=""><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; margin: 0 0 4px 0;color:inherit;"><strong>1x</strong> Lee Kum Kee Premium Dark Soy Sauce (250 ml)</p></td>
<td align="right" valign="top" style="padding: 0 0 0 24px;"><p class="para-rg" style="font-family: 'TTNorms',system-ui,sans-serif; font-weight: 500; font-size: 16px; line-height: 20px; text-decoration: none; margin: 0 0 4px 0;color:inherit;white-space:nowrap;">&nbsp;$3.65&nbsp;</p></td>
</tr> <!-- -->
</tbody>
</table></td>
</tr> <!-- --> <!-- -->
</tbody>
</table></td>
</tr>
</tbody>
</table> <!----></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!---->
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 32px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left" style="padding:0 0 24px 0;border-bottom:1px solid #C4C4C4;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><p class="p2">Subtotal</p></td>
<td align="right" valign="bottom"><p class="p2">$67.90</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Bag Fee</p></td>
<td align="right" valign="top"><p class="p2">$0.50</p></td>
</tr> <!----> <!----> <!---->
<tr>
<td align="left"><p class="p2">Tax</p></td>
<td align="right" valign="top"><p class="p2">$0.00</p></td>
</tr> <!----> <!----> <!---->
<tr>
<td align="left"><p class="p2">Delivery fee</p></td>
<td align="right" valign="top"><p class="p2">$0.00</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Service&nbsp;fee</p></td>
<td align="right" valign="top"><p class="p2">$6.11</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Dasher&nbsp;tip</p></td>
<td align="right" valign="top"><p class="p2">$0.00</p></td>
</tr> <!----> <!---->
<tr>
<td align="left"><p class="p2">Discount</p></td>
<td align="right" valign="top"><p class="p2">-$13.58</p></td>
</tr> <!----> <!----> <!----> <!---->
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><p class="p1" style="font-weight:700;">Final total charged</p></td>
<td align="right" valign="bottom"><p class="p1" style="font-weight:700;">$60.93</p></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="left" style="padding:16px 0 24px 0;">
<table align="left" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td align="left"><!----> <!----> <!----> <p class="p4" style="margin:0 0 16px;font-weight:400;">This email confirms revisions made to your original DoorDash order and reflects the final amount charged. The new total cost of your order is above and includes all taxes and fees. Payment processing adjustments to the original charge may take up to 5-7 business days to process.</p> <!----> <p class="p2" style="margin:0 0 16px;"><a class="Red200" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiXhYhQ4ra2libvRVipt1sfv4E-2FKwlbgukGbMndo1ZsJhMUiuAxeGb86p06pmk6V-2FQsCkNG42P38jfRm6zgoux4YpHAP_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dTef2rlCVIu36es-2FxRXYDPOLHXG7qitIbeuwICQOtiAiJyF0XW5mYCg4EenXQa5FiPOrlqnzXCXafNC5mlJGvxOlPnGz4KG6-2FibY4F4HrGTkxRoVpyf9CEBWQB3h4B6-2F1vV34umJj7-2FLlLpcjkRso-2FZrw9zD-2FDCCnEzAJ9b7RCYUIm4jyKucNAH6Fj2kRAnALL6-2FL0QY3vFFztXGwYqrzLSreyQBjHZ9aQwUSam7UJYCAaq48Y50TUgS9EuM1bSw4Twf5p6fp3H4FoRGPMueME-2FSTdpWyR6zn70BPVqAFezHiorOMilHHsOq6nk1-2FqORI-2F0veiu3RW2zrCwnVrabBGigtiGnhurr7p9nOs1AjdyZa-2Fy5Uh8bX3CPB4wzCMXE7O-2FOmAxPQkFoB0-2BgXl8YJlxRNDOaueR-2BgqPA2uYZxr4-2BQtI4L0YynseA3NMscHGJNGN88RJHrH4CqPbPBkbpXelO-2Ftz4qkPn2adhNtmCgMrl40rFinK7NkUBQ-2Fl8tQtwvq8JTmf6gxu6dY07cNv4deM6rPu-2BQ-2FvHH4q00LtMFjDuuQ3oUFkbnbQHKhXkIUv3eSN4o7Kl6vrZHuHXulUntzFpaf0-2BlkucXK2YwHzC7HliOAyEF6-2FBa1FHUj7-2B2nt5St" target="_blank" style="font-weight:700;text-decoration:none;" universal="true">Get Order Help</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
<table align="center" border="0" cellpadding="0" cellspacing="0" class="full" id="Footer" role="presentation" style="width:700px;">
<tbody>
<tr>
<td valign="top" align="center" style="padding:0 0 24px 0;"><!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:620px;">
<tr>
<td align="center">
<![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" id="Footer" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width: 100%; max-width: 700px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="center" style="padding: 0 24px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width:100%;max-width:572px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding:0 0 48px 0;border-bottom: 1px solid #E7E7E7;"></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 32px 0 16px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;">©2026 <a style="color: #9A9A9A; text-decoration: none;">DoorDash Technologies Australia Pty Ltd <br>401 Collins St. <br>Melbourne, VIC 3000 Australia</a></p> <p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYAqF1KGCKTTTznL6MvOfulOsmFa2kqsuG7LjgY0AllZKBKWegcAPOx5sr25l15pnWbLZL6VnVCDFc3hEnP4sDnr_qFX_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dTef2rlCVIu36es-2FxRXYDPOLHXG7qitIbeuwICQOtiAiJyF0XW5mYCg4EenXQa5FiPOrlqnzXCXafNC5mlJGvxOlPnGz4KG6-2FibY4F4HrGTkxRoVpyf9CEBWQB3h4B6-2F1vV34umJj7-2FLlLpcjkRso-2FZrw9zD-2FDCCnEzAJ9b7RCYUIm4jyKucNAH6Fj2kRAnALL6-2FL0QY3vFFztXGwYqrzLSreyQBjHZ9aQwUSam7UJYCAaq48Y50TUgS9EuM1bSw4Twf5p6fp3H4FoRGPMueME-2FSTdpWyR6zn70BPVqAFezHiorOMilHHsOq6nk1-2FqORI-2F0veiu3RW2zrCwnVrabBGigtiGnhurr7p9nOs1AjdyZa-2Fy5Uh8bX3CPB4wzCMXE7O-2FOmAxPQkFoB0-2BgXl8YJlxRNDOaueR-2BgqPA2uYZxr4-2BQtI4L0YynseA3NMscHGJNGN88RJHrH4CqPbPBkbpXelO-2Ftz4qkPn2adhNtmCgMrl47hiO5jAJKuIZrUFfimDnpntNrXHRtriBc5B6j34phPs9t-2FTsNtprBO5gereYjazskrJGz4kTq383Phk6ev5l-2FwkKCZAvVCUn589YJbi-2FoyqrxbStev5iE7PJ2Us6bPgQpdvcUQSEkpYDzIyI-2Blcws" target="_blank" style="color: #9A9A9A; text-decoration: none;">Privacy Policy</a></p></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 0 0 24px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:500;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYABnncKv1afIihr5Gt6bkMjesVR_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDdm5muv43mKBZj0FtslvRhwurT1HU7WzBFk0uKPD12dTef2rlCVIu36es-2FxRXYDPOLHXG7qitIbeuwICQOtiAiJyF0XW5mYCg4EenXQa5FiPOrlqnzXCXafNC5mlJGvxOlPnGz4KG6-2FibY4F4HrGTkxRoVpyf9CEBWQB3h4B6-2F1vV34umJj7-2FLlLpcjkRso-2FZrw9zD-2FDCCnEzAJ9b7RCYUIm4jyKucNAH6Fj2kRAnALL6-2FL0QY3vFFztXGwYqrzLSreyQBjHZ9aQwUSam7UJYCAaq48Y50TUgS9EuM1bSw4Twf5p6fp3H4FoRGPMueME-2FSTdpWyR6zn70BPVqAFezHiorOMilHHsOq6nk1-2FqORI-2F0veiu3RW2zrCwnVrabBGigtiGnhurr7p9nOs1AjdyZa-2Fy5Uh8bX3CPB4wzCMXE7O-2FOmAxPQkFoB0-2BgXl8YJlxRNDOaueR-2BgqPA2uYZxr4-2BQtI4L0YynseA3NMscHGJNGN88RJHrH4CqPbPBkbpXelO-2Ftz4qkPn2adhNtmCgMrl4Xvmy9Ho7hVCvflBaTaT7GIPK-2Bx-2FVY0eWPUYOIl9ze-2FigbiVg7zeZtEGGvUnrFsPyYMZvNqAmnc5awn0lwnuo6T2MwPVn7itLe2lk679GxtX4NcwYfkPFJXWYwEqreqmpCX0cU2u5EQKvkeFL5tyNJ" target="_blank" style="color:#9A9A9A;text-decoration:none;">Help Center</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!--[if (gte mso 9)|(IE)]>
</td>
</tr>
</table>
<![endif]--></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
</div>
<img src="https://tracksg.doordash.com/wf/open?upn=u001.EBL2ug8kstebd25Xirrl3olMckTI261ldPjJ39bNHcC7U6EKGAOA4dSVB97lcv3b8qsQRq6LwkHED6F3X4gqaFe59-2BHz9QfrDL7jp-2BN3jX4WgiXvlTBIakpalIO3Jdse0BvY-2BpzLRd3B7D76PRNnOdtT8H1IzuhLRJrs8Ejc-2BQ4LU1ObPOGMj6kj4yuf9wvF-2BNU8yHnNyO0aMIUyf7Vw-2FvxkWQyIhy6jsNc64aO9QhWMEzgvfqcwerkGC0infSMLleveIQg1DJBFCa1l1sbtqm8v4JdVcD3tIswbkSwUBel2KQ6xwvitDjmSW4JqAVQjU2bnGfsVtQIUlNm-2FVkiKuTOkUSpSv-2BlmuRSRwJBxspIW-2FHL-2Fizzna0UNWeoxCQEouEyMXVglI9wvbdjxbE2fJhnbSO5BQgiIaJi6Z1Agc9UNZnRJQfmuKx-2BvkOjjEvTyMkvt-2F1GvutzvpeXgVGLKtJPwmIIEYfS4bk0NKmMQHCG0VBFaOwtyWNr32tHHB6clMeOlpiIJ9B-2FV6NK2NOKOn7nF2XPwImzV33xN-2B0bIZZeeDZf0piG4s3LMX9IoAqChWag-2BAHkcHaYx0ULMfGzIdlJCvGzkUFqfvXEkO7EloGLJ7Ir77VX8C-2BK1PF-2Bev7l0-2F1IBaXJUUw185DM9Yga0FDlihJgZGc0DBp8ml0RmuDjeqZPfpMHZgCXSm-2BXpoAOZg8Jjnj0I8Xr3SrabOHhH5IyYeOz-2FFmDwDDEXGh7pvKTOmsNosAQAHnmTCzcE1ABT" alt="" width="1" height="1" border="0" style="height:1px !important;width:1px !important;border-width:0 !important;margin-top:0 !important;margin-bottom:0 !important;margin-right:0 !important;margin-left:0 !important;padding-top:0 !important;padding-bottom:0 !important;padding-right:0 !important;padding-left:0 !important;"/></body>
</html>
@@ -0,0 +1,554 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
<head><!--[if gte mso 9]><xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml><![endif]-->
<title>DoorDash</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0 ">
<meta name="format-detection" content="telephone=no">
<style type="text/css">body {
margin: 0 auto;
padding: 0;
-webkit-text-size-adjust: 100%!important;
-ms-text-size-adjust: 100%!important;
-webkit-font-smoothing: antialiased!important;
}
img {
border: 0!important;
outline: none!important;
}
p {
Margin: 0px!important;
Padding: 0px!important;
}
table {
border-collapse: collapse;
mso-table-lspace: 0px;
mso-table-rspace: 0px;
}
td, a, span {
border-collapse: collapse;
mso-line-height-rule: exactly;
}
.ExternalClass * {
line-height: 100%;
}
.em_defaultlink a {
color: inherit;
text-decoration: none;
}
a[x-apple-data-detectors], u+.em_body a {
color: inherit;
text-decoration: none;
font-size: inherit;
font-family: inherit;
font-weight: inherit;
line-height: inherit;
}
@media only screen and (max-width:667px) {
.em_main_table {
width: 100%!important;
}
.em_wrapper {
width: 100%!important;
}
.em_hide {
display: none!important;
}
.em_hauto {
height: auto !important;
}
.em_full_img img {
width: 100%!important;
height: auto!important;
}
.em_pad1 {
padding-right: 10px!important;
}
.em_hauto {
height: auto!important;
}
.em_side15 {
width: 40px!important;
}
.em_h20 {
height: 40px!important;
font-size: 1px!important;
line-height: 1px!important;
}
.em_h10 {
height: 10px!important;
font-size: 1px!important;
line-height: 1px!important;
}
.em_h30 {
height: 30px!important;
}
u+.em_body .em_full_wrap {
width: 100%!important;
width: 100vw!important;
}
.em_side30 {
width: 26px!important;
}
.em_cta {
width: 190px !important;
height: 40px!important;
}
.em_cta a {
font-size: 17px !important;
line-height: 40px!important;
}
.em_h90 {
height: 140px !important;
}
.em_font_58 {
font-size: 40px!important;
line-height: 44px!important;
}
.em_pad1 {
padding: 0px 15px !important;
}
.en_icon {
width: 30px !important;
padding-bottom:10px !important;
}
.em_rounded {
border-top-left-radius: 25px !important;
border-top-right-radius: 25px !important;
}
.em_bold {
letter-spacing: -1px !important;
}
}
@media screen and (max-width:480px) {
.em_side30 {
width: 26px!important;
}
.ft_16 {
font-size: 14px!important;
line-height: 18px!important;
}
.em_side15 {
width: 40px!important;
}
.em_font_58 {
font-size: 35px!important;
line-height: 42px!important;
}
.em_cta {
width: 165px !important;
height: 38px!important;
}
.em_cta a {
font-size: 15px !important;
line-height: 38px!important;
}
.em_h90 {
height: 105px !important;
}
}
@media screen and (max-width:374px) {
.ft_16 {
font-size: 12px!important;
line-height: 16px!important;
}
.em_side15 {
width: 40px!important;
}
.em_side30 {
width: 20px!important;
}
.em_font_58 {
font-size: 30px!important;
line-height: 38px!important;
}
.em_cta {
width: 160px !important;
height: 38px!important;
}
.em_cta a {
font-size: 15px !important;
line-height: 38px!important;
}
.em_h90 {
height: 95px !important;
}
}
@media screen {
@font-face {
font-family: 'TTNorms-Regular';
src: url('https://typography.doordash.com/TTNorms-Regular.woff') format('woff'), url('https://typography.doordash.com/TTNorms-Regular.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
@font-face {
font-family: 'TTNorms-Medium';
src: url('https://typography.doordash.com/TTNorms-Medium.woff') format('woff'), url('https://typography.doordash.com/TTNorms-Medium.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
@font-face {
font-family: 'TTNorms-Bold';
src: url('https://typography.doordash.com/TTNorms-Bold.woff') format('woff'), url('https://typography.doordash.com/TTNorms-Bold.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
@font-face {
font-family: 'TTNorms-ExtraBold';
src: url('https://typography.doordash.com/TTNorms-ExtraBold.woff') format('woff'), url('https://typography.doordash.com/TTNorms-ExtraBold.ttf') format('truetype');
font-weight: normal !important;
font-style: normal !important;
mso-font-alt: 'Arial'
}
}
</style>
</head>
<body bgcolor="#ffffff" class="em_body" data-gr-c-s-loaded="true" style="margin:0px auto; padding:0px;">
<span style="color:transparent;visibility:hidden;display:none;opacity:0;height:0;width:0;font-size:0;"></span> <!-- == Body Section == -->
<table bgcolor="#ffffff" border="0" cellpadding="0" cellspacing="0" class="em_full_wrap" width="100%">
<tbody>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="em_main_table" style="width:700px;" width="700">
<tbody>
<tr>
<td align="center" valign="top"><!---->
<table align="center" bgcolor="#ededed" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h30" height="62" style="height:62px; line-height:0px; font-size:0px;"></td>
</tr> <!-- banner Section -->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="center" bgcolor="#ededed" class="em_hauto" valign="top"><!---->
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side30" style="width:60px;" width="60"></td>
<td align="center" class="em_hauto" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" valign="top"><a style="text-decoration:none;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiX9NQvXQ9aE-2FeLMhxL9C-2FAEYEgU_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniCObtF-2F77Rftwzxtvch3D6ixsFu8SYfu5xBceQTH8-2FBodTZxiewjgPzbEdFl3FPmC8yd8up2svP69bkXzPP1EgX9eD-2FyUn-2FEnfP2x2wq7ZOBUoARCeqqlFkP6W7Y5dGla8nNiQlX7AucOtqmpWXoN748jOggntsFT6RKIRx0tqjjl8YZ9wNtw1lwTOb8kFmOgsOcVVtLje8EbuOzP3zqIlcuQWgqqYb-2BV3lOeDIxWBtKbxqWC5a-2FCRgVj5lY1Bv7imoZhcA0AGsBJcII2E70CeIU8WfbTYM4M37ZPgsh2cLUb3V4Aejx-2FWVUWAWH2KDEs5dv-2B4PKgCJ8Acse3h-2BQekWDD3i77HE0-2BDrWvpiQ0PqKJUExxn5P-2FL0klhkr7BaNj8Rk-2F1Chu5ZAE5-2BwUiki7JUuLsWW9OOERb4e0qR3cSg4LijaO28HYiLjXFPAYOjdZeQOd-2FBnPtUPMDVpU9gYUKfSgsagIJguyAqpdjLfY6G8VVr86jIoxtluUxhWGTXIjaVcoCCZMHwuVy8TqEvwJR2SqSwWKk68wYn83-2BGVzp0Q96Il8ghSJk4VqSWMBaTqTd0KosKTV3a2OQBYPn6Cz3rrGJtTstNW0ohwZ27PImy8rSHU9BerWxzrGv35FfsQbw-3D" universal="true"><img alt="DOORDASH" border="0" class="en_icon" style="display:block; max-width:45px;font-family:Arial, sans-serif;font-size:20px; line-height:30px; color:#ee3623; font-weight:bold;" width="45" src="https://assets.doordash.team/m/835d1d775f776ef/original/-04_April-MX_Winback_Campaign-logo_img.png"> </a></td>
</tr>
<tr>
<td class="em_h20" height="50" style="height:50px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink em_font_58 em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:51px; line-height:60px; font-weight: bold;" valign="top"><!---->Thanks for your<br> order, Siddharth<!----></td>
</tr>
<tr>
<td class="em_h10" height="20" style="height:20px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#000000;font-size:16px; line-height:20px;" valign="top"><!---->The estimated delivery time for your order<br class="em_hide"> is <strong>12:56 pm - 1:06 pm</strong>. Track your order in<br class="em_hide"> the DoorDash app or website.<!----></td>
</tr>
<tr>
<td class="em_h10" height="20" style="height:20px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" valign="top">
<table align="left" border="0" cellpadding="0" cellspacing="0" class="em_cta" style="width:220px; max-width:220px;" width="220">
<tbody>
<tr>
<td align="center" class="em_defaultlink em_cta em_bold" height="45" style="font-family:'TTNorms-Bold', Arial, sans-serif;color:#ffffff;font-size:18px; background-color:#eb1700; border-radius:25px; font-weight: bold; " valign="middle"><a style="text-decoration:none; display:block; color:#ffffff; line-height:45px;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiVnjyPy8cqQ7jo-2BNF2Wc6ScBomnSDcwnk7ZiV0pRP-2F7pg2J7U-2BGioomJQf-2FXVlW43g-3Dvyw__gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniCObtF-2F77Rftwzxtvch3D6ixsFu8SYfu5xBceQTH8-2FBodTZxiewjgPzbEdFl3FPmC8yd8up2svP69bkXzPP1EgX9eD-2FyUn-2FEnfP2x2wq7ZOBUoARCeqqlFkP6W7Y5dGla8nNiQlX7AucOtqmpWXoN748jOggntsFT6RKIRx0tqjjl8YZ9wNtw1lwTOb8kFmOgsOcVVtLje8EbuOzP3zqIlcuQWgqqYb-2BV3lOeDIxWBtKbxqWC5a-2FCRgVj5lY1Bv7imoZhcA0AGsBJcII2E70CeIU8WfbTYM4M37ZPgsh2cLUb3V4Aejx-2FWVUWAWH2KDEs5dv-2B4PKgCJ8Acse3h-2BQekWDD3i77HE0-2BDrWvpiQ0PqKJUExxn5P-2FL0klhkr7BaNj8Rk-2F1Chu5ZAE5-2BwUiki7JUuLsWW9OOERb4e0qR3cSg4LijaO28HYiLjXFPAYOjdZeQOd-2FBnPtUPMDVpU9gYUKfSgsagIJguyAqpdjLfY6G8c11Xrs5mrwxYvXOjM-2B31YOhRV-2FVn8biClWfjAQE-2FFKhuO4Omylt1Br9cDjiGoEk5b7gncfkgZItoZ0uVSEVcQFQl4dKCCcWTsNznKpdwNr7hzrx4kK9eLK5xE8TC9mvmLuZcj8FiuGDz2TIKo2aVMk-3D" universal="true">Track Your Order</a></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
<td class="em_side15" style="width:20px;" width="20"></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr> <!----><!----><!--Illustration 2-->
<tr>
<td align="center" class="em_full_img" valign="top"><a style="text-decoration:none;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiX9NQvXQ9aE-2FeLMhxL9C-2FAEvLxo_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniCObtF-2F77Rftwzxtvch3D6ixsFu8SYfu5xBceQTH8-2FBodTZxiewjgPzbEdFl3FPmC8yd8up2svP69bkXzPP1EgX9eD-2FyUn-2FEnfP2x2wq7ZOBUoARCeqqlFkP6W7Y5dGla8nNiQlX7AucOtqmpWXoN748jOggntsFT6RKIRx0tqjjl8YZ9wNtw1lwTOb8kFmOgsOcVVtLje8EbuOzP3zqIlcuQWgqqYb-2BV3lOeDIxWBtKbxqWC5a-2FCRgVj5lY1Bv7imoZhcA0AGsBJcII2E70CeIU8WfbTYM4M37ZPgsh2cLUb3V4Aejx-2FWVUWAWH2KDEs5dv-2B4PKgCJ8Acse3h-2BQekWDD3i77HE0-2BDrWvpiQ0PqKJUExxn5P-2FL0klhkr7BaNj8Rk-2F1Chu5ZAE5-2BwUiki7JUuLsWW9OOERb4e0qR3cSg4LijaO28HYiLjXFPAYOjdZeQOd-2FBnPtUPMDVpU9gYUKfSgsagIJguyAqpdjLfY6G8WRCD-2FqRcT3qYaTZhzIDIiyJa5PtObUnCjY4SczlOveif0uLWX8gst2iXvDBVuJze7WmSiLEzmN-2Bdnt8ToATmeJperQEu3d9WnvS8-2BknB4MEeK-2BwIQhdsw6X9lhJzohufq-2BYaSEg2vrnOSJed7mMlcQ-3D" universal="true"><img alt="" border="0" class="em_full_img" style="display:block; max-width:700px; font-family:Arial, sans-serif; font-size:22px; line-height:25px; color:#ffffff; font-weight:bold;" width="700" src="https://assets.doordash.team/m/188a590491f6c3c9/original/-template-OrderConfirmation-dancingfood.png"></a></td>
</tr> <!--//Illustration 2--><!----><!----><!-- //banner Section -->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td style="width:6%;" width="6%"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="center" class="em_rounded" style="border-top-left-radius: 40px; border-top-right-radius: 40px; background-color: #ffffff;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side15" style="width: 40px;" width="40"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h20" height="50" style="height:50px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:17px; line-height:24px;" valign="top">Paid with MasterCard Ending in 8032<br> Subway</td>
</tr>
<tr>
<td align="left" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#767676;font-size:17px; line-height:24px; font-weight:bold; color:#000000;" valign="top">Total: $29.08</td>
</tr>
<tr>
<td class="em_h20" height="35" style="height:35px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:26px; line-height:36px; font-weight: bold;" valign="top">Your receipt</td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:21px;" valign="top">19 Lady Penrhyn Dr, Wyndham Vale VIC 3024, Australia</td>
</tr>
<tr>
<td class="em_h20" height="45" style="height:45px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:17px; line-height:24px;" valign="top"><font size="2" color="#666666"><b>- For: Siddharth Bose -</b></font><br><br>
<table width="100%" style="margin: auto; margin-bottom: 20px">
<tbody>
<tr style="text-align: left;">
<td valign="top" width="10%" style="color: #666666; font-size: 18px; line-height: 24px">1x</td>
<td valign="top" width="75%" style="color: #666666; font-size: 18px; line-height: 24px"><b>Italian B.M.T.®</b> (All Subs)<br><font color="dimgrey">• Subway Footlong ®</font><br><font color="dimgrey">• Italian Herb &amp; Cheese Bread</font><br><font color="dimgrey">• Toasted</font><br><font color="dimgrey">• Old English Style Cheese</font><br><font color="dimgrey">• Double Cheese</font><br><font color="dimgrey">• Spinach</font><br><font color="dimgrey">• Tomato</font><br><font color="dimgrey">• Cucumber</font><br><font color="dimgrey">• Capsicum</font><br><font color="dimgrey">• Onions</font><br><font color="dimgrey">• Jalapenos</font><br><font color="dimgrey">• Carrots</font><br><font color="dimgrey">• Honey Mustard Sauce</font><br><font color="dimgrey">• Sweet Onion Dressing</font><br><font color="dimgrey">• Pepper</font><br><font color="dimgrey">• Sea Salt</font><br><br></td>
<td valign="top" width="15%" style="color: #666666; font-size: 18px; line-height: 24px text-align: right">$19.85</td>
</tr>
<tr style="text-align: left;">
<td valign="top" width="10%" style="color: #666666; font-size: 18px; line-height: 24px">1x</td>
<td valign="top" width="75%" style="color: #666666; font-size: 18px; line-height: 24px"><b>Italian Meatball</b> (All Subs)<br><font color="dimgrey">• Subway 6-Inch ®</font><br><font color="dimgrey">• Italian Herb &amp; Cheese Bread</font><br><font color="dimgrey">• Toasted</font><br><font color="dimgrey">• Mozzarella</font><br><font color="dimgrey">• Double Meat (Selected Meat only)</font><br><font color="dimgrey">• Double Cheese</font><br><font color="dimgrey">• Cucumber</font><br><font color="dimgrey">• Pickles</font><br><font color="dimgrey">• Capsicum</font><br><font color="dimgrey">• Onions</font><br><font color="dimgrey">• Ranch Dressing</font><br><font color="dimgrey">• Garlic Aioli</font><br><font color="dimgrey">• Pepper</font><br><font color="dimgrey">• Sea Salt</font><br><br></td>
<td valign="top" width="15%" style="color: #666666; font-size: 18px; line-height: 24px text-align: right">$16.00</td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td class="em_h20" height="22" style="height:22px; line-height:0px; font-size:0px;"></td>
</tr>
</tbody>
</table></td>
<td class="em_side15" style="width: 40px;" width="40"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" bgcolor="#ffffff" class="em_pad1" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="em_wrapper" style="width:530px;" width="530">
<tbody>
<tr>
<td bgcolor="#e5e5e5" height="2" style="line-height:0px; font-size:0px; height: 2px;"><img alt="" border="0" height="1" style="display:block;" width="1" src="https://assets.doordash.team/m/1b5c04bd5b887a06/original/-05_May-90D_Resurrection_Campaign_Refresh_T2-spacer.gif"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" style="background-color: #ffffff;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side15" style="width: 40px;" width="40"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h20" height="10" style="height:10px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr><!---->
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Subtotal</td> <!---->
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$35.85</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr><!---->
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Taxes</td> <!---->
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$0.00</td>
</tr>
</tbody>
</table></td>
</tr> <!----><!---->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Delivery Fee</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$0.00</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Service Fee</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$3.23</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Tip</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">$0.00</td>
</tr>
</tbody>
</table></td>
</tr> <!---->
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">Discounts</td>
<td align="right" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#767676;font-size:14px; line-height:22px;" valign="top">-$26.02</td>
</tr>
</tbody>
</table></td>
</tr> <!---->
<tr>
<td class="em_h20" height="18" style="height:18px; line-height:0px; font-size:0px;"></td>
</tr>
</tbody>
</table></td>
<td class="em_side15" style="width: 40px;" width="40"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" bgcolor="#ffffff" class="em_pad1" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="em_wrapper" style="width:530px;" width="530">
<tbody>
<tr>
<td bgcolor="#e5e5e5" height="2" style="line-height:0px; font-size:0px; height: 2px;"><img alt="" border="0" height="1" style="display:block;" width="1" src="https://assets.doordash.team/m/1b5c04bd5b887a06/original/-05_May-90D_Resurrection_Campaign_Refresh_T2-spacer.gif"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" style="background-color: #ffffff;" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_side15" style="width: 40px;" width="40"></td>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="em_h20" height="12" style="height:12px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="center" valign="top">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr><!---->
<td align="left" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:17px; line-height:24px; font-weight: bold;" valign="top">Total Charged</td> <!---->
<td align="right" class="em_defaultlink em_bold" style="font-family:'TTNorms-Bold', Arial, sans-serif; color:#000000;font-size:17px; line-height:24px; font-weight: bold;" valign="top">$29.08</td>
</tr>
</tbody>
</table></td>
</tr> <!----><!----><!----><!----><!----><!----><!----> <!---->
<tr>
<td class="em_h20" height="15" style="height:15px; line-height:0px; font-size:0px;"></td>
</tr>
<tr>
<td align="left" class="em_defaultlink" style="font-family:'TTNorms-Regular', Arial, sans-serif; color:#ff2f07;font-size:14px; line-height:21px; font-weight: bold;" valign="top"><a style="color:#ff2f07; text-decoration:none;" target="_blank" href="https://tracksg.doordash.com/uni/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FBg5Q-2B-2F17CbuWT8XZi-2BuiVnjyPy8cqQ7jo-2BNF2Wc6ScBomnSDcwnk7ZiV0pRP-2F7pg2J7U-2BGioomJQf-2FXVlW43g-3D6wBj_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniCObtF-2F77Rftwzxtvch3D6ixsFu8SYfu5xBceQTH8-2FBodTZxiewjgPzbEdFl3FPmC8yd8up2svP69bkXzPP1EgX9eD-2FyUn-2FEnfP2x2wq7ZOBUoARCeqqlFkP6W7Y5dGla8nNiQlX7AucOtqmpWXoN748jOggntsFT6RKIRx0tqjjl8YZ9wNtw1lwTOb8kFmOgsOcVVtLje8EbuOzP3zqIlcuQWgqqYb-2BV3lOeDIxWBtKbxqWC5a-2FCRgVj5lY1Bv7imoZhcA0AGsBJcII2E70CeIU8WfbTYM4M37ZPgsh2cLUb3V4Aejx-2FWVUWAWH2KDEs5dv-2B4PKgCJ8Acse3h-2BQekWDD3i77HE0-2BDrWvpiQ0PqKJUExxn5P-2FL0klhkr7BaNj8Rk-2F1Chu5ZAE5-2BwUiki7JUuLsWW9OOERb4e0qR3cSg4LijaO28HYiLjXFPAYOjdZeQOd-2FBnPtUPMDVpU9gYUKfSgsagIJguyAqpdjLfY6G8bOKlnu7vSFB-2BIQ-2FSa0IlYx-2F9RNR0nsTokQzCNSqlpkomb9IWoemjq9we5J1OThMwqfb3jx6ATLRRe0hZPiX7urz31ND8Ku6OkcqBpF9xCGYZ-2B8b-2FruvvcHPSbTGjapxW5zZugpMbHsegIXXCMVBkNg-3D" universal="true">Get Order Help</a></td>
</tr> <!-- -->
<tr>
<td class="em_h20" height="58" style="height:58px; line-height:0px; font-size:0px;"></td>
</tr>
</tbody>
</table> <!-- == //Body Section == --><!-- == Footer Section == --><!-- == //Footer Section == --></td>
<td class="em_side15" style="width: 40px;" width="40"></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
<td style="width:6%;" width="6%"></td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td align="center" valign="top"><!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:620px;">
<tr>
<td align="center">
<![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" id="Footer" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width: 100%; max-width: 700px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="center" style="padding: 0 24px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="mso-table-lspace: 0; mso-table-rspace: 0; width:100%;max-width:572px; border: 0; padding: 0; border-collapse: collapse;" width="100%">
<tbody>
<tr>
<td align="left" style="padding:0 0 48px 0;border-bottom: 1px solid #E7E7E7;"></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 32px 0 16px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;">©2026 <a style="color: #9A9A9A; text-decoration: none;">DoorDash Technologies Australia Pty Ltd <br>401 Collins St. <br>Melbourne, VIC 3000 Australia</a></p> <p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:400;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYAqF1KGCKTTTznL6MvOfulOsmFa2kqsuG7LjgY0AllZKBKWegcAPOx5sr25l15pnWbLZL6VnVCDFc3hEnP4sDnrBpZV_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniCObtF-2F77Rftwzxtvch3D6ixsFu8SYfu5xBceQTH8-2FBodTZxiewjgPzbEdFl3FPmC8yd8up2svP69bkXzPP1EgX9eD-2FyUn-2FEnfP2x2wq7ZOBUoARCeqqlFkP6W7Y5dGla8nNiQlX7AucOtqmpWXoN748jOggntsFT6RKIRx0tqjjl8YZ9wNtw1lwTOb8kFmOgsOcVVtLje8EbuOzP3zqIlcuQWgqqYb-2BV3lOeDIxWBtKbxqWC5a-2FCRgVj5lY1Bv7imoZhcA0AGsBJcII2E70CeIU8WfbTYM4M37ZPgsh2cLUb3V4Aejx-2FWVUWAWH2KDEs5dv-2B4PKgCJ8Acse3h-2BQekWDD3i77HE0-2BDrWvpiQ0PqKJUExxn5P-2FL0klhkr7BaNj8Rk-2F1Chu5ZAE5-2BwUiki7JUuLsWW9OOERb4e0qR3cSg4LijaO28HYiLjXFPAYOjdZeQOd-2FBnPtUPMDVpU9gYUKfSgsagIJguyAqpdjLfY6G8Q8l21R-2BUnujFyqLh7dgRALyW1uXR-2FN8S0g00dvJLLfcmlzcQZxW44cVyDjeLcQdT7oXKMmfaQcqjpUqJASXPTpcyojzmAR7AJNx0XL1wVst-2FulVzDY1gZlfxA5V-2BU-2F-2B4tKqztf0gKzb-2BVk9xtu1bac-3D" target="_blank" style="color: #9A9A9A; text-decoration: none;">Privacy Policy</a></p></td>
</tr>
<tr>
<td align="left" style="color: #191919; padding: 0 0 24px 0;"><p style="font-family:'TTNorms',system-ui,sans-serif;font-size:14px;line-height:18px;font-weight:500;margin:0;color:#9A9A9A;"><a href="https://tracksg.doordash.com/ls/click?upn=u001.2WPFTROKt87XSwhhpTWl-2B-2FDD8FcMNUAvAdfcDQmgdYABnncKv1afIihr5Gt6bkMjMbSD_gLgx7IOQjj9tjcBPTdxDOJz1JqFsZO0kLUqSc8MGlKXluNU-2FF7J47geTAg8w6cqXb3B-2FMFQSFRN7JikLQZlFDU38dwgb-2BDbpbbf0hwXhFRygzsqDKLqVcMuBPdkhwo7LHk9TXfSbi-2B0mW4NvsDLo9Q6gWLaNP3J-2Fyzkvnw5dniCObtF-2F77Rftwzxtvch3D6ixsFu8SYfu5xBceQTH8-2FBodTZxiewjgPzbEdFl3FPmC8yd8up2svP69bkXzPP1EgX9eD-2FyUn-2FEnfP2x2wq7ZOBUoARCeqqlFkP6W7Y5dGla8nNiQlX7AucOtqmpWXoN748jOggntsFT6RKIRx0tqjjl8YZ9wNtw1lwTOb8kFmOgsOcVVtLje8EbuOzP3zqIlcuQWgqqYb-2BV3lOeDIxWBtKbxqWC5a-2FCRgVj5lY1Bv7imoZhcA0AGsBJcII2E70CeIU8WfbTYM4M37ZPgsh2cLUb3V4Aejx-2FWVUWAWH2KDEs5dv-2B4PKgCJ8Acse3h-2BQekWDD3i77HE0-2BDrWvpiQ0PqKJUExxn5P-2FL0klhkr7BaNj8Rk-2F1Chu5ZAE5-2BwUiki7JUuLsWW9OOERb4e0qR3cSg4LijaO28HYiLjXFPAYOjdZeQOd-2FBnPtUPMDVpU9gYUKfSgsagIJguyAqpdjLfY6G8aanhk3H7M0AmyPIeD-2FSytmK5nE5elBgAZcjX3JsIKz28vuZG4HM2bl-2FxI9FZWifPR-2FNBQ-2FOmTQqLo0YK3jcUZRxpOUh8EYeWnkDHAf9CUnJYhfBCXrPHy8-2BIouWsFADv6rViHCrwIlJq7PKIdjhsQU-3D" target="_blank" style="color:#9A9A9A;text-decoration:none;">Help Center</a></p></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table> <!--[if (gte mso 9)|(IE)]>
</td>
</tr>
</table>
<![endif]--></td>
</tr>
<tr>
<td class="em_hide" style="line-height:1px;min-width:700px;background-color:#f4f4f4;"><img alt="" border="0" height="1" style="max-height:1px; min-height:1px; display:block; width:700px; min-width:700px;" width="700" src="https://assets.doordash.team/m/1b5c04bd5b887a06/original/-05_May-90D_Resurrection_Campaign_Refresh_T2-spacer.gif"></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
<img src="https://tracksg.doordash.com/wf/open?upn=u001.EBL2ug8kstebd25Xirrl3olMckTI261ldPjJ39bNHcC7U6EKGAOA4dSVB97lcv3b8qsQRq6LwkHED6F3X4gqaODB2b1wZFk4or4JbrThItr6lxxhe0ghxdjbmj40V9NR2q6sVlDPfArvtaJbtCejz-2BJxmNDpj6cBZjf16jHN3-2B0iC1V4tFBTMLc-2BJwfmofzVTZ93Zr38yBFeE9QeTx2HIPl8aahBdGSAhck5E0FopTVrs3ftPac-2BjBZQ-2F-2BOtO9AAatRdgybtYfdgGvULGP9PgScKi7bqhiEsMHtYK5BiFCtgHDd3wSmmSQEmLY5CxOdBaxC6hncHaAEfQICV5PV5RYoWJUn59AMV6iCj-2FAzsFmZDmbIos3SveyBNTIRxoQ9cPRYnGUJvcAO2C-2FN1QxbjuL3Y8ELK5gWiOUqwAeJaoIqwImrrWGzkrtF6Iu6lpAYw2yIml9u8FnfV-2BNo6dypylz5AbWbO4wm5AnTe6e7WmglLSPh-2FBr7RLUmgVl05JkvNjJmFrJUL-2FOA3VD8xCUTqdI8CiSkwhJgeP4PUUSKU6CPRXiEhpXbnj4JBARqbiZEvMCv3cChoIFQg20r6bMddokffgXp-2BiFWCvNIrp4WNUFzUegA1y-2FApKsMQemjXy5KM5DhVuyriQDcI1uKZbNH2L4o9QR7SSsEbRXbj-2F5-2FuRPshsLYfjHnGoPt11ACguPrpPaB5Kmke1gWd0UvceKwobel8MH3YRSgU2gvLJEJ000ZGfHr9Mj0j30BzHFnFaYfPzegN2Y2l5rXh6a3zR9Dsv0mUWU0mjRXrYJif2o5NEVM-3D" alt="" width="1" height="1" border="0" style="height:1px !important;width:1px !important;border-width:0 !important;margin-top:0 !important;margin-bottom:0 !important;margin-right:0 !important;margin-left:0 !important;padding-top:0 !important;padding-bottom:0 !important;padding-right:0 !important;padding-left:0 !important;"/></body>
</html>
@@ -0,0 +1,254 @@
[
{
"id": "19f89664ea7b3aeb",
"date": "Date: Wed, 22 Jul 2026 10:36:50 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Homey Meals",
"len": 38394
},
{
"id": "19f68fd09cd2c3f1",
"date": "Date: Thu, 16 Jul 2026 03:34:00 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Mad Mex",
"len": 37448
},
{
"id": "19f656a298f42858",
"date": "Date: Wed, 15 Jul 2026 10:54:42 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Carl's Jr.",
"len": 37970
},
{
"id": "19f605de9ab82216",
"date": "Date: Tue, 14 Jul 2026 11:23:14 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Delhi Nights - Sweets & Indian\r\n Cuisine",
"len": 38707
},
{
"id": "19f2b6390a95b665",
"date": "Date: Sat, 04 Jul 2026 04:29:32 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from TEG KEBABS & BIRYANI",
"len": 38005
},
{
"id": "19f2256c51714b9c",
"date": "Date: Thu, 02 Jul 2026 10:18:58 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Sri Dwaraka",
"len": 37817
},
{
"id": "19f1d0b003834626",
"date": "Date: Wed, 01 Jul 2026 09:38:07 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Taco Bell",
"len": 38019
},
{
"id": "19f1c301dda7332c",
"date": "Date: Wed, 01 Jul 2026 05:39:01 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Woolworths",
"len": 38753
},
{
"id": "19f0c5624707ae34",
"date": "Date: Sun, 28 Jun 2026 03:46:39 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from ALDI",
"len": 68206
},
{
"id": "19f0c0d0c33bf5c9",
"date": "Date: Sun, 28 Jun 2026 02:26:49 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from ALDI",
"len": 47419
},
{
"id": "19eed89eee79b624",
"date": "Date: Mon, 22 Jun 2026 04:14:59 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Woolworths",
"len": 48653
},
{
"id": "19eed498e3fb7fce",
"date": "Date: Mon, 22 Jun 2026 03:04:39 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Woolworths",
"len": 44104
},
{
"id": "19eed38ca77047a1",
"date": "Date: Mon, 22 Jun 2026 02:46:21 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Oporto",
"len": 38675
},
{
"id": "19ee9b9b1b7073c9",
"date": "Date: Sun, 21 Jun 2026 10:28:39 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37871
},
{
"id": "19e95be74e216594",
"date": "Date: Fri, 05 Jun 2026 03:05:46 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37817
},
{
"id": "19e854cdbf552dcf",
"date": "Date: Mon, 01 Jun 2026 22:27:45 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from TOMKINS BAKERY",
"len": 37741
},
{
"id": "19e8020eb0027109",
"date": "Date: Sun, 31 May 2026 22:21:39 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Tonmax Bakery",
"len": 37439
},
{
"id": "19e16b64b3f6dbad",
"date": "Date: Mon, 11 May 2026 11:05:04 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Woolworths",
"len": 39750
},
{
"id": "19e16b1a2d9526f8",
"date": "Date: Mon, 11 May 2026 11:00:00 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Burger Road",
"len": 38230
},
{
"id": "19e11390ea456222",
"date": "Date: Sun, 10 May 2026 09:30:11 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37847
},
{
"id": "19cdfa1d25f194a8",
"date": "Date: Thu, 12 Mar 2026 01:20:48 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Kesari Indian Kitchen",
"len": 37922
},
{
"id": "19cc62db0460b8a0",
"date": "Date: Sat, 07 Mar 2026 02:43:28 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37884
},
{
"id": "19ca1f0fa493f0ca",
"date": "Date: Sat, 28 Feb 2026 01:50:49 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37862
},
{
"id": "19c9c18ad4bf22e1",
"date": "Date: Thu, 26 Feb 2026 22:36:27 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Hungry Jacks",
"len": 37596
},
{
"id": "19c8ef02c0a0f590",
"date": "Date: Tue, 24 Feb 2026 09:17:09 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Schnitz",
"len": 38107
},
{
"id": "19c6e7cb5565afd5",
"date": "Date: Wed, 18 Feb 2026 02:03:12 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37418
},
{
"id": "19c4c4b1a0efa1e0",
"date": "Date: Wed, 11 Feb 2026 10:41:56 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from lahori fish n tikka",
"len": 37166
},
{
"id": "19c4013c5a7fac93",
"date": "Date: Mon, 09 Feb 2026 01:46:02 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Subway",
"len": 39212
},
{
"id": "19c30b95bf183a2b",
"date": "Date: Fri, 06 Feb 2026 02:12:59 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Souvlaki GR",
"len": 37776
},
{
"id": "19c30b773199c2fb",
"date": "Date: Fri, 06 Feb 2026 02:10:54 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Souvlaki GR",
"len": 37309
},
{
"id": "19c27f770fae04f2",
"date": "Date: Wed, 04 Feb 2026 09:24:13 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37440
},
{
"id": "19c21316b26e066f",
"date": "Date: Tue, 03 Feb 2026 01:50:11 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Punjabi bai sweets & Indian\r\n cuisine",
"len": 39289
},
{
"id": "19bf2e0fd25facda",
"date": "Date: Sun, 25 Jan 2026 01:59:48 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 38432
},
{
"id": "19bb18096ebd9bf5",
"date": "Date: Mon, 12 Jan 2026 09:19:12 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Woolworths",
"len": 42464
},
{
"id": "19bac527ef5fb1d4",
"date": "Date: Sun, 11 Jan 2026 09:10:45 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37833
},
{
"id": "19baad6dd7f80a9f",
"date": "Date: Sun, 11 Jan 2026 02:16:04 +0000 (UTC)",
"from": "From: DoorDash Order <no-reply@doordash.com>",
"subject": "Subject: Order Confirmation for Siddharth from Chilli India",
"len": 37334
}
]
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,205 @@
[
{
"i": 0,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkeckxXAAAA",
"date": "2026-07-22T03:41:19Z",
"subject": "Your Wednesday afternoon order with Uber Eats",
"len": 57778
},
{
"i": 1,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkd32TzAAAA",
"date": "2026-07-21T04:25:09Z",
"subject": "Your Tuesday afternoon order with Uber Eats",
"len": 61532
},
{
"i": 2,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkd32TsAAAA",
"date": "2026-07-20T23:17:05Z",
"subject": "Your Tuesday morning order with Uber Eats",
"len": 59110
},
{
"i": 3,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkdK0voAAAA",
"date": "2026-07-20T04:23:40Z",
"subject": "Your Monday afternoon order with Uber Eats",
"len": 66211
},
{
"i": 4,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0aigAAAA",
"date": "2026-07-07T15:31:27Z",
"subject": "[Family] Your Tuesday evening order with Uber Eats",
"len": 80279
},
{
"i": 5,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0aicAAAA",
"date": "2026-07-07T08:58:43Z",
"subject": "Your Tuesday evening order with Uber Eats",
"len": 73592
},
{
"i": 6,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0aibAAAA",
"date": "2026-07-07T08:50:06Z",
"subject": "[Family] Your Tuesday afternoon order with Uber Eats",
"len": 78782
},
{
"i": 7,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0aiaAAAA",
"date": "2026-07-07T08:46:17Z",
"subject": "Your Tuesday evening order with Uber Eats",
"len": 65886
},
{
"i": 8,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0ah6AAAA",
"date": "2026-07-05T15:51:11Z",
"subject": "[Family] Your Sunday evening order with Uber Eats",
"len": 82383
},
{
"i": 9,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0ah5AAAA",
"date": "2026-07-05T15:33:01Z",
"subject": "[Family] Your Sunday evening order with Uber Eats",
"len": 88958
},
{
"i": 10,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0ahTAAAA",
"date": "2026-07-03T10:04:15Z",
"subject": "Your Friday evening order with Uber Eats",
"len": 61485
},
{
"i": 11,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkR0ahFAAAA",
"date": "2026-07-02T22:57:18Z",
"subject": "Your Friday morning order with Uber Eats",
"len": 60751
},
{
"i": 12,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkOIIcBAAAA",
"date": "2026-06-27T04:21:08Z",
"subject": "Your Saturday afternoon order with Uber Eats",
"len": 60720
},
{
"i": 13,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkH8zVTAAAA",
"date": "2026-06-22T10:19:49Z",
"subject": "Your Monday evening order with Uber Eats",
"len": 58303
},
{
"i": 14,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkH8zUwAAAA",
"date": "2026-06-20T12:28:26Z",
"subject": "Your Saturday afternoon order with Uber Eats",
"len": 60856
},
{
"i": 15,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkH8zURAAAA",
"date": "2026-06-18T18:43:06Z",
"subject": "Your Thursday evening order with Uber Eats",
"len": 57881
},
{
"i": 16,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAkGJuBoAAAA",
"date": "2026-06-15T19:32:17Z",
"subject": "Your Monday evening order with Uber Eats",
"len": 60838
},
{
"i": 17,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAj9_fg8AAAA",
"date": "2026-06-02T11:27:03Z",
"subject": "Your Tuesday evening order with Uber Eats",
"len": 55147
},
{
"i": 18,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAj7_L67AAAA",
"date": "2026-06-02T03:11:33Z",
"subject": "Your Tuesday afternoon order with Uber Eats",
"len": 60716
},
{
"i": 19,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAj66TeuAAAA",
"date": "2026-05-29T02:47:06Z",
"subject": "Your Friday afternoon order with Uber Eats",
"len": 55127
},
{
"i": 20,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAj19QCWNwAAAA==",
"date": "2026-05-23T03:00:14Z",
"subject": "Your Saturday afternoon order with Uber Eats",
"len": 65562
},
{
"i": 21,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjzoSJtAAAA",
"date": "2026-05-18T10:50:25Z",
"subject": "Your Monday evening order with Uber Eats",
"len": 68144
},
{
"i": 22,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjy8e6sAAAA",
"date": "2026-05-17T03:13:05Z",
"subject": "Your Sunday afternoon order with Uber Eats",
"len": 62439
},
{
"i": 23,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjw8ZyAAAAA",
"date": "2026-05-15T09:45:15Z",
"subject": "Your Friday evening order with Uber Eats",
"len": 55113
},
{
"i": 24,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjw8ZxwAAAA",
"date": "2026-05-14T15:02:24Z",
"subject": "Your Thursday afternoon order with Uber Eats",
"len": 58231
},
{
"i": 25,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjw8ZxtAAAA",
"date": "2026-05-14T11:24:43Z",
"subject": "Your Thursday evening order with Uber Eats",
"len": 60745
},
{
"i": 26,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjV0eF4AAAA",
"date": "2026-04-08T05:54:03Z",
"subject": "Your Tuesday evening order with Uber Eats",
"len": 68338
},
{
"i": 27,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjV0eFyAAAA",
"date": "2026-04-07T22:40:52Z",
"subject": "Your Tuesday afternoon order with Uber Eats",
"len": 52600
},
{
"i": 28,
"id": "AQMkADAwATM0MDAAMS1hYzQyLTVjZDktMDACLTAwCgBGAAADS6kDcxBxKkKwbCK1wU1QlwcA7Ex_hlaTTU0AgHQ16optl_AAAAIBDAAAAOxMfoZWk01NAIB0NeqKbZfgAAjV0eFcAAAA",
"date": "2026-04-06T05:23:40Z",
"subject": "Your Sunday evening order with Uber Eats",
"len": 59440
}
]
@@ -0,0 +1,106 @@
import { describe, it, expect, beforeAll } from "vitest";
import { readFileSync } from "fs";
import { resolve } from "path";
import { queryRaw } from "../../lib/db";
/**
* The HTTP path had no tests at all — which is how three defects reached the
* branch through a suite of 105 green ones. These exercise the route handler
* directly (no server needed) so the auth gate and the error taxonomy are
* actually covered.
*/
const dir = resolve(__dirname, "../fixtures/orders/real");
const html = (f: string) => readFileSync(resolve(dir, `${f}.html`), "utf-8");
const TOKEN = "test-ingest-token";
let POST: any;
const req = (body: unknown, token: string | null = TOKEN) =>
({
headers: { get: (h: string) => (h === "x-ingest-token" ? token : null) },
json: async () => body,
}) as any;
beforeAll(async () => {
process.env.ORDER_INGEST_TOKEN = TOKEN;
({ POST } = await import("../../app/api/orders/ingest/route"));
});
describe("ingest API — auth", () => {
it("rejects a missing token", async () => {
const res = await POST(req({ html: "x", meta: {} }, null));
expect(res.status).toBe(401);
});
it("rejects a wrong token", async () => {
const res = await POST(req({ html: "x", meta: {} }, "nope"));
expect(res.status).toBe(401);
});
it("rejects a malformed body", async () => {
const res = await POST(req({ html: "only html" }));
expect(res.status).toBe(400);
});
});
describe("ingest API — error taxonomy", () => {
const meta = (over = {}) => ({
messageId: `api-${Math.random().toString(36).slice(2)}`,
subject: "Order Confirmation for Siddharth from Mad Mex",
receivedAt: "2026-07-16T03:34:00Z",
sender: "DoorDash Order <no-reply@doordash.com>",
...over,
});
it("a non-receipt is 200 and silent — it must not alert", async () => {
// A newsletter: real traffic, correctly ignored.
const res = await POST(req({ html: html("dd-01"), meta: meta({ subject: "Newsletter", sender: "promo@example.com" }) }));
expect(res.status).toBe(200);
expect((await res.json()).kind).toBe("skipped");
});
it("an adjustment notice is 200 and silent", async () => {
const res = await POST(req({
html: html("dd-08"),
meta: meta({ subject: "Order Confirmation for Siddharth from ALDI" }),
}));
expect(res.status).toBe(200);
expect((await res.json()).kind).toBe("skipped");
});
it("a receipt that cannot be parsed is 422 so it ALERTS", async () => {
// A DoorDash receipt with its totals stripped out — i.e. what a provider
// template change looks like. Previously this returned 200 and vanished.
const broken = html("dd-01")
.replace(/Total Charged/g, "Gesamtbetrag")
.replace(/Total:/g, "Summe:");
const res = await POST(req({ html: broken, meta: meta() }));
expect(res.status).toBe(422);
const body = await res.json();
expect(body.kind).toBe("parse_failed");
expect(body.reason).toMatch(/total/i);
});
it("a refund is routed to the amendment path, not ingestion", async () => {
const res = await POST(req({
html: html("ue-05"),
meta: meta({ subject: "Your Tuesday evening order with Uber Eats", sender: "uber.com" }),
dryRun: true,
}));
expect(res.status).toBe(200);
const body = await res.json();
expect(body.kind).toBe("amendment");
expect(body.amendment.new_total).toBeCloseTo(45.73, 2);
});
it("a good receipt ingests", async () => {
await queryRaw(`DELETE FROM expense_metadata WHERE source = 'email'`);
await queryRaw(`DELETE FROM transactions WHERE description LIKE 'Order - %'`);
const res = await POST(req({ html: html("dd-01"), meta: meta({ messageId: "api-ok-1" }) }));
expect(res.status).toBe(200);
const body = await res.json();
expect(body.kind).toBe("order");
expect(body.total).toBe(14.64);
expect(body.transactionId).not.toBeNull();
});
});
@@ -0,0 +1,358 @@
import { describe, it, expect, beforeEach } from "vitest";
import { readFileSync } from "fs";
import { resolve } from "path";
import { queryRaw, queryRow } from "../../lib/db";
import {
parseOrderHTML,
validateOrderTotals,
processOrderIngestion,
reconcilePendingOrders,
parseOrderAmendment,
applyOrderAmendment,
OrderParseError,
NotAReceiptError,
type MessageMeta,
} from "../../lib/order-ingestion";
import { EXCLUDE_NON_SPEND } from "../../lib/analytics-sql";
/**
* These run against REAL captured receipts, not synthetic fixtures. The earlier
* suite passed 31/31 against fixtures written to satisfy the parser, while the
* parser could not read a single real email. Fixtures live in
* __tests__/fixtures/orders/real/ and are unmodified message bodies.
*/
const dir = resolve(__dirname, "../fixtures/orders/real");
const html = (f: string) => readFileSync(resolve(dir, `${f}.html`), "utf-8");
const meta = (over: Partial<MessageMeta> = {}): MessageMeta => ({
messageId: `test-${Math.random().toString(36).slice(2)}`,
subject: "Order Confirmation for Siddharth from Mad Mex",
receivedAt: "2026-07-16T03:34:00Z",
sender: "DoorDash Order <no-reply@doordash.com>",
...over,
});
describe("Order parsing — real receipts", () => {
it("reads DoorDash totals structurally, not by flattening (I9)", () => {
const p = parseOrderHTML(html("dd-01"), meta());
expect(p.merchant_name).toBe("Mad Mex");
expect(p.totals.total_charged).toBe(14.64);
expect(p.payment.credits_amount).toBe(14.64);
expect(p.line_items).toHaveLength(1);
expect(p.line_items[0].description).toBe("Burrito (Mains)");
expect(p.line_items[0].options).toContain("Slow Cooked Beef (GF)");
});
it("does NOT gate on DoorDash's fee breakdown, which genuinely does not reconcile", () => {
// Real receipt: subtotal 22.10 + service 1.99 - Discounts 24.09 = 0.00,
// against a stated total of 14.64. DoorDash prints this; it is not a parse
// artefact. Recorded here so nobody "fixes" the parser to force it to sum.
const p = parseOrderHTML(html("dd-01"), meta());
expect(p.totals.subtotal).toBe(22.10);
expect(p.totals.discounts).toBe(24.09);
expect(validateOrderTotals(p, html("dd-01")).ok).toBe(true);
});
it("derives order_reference from the message, never randomly (I7)", () => {
const m = meta({ messageId: "abc123" });
const a = parseOrderHTML(html("dd-01"), m);
const b = parseOrderHTML(html("dd-01"), m);
expect(a.order_reference).toBe(b.order_reference);
expect(a.order_reference).toBe("msg:abc123");
});
it("uses Uber's embedded order UUID as the reference", () => {
const p = parseOrderHTML(
html("ue-00"),
meta({ subject: "Your Wednesday afternoon order with Uber Eats", sender: "uber.com" })
);
expect(p.order_reference).toMatch(/^[0-9a-f-]{36}$/);
expect(p.platform).toBe("ubereats");
});
it("takes the order date from the message, not a body string", () => {
const p = parseOrderHTML(html("dd-01"), meta({ receivedAt: "2026-07-16T03:34:00Z" }));
expect(p.order_datetime.slice(0, 10)).toBe("2026-07-16");
});
it("detects [Family] from the subject prefix, not a body substring (I11)", () => {
const fam = parseOrderHTML(
html("ue-04"),
meta({ subject: "[Family] Your Tuesday evening order with Uber Eats", sender: "uber.com" })
);
expect(fam.is_family).toBe(true);
const notFam = parseOrderHTML(html("dd-01"), meta());
expect(notFam.is_family).toBe(false);
});
it("reads [Family] orders as LKR, not dollars", () => {
const p = parseOrderHTML(
html("ue-04"),
meta({ subject: "[Family] Your Tuesday evening order with Uber Eats", sender: "uber.com" })
);
expect(p.currency).toBe("LKR");
expect(p.totals.total_charged).toBeCloseTo(3783.20, 2);
});
it("reads Swiss orders as CHF", () => {
const p = parseOrderHTML(
html("ue-26"),
meta({ subject: "Your Tuesday evening order with Uber Eats", sender: "uber.com" })
);
expect(p.currency).toBe("CHF");
expect(p.totals.total_charged).toBeCloseTo(51.23, 2);
});
it("skips a failed payment attempt and takes the successful one", () => {
// ue-09: "Visa ••••8841 LKR 4,267.01 ... Failed" then "LKR 3,757.01".
const p = parseOrderHTML(
html("ue-09"),
meta({ subject: "[Family] Your Sunday evening order with Uber Eats", sender: "uber.com" })
);
expect(p.totals.total_charged).toBeCloseTo(3757.01, 2);
expect(validateOrderTotals(p, html("ue-09")).ok).toBe(true);
});
it("rejects an order-adjustment notice rather than booking $0.00", () => {
// NotAReceiptError, not OrderParseError: this is expected traffic, so it
// must be skipped silently. Only a receipt that fails to parse should
// alert — see the ingest API's error taxonomy.
expect(() =>
parseOrderHTML(html("dd-08"), meta({ subject: "Order Confirmation for Siddharth from ALDI" }))
).toThrow(NotAReceiptError);
});
it("rejects a refund notice rather than inserting a duplicate order", () => {
expect(() =>
parseOrderHTML(html("ue-05"), meta({ subject: "Your Tuesday evening order with Uber Eats", sender: "uber.com" }))
).toThrow(/refund/i);
});
it("reads a grocery Final receipt that has no Total Charged row", () => {
const p = parseOrderHTML(
html("dd-10"),
meta({ subject: "Order Confirmation for Siddharth from Woolworths" })
);
expect(p.totals.total_charged).toBeCloseTo(60.93, 2);
expect(p.payment.ambiguous).toBe(true); // "8032 and/or credits"
});
});
describe("Order ingestion — invariants", () => {
beforeEach(async () => {
await queryRaw(`DELETE FROM expense_metadata WHERE source = 'email'`);
await queryRaw(`DELETE FROM transactions WHERE description LIKE 'Order - %'`);
});
it("I6: a credits order creates one transaction at face value", async () => {
const p = parseOrderHTML(html("dd-01"), meta());
const res = await processOrderIngestion(p);
expect(res.transactionId).not.toBeNull();
const txn = await queryRow<{ amount: string; payment_method: string; category: string }>(
`SELECT amount::text, payment_method, category FROM transactions WHERE id = $1`,
[res.transactionId]
);
expect(Number(txn!.amount)).toBe(14.64);
expect(txn!.payment_method).toBe("credits");
expect(txn!.category).toBe("dining");
});
it("I7: re-ingesting the same receipt creates nothing new", async () => {
const p = parseOrderHTML(html("dd-01"), meta({ messageId: "dedupe-1" }));
const a = await processOrderIngestion(p);
const b = await processOrderIngestion(parseOrderHTML(html("dd-01"), meta({ messageId: "dedupe-1" })));
expect(b.skipped).toBe("already_ingested");
expect(b.metadataId).toBe(a.metadataId);
const n = await queryRow<{ c: string }>(
`SELECT count(*)::text c FROM transactions WHERE description = 'Order - Mad Mex'`
);
expect(Number(n!.c)).toBe(1);
});
it("I1: a credits order before the cutover is refused", async () => {
const p = parseOrderHTML(html("dd-01"), meta({ receivedAt: "2025-11-15T12:00:00Z" }));
const res = await processOrderIngestion(p);
expect(res.skipped).toBe("pre_cutover");
expect(res.transactionId).toBeNull();
await expect(
queryRaw(
`INSERT INTO transactions (transaction_date, amount, payment_method) VALUES ('2025-11-15', 20.00, 'credits')`
)
).rejects.toThrow();
});
it("I11: a [Family] order is imported, tagged, and excluded from spend", async () => {
const p = parseOrderHTML(
html("ue-04"),
meta({ subject: "[Family] Your Tuesday evening order with Uber Eats", sender: "uber.com", receivedAt: "2026-07-07T10:08:00Z" })
);
const res = await processOrderIngestion(p);
expect(res.transactionId).not.toBeNull();
expect(res.flags).toContain("family_payment_assumed_credits");
});
it("a foreign-currency order records the original amount and code", async () => {
const p = parseOrderHTML(
html("ue-26"),
meta({ subject: "Your Tuesday evening order with Uber Eats", sender: "uber.com", receivedAt: "2026-04-07T08:53:00Z" })
);
// Card-settled Swiss order: no credits leg, so no transaction (I5).
const res = await processOrderIngestion(p);
expect(res.transactionId).toBeNull();
const meta_ = await queryRow<{ currency: string }>(
`SELECT currency FROM expense_metadata WHERE id = $1`,
[res.metadataId]
);
expect(meta_!.currency).toBe("CHF");
});
it("parks an unresolvable split instead of guessing, then resolves it once the statement lands", async () => {
const p = parseOrderHTML(
html("dd-10"),
meta({ subject: "Order Confirmation for Siddharth from Woolworths", receivedAt: "2026-03-02T12:00:00Z" })
);
const res = await processOrderIngestion(p);
expect(res.transactionId).toBeNull();
expect(res.flags).toContain("awaiting_card_statement");
// Statement arrives: card 8032 took 40.93 of the 60.93 order.
const st = await queryRow<{ id: number }>(
`INSERT INTO statements (bank_name, account_number, filename)
VALUES ('Westpac','5163103015778032','test-westpac-2026-03.pdf') RETURNING id`
);
await queryRaw(
`INSERT INTO transactions (statement_id, transaction_date, description, amount, transaction_type)
VALUES ($1, '2026-03-02', 'DD *DOORDASH WOOLWORTHS MELBOURNE AUS', 40.93, 'debit')`,
[st!.id]
);
const out = await reconcilePendingOrders();
expect(out.resolved).toBeGreaterThanOrEqual(1);
expect(out.created).toBeGreaterThanOrEqual(1);
const credits = await queryRow<{ amount: string }>(
`SELECT t.amount::text FROM transactions t
JOIN expense_metadata em ON em.transaction_id = t.id
WHERE em.id = $1`,
[res.metadataId]
);
expect(Number(credits!.amount)).toBeCloseTo(20.00, 2); // 60.93 - 40.93
});
it("reconciliation is idempotent — a second pass creates nothing", async () => {
const before = await queryRow<{ c: string }>(`SELECT count(*)::text c FROM transactions`);
const out = await reconcilePendingOrders();
const after = await queryRow<{ c: string }>(`SELECT count(*)::text c FROM transactions`);
expect(out.created).toBe(0);
expect(after!.c).toBe(before!.c);
});
it("EXCLUDE_NON_SPEND removes family-tagged rows", async () => {
const txn = await queryRow<{ id: number }>(
`INSERT INTO transactions (transaction_date, description, amount, category, transaction_type)
VALUES ('2026-03-01','Order - Family Test', 50.00, 'dining', 'debit') RETURNING id`
);
const tag = await queryRow<{ id: number }>(
`INSERT INTO tags (name, color) VALUES ('family','#ef4444')
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name RETURNING id`
);
await queryRaw(`INSERT INTO transaction_tags (transaction_id, tag_id) VALUES ($1,$2)`, [txn!.id, tag!.id]);
const visible = await queryRaw(
`SELECT t.id FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
WHERE t.id = $1 AND (${EXCLUDE_NON_SPEND})`,
[txn!.id]
);
expect(visible).toHaveLength(0);
});
});
describe("Refund amendments", () => {
const ueMeta = (over = {}) => meta({
subject: "Your Tuesday evening order with Uber Eats",
sender: "uber.com",
receivedAt: "2026-07-07T08:17:00Z",
...over,
});
it("parses a refund notice into an amendment, not an order", () => {
const a = parseOrderAmendment(html("ue-05"), ueMeta());
expect(a.previous_total).toBeCloseTo(49.94, 2);
expect(a.refund_amount).toBeCloseTo(4.21, 2);
expect(a.new_total).toBeCloseTo(45.73, 2);
expect(a.order_reference).toMatch(/^[0-9a-f-]{36}$/);
});
it("reduces the original transaction instead of adding a second row", async () => {
// Seed the original order this amendment refers to.
const a = parseOrderAmendment(html("ue-05"), ueMeta());
const txn = await queryRow<{ id: number }>(
`INSERT INTO transactions (transaction_date, description, amount, amount_aud, category, payment_method, transaction_type)
VALUES ('2026-07-07','Order - Coles (Wyndham Vale)', 49.94, 49.94, 'groceries', 'credits', 'debit')
RETURNING id`
);
await queryRaw(
`INSERT INTO expense_metadata (transaction_id, source, order_reference, amount, transaction_date, flags)
VALUES ($1,'email',$2, 49.94, '2026-07-07', '[]'::jsonb)`,
[txn!.id, a.order_reference]
);
const before = await queryRow<{ c: string }>(`SELECT count(*)::text c FROM transactions`);
const res = await applyOrderAmendment(a);
const after = await queryRow<{ c: string }>(`SELECT count(*)::text c FROM transactions`);
expect(res.matched).toBe(true);
expect(after!.c).toBe(before!.c); // amended in place, no second row
const updated = await queryRow<{ amount: string }>(
`SELECT amount::text FROM transactions WHERE id = $1`,
[txn!.id]
);
expect(Number(updated!.amount)).toBeCloseTo(45.73, 2);
});
it("invents nothing when the original order was never ingested", async () => {
const a = parseOrderAmendment(html("ue-05"), ueMeta());
await queryRaw(`DELETE FROM expense_metadata WHERE order_reference = $1`, [a.order_reference]);
const res = await applyOrderAmendment(a);
expect(res.matched).toBe(false);
expect(res.transactionId).toBeNull();
});
});
describe("[Family] orders import rather than park", () => {
it("records a family order as credits and tags it", async () => {
const p = parseOrderHTML(
html("ue-04"),
meta({ subject: "[Family] Your Tuesday evening order with Uber Eats", sender: "uber.com", receivedAt: "2026-07-07T10:08:00Z" })
);
expect(p.flags).toContain("family_payment_assumed_credits");
const res = await processOrderIngestion(p);
expect(res.transactionId).not.toBeNull();
const tag = await queryRow<{ name: string }>(
`SELECT tg.name FROM transaction_tags tt JOIN tags tg ON tg.id = tt.tag_id
WHERE tt.transaction_id = $1`,
[res.transactionId]
);
expect(tag!.name).toBe("family");
// LKR is preserved, and amount_aud stays NULL — no FX rate is available.
const txn = await queryRow<{ foreign_currency_code: string; amount_aud: string | null }>(
`SELECT foreign_currency_code, amount_aud::text FROM transactions WHERE id = $1`,
[res.transactionId]
);
expect(txn!.foreign_currency_code).toBe("LKR");
expect(txn!.amount_aud).toBeNull();
// And it must not reach spend.
const visible = await queryRaw(
`SELECT t.id FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
WHERE t.id = $1 AND (${EXCLUDE_NON_SPEND})`,
[res.transactionId]
);
expect(visible).toHaveLength(0);
});
});
+166
View File
@@ -0,0 +1,166 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "fs";
import { resolve } from "path";
import {
parseOrderHTML,
validateOrderTotals,
resolveCategory,
OrderParseError,
NotAReceiptError,
type MessageMeta,
type ParsedOrder,
} from "../../lib/order-ingestion";
/**
* Rewritten 2026-07-26. The previous unit suite exercised synthetic fixtures
* built to satisfy the parser, so it passed while the parser could not read a
* real email. These run against unmodified captured receipts.
*/
const dir = resolve(__dirname, "../fixtures/orders/real");
const html = (f: string) => readFileSync(resolve(dir, `${f}.html`), "utf-8");
const meta = (over: Partial<MessageMeta> = {}): MessageMeta => ({
messageId: "unit-1",
subject: "Order Confirmation for Siddharth from Mad Mex",
receivedAt: "2026-07-16T03:34:00Z",
sender: "DoorDash Order <no-reply@doordash.com>",
...over,
});
describe("payment detection", () => {
it("credits-only", () => {
const p = parseOrderHTML(html("dd-01"), meta());
expect(p.payment.credits_amount).toBe(14.64);
expect(p.payment.card_last4).toBeNull();
expect(p.payment.ambiguous).toBe(false);
});
it("card-only produces no credits figure", () => {
const p = parseOrderHTML(
html("dd-27"),
meta({ subject: "Order Confirmation for Siddharth from Subway" })
);
expect(p.payment.card_last4).toBe("8032");
expect(p.payment.credits_amount).toBeNull();
});
it("'and/or credits' is ambiguous, not silently credits", () => {
// Regression: an earlier regex delimited the payment line on a double
// space, which whitespace collapsing removes. Every card and mixed receipt
// fell through to the credits branch — this one booked the whole $60.93 as
// credits spend that never happened.
const p = parseOrderHTML(
html("dd-10"),
meta({ subject: "Order Confirmation for Siddharth from Woolworths" })
);
expect(p.payment.ambiguous).toBe(true);
expect(p.payment.card_last4).toBe("8032");
expect(p.payment.credits_amount).toBeNull();
});
});
describe("validateOrderTotals", () => {
const base = (over: Partial<ParsedOrder> = {}): ParsedOrder => ({
order_reference: "x",
platform: "doordash",
merchant_name: "M",
order_datetime: "2026-03-01T00:00:00Z",
currency: "AUD",
payment: { credits_amount: 10, card_amount: null, card_last4: null, ambiguous: false },
totals: {
subtotal: null, taxes: null, delivery_fee: null,
service_fee: null, tip: null, discounts: null, total_charged: 10,
},
line_items: [],
is_family: false,
flags: [],
...over,
});
it("rejects a non-positive total", () => {
const o = base();
o.totals.total_charged = 0;
expect(validateOrderTotals(o).ok).toBe(false);
});
it("rejects payments that do not account for the total", () => {
const r = validateOrderTotals(
base({ payment: { credits_amount: 5, card_amount: null, card_last4: null, ambiguous: false } })
);
expect(r.ok).toBe(false);
expect(r.reason).toMatch(/payments sum/);
});
it("accepts a matching total", () => {
expect(validateOrderTotals(base()).ok).toBe(true);
});
it("does not gate on DoorDash's non-reconciling fee breakdown", () => {
const p = parseOrderHTML(html("dd-01"), meta());
expect(p.totals.subtotal).toBe(22.10);
expect(p.totals.discounts).toBe(24.09); // 22.10 + 1.99 — genuinely printed
expect(validateOrderTotals(p, html("dd-01")).ok).toBe(true);
});
});
describe("resolveCategory", () => {
const o = (merchant: string, platform: ParsedOrder["platform"] = "doordash") =>
({ merchant_name: merchant, platform }) as ParsedOrder;
it("maps grocers to groceries", () => {
expect(resolveCategory(o("Woolworths"))).toBe("groceries");
expect(resolveCategory(o("ALDI"))).toBe("groceries");
expect(resolveCategory(o("GLOMARK Kandana", "ubereats"))).toBe("groceries");
});
it("maps restaurants to dining rather than 'other'", () => {
// The earlier six-merchant allowlist sent every one of these to `other`.
for (const m of ["Carl's Jr.", "Taco Bell", "Chilli India", "Oporto", "Schnitz", "Souvlaki GR"]) {
expect(resolveCategory(o(m))).toBe("dining");
}
});
it("maps rides to transport", () => {
expect(resolveCategory(o("Uber Trip", "uber"))).toBe("transport");
});
});
describe("parse guards", () => {
it("throws on a body too short to be a receipt", () => {
expect(() => parseOrderHTML("<html></html>", meta())).toThrow(NotAReceiptError);
});
it("throws rather than inventing a platform", () => {
expect(() =>
parseOrderHTML(html("dd-01"), meta({ subject: "Newsletter", sender: "someone@example.com" }))
).toThrow(/platform/i);
});
});
describe("order_reference anchoring", () => {
it("takes Uber's tripReference, not the first UUID in the document", () => {
const p = parseOrderHTML(
html("ue-00"),
meta({ subject: "Your Wednesday afternoon order with Uber Eats", sender: "uber.com" })
);
// The UUID the PDF redirect actually resolves to for this receipt.
expect(p.order_reference).toBe("34d6b4ee-da8f-5029-8d14-bd359617c8e9");
expect(p.flags).not.toContain("order_uuid_ambiguous");
});
it("is stable across repeated parses of the same message", () => {
const m = meta({ subject: "Your Wednesday afternoon order with Uber Eats", sender: "uber.com" });
const a = parseOrderHTML(html("ue-00"), m).order_reference;
const b = parseOrderHTML(html("ue-00"), m).order_reference;
expect(a).toBe(b);
});
it("flags ambiguity only when several UUIDs and no anchor", () => {
// Strip the anchor from a receipt that carries multiple UUIDs (ue-09 has 6).
const stripped = html("ue-09").replace(/tripReference/gi, "notTheAnchor");
const p = parseOrderHTML(
stripped,
meta({ subject: "[Family] Your Sunday evening order with Uber Eats", sender: "uber.com" })
);
expect(p.flags).toContain("order_uuid_ambiguous");
});
});
+5 -8
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { OWNER_SCOPE, STATEMENTS_JOIN, mySplitOf } from "@/lib/analytics-sql";
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
@@ -40,17 +41,13 @@ export async function GET(req: NextRequest) {
t.description,
t.merchant_name,
t.transaction_type,
CASE
WHEN ts.share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100
WHEN o.my_share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * o.my_share_percent / 100
ELSE COALESCE(t.amount_aud, t.amount)
END::numeric(12,2) AS my_amount,
s.bank_name
${mySplitOf(`COALESCE(t.amount_aud, t.amount)`)}::numeric(12,2) AS my_amount,
COALESCE(s.bank_name, 'Manual') AS bank_name
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
JOIN statements s ON s.id = t.statement_id
WHERE s.owner_id = $1
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('fee', 'interest')
ORDER BY t.transaction_date DESC`,
[user.id]
@@ -1,6 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { OWNER_SCOPE, STATEMENTS_JOIN, EFFECTIVE_CATEGORY, mySplitOf } from "@/lib/analytics-sql";
const MY_AMOUNT = mySplitOf(`COALESCE(t.amount_aud, t.amount)`);
export async function GET(
req: NextRequest,
@@ -31,20 +34,18 @@ export async function GET(
t.amount,
t.amount_aud,
CASE
WHEN t.transaction_type IN ('refund', 'credit') THEN
-(CASE WHEN ts.share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100 WHEN o.my_share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * o.my_share_percent / 100 ELSE COALESCE(t.amount_aud, t.amount) END)
ELSE
(CASE WHEN ts.share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100 WHEN o.my_share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * o.my_share_percent / 100 ELSE COALESCE(t.amount_aud, t.amount) END)
WHEN t.transaction_type IN ('refund', 'credit') THEN -${MY_AMOUNT}
ELSE ${MY_AMOUNT}
END::numeric(10,2) as my_amount,
t.transaction_type,
COALESCE(o.category_override, t.category) as category,
s.bank_name,
${EFFECTIVE_CATEGORY} as category,
COALESCE(s.bank_name, 'Manual') as bank_name,
t.statement_id
FROM transactions t
JOIN statements s ON s.id = t.statement_id
${STATEMENTS_JOIN}
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
WHERE s.owner_id = $1
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('debit', 'fee', 'interest', 'refund', 'credit')
AND COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name, t.description) = $2
ORDER BY t.transaction_date DESC
+9 -8
View File
@@ -1,9 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { OWNER_SCOPE, STATEMENTS_JOIN, EXCLUDE_NON_SPEND, EFFECTIVE_CATEGORY, mySplitOf } from "@/lib/analytics-sql";
// Split-adjusted amount helper (positive for spend, negative for refunds)
const MY_AMOUNT = `CASE WHEN ts.share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100 WHEN o.my_share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * o.my_share_percent / 100 ELSE COALESCE(t.amount_aud, t.amount) END`;
const MY_AMOUNT = mySplitOf(`COALESCE(t.amount_aud, t.amount)`);
const SPEND_EXPR = `
CASE
WHEN t.transaction_type IN ('refund', 'credit') THEN -(${MY_AMOUNT})
@@ -38,7 +39,7 @@ export async function GET(req: NextRequest) {
}>(`
SELECT
COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name, t.description) as merchant,
MODE() WITHIN GROUP (ORDER BY COALESCE(o.category_override, t.category)) as category,
MODE() WITHIN GROUP (ORDER BY ${EFFECTIVE_CATEGORY}) as category,
COUNT(*) FILTER (WHERE t.transaction_type IN ('debit', 'fee', 'interest'))::int as debit_count,
COUNT(*) FILTER (WHERE t.transaction_type IN ('refund', 'credit'))::int as refund_count,
COALESCE(SUM(
@@ -61,13 +62,13 @@ export async function GET(req: NextRequest) {
MAX(t.transaction_date)::text as last_seen,
COUNT(DISTINCT TO_CHAR(DATE_TRUNC('month', t.transaction_date::date), 'YYYY-MM'))::int as months_active
FROM transactions t
JOIN statements s ON s.id = t.statement_id
${STATEMENTS_JOIN}
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
WHERE s.owner_id = $1
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('debit', 'fee', 'interest', 'refund', 'credit')
AND t.transaction_date >= $2
AND COALESCE(o.category_override, t.category) NOT IN ('transfers', 'investment')
AND ${EXCLUDE_NON_SPEND}
GROUP BY 1
HAVING SUM(${SPEND_EXPR}) > 0
ORDER BY net_spend DESC
@@ -86,14 +87,14 @@ export async function GET(req: NextRequest) {
TO_CHAR(DATE_TRUNC('month', t.transaction_date::date), 'YYYY-MM') as month,
SUM(${SPEND_EXPR})::numeric(10,2) as total
FROM transactions t
JOIN statements s ON s.id = t.statement_id
${STATEMENTS_JOIN}
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
WHERE s.owner_id = $1
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('debit', 'fee', 'interest', 'refund', 'credit')
AND t.transaction_date >= $2
AND COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name, t.description) = ANY($3)
AND COALESCE(o.category_override, t.category) NOT IN ('transfers', 'investment')
AND ${EXCLUDE_NON_SPEND}
GROUP BY 1, 2
ORDER BY 1, 2
`, [user.id, fromDate, topMerchants]);
+21 -18
View File
@@ -1,6 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import {
OWNER_SCOPE,
STATEMENTS_JOIN,
EFFECTIVE_CATEGORY,
EXCLUDE_NON_SPEND,
NET_SPEND_ROWS,
SPEND_SIGNED,
mySplitOf,
} from "@/lib/analytics-sql";
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
@@ -25,22 +34,16 @@ export async function GET(req: NextRequest) {
}>(
`SELECT
TO_CHAR(DATE_TRUNC('month', t.transaction_date::date), 'YYYY-MM') as month,
COALESCE(o.category_override, t.category) as category,
SUM(
CASE
WHEN ts.share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100
WHEN o.my_share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * o.my_share_percent / 100
ELSE COALESCE(t.amount_aud, t.amount)
END
)::numeric(12,2) as total_spent,
${EFFECTIVE_CATEGORY} as category,
SUM(${mySplitOf(SPEND_SIGNED)})::numeric(12,2) as total_spent,
COUNT(*)::int as transaction_count
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
JOIN statements s ON s.id = t.statement_id
WHERE s.owner_id = $1
AND t.transaction_type IN ('debit', 'fee', 'interest')
AND COALESCE(o.category_override, t.category) NOT IN ('transfers', 'investment')
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND ${NET_SPEND_ROWS}
AND ${EXCLUDE_NON_SPEND}
AND t.transaction_date >= $2
AND t.transaction_date < $3
GROUP BY 1, 2
@@ -60,10 +63,10 @@ export async function GET(req: NextRequest) {
COUNT(*)::int as transaction_count
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
JOIN statements s ON s.id = t.statement_id
WHERE s.owner_id = $1
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('credit', 'payment')
AND COALESCE(o.category_override, t.category) = 'income'
AND ${EFFECTIVE_CATEGORY} = 'income'
AND t.transaction_date >= $2
AND t.transaction_date < $3
GROUP BY 1
@@ -83,9 +86,9 @@ export async function GET(req: NextRequest) {
COUNT(*)::int as transaction_count
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
JOIN statements s ON s.id = t.statement_id
WHERE s.owner_id = $1
AND COALESCE(o.category_override, t.category) = 'investment'
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND ${EFFECTIVE_CATEGORY} = 'investment'
AND t.transaction_date >= $2
AND t.transaction_date < $3
GROUP BY 1
+7 -9
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { OWNER_SCOPE, STATEMENTS_JOIN, EXCLUDE_NON_SPEND, EFFECTIVE_CATEGORY, mySplitOf } from "@/lib/analytics-sql";
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
@@ -20,19 +21,16 @@ export async function GET(req: NextRequest) {
`WITH merchant_txns AS (
SELECT
COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) AS merchant,
COALESCE(o.category_override, t.category) AS category,
${EFFECTIVE_CATEGORY} AS category,
t.transaction_date,
CASE
WHEN ts.share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100
WHEN o.my_share_percent IS NOT NULL THEN COALESCE(t.amount_aud, t.amount) * o.my_share_percent / 100
ELSE COALESCE(t.amount_aud, t.amount)
END AS my_amount
${mySplitOf(`COALESCE(t.amount_aud, t.amount)`)} AS my_amount
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
JOIN statements s ON s.id = t.statement_id
WHERE s.owner_id = $1
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('debit', 'fee')
AND ${EXCLUDE_NON_SPEND}
AND COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) IS NOT NULL
),
merchant_with_lag AS (
@@ -48,7 +46,7 @@ export async function GET(req: NextRequest) {
SELECT
merchant,
MODE() WITHIN GROUP (ORDER BY category) AS category,
COUNT(*) + 1 AS occurrences,
(COUNT(*) + 1)::int AS occurrences,
AVG(my_amount)::numeric(12,2) AS avg_amount,
MIN(transaction_date) AS first_seen,
MAX(transaction_date) AS last_seen,
+3
View File
@@ -1,7 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { getMerchantSuggestions, getBankNames } from "@/lib/queries";
import { getCurrentUser } from "@/lib/auth";
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const search = req.nextUrl.searchParams.get("search");
const type = req.nextUrl.searchParams.get("type");
+117
View File
@@ -0,0 +1,117 @@
import { NextRequest, NextResponse } from "next/server";
import {
parseOrderHTML,
parseOrderAmendment,
isAmendment,
validateOrderTotals,
processOrderIngestion,
applyOrderAmendment,
reconcilePendingOrders,
OrderParseError,
NotAReceiptError,
type MessageMeta,
} from "@/lib/order-ingestion";
/**
* Machine ingest endpoint for order receipts.
*
* n8n polls the two mailboxes and POSTs each message here. The parsing lives in
* the app, not in an n8n Code node, because the n8n sandbox has no `require`
* and no filesystem — a parser there could not be unit-tested against the real
* fixture corpus, which is the whole reason this one is trustworthy.
*
* Auth is a shared secret, not the Traefik `x-forwarded-user` header: this is
* called machine-to-machine and there is no browser session to forward.
*/
function authorised(req: NextRequest): boolean {
const expected = process.env.ORDER_INGEST_TOKEN;
if (!expected) return false; // fail closed when unconfigured
const got = req.headers.get("x-ingest-token");
return !!got && got === expected;
}
export async function POST(req: NextRequest) {
if (!authorised(req)) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
let body: { html?: string; meta?: MessageMeta; dryRun?: boolean };
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "invalid JSON" }, { status: 400 });
}
const { html, meta, dryRun } = body;
if (!html || !meta?.messageId || !meta?.subject || !meta?.receivedAt) {
return NextResponse.json(
{ error: "html and meta{messageId,subject,receivedAt} are required" },
{ status: 400 }
);
}
try {
// Amendments restate an existing order; they are not receipts.
if (isAmendment(html)) {
const amendment = parseOrderAmendment(html, meta);
if (dryRun) return NextResponse.json({ kind: "amendment", amendment });
const applied = await applyOrderAmendment(amendment);
return NextResponse.json({ kind: "amendment", amendment, applied });
}
const order = parseOrderHTML(html, meta);
const check = validateOrderTotals(order, html);
if (!check.ok) {
// Refuse rather than record a number we cannot stand behind.
return NextResponse.json(
{ kind: "rejected", reason: check.reason, order_reference: order.order_reference },
{ status: 422 }
);
}
if (dryRun) return NextResponse.json({ kind: "order", order });
const result = await processOrderIngestion(order, { messageId: meta.messageId });
return NextResponse.json({
kind: "order",
order_reference: order.order_reference,
merchant: order.merchant_name,
total: order.totals.total_charged,
currency: order.currency,
is_family: order.is_family,
...result,
});
} catch (e) {
// Not a receipt: promotions, delivery updates, adjustment and refund
// notices. Expected traffic — 200 and silent, or the alert channel fills
// with noise and stops being read.
if (e instanceof NotAReceiptError) {
return NextResponse.json({ kind: "skipped", reason: e.message });
}
// IS a receipt, could not be parsed. This is the failure that matters and
// it must be loud: a provider template change breaks every order at once,
// and the only other symptom is spend quietly ceasing to appear. Returning
// 200 here — as this route originally did — made the most likely
// production failure completely invisible.
if (e instanceof OrderParseError) {
return NextResponse.json(
{ kind: "parse_failed", reason: e.message, messageId: e.messageId },
{ status: 422 }
);
}
const message = e instanceof Error ? e.message : String(e);
return NextResponse.json({ error: message }, { status: 500 });
}
}
/** Statement-import hook: resolve orders parked awaiting a card statement. */
export async function PATCH(req: NextRequest) {
if (!authorised(req)) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const out = await reconcilePendingOrders();
return NextResponse.json(out);
}
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
interface BalanceRow {
participant_id: number;
@@ -9,14 +10,16 @@ interface BalanceRow {
}
export async function GET(
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
const rows = await queryRaw<BalanceRow>(
`SELECT ts.participant_id, p.name,
SUM(t.amount * ts.share_percent / 100)::numeric(12,2) as total_owed,
SUM(COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100)::numeric(12,2) as total_owed,
COUNT(*)::int as transaction_count
FROM transaction_splits ts
JOIN transactions t ON t.id = ts.transaction_id
+127
View File
@@ -0,0 +1,127 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { getTransactions } from "@/lib/queries";
import { evaluateCondition, type Condition, type Actions } from "@/lib/rules";
/**
* Dry run: which transactions would this rule touch, and what would change?
*
* Nothing is written. This exists so a rule can be inspected before it is
* applied — the apply path (POST /api/transactions/bulk with action
* "apply_rule") takes an explicit list of ids, so the flow is preview, pick,
* then apply.
*
* Matches are split into two groups because they need different attention:
* `changes` are rows the rule would actually alter, `noops` already have the
* value the rule would set. A merchant-normalisation rule matching 400 rows
* where 380 are already correct is 20 changes and 380 rows of noise.
*/
interface Change {
field: "category" | "merchant" | "tags" | "split";
from: string | null;
to: string;
}
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
const rules = await queryRaw<{
id: number; name: string; conditions: unknown; actions: unknown;
}>(
`SELECT id, name, conditions, actions FROM rules WHERE id = $1 AND owner_id = $2`,
[Number(id), user.id]
);
if (!rules.length) return NextResponse.json({ error: "Rule not found" }, { status: 404 });
const rule = rules[0];
const conditions = (typeof rule.conditions === "string"
? JSON.parse(rule.conditions) : rule.conditions) as Condition[];
const actions = (typeof rule.actions === "string"
? JSON.parse(rule.actions) : rule.actions) as Actions;
const { searchParams } = new URL(req.url);
const statementId = searchParams.get("statement_id");
const limit = Math.min(2000, Math.max(1, Number(searchParams.get("limit") || "500")));
const { data: transactions } = await getTransactions(user.id, {
limit: 100000,
offset: 0,
...(statementId ? { statement_id: statementId } : {}),
});
// A rule with no conditions matches every transaction. That is how the apply
// endpoint behaves too, so the preview must show it rather than hide it —
// seeing "matches 3,721" is the point.
const matchAll = conditions.length === 0;
const tagIds = new Set(actions.add_tag_ids ?? []);
const splitTarget = actions.apply_split ?? [];
const changes: unknown[] = [];
let noops = 0;
for (const tx of transactions) {
if (!matchAll && !conditions.every((c) => evaluateCondition(c, tx))) continue;
const diff: Change[] = [];
if (actions.set_category && tx.effective_category !== actions.set_category) {
diff.push({ field: "category", from: tx.effective_category ?? null, to: actions.set_category });
}
if (actions.set_merchant && tx.effective_merchant !== actions.set_merchant) {
diff.push({ field: "merchant", from: tx.effective_merchant ?? null, to: actions.set_merchant });
}
if (tagIds.size) {
const have = new Set((tx.tags ?? []).map((t) => t.id));
const missing = [...tagIds].filter((t) => !have.has(t));
if (missing.length) {
diff.push({ field: "tags", from: null, to: missing.join(",") });
}
}
if (splitTarget.length) {
// Compare the participant/share set the rule would write against what is
// already there; a re-run that changes nothing should not look like work.
const have = new Map((tx.splits ?? []).map((s) => [s.participant_id, Number(s.share_percent)]));
const differs = splitTarget.length !== have.size
|| splitTarget.some((s) => have.get(s.participant_id) !== Number(s.share_percent));
if (differs) {
diff.push({
field: "split",
from: [...have.entries()].map(([p, s]) => `${p}:${s}%`).join(" ") || null,
to: splitTarget.map((s) => `${s.participant_id}:${s.share_percent}%`).join(" "),
});
}
}
if (diff.length === 0) { noops++; continue; }
changes.push({
id: tx.id,
transaction_date: tx.transaction_date,
description: tx.description,
amount: tx.amount,
amount_aud: tx.amount_aud,
currency: tx.currency,
bank_name: tx.bank_name,
effective_merchant: tx.effective_merchant,
effective_category: tx.effective_category,
changes: diff,
});
}
return NextResponse.json({
rule: { id: rule.id, name: rule.name, matches_everything: matchAll },
total_matched: changes.length + noops,
would_change: changes.length,
already_correct: noops,
transactions: changes.slice(0, limit),
truncated: changes.length > limit,
});
}
+1
View File
@@ -22,6 +22,7 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
...(body.conditions !== undefined && { conditions: body.conditions }),
...(body.actions !== undefined && { actions: body.actions }),
...(body.enabled !== undefined && { enabled: body.enabled }),
...(body.manual_only !== undefined && { manual_only: body.manual_only }),
...(body.priority !== undefined && { priority: body.priority }),
},
});
+26 -93
View File
@@ -3,15 +3,7 @@ import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { getTransactions } from "@/lib/queries";
import { evaluateCondition, type Condition, type Actions } from "@/lib/rules";
interface SnapshotEntry {
transaction_id: number;
had_override: boolean;
prev_category_override: string | null;
prev_merchant_normalized: string | null;
prev_tag_ids: number[];
prev_splits: { participant_id: number; share_percent: number; settled: boolean }[];
}
import { applyRuleActions, captureSnapshot } from "@/lib/rule-actions";
export async function GET(req: NextRequest) {
@@ -25,8 +17,12 @@ export async function GET(req: NextRequest) {
matched: number;
transactions_affected: number;
reverted_at: string | null;
rule_id: number | null;
rule_name: string | null;
source: string | null;
}>(
`SELECT id, applied_at, split_from, matched, transactions_affected, reverted_at
`SELECT id, applied_at, split_from, matched, transactions_affected, reverted_at,
rule_id, rule_name, source
FROM rule_apply_runs WHERE owner_id = $1 ORDER BY applied_at DESC LIMIT 20`,
[user.id]
);
@@ -42,10 +38,16 @@ export async function POST(req: NextRequest) {
const splitFrom = body.splitFrom || null;
const ruleId = body.ruleId || null;
const rules = await queryRaw<{ id: number; conditions: unknown; actions: unknown }>(
// Manual-only rules ("quick actions") never take part in a condition-matched
// run — their conditions are typically empty, so they would match every
// transaction. They are fired from the transactions page against a selection.
const rules = await queryRaw<{ id: number; name: string; conditions: unknown; actions: unknown }>(
ruleId
? `SELECT id, conditions, actions FROM rules WHERE owner_id = $1 AND id = $2`
: `SELECT id, conditions, actions FROM rules WHERE owner_id = $1 AND enabled = true ORDER BY priority DESC`,
? `SELECT id, name, conditions, actions FROM rules
WHERE owner_id = $1 AND id = $2 AND manual_only = false`
: `SELECT id, name, conditions, actions FROM rules
WHERE owner_id = $1 AND enabled = true AND manual_only = false
ORDER BY priority DESC`,
ruleId ? [user.id, ruleId] : [user.id]
);
@@ -70,51 +72,7 @@ export async function POST(req: NextRequest) {
}
// --- Capture before-state for all matched transactions (batched) ---
const snapshot: SnapshotEntry[] = [];
if (matchedIds.size > 0) {
const ids = Array.from(matchedIds);
const idList = ids.join(",");
const overrides = await queryRaw<{ transaction_id: number; category_override: string | null; merchant_normalized: string | null }>(
`SELECT transaction_id, category_override, merchant_normalized FROM transaction_overrides WHERE transaction_id = ANY($1::int[])`,
[ids]
);
const overrideMap = new Map(overrides.map((o) => [o.transaction_id, o]));
const tagRows = await queryRaw<{ transaction_id: number; tag_id: number }>(
`SELECT transaction_id, tag_id FROM transaction_tags WHERE transaction_id = ANY($1::int[])`,
[ids]
);
const tagMap = new Map<number, number[]>();
for (const row of tagRows) {
if (!tagMap.has(row.transaction_id)) tagMap.set(row.transaction_id, []);
tagMap.get(row.transaction_id)!.push(row.tag_id);
}
const splitRows = await queryRaw<{ transaction_id: number; participant_id: number; share_percent: number; settled: boolean }>(
`SELECT transaction_id, participant_id, share_percent, settled FROM transaction_splits WHERE transaction_id = ANY($1::int[])`,
[ids]
);
const splitMap = new Map<number, { participant_id: number; share_percent: number; settled: boolean }[]>();
for (const row of splitRows) {
if (!splitMap.has(row.transaction_id)) splitMap.set(row.transaction_id, []);
splitMap.get(row.transaction_id)!.push({ participant_id: row.participant_id, share_percent: row.share_percent, settled: row.settled });
}
for (const id of ids) {
const ov = overrideMap.get(id);
snapshot.push({
transaction_id: id,
had_override: !!ov,
prev_category_override: ov?.category_override ?? null,
prev_merchant_normalized: ov?.merchant_normalized ?? null,
prev_tag_ids: tagMap.get(id) ?? [],
prev_splits: splitMap.get(id) ?? [],
});
}
void idList; // suppress unused warning
}
const snapshot = await captureSnapshot(Array.from(matchedIds));
// --- Apply rules ---
let matched = 0;
@@ -128,46 +86,21 @@ export async function POST(req: NextRequest) {
matched++;
affectedIds.add(tx.id);
if (actions.set_category || actions.set_merchant) {
await queryRaw(
`INSERT INTO transaction_overrides (transaction_id, category_override, merchant_normalized)
VALUES ($1, $2, $3)
ON CONFLICT (transaction_id) DO UPDATE SET
category_override = COALESCE($2, transaction_overrides.category_override),
merchant_normalized = COALESCE($3, transaction_overrides.merchant_normalized),
updated_at = NOW()`,
[tx.id, actions.set_category || null, actions.set_merchant || null]
);
}
if (actions.add_tag_ids?.length) {
for (const tagId of actions.add_tag_ids) {
await queryRaw(
`INSERT INTO transaction_tags (transaction_id, tag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[tx.id, tagId]
);
}
}
if (actions.apply_split?.length) {
if (splitFrom && tx.transaction_date < splitFrom) continue;
await queryRaw(`DELETE FROM transaction_splits WHERE transaction_id = $1`, [tx.id]);
for (const s of actions.apply_split) {
await queryRaw(
`INSERT INTO transaction_splits (transaction_id, participant_id, share_percent)
VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
[tx.id, s.participant_id, s.share_percent]
);
}
}
// splitFrom holds the split back to transactions on/after that date;
// category/merchant/tags still apply to everything matched.
await applyRuleActions(tx.id, actions, {
skipSplit: !!splitFrom && tx.transaction_date < splitFrom,
});
}
}
// --- Save run record ---
const run = await queryRaw<{ id: number }>(
`INSERT INTO rule_apply_runs (owner_id, split_from, matched, transactions_affected, snapshot)
VALUES ($1, $2, $3, $4, $5) RETURNING id`,
[user.id, splitFrom, matched, affectedIds.size, JSON.stringify(snapshot)]
`INSERT INTO rule_apply_runs (owner_id, split_from, matched, transactions_affected, snapshot,
rule_id, rule_name, source)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id`,
[user.id, splitFrom, matched, affectedIds.size, JSON.stringify(snapshot),
ruleId, ruleId ? (rules[0]?.name ?? null) : null, ruleId ? "rule" : "all"]
);
return NextResponse.json({ id: run[0].id, matched, transactions_affected: affectedIds.size });
+4 -2
View File
@@ -12,10 +12,11 @@ export async function GET(req: NextRequest) {
conditions: unknown;
actions: unknown;
enabled: boolean;
manual_only: boolean;
priority: number;
created_at: string;
}>(
`SELECT id, name, conditions, actions, enabled, priority, created_at
`SELECT id, name, conditions, actions, enabled, manual_only, priority, created_at
FROM rules WHERE owner_id = $1 ORDER BY priority DESC, id ASC`,
[user.id]
);
@@ -26,7 +27,7 @@ export async function POST(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { name, conditions, actions, enabled = true, priority = 0 } = await req.json();
const { name, conditions, actions, enabled = true, manual_only = false, priority = 0 } = await req.json();
if (!name) return NextResponse.json({ error: "name required" }, { status: 400 });
const rule = await prisma.rules.create({
@@ -36,6 +37,7 @@ export async function POST(req: NextRequest) {
conditions: conditions ?? [],
actions: actions ?? {},
enabled,
manual_only,
priority,
},
});
+134
View File
@@ -0,0 +1,134 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
/**
* What a rule run actually did — the before-state from its snapshot set against
* the values now.
*
* The run list only had counts, which is not enough to decide whether to revert:
* "13 matches · 13 transactions" reads the same whether it renamed a merchant or
* split your history with someone. Reverting is destructive, so the detail has
* to be visible before the button is pressed.
*/
interface SnapshotEntry {
transaction_id: number;
had_override: boolean;
prev_category_override: string | null;
prev_merchant_normalized: string | null;
prev_tag_ids: number[];
prev_splits: { participant_id: number; share_percent: number; settled: boolean }[];
}
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
const runs = await queryRaw<{
id: number; applied_at: string; reverted_at: string | null;
split_from: string | null; matched: number; transactions_affected: number;
rule_id: number | null; rule_name: string | null; source: string | null;
snapshot: unknown;
}>(
`SELECT id, applied_at, reverted_at, split_from, matched, transactions_affected,
rule_id, rule_name, source, snapshot
FROM rule_apply_runs WHERE id = $1 AND owner_id = $2`,
[Number(id), user.id]
);
if (!runs.length) return NextResponse.json({ error: "Run not found" }, { status: 404 });
const run = runs[0];
const snapshot = (typeof run.snapshot === "string"
? JSON.parse(run.snapshot) : run.snapshot) as SnapshotEntry[];
const byId = new Map(snapshot.map((s) => [s.transaction_id, s]));
const ids = snapshot.map((s) => s.transaction_id);
if (ids.length === 0) {
return NextResponse.json({ run: { ...run, snapshot: undefined }, transactions: [] });
}
const current = await queryRaw<{
id: number; transaction_date: string; description: string;
amount: number; amount_aud: number | null; bank_name: string;
category: string | null; category_override: string | null;
merchant_normalized: string | null; merchant_override: string | null;
merchant_name: string | null;
tag_ids: number[]; splits: { participant_id: number; share_percent: number }[];
}>(
`SELECT t.id, t.transaction_date::text, t.description, t.amount, t.amount_aud,
COALESCE(s.bank_name, 'Manual') as bank_name,
t.category, o.category_override,
t.merchant_normalized, o.merchant_normalized as merchant_override, t.merchant_name,
COALESCE((SELECT json_agg(tt.tag_id) FROM transaction_tags tt WHERE tt.transaction_id = t.id), '[]'::json) as tag_ids,
COALESCE((SELECT json_agg(json_build_object('participant_id', ts.participant_id, 'share_percent', ts.share_percent))
FROM transaction_splits ts WHERE ts.transaction_id = t.id), '[]'::json) as splits
FROM transactions t
LEFT JOIN statements s ON s.id = t.statement_id
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
WHERE t.id = ANY($1::int[])
ORDER BY t.transaction_date DESC`,
[ids]
);
const parse = <T,>(v: unknown, fallback: T): T =>
(typeof v === "string" ? JSON.parse(v) : v) ?? fallback;
const transactions = current.map((t) => {
const prev = byId.get(t.id);
const nowTags: number[] = parse(t.tag_ids, []);
const nowSplits = parse<{ participant_id: number; share_percent: number }[]>(t.splits, []);
const prevTags = prev?.prev_tag_ids ?? [];
const prevSplits = prev?.prev_splits ?? [];
const nowCategory = t.category_override ?? t.category;
const prevCategory = prev?.prev_category_override ?? t.category;
const nowMerchant = t.merchant_override ?? t.merchant_normalized ?? t.merchant_name;
const prevMerchant = prev?.prev_merchant_normalized ?? t.merchant_normalized ?? t.merchant_name;
const changes: { field: string; from: string | null; to: string | null }[] = [];
if (nowCategory !== prevCategory) {
changes.push({ field: "category", from: prevCategory, to: nowCategory });
}
if (nowMerchant !== prevMerchant) {
changes.push({ field: "merchant", from: prevMerchant, to: nowMerchant });
}
const addedTags = nowTags.filter((x) => !prevTags.includes(x));
if (addedTags.length) {
changes.push({ field: "tags", from: null, to: addedTags.join(",") });
}
const fmtSplits = (arr: { participant_id: number; share_percent: number }[]) =>
arr.length ? arr.map((s) => `${s.participant_id}:${Number(s.share_percent)}%`).sort().join(" ") : null;
if (fmtSplits(nowSplits) !== fmtSplits(prevSplits)) {
changes.push({ field: "split", from: fmtSplits(prevSplits), to: fmtSplits(nowSplits) });
}
return {
id: t.id,
transaction_date: t.transaction_date,
description: t.description,
amount: t.amount,
amount_aud: t.amount_aud,
bank_name: t.bank_name,
merchant: nowMerchant,
changes,
};
});
return NextResponse.json({
run: {
id: run.id, applied_at: run.applied_at, reverted_at: run.reverted_at,
split_from: run.split_from, matched: run.matched,
transactions_affected: run.transactions_affected,
rule_id: run.rule_id, rule_name: run.rule_name, source: run.source,
},
// A reverted run still lists its transactions, but they will show no changes
// because the values are back where they started.
transactions,
still_changed: transactions.filter((t) => t.changes.length > 0).length,
});
}
-30
View File
@@ -1,30 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export async function POST(req: NextRequest) {
const body = await req.json();
const { participant_id, split_ids } = body as {
participant_id?: number;
split_ids?: number[];
};
const now = new Date();
if (participant_id) {
const result = await prisma.transaction_splits.updateMany({
where: { participant_id, settled: false },
data: { settled: true, settled_at: now },
});
return NextResponse.json({ settled: result.count });
}
if (split_ids?.length) {
const result = await prisma.transaction_splits.updateMany({
where: { id: { in: split_ids }, settled: false },
data: { settled: true, settled_at: now },
});
return NextResponse.json({ settled: result.count });
}
return NextResponse.json({ error: "participant_id or split_ids required" }, { status: 400 });
}
+7 -2
View File
@@ -1,12 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
import { getStatementById } from "@/lib/queries";
import { getCurrentUser } from "@/lib/auth";
export async function GET(
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
const stmt = await getStatementById(Number(id));
if (!stmt) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!stmt || stmt.owner_id !== user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
return NextResponse.json(stmt);
}
@@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { createTrip, assignTransactionsToTrip, getTagTransactionIds } from "@/lib/queries";
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { id } = await params;
const tagId = Number(id);
const { start_date, end_date } = await req.json().catch(() => ({}));
// Fetch the tag
const tags = await queryRaw<{ id: number; name: string; color: string }>(
`SELECT id, name, color FROM tags WHERE id = $1`,
[tagId]
);
if (!tags[0]) return NextResponse.json({ error: "Tag not found" }, { status: 404 });
const tag = tags[0];
// Create trip from tag metadata
const trip = await createTrip(user.id, {
name: tag.name,
color: tag.color,
start_date: start_date ?? null,
end_date: end_date ?? null,
});
// Assign all transactions with this tag to the new trip
const transactionIds = await getTagTransactionIds(tagId);
if (transactionIds.length > 0) {
await assignTransactionsToTrip(trip.id, transactionIds);
}
return NextResponse.json({ trip, assigned: transactionIds.length }, { status: 201 });
}
+4 -1
View File
@@ -1,7 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
await queryRaw(`DELETE FROM tags WHERE id = $1`, [Number(id)]);
return NextResponse.json({ ok: true });
+6 -1
View File
@@ -1,13 +1,18 @@
import { NextRequest, NextResponse } from "next/server";
import { getTags } from "@/lib/queries";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
export async function GET() {
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const tags = await getTags();
return NextResponse.json(tags);
}
export async function POST(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { name, color } = await req.json();
if (!name?.trim()) {
return NextResponse.json({ error: "name required" }, { status: 400 });
+33 -5
View File
@@ -1,15 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { getTransactionById } from "@/lib/queries";
import { getTransactionById, canAccessTransactions } from "@/lib/queries";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { queryRaw } from "@/lib/db";
const VALID_TYPES = ["debit", "credit", "payment", "refund", "fee", "interest", "transfer"];
export async function GET(
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
if (!(await canAccessTransactions(user.id, [Number(id)]))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const txn = await getTransactionById(Number(id));
if (!txn) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(txn);
@@ -19,19 +25,26 @@ export async function PATCH(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
const transactionId = Number(id);
if (!(await canAccessTransactions(user.id, [transactionId]))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json();
const { category, merchant_normalized, notes, transaction_type, my_share_percent, description, amount, transaction_date } = body as {
const { category, merchant_normalized, notes, transaction_type, my_share_percent, description, amount, transaction_date, trip_id, payment_method } = body as {
category?: string;
merchant_normalized?: string;
notes?: string;
transaction_type?: string;
payment_method?: string | null;
my_share_percent?: number | null;
description?: string;
amount?: number;
transaction_date?: string;
trip_id?: number | null;
};
if (my_share_percent !== undefined && my_share_percent !== null) {
@@ -72,8 +85,21 @@ export async function PATCH(
);
}
// category/merchant/notes/my_share_percent go through the overrides table
const hasOverride = category !== undefined || merchant_normalized !== undefined || notes !== undefined || my_share_percent !== undefined;
// payment_method is a property of the transaction itself, not a user override
// of extracted data, so it lives on the transactions table.
if (payment_method !== undefined) {
const VALID_METHODS = ["card", "cash", "bank_transfer", "other"];
if (payment_method !== null && !VALID_METHODS.includes(payment_method)) {
return NextResponse.json({ error: "Invalid payment_method" }, { status: 400 });
}
await queryRaw(
`UPDATE transactions SET payment_method = $1 WHERE id = $2`,
[payment_method, transactionId]
);
}
// category/merchant/notes/my_share_percent/trip_id go through the overrides table
const hasOverride = category !== undefined || merchant_normalized !== undefined || notes !== undefined || my_share_percent !== undefined || trip_id !== undefined;
if (!hasOverride) {
return NextResponse.json({ ok: true });
}
@@ -83,6 +109,7 @@ export async function PATCH(
if (merchant_normalized !== undefined) data.merchant_normalized = merchant_normalized;
if (notes !== undefined) data.notes = notes;
if (my_share_percent !== undefined) data.my_share_percent = my_share_percent;
if (trip_id !== undefined) data.trip_id = trip_id;
const override = await prisma.transaction_overrides.upsert({
where: { transaction_id: transactionId },
@@ -93,6 +120,7 @@ export async function PATCH(
merchant_normalized: merchant_normalized || null,
notes: notes || null,
my_share_percent: my_share_percent != null ? String(my_share_percent) : null,
trip_id: trip_id ?? null,
},
});
+13 -1
View File
@@ -1,6 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { canAccessTransactions } from "@/lib/queries";
interface SplitInput {
participant_id: number;
@@ -19,10 +21,15 @@ interface SplitRow {
}
export async function GET(
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
if (!(await canAccessTransactions(user.id, [Number(id)]))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const splits = await queryRaw<SplitRow>(
`SELECT ts.*, p.name
FROM transaction_splits ts
@@ -38,8 +45,13 @@ export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
const transactionId = Number(id);
if (!(await canAccessTransactions(user.id, [transactionId]))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const { splits } = (await req.json()) as { splits: SplitInput[] };
if (!splits || !Array.isArray(splits) || splits.length === 0) {
@@ -1,8 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { canAccessTransactions } from "@/lib/queries";
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
if (!(await canAccessTransactions(user.id, [Number(id)]))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const { tag_id } = await req.json();
if (!tag_id) return NextResponse.json({ error: "tag_id required" }, { status: 400 });
await queryRaw(
@@ -13,7 +20,12 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
}
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { id } = await params;
if (!(await canAccessTransactions(user.id, [Number(id)]))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const { tag_id } = await req.json();
if (!tag_id) return NextResponse.json({ error: "tag_id required" }, { status: 400 });
await queryRaw(
+49
View File
@@ -1,7 +1,13 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma, queryRaw } from "@/lib/db";
import { assignTransactionsToTrip, canAccessTransactions } from "@/lib/queries";
import { getCurrentUser } from "@/lib/auth";
import { applyRuleActions, captureSnapshot } from "@/lib/rule-actions";
import type { Actions } from "@/lib/rules";
export async function POST(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const body = await req.json();
const { action, ids, category, merchant_normalized, splits, tag_id } = body as {
action: string;
@@ -16,6 +22,10 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "ids required" }, { status: 400 });
}
if (!(await canAccessTransactions(user.id, ids.map(Number)))) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
if (action === "categorize" && category) {
const ops = ids.map((id) =>
prisma.transaction_overrides.upsert({
@@ -77,5 +87,44 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ updated: ids.length });
}
// Quick action: fire a saved rule's actions at the current selection. The
// selection replaces the rule's conditions, which are not evaluated at all.
// Recorded as a rule_apply_run so it can be reverted like any other run.
if (action === "apply_rule") {
const { rule_id } = body as { rule_id?: number };
if (!rule_id) return NextResponse.json({ error: "rule_id required" }, { status: 400 });
const rules = await queryRaw<{ id: number; name: string; actions: unknown }>(
`SELECT id, name, actions FROM rules WHERE id = $1 AND owner_id = $2`,
[Number(rule_id), user.id]
);
if (!rules.length) return NextResponse.json({ error: "Rule not found" }, { status: 404 });
const actions = (typeof rules[0].actions === "string"
? JSON.parse(rules[0].actions)
: rules[0].actions) as Actions;
const snapshot = await captureSnapshot(ids.map(Number));
for (const id of ids) {
await applyRuleActions(Number(id), actions);
}
const run = await queryRaw<{ id: number }>(
`INSERT INTO rule_apply_runs (owner_id, split_from, matched, transactions_affected, snapshot,
rule_id, rule_name, source)
VALUES ($1, NULL, $2, $3, $4, $5, $6, 'selection') RETURNING id`,
[user.id, ids.length, ids.length, JSON.stringify(snapshot),
rules[0].id, rules[0].name]
);
return NextResponse.json({ updated: ids.length, run_id: run[0].id, rule: rules[0].name });
}
if (action === "assign_trip") {
const { trip_id } = body as { ids: number[]; trip_id: number | null };
await assignTransactionsToTrip(trip_id, ids);
return NextResponse.json({ updated: ids.length });
}
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}
+5 -2
View File
@@ -25,6 +25,7 @@ export async function GET(req: NextRequest) {
amount_min: sp.get("amount_min") ? Number(sp.get("amount_min")) : undefined,
amount_max: sp.get("amount_max") ? Number(sp.get("amount_max")) : undefined,
has_split: sp.get("has_split") || undefined,
trip_id: sp.get("trip_id") || undefined,
});
return NextResponse.json(result);
@@ -41,6 +42,7 @@ export async function POST(req: NextRequest) {
transaction_type?: string;
merchant_normalized?: string;
category?: string;
payment_method?: string;
splits?: { participant_id: number; share_percent: number }[];
};
@@ -50,8 +52,8 @@ export async function POST(req: NextRequest) {
// Insert manual transaction with no statement (statement_id = NULL, owner_id set directly)
const txRows = await queryRaw<{ id: number }>(
`INSERT INTO transactions (statement_id, owner_id, transaction_date, description, amount, transaction_type, merchant_normalized, category, row_index)
VALUES (NULL, $1, $2, $3, $4, $5, $6, $7, (
`INSERT INTO transactions (statement_id, owner_id, transaction_date, description, amount, transaction_type, merchant_normalized, category, payment_method, row_index)
VALUES (NULL, $1, $2, $3, $4, $5, $6, $7, $8, (
SELECT COALESCE(MAX(row_index), -1) + 1 FROM transactions WHERE owner_id = $1 AND statement_id IS NULL
))
RETURNING id`,
@@ -63,6 +65,7 @@ export async function POST(req: NextRequest) {
body.transaction_type || "debit",
body.merchant_normalized || null,
body.category || null,
body.payment_method || null,
]
);
const transactionId = txRows[0].id;
+15
View File
@@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { getTripAnalytics } from "@/lib/queries";
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { id } = await params;
try {
const analytics = await getTripAnalytics(Number(id), user.id);
return NextResponse.json(analytics);
} catch {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
}
+30
View File
@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { getTripById, updateTrip, deleteTrip } from "@/lib/queries";
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { id } = await params;
const trip = await getTripById(Number(id), user.id);
if (!trip) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(trip);
}
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { id } = await params;
const body = await req.json();
const trip = await updateTrip(Number(id), user.id, body);
if (!trip) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(trip);
}
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { id } = await params;
await deleteTrip(Number(id), user.id);
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { assignTransactionsToTrip } from "@/lib/queries";
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { id } = await params;
const { transactionIds } = await req.json() as { transactionIds: number[] };
if (!Array.isArray(transactionIds) || !transactionIds.length) {
return NextResponse.json({ error: "transactionIds must be a non-empty array" }, { status: 400 });
}
await assignTransactionsToTrip(Number(id), transactionIds);
return NextResponse.json({ ok: true });
}
+20
View File
@@ -0,0 +1,20 @@
import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { getTrips, createTrip } from "@/lib/queries";
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const trips = await getTrips(user.id);
return NextResponse.json(trips);
}
export async function POST(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await req.json();
const { name, description, start_date, end_date, color } = body;
if (!name?.trim()) return NextResponse.json({ error: "name is required" }, { status: 400 });
const trip = await createTrip(user.id, { name: name.trim(), description, start_date, end_date, color });
return NextResponse.json(trip, { status: 201 });
}
+290 -251
View File
@@ -1,9 +1,11 @@
"use client";
import { useState, Fragment, useMemo } from "react";
import { useState, useEffect, Fragment, useMemo } from "react";
import {
ComposedChart,
LineChart,
AreaChart,
Area,
Bar,
Line,
XAxis,
@@ -12,11 +14,11 @@ import {
ResponsiveContainer,
Cell,
ReferenceLine,
Legend,
} from "recharts";
import { useQueryClient } from "@tanstack/react-query";
import { useMonthlyAnalytics, useTransactions, useUpdateTransaction } from "@/lib/hooks";
import { formatCategory, CATEGORIES } from "@/lib/categories";
import { CATEGORY_COLORS, CHART, TOOLTIP_STYLE } from "@/lib/category-colors";
function currentMonthStr(): string {
const now = new Date();
@@ -27,11 +29,6 @@ function prevMonth(m: string): string {
const d = new Date(year, month - 2, 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
function nextMonth(m: string): string {
const [year, month] = m.split("-").map(Number);
const d = new Date(year, month, 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
function formatMonth(m: string): string {
const [year, month] = m.split("-");
return new Date(Number(year), Number(month) - 1, 1).toLocaleString("default", { month: "long", year: "numeric" });
@@ -40,73 +37,21 @@ function formatShortMonth(m: string): string {
const [year, month] = m.split("-");
return new Date(Number(year), Number(month) - 1, 1).toLocaleString("default", { month: "short" });
}
function fmt(n: number): string { return `$${n.toFixed(0)}`; }
function fmt(n: number): string { return `$${Math.round(n).toLocaleString()}`; }
function fmtExact(n: number): string { return `$${n.toFixed(2)}`; }
function deltaColor(n: number): string {
if (n > 0) return "text-red-400";
if (n < 0) return "text-emerald-400";
return "";
}
const TOOLTIP_STYLE = { background: "#18181b", border: "1px solid #3f3f46", borderRadius: 8, fontSize: 12 };
const CATEGORY_COLORS: Record<string, string> = {
groceries: "#22c55e",
dining: "#f97316",
transport: "#06b6d4",
fuel: "#eab308",
shopping: "#ec4899",
utilities: "#8b5cf6",
entertainment: "#f43f5e",
travel: "#0ea5e9",
health: "#10b981",
insurance: "#64748b",
subscriptions: "#a78bfa",
cash_advance: "#dc2626",
government: "#78716c",
education: "#3b82f6",
rent: "#d97706",
transfers: "#6b7280",
income: "#34d399",
investment: "#818cf8",
personal_care: "#fb7185",
pets: "#86efac",
gifts: "#fcd34d",
charity: "#a3e635",
home_goods: "#67e8f9",
home_maintenance: "#c084fc",
other: "#71717a",
};
function fmtSigned(n: number): string { return `${n >= 0 ? "+" : "−"}$${Math.abs(n) >= 100 ? Math.round(Math.abs(n)).toLocaleString() : Math.abs(n).toFixed(0)}`; }
// ─── Tooltips ────────────────────────────────────────────────────────────────
function TrendTooltip({ active, payload, label }: { active?: boolean; payload?: { dataKey: string; value: number; stroke: string }[]; label?: string }) {
if (!active || !payload?.length) return null;
const items = payload.filter((p) => p.value > 0.01).sort((a, b) => b.value - a.value);
if (!items.length) return null;
return (
<div style={TOOLTIP_STYLE} className="p-2.5 text-xs min-w-40">
<p className="text-zinc-400 mb-2 font-medium">{label}</p>
{items.map((p) => (
<div key={p.dataKey} className="flex items-center gap-2 mb-0.5">
<span className="w-2 h-2 rounded-sm shrink-0" style={{ background: p.stroke }} />
<span className="text-zinc-400">{formatCategory(p.dataKey.replace("cat_", ""))}:</span>
<span className="text-zinc-100 tabular-nums ml-auto pl-2">{fmtExact(p.value)}</span>
</div>
))}
</div>
);
}
function ParetoTooltip({ active, payload }: { active?: boolean; payload?: { payload: { category: string; spent: number; pct: number; cumulative: number } }[] }) {
if (!active || !payload?.length) return null;
const d = payload[0].payload;
return (
<div style={TOOLTIP_STYLE} className="p-2.5 text-xs">
<p className="font-medium text-zinc-300 mb-1">{formatCategory(d.category)}</p>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Spend</span><span>{fmtExact(d.spent)}</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Share</span><span>{d.pct}%</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Cumulative</span><span>{d.cumulative}%</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Spend</span><span className="font-mono">{fmtExact(d.spent)}</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Share</span><span className="font-mono">{d.pct}%</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Cumulative</span><span className="font-mono">{d.cumulative}%</span></div>
</div>
);
}
@@ -120,14 +65,59 @@ function CumulativeTooltip({ active, payload, label }: { active?: boolean; paylo
<div key={p.dataKey} className="flex items-center gap-2 mb-0.5">
<span className="w-2 h-2 rounded-sm shrink-0" style={{ background: p.stroke }} />
<span className="text-zinc-400">{p.dataKey === "actual" ? "Actual" : "Typical pace"}:</span>
<span className="text-zinc-100 tabular-nums ml-auto pl-2">{fmtExact(p.value)}</span>
<span className="text-zinc-100 font-mono tabular-nums ml-auto pl-2">{fmtExact(p.value)}</span>
</div>
))}
</div>
);
}
// ─── CategoryPanel ────────────────────────────────────────────────────────────
// ─── Month spine ─────────────────────────────────────────────────────────────
// Twelve clickable columns, one per month, scaled to that month's spend.
// Doubles as period navigation and year-at-a-glance context.
function MonthSpine({
months,
totals,
selected,
onSelect,
}: {
months: string[]; // ascending
totals: Record<string, { spent: number }>;
selected: string;
onSelect: (m: string) => void;
}) {
const max = Math.max(...months.map((m) => totals[m]?.spent || 0), 1);
return (
<div className="flex items-end gap-1 sm:gap-1.5">
{months.map((m) => {
const spent = totals[m]?.spent || 0;
const h = Math.max(4, Math.round((spent / max) * 56));
const active = m === selected;
return (
<button
key={m}
onClick={() => onSelect(m)}
title={`${formatMonth(m)} — ${fmt(spent)}`}
className="group flex-1 flex flex-col items-center gap-1.5 min-w-0"
>
<span
style={{ height: h }}
className={`w-full max-w-9 rounded-t-sm transition-colors ${
active ? "bg-indigo-400" : "bg-zinc-700 group-hover:bg-zinc-600"
}`}
/>
<span className={`text-[10px] leading-none uppercase tracking-wide ${active ? "text-indigo-300" : "text-zinc-500 group-hover:text-zinc-400"}`}>
{formatShortMonth(m)}
</span>
</button>
);
})}
</div>
);
}
// ─── CategoryPanel (drill-down) ──────────────────────────────────────────────
function CategoryPanel({ category, selectedMonth }: { category: string; selectedMonth: string }) {
const qc = useQueryClient();
@@ -143,7 +133,7 @@ function CategoryPanel({ category, selectedMonth }: { category: string; selected
<tr>
<td colSpan={4} className="px-0 pb-2 bg-zinc-950/60 border-b border-zinc-800">
{isLoading ? (
<p className="text-xs text-zinc-500 px-6 py-2">Loading...</p>
<p className="text-xs text-zinc-500 px-6 py-2">Loading…</p>
) : txns.length === 0 ? (
<p className="text-xs text-zinc-600 px-6 py-2">No transactions</p>
) : (
@@ -159,9 +149,9 @@ function CategoryPanel({ category, selectedMonth }: { category: string; selected
<tbody>
{txns.map((tx) => (
<tr key={tx.id} className="border-t border-zinc-800/30 hover:bg-zinc-800/20">
<td className="px-6 py-1.5 text-zinc-500 tabular-nums">{tx.transaction_date.slice(5).replace("-", "/")}</td>
<td className="px-6 py-1.5 text-zinc-500 font-mono tabular-nums">{tx.transaction_date.slice(5).replace("-", "/")}</td>
<td className="px-2 py-1.5 text-zinc-300 max-w-xs truncate">{tx.effective_merchant || tx.description}</td>
<td className="px-2 py-1.5 text-right tabular-nums text-zinc-300">{fmtExact(Number(tx.amount))}</td>
<td className="px-2 py-1.5 text-right font-mono tabular-nums text-zinc-300">{fmtExact(Number(tx.amount))}</td>
<td className="px-4 py-1.5 text-right">
<select
className="bg-zinc-800 border border-zinc-700 rounded px-2 py-0.5 text-xs text-zinc-300 focus:outline-none focus:border-indigo-500 cursor-pointer"
@@ -192,7 +182,18 @@ function CategoryPanel({ category, selectedMonth }: { category: string; selected
export default function AnalyticsPage() {
const [selectedMonth, setSelectedMonth] = useState(currentMonthStr);
const [expandedCategory, setExpandedCategory] = useState<string | null>(null);
const { data: analytics, isLoading } = useMonthlyAnalytics(6);
const { data: analytics, isLoading } = useMonthlyAnalytics(12);
const months = useMemo(() => analytics ? [...analytics.months].reverse() : [], [analytics]);
// If the initial month has no data yet (e.g. the 1st of the month), land on
// the most recent month that does.
useEffect(() => {
if (months.length && !months.includes(selectedMonth)) {
setSelectedMonth(months[months.length - 1]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [months]);
// Cumulative chart: fetch this month's transactions
const smFrom = `${selectedMonth}-01`;
@@ -201,8 +202,6 @@ export default function AnalyticsPage() {
const smTo = `${smNextDate.getFullYear()}-${String(smNextDate.getMonth() + 1).padStart(2, "0")}-01`;
const { data: monthTxData } = useTransactions({ from: smFrom, to: smTo, limit: 1000 });
const months = useMemo(() => analytics ? [...analytics.months].reverse() : [], [analytics]);
// Category rows for selected month
const categoryRows = useMemo(() => {
if (!analytics) return [];
@@ -212,25 +211,37 @@ export default function AnalyticsPage() {
.sort((a, b) => b.spent - a.spent);
}, [analytics, selectedMonth]);
// Trend line data — top 8 categories by total 6-month spend
const trendData = useMemo(() => {
if (!analytics) return { data: [], categories: [] };
const categoryTotals = analytics.rows
.map((r) => ({ category: r.category, total: months.reduce((s, m) => s + (r.spent[m] || 0), 0) }))
// Small multiples — top 8 categories by 12-month total
const sparkData = useMemo(() => {
if (!analytics) return [];
return analytics.rows
.map((r) => ({
category: r.category,
total: months.reduce((s, m) => s + (r.spent[m] || 0), 0),
thisMonth: r.spent[selectedMonth] || 0,
delta: (r.spent[selectedMonth] || 0) - (r.spent[prevMonth(selectedMonth)] || 0),
series: months.map((m) => ({ month: m, v: r.spent[m] || 0 })),
}))
.sort((a, b) => b.total - a.total)
.slice(0, 8)
.map((r) => r.category);
.slice(0, 8);
}, [analytics, months, selectedMonth]);
const data = months.map((m) => {
const entry: Record<string, unknown> = { month: m, label: formatShortMonth(m) };
for (const cat of categoryTotals) {
const row = analytics.rows.find((r) => r.category === cat);
entry[`cat_${cat}`] = row?.spent[m] || 0;
}
return entry;
});
return { data, categories: categoryTotals };
}, [analytics, months]);
// Top movers vs previous month
const movers = useMemo(() => {
if (!analytics) return [];
const pm = prevMonth(selectedMonth);
if (!months.includes(pm)) return [];
return analytics.rows
.map((r) => ({
category: r.category,
delta: (r.spent[selectedMonth] || 0) - (r.spent[pm] || 0),
now: r.spent[selectedMonth] || 0,
before: r.spent[pm] || 0,
}))
.filter((r) => Math.abs(r.delta) >= 1)
.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta))
.slice(0, 6);
}, [analytics, months, selectedMonth]);
// Pareto chart data
const paretoData = useMemo(() => {
@@ -254,16 +265,16 @@ export default function AnalyticsPage() {
const today = new Date();
const lastDay = isCurrentMonth ? today.getDate() : daysInMonth;
// Daily spend from transactions
const daily: Record<number, number> = {};
(monthTxData?.data ?? [])
.filter((tx) => tx.transaction_type === "debit" && !["transfers", "investment"].includes(tx.effective_category))
.filter((tx) => tx.transaction_type === "debit" &&
!["transfers", "investment"].includes(tx.effective_category) &&
!tx.tags?.some((t: any) => (typeof t === "string" ? t : t.name) === "family"))
.forEach((tx) => {
const day = new Date(tx.transaction_date).getDate();
daily[day] = (daily[day] || 0) + Number(tx.amount_aud ?? tx.amount);
});
// Typical pace: avg of prior months (straight-line ramp)
const priorMonths = analytics?.months.filter((m) => m !== selectedMonth) ?? [];
const priorAvg = priorMonths.length > 0
? priorMonths.reduce((s, m) => s + (analytics?.totals[m]?.spent || 0), 0) / priorMonths.length
@@ -283,131 +294,151 @@ export default function AnalyticsPage() {
if (isLoading || !analytics) {
return (
<div className="space-y-6">
<h2 className="text-xl font-semibold">Analytics</h2>
<p className="text-zinc-500 text-sm">Loading...</p>
<div className="space-y-6 max-w-5xl">
<h2 className="text-2xl font-display">Analytics</h2>
<p className="text-zinc-500 text-sm">Loading…</p>
</div>
);
}
const totals = analytics.totals[selectedMonth] ?? { spent: 0, income: 0, investments: 0, net: 0 };
const lastTotals = analytics.totals[prevMonth(selectedMonth)] ?? { spent: 0, income: 0, investments: 0, net: 0 };
const spentDelta = totals.spent - lastTotals.spent;
const largestCategory = categoryRows[0];
const hasIncome = months.some((m) => (analytics.totals[m]?.income || 0) > 0);
const hasInvestments = months.some((m) => (analytics.totals[m]?.investments || 0) > 0);
// Pareto: find where cumulative crosses 80%
// Hero delta vs the average of the other months that have data
const otherMonths = months.filter((m) => m !== selectedMonth && (analytics.totals[m]?.spent || 0) > 0);
const avgSpend = otherMonths.length
? otherMonths.reduce((s, m) => s + (analytics.totals[m]?.spent || 0), 0) / otherMonths.length
: 0;
const avgDeltaPct = avgSpend > 0 ? Math.round(((totals.spent - avgSpend) / avgSpend) * 100) : 0;
const heroSentence =
avgSpend === 0 ? "" :
Math.abs(avgDeltaPct) <= 3 ? `in line with your ${otherMonths.length}-month average` :
`${Math.abs(avgDeltaPct)}% ${avgDeltaPct > 0 ? "above" : "below"} your ${otherMonths.length}-month average of ${fmt(avgSpend)}`;
const pareto80idx = paretoData.findIndex((r) => r.cumulative >= 80);
const tableMonths = analytics.months.slice(0, 6); // newest-first, last 6
const maxMoverDelta = Math.max(...movers.map((m) => Math.abs(m.delta)), 1);
return (
<div className="space-y-6">
<div className="space-y-6 max-w-5xl">
{/* Header + month selector */}
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold">Analytics</h2>
<div className="flex items-center gap-3">
<button onClick={() => setSelectedMonth(prevMonth(selectedMonth))} className="p-2 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-sm leading-none">‹</button>
<span className="text-sm font-medium min-w-36 text-center">{formatMonth(selectedMonth)}</span>
<button onClick={() => setSelectedMonth(nextMonth(selectedMonth))} className="p-2 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-sm leading-none">›</button>
{/* ── Hero + month spine ── */}
<div className="border-b border-zinc-800 pb-5">
<p className="text-[11px] uppercase tracking-[0.18em] text-zinc-500 mb-2">Ledger · {formatMonth(selectedMonth)}</p>
<div className="flex flex-wrap items-end justify-between gap-x-8 gap-y-4">
<div>
<p className="font-display text-5xl text-zinc-50 leading-none">
{fmt(totals.spent)}
</p>
{heroSentence && (
<p className="text-sm text-zinc-400 mt-2">
<span className={avgDeltaPct > 3 ? "text-indigo-300" : avgDeltaPct < -3 ? "text-emerald-400" : "text-zinc-400"}>
{heroSentence}
</span>
</p>
)}
</div>
<div className="w-full sm:w-auto sm:min-w-80 sm:flex-1 sm:max-w-md">
<MonthSpine months={months} totals={analytics.totals} selected={selectedMonth} onSelect={(m) => { setSelectedMonth(m); setExpandedCategory(null); }} />
</div>
</div>
</div>
{/* Summary cards */}
<div className={`grid gap-4 ${hasIncome ? "grid-cols-2 sm:grid-cols-4" : "grid-cols-3"}`}>
{hasIncome && (
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
<p className="text-xs text-zinc-500 mb-1">Income</p>
<p className="text-2xl font-semibold text-emerald-400">{fmtExact(totals.income)}</p>
<p className="text-xs text-zinc-500 mt-1">received</p>
</div>
)}
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
<p className="text-xs text-zinc-500 mb-1">Expenses</p>
<p className="text-2xl font-semibold">{fmtExact(totals.spent)}</p>
<p className={`text-xs mt-1 ${deltaColor(spentDelta)}`}>
{spentDelta === 0 || lastTotals.spent === 0
? <span className="text-zinc-500">split-adjusted</span>
: `${spentDelta > 0 ? "+" : ""}${fmtExact(spentDelta)} vs ${formatShortMonth(prevMonth(selectedMonth))}`}
</p>
{/* ── Cashflow strip ── */}
<div className="bg-zinc-900 border border-zinc-800 rounded-xl grid grid-cols-2 sm:grid-cols-4 divide-x divide-y sm:divide-y-0 divide-zinc-800 overflow-hidden">
<div className="px-4 py-3.5">
<p className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">Income</p>
<p className={`text-xl font-mono tabular-nums ${hasIncome ? "text-emerald-400" : "text-zinc-600"}`}>{hasIncome ? fmt(totals.income) : "—"}</p>
</div>
{(hasInvestments || totals.investments > 0) && (
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
<p className="text-xs text-zinc-500 mb-1">Invested</p>
<p className="text-2xl font-semibold text-indigo-400">{fmtExact(totals.investments)}</p>
<p className="text-xs text-zinc-500 mt-1">shares / ETFs</p>
</div>
)}
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
<p className="text-xs text-zinc-500 mb-1">{hasIncome ? "Net Cash" : "Largest Category"}</p>
<div className="px-4 py-3.5">
<p className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">Expenses</p>
<p className="text-xl font-mono tabular-nums text-zinc-100">{fmt(totals.spent)}</p>
</div>
<div className="px-4 py-3.5">
<p className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">Invested</p>
<p className={`text-xl font-mono tabular-nums ${hasInvestments ? "text-indigo-300" : "text-zinc-600"}`}>{hasInvestments ? fmt(totals.investments) : "—"}</p>
</div>
<div className="px-4 py-3.5">
<p className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">Net cash</p>
{hasIncome ? (
<>
<p className={`text-2xl font-semibold ${totals.net >= 0 ? "text-emerald-400" : "text-red-400"}`}>
{totals.net >= 0 ? "+" : ""}{fmtExact(totals.net)}
</p>
<p className="text-xs text-zinc-500 mt-1">income − expenses − invested</p>
</>
) : largestCategory ? (
<>
<p className="text-2xl font-semibold">{fmtExact(largestCategory.spent)}</p>
<p className="text-xs text-zinc-400 mt-1">{formatCategory(largestCategory.category)}</p>
</>
<p className={`text-xl font-mono tabular-nums ${totals.net >= 0 ? "text-emerald-400" : "text-red-400"}`}>{totals.net >= 0 ? "+" : ""}{fmt(totals.net)}</p>
) : (
<p className="text-2xl font-semibold text-zinc-600">—</p>
<p className="text-xl font-mono tabular-nums text-zinc-600">—</p>
)}
</div>
</div>
{/* 1. Category trend lines */}
{trendData.categories.length > 0 && (
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
<h3 className="text-sm font-medium mb-4">Category Trends — 6 Months</h3>
<ResponsiveContainer width="100%" height={240}>
<LineChart
data={trendData.data}
margin={{ top: 4, right: 8, bottom: 0, left: 8 }}
onClick={(d) => {
const month = (d as any)?.activePayload?.[0]?.payload?.month as string | undefined;
if (month) setSelectedMonth(month);
}}
style={{ cursor: "pointer" }}
>
<XAxis dataKey="label" tick={{ fill: "#71717a", fontSize: 12 }} axisLine={false} tickLine={false} />
<YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${v}`} width={52} />
<Tooltip content={<TrendTooltip />} cursor={{ stroke: "rgba(255,255,255,0.08)", strokeWidth: 1 }} />
{trendData.categories.map((cat) => (
<Line
key={cat}
dataKey={`cat_${cat}`}
name={cat}
stroke={CATEGORY_COLORS[cat] || "#71717a"}
strokeWidth={selectedMonth && trendData.data.some((d) => (d as any).month === selectedMonth) ? 2 : 2}
dot={{ fill: CATEGORY_COLORS[cat] || "#71717a", r: 3 }}
activeDot={{ r: 5 }}
connectNulls
/>
))}
</LineChart>
</ResponsiveContainer>
<div className="flex flex-wrap gap-x-3 gap-y-1 mt-3 pt-3 border-t border-zinc-800">
{trendData.categories.map((cat) => (
<span key={cat} className="flex items-center gap-1 text-xs text-zinc-500">
<span className="w-2 h-2 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[cat] || "#71717a" }} />
{formatCategory(cat)}
</span>
{/* ── Top movers vs last month ── */}
{movers.length > 0 && (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-4">
<h3 className="text-sm font-medium mb-1">What changed</h3>
<p className="text-xs text-zinc-500 mb-4">Biggest category moves vs {formatShortMonth(prevMonth(selectedMonth))}</p>
<div className="grid sm:grid-cols-2 gap-x-8 gap-y-2.5">
{movers.map((m) => (
<div key={m.category} className="flex items-center gap-3">
<span className="w-2 h-2 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[m.category] || CHART.axis }} />
<span className="text-sm text-zinc-300 w-32 truncate shrink-0">{formatCategory(m.category)}</span>
<div className="flex-1 h-1.5 rounded-full bg-zinc-800 overflow-hidden">
<div
className={`h-full rounded-full ${m.delta > 0 ? "bg-indigo-400" : "bg-emerald-500"}`}
style={{ width: `${Math.max(6, Math.round((Math.abs(m.delta) / maxMoverDelta) * 100))}%` }}
/>
</div>
<span className={`text-xs font-mono tabular-nums w-16 text-right ${m.delta > 0 ? "text-indigo-300" : "text-emerald-400"}`}>
{fmtSigned(m.delta)}
</span>
</div>
))}
{analytics.rows.length > 8 && (
<span className="text-xs text-zinc-600">+ {analytics.rows.length - 8} more in table below</span>
)}
</div>
</div>
)}
{/* 2. Pareto chart */}
{/* ── Category small multiples ── */}
{sparkData.length > 0 && (
<div>
<div className="flex items-baseline justify-between mb-3">
<h3 className="text-sm font-medium">Category trends</h3>
<span className="text-xs text-zinc-500">12 months · top {sparkData.length} by total spend</span>
</div>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
{sparkData.map((s) => (
<div key={s.category} className="bg-zinc-900 border border-zinc-800 rounded-xl px-3.5 pt-3 pb-1.5">
<div className="flex items-center justify-between gap-2 mb-0.5">
<span className="flex items-center gap-1.5 text-xs text-zinc-400 truncate">
<span className="w-1.5 h-1.5 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[s.category] || CHART.axis }} />
{formatCategory(s.category)}
</span>
{Math.abs(s.delta) >= 1 && (
<span className={`text-[10px] font-mono tabular-nums shrink-0 ${s.delta > 0 ? "text-indigo-300" : "text-emerald-400"}`}>{fmtSigned(s.delta)}</span>
)}
</div>
<p className="text-lg font-mono tabular-nums text-zinc-100 mb-1">{fmt(s.thisMonth)}</p>
<div className="h-10 -mx-1">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={s.series} margin={{ top: 2, right: 0, bottom: 0, left: 0 }}>
<Area
dataKey="v"
stroke={CATEGORY_COLORS[s.category] || CHART.axis}
strokeWidth={1.5}
fill={CATEGORY_COLORS[s.category] || CHART.axis}
fillOpacity={0.12}
isAnimationActive={false}
/>
</AreaChart>
</ResponsiveContainer>
</div>
</div>
))}
</div>
</div>
)}
{/* ── Pareto ── */}
{paretoData.length > 0 && (
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-sm font-medium">Spend Concentration — {formatMonth(selectedMonth)}</h3>
<h3 className="text-sm font-medium">Spend concentration</h3>
{pareto80idx >= 0 && (
<span className="text-xs text-zinc-500">
Top {pareto80idx + 1} categor{pareto80idx === 0 ? "y" : "ies"} = 80% of spend
@@ -418,14 +449,14 @@ export default function AnalyticsPage() {
<ComposedChart data={paretoData} margin={{ top: 4, right: 48, bottom: 0, left: 8 }}>
<XAxis
dataKey="category"
tick={{ fill: "#71717a", fontSize: 11 }}
tick={{ fill: CHART.axis, fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={formatCategory}
/>
<YAxis
yAxisId="left"
tick={{ fill: "#71717a", fontSize: 11 }}
tick={{ fill: CHART.axis, fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={(v) => `$${v}`}
@@ -434,66 +465,66 @@ export default function AnalyticsPage() {
<YAxis
yAxisId="right"
orientation="right"
tick={{ fill: "#71717a", fontSize: 11 }}
tick={{ fill: CHART.axis, fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={(v) => `${v}%`}
domain={[0, 100]}
width={36}
/>
<Tooltip content={<ParetoTooltip />} cursor={{ fill: "rgba(255,255,255,0.04)" }} />
<ReferenceLine yAxisId="right" y={80} stroke="#52525b" strokeDasharray="4 2" label={{ value: "80%", fill: "#71717a", fontSize: 10, position: "right" }} />
<Tooltip content={<ParetoTooltip />} cursor={{ fill: "rgba(232,224,204,0.04)" }} />
<ReferenceLine yAxisId="right" y={80} stroke={CHART.faint} strokeDasharray="4 2" label={{ value: "80%", fill: CHART.axis, fontSize: 10, position: "right" }} />
<Bar yAxisId="left" dataKey="spent" radius={[3, 3, 0, 0]} maxBarSize={40}>
{paretoData.map((entry, i) => (
<Cell
key={entry.category}
fill={i <= pareto80idx ? (CATEGORY_COLORS[entry.category] || "#6366f1") : "#3f3f46"}
fill={i <= pareto80idx ? (CATEGORY_COLORS[entry.category] || CHART.accent) : CHART.dim}
/>
))}
</Bar>
<Line
yAxisId="right"
dataKey="cumulative"
stroke="#fbbf24"
stroke={CHART.accentSoft}
strokeWidth={2}
dot={{ fill: "#fbbf24", r: 3 }}
dot={{ fill: CHART.accentSoft, r: 3 }}
activeDot={{ r: 5 }}
/>
</ComposedChart>
</ResponsiveContainer>
<div className="flex items-center gap-4 mt-2 justify-end">
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-0.5 bg-amber-400 inline-block" />Cumulative %</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-2 rounded-sm bg-zinc-600 inline-block" />Below 80% threshold</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-0.5 inline-block" style={{ background: CHART.accentSoft }} />Cumulative %</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-2 rounded-sm inline-block" style={{ background: CHART.dim }} />Beyond 80%</span>
</div>
</div>
)}
{/* 3. Cumulative spend this month */}
<div className="bg-zinc-900 border border-zinc-700 rounded-xl p-4">
{/* ── Cumulative pace ── */}
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-sm font-medium">Cumulative Spend — {formatMonth(selectedMonth)}</h3>
<span className="text-xs text-zinc-500">vs avg monthly pace</span>
<h3 className="text-sm font-medium">Spend pace</h3>
<span className="text-xs text-zinc-500">cumulative through the month, vs typical</span>
</div>
<ResponsiveContainer width="100%" height={180}>
<LineChart data={cumulativeData} margin={{ top: 4, right: 8, bottom: 0, left: 8 }}>
<XAxis dataKey="day" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `${v}`} interval={4} />
<YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(1)}k`} width={44} />
<Tooltip content={<CumulativeTooltip />} cursor={{ stroke: "rgba(255,255,255,0.08)", strokeWidth: 1 }} />
<Line dataKey="typical" stroke="#3f3f46" strokeWidth={1.5} strokeDasharray="4 3" dot={false} name="typical" />
<Line dataKey="actual" stroke="#6366f1" strokeWidth={2} dot={false} activeDot={{ r: 4 }} connectNulls={false} name="actual" />
<XAxis dataKey="day" tick={{ fill: CHART.axis, fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `${v}`} interval={4} />
<YAxis tick={{ fill: CHART.axis, fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(1)}k`} width={44} />
<Tooltip content={<CumulativeTooltip />} cursor={{ stroke: "rgba(232,224,204,0.08)", strokeWidth: 1 }} />
<Line dataKey="typical" stroke={CHART.faint} strokeWidth={1.5} strokeDasharray="4 3" dot={false} name="typical" />
<Line dataKey="actual" stroke={CHART.accent} strokeWidth={2} dot={false} activeDot={{ r: 4 }} connectNulls={false} name="actual" />
</LineChart>
</ResponsiveContainer>
<div className="flex items-center gap-4 mt-2 justify-end">
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-4 h-0.5 bg-indigo-500 inline-block" />This month</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-4 h-0.5 bg-zinc-600 inline-block" style={{ borderTop: "1px dashed #52525b", display: "inline-block" }} />Typical pace</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-4 h-0.5 inline-block" style={{ background: CHART.accent }} />This month</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-4 h-0.5 inline-block border-t border-dashed" style={{ borderColor: CHART.faint }} />Typical pace</span>
</div>
</div>
{/* Category breakdown table — expandable rows */}
{/* ── Category breakdown table — expandable rows ── */}
{categoryRows.length > 0 && (
<div className="bg-zinc-900 border border-zinc-700 rounded-xl overflow-hidden">
<div className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
<div className="px-4 py-3 border-b border-zinc-800">
<h3 className="text-sm font-medium">Spending Breakdown — {formatMonth(selectedMonth)}</h3>
<h3 className="text-sm font-medium">Where it went — {formatMonth(selectedMonth)}</h3>
</div>
<table className="w-full text-sm">
<thead>
@@ -501,7 +532,7 @@ export default function AnalyticsPage() {
<th className="text-left px-4 py-2 text-xs text-zinc-500 font-medium">Category</th>
<th className="text-right px-4 py-2 text-xs text-zinc-500 font-medium">Spent</th>
<th className="text-right px-4 py-2 text-xs text-zinc-500 font-medium"># Txns</th>
<th className="text-right px-4 py-2 text-xs text-zinc-500 font-medium">% of Total</th>
<th className="text-right px-4 py-2 text-xs text-zinc-500 font-medium">% of total</th>
</tr>
</thead>
<tbody>
@@ -515,14 +546,14 @@ export default function AnalyticsPage() {
>
<td className="px-4 py-2.5 font-medium">
<span className="flex items-center gap-2">
<span className="w-2 h-2 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[category] || "#71717a" }} />
<span className="w-2 h-2 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[category] || CHART.axis }} />
{formatCategory(category)}
<span className="text-zinc-600 text-xs ml-1">{isExpanded ? "▲" : "▼"}</span>
</span>
</td>
<td className="px-4 py-2.5 text-right tabular-nums">{fmtExact(spent)}</td>
<td className="px-4 py-2.5 text-right text-zinc-400">{txCount}</td>
<td className="px-4 py-2.5 text-right text-zinc-400 tabular-nums">
<td className="px-4 py-2.5 text-right font-mono tabular-nums">{fmtExact(spent)}</td>
<td className="px-4 py-2.5 text-right text-zinc-400 font-mono tabular-nums">{txCount}</td>
<td className="px-4 py-2.5 text-right text-zinc-400 font-mono tabular-nums">
{totals.spent > 0 ? ((spent / totals.spent) * 100).toFixed(1) : "0.0"}%
</td>
</tr>
@@ -535,19 +566,19 @@ export default function AnalyticsPage() {
</div>
)}
{/* 6-month trend table */}
{analytics.months.length > 0 && (
{/* ── 6-month ledger table (heat-tinted) ── */}
{tableMonths.length > 0 && (
<div>
<h3 className="text-sm font-semibold text-zinc-400 mb-3">6-Month Trend</h3>
<div className="overflow-x-auto rounded-xl border border-zinc-700">
<h3 className="text-sm font-medium text-zinc-400 mb-3">Six-month ledger</h3>
<div className="overflow-x-auto rounded-xl border border-zinc-800">
<table className="w-full text-xs border-collapse">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900">
<th className="text-left px-3 py-2 text-zinc-500 font-medium sticky left-0 bg-zinc-900 min-w-32">Category</th>
{analytics.months.map((m) => (
{tableMonths.map((m) => (
<th
key={m}
className={`text-right px-3 py-2 font-medium whitespace-nowrap cursor-pointer hover:text-zinc-300 ${m === selectedMonth ? "text-indigo-400" : "text-zinc-500"}`}
className={`text-right px-3 py-2 font-medium whitespace-nowrap cursor-pointer hover:text-zinc-300 ${m === selectedMonth ? "text-indigo-300" : "text-zinc-500"}`}
onClick={() => setSelectedMonth(m)}
>
{formatShortMonth(m)}
@@ -556,31 +587,39 @@ export default function AnalyticsPage() {
</tr>
</thead>
<tbody>
{analytics.rows.map((row) => (
<tr key={row.category} className="border-b border-zinc-800/40 hover:bg-zinc-900/30">
<td className="px-3 py-2 font-medium sticky left-0 bg-zinc-950">
<span className="flex items-center gap-1.5">
<span className="w-1.5 h-1.5 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[row.category] || "#71717a" }} />
{formatCategory(row.category)}
</span>
</td>
{analytics.months.map((m) => {
const spent = row.spent[m];
return (
<td key={m} className={`px-3 py-2 text-right tabular-nums ${spent === undefined ? "text-zinc-700" : "text-zinc-300"} ${m === selectedMonth ? "bg-zinc-800/30" : ""}`}>
{spent !== undefined ? fmt(spent) : "—"}
</td>
);
})}
</tr>
))}
{analytics.rows.map((row) => {
const rowMax = Math.max(...tableMonths.map((m) => row.spent[m] || 0), 1);
return (
<tr key={row.category} className="border-b border-zinc-800/40 hover:bg-zinc-900/30">
<td className="px-3 py-2 font-medium sticky left-0 bg-zinc-950">
<span className="flex items-center gap-1.5">
<span className="w-1.5 h-1.5 rounded-sm shrink-0" style={{ background: CATEGORY_COLORS[row.category] || CHART.axis }} />
{formatCategory(row.category)}
</span>
</td>
{tableMonths.map((m) => {
const spent = row.spent[m];
const heat = spent !== undefined ? (spent / rowMax) * 0.28 : 0;
return (
<td
key={m}
className={`px-3 py-2 text-right font-mono tabular-nums ${spent === undefined ? "text-zinc-700" : "text-zinc-300"}`}
style={heat > 0.02 ? { background: `rgba(188, 111, 48, ${heat.toFixed(3)})` } : undefined}
>
{spent !== undefined ? fmt(spent) : "—"}
</td>
);
})}
</tr>
);
})}
{hasIncome && (
<tr className="border-b border-zinc-800/40">
<td className="px-3 py-2 font-medium sticky left-0 bg-zinc-950 text-emerald-600">Income</td>
{analytics.months.map((m) => {
{tableMonths.map((m) => {
const inc = analytics.income[m];
return (
<td key={m} className={`px-3 py-2 text-right tabular-nums text-emerald-500 ${m === selectedMonth ? "bg-zinc-800/30" : ""}`}>
<td key={m} className="px-3 py-2 text-right font-mono tabular-nums text-emerald-500">
{inc ? fmt(inc) : "—"}
</td>
);
@@ -589,11 +628,11 @@ export default function AnalyticsPage() {
)}
{hasInvestments && (
<tr className="border-b border-zinc-800/40">
<td className="px-3 py-2 font-medium sticky left-0 bg-zinc-950 text-indigo-500">Invested</td>
{analytics.months.map((m) => {
<td className="px-3 py-2 font-medium sticky left-0 bg-zinc-950 text-indigo-400">Invested</td>
{tableMonths.map((m) => {
const inv = analytics.investments[m];
return (
<td key={m} className={`px-3 py-2 text-right tabular-nums text-indigo-400 ${m === selectedMonth ? "bg-zinc-800/30" : ""}`}>
<td key={m} className="px-3 py-2 text-right font-mono tabular-nums text-indigo-300">
{inv ? fmt(inv) : "—"}
</td>
);
@@ -602,10 +641,10 @@ export default function AnalyticsPage() {
)}
<tr className="border-t-2 border-zinc-700 font-semibold bg-zinc-900/50">
<td className="px-3 py-2 sticky left-0 bg-zinc-900">Expenses</td>
{analytics.months.map((m) => {
{tableMonths.map((m) => {
const t = analytics.totals[m];
return (
<td key={m} className={`px-3 py-2 text-right tabular-nums ${m === selectedMonth ? "bg-zinc-800/30 text-indigo-300" : ""}`}>
<td key={m} className={`px-3 py-2 text-right font-mono tabular-nums ${m === selectedMonth ? "text-indigo-300" : ""}`}>
{fmt(t?.spent || 0)}
</td>
);
@@ -613,12 +652,12 @@ export default function AnalyticsPage() {
</tr>
{hasIncome && (
<tr className="font-semibold bg-zinc-900/50">
<td className="px-3 py-2 sticky left-0 bg-zinc-900">Net Cash</td>
{analytics.months.map((m) => {
<td className="px-3 py-2 sticky left-0 bg-zinc-900">Net cash</td>
{tableMonths.map((m) => {
const t = analytics.totals[m];
const net = t?.net || 0;
return (
<td key={m} className={`px-3 py-2 text-right tabular-nums ${net >= 0 ? "text-emerald-400" : "text-red-400"} ${m === selectedMonth ? "bg-zinc-800/30" : ""}`}>
<td key={m} className={`px-3 py-2 text-right font-mono tabular-nums ${net >= 0 ? "text-emerald-400" : "text-red-400"}`}>
{net >= 0 ? "+" : ""}{fmt(net)}
</td>
);
+49 -1
View File
@@ -1,6 +1,54 @@
@import "tailwindcss";
@theme inline {
/*
* Ink & copper ledger theme.
*
* The whole app is written against Tailwind's zinc (neutrals) and indigo
* (accent) scales, so the retheme happens here: zinc is remapped to warm
* ink/paper tones and indigo to copper. Pages therefore inherit the palette
* without per-page edits; chart hexes live in src/lib/category-colors.ts.
*/
@theme {
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--font-display: var(--font-fraunces), Georgia, serif;
/* Ink / paper neutrals (replaces zinc) */
--color-zinc-950: #0f0d0a;
--color-zinc-900: #171410;
--color-zinc-800: #242019;
--color-zinc-700: #332d23;
--color-zinc-600: #4d4536;
--color-zinc-500: #6e644f;
--color-zinc-400: #94896f;
--color-zinc-300: #b3a88e;
--color-zinc-200: #d1c7af;
--color-zinc-100: #e8e0cc;
--color-zinc-50: #f3edde;
/* Copper accent (replaces indigo) */
--color-indigo-950: #2a1708;
--color-indigo-900: #3e2410;
--color-indigo-800: #5c3517;
--color-indigo-700: #7c4820;
--color-indigo-600: #9c5b28;
--color-indigo-500: #bc6f30;
--color-indigo-400: #d28a47;
--color-indigo-300: #e3a968;
--color-indigo-200: #efc795;
--color-indigo-100: #f7e2c4;
}
::selection {
background: #bc6f30;
color: #0f0d0a;
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
+53 -41
View File
@@ -6,6 +6,7 @@ import {
} from "recharts";
import { useMonthlyAnalytics, useSubscriptions, useFees, useTransactions, useUpdateTransaction } from "@/lib/hooks";
import { CATEGORIES, REGULAR_CATEGORIES, formatCategory } from "@/lib/categories";
import { CHART, TOOLTIP_STYLE } from "@/lib/category-colors";
const SPEND_TYPES = new Set(["debit", "fee", "interest"]);
@@ -50,16 +51,16 @@ function Section({ title, children }: { title: string; children: React.ReactNode
}
// ─── Custom tooltip ──────────────────────────────────────────────────
function RegularTooltip({ active, payload, label }: any) {
function RegularTooltip({ active, payload, label }: { active?: boolean; payload?: { dataKey: string; value: number }[]; label?: string }) {
if (!active || !payload?.length) return null;
const regular = payload.find((p: any) => p.dataKey === "regular")?.value ?? 0;
const occasional = payload.find((p: any) => p.dataKey === "occasional")?.value ?? 0;
const regular = payload.find((p) => p.dataKey === "regular")?.value ?? 0;
const occasional = payload.find((p) => p.dataKey === "occasional")?.value ?? 0;
return (
<div className="bg-zinc-900 border border-zinc-700 rounded px-3 py-2 text-xs space-y-1">
<div style={TOOLTIP_STYLE} className="px-3 py-2 text-xs space-y-1">
<div className="font-medium text-zinc-300 mb-1">{label}</div>
<div className="flex justify-between gap-4"><span className="text-indigo-400">Regular</span><span>{fmt(regular)}</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Occasional</span><span>{fmt(occasional)}</span></div>
<div className="flex justify-between gap-4 border-t border-zinc-700 pt-1"><span className="text-zinc-500">Total</span><span>{fmt(regular + occasional)}</span></div>
<div className="flex justify-between gap-4"><span className="text-indigo-300">Regular</span><span className="font-mono">{fmt(regular)}</span></div>
<div className="flex justify-between gap-4"><span className="text-zinc-400">Occasional</span><span className="font-mono">{fmt(occasional)}</span></div>
<div className="flex justify-between gap-4 border-t border-zinc-700 pt-1"><span className="text-zinc-500">Total</span><span className="font-mono">{fmt(regular + occasional)}</span></div>
</div>
);
}
@@ -99,6 +100,7 @@ function DrillDownRow({
<tr className="border-b border-zinc-800">
<th className="text-left px-6 py-2 text-zinc-600 font-medium">Date</th>
<th className="text-left px-4 py-2 text-zinc-600 font-medium">Merchant</th>
<th className="text-right px-4 py-2 text-zinc-600 font-medium">Total</th>
<th className="text-right px-4 py-2 text-zinc-600 font-medium">My share</th>
<th className="text-left px-4 py-2 text-zinc-600 font-medium">Category</th>
<th className="text-right px-4 py-2 text-zinc-600 font-medium">% mine</th>
@@ -106,8 +108,14 @@ function DrillDownRow({
</thead>
<tbody>
{txns.map((t) => {
const sharePct = t.my_share_percent ?? 100;
const effectiveAmt = t.amount * sharePct / 100;
// Share is resolved server-side (see getTransactions) so this
// matches the category total being drilled into. The old
// `my_share_percent ?? 100` missed transaction_splits rows
// entirely and assumed 100% when a transaction was allocated
// wholly to someone else.
const sharePct = Number(t.my_share_pct ?? 100);
const grossAmt = Number(t.amount_aud ?? t.amount);
const effectiveAmt = Number(t.my_amount ?? grossAmt);
const isDebit = SPEND_TYPES.has(t.transaction_type);
return (
<tr key={t.id} className="border-b border-zinc-800/30 hover:bg-zinc-900/30">
@@ -115,10 +123,13 @@ function DrillDownRow({
{new Date(t.transaction_date).toLocaleDateString("en-AU", { day: "2-digit", month: "short" })}
</td>
<td className="px-4 py-2 text-zinc-300">{t.merchant_name || t.description}</td>
<td className="px-4 py-2 text-right tabular-nums text-zinc-500">
{fmtExact(grossAmt)}
</td>
<td className={`px-4 py-2 text-right tabular-nums ${isDebit ? "text-zinc-200" : "text-green-400"}`}>
{fmtTx(effectiveAmt, t.transaction_type)}
{sharePct < 100 && (
<span className="text-zinc-600 ml-1 line-through">{fmtExact(t.amount)}</span>
<span className="text-zinc-600 ml-1">({sharePct}%)</span>
)}
</td>
<td className="px-4 py-2">
@@ -185,8 +196,8 @@ function MonthlyBreakdown({ analytics }: { analytics: NonNullable<ReturnType<typ
.sort((a, b) => b.amount - a.amount);
}, [analytics.rows, selectedMonth]);
const regularRows = categoryData.filter((r) => REGULAR_CATEGORIES.has(r.category as any));
const occasionalRows = categoryData.filter((r) => !REGULAR_CATEGORIES.has(r.category as any));
const regularRows = categoryData.filter((r) => (REGULAR_CATEGORIES as Set<string>).has(r.category));
const occasionalRows = categoryData.filter((r) => !(REGULAR_CATEGORIES as Set<string>).has(r.category));
const regularTotal = regularRows.reduce((s, r) => s + r.amount, 0);
const occasionalTotal = occasionalRows.reduce((s, r) => s + r.amount, 0);
@@ -243,7 +254,7 @@ function MonthlyBreakdown({ analytics }: { analytics: NonNullable<ReturnType<typ
))}
</div>
<div className="border border-zinc-700 rounded-xl overflow-hidden">
<div className="border border-zinc-800 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900">
@@ -297,7 +308,7 @@ export default function InsightsPage() {
let occasional = 0;
for (const row of analytics.rows) {
const spend = Number(row.spent[month] ?? 0);
if (REGULAR_CATEGORIES.has(row.category as any)) regular += spend;
if ((REGULAR_CATEGORIES as Set<string>).has(row.category)) regular += spend;
else occasional += spend;
}
return {
@@ -321,46 +332,47 @@ export default function InsightsPage() {
return (
<div className="max-w-4xl">
<h2 className="text-xl font-semibold mb-6">Insights</h2>
<p className="text-[11px] uppercase tracking-[0.18em] text-zinc-500 mb-1">Ledger · patterns</p>
<h2 className="text-2xl font-display mb-6">Insights</h2>
{/* ── 1. Regular vs Occasional ── */}
<Section title="Regular vs Occasional Spend">
<div className="grid grid-cols-3 gap-3 mb-4">
<div className="bg-zinc-900 border border-zinc-800 rounded-lg px-4 py-3">
<div className="text-xs text-zinc-500 mb-1">This month — regular spend</div>
<div className="text-xl font-semibold text-indigo-400">{fmt(latestRegular)}</div>
<Section title="Regular vs occasional spend">
<div className="bg-zinc-900 border border-zinc-800 rounded-xl grid grid-cols-3 divide-x divide-zinc-800 overflow-hidden mb-4">
<div className="px-4 py-3.5">
<div className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">This month · regular</div>
<div className="text-xl font-mono tabular-nums text-indigo-300">{fmt(latestRegular)}</div>
</div>
<div className="bg-zinc-900 border border-zinc-800 rounded-lg px-4 py-3">
<div className="text-xs text-zinc-500 mb-1">12-month avg regular</div>
<div className="text-xl font-semibold text-zinc-200">{fmt(avgRegular)}</div>
<div className="px-4 py-3.5">
<div className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">12-month average</div>
<div className="text-xl font-mono tabular-nums text-zinc-200">{fmt(avgRegular)}</div>
</div>
<div className="bg-zinc-900 border border-zinc-800 rounded-lg px-4 py-3">
<div className="text-xs text-zinc-500 mb-1">Trend (first 3 vs last 3 mo)</div>
<div className={`text-xl font-semibold ${regularTrend.dir === "up" ? "text-red-400" : regularTrend.dir === "down" ? "text-green-400" : "text-zinc-400"}`}>
<div className="px-4 py-3.5">
<div className="text-[10px] uppercase tracking-wider text-zinc-500 mb-1.5">Trend · first 3 vs last 3</div>
<div className={`text-xl font-mono tabular-nums ${regularTrend.dir === "up" ? "text-red-400" : regularTrend.dir === "down" ? "text-emerald-400" : "text-zinc-400"}`}>
{regularTrend.dir === "up" ? "↑" : regularTrend.dir === "down" ? "↓" : "→"} {regularTrend.pct}%
</div>
</div>
</div>
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-4">
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-4">
<ResponsiveContainer width="100%" height={220}>
<ComposedChart data={chartData} margin={{ top: 4, right: 8, left: 0, bottom: 0 }}>
<XAxis dataKey="month" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} />
<YAxis tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} width={44} />
<Tooltip content={<RegularTooltip />} />
<Bar dataKey="regular" stackId="a" fill="#6366f1" name="Regular" radius={[0, 0, 0, 0]} />
<Bar dataKey="occasional" stackId="a" fill="#3f3f46" name="Occasional" radius={[3, 3, 0, 0]} />
<Line type="monotone" dataKey="regular" stroke="#818cf8" strokeWidth={2} dot={false} strokeDasharray="4 2" />
<XAxis dataKey="month" tick={{ fill: CHART.axis, fontSize: 11 }} axisLine={false} tickLine={false} />
<YAxis tick={{ fill: CHART.axis, fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} width={44} />
<Tooltip content={<RegularTooltip />} cursor={{ fill: "rgba(232,224,204,0.04)" }} />
<Bar dataKey="regular" stackId="a" fill={CHART.accent} name="Regular" radius={[0, 0, 0, 0]} />
<Bar dataKey="occasional" stackId="a" fill={CHART.dim} name="Occasional" radius={[3, 3, 0, 0]} />
<Line type="monotone" dataKey="regular" stroke={CHART.accentSoft} strokeWidth={2} dot={false} strokeDasharray="4 2" />
</ComposedChart>
</ResponsiveContainer>
<div className="flex gap-4 mt-2 justify-end">
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-2 rounded-sm bg-indigo-500 inline-block" />Regular (groceries, dining, transport…)</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-2 rounded-sm bg-zinc-600 inline-block" />Occasional</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-2 rounded-sm inline-block" style={{ background: CHART.accent }} />Regular (groceries, dining, transport…)</span>
<span className="flex items-center gap-1.5 text-xs text-zinc-500"><span className="w-3 h-2 rounded-sm inline-block" style={{ background: CHART.dim }} />Occasional</span>
</div>
</div>
</Section>
{/* ── 2. Monthly Spend Breakdown ── */}
<Section title="Monthly Spend Breakdown">
<Section title="Monthly spend breakdown">
{!analytics6 ? (
<p className="text-zinc-500 text-sm">Loading...</p>
) : (
@@ -369,7 +381,7 @@ export default function InsightsPage() {
</Section>
{/* ── 3. Recurring Charges ── */}
<Section title="Recurring Charges">
<Section title="Recurring charges">
{!subData ? (
<p className="text-zinc-500 text-sm">Loading...</p>
) : subData.subscriptions.length === 0 ? (
@@ -380,7 +392,7 @@ export default function InsightsPage() {
<span className="text-xs text-zinc-500">{activeSubscriptions.length} active · {inactiveSubscriptions.length} inactive</span>
<span className="text-sm font-medium text-indigo-400">{fmtExact(subData.total_monthly_equiv)}<span className="text-xs text-zinc-500 font-normal ml-1">/ month committed</span></span>
</div>
<div className="border border-zinc-700 rounded-xl overflow-hidden">
<div className="border border-zinc-800 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900">
@@ -419,7 +431,7 @@ export default function InsightsPage() {
</Section>
{/* ── 4. Fees & Interest ── */}
<Section title="Fees & Interest">
<Section title="Fees & interest">
{!feesData ? (
<p className="text-zinc-500 text-sm">Loading...</p>
) : feesData.by_bank.length === 0 && feesData.transactions.length === 0 ? (
@@ -427,7 +439,7 @@ export default function InsightsPage() {
) : (
<div className="space-y-4">
{feesData.by_bank.length > 0 && (
<div className="border border-zinc-700 rounded-xl overflow-hidden">
<div className="border border-zinc-800 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900">
@@ -459,7 +471,7 @@ export default function InsightsPage() {
{feesData.transactions.length > 0 && (
<div>
<p className="text-xs text-zinc-500 mb-2">Individual fee / interest transactions</p>
<div className="border border-zinc-700 rounded-xl overflow-hidden">
<div className="border border-zinc-800 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900">
+8 -2
View File
@@ -1,5 +1,5 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Geist, Geist_Mono, Fraunces } from "next/font/google";
import "./globals.css";
import { Providers } from "@/components/providers";
import { Sidebar } from "@/components/sidebar";
@@ -14,6 +14,12 @@ const geistMono = Geist_Mono({
subsets: ["latin"],
});
const fraunces = Fraunces({
variable: "--font-fraunces",
subsets: ["latin"],
weight: ["400", "500", "600"],
});
export const metadata: Metadata = {
title: "Finance",
description: "Personal Finance Dashboard",
@@ -27,7 +33,7 @@ export default function RootLayout({
return (
<html lang="en" className="dark">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-zinc-950 text-zinc-100`}
className={`${geistSans.variable} ${geistMono.variable} ${fraunces.variable} antialiased bg-zinc-950 text-zinc-100`}
>
<Providers>
<div className="flex min-h-screen">
+15 -15
View File
@@ -129,7 +129,7 @@ function MerchantProfile({
}));
}, [merchant.monthly_trend]);
const color = CATEGORY_COLORS[merchant.category] || "#6366f1";
const color = CATEGORY_COLORS[merchant.category] || "#bc6f30";
return (
<div className="fixed inset-0 z-50 flex justify-end">
@@ -190,23 +190,23 @@ function MerchantProfile({
<p className="text-sm font-medium text-zinc-300 mb-3">Monthly Spend</p>
<ResponsiveContainer width="100%" height={120}>
<LineChart data={trendData}>
<CartesianGrid stroke="#27272a" strokeDasharray="3 3" />
<CartesianGrid stroke="#242019" strokeDasharray="3 3" />
<XAxis
dataKey="label"
tick={{ fill: "#71717a", fontSize: 10 }}
tick={{ fill: "#94896f", fontSize: 10 }}
axisLine={false}
tickLine={false}
/>
<YAxis
tick={{ fill: "#71717a", fontSize: 10 }}
tick={{ fill: "#94896f", fontSize: 10 }}
axisLine={false}
tickLine={false}
tickFormatter={(v) => `$${Math.round(v)}`}
width={45}
/>
<Tooltip
contentStyle={{ background: "#18181b", border: "1px solid #3f3f46", borderRadius: "8px" }}
labelStyle={{ color: "#a1a1aa" }}
contentStyle={{ background: "#171410", border: "1px solid #332d23", borderRadius: "8px" }}
labelStyle={{ color: "#b3a88e" }}
/>
<Line
type="monotone"
@@ -295,7 +295,7 @@ export default function MerchantsPage() {
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-white">Merchants</h1>
<h1 className="text-2xl font-display text-zinc-50">Merchants</h1>
<p className="text-zinc-400 text-sm mt-0.5">{merchants.length} merchants · last {months} months</p>
</div>
<select
@@ -320,28 +320,28 @@ export default function MerchantsPage() {
<QuadrantLabels medianX={medianX} medianY={medianY} />
<ResponsiveContainer width="100%" height={360}>
<ScatterChart margin={{ top: 10, right: 20, bottom: 20, left: 10 }}>
<CartesianGrid stroke="#27272a" strokeDasharray="3 3" />
<CartesianGrid stroke="#242019" strokeDasharray="3 3" />
<XAxis
dataKey="debit_count"
name="Transactions"
type="number"
tick={{ fill: "#71717a", fontSize: 11 }}
tick={{ fill: "#94896f", fontSize: 11 }}
axisLine={false}
tickLine={false}
label={{ value: "Transaction Count", position: "insideBottom", offset: -10, fill: "#52525b", fontSize: 11 }}
label={{ value: "Transaction Count", position: "insideBottom", offset: -10, fill: "#6e644f", fontSize: 11 }}
/>
<YAxis
dataKey="net_spend"
name="Net Spend"
type="number"
tick={{ fill: "#71717a", fontSize: 11 }}
tick={{ fill: "#94896f", fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={(v) => `$${Math.round(v / 1000)}k`}
width={48}
label={{ value: "Total Spend", angle: -90, position: "insideLeft", offset: 10, fill: "#52525b", fontSize: 11 }}
label={{ value: "Total Spend", angle: -90, position: "insideLeft", offset: 10, fill: "#6e644f", fontSize: 11 }}
/>
<Tooltip content={<ScatterTooltip />} cursor={{ strokeDasharray: "3 3", stroke: "#52525b" }} />
<Tooltip content={<ScatterTooltip />} cursor={{ strokeDasharray: "3 3", stroke: "#6e644f" }} />
<Scatter
data={scatterData}
onClick={(d) => setSelected(d as unknown as MerchantRow)}
@@ -350,7 +350,7 @@ export default function MerchantsPage() {
{scatterData.map((entry, idx) => (
<Cell
key={idx}
fill={CATEGORY_COLORS[entry.category] || "#6366f1"}
fill={CATEGORY_COLORS[entry.category] || "#bc6f30"}
fillOpacity={0.75}
stroke={selected?.merchant === entry.merchant ? "#fff" : "transparent"}
strokeWidth={2}
@@ -400,7 +400,7 @@ export default function MerchantsPage() {
</thead>
<tbody>
{filtered.map((m) => {
const color = CATEGORY_COLORS[m.category] || "#6366f1";
const color = CATEGORY_COLORS[m.category] || "#bc6f30";
return (
<tr
key={m.merchant}
+2 -2
View File
@@ -94,7 +94,7 @@ export default function ReconcilePage() {
if (pending.length === 0) {
return (
<div className="p-6">
<h2 className="text-xl font-semibold mb-2">Reconcile</h2>
<h2 className="text-2xl font-display mb-2">Reconcile</h2>
<p className="text-zinc-500 text-sm">No unreconciled manual transactions. Import a CSV to get started.</p>
</div>
);
@@ -104,7 +104,7 @@ export default function ReconcilePage() {
<div className="p-6 space-y-4">
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-semibold">Reconcile</h2>
<h2 className="text-2xl font-display">Reconcile</h2>
<p className="text-xs text-zinc-500 mt-0.5">
{pending.length} manual transaction{pending.length !== 1 ? "s" : ""} ·{" "}
{withMatches.length} with potential matches
+102 -29
View File
@@ -3,6 +3,8 @@
import { useState } from "react";
import { useRules, useCreateRule, useUpdateRule, useDeleteRule, useApplyRules, useRuleRuns, useRevertRuleRun, useTags, useParticipants } from "@/lib/hooks";
import { CATEGORIES, formatCategory } from "@/lib/categories";
import { RulePreviewModal } from "@/components/rule-preview-modal";
import { RuleRunDetail } from "@/components/rule-run-detail";
const FIELDS = [
{ value: "merchant_normalized", label: "Merchant" },
@@ -82,10 +84,13 @@ export default function RulesPage() {
const [showForm, setShowForm] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
const [applyResult, setApplyResult] = useState<{ matched: number; transactions_affected: number } | null>(null);
const [preview, setPreview] = useState<{ id: number; name: string } | null>(null);
const [expandedRun, setExpandedRun] = useState<number | null>(null);
const [name, setName] = useState("");
const [conditions, setConditions] = useState<Condition[]>([]);
const [actions, setActions] = useState<Actions>(EMPTY_ACTIONS);
const [priority, setPriority] = useState(0);
const [manualOnly, setManualOnly] = useState(false);
function openNewForm() {
setEditingId(null);
@@ -93,15 +98,17 @@ export default function RulesPage() {
setConditions([]);
setActions(EMPTY_ACTIONS);
setPriority(0);
setManualOnly(false);
setShowForm(true);
}
function openEditForm(rule: { id: number; name: string; conditions: Condition[]; actions: Actions; priority: number }) {
function openEditForm(rule: { id: number; name: string; conditions: Condition[]; actions: Actions; priority: number; manual_only?: boolean }) {
setEditingId(rule.id);
setName(rule.name);
setConditions(Array.isArray(rule.conditions) ? rule.conditions : []);
setActions(rule.actions && typeof rule.actions === "object" ? rule.actions : EMPTY_ACTIONS);
setPriority(rule.priority);
setManualOnly(!!rule.manual_only);
setShowForm(true);
window.scrollTo({ top: 0, behavior: "smooth" });
}
@@ -141,7 +148,7 @@ export default function RulesPage() {
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
const payload = { name, conditions, actions, enabled: true, priority };
const payload = { name, conditions, actions, enabled: true, manual_only: manualOnly, priority };
if (editingId !== null) {
await updateRule.mutateAsync({ id: editingId, ...payload });
} else {
@@ -161,7 +168,7 @@ export default function RulesPage() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold">Rules</h2>
<h2 className="text-2xl font-display">Rules</h2>
<div className="flex gap-2 items-center">
<label className="text-xs text-zinc-500 whitespace-nowrap">Splits from</label>
<input
@@ -416,6 +423,20 @@ export default function RulesPage() {
className="w-24 bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-sm"
/>
</div>
<label className="flex items-center gap-2 text-sm text-zinc-400 cursor-pointer select-none pb-2">
<input
type="checkbox"
checked={manualOnly}
onChange={(e) => setManualOnly(e.target.checked)}
className="accent-amber-500"
/>
<span>
Quick action only
<span className="block text-xs text-zinc-600">
Never runs automatically — appears as a button on selected transactions
</span>
</span>
</label>
<button
type="submit"
disabled={isPending}
@@ -432,27 +453,49 @@ export default function RulesPage() {
<h3 className="text-sm font-medium text-zinc-400 mb-2">Apply History</h3>
<div className="space-y-2">
{runs.map((run) => (
<div key={run.id} className={`flex items-center justify-between px-4 py-2.5 rounded-lg border text-sm ${run.reverted_at ? "bg-zinc-900/40 border-zinc-800 opacity-60" : "bg-zinc-900 border-zinc-700"}`}>
<div className="flex items-center gap-4">
<span className="text-zinc-300">{new Date(run.applied_at).toLocaleString()}</span>
<span className="text-zinc-500">{run.matched} matches · {run.transactions_affected} transactions</span>
{run.split_from && <span className="text-zinc-600 text-xs">splits from {run.split_from}</span>}
<div key={run.id} className={`rounded-lg border text-sm overflow-hidden ${run.reverted_at ? "bg-zinc-900/40 border-zinc-800 opacity-60" : "bg-zinc-900 border-zinc-700"}`}>
<div className="flex items-center justify-between px-4 py-2.5">
<div className="flex items-center gap-3 flex-wrap">
<button
onClick={() => setExpandedRun(expandedRun === run.id ? null : run.id)}
className="text-zinc-500 hover:text-zinc-200 w-4 text-left"
title="Show what this run changed"
>
{expandedRun === run.id ? "▾" : "▸"}
</button>
<span className="text-zinc-300">{new Date(run.applied_at).toLocaleString()}</span>
{/* Which rule ran matters most: a merchant rename and a
50/50 split of everything look identical as counts. */}
<span className="text-zinc-200">
{run.rule_name ?? (run.source === "all" ? "All rules" : "Unknown rule")}
</span>
{run.source === "selection" && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-indigo-900/50 text-indigo-300">
selection
</span>
)}
<span className="text-zinc-500">{run.transactions_affected} transactions</span>
{run.split_from && (
<span className="text-zinc-600 text-xs">splits from {String(run.split_from).slice(0, 10)}</span>
)}
</div>
{run.reverted_at ? (
<span className="text-xs text-zinc-500">reverted {new Date(run.reverted_at).toLocaleString()}</span>
) : (
<button
onClick={() => {
if (confirm("Revert this run? This will restore all affected transactions to their state before the rules were applied.")) {
revertRun.mutate(run.id);
}
}}
disabled={revertRun.isPending}
className="text-xs text-amber-400 hover:text-amber-300 disabled:opacity-50"
>
Revert
</button>
)}
</div>
{run.reverted_at ? (
<span className="text-xs text-zinc-500">reverted {new Date(run.reverted_at).toLocaleString()}</span>
) : (
<button
onClick={() => {
if (confirm("Revert this run? This will restore all affected transactions to their state before the rules were applied.")) {
revertRun.mutate(run.id);
}
}}
disabled={revertRun.isPending}
className="text-xs text-amber-400 hover:text-amber-300 disabled:opacity-50"
>
Revert
</button>
)}
{expandedRun === run.id && <RuleRunDetail runId={run.id} />}
</div>
))}
</div>
@@ -475,21 +518,43 @@ export default function RulesPage() {
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-1">
<span className="font-medium text-sm">{rule.name}</span>
{rule.manual_only && (
<span className="text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-900/40 text-amber-300 border border-amber-800/60">
Quick action
</span>
)}
<span className="text-xs text-zinc-500">priority: {rule.priority}</span>
</div>
<p className="text-xs text-zinc-400">
{conds.length > 0 ? conds.map((c) => humanCondition(c, tagNames)).join(" AND ") : "(matches all)"}
{rule.manual_only
? "(fired by hand on selected transactions)"
: conds.length > 0
? conds.map((c) => humanCondition(c, tagNames)).join(" AND ")
: "(matches all)"}
</p>
<p className="text-xs text-zinc-500 mt-1">{humanAction(acts, tagNames, participantNames)}</p>
</div>
<div className="flex items-center gap-3 shrink-0">
{/* Preview is safe for every rule, including quick actions:
it writes nothing, and the apply step takes the ids you
tick rather than re-running the conditions. */}
<button
onClick={() => handleApply(rule.id)}
disabled={applyRules.isPending}
className="text-xs text-emerald-400 hover:text-emerald-300 disabled:opacity-50"
onClick={() => setPreview({ id: rule.id, name: rule.name })}
className="text-xs text-indigo-400 hover:text-indigo-300"
>
Apply
Preview
</button>
{/* No blind Apply for quick actions: their conditions are
empty, so a bulk apply would hit every transaction. */}
{!rule.manual_only && (
<button
onClick={() => handleApply(rule.id)}
disabled={applyRules.isPending}
className="text-xs text-emerald-400 hover:text-emerald-300 disabled:opacity-50"
>
Apply
</button>
)}
<button
onClick={() => updateRule.mutate({ id: rule.id, enabled: !rule.enabled })}
className={`relative inline-flex h-5 w-9 rounded-full transition-colors ${
@@ -503,7 +568,7 @@ export default function RulesPage() {
/>
</button>
<button
onClick={() => openEditForm({ id: rule.id, name: rule.name, conditions: conds as Condition[], actions: acts, priority: rule.priority })}
onClick={() => openEditForm({ id: rule.id, name: rule.name, conditions: conds as Condition[], actions: acts, priority: rule.priority, manual_only: rule.manual_only })}
className="text-zinc-400 hover:text-white text-sm"
>
Edit
@@ -523,6 +588,14 @@ export default function RulesPage() {
})}
</div>
)}
{preview && (
<RulePreviewModal
ruleId={preview.id}
ruleName={preview.name}
onClose={() => setPreview(null)}
/>
)}
</div>
);
}
+1 -1
View File
@@ -307,7 +307,7 @@ export default function SharedPage() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-3">
<h2 className="text-xl font-semibold">Shared Expenses</h2>
<h2 className="text-2xl font-display">Shared Expenses</h2>
<div className="flex items-center gap-2 ml-auto flex-wrap">
<select
value={participantId ?? ""}
+47 -11
View File
@@ -3,6 +3,12 @@
import { useState, useMemo } from "react";
import Link from "next/link";
import { useStatements, useParticipants, useUpdateStatement } from "@/lib/hooks";
import {
STATEMENT_TYPES,
STATEMENT_TYPE_LABELS,
asStatementType,
isLiability,
} from "@/lib/statement-types";
function formatDate(d: string | null) {
if (!d) return "—";
@@ -40,7 +46,7 @@ export default function StatementsPage() {
const updateStatement = useUpdateStatement();
const [bankFilter, setBankFilter] = useState("");
const [typeFilter, setTypeFilter] = useState<"all" | "card" | "bank">("all");
const [typeFilter, setTypeFilter] = useState<"all" | (typeof STATEMENT_TYPES)[number]>("all");
const [ownerFilter, setOwnerFilter] = useState("");
const [yearFilter, setYearFilter] = useState("");
@@ -63,10 +69,8 @@ export default function StatementsPage() {
const filtered = useMemo(() => {
if (!statements) return [];
return statements.filter((s) => {
const isCard = s.statement_type?.toLowerCase().includes("card") ?? false;
if (bankFilter && s.bank_name !== bankFilter) return false;
if (typeFilter === "card" && !isCard) return false;
if (typeFilter === "bank" && isCard) return false;
if (typeFilter !== "all" && asStatementType(s.statement_type) !== typeFilter) return false;
if (ownerFilter && String(s.owner_id) !== ownerFilter) return false;
if (yearFilter && s.billing_end_date?.slice(0, 4) !== yearFilter) return false;
return true;
@@ -78,7 +82,7 @@ export default function StatementsPage() {
return (
<div>
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-semibold">Statements</h2>
<h2 className="text-2xl font-display">Statements</h2>
{!isLoading && statements && (
<span className="text-xs text-zinc-500">
{hasFilters ? `${filtered.length} of ${statements.length}` : statements.length} statements
@@ -98,8 +102,9 @@ export default function StatementsPage() {
<select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value as typeof typeFilter)} className={selectCls}>
<option value="all">All types</option>
<option value="card">Credit card</option>
<option value="bank">Bank account</option>
{STATEMENT_TYPES.map((t) => (
<option key={t} value={t}>{STATEMENT_TYPE_LABELS[t]}</option>
))}
</select>
{participants && participants.length > 1 && (
@@ -152,10 +157,14 @@ export default function StatementsPage() {
</thead>
<tbody>
{filtered.map((s, idx) => {
const isCreditCard = s.statement_type?.toLowerCase().includes("card") ?? false;
const displayAmount = isCreditCard ? s.total_amount_due : s.closing_balance;
const stmtType = asStatementType(s.statement_type);
const owed = isLiability(s.statement_type);
// Cards headline the amount due; everything else (including loans,
// where the balance is what's still owed) headlines the balance.
const displayAmount =
stmtType === "credit_card" ? s.total_amount_due : s.closing_balance;
const amount = Number(displayAmount);
const amountColor = isCreditCard
const amountColor = owed
? "text-red-400"
: amount >= 0
? "text-green-400"
@@ -171,6 +180,20 @@ export default function StatementsPage() {
{s.card_name && (
<div className="text-xs text-zinc-500 truncate max-w-[160px]">{s.card_name}</div>
)}
{stmtType === "loan" && (s.interest_rate || s.scheduled_repayment) && (
<div className="text-xs text-zinc-500 truncate max-w-[160px]">
{[
s.interest_rate ? `${Number(s.interest_rate).toFixed(2)}% p.a.` : null,
s.scheduled_repayment
? `${formatAmount(s.scheduled_repayment)}${
s.repayment_frequency ? ` ${s.repayment_frequency}` : ""
}`
: null,
]
.filter(Boolean)
.join(" · ")}
</div>
)}
<Link
href={`/transactions?statement_id=${s.id}`}
className="sm:hidden text-xs text-indigo-400 hover:text-indigo-300 mt-1 inline-block"
@@ -185,7 +208,7 @@ export default function StatementsPage() {
{formatPeriod(s.billing_start_date, s.billing_end_date)}
</td>
<td className="px-4 py-3 text-zinc-400 whitespace-nowrap">
{isCreditCard ? formatDate(s.payment_due_date) : formatDate(s.billing_end_date)}
{formatDate(s.payment_due_date ?? s.billing_end_date)}
</td>
<td className="px-4 py-3 text-zinc-500 text-xs">
{s.currency}
@@ -199,6 +222,19 @@ export default function StatementsPage() {
</td>
<td className="px-4 py-3 text-right text-zinc-500">
{s.transaction_count}
{/* Balance assertion: flags statements whose transactions
don't add up to the closing balance. */}
{s.balance_diff !== null && s.balance_diff !== undefined &&
Math.abs(Number(s.balance_diff)) >= 0.02 && (
<div
className="text-[10px] text-amber-400 mt-0.5 whitespace-nowrap"
title={`Transactions don't reconcile: expected closing ${formatAmount(
s.expected_closing
)}, statement says ${formatAmount(s.closing_balance)}`}
>
⚠ {formatAmount(Math.abs(Number(s.balance_diff)))} off
</div>
)}
</td>
<td className="px-4 py-3">
{participants?.length ? (
+140 -22
View File
@@ -1,21 +1,128 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTags, useCreateTag, useDeleteTag } from "@/lib/hooks";
import { useQueryClient } from "@tanstack/react-query";
const PRESET_COLORS = [
"#6366f1", // indigo
"#8b5cf6", // violet
"#ec4899", // pink
"#ef4444", // red
"#f97316", // orange
"#eab308", // yellow
"#22c55e", // green
"#14b8a6", // teal
"#3b82f6", // blue
"#6b7280", // gray
"#6366f1", "#8b5cf6", "#ec4899", "#ef4444", "#f97316",
"#eab308", "#22c55e", "#14b8a6", "#3b82f6", "#6b7280",
];
function ConvertModal({
tag,
onClose,
}: {
tag: { id: number; name: string; color: string; transaction_count: number };
onClose: () => void;
}) {
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [deleteTag, setDeleteTag] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const router = useRouter();
const qc = useQueryClient();
async function handleConvert() {
setSaving(true);
setError("");
try {
const res = await fetch(`/api/tags/${tag.id}/convert-to-trip`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ start_date: startDate || null, end_date: endDate || null }),
});
if (!res.ok) throw new Error((await res.json()).error || "Failed");
const { trip } = await res.json();
if (deleteTag) {
await fetch(`/api/tags/${tag.id}`, { method: "DELETE" });
qc.invalidateQueries({ queryKey: ["tags"] });
}
qc.invalidateQueries({ queryKey: ["trips"] });
router.push(`/trips/${trip.id}`);
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to convert");
setSaving(false);
}
}
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60" onClick={onClose}>
<div
className="bg-zinc-900 border border-zinc-700 rounded-xl w-full max-w-sm mx-4 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="px-6 pt-5 pb-4 border-b border-zinc-800">
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: tag.color }} />
<h3 className="font-semibold text-sm text-zinc-300">Convert "{tag.name}" to Trip</h3>
</div>
<p className="text-xs text-zinc-500 mt-1">
Creates a trip with the same name and color, and assigns all {tag.transaction_count} tagged transaction{tag.transaction_count !== 1 ? "s" : ""} to it.
</p>
</div>
<div className="px-6 py-4 space-y-4">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs text-zinc-500 mb-1">Start Date</label>
<input
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
/>
</div>
<div>
<label className="block text-xs text-zinc-500 mb-1">End Date</label>
<input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
/>
</div>
</div>
<p className="text-xs text-zinc-600">Dates are optional — you can set them later from the trip page.</p>
<label className="flex items-center gap-2 cursor-pointer select-none">
<input
type="checkbox"
checked={deleteTag}
onChange={(e) => setDeleteTag(e.target.checked)}
className="accent-indigo-500"
/>
<span className="text-sm text-zinc-400">Delete this tag after converting</span>
</label>
</div>
<div className="px-6 py-4 border-t border-zinc-800 flex gap-2 items-center">
{error && <p className="text-red-400 text-xs mr-auto">{error}</p>}
<div className="flex gap-2 ml-auto">
<button
onClick={onClose}
className="px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg text-sm"
>
Cancel
</button>
<button
onClick={handleConvert}
disabled={saving}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg text-sm font-medium"
>
{saving ? "Converting…" : "Convert to Trip"}
</button>
</div>
</div>
</div>
</div>
);
}
export default function TagsPage() {
const { data: tags, isLoading } = useTags();
const createTag = useCreateTag();
@@ -24,6 +131,7 @@ export default function TagsPage() {
const [name, setName] = useState("");
const [color, setColor] = useState(PRESET_COLORS[0]);
const [error, setError] = useState("");
const [convertTag, setConvertTag] = useState<{ id: number; name: string; color: string; transaction_count: number } | null>(null);
const handleCreate = async () => {
if (!name.trim()) return;
@@ -38,7 +146,7 @@ export default function TagsPage() {
return (
<div>
<h2 className="text-xl font-semibold mb-4">Tags</h2>
<h2 className="text-2xl font-display mb-4">Tags</h2>
{/* Create form */}
<div className="mb-6 p-4 bg-zinc-900/50 border border-zinc-800 rounded-lg">
@@ -83,28 +191,38 @@ export default function TagsPage() {
{tags.map((tag) => (
<div
key={tag.id}
className="flex items-center justify-between px-4 py-2.5 bg-zinc-900/50 border border-zinc-800 rounded-lg"
className="flex items-center justify-between px-4 py-2.5 bg-zinc-900/50 border border-zinc-800 rounded-lg group"
>
<div className="flex items-center gap-3">
<span
className="w-3 h-3 rounded-full flex-shrink-0"
style={{ backgroundColor: tag.color }}
/>
<span className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: tag.color }} />
<span className="text-sm font-medium">{tag.name}</span>
<span className="text-xs text-zinc-500">
{tag.transaction_count} transaction{tag.transaction_count !== 1 ? "s" : ""}
</span>
</div>
<button
onClick={() => deleteTag.mutate(tag.id)}
className="text-xs text-zinc-600 hover:text-red-400 transition-colors px-2 py-0.5 rounded hover:bg-zinc-800"
>
Delete
</button>
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => setConvertTag(tag)}
className="text-xs text-zinc-400 hover:text-indigo-400 transition-colors px-2 py-1 rounded hover:bg-zinc-800"
title="Convert to Trip"
>
→ Trip
</button>
<button
onClick={() => deleteTag.mutate(tag.id)}
className="text-xs text-zinc-600 hover:text-red-400 transition-colors px-2 py-1 rounded hover:bg-zinc-800"
>
Delete
</button>
</div>
</div>
))}
</div>
)}
{convertTag && (
<ConvertModal tag={convertTag} onClose={() => setConvertTag(null)} />
)}
</div>
);
}
+121 -7
View File
@@ -2,7 +2,7 @@
import { useState, useCallback, useRef, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { useTransactions, useBanks, useUpdateTransaction, useBulkAction, useTags, useStatement, useCreateRule, useParticipants, useRecordPayment, useCurrentUser } from "@/lib/hooks";
import { useTransactions, useBanks, useUpdateTransaction, useBulkAction, useTags, useStatement, useCreateRule, useParticipants, useRecordPayment, useCurrentUser, useTrips, useAssignTransactionsToTrip, useRules } from "@/lib/hooks";
import { CATEGORIES, formatCategory } from "@/lib/categories";
import { SplitModal } from "@/components/split-modal";
import { TagPicker } from "@/components/tag-picker";
@@ -10,6 +10,7 @@ import { AddTransactionModal } from "@/components/add-transaction-modal";
import { EditTransactionModal } from "@/components/edit-transaction-modal";
import { CsvImportModal } from "@/components/csv-import-modal";
import type { TransactionRow } from "@/lib/queries";
import type { RuleRow } from "@/lib/hooks";
function formatDate(d: string) {
return new Date(d).toLocaleDateString("en-AU", {
@@ -21,10 +22,13 @@ function formatDate(d: string) {
const SPEND_TYPES = new Set(["debit", "fee", "interest"]);
function formatAmount(amount: number, type: string) {
// `amount` is in the statement's native currency; pass the currency to label it
// correctly. Callers showing a headline figure should pass amount_aud, which is
// what every analytics query totals.
function formatAmount(amount: number, type: string, currency = "AUD") {
const formatted = new Intl.NumberFormat("en-AU", {
style: "currency",
currency: "AUD",
currency,
}).format(amount);
return SPEND_TYPES.has(type) ? formatted : `+${formatted}`;
}
@@ -43,6 +47,28 @@ const TYPE_OPTIONS = [
"debit", "credit", "payment", "refund", "fee", "interest", "transfer",
].map((t) => ({ value: t, label: t }));
/** Tooltip text for a quick-action button: what the rule will actually do. */
function describeActions(
actions: RuleRow["actions"],
tags: { id: number; name: string }[] = [],
participants: { id: number; name: string }[] = []
): string {
const parts: string[] = [];
if (actions.set_category) parts.push(`category → ${formatCategory(actions.set_category)}`);
if (actions.set_merchant) parts.push(`merchant → ${actions.set_merchant}`);
if (actions.add_tag_ids?.length) {
const names = actions.add_tag_ids.map((id) => tags.find((t) => t.id === id)?.name ?? `tag#${id}`);
parts.push(`tag: ${names.join(", ")}`);
}
if (actions.apply_split?.length) {
const shares = actions.apply_split.map(
(s) => `${participants.find((p) => p.id === s.participant_id)?.name ?? `#${s.participant_id}`} ${s.share_percent}%`
);
parts.push(`split: ${shares.join(" / ")}`);
}
return parts.join(" · ") || "no actions";
}
function TypeBadge({ type }: { type: string }) {
return (
<span className={`px-2 py-0.5 rounded text-xs font-medium ${TYPE_COLORS[type] || "bg-zinc-800 text-zinc-400"}`}>
@@ -477,6 +503,7 @@ function TransactionsContent() {
amount_min: undefined as number | undefined,
amount_max: undefined as number | undefined,
has_split: "" as string,
trip_id: "" as string,
});
const [queryInput, setQueryInput] = useState("");
const [queryTokens, setQueryTokens] = useState<QueryToken[]>([]);
@@ -506,6 +533,7 @@ function TransactionsContent() {
const [selected, setSelected] = useState<Set<number>>(new Set());
const [bulkCategory, setBulkCategory] = useState("");
const [bulkTagId, setBulkTagId] = useState("");
const [bulkTripId, setBulkTripId] = useState("");
const [splitModal, setSplitModal] = useState<{ transactionId?: number; transactionIds?: number[]; amount?: number; description: string; merchant?: string } | null>(null);
const [addModal, setAddModal] = useState<{ prefill?: Parameters<typeof AddTransactionModal>[0]["prefill"]; title?: string } | null>(null);
const [editModal, setEditModal] = useState<TransactionRow | null>(null);
@@ -524,6 +552,12 @@ function TransactionsContent() {
const { data: statementInfo } = useStatement(parseInt(filters.statement_id) || 0);
const updateTxn = useUpdateTransaction();
const bulkAction = useBulkAction();
const { data: trips = [] } = useTrips();
const assignToTrip = useAssignTransactionsToTrip();
const { data: allRules = [] } = useRules();
const { data: participants = [] } = useParticipants();
const quickActions = allRules.filter((r) => r.manual_only);
const [quickResult, setQuickResult] = useState<string | null>(null);
const toggleSelect = useCallback((id: number) => {
setSelected((prev) => {
@@ -564,7 +598,7 @@ function TransactionsContent() {
return (
<div>
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-semibold">Transactions</h2>
<h2 className="text-2xl font-display">Transactions</h2>
<div className="flex gap-2">
<button
onClick={() => setShowImportModal(true)}
@@ -687,6 +721,17 @@ function TransactionsContent() {
<option value="yes">Split only</option>
<option value="no">Unsplit only</option>
</select>
<select
value={filters.trip_id}
onChange={(e) => setFilters((f) => ({ ...f, trip_id: e.target.value, offset: 0 }))}
className="bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm text-zinc-300"
>
<option value="">All Trips</option>
<option value="unassigned">No Trip</option>
{trips.map((t) => (
<option key={t.id} value={String(t.id)}>{t.name}</option>
))}
</select>
</div>
{/* Bulk action bar */}
@@ -748,6 +793,56 @@ function TransactionsContent() {
>
Tag
</button>
<select
value={bulkTripId}
onChange={(e) => setBulkTripId(e.target.value)}
className="bg-zinc-800 border border-zinc-600 rounded px-2 py-1 text-sm"
>
<option value="">Assign trip…</option>
<option value="remove">Remove from trip</option>
{trips.filter((t) => !t.archived).map((t) => (
<option key={t.id} value={String(t.id)}>{t.name}</option>
))}
</select>
<button
disabled={!bulkTripId || assignToTrip.isPending}
onClick={() => {
const tripId = bulkTripId === "remove" ? null : Number(bulkTripId);
assignToTrip.mutate(
{ tripId, transactionIds: Array.from(selected) },
{ onSuccess: () => { setSelected(new Set()); setBulkTripId(""); } }
);
}}
className="px-3 py-1 bg-emerald-700 hover:bg-emerald-600 disabled:opacity-50 rounded text-sm"
>
{bulkTripId === "remove" ? "Remove" : "Assign"}
</button>
{quickActions.length > 0 && (
<div className="flex items-center gap-2 pl-3 ml-1 border-l border-zinc-700">
{quickActions.map((rule) => (
<button
key={rule.id}
disabled={bulkAction.isPending}
title={describeActions(rule.actions, tags, participants)}
onClick={() => {
const count = selected.size;
bulkAction.mutate(
{ action: "apply_rule", ids: Array.from(selected), rule_id: rule.id },
{
onSuccess: () => {
setSelected(new Set());
setQuickResult(`${rule.name} applied to ${count} transaction${count !== 1 ? "s" : ""}`);
},
}
);
}}
className="px-3 py-1 bg-amber-700/80 hover:bg-amber-600 disabled:opacity-50 rounded text-sm"
>
{rule.name}
</button>
))}
</div>
)}
<button
onClick={() => setSelected(new Set())}
className="px-3 py-1 text-zinc-400 hover:text-white text-sm"
@@ -757,6 +852,18 @@ function TransactionsContent() {
</div>
)}
{quickResult && (
<div className="flex items-center gap-3 mb-3 px-3 py-2 bg-emerald-900/30 border border-emerald-700 rounded text-sm text-emerald-200">
<span>{quickResult}</span>
<a href="/rules" className="text-emerald-400 hover:text-emerald-300 underline">
undo from Rules → Apply History
</a>
<button onClick={() => setQuickResult(null)} className="ml-auto text-zinc-400 hover:text-white">
dismiss
</button>
</div>
)}
{/* Table */}
<div className="overflow-x-auto border border-zinc-800 rounded-lg">
<table className="w-full text-sm min-w-[900px]">
@@ -843,7 +950,12 @@ function TransactionsContent() {
<td className={`p-2 text-right whitespace-nowrap font-mono ${
SPEND_TYPES.has(t.transaction_type) ? "text-red-400" : "text-green-400"
}`}>
{formatAmount(t.amount, t.transaction_type)}
{formatAmount(t.amount_aud ?? t.amount, t.transaction_type)}
{t.currency && t.currency !== "AUD" && (
<div className="text-[10px] text-zinc-500 mt-0.5">
{formatAmount(t.amount, t.transaction_type, t.currency)}
</div>
)}
</td>
<td className="p-2">
<EditableTypeBadge
@@ -896,7 +1008,7 @@ function TransactionsContent() {
</span>
))}
<button
onClick={() => setSplitModal({ transactionId: t.id, amount: t.amount, description: t.description, merchant: t.effective_merchant || undefined, transactionIds: undefined })}
onClick={() => setSplitModal({ transactionId: t.id, amount: t.amount_aud ?? t.amount, description: t.description, merchant: t.effective_merchant || undefined, transactionIds: undefined })}
className={`text-xs px-2 py-0.5 rounded transition-colors ${
t.splits?.some((s) => s.participant_id !== me?.id)
? "text-amber-400 hover:text-amber-200 hover:bg-zinc-800"
@@ -929,7 +1041,9 @@ function TransactionsContent() {
prefill: {
date: new Date().toISOString().slice(0, 10),
description: t.description,
amount: t.amount,
// Duplicates become manual (AUD) transactions, so seed
// them with the converted figure, not the native one.
amount: t.amount_aud ?? t.amount,
transaction_type: t.transaction_type,
merchant_normalized: t.effective_merchant || undefined,
category: t.effective_category || undefined,
+373
View File
@@ -0,0 +1,373 @@
"use client";
import { use, useState } from "react";
import Link from "next/link";
import {
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
Cell,
} from "recharts";
import { useTripAnalytics, useTrip, useTransactions } from "@/lib/hooks";
import { CreateTripModal } from "@/components/create-trip-modal";
import { formatCategory } from "@/lib/categories";
import { CATEGORY_COLORS, TOOLTIP_STYLE } from "@/lib/category-colors";
function fmtDate(d: string | null) {
if (!d) return null;
return new Date(d).toLocaleDateString("en-AU", { day: "2-digit", month: "short", year: "numeric" });
}
function StatCard({
label,
value,
sub,
color,
}: {
label: string;
value: string;
sub?: string;
color: string;
}) {
return (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5 relative overflow-hidden">
<div className="absolute top-0 left-0 right-0 h-0.5" style={{ backgroundColor: color }} />
<p className="text-xs text-zinc-500 mb-1">{label}</p>
<p className="text-2xl font-semibold tabular-nums">{value}</p>
{sub && <p className="text-xs text-zinc-600 mt-1 truncate">{sub}</p>}
</div>
);
}
function DailyTooltip({ active, payload, label }: { active?: boolean; payload?: { value: number }[]; label?: string }) {
if (!active || !payload?.length) return null;
return (
<div style={TOOLTIP_STYLE} className="p-2.5 text-xs">
<p className="text-zinc-400 mb-1">
{label ? new Date(label).toLocaleDateString("en-AU", { day: "2-digit", month: "short", year: "numeric" }) : ""}
</p>
<p className="text-zinc-100 font-medium">${Number(payload[0].value).toFixed(2)}</p>
</div>
);
}
function CategoryTooltip({ active, payload }: { active?: boolean; payload?: { payload: { category: string }; value: number }[] }) {
if (!active || !payload?.length) return null;
return (
<div style={TOOLTIP_STYLE} className="p-2.5 text-xs">
<p className="text-zinc-400 mb-1">{formatCategory(payload[0].payload.category)}</p>
<p className="text-zinc-100 font-medium">${Number(payload[0].value).toFixed(2)}</p>
</div>
);
}
export default function TripDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params);
const tripId = Number(id);
const { data: analytics, isLoading } = useTripAnalytics(tripId);
const { data: trip } = useTrip(tripId);
const [tab, setTab] = useState<"overview" | "transactions">("overview");
const [editModal, setEditModal] = useState(false);
const { data: txData } = useTransactions({ trip_id: id, limit: 500 });
if (isLoading || !analytics) {
return (
<div className="space-y-6">
<div className="h-32 bg-zinc-900 rounded-2xl animate-pulse" />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
{[...Array(4)].map((_, i) => <div key={i} className="h-24 bg-zinc-900 rounded-xl animate-pulse" />)}
</div>
</div>
);
}
const { total_spend, transaction_count, num_days, daily_average, category_breakdown, daily_spend, top_merchants, tag_breakdown, participant_splits } = analytics;
const t = analytics.trip;
const maxMerchant = top_merchants[0]?.amount ?? 1;
const dateRange = t.start_date && t.end_date
? `${fmtDate(t.start_date)} – ${fmtDate(t.end_date)}`
: t.start_date
? `From ${fmtDate(t.start_date)}`
: null;
return (
<div className="space-y-6">
{/* Hero */}
<div
className="relative rounded-2xl overflow-hidden p-6"
style={{
background: `linear-gradient(135deg, ${t.color}28 0%, #18181b 60%)`,
borderLeft: `3px solid ${t.color}`,
}}
>
<div className="flex items-start justify-between gap-4 flex-wrap">
<div>
<div className="flex items-center gap-2 mb-1">
<Link href="/trips" className="text-xs text-zinc-500 hover:text-zinc-300 transition-colors">
← Trips
</Link>
</div>
<h1 className="text-2xl font-bold">{t.name}</h1>
{dateRange && <p className="text-sm text-zinc-400 mt-1">{dateRange}</p>}
{t.description && <p className="text-sm text-zinc-500 mt-1">{t.description}</p>}
</div>
<button
onClick={() => setEditModal(true)}
className="px-3 py-1.5 bg-zinc-800/80 hover:bg-zinc-700 text-zinc-300 rounded-lg text-sm transition-colors flex-shrink-0"
>
Edit Trip
</button>
</div>
</div>
{/* Stat cards */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
<StatCard label="Total Spend" value={`$${Number(total_spend).toFixed(2)}`} sub="all transactions" color={t.color} />
<StatCard label="Transactions" value={String(transaction_count)} sub="total" color={t.color} />
<StatCard label="Daily Average" value={`$${Number(daily_average).toFixed(2)}`} sub="per day" color={t.color} />
<StatCard label="Days" value={String(num_days)} sub={dateRange ?? "date range"} color={t.color} />
</div>
{/* Tab bar */}
<div className="flex gap-0 border-b border-zinc-800">
{(["overview", "transactions"] as const).map((tabName) => (
<button
key={tabName}
onClick={() => setTab(tabName)}
className={`px-5 py-2.5 text-sm capitalize transition-colors border-b-2 -mb-px ${
tab === tabName
? "border-current text-white font-medium"
: "border-transparent text-zinc-500 hover:text-zinc-300"
}`}
style={tab === tabName ? { borderColor: t.color } : {}}
>
{tabName}
</button>
))}
</div>
{tab === "overview" && (
<div className="space-y-5">
{/* Daily spend */}
{daily_spend.length > 0 && (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
<h3 className="text-sm font-medium mb-4">Daily Spend</h3>
<ResponsiveContainer width="100%" height={200}>
<BarChart data={daily_spend} margin={{ top: 4, right: 8, bottom: 0, left: 8 }}>
<XAxis
dataKey="date"
tick={{ fill: "#71717a", fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={(v) => new Date(v).toLocaleDateString("en-AU", { day: "2-digit", month: "short" })}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fill: "#71717a", fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={(v) => `$${v}`}
width={52}
/>
<Tooltip content={<DailyTooltip />} cursor={{ fill: "#27272a" }} />
<Bar dataKey="amount" fill={t.color} radius={[3, 3, 0, 0]} maxBarSize={40} opacity={0.85} />
</BarChart>
</ResponsiveContainer>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
{/* Category breakdown */}
{category_breakdown.length > 0 && (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
<h3 className="text-sm font-medium mb-4">By Category</h3>
<ResponsiveContainer width="100%" height={Math.max(120, category_breakdown.length * 32)}>
<BarChart
data={category_breakdown}
layout="vertical"
margin={{ top: 0, right: 60, bottom: 0, left: 100 }}
>
<XAxis type="number" tick={{ fill: "#71717a", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `$${v}`} />
<YAxis
type="category"
dataKey="category"
tick={{ fill: "#a1a1aa", fontSize: 12 }}
axisLine={false}
tickLine={false}
tickFormatter={formatCategory}
width={98}
/>
<Tooltip content={<CategoryTooltip />} cursor={{ fill: "#27272a" }} />
<Bar dataKey="amount" radius={[0, 3, 3, 0]} maxBarSize={22}>
{category_breakdown.map((entry) => (
<Cell key={entry.category} fill={CATEGORY_COLORS[entry.category] || "#6366f1"} opacity={0.85} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)}
{/* Top merchants */}
{top_merchants.length > 0 && (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
<h3 className="text-sm font-medium mb-4">Top Merchants</h3>
<div className="space-y-3">
{top_merchants.map((m, i) => (
<div key={m.merchant} className="flex items-center gap-3">
<span className="text-xs text-zinc-600 w-4 tabular-nums text-right">{i + 1}</span>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-1">
<span className="text-sm truncate">{m.merchant || "Unknown"}</span>
<span className="text-sm font-mono tabular-nums ml-2 flex-shrink-0">${Number(m.amount).toFixed(2)}</span>
</div>
<div className="h-1.5 bg-zinc-800 rounded-full overflow-hidden">
<div
className="h-full rounded-full"
style={{
width: `${(m.amount / maxMerchant) * 100}%`,
backgroundColor: t.color,
opacity: 0.7,
}}
/>
</div>
</div>
</div>
))}
</div>
</div>
)}
</div>
{/* Tag breakdown */}
{tag_breakdown.length > 0 && (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
<h3 className="text-sm font-medium mb-3">By Tag</h3>
<div className="flex flex-wrap gap-2">
{tag_breakdown.map((tag) => (
<div
key={tag.tag_id}
className="flex items-center gap-2 px-3 py-2 rounded-lg border border-zinc-800 bg-zinc-800/50"
>
<span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ backgroundColor: tag.color }} />
<span className="text-sm font-medium">{tag.name}</span>
<span className="text-xs text-zinc-500">{tag.count} txns</span>
<span className="text-sm font-mono tabular-nums text-zinc-300">${Number(tag.amount).toFixed(2)}</span>
</div>
))}
</div>
</div>
)}
{/* Participant splits */}
{participant_splits.length > 0 && (
<div className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
<div className="px-5 py-3 border-b border-zinc-800 flex items-center justify-between">
<h3 className="text-sm font-medium">Participant Splits</h3>
<Link href="/shared" className="text-xs text-zinc-500 hover:text-zinc-300">
View in Shared →
</Link>
</div>
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800">
{["Person", "Share of this trip"].map((h) => (
<th
key={h}
className={`px-5 py-2.5 text-xs text-zinc-500 font-medium ${h === "Person" ? "text-left" : "text-right"}`}
>
{h}
</th>
))}
</tr>
</thead>
<tbody>
{participant_splits.map((p) => (
<tr key={p.participant_id} className="border-b border-zinc-800/50 last:border-0">
<td className="px-5 py-3 font-medium">{p.name}</td>
<td className="px-5 py-3 text-right tabular-nums font-mono">${Number(p.owed).toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
{/* Settled/unsettled was reported from transaction_splits.settled,
which nothing sets — so every trip showed 100% unsettled forever,
including ones already paid in full. Settlement is tracked across
the whole relationship, not per trip: payments carry no trip
attribution, so a per-trip figure cannot be computed. */}
<p className="px-5 py-2.5 text-xs text-zinc-500 border-t border-zinc-800">
Settlement is tracked across all shared expenses, not per trip —
see <Link href="/shared" className="text-zinc-400 hover:text-zinc-200 underline">Shared</Link> for
what is actually owed.
</p>
</div>
)}
{category_breakdown.length === 0 && daily_spend.length === 0 && (
<div className="text-center py-12 text-zinc-600">
<p className="text-sm">No transactions assigned to this trip yet.</p>
<Link href="/transactions" className="text-indigo-400 hover:text-indigo-300 text-sm mt-1 inline-block">
Go to Transactions to assign some →
</Link>
</div>
)}
</div>
)}
{tab === "transactions" && (
<div>
{!txData?.data.length ? (
<div className="text-center py-12 text-zinc-600">
<p className="text-sm">No transactions assigned to this trip yet.</p>
<Link href="/transactions" className="text-indigo-400 hover:text-indigo-300 text-sm mt-1 inline-block">
Go to Transactions to assign some →
</Link>
</div>
) : (
<div className="border border-zinc-800 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900/60">
{["Date", "Description", "Merchant", "Category", "Amount"].map((h) => (
<th
key={h}
className={`px-4 py-2.5 text-xs text-zinc-500 font-medium ${h === "Amount" ? "text-right" : "text-left"}`}
>
{h}
</th>
))}
</tr>
</thead>
<tbody>
{txData.data.map((tx) => (
<tr key={tx.id} className="border-b border-zinc-800/40 last:border-0 hover:bg-zinc-900/40 transition-colors">
<td className="px-4 py-2.5 text-xs text-zinc-400 whitespace-nowrap">
{new Date(tx.transaction_date).toLocaleDateString("en-AU", { day: "2-digit", month: "short" })}
</td>
<td className="px-4 py-2.5 max-w-xs truncate text-zinc-300">{tx.description}</td>
<td className="px-4 py-2.5 text-zinc-400 truncate">{tx.effective_merchant || "—"}</td>
<td className="px-4 py-2.5 text-zinc-500 text-xs">{formatCategory(tx.effective_category)}</td>
<td className="px-4 py-2.5 text-right tabular-nums font-mono text-red-400">
${Number(tx.amount).toFixed(2)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)}
{editModal && trip && (
<CreateTripModal trip={trip} onClose={() => setEditModal(false)} />
)}
</div>
);
}
+153
View File
@@ -0,0 +1,153 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { useTrips, useDeleteTrip } from "@/lib/hooks";
import type { TripRow } from "@/lib/hooks";
import { CreateTripModal } from "@/components/create-trip-modal";
function fmtDate(d: string | null) {
if (!d) return null;
return new Date(d).toLocaleDateString("en-AU", { day: "2-digit", month: "short", year: "numeric" });
}
function TripCard({ trip, onEdit, onDelete }: { trip: TripRow; onEdit: () => void; onDelete: () => void }) {
const dateRange = trip.start_date && trip.end_date
? `${fmtDate(trip.start_date)} – ${fmtDate(trip.end_date)}`
: trip.start_date
? `From ${fmtDate(trip.start_date)}`
: "No dates set";
return (
<div className="relative bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden hover:border-zinc-600 transition-colors group">
<div className="absolute left-0 top-0 bottom-0 w-1 rounded-l-xl" style={{ backgroundColor: trip.color }} />
<Link href={`/trips/${trip.id}`} className="block p-5 pl-6">
<p className="font-semibold text-base truncate">{trip.name}</p>
{trip.description && (
<p className="text-xs text-zinc-500 mt-0.5 truncate">{trip.description}</p>
)}
<p className="text-xs text-zinc-600 mt-1">{dateRange}</p>
<div className="mt-4 flex items-baseline gap-3">
<span className="text-2xl font-semibold tabular-nums">${Number(trip.total_spend).toFixed(2)}</span>
<span className="text-xs text-zinc-500">{trip.transaction_count} transactions</span>
</div>
</Link>
<div className="px-5 pb-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={onEdit}
className="text-xs text-zinc-400 hover:text-white px-2 py-1 rounded hover:bg-zinc-800 transition-colors"
>
Edit
</button>
<button
onClick={onDelete}
className="text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-zinc-800 transition-colors"
>
Delete
</button>
</div>
</div>
);
}
export default function TripsPage() {
const { data: trips = [], isLoading } = useTrips();
const deleteTrip = useDeleteTrip();
const [modal, setModal] = useState<{ trip?: TripRow } | null>(null);
const active = trips.filter((t) => !t.archived);
const archived = trips.filter((t) => t.archived);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-display">Trips</h2>
<p className="text-sm text-zinc-500 mt-0.5">Group and analyse expenses by trip</p>
</div>
<button
onClick={() => setModal({})}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg text-sm font-medium transition-colors"
>
+ New Trip
</button>
</div>
{isLoading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{[...Array(3)].map((_, i) => (
<div key={i} className="bg-zinc-900 border border-zinc-800 rounded-xl p-5 animate-pulse">
<div className="h-4 bg-zinc-800 rounded w-2/3 mb-3" />
<div className="h-3 bg-zinc-800 rounded w-1/3 mb-4" />
<div className="h-7 bg-zinc-800 rounded w-1/2" />
</div>
))}
</div>
) : active.length === 0 ? (
<div className="text-center py-20 text-zinc-600">
<svg className="w-12 h-12 mx-auto mb-4 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<p className="text-lg font-medium mb-1">No trips yet</p>
<p className="text-sm">Create a trip to group and analyse expenses — holidays, events, work travel.</p>
<button
onClick={() => setModal({})}
className="mt-4 px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg text-sm font-medium"
>
Create your first trip
</button>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{active.map((trip) => (
<TripCard
key={trip.id}
trip={trip}
onEdit={() => setModal({ trip })}
onDelete={() => {
if (confirm(`Delete "${trip.name}"? This will unlink all transactions from this trip.`)) {
deleteTrip.mutate(trip.id);
}
}}
/>
))}
</div>
)}
{archived.length > 0 && (
<details className="group/archived">
<summary className="text-sm text-zinc-500 cursor-pointer hover:text-zinc-300 list-none flex items-center gap-2 select-none">
<svg className="w-3 h-3 transition-transform group-open/archived:rotate-90" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M7.293 4.707a1 1 0 011.414 0L14 10l-5.293 5.293a1 1 0 01-1.414-1.414L11.586 10 6.586 5a1 1 0 010-1.293z" clipRule="evenodd" />
</svg>
Archived ({archived.length})
</summary>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-3">
{archived.map((trip) => (
<div key={trip.id} className="relative bg-zinc-900/50 border border-zinc-800 rounded-xl overflow-hidden opacity-60 hover:opacity-100 transition-opacity group">
<div className="absolute left-0 top-0 bottom-0 w-1 rounded-l-xl" style={{ backgroundColor: trip.color }} />
<Link href={`/trips/${trip.id}`} className="block p-5 pl-6">
<p className="font-medium truncate">{trip.name}</p>
<p className="text-xs text-zinc-600 mt-1">${Number(trip.total_spend).toFixed(2)} · {trip.transaction_count} transactions</p>
</Link>
<div className="px-5 pb-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => setModal({ trip })}
className="text-xs text-zinc-400 hover:text-white px-2 py-1 rounded hover:bg-zinc-800"
>
Edit
</button>
</div>
</div>
))}
</div>
</details>
)}
{modal !== null && (
<CreateTripModal trip={modal.trip} onClose={() => setModal(null)} />
)}
</div>
);
}
+23
View File
@@ -35,6 +35,8 @@ export function AddTransactionModal({
const [type, setType] = useState(prefill?.transaction_type ?? "debit");
const [merchant, setMerchant] = useState(prefill?.merchant_normalized ?? "");
const [category, setCategory] = useState(prefill?.category ?? "");
// Cash is excluded from reconciliation — it will never appear on a statement.
const [paymentMethod, setPaymentMethod] = useState("");
const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
const [splits, setSplits] = useState<{ participant_id: number; share_percent: number }[]>(
prefill?.splits ?? []
@@ -68,6 +70,7 @@ export function AddTransactionModal({
transaction_type: type,
merchant_normalized: merchant || undefined,
category: category || undefined,
payment_method: paymentMethod || undefined,
splits: splits.length ? splits : undefined,
});
if (selectedTagIds.length && result?.id) {
@@ -159,6 +162,26 @@ export function AddTransactionModal({
</div>
</div>
<div>
<label className="block text-xs text-zinc-500 mb-1">Paid by</label>
<select
value={paymentMethod}
onChange={(e) => setPaymentMethod(e.target.value)}
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm"
>
<option value="">— unknown —</option>
<option value="card">Card</option>
<option value="cash">Cash</option>
<option value="bank_transfer">Bank transfer</option>
<option value="other">Other</option>
</select>
{paymentMethod === "cash" && (
<p className="text-[11px] text-zinc-500 mt-1">
Cash won&apos;t be offered for reconciliation — it never appears on a statement.
</p>
)}
</div>
<div>
<label className="block text-xs text-zinc-500 mb-1">Merchant (optional)</label>
<input
+157
View File
@@ -0,0 +1,157 @@
"use client";
import { useState } from "react";
import { useCreateTrip, useUpdateTrip } from "@/lib/hooks";
import type { TripRow } from "@/lib/hooks";
export function CreateTripModal({
trip,
onClose,
}: {
trip?: TripRow;
onClose: () => void;
}) {
const isEdit = !!trip;
const [name, setName] = useState(trip?.name ?? "");
const [description, setDescription] = useState(trip?.description ?? "");
const [startDate, setStartDate] = useState(trip?.start_date?.slice(0, 10) ?? "");
const [endDate, setEndDate] = useState(trip?.end_date?.slice(0, 10) ?? "");
const [color, setColor] = useState(trip?.color ?? "#6366f1");
const [archived, setArchived] = useState(trip?.archived ?? false);
const [error, setError] = useState("");
const createTrip = useCreateTrip();
const updateTrip = useUpdateTrip();
const isPending = createTrip.isPending || updateTrip.isPending;
async function handleSave() {
setError("");
if (!name.trim()) { setError("Name is required"); return; }
try {
if (isEdit) {
await updateTrip.mutateAsync({
id: trip!.id,
name: name.trim(),
description: description || null,
start_date: startDate || null,
end_date: endDate || null,
color,
archived,
});
} else {
await createTrip.mutateAsync({
name: name.trim(),
description: description || null,
start_date: startDate || null,
end_date: endDate || null,
color,
archived,
});
}
onClose();
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to save");
}
}
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60" onClick={onClose}>
<div
className="bg-zinc-900 border border-zinc-700 rounded-xl w-full max-w-md mx-4 shadow-2xl flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="px-6 pt-5 pb-4 border-b border-zinc-800">
<h3 className="font-semibold text-sm text-zinc-300">{isEdit ? "Edit Trip" : "New Trip"}</h3>
</div>
<div className="px-6 py-4 space-y-4">
<div>
<label className="block text-xs text-zinc-500 mb-1">Name *</label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Europe 2026"
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
/>
</div>
<div>
<label className="block text-xs text-zinc-500 mb-1">Description</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={2}
placeholder="Optional notes about this trip"
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm resize-none focus:outline-none focus:border-zinc-500"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs text-zinc-500 mb-1">Start Date</label>
<input
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
/>
</div>
<div>
<label className="block text-xs text-zinc-500 mb-1">End Date</label>
<input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
/>
</div>
</div>
<div className="flex items-center gap-4">
<div>
<label className="block text-xs text-zinc-500 mb-1">Color</label>
<input
type="color"
value={color}
onChange={(e) => setColor(e.target.value)}
className="h-9 w-16 rounded border border-zinc-700 bg-zinc-800 cursor-pointer"
/>
</div>
{isEdit && (
<label className="flex items-center gap-2 text-sm text-zinc-400 mt-4 cursor-pointer select-none">
<input
type="checkbox"
checked={archived}
onChange={(e) => setArchived(e.target.checked)}
className="accent-indigo-500"
/>
Archived
</label>
)}
</div>
</div>
<div className="px-6 py-4 border-t border-zinc-800 flex gap-2 items-center">
{error && <p className="text-red-400 text-xs mr-auto">{error}</p>}
<div className="flex gap-2 ml-auto">
<button
type="button"
onClick={onClose}
className="px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg text-sm"
>
Cancel
</button>
<button
type="button"
onClick={handleSave}
disabled={isPending}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg text-sm font-medium"
>
{isPending ? "Saving…" : isEdit ? "Save Changes" : "Create Trip"}
</button>
</div>
</div>
</div>
</div>
);
}
+22
View File
@@ -7,6 +7,7 @@ import {
useAddTransactionTag,
useRemoveTransactionTag,
useTransactionSplits,
useTrips,
} from "@/lib/hooks";
import { SplitModal } from "./split-modal";
import { CATEGORIES, formatCategory } from "@/lib/categories";
@@ -93,6 +94,7 @@ export function EditTransactionModal({
}) {
const isManual = !transaction.statement_id;
const updateTxn = useUpdateTransaction();
const { data: trips = [] } = useTrips();
// Editable override fields
const [merchant, setMerchant] = useState(transaction.merchant_override ?? transaction.merchant_normalized ?? "");
@@ -105,6 +107,8 @@ export function EditTransactionModal({
const [description, setDescription] = useState(transaction.description);
const [amount, setAmount] = useState(String(transaction.amount));
const [tripId, setTripId] = useState<number | null>(transaction.trip_id ?? null);
// Splits — live via hook so they refresh after SplitModal saves
const { data: liveSplits = [] } = useTransactionSplits(transaction.id);
@@ -136,6 +140,9 @@ export function EditTransactionModal({
patch.amount = parseFloat(amount);
}
if (tripId !== (transaction.trip_id ?? null))
patch.trip_id = tripId;
await updateTxn.mutateAsync(patch);
onClose();
} catch (e) {
@@ -255,6 +262,21 @@ export function EditTransactionModal({
</div>
</div>
{/* Trip */}
<div>
<label className="block text-xs text-zinc-500 mb-1">Trip</label>
<select
value={tripId ?? ""}
onChange={(e) => setTripId(e.target.value ? Number(e.target.value) : null)}
className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm"
>
<option value="">— No Trip —</option>
{trips.filter((t) => !t.archived).map((t) => (
<option key={t.id} value={t.id}>{t.name}</option>
))}
</select>
</div>
{/* Tags */}
<div>
<p className="text-xs text-zinc-500 mb-1.5">Tags</p>
+164
View File
@@ -0,0 +1,164 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useRuleMatches, useApplyRuleToSelection, type RuleMatchChange } from "@/lib/hooks";
import { formatCategory } from "@/lib/categories";
/**
* Preview what a rule would do, then apply it to a chosen subset.
*
* The apply path takes explicit transaction ids rather than re-running the
* conditions, so what you tick is exactly what changes — a rule whose
* conditions are too broad cannot quietly reach further than the preview showed.
*/
function fmt(amount: number, currency = "AUD") {
return new Intl.NumberFormat("en-AU", { style: "currency", currency }).format(amount);
}
function describe(c: RuleMatchChange) {
if (c.field === "category") return `${formatCategory(c.from)} → ${formatCategory(c.to)}`;
if (c.field === "merchant") return `${c.from ?? "—"} → ${c.to}`;
if (c.field === "tags") return `+ tags`;
return c.from ? `split ${c.from} → ${c.to}` : `split → ${c.to}`;
}
export function RulePreviewModal({
ruleId,
ruleName,
onClose,
}: {
ruleId: number;
ruleName: string;
onClose: () => void;
}) {
const { data, isLoading, error } = useRuleMatches(ruleId);
const apply = useApplyRuleToSelection();
const [selected, setSelected] = useState<Set<number>>(new Set());
const [done, setDone] = useState<string | null>(null);
// Default to everything the rule would change — the common case is "yes, all
// of these", with deselection as the exception.
useEffect(() => {
if (data?.transactions) setSelected(new Set(data.transactions.map((t) => t.id)));
}, [data]);
const rows = data?.transactions ?? [];
const allSelected = rows.length > 0 && selected.size === rows.length;
const totalValue = useMemo(
() => rows.filter((r) => selected.has(r.id))
.reduce((a, r) => a + Number(r.amount_aud ?? r.amount), 0),
[rows, selected]
);
return (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
<div className="bg-zinc-900 border border-zinc-700 rounded-lg w-full max-w-4xl max-h-[85vh] flex flex-col">
<div className="px-5 py-4 border-b border-zinc-800">
<h2 className="text-lg font-medium">Preview: {ruleName}</h2>
{data && (
<p className="text-xs text-zinc-500 mt-1">
{data.total_matched} matched · <span className="text-amber-400">{data.would_change} would change</span>
{data.already_correct > 0 && ` · ${data.already_correct} already correct`}
</p>
)}
{data?.rule.matches_everything && (
<p className="text-xs text-red-400 mt-1">
This rule has no conditions — it matches every transaction.
</p>
)}
</div>
<div className="flex-1 overflow-auto px-5 py-3">
{isLoading && <p className="text-sm text-zinc-500">Checking…</p>}
{error && <p className="text-sm text-red-400">Failed to load matches.</p>}
{data && rows.length === 0 && (
<p className="text-sm text-zinc-500">
Nothing would change{data.already_correct > 0 && ` — all ${data.already_correct} matching transactions already have these values`}.
</p>
)}
{rows.length > 0 && (
<table className="w-full text-xs">
<thead className="sticky top-0 bg-zinc-900">
<tr className="border-b border-zinc-800 text-zinc-500">
<th className="p-2 w-8">
<input
type="checkbox"
checked={allSelected}
onChange={(e) =>
setSelected(e.target.checked ? new Set(rows.map((r) => r.id)) : new Set())
}
/>
</th>
<th className="text-left p-2">Date</th>
<th className="text-left p-2">Description</th>
<th className="text-right p-2">Amount</th>
<th className="text-left p-2">Would change</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.id} className="border-b border-zinc-800/40 hover:bg-zinc-800/30">
<td className="p-2">
<input
type="checkbox"
checked={selected.has(r.id)}
onChange={(e) => {
const next = new Set(selected);
if (e.target.checked) next.add(r.id); else next.delete(r.id);
setSelected(next);
}}
/>
</td>
<td className="p-2 text-zinc-500 whitespace-nowrap">{String(r.transaction_date).slice(0, 10)}</td>
<td className="p-2 text-zinc-300 max-w-[280px] truncate" title={r.description}>
{r.effective_merchant || r.description}
<span className="text-zinc-600 ml-2">{r.bank_name}</span>
</td>
<td className="p-2 text-right tabular-nums text-zinc-400">
{fmt(Number(r.amount_aud ?? r.amount))}
</td>
<td className="p-2 text-amber-400">
{r.changes.map((c, i) => <div key={i}>{describe(c)}</div>)}
</td>
</tr>
))}
</tbody>
</table>
)}
{data?.truncated && (
<p className="text-xs text-zinc-500 mt-2">Showing the first {rows.length} — narrow the rule to see the rest.</p>
)}
</div>
<div className="px-5 py-3 border-t border-zinc-800 flex items-center justify-between">
<span className="text-xs text-zinc-500">
{done ?? `${selected.size} selected · ${fmt(totalValue)}`}
</span>
<div className="flex gap-2">
<button onClick={onClose} className="px-3 py-1.5 text-sm text-zinc-400 hover:text-white">
Close
</button>
<button
disabled={selected.size === 0 || apply.isPending}
onClick={() =>
apply.mutate(
{ ruleId, ids: Array.from(selected) },
{
onSuccess: () => {
setDone(`Applied to ${selected.size} transaction${selected.size !== 1 ? "s" : ""}`);
setSelected(new Set());
},
}
)
}
className="px-3 py-1.5 bg-emerald-700 hover:bg-emerald-600 disabled:opacity-40 rounded text-sm"
>
{apply.isPending ? "Applying…" : `Apply to ${selected.size}`}
</button>
</div>
</div>
</div>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
"use client";
import { useRuleRunDetail } from "@/lib/hooks";
import { formatCategory } from "@/lib/categories";
/**
* The expanded body of an Apply History row: which transactions the run touched
* and what it changed on each, so Revert is an informed decision rather than a
* guess from a count.
*/
function fmt(n: number) {
return new Intl.NumberFormat("en-AU", { style: "currency", currency: "AUD" }).format(n);
}
function describe(c: { field: string; from: string | null; to: string | null }) {
if (c.field === "category") return `${formatCategory(c.from)} → ${formatCategory(c.to)}`;
if (c.field === "merchant") return `${c.from ?? "—"} → ${c.to ?? "—"}`;
if (c.field === "tags") return `+ tag ${c.to}`;
return `split ${c.from ?? "none"} → ${c.to ?? "none"}`;
}
export function RuleRunDetail({ runId }: { runId: number }) {
const { data, isLoading, error } = useRuleRunDetail(runId);
if (isLoading) return <p className="px-4 py-3 text-xs text-zinc-500">Loading…</p>;
if (error) return <p className="px-4 py-3 text-xs text-red-400">Failed to load detail.</p>;
if (!data) return null;
const { transactions, still_changed, run } = data;
return (
<div className="border-t border-zinc-800 bg-zinc-950/60">
<div className="px-4 py-2 text-xs text-zinc-500 flex gap-4 flex-wrap">
<span>{transactions.length} transactions</span>
{run.reverted_at ? (
<span className="text-zinc-500">already reverted — values are back to their originals</span>
) : (
<span className="text-amber-400">{still_changed} still showing this run&apos;s changes</span>
)}
{still_changed < transactions.length && !run.reverted_at && (
<span className="text-zinc-600">
{transactions.length - still_changed} since changed by something else — reverting restores the pre-run value
</span>
)}
</div>
<div className="max-h-72 overflow-auto">
<table className="w-full text-xs">
<thead className="sticky top-0 bg-zinc-950">
<tr className="text-zinc-600 border-b border-zinc-800">
<th className="text-left px-4 py-1.5">Date</th>
<th className="text-left px-3 py-1.5">Transaction</th>
<th className="text-right px-3 py-1.5">Amount</th>
<th className="text-left px-3 py-1.5">Changed</th>
</tr>
</thead>
<tbody>
{transactions.map((t) => (
<tr key={t.id} className="border-b border-zinc-800/40">
<td className="px-4 py-1.5 text-zinc-500 whitespace-nowrap">
{String(t.transaction_date).slice(0, 10)}
</td>
<td className="px-3 py-1.5 text-zinc-300 max-w-[300px] truncate" title={t.description}>
{t.merchant || t.description}
<span className="text-zinc-600 ml-2">{t.bank_name}</span>
</td>
<td className="px-3 py-1.5 text-right tabular-nums text-zinc-400">
{fmt(Number(t.amount_aud ?? t.amount))}
</td>
<td className="px-3 py-1.5">
{t.changes.length === 0 ? (
<span className="text-zinc-600">no change</span>
) : (
t.changes.map((c, i) => (
<div key={i} className="text-amber-400">{describe(c)}</div>
))
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
+12 -5
View File
@@ -7,6 +7,7 @@ import { useState, useEffect } from "react";
const NAV_ITEMS = [
{ href: "/transactions", label: "Transactions", icon: "receipt" },
{ href: "/statements", label: "Statements", icon: "file-text" },
{ href: "/trips", label: "Trips", icon: "map-pin" },
{ href: "/shared", label: "Shared", icon: "users" },
{ href: "/budget", label: "Analytics", icon: "bar-chart" },
{ href: "/insights", label: "Insights", icon: "lightbulb" },
@@ -27,6 +28,12 @@ const ICONS: Record<string, React.ReactNode> = {
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
),
"map-pin": (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
),
users: (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
@@ -85,7 +92,7 @@ export function Sidebar() {
const navContent = (
<>
<div className="p-4 border-b border-zinc-800 flex items-center justify-between">
<h1 className="text-lg font-semibold text-white">Finance</h1>
<h1 className="text-xl text-zinc-100 font-display tracking-tight">Finance<span className="text-indigo-400">.</span></h1>
<button
onClick={() => setOpen(false)}
className="md:hidden p-1 rounded text-zinc-400 hover:text-white hover:bg-zinc-800"
@@ -103,10 +110,10 @@ export function Sidebar() {
<Link
key={item.href}
href={item.href}
className={`flex items-center gap-3 px-3 py-2 rounded-md text-sm mb-0.5 transition-colors ${
className={`relative flex items-center gap-3 px-3 py-2 rounded-md text-sm mb-0.5 transition-colors ${
active
? "bg-zinc-800 text-white"
: "text-zinc-400 hover:text-white hover:bg-zinc-800/50"
? "bg-zinc-800 text-zinc-50 before:absolute before:left-0 before:top-1.5 before:bottom-1.5 before:w-0.5 before:rounded-full before:bg-indigo-400"
: "text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800/50"
}`}
>
{ICONS[item.icon]}
@@ -131,7 +138,7 @@ export function Sidebar() {
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
<span className="ml-3 text-base font-semibold text-white">Finance</span>
<span className="ml-3 text-lg text-zinc-100 font-display tracking-tight">Finance<span className="text-indigo-400">.</span></span>
</div>
{/* Mobile drawer overlay */}
+106
View File
@@ -0,0 +1,106 @@
// Shared SQL fragments for analytics queries, so spend/income semantics stay
// identical across routes.
//
// Two rules every analytics query must follow:
//
// 1. Join `statements` with LEFT JOIN and scope on COALESCE(t.owner_id, s.owner_id).
// An INNER JOIN silently drops every manual/CSV transaction (statement_id IS
// NULL) — which is most of the reconciliation and cash-spend data.
// 2. Exclude `transfers` and `investment` from spend. Once bank statements are
// imported, a credit-card payment appears twice: once as a debit leaving the
// bank account and again as the underlying purchases on the card statement.
// Categorising the money movement as `transfers` and excluding it here is what
// stops the double count. Investments are a balance-sheet move, not spend.
/** Owner scoping that works for both statement-linked and manual transactions. */
export const OWNER_SCOPE = `COALESCE(t.owner_id, s.owner_id)`;
/** Join clause to pair with OWNER_SCOPE. */
export const STATEMENTS_JOIN = `LEFT JOIN statements s ON s.id = t.statement_id`;
/** Transaction types that represent money going out. */
export const SPEND_TYPES = `('debit', 'fee', 'interest')`;
/**
* Rows that count towards spend.
*
* The `interest_amount IS NOT NULL` arm is for loan repayments: when a lender
* itemises principal and interest on a single repayment row, that row is usually
* typed 'payment' (money reducing the loan balance) and would otherwise be
* skipped — but its interest portion is real spend.
*/
export const SPEND_ROWS = `(t.transaction_type IN ('debit', 'fee', 'interest') OR t.interest_amount IS NOT NULL)`;
/**
* The amount of a row that counts as spend, before split adjustment.
*
* For an itemised loan repayment only the interest portion is an expense; the
* principal builds equity and is a balance-sheet move, not spending.
*/
export const SPEND_BASE = `CASE WHEN t.interest_amount IS NOT NULL THEN t.interest_amount ELSE COALESCE(t.amount_aud, t.amount) END`;
/** Effective category, honouring overrides. Never NULL. */
export const EFFECTIVE_CATEGORY = `COALESCE(o.category_override, t.category, 'other')`;
/**
* My percentage share of a transaction, 0-100.
*
* Resolution order:
* 1. An explicit `transaction_splits` row for me.
* 2. The `my_share_percent` override.
* 3. Whatever is left after everyone else's shares.
*
* Step 3 is the one that matters. Assuming 100% when no split row exists for me
* is wrong whenever a transaction is allocated entirely to someone else — I paid,
* they owe all of it, and there is no row for me to find. Those rows would
* otherwise land in my spend at full value.
*
* Requires `transaction_splits ts` joined on `ts.participant_id = <participant>`
* and `transaction_overrides o` joined on the transaction.
*/
export const myShare = (participant = "$1") => `COALESCE(
ts.share_percent,
o.my_share_percent,
100 - COALESCE((
SELECT SUM(x.share_percent) FROM transaction_splits x
WHERE x.transaction_id = t.id AND x.participant_id <> ${participant}
), 0)
)`;
/** `base` scaled to my share. Use for every per-user spend total. */
export const mySplitOf = (base: string, participant = "$1") =>
`((${base}) * ${myShare(participant)} / 100)`;
export const NON_BUDGET_TAGS = ['family'];
export const EXCLUDE_NON_BUDGET_TAGS = `NOT EXISTS (
SELECT 1 FROM transaction_tags tt JOIN tags tg ON tg.id = tt.tag_id
WHERE tt.transaction_id = t.id AND tg.name = ANY(ARRAY['family'])
)`;
/**
* Predicate excluding categories and tags that are not spend.
* The COALESCE matters: a bare `category NOT IN (...)` evaluates to NULL for
* uncategorised rows, which silently drops them from spend totals.
*/
export const EXCLUDE_NON_SPEND = `${EFFECTIVE_CATEGORY} NOT IN ('transfers', 'investment', 'income') AND ${EXCLUDE_NON_BUDGET_TAGS}`;
/**
* Rows that count towards NET spend — outgoings plus the refunds that cancel
* them. Pair with SPEND_SIGNED, which carries the direction.
*/
export const NET_SPEND_ROWS = `(${SPEND_ROWS} OR t.transaction_type IN ('refund', 'credit'))`;
/**
* SPEND_BASE, signed: refunds and credits come back as negatives so they cancel
* the original purchase.
*
* Without this a refund is counted nowhere. It is excluded from spend by type
* and only counted as income if categorised 'income', which a refund is not —
* so it falls through both and never reduces anything. A $2,888.92 Expedia
* purchase refunded in full eight days later still read as $2,888.92 of spend.
*/
export const SPEND_SIGNED = `CASE
WHEN t.transaction_type IN ('refund', 'credit') THEN -(${SPEND_BASE})
ELSE (${SPEND_BASE})
END`;
+5 -1
View File
@@ -25,6 +25,7 @@ export const CATEGORIES = [
"transfers",
"income",
"investment",
"loan_interest",
"personal_care",
"pets",
"gifts",
@@ -35,7 +36,10 @@ export const CATEGORIES = [
export type Category = (typeof CATEGORIES)[number];
export function formatCategory(cat: string): string {
// Tolerates null/undefined: an uncategorised transaction must never be able to
// crash a page that renders its category.
export function formatCategory(cat: string | null | undefined): string {
if (!cat) return "Uncategorised";
return cat
.split("_")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
+48
View File
@@ -0,0 +1,48 @@
export const CATEGORY_COLORS: Record<string, string> = {
groceries: "#22c55e",
dining: "#f97316",
transport: "#06b6d4",
fuel: "#eab308",
shopping: "#ec4899",
utilities: "#8b5cf6",
entertainment: "#f43f5e",
travel: "#0ea5e9",
health: "#10b981",
insurance: "#64748b",
subscriptions: "#a78bfa",
cash_advance: "#dc2626",
government: "#78716c",
education: "#3b82f6",
rent: "#d97706",
transfers: "#6b7280",
income: "#34d399",
investment: "#818cf8",
loan_interest: "#9f1239",
fees: "#f87171",
personal_care: "#fb7185",
pets: "#86efac",
gifts: "#fcd34d",
charity: "#a3e635",
home_goods: "#67e8f9",
home_maintenance: "#c084fc",
other: "#71717a",
};
// Ink & copper chart tokens — keep in sync with the @theme scales in globals.css.
export const CHART = {
accent: "#bc6f30", // copper (indigo-500)
accentSoft: "#d28a47", // copper light (indigo-400)
positive: "#34d399",
negative: "#e35f4b",
axis: "#94896f", // muted paper (zinc-400)
faint: "#6e644f", // zinc-500
grid: "#242019", // zinc-800
dim: "#332d23", // zinc-700 — de-emphasised series
};
export const TOOLTIP_STYLE = {
background: "#171410",
border: "1px solid #332d23",
borderRadius: 8,
fontSize: 12,
};
+5
View File
@@ -15,3 +15,8 @@ if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
export async function queryRaw<T>(sql: string, params: unknown[] = []): Promise<T[]> {
return prisma.$queryRawUnsafe<T[]>(sql, ...params);
}
export async function queryRow<T>(sql: string, params: unknown[] = []): Promise<T | null> {
const rows = await prisma.$queryRawUnsafe<T[]>(sql, ...params);
return rows.length > 0 ? rows[0] : null;
}
+202 -1
View File
@@ -1,7 +1,8 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { TransactionRow, StatementRow, TagRow } from "./queries";
import type { TransactionRow, StatementRow, TagRow, TripRow, TripAnalytics } from "./queries";
export type { TripRow, TripAnalytics };
import type { CurrentUser } from "./auth";
interface TransactionsResponse {
@@ -27,6 +28,7 @@ interface TransactionFilters {
amount_min?: number;
amount_max?: number;
has_split?: string;
trip_id?: string;
}
function buildParams(filters: TransactionFilters): string {
@@ -102,6 +104,7 @@ export function useCreateTransaction() {
transaction_type?: string;
merchant_normalized?: string;
category?: string;
payment_method?: string;
splits?: { participant_id: number; share_percent: number }[];
}) => {
const res = await fetch("/api/transactions", {
@@ -137,6 +140,8 @@ export function useUpdateTransaction() {
description?: string;
amount?: number;
transaction_date?: string;
trip_id?: number | null;
payment_method?: string | null;
}) => {
const res = await fetch(`/api/transactions/${id}`, {
method: "PATCH",
@@ -163,6 +168,7 @@ export function useBulkAction() {
merchant_normalized?: string;
splits?: { participant_id: number; share_percent: number }[];
tag_id?: number;
rule_id?: number;
}) => {
const res = await fetch("/api/transactions/bulk", {
method: "POST",
@@ -185,6 +191,16 @@ export function useBulkAction() {
if (variables.action === "tag" || variables.action === "untag") {
qc.invalidateQueries({ queryKey: ["tags"] });
}
// A quick action can touch category, tags and splits at once, and records
// a revertible run — refresh everything it could have changed.
if (variables.action === "apply_rule") {
qc.invalidateQueries({ queryKey: ["tags"] });
qc.invalidateQueries({ queryKey: ["splits"] });
qc.invalidateQueries({ queryKey: ["shared-transactions"] });
qc.invalidateQueries({ queryKey: ["participant-balances"] });
qc.invalidateQueries({ queryKey: ["analytics"] });
qc.invalidateQueries({ queryKey: ["rule-runs"] });
}
},
});
}
@@ -456,6 +472,8 @@ export interface RuleRow {
conditions: { field: string; operator: string; value: string }[];
actions: { set_category?: string; add_tag_ids?: number[]; set_merchant?: string; apply_split?: { participant_id: number; share_percent: number }[] };
enabled: boolean;
/** Excluded from the apply-all run; fired by hand as a quick action instead. */
manual_only?: boolean;
priority: number;
created_at: string;
}
@@ -512,6 +530,66 @@ export function useDeleteRule() {
});
}
export interface RuleMatchChange {
field: "category" | "merchant" | "tags" | "split";
from: string | null;
to: string;
}
export interface RuleMatchRow {
id: number;
transaction_date: string;
description: string;
amount: number;
amount_aud: number | null;
currency: string;
bank_name: string;
effective_merchant: string;
effective_category: string;
changes: RuleMatchChange[];
}
export interface RuleMatches {
rule: { id: number; name: string; matches_everything: boolean };
total_matched: number;
would_change: number;
already_correct: number;
transactions: RuleMatchRow[];
truncated: boolean;
}
/** Dry run — what a rule would change. Writes nothing. */
export function useRuleMatches(ruleId: number | null) {
return useQuery<RuleMatches>({
queryKey: ["rule-matches", ruleId],
enabled: ruleId != null,
queryFn: async () => {
const res = await fetch(`/api/rules/${ruleId}/matches`);
if (!res.ok) throw new Error("Failed to load rule matches");
return res.json();
},
});
}
/** Apply a rule to a hand-picked set of transactions (conditions ignored). */
export function useApplyRuleToSelection() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ ruleId, ids }: { ruleId: number; ids: number[] }) => {
const res = await fetch("/api/transactions/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "apply_rule", rule_id: ruleId, ids }),
});
if (!res.ok) throw new Error((await res.json()).error || "Failed to apply rule");
return res.json();
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["transactions"] });
qc.invalidateQueries({ queryKey: ["rule-matches"] });
qc.invalidateQueries({ queryKey: ["rules"] });
},
});
}
export function useApplyRules() {
const qc = useQueryClient();
return useMutation({
@@ -539,6 +617,38 @@ export interface RuleRun {
matched: number;
transactions_affected: number;
reverted_at: string | null;
// Provenance (migration 0017). NULL on runs recorded before it existed.
rule_id: number | null;
rule_name: string | null;
source: "all" | "rule" | "selection" | null;
}
export interface RuleRunDetail {
run: RuleRun & { transactions_affected: number };
transactions: {
id: number;
transaction_date: string;
description: string;
amount: number;
amount_aud: number | null;
bank_name: string;
merchant: string | null;
changes: { field: string; from: string | null; to: string | null }[];
}[];
still_changed: number;
}
/** What a run actually did — loaded on demand when a row is expanded. */
export function useRuleRunDetail(runId: number | null) {
return useQuery<RuleRunDetail>({
queryKey: ["rule-run-detail", runId],
enabled: runId != null,
queryFn: async () => {
const res = await fetch(`/api/rules/runs/${runId}`);
if (!res.ok) throw new Error("Failed to load run detail");
return res.json();
},
});
}
export function useRuleRuns() {
@@ -801,3 +911,94 @@ export function useMerchantTransactions(merchant: string | null) {
enabled: !!merchant,
});
}
// ─── Trips ───────────────────────────────────────────────────────────────────
export function useTrips() {
return useQuery<TripRow[]>({
queryKey: ["trips"],
queryFn: async () => (await fetch("/api/trips")).json(),
});
}
export function useTrip(id: number) {
return useQuery<TripRow>({
queryKey: ["trip", id],
queryFn: async () => (await fetch(`/api/trips/${id}`)).json(),
enabled: id > 0,
});
}
export function useTripAnalytics(id: number) {
return useQuery<TripAnalytics>({
queryKey: ["trip-analytics", id],
queryFn: async () => (await fetch(`/api/trips/${id}/analytics`)).json(),
enabled: id > 0,
});
}
export function useCreateTrip() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: Omit<TripRow, "id" | "owner_id" | "created_at" | "total_spend" | "transaction_count">) => {
const res = await fetch("/api/trips", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error((await res.json()).error || "Failed");
return res.json() as Promise<TripRow>;
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["trips"] }),
});
}
export function useUpdateTrip() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, ...data }: Partial<TripRow> & { id: number }) => {
const res = await fetch(`/api/trips/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error((await res.json()).error || "Failed");
return res.json() as Promise<TripRow>;
},
onSuccess: (_d, { id }) => {
qc.invalidateQueries({ queryKey: ["trips"] });
qc.invalidateQueries({ queryKey: ["trip", id] });
qc.invalidateQueries({ queryKey: ["trip-analytics", id] });
},
});
}
export function useDeleteTrip() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: number) => {
await fetch(`/api/trips/${id}`, { method: "DELETE" });
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["trips"] }),
});
}
export function useAssignTransactionsToTrip() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ tripId, transactionIds }: { tripId: number | null; transactionIds: number[] }) => {
const res = await fetch("/api/transactions/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "assign_trip", ids: transactionIds, trip_id: tripId }),
});
if (!res.ok) throw new Error("Failed to assign trip");
return res.json();
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["transactions"] });
qc.invalidateQueries({ queryKey: ["trips"] });
qc.invalidateQueries({ queryKey: ["trip-analytics"] });
},
});
}
+389
View File
@@ -0,0 +1,389 @@
import { queryRaw, queryRow } from "./db";
import type { ParsedOrder } from "./order-parse";
export * from "./order-parse";
export const CUTOVER_DATE = "2026-01-09";
export interface IngestResult {
transactionId: number | null;
metadataId: number | null;
flags: string[];
skipped?: string;
}
/**
* Resolves how much of a card-settled order actually hit the card.
*
* DoorDash writes "MasterCard Ending in 8032 and/or credits" without ever
* stating the split. The split is not in the mail — but it IS in the ledger:
* the card leg arrives on the statement for that card. Reconciling against it
* beats guessing (user, 2026-07-26).
*
* Subway receipt $29.08, statement 8032 charge $13.06 -> $16.02 was credits
* lahori receipt $50.85, statement 8032 charge $50.85 -> fully card
*
* Returns the card amount if a statement line can be matched, else null. A null
* means "unknown", and the caller must not invent a credits figure from it.
*/
export async function reconcileCardLeg(
order: ParsedOrder,
windowDays = 4
): Promise<{ cardAmount: number | null; matchedTransactionId: number | null }> {
const last4 = order.payment.card_last4;
if (!last4) return { cardAmount: null, matchedTransactionId: null };
const day = order.order_datetime.slice(0, 10);
const row = await queryRow<{ id: number; amount: string }>(
`SELECT t.id, t.amount::text
FROM transactions t
JOIN statements s ON s.id = t.statement_id
WHERE replace(s.account_number, '-', '') LIKE $1
AND t.transaction_date BETWEEN $2::date - $4::int AND $2::date + $4::int
AND (t.description ILIKE '%doordash%' OR t.description ILIKE '%uber%')
AND t.amount <= $3::numeric + 0.02
-- A statement line settles exactly one order. Without this, two orders
-- on the same card inside the window both match the same charge and
-- each books its own credits remainder — double-counting spend. At
-- 10-15 orders a month on one card that is not a corner case.
AND NOT EXISTS (
SELECT 1 FROM expense_metadata em
WHERE em.matched_transaction_id = t.id
AND ($5::text IS NULL OR em.order_reference IS DISTINCT FROM $5::text)
)
ORDER BY abs(t.amount - $3::numeric), abs(t.transaction_date - $2::date)
LIMIT 1`,
[`%${last4}`, day, order.totals.total_charged, windowDays, order.order_reference || null]
);
if (!row) return { cardAmount: null, matchedTransactionId: null };
return { cardAmount: Number(row.amount), matchedTransactionId: row.id };
}
async function ensureTag(name: string): Promise<number> {
const existing = await queryRow<{ id: number }>(`SELECT id FROM tags WHERE name = $1`, [name]);
if (existing) return existing.id;
const created = await queryRow<{ id: number }>(
`INSERT INTO tags (name, color) VALUES ($1, '#ef4444')
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name RETURNING id`,
[name]
);
return created!.id;
}
/**
* Records one parsed order.
*
* Invariants enforced here:
* I1 no credits-funded order before the cutover — before it, splits lived in
* another system and re-importing double-counts.
* I5 a card-settled order creates NO transaction. The statement line is the
* transaction; creating another would double-count.
* I6 a credits-funded order creates a transaction for the credits portion at
* face value.
* I7 idempotent on (source, order_reference).
* I11 [Family] orders are imported and tagged, never silently dropped.
*/
export async function processOrderIngestion(
order: ParsedOrder,
options: { messageId?: string; backfillMode?: boolean } = {}
): Promise<IngestResult> {
const flags = [...order.flags];
const day = order.order_datetime.slice(0, 10);
// ---- I7: idempotency ----------------------------------------------------
const existing = await queryRow<{ id: number; transaction_id: number | null }>(
`SELECT id, transaction_id FROM expense_metadata
WHERE source = 'email' AND order_reference = $1`,
[order.order_reference]
);
if (existing) {
return {
transactionId: existing.transaction_id,
metadataId: existing.id,
flags,
skipped: "already_ingested",
};
}
// ---- resolve the credits portion ----------------------------------------
let creditsAmount: number | null = null;
let cardAmount: number | null = order.payment.card_amount;
if (order.payment.ambiguous) {
const { cardAmount: reconciled } = await reconcileCardLeg(order);
if (reconciled === null) {
// No statement line yet. For a live order this is the NORMAL case, not an
// error — card statements arrive monthly, so an order ingested today has
// no card leg in the ledger for weeks (user, 2026-07-26).
//
// Deciding now would mean guessing. Instead the order is recorded as
// provenance with no transaction, and left pending: reconcilePendingOrders()
// resolves it once the statement lands. Backfill hits the same path and
// resolves immediately, because those statements are already imported.
flags.push("awaiting_card_statement");
cardAmount = null;
} else {
cardAmount = reconciled;
const remainder = Number((order.totals.total_charged - reconciled).toFixed(2));
if (remainder > 0.02) {
creditsAmount = remainder;
flags.push(`split_reconciled_card_${reconciled.toFixed(2)}`);
}
}
} else {
creditsAmount = order.payment.credits_amount;
}
// ---- I1: cutover --------------------------------------------------------
if (creditsAmount !== null && day < CUTOVER_DATE) {
return { transactionId: null, metadataId: null, flags, skipped: "pre_cutover" };
}
// ---- I6 / I5 ------------------------------------------------------------
let transactionId: number | null = null;
if (creditsAmount !== null && creditsAmount > 0) {
const isAud = order.currency === "AUD";
if (!isAud) flags.push(`foreign_currency_${order.currency}`);
const txn = await queryRow<{ id: number }>(
`INSERT INTO transactions (
transaction_date, description, amount, amount_aud, category, payment_method,
merchant_name, merchant_normalized, transaction_type,
foreign_currency_amount, foreign_currency_code, owner_id
) VALUES ($1,$2,$3,$4,$5,'credits',$6,$6,'debit',$7,$8,NULL)
RETURNING id`,
[
day,
`Order - ${order.merchant_name}`,
creditsAmount,
// No FX rate is available at ingest, so amount_aud is left NULL for
// foreign orders rather than asserting a conversion we cannot make.
isAud ? creditsAmount : null,
resolveCategory(order),
order.merchant_name,
isAud ? null : creditsAmount,
isAud ? null : order.currency,
]
);
transactionId = txn!.id;
// I11: tag, don't drop. The tag is what removes it from budgets.
if (order.is_family) {
const tagId = await ensureTag("family");
await queryRaw(
`INSERT INTO transaction_tags (transaction_id, tag_id) VALUES ($1,$2)
ON CONFLICT DO NOTHING`,
[transactionId, tagId]
);
}
}
// ---- provenance ---------------------------------------------------------
const pending = flags.includes("awaiting_card_statement");
const meta = await queryRow<{ id: number }>(
`INSERT INTO expense_metadata (
transaction_id, source, source_message_id, order_reference, line_items,
subtotal, amount, merchant_normalized, transaction_date,
card_last4, currency, flags, reconciled_at
) VALUES ($1,'email',$2,$3,$4::jsonb,$5,$6,$7,$8,$9,$10,$11::jsonb,$12)
RETURNING id`,
[
transactionId,
options.messageId || null,
order.order_reference,
JSON.stringify(order.line_items),
order.totals.subtotal,
order.totals.total_charged,
order.merchant_name,
day,
order.payment.card_last4,
order.currency,
JSON.stringify(flags),
pending ? null : new Date().toISOString(),
]
);
return { transactionId, metadataId: meta!.id, flags };
}
/**
* Second pass over orders parked awaiting a card statement.
*
* Run after each statement import. For every pending order it retries the
* reconciliation; once the card leg appears, any remainder above it was paid in
* credits and becomes a transaction at that point. Orders whose card leg covers
* the whole total resolve to "fully card" and correctly create nothing.
*
* Idempotent: a resolved row gets reconciled_at set and is never revisited.
*/
export async function reconcilePendingOrders(): Promise<{
examined: number;
resolved: number;
created: number;
}> {
const pendingRows = await queryRaw<{
id: number;
order_reference: string;
amount: string;
transaction_date: string;
merchant_normalized: string;
card_last4: string | null;
currency: string | null;
}>(
`SELECT id, order_reference, amount::text, transaction_date::text,
merchant_normalized, card_last4, currency
FROM expense_metadata
WHERE transaction_id IS NULL
AND reconciled_at IS NULL
AND card_last4 IS NOT NULL`
);
let resolved = 0;
let created = 0;
for (const row of pendingRows) {
const total = Number(row.amount);
const probe: ParsedOrder = {
order_reference: row.order_reference,
platform: "doordash",
merchant_name: row.merchant_normalized,
order_datetime: `${row.transaction_date}T00:00:00Z`,
currency: row.currency || "AUD",
payment: { credits_amount: null, card_amount: null, card_last4: row.card_last4, ambiguous: true },
totals: {
subtotal: null, taxes: null, delivery_fee: null,
service_fee: null, tip: null, discounts: null, total_charged: total,
},
line_items: [],
is_family: false,
flags: [],
};
const { cardAmount, matchedTransactionId } = await reconcileCardLeg(probe);
if (cardAmount === null) continue; // statement still hasn't arrived
const remainder = Number((total - cardAmount).toFixed(2));
let txnId: number | null = null;
if (remainder > 0.02 && row.transaction_date >= CUTOVER_DATE) {
// Category from the merchant, never hardcoded. Hardcoding 'dining' here
// silently misfiled every grocery order that arrived with an unstated
// split — reintroducing, through the deferred path, exactly the
// misfiling resolveCategory() exists to prevent.
const category = resolveCategory({
merchant_name: row.merchant_normalized,
platform: "doordash",
} as ParsedOrder);
const txn = await queryRow<{ id: number }>(
`INSERT INTO transactions (
transaction_date, description, amount, amount_aud, category,
payment_method, merchant_name, merchant_normalized, transaction_type, owner_id
) VALUES ($1,$2,$3,$3,$5,'credits',$4,$4,'debit',NULL)
RETURNING id`,
[row.transaction_date, `Order - ${row.merchant_normalized}`, remainder, row.merchant_normalized, category]
);
txnId = txn!.id;
created++;
}
await queryRaw(
`UPDATE expense_metadata
SET transaction_id = COALESCE($2, transaction_id),
matched_transaction_id = $4,
reconciled_at = NOW(),
flags = flags || $3::jsonb
WHERE id = $1`,
[row.id, txnId, JSON.stringify([`card_leg_${cardAmount.toFixed(2)}`]), matchedTransactionId]
);
resolved++;
}
return { examined: pendingRows.length, resolved, created };
}
/**
* Category from the merchant.
*
* The spec's Correction 1 said never default to `dining`, because ~19% of the
* corpus is groceries and a blanket dining default misfiles a fifth of orders.
* That reasoning is right about groceries and wrong about the remedy: the
* earlier implementation sent everything unrecognised to `other`, and since it
* knew six merchants, that meant Carl's Jr, Taco Bell, Chilli India, Oporto,
* Hungry Jacks, Schnitz, Subway, Souvlaki GR and the rest all landed in
* `other` — worse than the problem it avoided.
*
* Deliberate reversal: grocery merchants are a closed, enumerable set;
* restaurants are an open one. So match groceries explicitly and let the
* residual be `dining`, which is what a delivery order otherwise is. A
* misfiled grocer is one rule away from fixed; a corpus in `other` is not.
*/
export function resolveCategory(order: ParsedOrder): string {
if (order.platform === "uber") return "transport";
const m = order.merchant_name.toLowerCase();
if (/woolworths|aldi|coles|glomark|keells|cargills|iga|costco/.test(m)) return "groceries";
return "dining";
}
/**
* Applies a refund / total-adjustment notice to an already-ingested order.
*
* The order it amends is matched by the UUID Uber reuses across the original
* receipt and the amendment. The recorded transaction is reduced to the new
* total rather than a compensating negative row being added: the order is one
* event and its cost changed, and a second row would misreport both the meal
* count and the merchant's spend.
*
* If the original has not been ingested (amendment arrived first, or the
* receipt predates the cutover), nothing is invented — the amendment is
* recorded as unmatched for a later pass.
*/
export async function applyOrderAmendment(a: {
order_reference: string | null;
new_total: number;
refund_amount: number | null;
previous_total: number | null;
order_datetime: string;
messageId: string;
}): Promise<{ matched: boolean; transactionId: number | null; adjusted: number | null }> {
if (!a.order_reference) return { matched: false, transactionId: null, adjusted: null };
const meta = await queryRow<{ id: number; transaction_id: number | null; amount: string }>(
`SELECT id, transaction_id, amount::text FROM expense_metadata
WHERE source = 'email' AND order_reference = $1`,
[a.order_reference]
);
if (!meta) return { matched: false, transactionId: null, adjusted: null };
await queryRaw(
`UPDATE expense_metadata
SET amount = $2,
flags = flags || $3::jsonb
WHERE id = $1`,
[
meta.id,
a.new_total,
JSON.stringify([
`amended_from_${Number(meta.amount).toFixed(2)}`,
a.refund_amount !== null ? `refund_${a.refund_amount.toFixed(2)}` : "amended",
]),
]
);
if (meta.transaction_id === null) {
// Card-settled or still pending: no transaction of ours to reduce. The
// refund will show on the statement in its own right.
return { matched: true, transactionId: null, adjusted: null };
}
await queryRaw(
`UPDATE transactions
SET amount = $2,
amount_aud = CASE WHEN foreign_currency_code IS NULL THEN $2 ELSE amount_aud END
WHERE id = $1`,
[meta.transaction_id, a.new_total]
);
return { matched: true, transactionId: meta.transaction_id, adjusted: a.new_total };
}
+545
View File
@@ -0,0 +1,545 @@
/**
* Order receipt parsing, written against REAL captured emails.
*
* History: the first version of this parser was written against synthetic
* fixtures that were shaped to match the code rather than the mail. It invented
* a <table><tr><td>Label</td><td>$X</td></tr> layout that DoorDash does not
* send, derived order_reference from Math.random(), and read the order date
* from a `Date: YYYY-MM-DD` string that appears in no real message. All of it
* passed its tests. This version is built from 36 real DoorDash and 29 real
* Uber Eats receipts; see docs in memory-bank/order-ingestion-implementation.md.
*
* Governing rule: parse or throw. Never fabricate a value that the mail did not
* state (I9). A caller that gets a ParsedOrder back can trust every field in it.
*/
export interface LineItem {
qty: number;
description: string;
amount: number;
options?: string[];
}
export interface PaymentBreakdown {
credits_amount: number | null;
card_amount: number | null;
card_last4: string | null;
/** true when the mail states a payment method it does not fully disaggregate. */
ambiguous: boolean;
}
export interface OrderTotals {
subtotal: number | null;
taxes: number | null;
delivery_fee: number | null;
service_fee: number | null;
tip: number | null;
discounts: number | null;
total_charged: number;
}
export interface ParsedOrder {
order_reference: string;
platform: "doordash" | "ubereats" | "uber";
merchant_name: string;
order_datetime: string;
currency: string;
payment: PaymentBreakdown;
totals: OrderTotals;
line_items: LineItem[];
is_family: boolean;
flags: string[];
}
/** Everything the parser needs that lives on the message, not in the body. */
export interface MessageMeta {
/** Provider message id. The only stable per-mail identity DoorDash offers. */
messageId: string;
subject: string;
/** ISO 8601. The authoritative order date — the body carries no reliable one. */
receivedAt: string;
sender?: string;
}
/**
* The message is not a receipt at all — a promotion, a delivery update, an
* adjustment or refund notice. Expected traffic. Skipping it is correct and
* must not raise an alert, or the channel becomes noise and gets ignored.
*/
export class NotAReceiptError extends Error {
constructor(message: string, readonly messageId?: string) {
super(message);
this.name = "NotAReceiptError";
}
}
/**
* The message IS a receipt and could not be parsed. This is the failure that
* matters: a provider template change breaks every order at once, silently, and
* the only symptom is spend quietly ceasing to appear. It must alert loudly.
*/
export class OrderParseError extends Error {
constructor(message: string, readonly messageId?: string) {
super(message);
this.name = "OrderParseError";
}
}
const stripTags = (s: string) => s.replace(/<[^>]+>/g, " ");
const decodeEntities = (s: string) =>
s
.replace(/&nbsp;/gi, " ")
.replace(/&amp;/gi, "&")
.replace(/&#39;|&apos;/gi, "'")
.replace(/&quot;/gi, '"')
.replace(/&#36;/g, "$")
.replace(/&hellip;/gi, "…");
const collapse = (s: string) => s.replace(/\s+/g, " ").trim();
/** URL-decodes without throwing on malformed percent-escapes. */
function safeDecode(s: string): string {
try {
return decodeURIComponent(s.replace(/%(?![0-9a-f]{2})/gi, "%25"));
} catch {
return s;
}
}
const money = (raw: string): number => Math.abs(parseFloat(raw.replace(/[$,]/g, "")));
/**
* DoorDash renders each total as its own nested table:
* <td align="left" ...>Subtotal</td> <!----> <td align="right" ...>$22.10</td>
* Reading the pair structurally is what stops the label/value rebinding that
* flattening causes (I9) — flattened, "Discounts -$24.09 Total Charged $14.64"
* invites a regex to bind the wrong number to the wrong label.
*/
function tdPairValue(html: string, label: string): number | null {
const re = new RegExp(
`<td[^>]*>\\s*${label}\\s*</td>\\s*<td[^>]*>\\s*(-?\\s*\\$?[\\d,]+\\.\\d{2})\\s*</td>`,
"i"
);
const m = html.match(re);
return m ? money(m[1]) : null;
}
function parseDoorDashLineItems(html: string): LineItem[] {
// <td width="10%">1x</td><td width="75%"><b>Name</b> (Cat)<br><font>• Opt</font>…</td><td width="15%">$22.10</td>
const re =
/<td[^>]*width="10%"[^>]*>\s*(\d+)x\s*<\/td>\s*<td[^>]*width="75%"[^>]*>([\s\S]*?)<\/td>\s*<td[^>]*width="15%"[^>]*>\s*\$?([\d,]+\.\d{2})\s*<\/td>/gi;
const items: LineItem[] = [];
for (const m of html.matchAll(re)) {
const parts = decodeEntities(stripTags(m[2]))
.split("•")
.map((p) => collapse(p))
.filter(Boolean);
if (!parts.length) continue;
items.push({
qty: parseInt(m[1], 10),
description: parts[0],
amount: money(m[3]),
options: parts.slice(1),
});
}
return items;
}
/** Reads "<Label> [CUR] 1,234.56" out of already-flattened Uber receipt text. */
function extractLabelled(text: string, label: string): number | null {
const m = text.match(
new RegExp(`${label}\\s*(?:[A-Z]{3})?\\s*\\$?\\s*([\\d,]+\\.\\d{2})`, "i")
);
return m ? money(m[1]) : null;
}
function detectPlatform(meta: MessageMeta, html: string): ParsedOrder["platform"] {
const s = meta.subject || "";
const from = (meta.sender || "").toLowerCase();
if (/doordash/i.test(from) || /^\s*(\[Family\]\s*)?Order Confirmation for/i.test(s)) {
return "doordash";
}
if (/order with Uber Eats/i.test(s)) return "ubereats";
if (/trip with Uber|Uber receipt|Trip fare/i.test(s) || /Trip fare/i.test(html)) return "uber";
throw new NotAReceiptError(`cannot determine platform from subject: ${s}`, meta.messageId);
}
function parseMerchant(platform: string, meta: MessageMeta, text: string): string {
if (platform === "doordash") {
// Subject: "Order Confirmation for Siddharth from Mad Mex"
const m = meta.subject.match(/Order Confirmation for \S+\s+from\s+([\s\S]+?)\s*$/i);
if (m) return collapse(m[1]);
}
if (platform === "ubereats") {
// Body: "Here's your receipt for TEG Kebabs & Biryani."
const m = text.match(/receipt for\s+([\s\S]+?)\s*\.\s/i);
if (m) return collapse(m[1]);
}
if (platform === "uber") return "Uber Trip";
throw new OrderParseError(`cannot determine merchant`, meta.messageId);
}
function parsePayment(platform: string, html: string, text: string): PaymentBreakdown {
// eslint-disable-next-line no-param-reassign
const out: PaymentBreakdown = {
credits_amount: null,
card_amount: null,
card_last4: null,
ambiguous: false,
};
if (platform === "doordash") {
// Match the instrument directly. An earlier version captured a trailing
// window delimited by a double space, which does not survive whitespace
// collapsing — so every card/mixed receipt fell through to the credits
// branch and booked the full total as credits.
if (/Paid with[\s\S]{0,60}?and\/or\s*credits/i.test(text)) {
out.ambiguous = true;
const l4 = text.match(/Paid with[\s\S]{0,60}?Ending in\s*(\d{3,4})/i);
out.card_last4 = l4 ? l4[1] : null;
return out;
}
const card = text.match(/Paid with[\s\S]{0,40}?Ending in\s*(\d{3,4})/i);
if (card) {
out.card_last4 = card[1];
return out; // card-only; amount filled from total
}
if (/Paid with\s+credits/i.test(text)) return out; // credits-only
return out;
}
// Uber Eats / Uber: "Payments Uber Cash $25.33", or a card line, or — on
// [Family] orders placed on a shared account — just the payer's name:
// "Payments Siddharth LKR 3,783.20". That last form names no instrument at
// all, so the split cannot be read from the mail and must not be invented.
// A declined attempt is still printed, immediately followed by "Failed":
// Visa ••••8841 LKR 4,267.01 7/5/26 7:20 pm Failed
// Siddharth LKR 3,757.01 7/5/26 9:02 pm
// (grocery order re-charged lower after sold-out items). Taking the first
// match would record money that never left the account, so drop the failed
// attempts before reading any instrument.
text = text.replace(
/(?:Visa|MasterCard|Amex|American Express|Uber Cash)[^.]{0,40}?[\d,]+\.\d{2}\s+\S+\s+\S+\s*(?:am|pm)?\s*Failed/gi,
" "
);
const cash = text.match(/Uber Cash\s*(?:[A-Z]{3})?\s*\$?([\d,]+\.\d{2})/i);
if (cash) out.credits_amount = money(cash[1]);
const card = text.match(
/(?:Visa|MasterCard|American Express|Amex)[^\d]*(\d{4})[^\d]*(?:[A-Z]{3})?\s*\$?([\d,]+\.\d{2})/i
);
if (card) {
out.card_last4 = card[1];
out.card_amount = money(card[2]);
}
if (!cash && !card && /Payments\s+\S+\s+(?:[A-Z]{3}\s|\$)/.test(text)) {
out.ambiguous = true;
}
return out;
}
export function parseOrderHTML(html: string, meta: MessageMeta): ParsedOrder {
if (!html || html.length < 200) {
throw new NotAReceiptError("body too short to be a receipt", meta.messageId);
}
const clean = html.replace(/<!--[\s\S]*?-->/g, "");
const text = collapse(decodeEntities(stripTags(clean)));
const flags: string[] = [];
let explicitCurrency: string | null = null;
// Grocery orders (ALDI, Woolworths) generate a follow-up "There are
// adjustments to your order" mail for out-of-stock and substituted items. It
// reuses the receipt layout but states `Total: $0.00` — the real amount is
// settled later. Ingesting it would book a $0.00 order and, worse, its
// order_reference would collide with nothing and create a phantom row.
// Refund / total-adjustment mails ("We adjusted the total for your recent
// order", "Previous total ... Refund ... New Total"). These restate an order
// already ingested and must be applied as an amendment, not inserted as a new
// order. Amendment handling is not in this pass — reject loudly so none is
// silently double-counted.
if (/We adjusted the total|Your refund has been applied|Previous total/i.test(text)) {
throw new NotAReceiptError(
"refund/total-adjustment notice — amends an existing order, not a new receipt",
meta.messageId
);
}
if (/There are adjustments to your order/i.test(text)) {
throw new NotAReceiptError(
"order-adjustment notice, not a receipt — no final total stated",
meta.messageId
);
}
const platform = detectPlatform(meta, text);
const merchant_name = parseMerchant(platform, meta, text);
// ---- order_reference -----------------------------------------------------
// Uber embeds a real order UUID in the body. DoorDash embeds no order id at
// all, so the provider message id is the only stable identity available —
// which is correct for ingestion idempotency (one receipt = one order).
//
// Anchor on Uber's own `tripReference` cell — a hidden
// <td class="tripReference">xid<UUID></td> present in all 29 captured
// receipts. For ue-00 it equals the UUID the PDF redirect resolves to
// (ubereats.com/orders/34d6b4ee-...), so it is the order's real identity.
//
// The alternative, "first UUID in the document", is positional rather than
// semantic: 4 of 29 receipts carry several UUIDs, and if a template reshuffle
// ever put a per-send tracking id first, the symptom would be a reference
// that changes every fetch and silently duplicates every order on every
// backfill. Fall back to it only when the anchor is absent, and flag when
// that fallback is genuinely ambiguous.
let order_reference: string;
const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
const anchored = clean.match(
/tripReference[^>]*>\s*xid([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
);
const firstUuid = clean.match(UUID_RE);
if (platform !== "doordash" && (anchored || firstUuid)) {
order_reference = (anchored ? anchored[1] : firstUuid![0]).toLowerCase();
if (!anchored) {
const distinct = new Set(
(clean.match(new RegExp(UUID_RE.source, "gi")) || []).map((u) => u.toLowerCase())
);
// Only ambiguous when there is more than one candidate to choose between.
if (distinct.size > 1) flags.push("order_uuid_ambiguous");
}
} else {
// DoorDash carries no order id anywhere in the receipt, so the provider
// message id is the only stable identity available. That is correct for
// ingestion idempotency: one receipt is one order.
if (!meta.messageId) {
throw new OrderParseError("no order id in body and no messageId supplied");
}
order_reference = `msg:${meta.messageId}`;
}
// ---- date ----------------------------------------------------------------
// From the message, never the body. DoorDash confirmations are sent at order
// time; the body's own date strings are inconsistent and locale-formatted.
const received = new Date(meta.receivedAt);
if (isNaN(received.getTime())) {
throw new OrderParseError(`unparseable receivedAt: ${meta.receivedAt}`, meta.messageId);
}
const order_datetime = received.toISOString();
// ---- [Family] ------------------------------------------------------------
// A subject prefix on Uber Eats: "[Family] Your Sunday evening order with…".
// Deliberately anchored — a bare substring search for "family" matches
// footer copy and merchant names, and a false positive here silently drops
// the order out of every budget.
const is_family = /^\s*\[Family\]/i.test(meta.subject || "");
// ---- totals --------------------------------------------------------------
let totals: OrderTotals;
if (platform === "doordash") {
// Grocery "Final receipt" mails price each item and carry no Total Charged
// row; the only stated total is the header. Fall back to it explicitly
// rather than letting a partial total through.
const headerTotal = text.match(/Total:\s*\$?([\d,]+\.\d{2})/i);
const total =
tdPairValue(clean, "Total Charged") ??
tdPairValue(clean, "Total") ??
(headerTotal ? money(headerTotal[1]) : null);
if (total === null) {
throw new OrderParseError("no total stated anywhere in receipt", meta.messageId);
}
totals = {
subtotal: tdPairValue(clean, "Subtotal"),
taxes: tdPairValue(clean, "Taxes"),
delivery_fee: tdPairValue(clean, "Delivery Fee"),
service_fee: tdPairValue(clean, "Service Fee"),
tip: tdPairValue(clean, "Tip"),
discounts: tdPairValue(clean, "Discounts"),
total_charged: total,
};
} else {
// Uber Eats states a Total, optionally in a foreign currency:
// "Total $25.33" | "Total LKR 3,783.20"
// The [Family] orders are placed for family in Sri Lanka and are priced in
// LKR — reading those as dollars would inflate them ~200x, which is a large
// part of why they must not reach a budget untagged.
const m = text.match(/(?:New Total|Total)\s*(?:([A-Z]{3})\s*)?\$?\s*([\d,]+\.\d{2})/);
if (!m) throw new OrderParseError("no Total found", meta.messageId);
totals = {
subtotal: extractLabelled(text, "Item subtotal"),
taxes: extractLabelled(text, "Tax"),
delivery_fee: extractLabelled(text, "Delivery Fee"),
service_fee: extractLabelled(text, "Service Fee"),
tip: null,
discounts: null,
total_charged: money(m[2]),
};
if (m[1]) explicitCurrency = m[1].toUpperCase().replace(/\$$/, "");
}
// ---- payment -------------------------------------------------------------
const payment = parsePayment(platform, clean, text);
if (payment.ambiguous && is_family) {
// [Family] receipts name the payer, not an instrument ("Payments Siddharth
// LKR 3,783.20"), so no split is recoverable and there is no card leg to
// reconcile against — parking them would mean never importing them, which
// fails the actual requirement (import, tag, exclude from budgets).
// Treated as credits so the order is recorded and tagged. Safe because the
// family tag removes it from every budget regardless of instrument.
payment.ambiguous = false;
payment.credits_amount = totals.total_charged;
flags.push("family_payment_assumed_credits");
} else if (payment.ambiguous) {
// Split not stated and resolvable from the card statement — left for the
// ingestion runner to reconcile, not guessed here.
flags.push("payment_split_not_stated");
} else if (platform === "doordash") {
// DoorDash names the method but not the amount; the total is the amount.
if (payment.card_last4) payment.card_amount = totals.total_charged;
else payment.credits_amount = totals.total_charged;
}
// ---- line items ----------------------------------------------------------
// Uber Eats receipts carry no itemisation (verified across 29 real mails).
const line_items =
platform === "doordash" ? parseDoorDashLineItems(clean) : [];
if (platform === "doordash" && line_items.length === 0) {
flags.push("no_line_items_parsed");
}
const currency =
explicitCurrency ||
(/\b(NZD|USD|LKR|CHF|EUR|GBP|SGD|INR)\b/.test(text)
? (text.match(/\b(NZD|USD|LKR|CHF|EUR|GBP|SGD|INR)\b/) as RegExpMatchArray)[1]
: "AUD");
return {
order_reference,
platform,
merchant_name,
order_datetime,
currency,
payment,
totals,
line_items,
is_family,
flags,
};
}
/**
* Integrity check on the amount we are about to record as spend.
*
* NOT an arithmetic reconciliation of the fee breakdown. Measured against 36
* real DoorDash receipts, the components do not sum to the total on 32 of them:
* DoorDash's `Discounts` line frequently equals subtotal + service fee exactly
* (Mad Mex: subtotal 22.10, service 1.99, Discounts -24.09, Total Charged
* 14.64) and sometimes differs by an unrelated margin. Whatever that line means
* to DoorDash, it is not a term in `total = components`.
*
* This corrects an earlier diagnosis that read the same numbers as an
* HTML-flattening artefact with a "true discount of $9.45". Parsing the table
* cells structurally yields the identical figures, and no $9.45 appears
* anywhere in the message — the receipt genuinely says this.
*
* So the breakdown is stored as provenance and never gated on. What IS checked
* is the number that becomes money in the ledger: DoorDash states the total
* twice, independently (a `Total: $X` header and a `Total Charged` table row),
* and those must agree. That catches a mis-parse, which is the failure that
* actually matters.
*/
export function validateOrderTotals(
order: ParsedOrder,
html?: string
): { ok: boolean; reason?: string } {
const t = order.totals;
if (!(t.total_charged > 0)) {
return { ok: false, reason: `non-positive total ${t.total_charged}` };
}
// Cross-check the header total against the table total where both exist.
if (html && order.platform === "doordash") {
const header = collapse(decodeEntities(stripTags(html))).match(
/Total:\s*\$?([\d,]+\.\d{2})/i
);
if (header) {
const stated = money(header[1]);
if (Math.abs(stated - t.total_charged) > 0.02) {
return {
ok: false,
reason: `header total ${stated.toFixed(2)} disagrees with Total Charged ${t.total_charged.toFixed(2)}`,
};
}
}
}
// The payment line must account for the total, or we are recording an amount
// no stated payment method covers.
if (!order.payment.ambiguous) {
const paid = (order.payment.credits_amount || 0) + (order.payment.card_amount || 0);
if (paid > 0 && Math.abs(paid - t.total_charged) > 0.02) {
return {
ok: false,
reason: `payments sum to ${paid.toFixed(2)} but receipt states ${t.total_charged.toFixed(2)}`,
};
}
}
return { ok: true };
}
export interface OrderAmendment {
order_reference: string | null;
previous_total: number | null;
refund_amount: number | null;
new_total: number;
order_datetime: string;
messageId: string;
}
/**
* Refund / total-adjustment notices restate an order that was already ingested:
*
* "We adjusted the total for your recent order from Coles (Wyndham Vale)."
* Previous total $49.94 · Refund -$4.21 · New Total $45.73
*
* These are amendments, not receipts — inserting one as a new order would
* double-count the meal and hide the refund. Uber embeds the same order UUID it
* used on the original receipt, so the amendment can be matched back to it.
*/
export function parseOrderAmendment(html: string, meta: MessageMeta): OrderAmendment {
const clean = html.replace(/<!--[\s\S]*?-->/g, "");
const text = collapse(decodeEntities(stripTags(clean)));
if (!/We adjusted the total|Your refund has been applied|Previous total/i.test(text)) {
throw new OrderParseError("not an amendment notice", meta.messageId);
}
const newTotal = text.match(/New Total\s*(?:[A-Z]{3})?\s*\$?\s*([\d,]+\.\d{2})/i);
if (!newTotal) {
throw new OrderParseError("amendment states no New Total", meta.messageId);
}
const prev = text.match(/Previous total\s*(?:[A-Z]{3})?\s*\$?\s*([\d,]+\.\d{2})/i);
const refund = text.match(/Refund\s*-?\s*(?:[A-Z]{3})?\s*\$?\s*([\d,]+\.\d{2})/i);
const uuid = clean.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);
const received = new Date(meta.receivedAt);
if (isNaN(received.getTime())) {
throw new OrderParseError(`unparseable receivedAt: ${meta.receivedAt}`, meta.messageId);
}
return {
order_reference: uuid ? uuid[0].toLowerCase() : null,
previous_total: prev ? money(prev[1]) : null,
refund_amount: refund ? money(refund[1]) : null,
new_total: money(newTotal[1]),
order_datetime: received.toISOString(),
messageId: meta.messageId,
};
}
/** True when a message is an amendment rather than a receipt. */
export function isAmendment(html: string): boolean {
const text = collapse(decodeEntities(stripTags(html.replace(/<!--[\s\S]*?-->/g, ""))));
return /We adjusted the total|Your refund has been applied|Previous total/i.test(text);
}
+359 -3
View File
@@ -22,6 +22,12 @@ export interface TransactionRow {
category: string;
row_index: number;
created_at: string;
// loan repayment split — set only when the lender itemises it (migration 0014)
principal_amount: number | null;
interest_amount: number | null;
// How it was paid (migration 0016). NULL = unknown, treated as reconcilable.
// 'cash' is excluded from reconciliation — see notCash().
payment_method: string | null;
// override fields
category_override: string | null;
merchant_override: string | null;
@@ -29,14 +35,24 @@ export interface TransactionRow {
my_share_percent: number | null;
effective_category: string;
effective_merchant: string;
// My share of this transaction, resolved server-side so the UI matches analytics.
my_share_pct: number;
my_amount: number;
// statement context (null for manual transactions)
bank_name: string;
// Native currency of the statement this row came from ('AUD' for manual rows).
// `amount` is in this currency; `amount_aud` is the converted figure.
currency: string;
owner_id: number;
owner_name: string;
// tags
tags: TagRow[];
// splits
splits: { participant_id: number; name: string; share_percent: number; settled: boolean }[];
// trip
trip_id: number | null;
trip_name: string | null;
trip_color: string | null;
}
export interface StatementRow {
@@ -60,11 +76,21 @@ export interface StatementRow {
credit_limit: number | null;
currency: string;
statement_type: string | null;
// Loan statements only (see migration 0014)
interest_rate: number | null;
scheduled_repayment: number | null;
repayment_frequency: string | null;
redraw_available: number | null;
loan_term_months: number | null;
tier_used: string | null;
owner_id: number;
owner_name: string;
created_at: string;
transaction_count: number;
// Balance assertion (see BALANCE_DELTA). Null when the statement has no
// opening/closing balance to check against.
expected_closing: number | null;
balance_diff: number | null;
}
interface TransactionFilters {
@@ -83,6 +109,7 @@ interface TransactionFilters {
amount_min?: number;
amount_max?: number;
has_split?: string;
trip_id?: string;
}
export async function getTransactions(ownerId: number, filters: TransactionFilters) {
@@ -154,6 +181,12 @@ export async function getTransactions(ownerId: number, filters: TransactionFilte
} else if (filters.has_split === "no") {
conditions.push(`NOT EXISTS (SELECT 1 FROM transaction_splits ts_f WHERE ts_f.transaction_id = t.id)`);
}
if (filters.trip_id === "unassigned") {
conditions.push(`o.trip_id IS NULL`);
} else if (filters.trip_id) {
conditions.push(`o.trip_id = $${paramIdx++}`);
params.push(Number(filters.trip_id));
}
const where = `WHERE ${conditions.join(" AND ")}`;
@@ -178,9 +211,31 @@ export async function getTransactions(ownerId: number, filters: TransactionFilte
COALESCE(o.category_override, t.category) as effective_category,
COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) as effective_merchant,
COALESCE(s.bank_name, 'Manual') as bank_name,
COALESCE(s.currency, 'AUD') as currency,
-- My share, resolved the same way analytics does it (see myShare in
-- analytics-sql.ts): explicit split row, then override, then whatever is
-- left after everyone else. Computed here so the UI cannot drift from
-- the totals it is drilling into.
COALESCE(
(SELECT x.share_percent FROM transaction_splits x
WHERE x.transaction_id = t.id AND x.participant_id = $1),
o.my_share_percent,
100 - COALESCE((SELECT SUM(x.share_percent) FROM transaction_splits x
WHERE x.transaction_id = t.id AND x.participant_id <> $1), 0)
)::numeric(5,2) as my_share_pct,
(COALESCE(t.amount_aud, t.amount) * COALESCE(
(SELECT x.share_percent FROM transaction_splits x
WHERE x.transaction_id = t.id AND x.participant_id = $1),
o.my_share_percent,
100 - COALESCE((SELECT SUM(x.share_percent) FROM transaction_splits x
WHERE x.transaction_id = t.id AND x.participant_id <> $1), 0)
) / 100)::numeric(12,2) as my_amount,
COALESCE(t.owner_id, s.owner_id) as owner_id,
p.name as owner_name,
COALESCE(src.created_at, t.created_at) as created_at,
o.trip_id,
tr.name as trip_name,
tr.color as trip_color,
txn_tags.tags,
txn_splits.splits
FROM transactions t
@@ -188,6 +243,7 @@ export async function getTransactions(ownerId: number, filters: TransactionFilte
LEFT JOIN statements s ON s.id = t.statement_id
LEFT JOIN participants p ON p.id = COALESCE(t.owner_id, s.owner_id)
LEFT JOIN transactions src ON src.reconciled_with_id = t.id AND src.statement_id IS NULL
LEFT JOIN trips tr ON tr.id = o.trip_id
LEFT JOIN LATERAL (
SELECT COALESCE(json_agg(json_build_object('id', tg.id, 'name', tg.name, 'color', tg.color) ORDER BY tg.name), '[]'::json) as tags
FROM transaction_tags tt
@@ -216,6 +272,22 @@ export async function getTransactions(ownerId: number, filters: TransactionFilte
return { data, total, limit, offset };
}
// A user may act on a transaction they own (directly or via the parent
// statement) or one they participate in via a split.
export async function canAccessTransactions(ownerId: number, transactionIds: number[]): Promise<boolean> {
if (!transactionIds.length) return false;
const rows = await queryRaw<{ n: number }>(
`SELECT COUNT(*)::int AS n
FROM transactions t
LEFT JOIN statements s ON s.id = t.statement_id
WHERE t.id = ANY($2::int[])
AND (COALESCE(t.owner_id, s.owner_id) = $1
OR EXISTS (SELECT 1 FROM transaction_splits ts WHERE ts.transaction_id = t.id AND ts.participant_id = $1))`,
[ownerId, transactionIds]
);
return rows[0]?.n === transactionIds.length;
}
export async function getTransactionById(id: number) {
const sql = `
SELECT t.*,
@@ -235,13 +307,43 @@ export async function getTransactionById(id: number) {
return rows[0] || null;
}
/**
* Does opening_balance + the period's transactions equal closing_balance?
*
* The single cheapest check on extraction quality: it catches missed rows,
* duplicates, sign errors and transactions filed against the wrong statement,
* none of which are visible by eye. Borrowed from double-entry accounting,
* where it is called a balance assertion.
*
* Sign depends on what the balance means. On a liability (credit card, loan)
* the balance is what you OWE, so spending increases it and payments reduce it.
* On an asset (transaction, savings, offset) the balance is what you HOLD, so
* the signs invert.
*/
export const BALANCE_DELTA = `SUM(CASE
WHEN s.statement_type IN ('credit_card', 'loan')
THEN CASE WHEN t.transaction_type IN ('debit', 'fee', 'interest') THEN t.amount ELSE -t.amount END
ELSE CASE WHEN t.transaction_type IN ('debit', 'fee', 'interest') THEN -t.amount ELSE t.amount END
END)`;
export async function getStatements(ownerId: number) {
const sql = `
SELECT s.*,
(SELECT COUNT(*)::int FROM transactions t WHERE t.statement_id = s.id) as transaction_count,
p.name as owner_name
p.name as owner_name,
recon.expected_closing,
recon.balance_diff
FROM statements s
LEFT JOIN participants p ON p.id = s.owner_id
LEFT JOIN LATERAL (
SELECT
(s.opening_balance + ${BALANCE_DELTA})::numeric(12,2) as expected_closing,
(s.opening_balance + ${BALANCE_DELTA} - s.closing_balance)::numeric(12,2) as balance_diff
FROM transactions t
WHERE t.statement_id = s.id
AND s.opening_balance IS NOT NULL
AND s.closing_balance IS NOT NULL
) recon ON true
WHERE s.owner_id = $1
ORDER BY s.billing_end_date DESC NULLS LAST, s.created_at DESC
`;
@@ -322,8 +424,10 @@ export async function getParticipantBalances(ownerId: number, tagIds?: number[])
LEFT JOIN (
-- They owe me: their splits on transactions I own
-- Settle in AUD: on a foreign-currency row the amount column is in its own
-- currency, so splitting on it nets a USD figure against AUD ones.
SELECT ts.participant_id AS pid,
(CASE WHEN t.transaction_type IN ('debit', 'fee', 'interest') THEN t.amount ELSE -t.amount END) * ts.share_percent / 100 AS signed_amount,
(CASE WHEN t.transaction_type IN ('debit', 'fee', 'interest') THEN COALESCE(t.amount_aud, t.amount) ELSE -COALESCE(t.amount_aud, t.amount) END) * ts.share_percent / 100 AS signed_amount,
1 AS split_count
FROM transaction_splits ts
JOIN transactions t ON t.id = ts.transaction_id
@@ -336,7 +440,7 @@ export async function getParticipantBalances(ownerId: number, tagIds?: number[])
-- I owe them: my splits on transactions they own
SELECT COALESCE(t.owner_id, s.owner_id) AS pid,
-((CASE WHEN t.transaction_type IN ('debit', 'fee', 'interest') THEN t.amount ELSE -t.amount END) * ts.share_percent / 100) AS signed_amount,
-((CASE WHEN t.transaction_type IN ('debit', 'fee', 'interest') THEN COALESCE(t.amount_aud, t.amount) ELSE -COALESCE(t.amount_aud, t.amount) END) * ts.share_percent / 100) AS signed_amount,
0 AS split_count
FROM transaction_splits ts
JOIN transactions t ON t.id = ts.transaction_id
@@ -416,6 +520,22 @@ export async function batchInsertCSVTransactions(
return txIds.length;
}
/**
* Excludes cash from reconciliation.
*
* Cash never appears on a statement, so a cash transaction would sit in the
* queue forever being offered matches within 3 days and 1% on amount. Accepting
* one is silently destructive: reconciled manual rows are filtered out of every
* query, so the cash spend vanishes while the card transaction it matched
* claims to be that same spend.
*
* Only cash is excluded. Bank transfers do appear on a statement now that
* transaction accounts are imported, and NULL means unknown — both stay
* candidates, which preserves the behaviour of every pre-existing row.
*/
export const notCash = (alias = "t") =>
`(${alias}.payment_method IS NULL OR ${alias}.payment_method <> 'cash')`;
export interface PotentialMatch {
id: number;
transaction_date: string;
@@ -458,6 +578,7 @@ export async function getPendingReconciliations(ownerId: number): Promise<Manual
WHERE ts.transaction_id = t.id
) txn_splits ON true
WHERE t.statement_id IS NULL AND t.owner_id = $1 AND t.reconciled_with_id IS NULL
AND ${notCash("t")}
ORDER BY t.transaction_date DESC, t.row_index ASC`,
[ownerId]
);
@@ -499,6 +620,7 @@ export async function getPendingReconciliations(ownerId: number): Promise<Manual
WHERE m.statement_id IS NULL
AND m.owner_id = $1
AND m.reconciled_with_id IS NULL
AND ${notCash("m")}
AND COALESCE(t.owner_id, s.owner_id) = $1
AND NOT EXISTS (
SELECT 1 FROM transactions mt WHERE mt.reconciled_with_id = t.id
@@ -604,3 +726,237 @@ export async function getSharedTransactions(ownerId: number, tagIds?: number[],
splits: typeof r.split_data === "string" ? JSON.parse(r.split_data) : r.split_data,
}));
}
// ─── Trips ───────────────────────────────────────────────────────────────────
export interface TripRow {
id: number;
owner_id: number;
name: string;
description: string | null;
start_date: string | null;
end_date: string | null;
color: string;
archived: boolean;
created_at: string;
total_spend: number;
transaction_count: number;
}
export interface TripAnalytics {
trip: TripRow;
total_spend: number;
transaction_count: number;
num_days: number;
daily_average: number;
category_breakdown: { category: string; amount: number; count: number }[];
daily_spend: { date: string; amount: number }[];
top_merchants: { merchant: string; amount: number; count: number }[];
tag_breakdown: { tag_id: number; name: string; color: string; amount: number; count: number }[];
participant_splits: { participant_id: number; name: string; owed: number }[];
}
export async function getTrips(ownerId: number): Promise<TripRow[]> {
return queryRaw<TripRow>(`
SELECT
t.*,
COALESCE(SUM(
CASE WHEN tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
THEN COALESCE(tx.amount_aud, tx.amount) ELSE 0 END
), 0)::float AS total_spend,
COUNT(o.transaction_id)::int AS transaction_count
FROM trips t
LEFT JOIN transaction_overrides o ON o.trip_id = t.id
LEFT JOIN transactions tx ON tx.id = o.transaction_id
WHERE t.owner_id = $1
GROUP BY t.id
ORDER BY t.created_at DESC
`, [ownerId]);
}
export async function getTripById(id: number, ownerId: number): Promise<TripRow | null> {
const rows = await queryRaw<TripRow>(`
SELECT
t.*,
COALESCE(SUM(
CASE WHEN tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
THEN COALESCE(tx.amount_aud, tx.amount) ELSE 0 END
), 0)::float AS total_spend,
COUNT(o.transaction_id)::int AS transaction_count
FROM trips t
LEFT JOIN transaction_overrides o ON o.trip_id = t.id
LEFT JOIN transactions tx ON tx.id = o.transaction_id
WHERE t.id = $1 AND t.owner_id = $2
GROUP BY t.id
`, [id, ownerId]);
return rows[0] ?? null;
}
export async function getTripAnalytics(tripId: number, ownerId: number): Promise<TripAnalytics> {
const trip = await getTripById(tripId, ownerId);
if (!trip) throw new Error("Trip not found");
const [categoryRows, dailyRows, merchantRows, tagRows, splitRows] = await Promise.all([
queryRaw<{ category: string; amount: number; count: number }>(`
SELECT
COALESCE(o.category_override, tx.category, 'other') AS category,
SUM(COALESCE(tx.amount_aud, tx.amount))::float AS amount,
COUNT(*)::int AS count
FROM transaction_overrides o
JOIN transactions tx ON tx.id = o.transaction_id
WHERE o.trip_id = $1
AND tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
GROUP BY 1
ORDER BY 2 DESC
`, [tripId]),
queryRaw<{ date: string; amount: number }>(`
SELECT
tx.transaction_date::text AS date,
SUM(COALESCE(tx.amount_aud, tx.amount))::float AS amount
FROM transaction_overrides o
JOIN transactions tx ON tx.id = o.transaction_id
WHERE o.trip_id = $1
AND tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
GROUP BY 1
ORDER BY 1
`, [tripId]),
queryRaw<{ merchant: string; amount: number; count: number }>(`
SELECT
COALESCE(o.merchant_normalized, tx.merchant_normalized, tx.merchant_name, tx.description) AS merchant,
SUM(COALESCE(tx.amount_aud, tx.amount))::float AS amount,
COUNT(*)::int AS count
FROM transaction_overrides o
JOIN transactions tx ON tx.id = o.transaction_id
WHERE o.trip_id = $1
AND tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10
`, [tripId]),
queryRaw<{ tag_id: number; name: string; color: string; amount: number; count: number }>(`
SELECT
tg.id AS tag_id, tg.name, tg.color,
SUM(COALESCE(tx.amount_aud, tx.amount))::float AS amount,
COUNT(DISTINCT tx.id)::int AS count
FROM transaction_overrides o
JOIN transactions tx ON tx.id = o.transaction_id
JOIN transaction_tags tt ON tt.transaction_id = tx.id
JOIN tags tg ON tg.id = tt.tag_id
WHERE o.trip_id = $1
AND tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
GROUP BY tg.id
ORDER BY 4 DESC
`, [tripId]),
// No settled/unsettled breakdown here. It was computed from
// transaction_splits.settled, which only /api/splits/settle writes and
// nothing in the UI calls — so it is false on all 673 splits and every trip
// reported 100% unsettled, including trips paid in full. A real per-trip
// figure is not computable either: split_payments carries no trip
// attribution, so a payment cannot be assigned to a trip. Settlement is a
// property of the whole relationship until settlement contexts exist
// (see docs/shared-expenses-design.md).
queryRaw<{ participant_id: number; name: string; owed: number }>(`
SELECT
p.id AS participant_id,
p.name,
SUM(ts.share_percent / 100.0 * COALESCE(tx.amount_aud, tx.amount))::float AS owed
FROM transaction_overrides o
JOIN transactions tx ON tx.id = o.transaction_id
JOIN transaction_splits ts ON ts.transaction_id = tx.id
JOIN participants p ON p.id = ts.participant_id
WHERE o.trip_id = $1
AND tx.transaction_type IN ('debit','fee','interest')
AND COALESCE(o.category_override, tx.category, 'other') NOT IN ('transfers', 'investment')
GROUP BY p.id
ORDER BY 3 DESC
`, [tripId]),
]);
const num_days = (trip.start_date && trip.end_date)
? Math.max(1, Math.round((new Date(trip.end_date).getTime() - new Date(trip.start_date).getTime()) / 86400000) + 1)
: Math.max(dailyRows.length, 1);
return {
trip,
total_spend: trip.total_spend,
transaction_count: trip.transaction_count,
num_days,
daily_average: trip.total_spend / num_days,
category_breakdown: categoryRows,
daily_spend: dailyRows,
top_merchants: merchantRows,
tag_breakdown: tagRows,
participant_splits: splitRows,
};
}
export async function createTrip(
ownerId: number,
data: { name: string; description?: string | null; start_date?: string | null; end_date?: string | null; color?: string }
): Promise<TripRow> {
const rows = await queryRaw<TripRow>(`
INSERT INTO trips (owner_id, name, description, start_date, end_date, color)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *, 0::float AS total_spend, 0::int AS transaction_count
`, [ownerId, data.name, data.description ?? null, data.start_date ?? null, data.end_date ?? null, data.color ?? '#6366f1']);
return rows[0];
}
export async function updateTrip(
id: number,
ownerId: number,
data: Partial<{ name: string; description: string | null; start_date: string | null; end_date: string | null; color: string; archived: boolean }>
): Promise<TripRow | null> {
const setClauses: string[] = [];
const params: unknown[] = [];
let idx = 1;
if (data.name !== undefined) { setClauses.push(`name = $${idx++}`); params.push(data.name); }
if ('description' in data) { setClauses.push(`description = $${idx++}`); params.push(data.description ?? null); }
if ('start_date' in data) { setClauses.push(`start_date = $${idx++}`); params.push(data.start_date ?? null); }
if ('end_date' in data) { setClauses.push(`end_date = $${idx++}`); params.push(data.end_date ?? null); }
if (data.color !== undefined) { setClauses.push(`color = $${idx++}`); params.push(data.color); }
if (data.archived !== undefined) { setClauses.push(`archived = $${idx++}`); params.push(data.archived); }
if (!setClauses.length) return getTripById(id, ownerId);
params.push(id, ownerId);
const rows = await queryRaw<TripRow>(`
UPDATE trips SET ${setClauses.join(', ')}
WHERE id = $${idx++} AND owner_id = $${idx}
RETURNING *, 0::float AS total_spend, 0::int AS transaction_count
`, params);
return rows[0] ?? null;
}
export async function deleteTrip(id: number, ownerId: number): Promise<void> {
await queryRaw(`DELETE FROM trips WHERE id = $1 AND owner_id = $2`, [id, ownerId]);
}
export async function assignTransactionsToTrip(
tripId: number | null,
transactionIds: number[]
): Promise<void> {
if (!transactionIds.length) return;
await queryRaw(`
INSERT INTO transaction_overrides (transaction_id, trip_id)
SELECT unnest($1::int[]), $2
ON CONFLICT (transaction_id)
DO UPDATE SET trip_id = EXCLUDED.trip_id
`, [transactionIds, tripId]);
}
export async function getTagTransactionIds(tagId: number): Promise<number[]> {
const rows = await queryRaw<{ transaction_id: number }>(
`SELECT transaction_id FROM transaction_tags WHERE tag_id = $1`,
[tagId]
);
return rows.map((r) => r.transaction_id);
}
+130
View File
@@ -0,0 +1,130 @@
/**
* Applying a rule's `actions` to transactions, and snapshotting the before-state
* so a run can be reverted.
*
* Shared by the two callers that write rule actions:
* - `POST /api/rules/apply` — condition-matched bulk run
* - `POST /api/transactions/bulk` with `action: "apply_rule"` — quick action
* fired against a hand-picked selection (conditions ignored)
*/
import { queryRaw } from "@/lib/db";
import type { Actions } from "@/lib/rules";
export interface SnapshotEntry {
transaction_id: number;
had_override: boolean;
prev_category_override: string | null;
prev_merchant_normalized: string | null;
prev_tag_ids: number[];
prev_splits: { participant_id: number; share_percent: number; settled: boolean }[];
}
/**
* Apply `actions` to one transaction.
*
* Tags are additive (ON CONFLICT DO NOTHING) — re-running never duplicates and
* never removes tags the rule doesn't mention. Splits replace the participant
* set but upsert shares, so `settled` flags survive a re-run; a plain
* delete+reinsert would silently un-settle reconciled splits.
*/
export async function applyRuleActions(
transactionId: number,
actions: Actions,
opts: { skipSplit?: boolean } = {}
): Promise<void> {
if (actions.set_category || actions.set_merchant) {
await queryRaw(
`INSERT INTO transaction_overrides (transaction_id, category_override, merchant_normalized)
VALUES ($1, $2, $3)
ON CONFLICT (transaction_id) DO UPDATE SET
category_override = COALESCE($2, transaction_overrides.category_override),
merchant_normalized = COALESCE($3, transaction_overrides.merchant_normalized),
updated_at = NOW()`,
[transactionId, actions.set_category || null, actions.set_merchant || null]
);
}
if (actions.add_tag_ids?.length) {
for (const tagId of actions.add_tag_ids) {
await queryRaw(
`INSERT INTO transaction_tags (transaction_id, tag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[transactionId, tagId]
);
}
}
if (actions.apply_split?.length && !opts.skipSplit) {
await queryRaw(
`DELETE FROM transaction_splits WHERE transaction_id = $1 AND participant_id != ALL($2::int[])`,
[transactionId, actions.apply_split.map((s) => s.participant_id)]
);
for (const s of actions.apply_split) {
await queryRaw(
`INSERT INTO transaction_splits (transaction_id, participant_id, share_percent)
VALUES ($1, $2, $3)
ON CONFLICT (transaction_id, participant_id)
DO UPDATE SET share_percent = EXCLUDED.share_percent`,
[transactionId, s.participant_id, s.share_percent]
);
}
}
}
/** Capture the overrides / tags / splits of `ids` before a run mutates them. */
export async function captureSnapshot(ids: number[]): Promise<SnapshotEntry[]> {
if (ids.length === 0) return [];
const overrides = await queryRaw<{
transaction_id: number;
category_override: string | null;
merchant_normalized: string | null;
}>(
`SELECT transaction_id, category_override, merchant_normalized
FROM transaction_overrides WHERE transaction_id = ANY($1::int[])`,
[ids]
);
const overrideMap = new Map(overrides.map((o) => [o.transaction_id, o]));
const tagRows = await queryRaw<{ transaction_id: number; tag_id: number }>(
`SELECT transaction_id, tag_id FROM transaction_tags WHERE transaction_id = ANY($1::int[])`,
[ids]
);
const tagMap = new Map<number, number[]>();
for (const row of tagRows) {
if (!tagMap.has(row.transaction_id)) tagMap.set(row.transaction_id, []);
tagMap.get(row.transaction_id)!.push(row.tag_id);
}
const splitRows = await queryRaw<{
transaction_id: number;
participant_id: number;
share_percent: number;
settled: boolean;
}>(
`SELECT transaction_id, participant_id, share_percent, settled
FROM transaction_splits WHERE transaction_id = ANY($1::int[])`,
[ids]
);
const splitMap = new Map<number, { participant_id: number; share_percent: number; settled: boolean }[]>();
for (const row of splitRows) {
if (!splitMap.has(row.transaction_id)) splitMap.set(row.transaction_id, []);
splitMap.get(row.transaction_id)!.push({
participant_id: row.participant_id,
share_percent: row.share_percent,
settled: row.settled,
});
}
return ids.map((id) => {
const ov = overrideMap.get(id);
return {
transaction_id: id,
had_override: !!ov,
prev_category_override: ov?.category_override ?? null,
prev_merchant_normalized: ov?.merchant_normalized ?? null,
prev_tag_ids: tagMap.get(id) ?? [],
prev_splits: splitMap.get(id) ?? [],
};
});
}
+45
View File
@@ -0,0 +1,45 @@
// Canonical statement types. Mirrors the CHECK constraint and the
// normalize_statement_type() SQL function in migration 0013 — keep them in sync.
export const STATEMENT_TYPES = [
"credit_card",
"transaction",
"savings",
"loan",
"offset",
"investment",
"other",
] as const;
export type StatementType = (typeof STATEMENT_TYPES)[number];
export const STATEMENT_TYPE_LABELS: Record<StatementType, string> = {
credit_card: "Credit Card",
transaction: "Transaction",
savings: "Savings",
loan: "Loan",
offset: "Offset",
investment: "Investment",
other: "Other",
};
export function isStatementType(v: string | null | undefined): v is StatementType {
return !!v && (STATEMENT_TYPES as readonly string[]).includes(v);
}
/** Falls back to "other" for anything unrecognised (e.g. rows predating 0013). */
export function asStatementType(v: string | null | undefined): StatementType {
return isStatementType(v) ? v : "other";
}
export function formatStatementType(v: string | null | undefined): string {
return STATEMENT_TYPE_LABELS[asStatementType(v)];
}
/**
* Types where the headline figure is "amount owed" rather than "balance held",
* and where a payment due date is meaningful.
*/
export function isLiability(v: string | null | undefined): boolean {
const t = asStatementType(v);
return t === "credit_card" || t === "loan";
}
+5
View File
@@ -20,5 +20,10 @@ export default defineConfig({
environment: "node",
include: ["src/__tests__/integration/**/*.test.ts"],
pool: "forks",
// Every integration file shares the one `personal_test` database, and
// helpers.resetDB() TRUNCATEs it (CASCADE reaches expense_metadata).
// Run files one at a time so a sibling's reset cannot delete rows another
// file just inserted — that raced non-deterministically across I6/I7/I11.
fileParallelism: false,
},
});