diff --git a/.gitignore b/.gitignore index 4d95ed3..7ff1182 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ __pycache__/ *.xlsx *.csv *.pdf +!app/tools/eib/eib_pre_template.xlsx .claude/settings.local.json diff --git a/CLAUDE.md b/CLAUDE.md index 6a4d9d8..2753f9f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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]_.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]_.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` (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. diff --git a/app/tools/eib/eib_pre_template.xlsx b/app/tools/eib/eib_pre_template.xlsx new file mode 100644 index 0000000..7e49196 Binary files /dev/null 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 4f436fb..42ec73f 100644 --- a/app/tools/eib/logic.py +++ b/app/tools/eib/logic.py @@ -1,8 +1,18 @@ 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 def probe_docling(pdf_path, docling_url, output_folder): @@ -707,8 +717,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, 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 +777,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 +807,37 @@ 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 diff --git a/app/tools/eib/routes.py b/app/tools/eib/routes.py index fcab0f5..91acd38 100644 --- a/app/tools/eib/routes.py +++ b/app/tools/eib/routes.py @@ -10,7 +10,7 @@ from .logic import ( parse_pdf_with_docling, extract_balances_from_markdown, run_audit_pdf, - build_excel, + populate_template, ) eib_bp = Blueprint("eib", __name__, url_prefix="/eib") @@ -207,7 +207,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 = {