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.
This commit is contained in:
2026-07-27 00:48:20 +10:00
parent c82a22767f
commit a9e251d969
4 changed files with 328 additions and 6 deletions
+71 -4
View File
@@ -328,10 +328,20 @@ export function parseOrderHTML(html: string, meta: MessageMeta): ParsedOrder {
// ---- payment -------------------------------------------------------------
const payment = parsePayment(platform, clean, text);
if (payment.ambiguous) {
// Settled as card — see parsePayment. No credits transaction is created.
flags.push("payment_split_not_stated_settled_as_card");
payment.card_amount = totals.total_charged;
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;
@@ -427,3 +437,60 @@ export function validateOrderTotals(
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);
}