diff --git a/pm-stack/aggregator/src/charges-match.ts b/pm-stack/aggregator/src/charges-match.ts new file mode 100644 index 0000000000..4f3c0c7f87 --- /dev/null +++ b/pm-stack/aggregator/src/charges-match.ts @@ -0,0 +1,240 @@ +// charges-match (#1057): the pure core of the usage-hub charges +// auto-matcher. The daily collector (scripts/collect-fleet-feed.ts) +// reads Plaid transactions and Gmail receipt/card alerts, normalizes +// both into ChargeCandidates, and calls matchCharges: one ChargeRow +// per real charge, source-labelled, deduped across sources, matched +// to a hub service where one fits, with unmatched SaaS/AI-looking +// charges returned separately for the attention strip. +// +// Pure and deterministic by design: the same inputs always produce +// the same feed section, so re-running the collector for a period +// republishes identical rows instead of appending duplicates (the +// feed section is replaced, never appended). Persisted +// classification state (which unmatched charges already surfaced) +// lives in the collector, not here — this module only decides what +// a charge IS, never what was already shown. +// +// No balances or debt data pass through here: candidates are charge +// evidence only (date, merchant, amount, payment-method label). + +import type { ChargeRow } from "./model.ts"; + +export type ChargeSourceKind = "plaid" | "gmail"; + +/** One observed charge from one source, before dedupe/matching. */ +export interface ChargeCandidate { + source: ChargeSourceKind; + /** ISO date the charge posted / the alert was sent. */ + at: string; + /** Raw merchant/descriptor text as the source reported it. */ + merchant: string; + /** Positive = money out (a charge). Non-positive candidates are ignored. */ + amountUsd: number; + /** Payment method as recorded, e.g. "Visa •7535", when known. */ + method?: string; +} + +/** A hub service a charge can be matched to (name + known aliases). */ +export interface ChargeServiceRef { + name: string; + aliases?: string[]; +} + +/** A deduped charge that matched no hub service but looks SaaS/AI. */ +export interface UnmatchedCharge { + merchant: string; + normalized: string; + amountUsd: number; + at: string; + source: ChargeSourceKind; +} + +export interface ChargeMatchResult { + /** One row per deduped charge, date order. */ + rows: ChargeRow[]; + /** Deduped, service-unmatched, SaaS/AI-looking charges (attention). */ + unmatchedSaas: UnmatchedCharge[]; +} + +/** Charges from two sources for the same purchase post within days. */ +export const DEDUPE_WINDOW_DAYS = 3; + +const DROP_TOKENS = new Set([ + "US", + "USA", + "INC", + "LLC", + "LTD", + "CO", + "COM", + "WWW", + "HTTP", + "HTTPS", + "POS", + "ACH", + "DEBIT", + "PURCHASE", +]); + +/** Id-like descriptor tokens (mixed letters+digits, e.g. UC5DPA22Y4). */ +function isIdLike(token: string): boolean { + return token.length >= 6 && /[A-Z]/.test(token) && /\d/.test(token); +} + +/** + * Normalize a raw merchant descriptor to a comparable token string: + * "OPENAI *CHATGPT SUB" -> "OPENAI CHATGPT SUB", + * "METAPAY*UC5DPA22Y4 US" -> "METAPAY", + * "CURSOR.COM" -> "CURSOR". + */ +export function normalizeMerchantName(raw: string): string { + const upper = raw.toUpperCase().replace(/[*]/g, " "); + const tokens = upper + .replace(/[^A-Z0-9]+/g, " ") + .split(/\s+/) + .filter((t) => t.length > 0) + .filter((t) => !DROP_TOKENS.has(t)) + .filter((t) => !/^\d+$/.test(t)) + .filter((t) => !isIdLike(t)); + return tokens.join(" "); +} + +function squash(normalized: string): string { + return normalized.replace(/\s+/g, ""); +} + +function daysBetween(a: string, b: string): number { + const ms = Math.abs(Date.parse(a) - Date.parse(b)); + return Math.floor(ms / 86_400_000); +} + +/** Merchant token strings that mark a charge as SaaS/AI-looking. */ +const SAAS_MARKERS = [ + "OPENAI", + "CHATGPT", + "ANTHROPIC", + "CLAUDE", + "DEEPSEEK", + "PERPLEXITY", + "MIDJOURNEY", + "XAI", + "GROK", + "CURSOR", + "GITHUB", + "GITLAB", + "VERCEL", + "NETLIFY", + "RAILWAY", + "SUPABASE", + "PLANETSCALE", + "TURSO", + "MODAL", + "REPLICATE", + "HUGGINGFACE", + "LINEAR", + "NOTION", + "FIGMA", + "ATLASSIAN", + "DATADOG", + "SENTRY", + "CLOUDFLARE", + "DIGITALOCEAN", + "LINODE", + "STRIPE", + "PADDLE", +]; + +/** Heuristic: does this normalized merchant look like a SaaS/AI charge? */ +export function isSaasLooking(normalized: string): boolean { + const flat = squash(normalized); + return SAAS_MARKERS.some((marker) => flat.includes(marker)); +} + +/** The hub service a normalized merchant belongs to, if any. */ +export function matchService(normalized: string, services: ChargeServiceRef[]): ChargeServiceRef | undefined { + const flat = squash(normalized); + const tokenSet = new Set(normalized.split(" ").filter(Boolean)); + for (const service of services) { + for (const candidate of [service.name, ...(service.aliases ?? [])]) { + const norm = normalizeMerchantName(candidate); + if (!norm) continue; + const flatNorm = squash(norm); + if (flatNorm.length >= 4 && flat.includes(flatNorm)) return service; + const tokens = norm.split(" ").filter(Boolean); + if (tokens.length > 0 && tokens.every((t) => tokenSet.has(t))) return service; + } + } + return undefined; +} + +interface Cluster { + amountUsd: number; + normalized: string; + plaid?: ChargeCandidate; + gmail?: ChargeCandidate; + first: ChargeCandidate; +} + +/** + * Dedupe across sources and match to services. Plaid is the source + * of record on a tie: when both sources saw the charge, the row is + * labelled "Plaid" and carries the Plaid date/method. + */ +export function matchCharges(candidates: ChargeCandidate[], services: ChargeServiceRef[]): ChargeMatchResult { + const charges = candidates + .filter((c) => c.amountUsd > 0 && c.at && c.merchant) + .map((c) => ({ ...c, amountUsd: Math.round(c.amountUsd * 100) / 100 })); + + const clusters: Cluster[] = []; + // Plaid first so a cluster's record fields come from Plaid when present. + const ordered = [...charges].sort((a, b) => + a.source === b.source ? a.at.localeCompare(b.at) : a.source === "plaid" ? -1 : 1, + ); + for (const candidate of ordered) { + const normalized = normalizeMerchantName(candidate.merchant); + const existing = clusters.find( + (cl) => + cl.amountUsd === candidate.amountUsd && + cl.normalized === normalized && + daysBetween(cl.first.at, candidate.at) <= DEDUPE_WINDOW_DAYS, + ); + if (existing) { + if (candidate.source === "plaid" && !existing.plaid) existing.plaid = candidate; + if (candidate.source === "gmail" && !existing.gmail) existing.gmail = candidate; + continue; + } + clusters.push({ + amountUsd: candidate.amountUsd, + normalized, + plaid: candidate.source === "plaid" ? candidate : undefined, + gmail: candidate.source === "gmail" ? candidate : undefined, + first: candidate, + }); + } + + const rows: ChargeRow[] = []; + const unmatchedSaas: UnmatchedCharge[] = []; + for (const cluster of clusters) { + const record = cluster.plaid ?? cluster.first; + const service = matchService(cluster.normalized, services); + rows.push({ + at: record.at, + label: service ? service.name : record.merchant.trim(), + amountUsd: cluster.amountUsd, + method: cluster.plaid?.method ?? cluster.gmail?.method ?? "card", + source: cluster.plaid ? "Plaid" : "Gmail alert", + }); + if (!service && isSaasLooking(cluster.normalized)) { + unmatchedSaas.push({ + merchant: record.merchant.trim(), + normalized: cluster.normalized, + amountUsd: cluster.amountUsd, + at: record.at, + source: cluster.plaid ? "plaid" : "gmail", + }); + } + } + rows.sort((a, b) => a.at.localeCompare(b.at) || a.label.localeCompare(b.label)); + unmatchedSaas.sort((a, b) => a.at.localeCompare(b.at) || a.merchant.localeCompare(b.merchant)); + return { rows, unmatchedSaas }; +} diff --git a/pm-stack/aggregator/test/charges-match.test.ts b/pm-stack/aggregator/test/charges-match.test.ts new file mode 100644 index 0000000000..5590bbe641 --- /dev/null +++ b/pm-stack/aggregator/test/charges-match.test.ts @@ -0,0 +1,108 @@ +// #1057: charges auto-matcher — cross-source dedupe, service match, +// source labels, unmatched SaaS surfacing, rerun determinism. +import { describe, expect, test } from "bun:test"; +import { isSaasLooking, matchCharges, normalizeMerchantName, type ChargeCandidate } from "../src/charges-match.ts"; + +const SERVICES = [ + { name: "Anthropic", aliases: ["Claude"] }, + { name: "OpenAI", aliases: ["ChatGPT"] }, + { name: "Cloudflare" }, +]; + +describe("normalizeMerchantName", () => { + test("strips descriptors, id tokens, and filler", () => { + expect(normalizeMerchantName("METAPAY*UC5DPA22Y4 US")).toBe("METAPAY"); + expect(normalizeMerchantName("OPENAI *CHATGPT SUB")).toBe("OPENAI CHATGPT SUB"); + expect(normalizeMerchantName("CURSOR.COM")).toBe("CURSOR"); + expect(normalizeMerchantName("WALMART STORE 1234")).toBe("WALMART STORE"); + }); +}); + +describe("matchCharges", () => { + test("a charge seen by both Plaid and Gmail is one row, Plaid of record", () => { + const candidates: ChargeCandidate[] = [ + { source: "gmail", at: "2026-10-27", merchant: "MetaPay", amountUsd: 20 }, + { source: "plaid", at: "2026-10-28", merchant: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535" }, + ]; + const { rows } = matchCharges(candidates, SERVICES); + expect(rows).toEqual([ + { at: "2026-10-28", label: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535", source: "Plaid" }, + ]); + }); + + test("same merchant and amount outside the window is two charges", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-01", merchant: "NETFLIX", amountUsd: 15.99 }, + { source: "gmail", at: "2026-10-20", merchant: "Netflix", amountUsd: 15.99 }, + ]; + expect(matchCharges(candidates, SERVICES).rows).toHaveLength(2); + }); + + test("different amounts are different charges even on the same day", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-05", merchant: "STRIPE", amountUsd: 5 }, + { source: "plaid", at: "2026-10-05", merchant: "STRIPE", amountUsd: 9 }, + ]; + expect(matchCharges(candidates, SERVICES).rows).toHaveLength(2); + }); + + test("matched charges take the service name as their label", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-11", merchant: "ANTHROPIC PBC", amountUsd: 100 }, + ]; + const { rows, unmatchedSaas } = matchCharges(candidates, SERVICES); + expect(rows[0]?.label).toBe("Anthropic"); + expect(unmatchedSaas).toEqual([]); + }); + + test("alias match: a ChatGPT charge matches the OpenAI service", () => { + const candidates: ChargeCandidate[] = [ + { source: "gmail", at: "2026-10-09", merchant: "ChatGPT Subscription", amountUsd: 20 }, + ]; + const { rows } = matchCharges(candidates, SERVICES); + expect(rows[0]?.label).toBe("OpenAI"); + expect(rows[0]?.source).toBe("Gmail alert"); + }); + + test("unmatched SaaS-looking charges surface once, deduped", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-12", merchant: "CURSOR.COM", amountUsd: 20 }, + { source: "gmail", at: "2026-10-12", merchant: "Cursor", amountUsd: 20 }, + ]; + const { rows, unmatchedSaas } = matchCharges(candidates, SERVICES); + expect(rows).toHaveLength(1); + expect(unmatchedSaas).toHaveLength(1); + expect(unmatchedSaas[0]?.normalized).toBe("CURSOR"); + }); + + test("unmatched non-SaaS charges are rows but never surface", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-13", merchant: "WALMART STORE 1234", amountUsd: 54.12 }, + ]; + const { rows, unmatchedSaas } = matchCharges(candidates, SERVICES); + expect(rows).toHaveLength(1); + expect(unmatchedSaas).toEqual([]); + expect(isSaasLooking("WALMART STORE")).toBe(false); + }); + + test("non-positive candidates (refunds/inflows) are ignored", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-14", merchant: "OPENAI REFUND", amountUsd: -20 }, + { source: "plaid", at: "2026-10-14", merchant: "PAYROLL", amountUsd: 0 }, + ]; + expect(matchCharges(candidates, SERVICES)).toEqual({ rows: [], unmatchedSaas: [] }); + }); + + test("re-running the same period is deterministic and adds nothing", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-28", merchant: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535" }, + { source: "gmail", at: "2026-10-27", merchant: "MetaPay", amountUsd: 20 }, + { source: "gmail", at: "2026-10-09", merchant: "ChatGPT Subscription", amountUsd: 20 }, + { source: "plaid", at: "2026-10-12", merchant: "CURSOR.COM", amountUsd: 20 }, + ]; + const first = matchCharges(candidates, SERVICES); + const second = matchCharges(candidates, SERVICES); + expect(second).toEqual(first); + expect(first.rows).toHaveLength(3); + }); +});