equals-wd-card-expense-proc.../CLAUDE.md

169 lines
11 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
An internal tools platform for Planeterra International Foundation, built by
Undo Designs. It currently hosts one tool, the **EIB Processor**
(Equals Money → Workday EIB transformer and statement auditor), but the app
is structured so additional tools can be added as self-contained modules
behind a shared landing page.
## Commands
```bash
docker compose up --build # start everything (app + Docling), foreground
docker compose up --build -d app # rebuild + restart just the Flask app after code changes
docker compose down # stop and remove both containers
docker logs eib_app --tail 50 # tail the Flask app's logs
```
- App: http://localhost:8081 (landing page) / http://localhost:8081/eib/ (EIB tool)
- Only `./uploads` and `./outputs` are bind-mounted (see `docker-compose.yml`) — everything
else is baked into the image at build time, so **code/template edits require a rebuild**
(`docker compose up --build -d app`) to show up; there is no hot reload.
- There is no test suite or linter configured. `python3 -m py_compile <file>` is the
fastest available sanity check after editing a `.py` file.
- Running `python app/main.py` outside Docker will fail on the default
`UPLOAD_FOLDER`/`OUTPUT_FOLDER` paths (`/app/uploads`, `/app/outputs`) unless those env
vars are overridden — they're container-absolute paths, not repo-relative.
## Architecture
**Platform shell — `app/main.py`:** a small Flask app factory. It registers each tool's
Blueprint, defines the `/` route (renders `templates/home.html`), and holds a `TOOLS` list
— one dict per tool (name, tagline, description, url) — that `home.html` loops over to
render tool cards. Adding a tool to the landing page is just appending to `TOOLS`.
**Tool convention — `app/tools/<name>/`:** each tool is a self-contained package:
- `routes.py` — a Flask `Blueprint` with `url_prefix="/<name>"`. All of the tool's page
and API routes live under that prefix (e.g. `/eib/`, `/eib/api/process`), so tool APIs
are namespaced and can't collide with a future tool's routes. Request handling,
`current_app.config` access, and any tool-local mutable state live here.
- `logic.py` — the tool's actual business logic, deliberately Flask-free (no `app`/
`current_app`/`request` imports; config like folder paths or external service URLs are
passed in as plain arguments). This is what makes a tool "simple but modular": the
transformation rules are portable and readable without the web plumbing.
- Its own `templates/<name>/` folder for the tool's page.
There's intentionally no shared `app/common.py` yet — the plan (per prior discussion) is
to lift out shared helpers only once a second tool actually duplicates something from
`eib`, not preemptively.
**The EIB tool (`app/tools/eib/`):**
- `logic.py` does the real work:
- `process_raw()` classifies each row of a raw Equals Money export (Card, Exchange,
Cash withdrawal, Fee, Credit, Refund, ...), collapses ATM cash-withdrawal/fee/exchange
transaction groups into single clean rows, and maps merchant descriptions to clean
names via `_load_merchant_lookup()` (reads `merchant_lookup.csv` fresh on every call) —
anything not in there comes back as `unmapped` and processing halts until it's added.
- `run_audit()` (CSV statement) and `run_audit_pdf()` (PDF statement, four-layer check:
raw-vs-PDF totals, EIB value fidelity, structural zero-impact check on excluded rows,
statement arithmetic identity) reconcile the generated EIB output against a real
statement, per cardholder.
- `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.
- `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.
- `populate_upload_template()` writes a second, on-demand output —
`EIB_Upload_<date>.xlsx` — by loading `app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx`
(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)
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).
- Merchant mappings live in `app/tools/eib/merchant_lookup.csv` (`raw_description,clean_name`),
bind-mounted in `docker-compose.yml` (single-file mount, not baked into the image) so edits
— by hand, or via the "map it now" form the UI shows for unmapped merchants
(`POST /eib/api/merchant-mappings` → `add_merchant_mappings()`) — take effect on the very
next `/api/process` call, no rebuild or restart. The UI form re-submits the same in-browser
`File` object automatically after saving, so a run that hits unmapped merchants resumes
without a re-upload. Also git-tracked via a `!` gitignore exception, like the two `.xlsx`
templates.
**Docker:** `docker-compose.yml` runs two services — `docling`
(`quay.io/docling-project/docling-serve`, port 5001, healthchecked, ~60s to become healthy
on first start) and `app` (this Flask app, host `8081` → container `8080`), with `app`
waiting on Docling's healthcheck via `depends_on`. No database; all state is files under
`uploads/` (temp uploads) and `outputs/` (generated Excel files, plus
`outputs/_debug_markdown/` where Docling's raw responses and extracted markdown get
dumped for debugging PDF parsing failures).
## Project trajectory
This started as a single-purpose Flask app: one `app/main.py` (~1000 lines, routes and
business logic together) serving one template at `templates/index.html`, with no other
tools in mind.
The decision was made to grow it into a small platform hosting several internal tools
behind one landing page. That happened in two deliberate steps rather than one big
rewrite:
1. **Landing page first, in isolation.** `templates/home.html` was built and previewed
behind a throwaway `/home-preview` route so the design (navy/cyan theme matching the
EIB tool, a card grid, a "more tools soon" placeholder) could be reviewed live without
touching the working EIB tool at all.
2. **Restructure once the design was approved.** The EIB tool was split into
`app/tools/eib/` (`routes.py` + `logic.py`, per the "simple but modular" convention
above), given its own `/eib` URL prefix and namespaced API routes, and the temporary
`/home-preview` route was replaced by the real `/` route driven by the `TOOLS` registry
in `app/main.py`.
The explicit reasoning behind the module boundary (routes vs. logic, one Blueprint per
tool, no shared `core` package yet) is: keep each tool's business logic simple and
testable in isolation, while keeping the platform shell (`main.py`) thin enough that
adding tool #2 doesn't require touching tool #1.
**For the next tool:** create `app/tools/<name>/` following the `eib` pattern (Blueprint
with `url_prefix="/<name>"`, Flask-free `logic.py`), add `templates/<name>/`, register the
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,
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
mechanics (predates the platform restructuring but still accurate for `app/tools/eib/`).