Update docs for the template-population features

eib-processor_how-it-works.md still described the pre-restructure
single-file app; corrected paths and added the two-output-file workflow
(eib_pre_template.xlsx vs. planeterra_equals_cards_transactions_eib_v45.xlsx).
CLAUDE.md gains populate_upload_template()/LAST_RESULT/the generate-upload
route, and a trajectory entry for how both template features were built.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-08-18 16:13:58 -04:00
parent f89497b25d
commit 6590567c98
2 changed files with 58 additions and 14 deletions

View File

@ -76,11 +76,26 @@ to lift out shared helpers only once a second tool actually duplicates something
`J:M` formula (translated from row 2's pattern) on rows within the new data range that `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 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. (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 - `populate_upload_template()` writes a second, on-demand output —
module-level `PROCESS_STATUS` dict polled by the frontend for live progress — explicitly `EIB_Upload_<date>.xlsx` — by loading `app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx`
a single-job/single-user shortcut, not safe for concurrent runs. (also git-tracked via a `!` exception; the actual Workday EIB import template) and
writing one row per transaction into its "Expense Credit Card Transaction" sheet
(Header Key, sequential Line Key, Transaction Number/Date, Amount, currencies,
description, merchant name) plus one metadata row into "Credit Card Transaction
Header" (Header Key, Credit Card Type, an auto-generated File Name/Report Create Date
from the run's data). Corporate-card identifiers are resolved via `_load_card_id_lookup()`,
which reads `eib_pre_template.xlsx`'s "Equals Card IDs" sheet directly rather than
duplicating that mapping, so both output files always agree.
- `routes.py` wires uploads and these functions together behind `/eib/...`, including two
module-level dicts: `PROCESS_STATUS` (polled by the frontend for live progress) and
`LAST_RESULT` (holds the most recently processed `output_df` so the "Generate EIB File
for Upload" button — `/eib/api/generate-upload` — can reuse it without a re-upload).
Both are explicit single-job/single-user shortcuts, not safe for concurrent runs;
`LAST_RESULT` is cleared at the start of every new `/api/process` call.
- `templates/eib/index.html` is a single vanilla-JS page (no build step, no framework) - `templates/eib/index.html` is a single vanilla-JS page (no build step, no framework)
that polls `/eib/api/process/status` during processing. that polls `/eib/api/process/status` during processing; the result panel has two
buttons — Download EIB File (`populate_template()`'s output) and Generate EIB File for
Upload (`populate_upload_template()`'s output, fetched on click).
- To add a merchant mapping: edit `MERCHANT_LOOKUP` in `app/tools/eib/logic.py`, then - To add a merchant mapping: edit `MERCHANT_LOOKUP` in `app/tools/eib/logic.py`, then
rebuild/restart the `app` service. rebuild/restart the `app` service.
@ -123,5 +138,25 @@ blueprint in `app/main.py`, and append an entry to `TOOLS`. Don't build shared
infrastructure speculatively — wait until a second tool needs something `eib` already has, infrastructure speculatively — wait until a second tool needs something `eib` already has,
then lift just that piece into a common module. then lift just that piece into a common module.
**Next chapter — writing into finance's own Excel templates instead of generating from
scratch.** `build_excel()` originally generated a brand-new workbook every run. That was
replaced in two steps, each scoped tightly around one finance-owned template file:
1. `populate_template()` — write into `eib_pre_template.xlsx` (finance's day-to-day working
file) instead. The key constraint throughout was to never touch columns finance already
owns (J:Y — their own lookup formulas), which surfaced a real finding along the way: the
template's formula rows turned out to be non-contiguous (leftover manual test batches),
so "leave it alone" alone wasn't enough — `_extend_formulas_down()` had to actively fill
gaps within the new data range to keep those formulas actually resolving for every row.
2. `populate_upload_template()` — a second, deliberately separate on-demand output into
`planeterra_equals_cards_transactions_eib_v45.xlsx` (the real Workday EIB import
template), triggered by its own button rather than folded into the main Process step.
This is why `LAST_RESULT` exists: the button needed access to a completed run's data
without forcing a re-upload.
Both features were built the same way: inspect the real template first (sheet structure,
formulas, existing sample data) before writing any code, then confirm the ambiguous
column-mapping/behavior questions explicitly rather than guessing, since a wrong guess
here means either destroyed formulas or bad data in a file that feeds Workday.
See `eib-processor_how-it-works.md` for a deeper standalone write-up of the EIB tool's See `eib-processor_how-it-works.md` for a deeper standalone write-up of the EIB tool's
mechanics (predates the platform restructuring but still accurate for `app/tools/eib/`). mechanics (predates the platform restructuring but still accurate for `app/tools/eib/`).

View File

@ -1,16 +1,17 @@
# EIB Processor — How It Works # EIB Processor — How It Works
**EIB Processor** — a small internal tool built by "Undo Designs" for **Planeterra International Foundation**. It converts a raw **Equals Money** card-spend export into a **Workday EIB** (Expense Import Batch) Excel file, and can cross-check the result against bank/card statements to flag discrepancies before finance re-keys the numbers. **EIB Processor** — a small internal tool built by "Undo Designs" for **Planeterra International Foundation**. It converts a raw **Equals Money** card-spend export into Workday-ready Excel output, and can cross-check the result against bank/card statements to flag discrepancies before finance re-keys the numbers.
## Stack & architecture It's one tool hosted inside a small internal-tools platform — see `CLAUDE.md` for the platform-level architecture (landing page, tool registry, the Blueprint-per-tool convention). This doc is a deeper, narrative write-up of just the EIB tool itself, which lives at `app/tools/eib/` and is served at `/eib/`.
- **Backend**: Python 3.11 + Flask (`app/main.py`, single ~1000-line file), pandas/openpyxl for data wrangling and Excel generation. ## Stack
- **Frontend**: one static page (`templates/index.html`, ~800 lines) — a dark navy/cyan-themed single-page UI with drag-and-drop upload zones, no JS framework, plain `fetch()` calls polling a status endpoint for progress.
- **Backend**: Python 3.11 + Flask Blueprint (`app/tools/eib/routes.py` for request handling, `app/tools/eib/logic.py` for the actual data-processing/Excel logic — deliberately Flask-free), pandas/openpyxl for data wrangling.
- **Frontend**: `templates/eib/index.html` — a dark navy/cyan-themed single-page UI with drag-and-drop upload zones, no JS framework, plain `fetch()` calls polling a status endpoint for progress.
- **PDF parsing**: a second container running **Docling** (`quay.io/docling-project/docling-serve`), called over HTTP to OCR/convert PDF bank statements into markdown. - **PDF parsing**: a second container running **Docling** (`quay.io/docling-project/docling-serve`), called over HTTP to OCR/convert PDF bank statements into markdown.
- **Deployment**: `docker-compose.yml` runs two services — `docling` (port 5001, healthchecked) and `app` (Flask, port 8080→8081 on host), the app depends on Docling being healthy first. Uploads/outputs are bind-mounted host volumes. - **Storage**: no database — everything is file-based (`/uploads`, `/outputs`), plus two module-level dicts in `routes.py` (`PROCESS_STATUS` for progress polling, `LAST_RESULT` holding the most recently processed output) — both explicitly single-job/single-user shortcuts, not safe for concurrent runs.
- **Storage**: no database — everything is stateless, file-based (`/uploads`, `/outputs`), single-job global status dict (explicitly documented as a "single-user tool" assumption).
## Core workflow (`app/main.py`) ## Core workflow
1. **Upload** a raw Equals Money `.xlsx` export. 1. **Upload** a raw Equals Money `.xlsx` export.
2. **`process_raw()`** classifies each transaction row (Card, Exchange, Cash withdrawal, Fee, Credit, Refund, etc.) using a fairly intricate rules engine that: 2. **`process_raw()`** classifies each transaction row (Card, Exchange, Cash withdrawal, Fee, Credit, Refund, etc.) using a fairly intricate rules engine that:
@ -20,10 +21,18 @@
3. **Optional audit**, two modes: 3. **Optional audit**, two modes:
- **CSV mode** (`run_audit`): upload a combined card-statement CSV; per cardholder, checks `sum(EIB Converted Amount) == sum(statement Total debited)`. - **CSV mode** (`run_audit`): upload a combined card-statement CSV; per cardholder, checks `sum(EIB Converted Amount) == sum(statement Total debited)`.
- **PDF mode** (`run_audit_pdf`): upload per-person PDF statements; Docling converts each to markdown, `extract_balances_from_markdown()` parses the opening/credit/debit/closing balance table, and a 4-layer audit runs (raw-vs-PDF totals → EIB value fidelity → structural "every excluded row is zero-impact" check → statement arithmetic identity), producing a much more detailed reconciliation with human-readable failure explanations. - **PDF mode** (`run_audit_pdf`): upload per-person PDF statements; Docling converts each to markdown, `extract_balances_from_markdown()` parses the opening/credit/debit/closing balance table, and a 4-layer audit runs (raw-vs-PDF totals → EIB value fidelity → structural "every excluded row is zero-impact" check → statement arithmetic identity), producing a much more detailed reconciliation with human-readable failure explanations.
4. **`build_excel()`** writes the final `EIB_Processed_<date>.xlsx`, with the audit table appended 4 columns to the right of the EIB columns, color-coded green (MATCHED) / red (REVIEW REQUIRED). 4. **`populate_template()`** writes `EIB_Processed[_Audited]_<date>.xlsx` by loading finance's own `eib_pre_template.xlsx` and writing the processed rows into its `Final Sheet` (columns A:I), leaving finance's own corporate-card-ID lookup formulas (J:M) and a legacy block (N:Y) untouched, plus the audit table starting at column AA. The template file itself is never modified — every run saves a fresh dated copy. This is the file downloaded from the main "Download EIB File" button.
5. Frontend polls `/api/process/status` for live progress text/log while processing runs, then offers a download link. 5. **`populate_upload_template()`** — a second, on-demand output. A "Generate EIB File (for Upload)" button (shown after a successful run) reuses that same run's data to populate `planeterra_equals_cards_transactions_eib_v45.xlsx`, the actual Workday EIB import template ("Expense Credit Card Transaction" + "Credit Card Transaction Header" sheets). Corporate-card identifiers here are resolved by reading `eib_pre_template.xlsx`'s "Equals Card IDs" sheet directly, so both output files always agree on the same mapping without duplicating it.
6. Frontend polls `/eib/api/process/status` for live progress text/log while processing runs, then offers both downloads.
There's also a diagnostic-only `/api/debug/probe-pdf` endpoint that dumps raw Docling responses to `outputs/_debug_markdown/*.PROBE.json` for troubleshooting extraction logic, unrelated to the main flow. There's also a diagnostic-only `/eib/api/debug/probe-pdf` endpoint that dumps raw Docling responses to `outputs/_debug_markdown/*.PROBE.json` for troubleshooting extraction logic, unrelated to the main flow.
## The two bundled Excel templates
Both live in `app/tools/eib/` and are tracked in git despite the repo's blanket `*.xlsx` gitignore rule (each has an explicit `!` exception) — they're finance-owned reference files, not generated output:
- **`eib_pre_template.xlsx`** — finance's working file. Its `Final Sheet` has our 9 output columns (A:I), finance's own VLOOKUP formulas resolving corporate-card identifiers per row (J:M, keyed off cardholder name against the `Equals Card IDs` sheet), and a legacy static block (O:Y) that predates automation and is left alone. Populated by `populate_template()`.
- **`planeterra_equals_cards_transactions_eib_v45.xlsx`** — the actual Workday EIB "Credit Card Transaction Header" + "Expense Credit Card Transaction" import template (fixed schema, Required/Optional/Format rows baked in). Populated by `populate_upload_template()`.
## Notable characteristics ## Notable characteristics