Compare commits

...

2 Commits

Author SHA1 Message Date
JasonFraser f89497b25d Add local generation of the Workday upload-ready EIB file
New "Generate EIB File (for Upload)" button, shown after a successful
process run, populates planeterra_equals_cards_transactions_eib_v45.xlsx
(the Workday EIB "Expense Credit Card Transaction" import template)
directly from that run's output, without a re-upload:

- app/tools/eib/logic.py: populate_upload_template() writes Header Key,
  Line Key, Transaction Number/Date, Amount, currencies, description and
  merchant name into the "Expense Credit Card Transaction" sheet, plus a
  per-file metadata row into "Credit Card Transaction Header" (Header
  Key, Credit Card Type, an auto-generated File Name covering the run's
  date range, and today's date). Corporate-card identifiers
  (AK/AM/AN) are resolved by reading eib_pre_template.xlsx's "Equals
  Card IDs" sheet at generation time rather than duplicating that
  mapping, so both output files always agree.
- app/tools/eib/routes.py: new /api/generate-upload route, backed by a
  small module-level "last processed output" holder (same single-user
  pattern as PROCESS_STATUS) so the button can reuse the prior run's
  data.
- templates/eib/index.html: the new button + status note in the result
  panel.
- .gitignore: exception for the new template, same as eib_pre_template.xlsx.

Also includes the user's own edit to eib_pre_template.xlsx (J:M formula
fill range manually extended from row 699 to row 2000).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 15:58:52 -04:00
JasonFraser a9df545952 Populate finance's EIB template instead of generating a fresh workbook
Replace build_excel() with populate_template(): loads
app/tools/eib/eib_pre_template.xlsx fresh each run, writes EIB rows into
Final Sheet A2:I<n+1> (clearing prior run's rows first) and the audit
table starting at column AA, then saves a dated copy into outputs/ —
the template itself is never mutated. Columns J:Y (finance's own
corporate-card-ID lookup formulas and a legacy static block) are never
written to; _extend_formulas_down() only fills in a missing J:M formula
within the new data range (the template's formula rows turned out to be
non-contiguous, leftover from old manual test batches) without ever
touching a row that already has one.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 15:24:21 -04:00
7 changed files with 325 additions and 44 deletions

2
.gitignore vendored
View File

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

View File

@ -65,9 +65,17 @@ to lift out shared helpers only once a second tool actually duplicates something
- `parse_pdf_with_docling()` / `extract_balances_from_markdown()` call the self-hosted
Docling container over HTTP to OCR a PDF statement into markdown and pull the
opening/credits/debits/closing balance table out of it.
- `build_excel()` writes the final `EIB_Processed[_Audited]_<date>.xlsx`, appending the
audit table 4 columns right of the EIB columns, color-coded MATCHED (green) /
REVIEW REQUIRED (red).
- `populate_template()` writes the final `EIB_Processed[_Audited]_<date>.xlsx` by loading
the finance-owned `app/tools/eib/eib_pre_template.xlsx` (tracked in git despite the
blanket `*.xlsx` gitignore rule — see the `!` exception) and writing into its
`Final Sheet`: EIB rows into `A2:I<n+1>` (clearing any previous run's rows first),
audit table starting at column `AA` (color-coded MATCHED/REVIEW REQUIRED), saved as a
new dated file — the template itself is never mutated. Columns `J:Y` are finance's own
corporate-card-ID lookup formulas (against the `Equals Card IDs` sheet) plus a legacy
static block and are **never written to**; `_extend_formulas_down()` only fills in a
`J:M` formula (translated from row 2's pattern) on rows within the new data range that
don't already have one — the template's formula rows are known to be non-contiguous
(leftover manual test batches), so gaps get filled but nothing existing is overwritten.
- `routes.py` wires uploads and these functions together behind `/eib/...`, including a
module-level `PROCESS_STATUS` dict polled by the frontend for live progress — explicitly
a single-job/single-user shortcut, not safe for concurrent runs.

Binary file not shown.

View File

@ -1,8 +1,44 @@
import os, re, 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):
@ -707,8 +743,46 @@ def run_audit_pdf(output_df, included_box_ids, pdf_balances_by_person, raw_df):
})
return pd.DataFrame(audit_rows)
def build_excel(output_df, output_folder, audit_df=None):
"""Write the EIB output Excel with optional audit table."""
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[
[
@ -729,10 +803,26 @@ def build_excel(output_df, output_folder, audit_df=None):
.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)
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")
@ -743,43 +833,152 @@ def build_excel(output_df, output_folder, audit_df=None):
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"]
if audit_df is not None:
audit_start_col = TEMPLATE_AUDIT_START_COL
audit_headers = list(audit_df.columns)
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)
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")
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
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="center")
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
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
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)

