diff --git a/.gitignore b/.gitignore index 7ff1182..15656a3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ __pycache__/ *.csv *.pdf !app/tools/eib/eib_pre_template.xlsx +!app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx .claude/settings.local.json diff --git a/app/tools/eib/eib_pre_template.xlsx b/app/tools/eib/eib_pre_template.xlsx index 7e49196..6171db2 100644 Binary files a/app/tools/eib/eib_pre_template.xlsx and b/app/tools/eib/eib_pre_template.xlsx differ diff --git a/app/tools/eib/logic.py b/app/tools/eib/logic.py index 42ec73f..b956a40 100644 --- a/app/tools/eib/logic.py +++ b/app/tools/eib/logic.py @@ -14,6 +14,32 @@ 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): """ @@ -841,3 +867,118 @@ def populate_template(output_df, output_folder, audit_df=None, template_path=TEM 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) diff --git a/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx b/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx new file mode 100644 index 0000000..6324c88 Binary files /dev/null and b/app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx differ diff --git a/app/tools/eib/routes.py b/app/tools/eib/routes.py index 91acd38..6983925 100644 --- a/app/tools/eib/routes.py +++ b/app/tools/eib/routes.py @@ -11,6 +11,7 @@ from .logic import ( extract_balances_from_markdown, run_audit_pdf, 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: @@ -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/") def api_download(filename): safe = secure_filename(filename) diff --git a/templates/eib/index.html b/templates/eib/index.html index ba7f437..0aa7129 100644 --- a/templates/eib/index.html +++ b/templates/eib/index.html @@ -522,6 +522,16 @@ footer a { color: var(--cyan); text-decoration: none; } Download EIB File + + + @@ -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; +}); \ No newline at end of file