diff --git a/.gitignore b/.gitignore index 15656a3..5d8f380 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ __pycache__/ *.pdf !app/tools/eib/eib_pre_template.xlsx !app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx +!app/tools/eib/merchant_lookup.csv .claude/settings.local.json diff --git a/CLAUDE.md b/CLAUDE.md index a746bd0..2576cb0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,8 +56,8 @@ to lift out shared helpers only once a second tool actually duplicates something - `process_raw()` classifies each row of a raw Equals Money export (Card, Exchange, Cash withdrawal, Fee, Credit, Refund, ...), collapses ATM cash-withdrawal/fee/exchange transaction groups into single clean rows, and maps merchant descriptions to clean - names via the `MERCHANT_LOOKUP` dict — anything not in that dict comes back as - `unmapped` and processing halts until it's added there. + names via `_load_merchant_lookup()` (reads `merchant_lookup.csv` fresh on every call) — + anything not in there comes back as `unmapped` and processing halts until it's added. - `run_audit()` (CSV statement) and `run_audit_pdf()` (PDF statement, four-layer check: raw-vs-PDF totals, EIB value fidelity, structural zero-impact check on excluded rows, statement arithmetic identity) reconcile the generated EIB output against a real @@ -96,8 +96,14 @@ to lift out shared helpers only once a second tool actually duplicates something that polls `/eib/api/process/status` during processing; the result panel has two buttons — Download EIB File (`populate_template()`'s output) and Generate EIB File for Upload (`populate_upload_template()`'s output, fetched on click). -- To add a merchant mapping: edit `MERCHANT_LOOKUP` in `app/tools/eib/logic.py`, then - rebuild/restart the `app` service. +- Merchant mappings live in `app/tools/eib/merchant_lookup.csv` (`raw_description,clean_name`), + bind-mounted in `docker-compose.yml` (single-file mount, not baked into the image) so edits + — by hand, or via the "map it now" form the UI shows for unmapped merchants + (`POST /eib/api/merchant-mappings` → `add_merchant_mappings()`) — take effect on the very + next `/api/process` call, no rebuild or restart. The UI form re-submits the same in-browser + `File` object automatically after saving, so a run that hits unmapped merchants resumes + without a re-upload. Also git-tracked via a `!` gitignore exception, like the two `.xlsx` + templates. **Docker:** `docker-compose.yml` runs two services — `docling` (`quay.io/docling-project/docling-serve`, port 5001, healthchecked, ~60s to become healthy diff --git a/README.md b/README.md index 4acacfc..5d59ea9 100644 --- a/README.md +++ b/README.md @@ -44,12 +44,14 @@ 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/tools/eib/logic.py` and restart: +If the processor reports unmapped merchants, the result panel lets you type +a clean name for each one right there and continue processing immediately — +no code changes or restarts needed. -```bash -docker compose restart app -``` +The mappings live in `app/tools/eib/merchant_lookup.csv` (bind-mounted, so +edits — from the UI or by hand — take effect on the next run with no +rebuild). Editing it directly works too: it's a plain two-column CSV +(`raw_description,clean_name`). ## Services diff --git a/app/tools/eib/logic.py b/app/tools/eib/logic.py index b956a40..446295e 100644 --- a/app/tools/eib/logic.py +++ b/app/tools/eib/logic.py @@ -1,4 +1,4 @@ -import os, re, json, requests +import os, re, csv, json, requests from datetime import datetime import pandas as pd import openpyxl @@ -110,62 +110,41 @@ def probe_docling(pdf_path, docling_url, output_folder): 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", -} +MERCHANT_LOOKUP_PATH = os.path.join(os.path.dirname(__file__), "merchant_lookup.csv") + + +def _load_merchant_lookup(path=MERCHANT_LOOKUP_PATH): + """ + Read the raw-description -> clean-name merchant mapping fresh from + merchant_lookup.csv on every call. The CSV is bind-mounted (see + docker-compose.yml), so edits — by hand or via the "map it now" + unmapped-merchant flow in the UI — take effect on the very next run, + no restart or rebuild needed. + """ + lookup = {} + if not os.path.exists(path): + return lookup + with open(path, newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + raw = row.get("raw_description") + if raw: + lookup[raw] = row.get("clean_name") or raw + return lookup + + +def add_merchant_mappings(mappings, path=MERCHANT_LOOKUP_PATH): + """ + Add/update raw->clean merchant mappings in merchant_lookup.csv. The + whole file is rewritten (it's small) rather than appended in place, so + an existing raw_description is updated rather than duplicated. + """ + lookup = _load_merchant_lookup(path) + lookup.update(mappings) + with open(path, "w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=["raw_description", "clean_name"]) + writer.writeheader() + for raw, clean in lookup.items(): + writer.writerow({"raw_description": raw, "clean_name": clean}) def strip_prefix(desc): @@ -173,7 +152,8 @@ def strip_prefix(desc): def process_raw(raw_df, merchant_lookup=None): - lookup = {**MERCHANT_LOOKUP, **(merchant_lookup or {})} + lookup = _load_merchant_lookup() + lookup.update(merchant_lookup or {}) output_rows = [] included_box_ids = set() unmapped = {} diff --git a/app/tools/eib/merchant_lookup.csv b/app/tools/eib/merchant_lookup.csv new file mode 100644 index 0000000..b775d1c --- /dev/null +++ b/app/tools/eib/merchant_lookup.csv @@ -0,0 +1,55 @@ +raw_description,clean_name +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 +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 +Uber,Uber diff --git a/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx b/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx index 6324c88..eb1fff0 100644 Binary files a/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx and b/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx differ diff --git a/app/tools/eib/routes.py b/app/tools/eib/routes.py index 6983925..0dd58a8 100644 --- a/app/tools/eib/routes.py +++ b/app/tools/eib/routes.py @@ -12,6 +12,7 @@ from .logic import ( run_audit_pdf, populate_template, populate_upload_template, + add_merchant_mappings, ) eib_bp = Blueprint("eib", __name__, url_prefix="/eib") @@ -243,6 +244,24 @@ def api_process_status(): return jsonify(PROCESS_STATUS) +@eib_bp.route("/api/merchant-mappings", methods=["POST"]) +def api_merchant_mappings(): + """ + Add clean names for previously-unmapped merchants, submitted from the + "map it now" form in the unmapped-merchant panel. Writes straight to + merchant_lookup.csv so the very next /api/process run picks them up. + """ + data = request.get_json(silent=True) or {} + mappings = data.get("mappings") + if not mappings or not isinstance(mappings, dict): + return jsonify({"error": "No mappings provided"}), 400 + if not all(str(v).strip() for v in mappings.values()): + return jsonify({"error": "Every merchant needs a clean name"}), 400 + + add_merchant_mappings(mappings) + return jsonify({"status": "ok", "added": len(mappings)}), 200 + + @eib_bp.route("/api/generate-upload", methods=["POST"]) def api_generate_upload(): """ diff --git a/docker-compose.yml b/docker-compose.yml index a3d887a..02c7234 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,6 +24,7 @@ services: volumes: - ./uploads:/app/uploads - ./outputs:/app/outputs + - ./app/tools/eib/merchant_lookup.csv:/app/app/tools/eib/merchant_lookup.csv environment: - FLASK_ENV=production - DOCLING_URL=http://docling:5001 diff --git a/templates/eib/index.html b/templates/eib/index.html index 0aa7129..3016c42 100644 --- a/templates/eib/index.html +++ b/templates/eib/index.html @@ -311,8 +311,23 @@ table.audit-table { width: 100%; border-collapse: collapse; font-size: 12px; } .unmapped-panel.visible { display: block; } .unmapped-title { font-family: var(--disp); font-size: 13px; font-weight: 600; color: var(--amber); margin-bottom: 10px; } .unmapped-list { list-style: none; margin-bottom: 16px; } -.unmapped-list li { font-family: var(--mono); font-size: 11px; color: var(--w2); padding: 6px 0; border-bottom: 1px solid var(--w5); } +.unmapped-list li { + display: flex; align-items: center; gap: 10px; + padding: 8px 0; border-bottom: 1px solid var(--w5); +} .unmapped-list li:last-child { border-bottom: none; } +.unmapped-raw { + flex: 0 0 42%; min-width: 0; + font-family: var(--mono); font-size: 10.5px; color: var(--w2); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.unmapped-input { + flex: 1; min-width: 0; + background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px; + padding: 7px 10px; font-family: var(--mono); font-size: 11px; color: var(--w1); + outline: none; transition: border-color .2s; +} +.unmapped-input:focus { border-color: var(--cyan); } footer { position: relative; z-index: 1; text-align: center; padding: 20px; font-size: 11px; color: var(--w3); border-top: 1px solid var(--border); } footer a { color: var(--cyan); text-decoration: none; } @@ -466,8 +481,10 @@ footer a { color: var(--cyan); text-decoration: none; }
⚠ Unmapped Merchants
+

Give each one a clean name, then continue — no code changes needed.

-

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

+ +
@@ -717,8 +734,13 @@ function finishProgress() { // ── Process ─────────────────────────────────────────────────────────────────── let lastFilename = ''; +let unmappedRawNames = []; -$('processBtn').addEventListener('click', async () => { +function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +} + +async function runProcess() { const raw = $('rawFile').files[0]; if (!raw) return; @@ -746,7 +768,13 @@ $('processBtn').addEventListener('click', async () => { finishProgress(); if (d.status === 'unmapped') { - $('unmappedList').innerHTML = d.unmapped.map(m => `
  • ${m}
  • `).join(''); + unmappedRawNames = d.unmapped; + $('unmappedList').innerHTML = unmappedRawNames.map((m, i) => ` +
  • + ${escapeHtml(m)} + +
  • `).join(''); + $('mappingSaveNote').style.display = 'none'; $('unmappedPanel').classList.add('visible'); $('processBtn').disabled = false; return; @@ -789,6 +817,46 @@ $('processBtn').addEventListener('click', async () => { alert('Network error: ' + e.message); } $('processBtn').disabled = false; +} + +$('processBtn').addEventListener('click', runProcess); + +// ── Unmapped merchants: save mappings, then reprocess automatically ─────────── +$('saveMappingsBtn').addEventListener('click', async () => { + const note = $('mappingSaveNote'); + note.style.display = 'none'; + + const mappings = {}; + for (let i = 0; i < unmappedRawNames.length; i++) { + const val = $('unmappedInput' + i).value.trim(); + if (!val) { + note.textContent = 'Every merchant needs a clean name.'; + note.style.display = 'block'; + return; + } + mappings[unmappedRawNames[i]] = val; + } + + $('saveMappingsBtn').disabled = true; + try { + const r = await fetch('/eib/api/merchant-mappings', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mappings }), + }); + const d = await r.json(); + if (d.status === 'ok') { + $('unmappedPanel').classList.remove('visible'); + runProcess(); + } else { + note.textContent = d.error || 'Could not save mappings'; + note.style.display = 'block'; + } + } catch (e) { + note.textContent = 'Network error: ' + e.message; + note.style.display = 'block'; + } + $('saveMappingsBtn').disabled = false; }); // ── Download ──────────────────────────────────────────────────────────────────