View File

@ -10,7 +10,8 @@ from .logic import (
parse_pdf_with_docling,
extract_balances_from_markdown,
run_audit_pdf,
build_excel,
populate_template,
populate_upload_template,
)
eib_bp = Blueprint("eib", __name__, url_prefix="/eib")
@ -22,11 +23,17 @@ DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001")
# status dict is enough. Reset at the start of every /api/process call.
PROCESS_STATUS = {"active": False, "current": "", "log": []}
# Holds the most recently completed run's output_df, so the "Generate EIB
# File (for Upload)" button can reuse it without re-uploading. Same
# single-user/local-tool assumption as PROCESS_STATUS.
LAST_RESULT = {"output_df": None}
def status_reset():
PROCESS_STATUS["active"] = True
PROCESS_STATUS["current"] = "Starting..."
PROCESS_STATUS["log"] = []
LAST_RESULT["output_df"] = None
def status_set(current):
@ -120,6 +127,8 @@ def api_process():
"message": f"{len(unmapped)} merchant(s) need clean names before output can be generated.",
}), 200
LAST_RESULT["output_df"] = output_df
audit_df = None
if stmt_file and stmt_file.filename:
@ -207,7 +216,7 @@ def api_process():
)
status_set("Building EIB output file...")
fname, fpath = build_excel(output_df, current_app.config["OUTPUT_FOLDER"], audit_df)
fname, fpath = populate_template(output_df, current_app.config["OUTPUT_FOLDER"], audit_df)
people = sorted(output_df["Balance"].dropna().unique().tolist())
summary = {
@ -234,6 +243,29 @@ def api_process_status():
return jsonify(PROCESS_STATUS)
@eib_bp.route("/api/generate-upload", methods=["POST"])
def api_generate_upload():
"""
Populate planeterra_equals_cards_transactions_eib_v45.xlsx (the
Workday-ready upload file) from the most recently completed /api/process
run, without requiring a re-upload.
"""
output_df = LAST_RESULT["output_df"]
if output_df is None:
return jsonify({"error": "No processed data available — run Process first."}), 400
try:
fname, fpath, unmatched = populate_upload_template(output_df, current_app.config["OUTPUT_FOLDER"])
except FileNotFoundError as e:
return jsonify({"error": f"Upload template file is missing from the server: {e}"}), 500
return jsonify({
"status": "ok",
"filename": fname,
"unmatched_cardholders": unmatched,
}), 200
@eib_bp.route("/api/download/<filename>")
def api_download(filename):
safe = secure_filename(filename)

View File

@ -522,6 +522,16 @@ footer a { color: var(--cyan); text-decoration: none; }
</svg>
Download EIB File
</button>
<button class="btn btn-ghost btn-full" id="generateUploadBtn" style="margin-top:10px">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17,8 12,3 7,8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
Generate EIB File (for Upload)
</button>
<div id="uploadGenNote" style="display:none;font-size:11px;color:var(--w3);margin-top:8px;line-height:1.5"></div>
</div>
</div>
</main>
@ -715,6 +725,8 @@ $('processBtn').addEventListener('click', async () => {
$('processBtn').disabled = true;
$('resultPanel').classList.remove('visible');
$('unmappedPanel').classList.remove('visible');
$('uploadGenNote').style.display = 'none';
$('generateUploadBtn').disabled = false;
startProgress();
const fd = new FormData();
@ -783,6 +795,34 @@ $('processBtn').addEventListener('click', async () => {
$('downloadBtn').addEventListener('click', () => {
if (lastFilename) window.location.href = '/eib/api/download/' + encodeURIComponent(lastFilename);
});
// ── Generate EIB file for upload (separate Workday-ready template) ────────────
$('generateUploadBtn').addEventListener('click', async () => {
const btn = $('generateUploadBtn');
const note = $('uploadGenNote');
btn.disabled = true;
note.style.display = 'none';
try {
const r = await fetch('/eib/api/generate-upload', { method: 'POST' });
const d = await r.json();
if (d.status === 'ok') {
note.textContent = d.unmatched_cardholders && d.unmatched_cardholders.length
? `⚠ No card-ID match for: ${d.unmatched_cardholders.join(', ')} — those rows were left blank.`
: 'Generated. Starting download…';
note.style.display = 'block';
window.location.href = '/eib/api/download/' + encodeURIComponent(d.filename);
} else {
note.textContent = d.error || 'Unexpected error';
note.style.display = 'block';
}
} catch (e) {
note.textContent = 'Network error: ' + e.message;
note.style.display = 'block';
}
btn.disabled = false;
});
</script>
</body>
</html>