Move merchant mapping to a bind-mounted CSV, add in-UI mapping flow

MERCHANT_LOOKUP was a hardcoded dict in logic.py, so adding a merchant
meant editing Python and rebuilding the Docker image just to add one
row of data. Replaces it with:

- app/tools/eib/merchant_lookup.csv (raw_description,clean_name),
  bind-mounted in docker-compose.yml so edits (by hand or via the app)
  take effect on the next run — no rebuild, no restart.
- logic.py: _load_merchant_lookup() reads it fresh on every
  process_raw() call; add_merchant_mappings() rewrites it with new
  entries merged in.
- routes.py: new POST /api/merchant-mappings endpoint.
- templates/eib/index.html: the unmapped-merchant panel is now a form
  (raw name -> editable clean-name input per merchant, prefilled with
  the raw name) with a "Save & Continue Processing" button. Saving
  posts the mappings, then automatically resubmits the same in-browser
  File object to /api/process — no re-upload needed to resume.

Verified end to end: removed a known mapping to trigger the unmapped
path with zero rebuild (confirming the bind mount), saved it back via
curl, confirmed the CSV was updated on the host, and confirmed
reprocessing succeeded immediately after.

Also includes the user's own edits to eib_pre_template.xlsx and
planeterra_equals_cards_transactions_eib_v45.xlsx made directly in
Excel/Numbers outside this session.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-08-19 11:55:43 -04:00
parent 6590567c98
commit e339b7147a
9 changed files with 203 additions and 71 deletions

1
.gitignore vendored
View File

@ -8,4 +8,5 @@ __pycache__/
*.pdf *.pdf
!app/tools/eib/eib_pre_template.xlsx !app/tools/eib/eib_pre_template.xlsx
!app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx !app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx
!app/tools/eib/merchant_lookup.csv
.claude/settings.local.json .claude/settings.local.json

View File

