From e4cef1faec5e53def8adda3e27e51922ead67899 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Tue, 18 Aug 2026 10:30:53 -0400 Subject: [PATCH] Initial commit: EIB processor tool with new landing page preview Single-tool Flask app (Equals Money -> Workday EIB conversion + audit) plus a new /home-preview landing page in preparation for turning this into a multi-tool platform. Co-Authored-By: Claude Sonnet 5 --- .gitignore | 9 + Dockerfile | 18 + README.md | 55 ++ app/main.py | 1046 +++++++++++++++++++++++++++++++++ docker-compose.yml | 37 ++ eib-processor_how-it-works.md | 32 + requirements.txt | 5 + templates/home.html | 257 ++++++++ templates/index.html | 788 +++++++++++++++++++++++++ 9 files changed, 2247 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 app/main.py create mode 100644 docker-compose.yml create mode 100644 eib-processor_how-it-works.md create mode 100644 requirements.txt create mode 100644 templates/home.html create mode 100644 templates/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d95ed3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +uploads/ +outputs/ +__pycache__/ +*.pyc +.env +*.xlsx +*.csv +*.pdf +.claude/settings.local.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f37d97c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.11-slim + +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + curl \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +RUN mkdir -p /app/uploads /app/outputs + +EXPOSE 5000 + +CMD ["python", "app/main.py"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..62c3864 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# EIB Processor + +Equals Money → Workday EIB transformer and statement auditor. +Built by Undo Designs for Planeterra International Foundation. + +## Quick start + +```bash +docker compose up --build +``` + +Then open http://localhost:5000 + +## What it does + +1. Upload a raw Equals Money export (.xlsx) +2. Optionally upload a combined card statement CSV for per-person audit +3. Download the processed EIB Excel file + +The audit table appears in the output file four columns after the last EIB column. +Each person gets a single MATCHED / REVIEW REQUIRED status based on: + +``` +sum(EIB Converted Amount) == sum(statement Total debited for rows in EIB) +``` + +## PDF statement audit (Docling) + +The Docling container starts automatically with Docker Compose. +Once it's healthy (check the badge in the top-right of the UI), +you can upload a PDF statement instead of the CSV. + +PDF parsing extracts the opening/closing balance summary from page 1 +of the Equals statement. The Docling health check takes ~60s on first start. + +## Adding new merchants + +If the processor reports unmapped merchants, add them to `MERCHANT_LOOKUP` +in `app/main.py` and restart: + +```bash +docker compose restart app +``` + +## Services + +| Service | Port | Description | +|----------|-------|------------------------------------| +| app | 5000 | Flask web app | +| docling | 5001 | Docling PDF parsing service | + +## Volumes + +- `./uploads/` — temporary uploaded files +- `./outputs/` — generated EIB Excel files diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..64e162d --- /dev/null +++ b/app/main.py @@ -0,0 +1,1046 @@ +import os, re, uuid, json, requests +from datetime import datetime +from flask import Flask, request, jsonify, send_file, render_template +from werkzeug.utils import secure_filename +import pandas as pd +from openpyxl.styles import PatternFill, Font, Alignment, Border, Side +from openpyxl.utils import get_column_letter + +app = Flask(__name__, template_folder="../templates", static_folder="../static") +app.config["UPLOAD_FOLDER"] = os.environ.get("UPLOAD_FOLDER", "/app/uploads") +app.config["OUTPUT_FOLDER"] = os.environ.get("OUTPUT_FOLDER", "/app/outputs") +app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50MB + +# ── Progress tracking for the frontend polling UI ─────────────────────────── +# Single-job assumption: this is a local single-user tool, so one shared +# status dict is enough. Reset at the start of every /api/process call. +PROCESS_STATUS = {"active": False, "current": "", "log": []} + + +def status_reset(): + PROCESS_STATUS["active"] = True + PROCESS_STATUS["current"] = "Starting..." + PROCESS_STATUS["log"] = [] + + +def status_set(current): + PROCESS_STATUS["current"] = current + + +def status_log(line): + PROCESS_STATUS["log"].append(line) + + +def status_done(): + PROCESS_STATUS["active"] = False + PROCESS_STATUS["current"] = "Done" +DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001") + + + +def probe_docling(pdf_path): + """ + DIAGNOSTIC ONLY. Calls Docling and logs the RAW response exactly as + received - no parsing, no assumptions. Used to capture real ground + truth before writing/adjusting extraction logic. Does not affect + the normal processing flow. + """ + filename = os.path.basename(pdf_path) + print(f"\n{'='*70}") + print(f"[PROBE] {filename}") + print(f"{'='*70}") + + try: + with open(pdf_path, "rb") as f: + response = requests.post( + f"{DOCLING_URL}/v1/convert/file", + files={"files": (filename, f, "application/pdf")}, + timeout=300, + ) + print(f"[PROBE] HTTP status: {response.status_code}") + response.raise_for_status() + except Exception as e: + print(f"[PROBE] Request failed: {e}") + return None + + try: + result = response.json() + except Exception as e: + print(f"[PROBE] Response is not JSON: {e}") + print(f"[PROBE] Raw response text (first 2000 chars):\n{response.text[:2000]}") + return None + + print(f"[PROBE] Response type: {type(result).__name__}") + + if isinstance(result, dict): + print(f"[PROBE] Top-level keys: {list(result.keys())}") + for key, val in result.items(): + if isinstance(val, dict): + print(f"[PROBE] \'{key}\' is a dict with keys: {list(val.keys())}") + for subkey, subval in val.items(): + if isinstance(subval, str): + print(f"[PROBE] \'{key}.{subkey}\' is a string, length={len(subval)}") + print(f"[PROBE] \'{key}.{subkey}\' first 800 chars:\n{subval[:800]}") + if len(subval) > 800: + print(f"[PROBE] \'{key}.{subkey}\' last 300 chars:\n{subval[-300:]}") + else: + print(f"[PROBE] \'{key}.{subkey}\' type={type(subval).__name__} " + f"value={str(subval)[:200]}") + elif isinstance(val, str): + print(f"[PROBE] \'{key}\' is a string, length={len(val)}") + print(f"[PROBE] \'{key}\' first 800 chars:\n{val[:800]}") + else: + print(f"[PROBE] \'{key}\' type={type(val).__name__} value={str(val)[:300]}") + elif isinstance(result, list): + print(f"[PROBE] List with {len(result)} item(s)") + if result: + print(f"[PROBE] First item: {json.dumps(result[0], indent=2, default=str)[:2000]}") + + debug_dir = os.path.join(app.config["OUTPUT_FOLDER"], "_debug_markdown") + os.makedirs(debug_dir, exist_ok=True) + dump_path = os.path.join(debug_dir, f"{filename}.PROBE.json") + with open(dump_path, "w", encoding="utf-8") as f: + json.dump(result, f, indent=2, default=str) + print(f"[PROBE] Full raw response saved to: {dump_path}") + print(f"{'='*70}\n") + + return result + + +MERCHANT_LOOKUP = { + "AIR SUITES": "AIR SUITES", + "EL ESPANOL E023 PREEMB": "EL ESPANOL E023 PREEMB", + "EURO HOTEL": "EURO HOTEL", + "EURO HOTEL LTDA": "EURO HOTEL LTDA", + "Euronics": "Euronics", + "FUENTE ALEMANA": "Fuente Alemana", + "GOLDEN PRAGUE QUITO": "GOLDEN PRAGUE QUITO", + "GUARDIA VIEJA": "GUARDIA VIEJA", + "HOTEL LA CASONA $US A": "HOTEL LA CASONA $US A", + "IMG INSURANCE": "IMG INSURANCE", + "LOMIT S PROVIDENCIA": "LOMIT S PROVIDENCIA", + "LOYOLA INTERNACIONAL": "LOYOLA INTERNACIONAL", + "Lp Latam Xp": "Lp Latam Xp", + "MARIKI AND LILAC TANZA": "MARIKI AND LILAC TANZA", + "MERCADOPAGO *FELIXCAF": "Felixcaf - Mercado Pago", + "MERPAGO*SANTAMONICAFO": "MERPAGO*SANTAMONICAFO", + "MI COCINA": "MI COCINA", + "MUNICH": "MUNICH", + "NGORONGORO CONSERVATIO": "NGORONGORO CONSERVATIO", + "NOE SUSHIBAR N005": "NOE SUSHIBAR N005", + "ONE PAYMENT TZ AIRLINE": "ONE PAYMENT TZ AIRLINE", + "P.F. Chang's": "P.F. Chang's", + "PAYU*AR*UBER": "Uber", + "PETROCOMERCIAL ESTACIO": "PETROCOMERCIAL ESTACIO", + "PRECISION AIR SERVICES": "PRECISION AIR SERVICES", + "RESTAURANTE SEGUNDO MU": "RESTAURANTE SEGUNDO MU", + "RUMBO ESPIGON F T2": "RUMBO ESPIGON F T1", + "RUMBO ESPIGON F T1": "RUMBO ESPIGON F T1", + "Selcom Card Wallet": "Selcom Card Wallet", + "Selcom Tanzania": "Selcom Tanzania", + "SumUp * FOTO 37": "Foto 37 - SumUp", + "THE PLANTATION LODGE &": "THE PLANTATION LODGE &", + "TULIA BOUTIQUE HOTEL": "TULIA BOUTIQUE HOTEL", + "UBER *TRIP": "Uber", + "UBER *TRIP HELP.UBER.C": "UBER *TRIP HELP.UBER.C", + "UberDirectSA_2": "Uber", + "WT* FEDERICO BAGGIO BO": "WT* FEDERICO BAGGIO BO", + "WWW.TENORSHARE.COM": "WWW.TENORSHARE.COM", + "WYM SOLUTIONS": "WYM SOLUTIONS", + "CHALACA ": "Chalaca", + "Uber": "Uber", + "HANSEL Y GRETEL ": "HANSEL Y GRETEL", + "Grab": "Grab", + "TANTA LAP P20": "TANTA LAP P20", + "LAS REYES SWING": "LAS REYES SWING", + "IZI*RESTAURANTE LA MAR": "IZI RESTAURANTE LA MAR", + "IZI*LA BRASA HCO": "IZI LA BRASA HCO", + "EL BODEGON": "EL BODEGON", + "PesaPal*Kupaga Villas": "PesaPal Kupaga Villas", + "PesaPal*ZANZISTAR LODG": "PesaPal ZANZISTAR LODG", + "DNATA ZANZIBAR SERVICE": "DNATA ZANZIBAR SERVICE", + "EMIRATES LEISURE RETAI": "EMIRATES LEISURE RETAI", + "MUGG AND BEAN ROSEBANK": "MUGG AND BEAN ROSEBANK", + "WWW.GRAB.COM": "Grab", +} + + +def strip_prefix(desc): + return re.sub(r"^To \w+ for ", "", str(desc)).strip() + + +def process_raw(raw_df, merchant_lookup=None): + lookup = {**MERCHANT_LOOKUP, **(merchant_lookup or {})} + output_rows = [] + included_box_ids = set() + unmapped = {} + + raw = raw_df.copy() + raw["Box Transaction ID str"] = raw["Box Transaction ID"].astype(str) + raw["Group transaction ID str"] = raw["Group transaction ID"].astype(str) + raw["_row_order"] = range(len(raw)) + id_lookup = ( + raw.set_index("Box Transaction ID str")[ + ["Balance", "Card last four", "_row_order"] + ] + .to_dict("index") + ) + + cash_groups = set( + raw[raw["Type"] == "Cash withdrawal"]["Group transaction ID str"].tolist() + ) + atm_fee_groups = set( + raw[(raw["Type"] == "Fee") & (raw["MCC"] == 6011)][ + "Group transaction ID str" + ].tolist() + ) + all_atm_groups = cash_groups | atm_fee_groups + + refund_tuples = set( + ( + str(r["Description"]).strip().lower(), + round(float(r["Total credited"]), 2), + str(r["Balance currency"]), + ) + for _, r in raw[raw["Type"] == "Card refund"].iterrows() + ) + + group_max_exchange_pay = {} + for gid in all_atm_groups: + et = raw[ + (raw["Group transaction ID str"] == gid) + & (raw["Type"] == "Exchange") + & (raw["Description"].str.startswith("To ")) + ] + group_max_exchange_pay[gid] = ( + et["Payment / Exchange amount"].max() if len(et) > 0 else 0 + ) + + exchange_principal_groups = { + gid + for gid, maxpay in group_max_exchange_pay.items() + if maxpay > 2.50 and gid not in cash_groups + } + + def append_row(box_id, completed, amount, src_cur, conv_amt, conv_cur, label): + info = id_lookup.get(box_id, {}) + included_box_ids.add(box_id) + output_rows.append( + { + "Transaction Number": f"{box_id}-1", + "Transaction Date": completed, + "Amount": amount, + "Source Currency": src_cur, + "Converted Amount": conv_amt, + "Converted Currency": conv_cur, + "charge description line 1": label, + "_row_order": info.get("_row_order", 999999), + "Balance": info.get("Balance", ""), + "Card last four": info.get("Card last four", ""), + "_mapped": not label.startswith("UNMAPPED:"), + } + ) + + for _, row in raw.iterrows(): + tx_type = row["Type"] + desc = str(row["Description"]) + group_id = row["Group transaction ID str"] + box_id = row["Box Transaction ID str"] + bal_cur = row["Balance currency"] + debited = row["Total debited"] + pay_cur = row["Payment / Exchange currency"] + pay_amt = row["Payment / Exchange amount"] + completed = row["Completed date (UTC)"] + + if tx_type in ["Credit", "Card refund"]: + continue + if tx_type == "Exchange" and desc.startswith("From "): + continue + if tx_type == "Exchange" and "Auto exchange" in desc: + continue + if tx_type == "Card" and bal_cur not in ["USD", "EUR"]: + sib = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Exchange") + & (raw["Description"].str.startswith("To ")) + ] + if len(sib) > 0: + continue + + if tx_type == "Fee": + if group_id in all_atm_groups: + ef = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Exchange") + & (raw["Description"].str.startswith("To ")) + & (raw["Payment / Exchange amount"] == 1.50) + ] + if len(ef) > 0: + continue + append_row( + box_id, completed, debited, bal_cur, debited, bal_cur, + "Cash withdrawal", + ) + continue + + if tx_type == "Cash withdrawal": + if ( + desc.strip().lower(), + round(float(debited), 2), + bal_cur, + ) in refund_tuples: + continue + if group_max_exchange_pay.get(group_id, 0) > 2.50: + continue + fs = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Fee") + ] + es = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Exchange") + & (raw["Description"].str.startswith("To ")) + ] + label = ( + "Cash withdrawal fee" + if len(fs) > 0 and len(es) == 0 + else "Cash withdrawal" + ) + append_row(box_id, completed, debited, bal_cur, debited, bal_cur, label) + continue + + if tx_type == "Exchange" and desc.startswith("To "): + if group_id in exchange_principal_groups: + if pay_amt <= 2.50: + append_row( + box_id, completed, pay_amt, pay_cur, debited, bal_cur, + "Cash withdrawal fee", + ) + else: + append_row( + box_id, completed, debited, bal_cur, debited, bal_cur, + "Cash withdrawal", + ) + continue + if group_id in cash_groups: + if pay_amt == 1.50: + append_row( + box_id, completed, pay_amt, pay_cur, debited, bal_cur, + "Cash withdrawal fee", + ) + elif pay_amt > 2.50: + cs = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Cash withdrawal") + & (raw["Balance currency"] == pay_cur) + ] + ua = cs.iloc[0]["Total debited"] if len(cs) > 0 else pay_amt + append_row( + box_id, completed, ua, pay_cur, debited, bal_cur, + "Cash withdrawal", + ) + continue + if ( + group_id in atm_fee_groups + and group_id not in cash_groups + and pay_amt == 1.50 + ): + append_row( + box_id, completed, pay_amt, pay_cur, debited, bal_cur, + "Cash withdrawal fee", + ) + continue + if group_id not in all_atm_groups: + rn = strip_prefix(desc) + cn = lookup.get(rn) + if cn is None: + unmapped[rn] = box_id + cn = "UNMAPPED: " + rn + crd = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Card") + ] + if len(crd) > 0: + ua = crd.iloc[0]["Total debited"] + us = crd.iloc[0]["Balance currency"] + else: + ua, us = pay_amt, pay_cur + append_row(box_id, completed, ua, us, debited, bal_cur, cn) + continue + + if tx_type == "Card": + rn = desc + cn = lookup.get(rn) + if cn is None: + unmapped[rn] = box_id + cn = "UNMAPPED: " + rn + append_row(box_id, completed, debited, bal_cur, debited, bal_cur, cn) + + output_df = pd.DataFrame(output_rows) + return output_df, included_box_ids, unmapped + + +def run_audit(output_df, included_box_ids, stmt_df): + """ + Audit check per person (CSV statement): + sum(EIB Converted Amount) == sum(statement Total debited for rows in EIB) + """ + stmt_df = stmt_df.copy() + stmt_df["Box Transaction ID"] = stmt_df["Box Transaction ID"].astype(str) + audit_rows = [] + people = sorted(stmt_df["Balance"].dropna().unique()) + for person in people: + ps = stmt_df[stmt_df["Balance"] == person] + person_eib_ids = set( + output_df[output_df["Balance"] == person]["Transaction Number"] + .str.replace(r"-\d+$", "", regex=True) + .tolist() + ) + eib_total = round( + output_df[output_df["Balance"] == person]["Converted Amount"].sum(), 2 + ) + stmt_included_debits = round( + ps[ps["Box Transaction ID"].isin(person_eib_ids)]["Total debited"].sum(), 2 + ) + matched = abs(eib_total - stmt_included_debits) < 0.01 + audit_rows.append( + { + "Cardholder": person, + "EIB Total (USD)": eib_total, + "Statement Debits (USD)": stmt_included_debits, + "Audit Status": "MATCHED" if matched else "REVIEW REQUIRED", + } + ) + return pd.DataFrame(audit_rows) + + +def parse_pdf_with_docling(pdf_path): + """Call self-hosted Docling to extract markdown from a PDF statement.""" + try: + with open(pdf_path, "rb") as f: + response = requests.post( + f"{DOCLING_URL}/v1/convert/file", + files={"files": (os.path.basename(pdf_path), f, "application/pdf")}, + timeout=300, + ) + response.raise_for_status() + result = response.json() + + markdown = None + if isinstance(result, dict): + doc = result.get("document") + if isinstance(doc, dict): + markdown = doc.get("md_content") or doc.get("markdown") + if not markdown: + markdown = result.get("md_content") or result.get("markdown") + elif isinstance(result, list) and len(result) > 0: + first = result[0] + if isinstance(first, dict): + doc = first.get("document") + if isinstance(doc, dict): + markdown = doc.get("md_content") or doc.get("markdown") + if not markdown: + markdown = first.get("md_content") or first.get("markdown") + + if not markdown: + debug_dir = os.path.join(app.config["OUTPUT_FOLDER"], "_debug_markdown") + os.makedirs(debug_dir, exist_ok=True) + raw_path = os.path.join( + debug_dir, f"{os.path.basename(pdf_path)}.raw_response.json" + ) + with open(raw_path, "w", encoding="utf-8") as rf: + json.dump(result, rf, indent=2, default=str) + print(f"[docling] Empty markdown for {pdf_path} — raw response saved to {raw_path}") + print(f"[docling] Response keys: {list(result.keys()) if isinstance(result, dict) else type(result)}") + if isinstance(result, dict) and "status" in result: + print(f"[docling] Status: {result.get('status')}, Errors: {result.get('errors')}") + return None + + return markdown + + except Exception as e: + print(f"[docling] Request failed for {pdf_path}: {e}") + return None + + +def extract_balances_from_markdown(markdown): + """ + Extracts per-currency opening/credits/debits/closing balances from + Docling markdown by reading the summary table row structure directly. + + Docling renders the page 1 summary as a standard markdown pipe table: + | GBP | £12.29 | £0.00 | £12.27 | £0.02 | + | USD | $1,494.99 | $0.00 | $0.00 | $1,494.99 | + + Column order is always: Currency | Opening | Credits | Debits | Closing. + Each amount cell may carry a currency symbol prefix of any form + (£, $, €, CA$, ZAR, TRY, etc.) - we simply pull the first decimal + number out of each cell rather than guessing the symbol. + """ + balances = {} + + for line in markdown.splitlines(): + line = line.strip() + if not line.startswith('|'): + continue + + cells = [c.strip() for c in line.strip('|').split('|')] + if len(cells) < 5: + continue + + cur = cells[0] + if not re.match(r'^[A-Z]{3}$', cur): + continue + + amounts = [] + for cell in cells[1:5]: + m = re.search(r'-?[\d,]+\.\d{2}', cell) + if not m: + amounts = None + break + amounts.append(float(m.group(0).replace(',', ''))) + + if amounts is None: + continue + + opening, credits, debits, closing = amounts + expected = round(opening + credits - debits, 2) + diff = abs(expected - closing) + + print(f"[pdf] Row match: {cur} open={opening} cr={credits} dr={debits} " + f"close={closing} (identity diff={diff:.4f})") + + if diff < 0.05: + if cur not in balances: + balances[cur] = { + "opening": opening, + "credits": credits, + "debits": debits, + "closing": closing, + } + + print(f"[pdf] Final extracted balances: {balances}") + return balances + +def run_audit_pdf(output_df, included_box_ids, pdf_balances_by_person, raw_df): + """ + Four-layer audit, each proving a different link in the chain: + + PDF (external truth) + | [1] RAW-VS-PDF TOTALS -> is the raw export complete & accurate? + Raw file + | [2] EIB VALUE FIDELITY -> does the EIB output's actual dollar + | amounts match what the raw file says? + | [3] STRUCTURAL CHECK -> was every excluded row legitimately + EIB output zero-impact, or does it represent a + real expense that got dropped? + | [4] STATEMENT IDENTITY -> was the PDF itself parsed correctly? + + True expense impact is confirmed only when all four layers pass. + + [1] RAW-VS-PDF TOTALS (per currency): + sum(raw Total debited) vs PDF debits + sum(raw Total credited) vs PDF credits + Confirms the raw file matches the independently-generated PDF - + no missing rows, no wrong amounts. + + [2] EIB VALUE FIDELITY (raw file -> generated EIB output, explicit): + For every raw row marked as included, this reads the ACTUAL + Converted Amount that landed in the generated EIB file + (output_df) and checks it equals that row's own raw Total + debited. This is the layer that literally opens the EIB output + and confirms its numbers, not just which rows were kept. + + [3] STRUCTURAL CHECK (raw file -> EIB inclusion decisions): + Every excluded debit row is properly accounted for - either it + has zero debit impact (Credits, Card refunds, Exchange From + legs), or it's covered by an included counterpart in the same + transaction group (its real expense was captured there instead, + usually in a different currency after FX conversion). If + neither applies, step 1 dropped a transaction with real expense + impact - this is flagged explicitly, naming the transaction. + + [4] STATEMENT IDENTITY (PDF only): + opening + credits - debits == closing, per currency. + """ + raw = raw_df.copy() + raw["Box Transaction ID str"] = raw["Box Transaction ID"].astype(str) + raw["Group transaction ID str"] = raw["Group transaction ID"].astype(str) + + refund_tuples = set( + ( + str(r["Description"]).strip().lower(), + round(float(r["Total credited"]), 2), + str(r["Balance currency"]), + ) + for _, r in raw[raw["Type"] == "Card refund"].iterrows() + ) + + audit_rows = [] + for person, currency_balances in sorted(pdf_balances_by_person.items()): + ps = raw[raw["Balance"] == person] + person_eib = output_df[output_df["Balance"] == person].copy() + person_eib["base_id"] = person_eib["Transaction Number"].str.replace(r"-\d+$", "", regex=True) + + # ── [1] Raw-vs-PDF totals per currency ────────────────────────────── + raw_mismatches = [] + for cur, b in sorted(currency_balances.items()): + cur_rows = ps[ps["Balance currency"] == cur] + raw_debits = round(cur_rows["Total debited"].sum(), 2) + raw_credits = round(cur_rows["Total credited"].sum(), 2) + if abs(raw_debits - b["debits"]) >= 0.02 or abs(raw_credits - b["credits"]) >= 0.02: + raw_mismatches.append( + f"{cur}: raw dr={raw_debits:.2f}/cr={raw_credits:.2f} " + f"vs PDF dr={b['debits']:.2f}/cr={b['credits']:.2f}" + ) + + # ── [2] EIB value fidelity: does the generated file's actual dollar + # amount match what the raw file says, for every included row? + fidelity_fails = [] + included_rows = ps[ps["Box Transaction ID str"].isin(included_box_ids)] + for _, rrow in included_rows.iterrows(): + box_id = rrow["Box Transaction ID str"] + expected = round(rrow["Total debited"], 2) + eib_match = person_eib[person_eib["base_id"] == box_id] + if len(eib_match) == 0: + fidelity_fails.append(f"{box_id}: marked included but missing from EIB output") + continue + actual = round(eib_match.iloc[0]["Converted Amount"], 2) + if abs(expected - actual) >= 0.02: + fidelity_fails.append( + f"{box_id}: raw debited={expected:.2f} but EIB shows {actual:.2f}" + ) + + # ── [3] Structural check: every excluded debit accounted for ──────── + excluded = ps[~ps["Box Transaction ID str"].isin(included_box_ids)] + excluded_debits = excluded[excluded["Total debited"] > 0] + + unaccounted = [] + funding_notes = [] + for _, exrow in excluded_debits.iterrows(): + tx_type = exrow["Type"] + desc = str(exrow["Description"]) + group_id = exrow["Group transaction ID str"] + bal_cur = exrow["Balance currency"] + debited = exrow["Total debited"] + accounted = False + + if (desc.strip().lower(), round(float(debited), 2), bal_cur) in refund_tuples: + accounted = True + elif tx_type == "Card" and bal_cur not in ["USD", "EUR"]: + covers = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Exchange") + & (raw["Description"].str.startswith("To ")) + & (raw["Box Transaction ID str"].isin(included_box_ids)) + ] + if len(covers) > 0: + accounted = True + # The Exchange conversion topped up this wallet based on an + # earlier rate estimate; the Card then spent the actual + # amount at settlement. These rarely match exactly - flag + # it when the gap is more than a rounding difference, since + # it means real GBP (or other local currency) is sitting + # unused (over-funded) or was short (under-funded). + funded_amount = round(covers.iloc[0]["Payment / Exchange amount"], 2) + spent_amount = round(debited, 2) + gap = round(funded_amount - spent_amount, 2) + if abs(gap) >= 0.02: + direction = "over-funded" if gap > 0 else "under-funded" + funding_notes.append( + f"{desc[:30]}: funded {funded_amount:.2f} {bal_cur}, " + f"spent {spent_amount:.2f} {bal_cur} " + f"({direction} by {abs(gap):.2f})" + ) + elif tx_type == "Exchange" and "Auto exchange" in desc: + accounted = True + elif tx_type in ["Cash withdrawal", "Fee"]: + covers = raw[ + (raw["Group transaction ID str"] == group_id) + & (raw["Type"] == "Exchange") + & (raw["Description"].str.startswith("To ")) + & (raw["Box Transaction ID str"].isin(included_box_ids)) + ] + if len(covers) > 0: + accounted = True + + if not accounted: + unaccounted.append(f"{tx_type} {bal_cur} {debited:.2f}: {desc[:40]}") + + # ── [4] Statement identity sanity check ────────────────────────────── + identity_fails = [] + for cur, b in sorted(currency_balances.items()): + expected = round(b["opening"] + b["credits"] - b["debits"], 2) + if abs(expected - b["closing"]) > 0.02: + identity_fails.append( + f"{cur}: {b['opening']:.2f}+{b['credits']:.2f}cr-{b['debits']:.2f}dr" + f"={expected:.2f} (stated closing {b['closing']:.2f})" + ) + + # ── Build summary ───────────────────────────────────────────────────── + checks = [] + + checks.append( + "Raw file does not match PDF: " + "; ".join(raw_mismatches) + if raw_mismatches + else f"Raw file matches PDF for {len(currency_balances)} currenc" + f"{'y' if len(currency_balances)==1 else 'ies'}" + ) + + checks.append( + f"{len(fidelity_fails)} EIB value mismatch(es): " + "; ".join(fidelity_fails[:3]) + + (" ..." if len(fidelity_fails) > 3 else "") + if fidelity_fails + else f"EIB output values verified for {len(included_rows)} included row(s)" + ) + + checks.append( + f"{len(unaccounted)} excluded debit(s) NOT a true zero-impact: " + + "; ".join(unaccounted[:3]) + (" ..." if len(unaccounted) > 3 else "") + if unaccounted + else f"All {len(excluded_debits)} excluded debit(s) confirmed zero-impact" + ) + + checks.append( + "Statement identity failed: " + "; ".join(identity_fails) + if identity_fails + else "Statement identity OK" + ) + + if funding_notes: + checks.append( + f"{len(funding_notes)} FX top-up mismatch(es) (informational, not an error): " + + "; ".join(funding_notes[:3]) + (" ..." if len(funding_notes) > 3 else "") + ) + + status = ( + "MATCHED" + if not raw_mismatches and not fidelity_fails and not unaccounted and not identity_fails + else "REVIEW REQUIRED" + ) + + # Explicit per-currency totals, at a glance - the actual dollar + # figures being compared, separate from the pass/fail detail + eib_totals_str = " | ".join( + f"{cur}: {round(person_eib[person_eib['Converted Currency'] == cur]['Converted Amount'].sum(), 2):.2f}" + for cur in sorted(currency_balances.keys()) + ) + stmt_totals_str = " | ".join( + f"{cur}: {b['debits']:.2f}" for cur, b in sorted(currency_balances.items()) + ) + funding_notes_str = " | ".join(funding_notes) if funding_notes else "" + + audit_rows.append({ + "Audit Status": status, + "Cardholder": person, + "EIB Totals": eib_totals_str, + "Statement Debits": stmt_totals_str, + "Currency Checks": " | ".join(checks), + "FX Top-up Notes": funding_notes_str, + }) + return pd.DataFrame(audit_rows) + +def build_excel(output_df, audit_df=None): + """Write the EIB output Excel with optional audit table.""" + final_df = output_df.sort_values(["Balance", "_row_order"]).reset_index(drop=True) + final_df = final_df[ + [ + "Transaction Number", "Transaction Date", "Amount", "Source Currency", + "Converted Amount", "Converted Currency", "charge description line 1", + "Balance", "Card last four", + ] + ].copy() + final_df["Transaction Date"] = pd.to_datetime( + final_df["Transaction Date"] + ).dt.strftime("%Y-%m-%d") + final_df["Amount"] = final_df["Amount"].round(2) + final_df["Converted Amount"] = final_df["Converted Amount"].round(2) + final_df["Card last four"] = ( + final_df["Card last four"] + .fillna("") + .astype(str) + .str.replace("nan", "", regex=False) + ) + + today = datetime.today().strftime("%Y-%m-%d") + suffix = "_Audited" if audit_df is not None else "" + fname = f"EIB_Processed{suffix}_{today}.xlsx" + fpath = os.path.join(app.config["OUTPUT_FOLDER"], fname) + + green_fill = PatternFill("solid", fgColor="C6EFCE") + red_fill = PatternFill("solid", fgColor="FFC7CE") + hdr_fill = PatternFill("solid", fgColor="0C1A3A") + alt_fill = PatternFill("solid", fgColor="F2F2F2") + white_font = Font(color="FFFFFF", bold=True) + bold_font = Font(bold=True) + thin = Side(style="thin") + border = Border(left=thin, right=thin, top=thin, bottom=thin) + + with pd.ExcelWriter(fpath, engine="openpyxl") as writer: + final_df.to_excel(writer, index=False, sheet_name="EIB Output") + ws = writer.sheets["EIB Output"] + + for col in ws.columns: + max_len = max(len(str(cell.value or "")) for cell in col) + ws.column_dimensions[col[0].column_letter].width = min(max_len + 4, 50) + + if audit_df is not None: + audit_start_col = len(final_df.columns) + 1 + 4 + audit_headers = list(audit_df.columns) + + for j, h in enumerate(audit_headers): + c = ws.cell(row=1, column=audit_start_col + j, value=h) + c.fill = hdr_fill + c.font = white_font + c.border = border + c.alignment = Alignment(horizontal="center") + + for i, arow in audit_df.iterrows(): + for j, val in enumerate(arow): + c = ws.cell(row=i + 2, column=audit_start_col + j, value=val) + c.border = border + c.alignment = Alignment( + horizontal="left" if j == 0 else "center" + ) + if audit_headers[j] == "Audit Status": + c.fill = green_fill if val == "MATCHED" else red_fill + c.font = bold_font + elif i % 2 == 1: + c.fill = alt_fill + + col_widths = [18, 26, 22, 22, 70, 60] + for j, w in enumerate(col_widths): + if j < len(audit_headers): + ws.column_dimensions[ + get_column_letter(audit_start_col + j) + ].width = w + + return fname, fpath + + +# ── Routes ──────────────────────────────────────────────────────────────────── + +@app.route("/") +def index(): + return render_template("index.html") + + +@app.route("/home-preview") +def home_preview(): + """Temporary preview route for the new landing page design — not wired + into the real navigation yet. Remove once the landing page is approved + and the multi-tool routing is wired up for real.""" + return render_template("home.html") + + + +@app.route("/api/debug/probe-pdf", methods=["POST"]) +def api_probe_pdf(): + """ + Diagnostic endpoint. Upload one or more PDFs and this calls Docling + on each, logging the raw response structure to the container logs + (docker compose logs app) and saving full JSON dumps to + outputs/_debug_markdown/*.PROBE.json. Does not touch the normal + processing flow or produce an EIB file. + """ + pdf_files = [ + f for key, f in request.files.items() + if key.startswith("pdf_file") and f.filename + ] + if not pdf_files: + return jsonify({"error": "No PDF files uploaded"}), 400 + + results = [] + for pdf_file in pdf_files: + pdf_path = os.path.join( + app.config["UPLOAD_FOLDER"], + f"{uuid.uuid4()}_{secure_filename(pdf_file.filename)}", + ) + pdf_file.save(pdf_path) + result = probe_docling(pdf_path) + results.append({ + "filename": pdf_file.filename, + "probed": result is not None, + }) + + return jsonify({ + "status": "probed", + "files": results, + "message": "Check container logs (docker compose logs app) and " + "outputs/_debug_markdown/*.PROBE.json for full detail.", + }), 200 + + +@app.route("/api/process", methods=["POST"]) +def api_process(): + if "raw_file" not in request.files: + return jsonify({"error": "No raw file uploaded"}), 400 + + status_reset() + + try: + raw_file = request.files["raw_file"] + stmt_file = request.files.get("stmt_file") + pdf_files = [ + f for key, f in request.files.items() + if key.startswith("pdf_file") and f.filename + ] + + status_set("Reading raw file...") + raw_filename = secure_filename(raw_file.filename) + raw_path = os.path.join(app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{raw_filename}") + raw_file.save(raw_path) + + try: + raw_df = pd.read_excel(raw_path) + except Exception as e: + return jsonify({"error": f"Could not read raw file: {e}"}), 400 + + status_set("Classifying transactions...") + output_df, included_box_ids, unmapped = process_raw(raw_df) + status_log(f"Processed {len(output_df)} EIB transactions from {len(raw_df)} raw rows") + + if unmapped: + return jsonify({ + "status": "unmapped", + "unmapped": list(unmapped.keys()), + "message": f"{len(unmapped)} merchant(s) need clean names before output can be generated.", + }), 200 + + audit_df = None + + if stmt_file and stmt_file.filename: + status_set("Reading statement CSV...") + stmt_path = os.path.join( + app.config["UPLOAD_FOLDER"], + f"{uuid.uuid4()}_{secure_filename(stmt_file.filename)}", + ) + stmt_file.save(stmt_path) + try: + stmt_df = pd.read_csv(stmt_path) + status_set("Running CSV audit...") + audit_df = run_audit(output_df, included_box_ids, stmt_df) + status_log(f"Audited {len(stmt_df['Balance'].dropna().unique())} cardholder(s)") + except Exception as e: + return jsonify({"error": f"Could not read statement CSV: {e}"}), 400 + + elif pdf_files: + pdf_balances_by_person = {} + parse_errors = [] + debug_dir = os.path.join(app.config["OUTPUT_FOLDER"], "_debug_markdown") + os.makedirs(debug_dir, exist_ok=True) + + total = len(pdf_files) + for i, pdf_file in enumerate(pdf_files, start=1): + status_set(f"Converting {pdf_file.filename} via Docling ({i} of {total})...") + + pdf_path = os.path.join( + app.config["UPLOAD_FOLDER"], + f"{uuid.uuid4()}_{secure_filename(pdf_file.filename)}", + ) + pdf_file.save(pdf_path) + markdown = parse_pdf_with_docling(pdf_path) + + if markdown is None: + parse_errors.append(pdf_file.filename) + status_log(f"✕ {pdf_file.filename}: Docling conversion failed") + continue + + person_match = re.search( + r"Balances\s*\n+([A-Z][a-z]+(?: [A-Z][a-z]+)+)", markdown + ) + person_name = ( + person_match.group(1).strip() if person_match + else os.path.splitext(pdf_file.filename)[0].replace("_", " ").title() + ) + + status_set(f"Extracting balances from {pdf_file.filename} ({i} of {total})...") + balances = extract_balances_from_markdown(markdown) + + debug_path = os.path.join( + debug_dir, f"{secure_filename(pdf_file.filename)}.md" + ) + with open(debug_path, "w", encoding="utf-8") as dbg: + dbg.write(markdown) + + if balances: + pdf_balances_by_person[person_name] = balances + currencies = ", ".join(sorted(balances.keys())) + status_log(f"✓ {pdf_file.filename} -> {person_name} ({currencies})") + print(f"[docling] {pdf_file.filename} -> '{person_name}': {balances}") + else: + parse_errors.append(pdf_file.filename) + status_log(f"✕ {pdf_file.filename}: no balance table found") + print(f"[docling] No balances found in {pdf_file.filename} — " + f"markdown saved to {debug_path}") + print(f"[docling] First 1000 chars:\n{markdown[:1000]}") + + if not pdf_balances_by_person: + return jsonify({ + "status": "pdf_parse_failed", + "message": ( + f"Docling converted the PDF(s) but no balance summary table " + f"could be found in: {', '.join(parse_errors)}. " + f"Debug files saved to outputs/_debug_markdown/ for review." + ), + }), 200 + + status_set("Running PDF audit...") + audit_df = run_audit_pdf(output_df, included_box_ids, pdf_balances_by_person, raw_df) + + if parse_errors: + audit_df["Note"] = audit_df["Cardholder"].apply( + lambda p: "Parse failed" if p in parse_errors else "" + ) + + status_set("Building EIB output file...") + fname, fpath = build_excel(output_df, audit_df) + + people = sorted(output_df["Balance"].dropna().unique().tolist()) + summary = { + "rows": len(output_df), + "people": people, + "totals_usd": round( + output_df[output_df["Converted Currency"] == "USD"]["Converted Amount"].sum(), 2 + ), + "totals_gbp": round( + output_df[output_df["Converted Currency"] == "GBP"]["Converted Amount"].sum(), 2 + ), + "audit": audit_df.to_dict("records") if audit_df is not None else None, + "filename": fname, + } + status_log("Done.") + return jsonify({"status": "ok", **summary}), 200 + + finally: + status_done() + + +@app.route("/api/process/status") +def api_process_status(): + return jsonify(PROCESS_STATUS) + + +@app.route("/api/download/") +def api_download(filename): + safe = secure_filename(filename) + fpath = os.path.join(app.config["OUTPUT_FOLDER"], safe) + if not os.path.exists(fpath): + return jsonify({"error": "File not found"}), 404 + return send_file(fpath, as_attachment=True) + + +@app.route("/api/docling/status") +def docling_status(): + try: + r = requests.get(f"{DOCLING_URL}/health", timeout=5) + return jsonify({"available": r.status_code == 200}) + except Exception: + return jsonify({"available": False}) + + +if __name__ == "__main__": + os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True) + os.makedirs(app.config["OUTPUT_FOLDER"], exist_ok=True) + port = int(os.environ.get("PORT", 8080)) + app.run(host="0.0.0.0", port=port, debug=False, threaded=True) \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a3d887a --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,37 @@ +version: "3.9" + +services: + docling: + image: quay.io/docling-project/docling-serve:latest + container_name: eib_docling + ports: + - "127.0.0.1:5001:5001" + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:5001/health"] + interval: 30s + timeout: 10s + retries: 5 + start_period: 60s + + app: + build: + context: . + dockerfile: Dockerfile + container_name: eib_app + ports: + - "127.0.0.1:8081:8080" + volumes: + - ./uploads:/app/uploads + - ./outputs:/app/outputs + environment: + - FLASK_ENV=production + - DOCLING_URL=http://docling:5001 + - UPLOAD_FOLDER=/app/uploads + - OUTPUT_FOLDER=/app/outputs + - PORT=8080 + - PYTHONUNBUFFERED=1 + depends_on: + docling: + condition: service_healthy + restart: unless-stopped \ No newline at end of file diff --git a/eib-processor_how-it-works.md b/eib-processor_how-it-works.md new file mode 100644 index 0000000..b0dc492 --- /dev/null +++ b/eib-processor_how-it-works.md @@ -0,0 +1,32 @@ +# EIB Processor — How It Works + +**EIB Processor** — a small internal tool built by "Undo Designs" for **Planeterra International Foundation**. It converts a raw **Equals Money** card-spend export into a **Workday EIB** (Expense Import Batch) Excel file, and can cross-check the result against bank/card statements to flag discrepancies before finance re-keys the numbers. + +## Stack & architecture + +- **Backend**: Python 3.11 + Flask (`app/main.py`, single ~1000-line file), pandas/openpyxl for data wrangling and Excel generation. +- **Frontend**: one static page (`templates/index.html`, ~800 lines) — a dark navy/cyan-themed single-page UI with drag-and-drop upload zones, no JS framework, plain `fetch()` calls polling a status endpoint for progress. +- **PDF parsing**: a second container running **Docling** (`quay.io/docling-project/docling-serve`), called over HTTP to OCR/convert PDF bank statements into markdown. +- **Deployment**: `docker-compose.yml` runs two services — `docling` (port 5001, healthchecked) and `app` (Flask, port 8080→8081 on host), the app depends on Docling being healthy first. Uploads/outputs are bind-mounted host volumes. +- **Storage**: no database — everything is stateless, file-based (`/uploads`, `/outputs`), single-job global status dict (explicitly documented as a "single-user tool" assumption). + +## Core workflow (`app/main.py`) + +1. **Upload** a raw Equals Money `.xlsx` export. +2. **`process_raw()`** classifies each transaction row (Card, Exchange, Cash withdrawal, Fee, Credit, Refund, etc.) using a fairly intricate rules engine that: + - Drops non-expense rows (credits, refunds, internal FX "From" legs, auto-exchange). + - Collapses ATM cash-withdrawal + FX-exchange + fee row groups into a single clean "Cash withdrawal" / "Cash withdrawal fee" line. + - Maps raw merchant description strings to clean names via a hardcoded `MERCHANT_LOOKUP` dict (~50 entries); anything unmapped halts processing and reports back to the UI for the merchant to be added manually. +3. **Optional audit**, two modes: + - **CSV mode** (`run_audit`): upload a combined card-statement CSV; per cardholder, checks `sum(EIB Converted Amount) == sum(statement Total debited)`. + - **PDF mode** (`run_audit_pdf`): upload per-person PDF statements; Docling converts each to markdown, `extract_balances_from_markdown()` parses the opening/credit/debit/closing balance table, and a 4-layer audit runs (raw-vs-PDF totals → EIB value fidelity → structural "every excluded row is zero-impact" check → statement arithmetic identity), producing a much more detailed reconciliation with human-readable failure explanations. +4. **`build_excel()`** writes the final `EIB_Processed_.xlsx`, with the audit table appended 4 columns to the right of the EIB columns, color-coded green (MATCHED) / red (REVIEW REQUIRED). +5. Frontend polls `/api/process/status` for live progress text/log while processing runs, then offers a download link. + +There's also a diagnostic-only `/api/debug/probe-pdf` endpoint that dumps raw Docling responses to `outputs/_debug_markdown/*.PROBE.json` for troubleshooting extraction logic, unrelated to the main flow. + +## Notable characteristics + +- Heavily domain-specific: the transaction-classification logic encodes many real-world Equals Money quirks (ATM fee/exchange grouping, FX top-up over/under-funding detection, refund matching by description+amount+currency tuples). +- No auth, no database — designed as a trusted, local/single-user tool. +- `uploads/` currently has dozens of leftover UUID-prefixed files from prior runs (PDFs, CSVs, xlsx) — this is working/scratch data, not part of the app itself. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a6b3127 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +flask==3.0.3 +pandas==2.2.2 +openpyxl==3.1.2 +requests==2.32.3 +werkzeug==3.0.3 diff --git a/templates/home.html b/templates/home.html new file mode 100644 index 0000000..18adaef --- /dev/null +++ b/templates/home.html @@ -0,0 +1,257 @@ + + + + + +Internal Tools — Undo Designs + + + + + +
+ +
+
1 tool
+
+
+ +
+
+
Planeterra International Foundation
+

Internal Tools

+

A small collection of internal utilities. Pick one to get started.

+
+ + +
+ + + + + diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..5c3e281 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,788 @@ + + + + + +EIB Processor — Undo Designs + + + + + +
+ +
+
+
+ Docling +
+
+
+ +
+
+
Planeterra International Foundation
+

Equals Money → Workday EIB

+

Upload a raw Equals Money export to generate a clean EIB file. Optionally upload a card statement to run a per-person audit.

+
+ + +
+
+
1
+
+
Upload Equals Money Export
+
The raw Excel export from the Equals Money platform
+
+
+
+ +
+ + + + +
+
Click to browse or drag & drop
+
Excel file (.xlsx)
+
+
+
+ + +
+
+
2
+
+
Statement Audit
+
Optional — verify the output against card statements
+
+
+ +
+
+
+
+
Include statement audit
+
+ +
+
+ + +
+ +
+
+ +
+ + + + +
+
Click to browse or drag & drop
+
Combined CSV statement (all cardholders)
+
+
+
+ + +
+
+ + +
+
+
3
+
+
Process & Download
+
Generate the EIB output file
+
+
+ + +
+
+
+
+
+
Processing transactions…
+ +
+
+
+
+ + +
+
⚠ Unmapped Merchants
+
    +

    Add these to MERCHANT_LOOKUP in app/main.py and reprocess.

    +
    + + +
    +
    +
    +
    + + + +
    +
    +
    Processing complete
    +
    +
    +
    + +
    +
    +
    —
    +
    EIB Rows
    +
    +
    +
    —
    +
    USD Total
    +
    +
    +
    —
    +
    Cardholders
    +
    +
    + + + + +
    +
    +
    + + + + + + \ No newline at end of file