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.
This commit is contained in:
+59
-10
@@ -61,6 +61,23 @@ export interface MessageMeta {
|
||||
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);
|
||||
@@ -81,6 +98,15 @@ const decodeEntities = (s: string) =>
|
||||
|
||||
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, "")));
|
||||
|
||||
/**
|
||||
@@ -136,7 +162,7 @@ function detectPlatform(meta: MessageMeta, html: string): ParsedOrder["platform"
|
||||
}
|
||||
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 OrderParseError(`cannot determine platform from subject: ${s}`, meta.messageId);
|
||||
throw new NotAReceiptError(`cannot determine platform from subject: ${s}`, meta.messageId);
|
||||
}
|
||||
|
||||
function parseMerchant(platform: string, meta: MessageMeta, text: string): string {
|
||||
@@ -194,7 +220,7 @@ function parsePayment(platform: string, html: string, text: string): PaymentBrea
|
||||
// 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|Payments)?[^.]{0,60}?[\d,]+\.\d{2}\s+\S+\s+\S+\s*(?:am|pm)?\s*Failed/gi,
|
||||
/(?:Visa|MasterCard|Amex|American Express|Uber Cash)[^.]{0,40}?[\d,]+\.\d{2}\s+\S+\s+\S+\s*(?:am|pm)?\s*Failed/gi,
|
||||
" "
|
||||
);
|
||||
|
||||
@@ -215,7 +241,7 @@ function parsePayment(platform: string, html: string, text: string): PaymentBrea
|
||||
|
||||
export function parseOrderHTML(html: string, meta: MessageMeta): ParsedOrder {
|
||||
if (!html || html.length < 200) {
|
||||
throw new OrderParseError("body too short to be a receipt", meta.messageId);
|
||||
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)));
|
||||
@@ -233,14 +259,14 @@ export function parseOrderHTML(html: string, meta: MessageMeta): ParsedOrder {
|
||||
// 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 OrderParseError(
|
||||
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 OrderParseError(
|
||||
throw new NotAReceiptError(
|
||||
"order-adjustment notice, not a receipt — no final total stated",
|
||||
meta.messageId
|
||||
);
|
||||
@@ -253,18 +279,41 @@ export function parseOrderHTML(html: string, meta: MessageMeta): ParsedOrder {
|
||||
// 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 = clean.match(
|
||||
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
|
||||
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
|
||||
);
|
||||
if (platform !== "doordash" && uuid) {
|
||||
order_reference = uuid[0].toLowerCase();
|
||||
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}`;
|
||||
if (platform !== "doordash") flags.push("no_order_uuid_fell_back_to_message_id");
|
||||
}
|
||||
|
||||
// ---- date ----------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user