@ -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, - `process_raw()` classifies each row of a raw Equals Money export (Card, Exchange,
Cash withdrawal, Fee, Credit, Refund, ...), collapses ATM cash-withdrawal/fee/exchange Cash withdrawal, Fee, Credit, Refund, ...), collapses ATM cash-withdrawal/fee/exchange
transaction groups into single clean rows, and maps merchant descriptions to clean 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 names via `_load_merchant_lookup()` (reads `merchant_lookup.csv` fresh on every call) —
`unmapped` and processing halts until it's added there. 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: - `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, 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 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 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 buttons — Download EIB File (`populate_template()`'s output) and Generate EIB File for
Upload (`populate_upload_template()`'s output, fetched on click). Upload (`populate_upload_template()`'s output, fetched on click).
- To add a merchant mapping: edit `MERCHANT_LOOKUP` in `app/tools/eib/logic.py`, then - Merchant mappings live in `app/tools/eib/merchant_lookup.csv` (`raw_description,clean_name`),
rebuild/restart the `app` service. 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` **Docker:** `docker-compose.yml` runs two services — `docling`
(`quay.io/docling-project/docling-serve`, port 5001, healthchecked, ~60s to become healthy (`quay.io/docling-project/docling-serve`, port 5001, healthchecked, ~60s to become healthy

View File

@ -44,12 +44,14 @@ of the Equals statement. The Docling health check takes ~60s on first start.
## Adding new merchants ## Adding new merchants
If the processor reports unmapped merchants, add them to `MERCHANT_LOOKUP` If the processor reports unmapped merchants, the result panel lets you type
in `app/tools/eib/logic.py` and restart: a clean name for each one right there and continue processing immediately —
no code changes or restarts needed.
```bash The mappings live in `app/tools/eib/merchant_lookup.csv` (bind-mounted, so
docker compose restart app 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 ## Services

View File

@ -1,4 +1,4 @@
import os, re, json, requests import os, re, csv, json, requests
from datetime import datetime from datetime import datetime
import pandas as pd import pandas as pd
import openpyxl import openpyxl
@ -110,62 +110,41 @@ def probe_docling(pdf_path, docling_url, output_folder):
return result return result
MERCHANT_LOOKUP = { MERCHANT_LOOKUP_PATH = os.path.join(os.path.dirname(__file__), "merchant_lookup.csv")
"AIR SUITES": "AIR SUITES",
"EL ESPANOL E023 PREEMB": "EL ESPANOL E023 PREEMB",
"EURO HOTEL": "EURO HOTEL", def _load_merchant_lookup(path=MERCHANT_LOOKUP_PATH):
"EURO HOTEL LTDA": "EURO HOTEL LTDA", """
"Euronics": "Euronics", Read the raw-description -> clean-name merchant mapping fresh from
"FUENTE ALEMANA": "Fuente Alemana", merchant_lookup.csv on every call. The CSV is bind-mounted (see
"GOLDEN PRAGUE QUITO": "GOLDEN PRAGUE QUITO", docker-compose.yml), so edits — by hand or via the "map it now"
"GUARDIA VIEJA": "GUARDIA VIEJA", unmapped-merchant flow in the UI — take effect on the very next run,
"HOTEL LA CASONA $US A": "HOTEL LA CASONA $US A", no restart or rebuild needed.
"IMG INSURANCE": "IMG INSURANCE", """
"LOMIT S PROVIDENCIA": "LOMIT S PROVIDENCIA", lookup = {}
"LOYOLA INTERNACIONAL": "LOYOLA INTERNACIONAL", if not os.path.exists(path):
"Lp Latam Xp": "Lp Latam Xp", return lookup
"MARIKI AND LILAC TANZA": "MARIKI AND LILAC TANZA", with open(path, newline="", encoding="utf-8") as f:
"MERCADOPAGO *FELIXCAF": "Felixcaf - Mercado Pago", for row in csv.DictReader(f):
"MERPAGO*SANTAMONICAFO": "MERPAGO*SANTAMONICAFO", raw = row.get("raw_description")
"MI COCINA": "MI COCINA", if raw:
"MUNICH": "MUNICH", lookup[raw] = row.get("clean_name") or raw
"NGORONGORO CONSERVATIO": "NGORONGORO CONSERVATIO", return lookup
"NOE SUSHIBAR N005": "NOE SUSHIBAR N005",
"ONE PAYMENT TZ AIRLINE": "ONE PAYMENT TZ AIRLINE",
"P.F. Chang's": "P.F. Chang's", def add_merchant_mappings(mappings, path=MERCHANT_LOOKUP_PATH):
"PAYU*AR*UBER": "Uber", """
"PETROCOMERCIAL ESTACIO": "PETROCOMERCIAL ESTACIO", Add/update raw->clean merchant mappings in merchant_lookup.csv. The
"PRECISION AIR SERVICES": "PRECISION AIR SERVICES", whole file is rewritten (it's small) rather than appended in place, so
"RESTAURANTE SEGUNDO MU": "RESTAURANTE SEGUNDO MU", an existing raw_description is updated rather than duplicated.
"RUMBO ESPIGON F T2": "RUMBO ESPIGON F T1", """
"RUMBO ESPIGON F T1": "RUMBO ESPIGON F T1", lookup = _load_merchant_lookup(path)
"Selcom Card Wallet": "Selcom Card Wallet", lookup.update(mappings)
"Selcom Tanzania": "Selcom Tanzania", with open(path, "w", newline="", encoding="utf-8") as f:
"SumUp * FOTO 37": "Foto 37 - SumUp", writer = csv.DictWriter(f, fieldnames=["raw_description", "clean_name"])
"THE PLANTATION LODGE &": "THE PLANTATION LODGE &", writer.writeheader()
"TULIA BOUTIQUE HOTEL": "TULIA BOUTIQUE HOTEL", for raw, clean in lookup.items():
"UBER *TRIP": "Uber", writer.writerow({"raw_description": raw, "clean_name": clean})
"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): def strip_prefix(desc):
@ -173,7 +152,8 @@ def strip_prefix(desc):
def process_raw(raw_df, merchant_lookup=None): 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 = [] output_rows = []
included_box_ids = set() included_box_ids = set()
unmapped = {} unmapped = {}

View File

@ -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
1 raw_description clean_name
2 AIR SUITES AIR SUITES
3 EL ESPANOL E023 PREEMB EL ESPANOL E023 PREEMB
4 EURO HOTEL EURO HOTEL
5 EURO HOTEL LTDA EURO HOTEL LTDA
6 Euronics Euronics
7 FUENTE ALEMANA Fuente Alemana
8 GOLDEN PRAGUE QUITO GOLDEN PRAGUE QUITO
9 GUARDIA VIEJA GUARDIA VIEJA
10 HOTEL LA CASONA $US A HOTEL LA CASONA $US A
11 IMG INSURANCE IMG INSURANCE
12 LOMIT S PROVIDENCIA LOMIT S PROVIDENCIA
13 LOYOLA INTERNACIONAL LOYOLA INTERNACIONAL
14 Lp Latam Xp Lp Latam Xp
15 MARIKI AND LILAC TANZA MARIKI AND LILAC TANZA
16 MERCADOPAGO *FELIXCAF Felixcaf - Mercado Pago
17 MERPAGO*SANTAMONICAFO MERPAGO*SANTAMONICAFO
18 MI COCINA MI COCINA
19 MUNICH MUNICH
20 NGORONGORO CONSERVATIO NGORONGORO CONSERVATIO
21 NOE SUSHIBAR N005 NOE SUSHIBAR N005
22 ONE PAYMENT TZ AIRLINE ONE PAYMENT TZ AIRLINE
23 P.F. Chang's P.F. Chang's
24 PAYU*AR*UBER Uber
25 PETROCOMERCIAL ESTACIO PETROCOMERCIAL ESTACIO
26 PRECISION AIR SERVICES PRECISION AIR SERVICES
27 RESTAURANTE SEGUNDO MU RESTAURANTE SEGUNDO MU
28 RUMBO ESPIGON F T2 RUMBO ESPIGON F T1
29 RUMBO ESPIGON F T1 RUMBO ESPIGON F T1
30 Selcom Card Wallet Selcom Card Wallet
31 Selcom Tanzania Selcom Tanzania
32 SumUp * FOTO 37 Foto 37 - SumUp
33 THE PLANTATION LODGE & THE PLANTATION LODGE &
34 TULIA BOUTIQUE HOTEL TULIA BOUTIQUE HOTEL
35 UBER *TRIP Uber
36 UBER *TRIP HELP.UBER.C UBER *TRIP HELP.UBER.C
37 UberDirectSA_2 Uber
38 WT* FEDERICO BAGGIO BO WT* FEDERICO BAGGIO BO
39 WWW.TENORSHARE.COM WWW.TENORSHARE.COM
40 WYM SOLUTIONS WYM SOLUTIONS
41 CHALACA Chalaca
42 HANSEL Y GRETEL HANSEL Y GRETEL
43 Grab Grab
44 TANTA LAP P20 TANTA LAP P20
45 LAS REYES SWING LAS REYES SWING
46 IZI*RESTAURANTE LA MAR IZI RESTAURANTE LA MAR
47 IZI*LA BRASA HCO IZI LA BRASA HCO
48 EL BODEGON EL BODEGON
49 PesaPal*Kupaga Villas PesaPal Kupaga Villas
50 PesaPal*ZANZISTAR LODG PesaPal ZANZISTAR LODG
51 DNATA ZANZIBAR SERVICE DNATA ZANZIBAR SERVICE
52 EMIRATES LEISURE RETAI EMIRATES LEISURE RETAI
53 MUGG AND BEAN ROSEBANK MUGG AND BEAN ROSEBANK
54 WWW.GRAB.COM Grab
55 Uber Uber

View File

@ -12,6 +12,7 @@ from .logic import (
run_audit_pdf, run_audit_pdf,
populate_template, populate_template,
populate_upload_template, populate_upload_template,
add_merchant_mappings,
) )
eib_bp = Blueprint("eib", __name__, url_prefix="/eib") eib_bp = Blueprint("eib", __name__, url_prefix="/eib")
@ -243,6 +244,24 @@ def api_process_status():
return jsonify(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"]) @eib_bp.route("/api/generate-upload", methods=["POST"])
def api_generate_upload(): def api_generate_upload():
""" """

View File

@ -24,6 +24,7 @@ services:
volumes: volumes:
- ./uploads:/app/uploads - ./uploads:/app/uploads
- ./outputs:/app/outputs - ./outputs:/app/outputs
- ./app/tools/eib/merchant_lookup.csv:/app/app/tools/eib/merchant_lookup.csv
environment: environment:
- FLASK_ENV=production - FLASK_ENV=production
- DOCLING_URL=http://docling:5001 - DOCLING_URL=http://docling:5001

View File

@ -311,8 +311,23 @@ table.audit-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.unmapped-panel.visible { display: block; } .unmapped-panel.visible { display: block; }
.unmapped-title { font-family: var(--disp); font-size: 13px; font-weight: 600; color: var(--amber); margin-bottom: 10px; } .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 { 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-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 { 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; } footer a { color: var(--cyan); text-decoration: none; }
@ -466,8 +481,10 @@ footer a { color: var(--cyan); text-decoration: none; }
<!-- Unmapped merchants --> <!-- Unmapped merchants -->
<div class="unmapped-panel" id="unmappedPanel"> <div class="unmapped-panel" id="unmappedPanel">
<div class="unmapped-title">⚠ Unmapped Merchants</div> <div class="unmapped-title">⚠ Unmapped Merchants</div>
<p style="font-size:12px;color:var(--w3);margin-bottom:12px">Give each one a clean name, then continue — no code changes needed.</p>
<ul class="unmapped-list" id="unmappedList"></ul> <ul class="unmapped-list" id="unmappedList"></ul>
<p style="font-size:12px;color:var(--w3)">Add these to <code style="font-family:var(--mono);font-size:11px;color:var(--cyan)">MERCHANT_LOOKUP</code> in <code style="font-family:var(--mono);font-size:11px;color:var(--cyan)">app/main.py</code> and reprocess.</p> <button class="btn btn-primary btn-full" id="saveMappingsBtn">Save &amp; Continue Processing</button>
<div id="mappingSaveNote" style="display:none;font-size:11px;color:var(--red);margin-top:8px"></div>
</div> </div>
<!-- Result --> <!-- Result -->
@ -717,8 +734,13 @@ function finishProgress() {
// ── Process ─────────────────────────────────────────────────────────────────── // ── Process ───────────────────────────────────────────────────────────────────
let lastFilename = ''; let lastFilename = '';
let unmappedRawNames = [];
$('processBtn').addEventListener('click', async () => { function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
async function runProcess() {
const raw = $('rawFile').files[0]; const raw = $('rawFile').files[0];
if (!raw) return; if (!raw) return;
@ -746,7 +768,13 @@ $('processBtn').addEventListener('click', async () => {
finishProgress(); finishProgress();
if (d.status === 'unmapped') { if (d.status === 'unmapped') {
$('unmappedList').innerHTML = d.unmapped.map(m => `<li>${m}</li>`).join(''); unmappedRawNames = d.unmapped;
$('unmappedList').innerHTML = unmappedRawNames.map((m, i) => `
<li>
<span class="unmapped-raw" title="${escapeHtml(m)}">${escapeHtml(m)}</span>
<input type="text" class="unmapped-input" id="unmappedInput${i}" value="${escapeHtml(m)}">
</li>`).join('');
$('mappingSaveNote').style.display = 'none';
$('unmappedPanel').classList.add('visible'); $('unmappedPanel').classList.add('visible');
$('processBtn').disabled = false; $('processBtn').disabled = false;
return; return;
@ -789,6 +817,46 @@ $('processBtn').addEventListener('click', async () => {
alert('Network error: ' + e.message); alert('Network error: ' + e.message);
} }
$('processBtn').disabled = false; $('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 ────────────────────────────────────────────────────────────────── // ── Download ──────────────────────────────────────────────────────────────────