From f2b6153aa6905f064e930d4707b1698503eb307a Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Fri, 13 Nov 2026 20:18:44 +0000 Subject: [PATCH] reconcile: show a candidate's nearby ledger rows, so a manual grant isn't read as a gap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Widening the window to OC's whole order history found three $5 packs from 2026-09-28 reported as uncredited — ntnsndr's launch-day purchases, which WERE credited by hand that morning: +20.00, +5.75, then a -10.75 correction ('true contributions were 3 x $5.00'), netting exactly $15, with no per-order reference on any row. credit_pack_accounted() is right not to infer 'accounted for' from a nearby amount — that would hide genuine gaps — but a reviewer could not tell the two cases apart from the candidate alone. Each candidate now carries its nearby ledger/held rows (7-day window, capped at 5) and the report-mode log line prints them, so a manual grant explains itself. Nothing about the decision changes. 36 checks; all 18 suites green. --- app/main.py | 55 +++++++++++++++++++++++++++-- tests/test_credit_pack_reconcile.py | 34 +++++++++++++++++- 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/app/main.py b/app/main.py index b1cb715..db45ca7 100644 --- a/app/main.py +++ b/app/main.py @@ -7793,6 +7793,43 @@ def credit_pack_accounted(order: dict, ledger_rows: list, held_rows: list) -> st return None +def _nearby_book_rows(slug: str, email: str, when: datetime | None, ledger_rows: list, + held_rows: list, days: int = 7, cap: int = 5) -> list[dict]: + """Our own rows for this member NEAR this order — context for a human, never a decision. + + WHY: a manual grant can be real and still carry no per-order reference. + ntnsndr's three launch-day $5 packs were credited on 2026-09-28 as +20.00 and + then corrected by -10.75, netting exactly 3 x $5.00 — with no reference on any + row. `credit_pack_accounted()` cannot see that (correctly: inferring + "accounted for" from a nearby amount would hide genuine gaps), so the order is + reported as unmatched. Without these neighbouring rows a reviewer cannot tell + that case from a real gap; with them, the manual grant is right there and the + candidate explains itself. + """ + out: list[dict] = [] + if not when: + return out + for kind, rows in (("ledger", ledger_rows), ("held", held_rows)): + for r in rows: + ref = (r.get("reference") or r.get("oc_reference") or "") + em = (r.get("email") or "").lower() + if slug and slug.lower() not in ref.lower() and slug.lower() not in em: + continue + if email and email.lower() not in em: + continue + rt = _parse_ts(r.get("created_at")) + if rt and abs((rt - when).total_seconds()) <= days * 86400: + out.append({ + "kind": kind, + "delta": r.get("delta") if kind == "ledger" else r.get("amount"), + "reason": r.get("reason") or r.get("status") or "", + "reference": ref or None, + "created_at": r.get("created_at"), + }) + out.sort(key=lambda x: str(x.get("created_at") or "")) + return out[:cap] + + async def reconcile_credit_packs(apply: bool = False) -> dict: """Credit PAID credit packs that never reached our books (issue #7). @@ -7829,9 +7866,9 @@ async def reconcile_credit_packs(apply: bool = False) -> dict: # Positional rows: get_db() hands back a plain connection (no row_factory), # which is how the rest of this module reads it too. ledger_rows = [ - {"email": r[0], "delta": r[1], "reference": r[2], "created_at": r[3]} + {"email": r[0], "delta": r[1], "reference": r[2], "created_at": r[3], "reason": r[4]} for r in conn.execute( - "SELECT email, delta, reference, created_at FROM credit_ledger")] + "SELECT email, delta, reference, created_at, reason FROM credit_ledger")] held_rows = [ {"id": r[0], "slug": r[1], "email": r[2], "amount": r[3], "oc_reference": r[4], "status": r[5], "created_at": r[6]} @@ -7880,6 +7917,12 @@ async def reconcile_credit_packs(apply: bool = False) -> dict: rec["email"] = email ref = credit_pack_reference(slug, {"idV2": o.get("id")}) rec["reference"] = ref + nearby = _nearby_book_rows(slug, email, _parse_ts(o.get("createdAt")), + ledger_rows, held_rows) + if nearby: + # Printed for a HUMAN to judge: a manual grant can be real and carry + # no reference at all, and this is the only way to tell that from a gap. + rec["nearby_book_rows"] = nearby candidates.append(rec) if not acting or credit_reference_exists(ref): continue @@ -7902,7 +7945,13 @@ async def reconcile_credit_packs(apply: bool = False) -> dict: logger.warning( "Credit reconcile: %d PAID credit pack(s) with no record in our books " "(report mode — nothing changed): %s", len(candidates), - "; ".join(f"${c['amount']:.2f} {c['slug']} {c['created_at']}" for c in candidates)) + "; ".join( + f"${c['amount']:.2f} {c['slug']} {c['created_at']}" + + (f" [nearby rows: " + + ", ".join(f"{n['delta']} on {n['created_at']} ({n['reason']})" + for n in c["nearby_book_rows"]) + "]" + if c.get("nearby_book_rows") else "") + for c in candidates)) return { "status": "ok", diff --git a/tests/test_credit_pack_reconcile.py b/tests/test_credit_pack_reconcile.py index 86873ee..b176cd6 100644 --- a/tests/test_credit_pack_reconcile.py +++ b/tests/test_credit_pack_reconcile.py @@ -106,7 +106,7 @@ async def fake_index(): raise Boom("member index unavailable") return {e: {"slug": e.split("@")[0]} for e in ("alice@x.org", "bob@x.org", "carol@x.org", "dave@x.org", - "erin@x.org", "frank@x.org")} + "erin@x.org", "frank@x.org", "gina@x.org")} BUDGET_PUSHES = [] @@ -264,6 +264,38 @@ async def main(): check(f"still one row for the order (got {len(ledger_rows())})", len(ledger_rows()) == 4) + # ---------- a candidate must SHOW the nearby rows a human needs ---------- + # A manual grant can be real and carry no per-order reference: ntnsndr's three + # launch-day $5 packs were credited as +20.00 then corrected by -10.75, netting + # exactly 3 x $5.00, with no reference on any row. The matcher must NOT read + # that as accounted for (that would hide real gaps), so the candidate has to + # carry enough context for a reviewer to tell the two apart. + seed() + conn = m.get_db() + conn.execute("INSERT INTO members (email, slug, active, account_type, credit_balance) " + "VALUES ('gina@x.org', 'gina', 1, 'member', 0)") + conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) " + "VALUES ('gina@x.org', 7.5, 'manual application', NULL, ?)", (stamp(0.5),)) + conn.commit() + conn.close() + + async def only_gina(per_page=100, max_pages=3): + return [order("or_GGG", "gina", 10, 0.5)] + + saved_orders = m.fetch_collective_orders + m.fetch_collective_orders = only_gina + res = await m.reconcile_credit_packs(apply=False) + cand = (res.get("candidates") or [{}])[0] + check(f"an unreferenced nearby grant is SURFACED on the candidate " + f"(got {cand.get('nearby_book_rows')})", + any(abs(float(n["delta"]) - 7.5) < 0.01 + for n in cand.get("nearby_book_rows") or [])) + check("a nearby unreferenced grant does NOT count as accounted for", + len(res.get("candidates") or []) == 1) + check(f"the pass still leaves the money alone (got {balance('gina@x.org')})", + balance("gina@x.org") == 0.0) + m.fetch_collective_orders = saved_orders + # ---------- the endpoint ------------------------------------------------- # Re-seed: the direct apply above already credited carol, so the endpoint # would have no candidate and the check would pass for the wrong reason.