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

965 lines
40 KiB
Python

import os, re, csv, json, requests
from datetime import datetime
import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from openpyxl.formula.translate import Translator
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "eib_pre_template.xlsx")
TEMPLATE_SHEET = "Final Sheet"
# A:I holds our EIB output; J:Y is finance's own formula/lookup area and is
# never touched; the audit table is written starting at column AA.
TEMPLATE_DATA_COLS = 9 # A..I
TEMPLATE_FORMULA_COLS = (10, 13) # J..M — extended downward only, never cleared
TEMPLATE_AUDIT_START_COL = 27 # AA
CARD_ID_LOOKUP_SHEET = "Equals Card IDs"
UPLOAD_TEMPLATE_PATH = os.path.join(
os.path.dirname(__file__), "planeterra_equals_cards_transactions_eib_v45.xlsx"
)
UPLOAD_TRANSACTION_SHEET = "Expense Credit Card Transaction"
UPLOAD_HEADER_SHEET = "Credit Card Transaction Header"
UPLOAD_DATA_START_ROW = 6
UPLOAD_HEADER_DATA_ROW = 6
# Column indices (1-based) on the "Expense Credit Card Transaction" sheet.
UPLOAD_COLS = {
"header_key": 2, # B
"line_key": 3, # C
"transaction_number": 4, # D
"transaction_date": 6, # F
"amount": 19, # S
"source_currency": 22, # V
"converted_amount": 24, # X
"converted_currency": 26, # Z
"charge_description": 32, # AF
"expense_credit_card_id": 37, # AK
"corporate_account": 39, # AM
"cardholder_id": 40, # AN
"merchant_name": 45, # AS
}
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_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):
return re.sub(r"^To \w+ for ", "", str(desc)).strip()
def process_raw(raw_df, merchant_lookup=None):
lookup = _load_merchant_lookup()
lookup.update(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 _extend_formulas_down(ws, cols, first_row, last_row):
"""
Ensure every row in [first_row, last_row] has a formula in each of
`cols`, using row `first_row`'s formula as the canonical pattern
(relative-reference translated per row). The template's formula rows
are known to be non-contiguous — leftover from earlier manual test
batches — so this fills every gap in the current data range rather
than just extending past the last existing formula row. Never
overwrites a cell that already has a formula.
"""
for col in cols:
source_cell = ws.cell(row=first_row, column=col)
if not (isinstance(source_cell.value, str) and source_cell.value.startswith("=")):
continue # no canonical formula in this column to propagate
source_formula = source_cell.value
source_coord = source_cell.coordinate
for r in range(first_row, last_row + 1):
cell = ws.cell(row=r, column=col)
if isinstance(cell.value, str) and cell.value.startswith("="):
continue # already has a formula, leave it alone
cell.value = Translator(source_formula, origin=source_coord).translate_formula(
cell.coordinate
)
def populate_template(output_df, output_folder, audit_df=None, template_path=TEMPLATE_PATH):
"""
Populate finance's eib_pre_template.xlsx with this run's output instead
of generating a fresh workbook from scratch.
Writes EIB rows into 'Final Sheet' A2:I<n+1>, clearing any previous
data first. Columns J:Y (finance's own card-ID lookup formulas and a
legacy mirrored block) are never written to or cleared — the J:M
formulas are guarded with IF(A<>"",...) so they resolve to blank on
rows with no data, and are only ever extended downward (never
overwritten) if a run has more rows than the template currently
covers. The audit table, if provided, is written starting at column AA.
Saves a dated copy into output_folder; the template itself is untouched.
"""
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)
)
wb = openpyxl.load_workbook(template_path)
ws = wb[TEMPLATE_SHEET]
old_max_row = ws.max_row
# Clear any previous run's data out of A:I (header row untouched).
for r in range(2, old_max_row + 1):
for c in range(1, TEMPLATE_DATA_COLS + 1):
ws.cell(row=r, column=c).value = None
for i, row in enumerate(final_df.itertuples(index=False), start=2):
for c, val in enumerate(row, start=1):
ws.cell(row=i, column=c, value=val)
last_data_row = len(final_df) + 1
if last_data_row > 1:
_extend_formulas_down(
ws, range(TEMPLATE_FORMULA_COLS[0], TEMPLATE_FORMULA_COLS[1] + 1),
first_row=2, last_row=last_data_row,
)
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)
if audit_df is not None:
audit_start_col = TEMPLATE_AUDIT_START_COL
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
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)
wb.save(fpath)
return fname, fpath
def _load_card_id_lookup(lookup_path):
"""
Read the cardholder -> corporate-card-ID mapping straight from
eib_pre_template.xlsx's 'Equals Card IDs' sheet (CC Holder, Expense
Credit Card ID [formula], ID, Corporate Account, Card Ending) instead
of duplicating it here, so both output files always agree with
whatever finance currently has on file there. Expense Credit Card ID
is recomputed from ID/Corporate Account/Card Ending rather than read
from the sheet's own formula, matching that formula's own pattern
(Corporate Account & "-" & ID & "-" & Card Ending).
"""
wb = openpyxl.load_workbook(lookup_path)
ws = wb[CARD_ID_LOOKUP_SHEET]
lookup = {}
for holder, _formula, card_id, corp_account, card_ending in ws.iter_rows(
min_row=2, max_col=5, values_only=True
):
if not holder:
continue
lookup[str(holder).strip()] = {
"expense_credit_card_id": f"{corp_account}-{card_id}-{card_ending}",
"corporate_account": corp_account,
"cardholder_id": card_id,
}
return lookup
def _format_period_label(dates):
dmin, dmax = min(dates), max(dates)
if (dmin.year, dmin.month) == (dmax.year, dmax.month):
return f"{dmin.strftime('%B')} {dmin.day} - {dmax.day} {dmin.year} Equals Card Transactions"
return f"{dmin.strftime('%B %d, %Y')} - {dmax.strftime('%B %d, %Y')} Equals Card Transactions"
def populate_upload_template(output_df, output_folder,
template_path=UPLOAD_TEMPLATE_PATH,
lookup_path=TEMPLATE_PATH):
"""
Populate finance's Workday-ready
planeterra_equals_cards_transactions_eib_v45.xlsx from this run's
output (a separate, on-demand output from eib_pre_template.xlsx).
Writes one row per transaction into 'Expense Credit Card Transaction'
(Header Key, Line Key, Transaction Number, Transaction Date, Amount,
Source/Converted Currency, Converted Amount, Charge Description,
Merchant Name, and the three corporate-card-ID fields resolved via
_load_card_id_lookup), clearing any previous run's rows first, plus a
single per-file metadata row in 'Credit Card Transaction Header'
(Header Key, Credit Card Type, a generated File Name covering this
run's date range, and today's date as Report Create Date). Saves a
dated copy into output_folder; the template itself is never mutated.
Returns (filename, filepath, unmatched_cardholders) — cardholders with
no row in the 'Equals Card IDs' lookup get blank ID fields, and their
names are returned so the caller can surface a warning.
"""
final_df = output_df.sort_values(["Balance", "_row_order"]).reset_index(drop=True)
final_df["Transaction Date"] = pd.to_datetime(final_df["Transaction Date"])
final_df["Amount"] = final_df["Amount"].round(2)
final_df["Converted Amount"] = final_df["Converted Amount"].round(2)
lookup = _load_card_id_lookup(lookup_path)
unmatched_cardholders = set()
wb = openpyxl.load_workbook(template_path)
ws = wb[UPLOAD_TRANSACTION_SHEET]
c = UPLOAD_COLS
old_max_row = ws.max_row
for r in range(UPLOAD_DATA_START_ROW, old_max_row + 1):
for col in c.values():
ws.cell(row=r, column=col).value = None
for i, (_, row) in enumerate(final_df.iterrows(), start=UPLOAD_DATA_START_ROW):
cardholder = row["Balance"]
ids = lookup.get(str(cardholder).strip())
if ids is None:
unmatched_cardholders.add(cardholder)
ids = {"expense_credit_card_id": "", "corporate_account": "", "cardholder_id": ""}
ws.cell(row=i, column=c["header_key"], value=1)
ws.cell(row=i, column=c["line_key"], value=i - UPLOAD_DATA_START_ROW + 1)
ws.cell(row=i, column=c["transaction_number"], value=row["Transaction Number"])
ws.cell(row=i, column=c["transaction_date"], value=row["Transaction Date"].to_pydatetime())
ws.cell(row=i, column=c["amount"], value=row["Amount"])
ws.cell(row=i, column=c["source_currency"], value=row["Source Currency"])
ws.cell(row=i, column=c["converted_amount"], value=row["Converted Amount"])
ws.cell(row=i, column=c["converted_currency"], value=row["Converted Currency"])
ws.cell(row=i, column=c["charge_description"], value=row["charge description line 1"])
ws.cell(row=i, column=c["merchant_name"], value=row["charge description line 1"])
ws.cell(row=i, column=c["expense_credit_card_id"], value=ids["expense_credit_card_id"])
ws.cell(row=i, column=c["corporate_account"], value=ids["corporate_account"])
ws.cell(row=i, column=c["cardholder_id"], value=ids["cardholder_id"])
hws = wb[UPLOAD_HEADER_SHEET]
hws.cell(row=UPLOAD_HEADER_DATA_ROW, column=2, value=1) # Header Key*
hws.cell(row=UPLOAD_HEADER_DATA_ROW, column=8, value="Mastercard") # Credit Card Type*
if len(final_df) > 0:
hws.cell(
row=UPLOAD_HEADER_DATA_ROW, column=6,
value=_format_period_label(final_df["Transaction Date"].tolist()),
) # File Name
hws.cell(row=UPLOAD_HEADER_DATA_ROW, column=7, value=datetime.today()) # Report Create Date
if unmatched_cardholders:
print(f"[upload-template] No card-ID match for: {', '.join(sorted(unmatched_cardholders))}")
today = datetime.today().strftime("%Y-%m-%d")
fname = f"EIB_Upload_{today}.xlsx"
fpath = os.path.join(output_folder, fname)
wb.save(fpath)
return fname, fpath, sorted(unmatched_cardholders)