Restructure into a multi-tool platform with blueprints
Split the EIB tool into app/tools/eib/ (routes.py for Flask glue, logic.py for Flask-free business logic), registered as a Blueprint under /eib with its own namespaced /eib/api/* routes. The home page now renders a tool registry (app/main.py TOOLS list) instead of the temporary /home-preview route, so future tools plug in the same way. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
e4cef1faec
commit
04dabbdfab
23
README.md
23
README.md
|
|
@ -1,7 +1,8 @@
|
|||
# EIB Processor
|
||||
# Internal Tools
|
||||
|
||||
Equals Money → Workday EIB transformer and statement auditor.
|
||||
Built by Undo Designs for Planeterra International Foundation.
|
||||
A small platform of internal tools for Planeterra International Foundation.
|
||||
Built by Undo Designs. Currently hosts one tool: the **EIB Processor**
|
||||
(Equals Money → Workday EIB transformer and statement auditor).
|
||||
|
||||
## Quick start
|
||||
|
||||
|
|
@ -9,9 +10,17 @@ Built by Undo Designs for Planeterra International Foundation.
|
|||
docker compose up --build
|
||||
```
|
||||
|
||||
Then open http://localhost:5000
|
||||
Then open http://localhost:8081 for the tools landing page, or go straight
|
||||
to http://localhost:8081/eib/ for the EIB Processor.
|
||||
|
||||
## What it does
|
||||
## Adding a new tool
|
||||
|
||||
Each tool lives in its own `app/tools/<name>/` package with a Flask
|
||||
`Blueprint` (routes + a `logic.py` of Flask-free business logic) and its
|
||||
own `templates/<name>/` folder. Register the blueprint and add an entry to
|
||||
the `TOOLS` list in `app/main.py` to get a card on the landing page.
|
||||
|
||||
## EIB Processor — what it does
|
||||
|
||||
1. Upload a raw Equals Money export (.xlsx)
|
||||
2. Optionally upload a combined card statement CSV for per-person audit
|
||||
|
|
@ -36,7 +45,7 @@ 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:
|
||||
in `app/tools/eib/logic.py` and restart:
|
||||
|
||||
```bash
|
||||
docker compose restart app
|
||||
|
|
@ -46,7 +55,7 @@ docker compose restart app
|
|||
|
||||
| Service | Port | Description |
|
||||
|----------|-------|------------------------------------|
|
||||
| app | 5000 | Flask web app |
|
||||
| app | 8081 | Flask web app (tools platform) |
|
||||
| docling | 5001 | Docling PDF parsing service |
|
||||
|
||||
## Volumes
|
||||
|
|
|
|||
1082
app/main.py
1082
app/main.py
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,3 @@
|
|||
from .routes import eib_bp
|
||||
|
||||
__all__ = ["eib_bp"]
|
||||
|
|
@ -0,0 +1,785 @@
|
|||
import os, re, json, requests
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
|
||||
def probe_docling(pdf_path, docling_url, output_folder):
|
||||
"""
|
||||
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(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, docling_url, output_folder):
|
||||
"""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(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, output_folder, 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(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
|
||||
|
|
@ -0,0 +1,252 @@
|
|||
import os, re, uuid, requests
|
||||
from flask import Blueprint, request, jsonify, send_file, render_template, current_app
|
||||
from werkzeug.utils import secure_filename
|
||||
import pandas as pd
|
||||
|
||||
from .logic import (
|
||||
probe_docling,
|
||||
process_raw,
|
||||
run_audit,
|
||||
parse_pdf_with_docling,
|
||||
extract_balances_from_markdown,
|
||||
run_audit_pdf,
|
||||
build_excel,
|
||||
)
|
||||
|
||||
eib_bp = Blueprint("eib", __name__, url_prefix="/eib")
|
||||
|
||||
DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001")
|
||||
|
||||
# ── 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"
|
||||
|
||||
|
||||
@eib_bp.route("/")
|
||||
def index():
|
||||
return render_template("eib/index.html")
|
||||
|
||||
|
||||
@eib_bp.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(
|
||||
current_app.config["UPLOAD_FOLDER"],
|
||||
f"{uuid.uuid4()}_{secure_filename(pdf_file.filename)}",
|
||||
)
|
||||
pdf_file.save(pdf_path)
|
||||
result = probe_docling(pdf_path, DOCLING_URL, current_app.config["OUTPUT_FOLDER"])
|
||||
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
|
||||
|
||||
|
||||
@eib_bp.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(current_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(
|
||||
current_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(current_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(
|
||||
current_app.config["UPLOAD_FOLDER"],
|
||||
f"{uuid.uuid4()}_{secure_filename(pdf_file.filename)}",
|
||||
)
|
||||
pdf_file.save(pdf_path)
|
||||
markdown = parse_pdf_with_docling(pdf_path, DOCLING_URL, current_app.config["OUTPUT_FOLDER"])
|
||||
|
||||
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, current_app.config["OUTPUT_FOLDER"], 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()
|
||||
|
||||
|
||||
@eib_bp.route("/api/process/status")
|
||||
def api_process_status():
|
||||
return jsonify(PROCESS_STATUS)
|
||||
|
||||
|
||||
@eib_bp.route("/api/download/<filename>")
|
||||
def api_download(filename):
|
||||
safe = secure_filename(filename)
|
||||
fpath = os.path.join(current_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)
|
||||
|
||||
|
||||
@eib_bp.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})
|
||||
|
|
@ -536,7 +536,7 @@ const $ = id => document.getElementById(id);
|
|||
// ── Docling status ────────────────────────────────────────────────────────────
|
||||
async function checkDocling() {
|
||||
try {
|
||||
const r = await fetch('/api/docling/status');
|
||||
const r = await fetch('/eib/api/docling/status');
|
||||
const d = await r.json();
|
||||
$('doclingDot').className = 'docling-dot' + (d.available ? ' online' : '');
|
||||
$('doclingLabel').textContent = d.available ? 'Docling · online' : 'Docling · offline';
|
||||
|
|
@ -678,7 +678,7 @@ function startProgress() {
|
|||
|
||||
statusPollInterval = setInterval(async () => {
|
||||
try {
|
||||
const r = await fetch('/api/process/status');
|
||||
const r = await fetch('/eib/api/process/status');
|
||||
const d = await r.json();
|
||||
if (d.current) $('progressLabel').textContent = d.current;
|
||||
if (d.log && d.log.length > renderedLogCount) {
|
||||
|
|
@ -729,7 +729,7 @@ $('processBtn').addEventListener('click', async () => {
|
|||
}
|
||||
|
||||
try {
|
||||
const r = await fetch('/api/process', { method: 'POST', body: fd });
|
||||
const r = await fetch('/eib/api/process', { method: 'POST', body: fd });
|
||||
const d = await r.json();
|
||||
finishProgress();
|
||||
|
||||
|
|
@ -781,7 +781,7 @@ $('processBtn').addEventListener('click', async () => {
|
|||
|
||||
// ── Download ──────────────────────────────────────────────────────────────────
|
||||
$('downloadBtn').addEventListener('click', () => {
|
||||
if (lastFilename) window.location.href = '/api/download/' + encodeURIComponent(lastFilename);
|
||||
if (lastFilename) window.location.href = '/eib/api/download/' + encodeURIComponent(lastFilename);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
|
@ -190,7 +190,7 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
Undo <span>Tools</span>
|
||||
</a>
|
||||
<div class="header-right">
|
||||
<div class="tool-count" id="toolCount">1 tool</div>
|
||||
<div class="tool-count">{{ tools|length }} tool{{ 's' if tools|length != 1 else '' }}</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
|
@ -203,7 +203,8 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
|
||||
<div class="tool-grid">
|
||||
|
||||
<a class="tool-card" href="/">
|
||||
{% for tool in tools %}
|
||||
<a class="tool-card" href="{{ tool.url }}">
|
||||
<div class="tool-card-top">
|
||||
<div class="tool-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||
|
|
@ -211,15 +212,11 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="tool-name">EIB Processor</div>
|
||||
<div class="tool-tagline">Equals Money → Workday EIB</div>
|
||||
<div class="tool-name">{{ tool.name }}</div>
|
||||
<div class="tool-tagline">{{ tool.tagline }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tool-desc">
|
||||
Converts raw Equals Money card-spend exports into clean Workday EIB
|
||||
files, with an optional per-cardholder statement audit against CSV
|
||||
or PDF statements.
|
||||
</div>
|
||||
<div class="tool-desc">{{ tool.description }}</div>
|
||||
<div class="tool-card-foot">
|
||||
<div class="tool-status"><div class="status-dot-sm"></div>Available</div>
|
||||
<div class="tool-open">
|
||||
|
|
@ -230,6 +227,7 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
</div>
|
||||
</div>
|
||||
</a>
|
||||
{% endfor %}
|
||||
|
||||
<div class="tool-card placeholder-card">
|
||||
<div class="tool-card-top">
|
||||
|
|
|
|||
Loading…
Reference in New Issue