equals-wd-card-expense-proc.../app/tools/eib/logic.py

786 lines
32 KiB
Python

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