# CLAUDE.md

Guidance for Claude Code when working in this repository. The architecture deliberately follows
`10-HEC/hec-photo-app` (same author, same operating model) — when in doubt, do what HEC does and read its
`CLAUDE.md` for the reasoning. Deviations are listed in `DECISIONS.md`.

## Project overview

Meeconic — school photo sales, **multi-school**. Families open a card (QR / code), see their children's
photos, order prints / digital / AI "magic" photos, and pay with Stripe. Three roles: the **admin** (everything: payment
keys, products, revenue), the **operators** (classes, photo upload, cards, orders; no keys, no revenue, products
read-only) and a head teacher with a read-only dashboard of their school. Photos are loaded BY HAND, class by class
(client brief of 2026-10-21, `DECISIONS.md`); the photographer app and the FTP are switched off, not deleted.

## Commands

```
cd backend && python -m venv venv && venv\Scripts\pip install -r requirements.txt
python main.py                      # API on http://localhost:3002 (UVICORN_RELOAD=true for dev reload)
venv\Scripts\python -m pytest -q    # ~400 tests; needs MySQL/MariaDB (XAMPP is fine), makes+drops its own meeconic_test_<pid> DB
TEST_STORAGE=s3 venv\Scripts\python -m pytest -q   # the same suite on a bucket (moto, in-process S3); CI runs both
cd frontend && npm install && npm run dev      # http://localhost:5174, proxies /api and /r to :3002
cd frontend && npm run typecheck && npx vite build
python backend/scripts/purge_demo_data.py [--apply]   # old installs only: remove the retired demo data
python backend/scripts/migrate_photos_to_s3.py [--apply [--delete-local]]   # photos on the disk -> MinIO, once
python backend/scripts/check_storage.py   # every S3 call the app makes, against the REAL bucket of .env
```

## Architecture

```
backend/
  main.py       portal API + lifespan (startup/background tasks)      admin.py   admin/director API
  ia.py         "magic photo" (storyface)
  core/         config (ALL env vars are read here, once), db (MySQL via SQLAlchemy+PyMySQL, `get_db()`), security, rate_limit (persistent),
                leader (one worker runs background tasks), logging_setup, timeutil, storage (photos on disk or MinIO)
  models/       pydantic models shared by services (PhotoInfo, FamilyInfo)
  utils/        retry (with_retries for StoryFace), code_generator (PREFIX-XXX-XXX)
  services/     school_service · photo_service · media_service · protection_service · qr_detect · scan_service
                organizer_service · photographer_service · cleanup_service · backup_service · monitor_service
                audit_service · alert_service · ai_health · email_service · card_service
                family_service (siblings) · format_service (catalogue) · brand_service (logo, watermark, sheet)
frontend/src/   pages (Portal, Admin, Director, Settings/Photos/Cards/Audit tabs) · components/protection · lib · i18n
```

Services are plain modules; routes stay thin. **No `os.getenv` outside `core/config.py`** (a few legacy
reads remain in `email_service`/`alert_service` for SMTP — move them when touching those files).

### Multi-school
A school owns families, classes, products, orders, prices and settings (`school_settings`, validated in
`school_service.SETTINGS_SPEC`). Family codes are globally unique, so a code identifies family **and** school.
The operator picks the school with `X-School`; a director's token pins them to one. Every admin query is
scoped by `school_id` — keep it that way (`tests/test_schools_settings.py`, `test_payments.py` check isolation).

### Photo storage (`core/storage.py`, read its docstring before touching it)
Photos live on this disk (`STORAGE_BACKEND=local`: dev, tests) or in a MinIO bucket (`s3`: production since
2026-10, the app server has almost no disk). Code handles a `storage.Key` (`photos/…` or `thumbs/…`), never a path:
`storage.exists/files/dirs/walk/stat/read_bytes/write_bytes/produce/move/move_tree/delete…`; a library that needs a
real file gets one from `storage.local_path(key)` (in s3: a copy in the bounded cache, `STORAGE_CACHE_MB`). Rules:
the mtime is the ARRIVAL time (RGPD) and survives moves/trash (s3 keeps it in metadata + the MySQL index
`stored_objects`, which also answers listings; `reconcile()` rebuilds it); a move is copy + verify + delete and raises
on failure; paid downloads stream from storage, never through the cache. Only `incoming/` (FTP drop + parking
folders) stays a local `Path`. Tests: `isolated_storage` fixture for a store of one's own; `TEST_STORAGE=s3` runs
everything on moto. Setup and migration: `deploy/minio/README.md`.

### Photo layout (the client's: school → class → student, no name anywhere)
```
photos/{school}/{Class}/Student {N}/foto.jpg        .qr/ = the card photo (never sold)   .protect/ = blurred cache
                                                    (storage keys: the same names on the disk and in the bucket)
photos/.trash/{school}/{batch}/…                    deleting MOVES here (restorable), outside the school folder
thumbs/{school}/{Class}/Student {N}/…               previews, mirrors the photos tree
incoming/{school}/                                  FTP drop, flat, ALWAYS on this disk (a school migrated from the single-school version keeps incoming/ itself)
photos/{school}/{photographer}/{CODE}/              HEC layout: still read; written only for a code the DB does not know (card mode)
photos/{CODE}/                                      OLD layout: still read, never written (empties itself via RGPD retention)
```
`photo_service` is the only module that knows this layout. `N` is the child's order in its class, handed out by MySQL
(`child_folders`, under a named lock) through `child_dir()`; the FAMILY is still a code (QR, orders, downloads) and
`child_folders` says which folders are its own (siblings: several). `family_dirs()` returns every folder of a code, all
layouts. A file name is unique within a family (`unique_name()`): photos are found by (code, name). A class folder
must never be read as a photographer (`photographer_dirs(root, school_id)` excludes them).

### QR reader (the organizer) — read `organizer_service.py`'s docstring before touching it
`qr_detect.detect_qr` is the single reading cascade used by the organizer **and** the live-camera scan
(`POST /api/portal/scan`): double detector gate → multi-decode → raw → CLAHE → Otsu → sharpen → OCR of the printed
code (prefixes of the school + those already on disk). Per-photographer **sticky QR** persisted in MySQL. One
organizer per active school (`run_all_organizers`, elected leader), state per school, published in `app_kv`.
Rules that came from real outages in HEC and are pinned by `tests/test_organizer.py`: `process_pending` in
`try/finally`; one bad file never kills the batch; the loop lives outside the `try` with backoff; `_move` returns
False and the result is checked; watchdog → loop via `call_soon_threadsafe`; CPU work in threads.
A QR's content becomes a **folder name**: always go through `qr_detect.extract_code` (validated), never use raw text.

### Photo protection (two independent axes, like HEC)
1. **Server**: `protection_service` blurs faces with StoryFace KIS, on demand, cached in `.protect/` with a config
   fingerprint in the filename (changing settings must change what is served). `protect_invert` is sent INVERTED.
2. **Browser**: `components/protection/*` overlays (lens / puzzle) copied from HEC; `lib/photoProtection.ts`.
The browser **never receives an original before payment**: previews come from `GET /api/media/preview/…` (signed,
expiring URL) → protected file, or — if protection is off or KIS fails — a reduced preview; on top of either, ALWAYS,
the **watermark** (client request 2026-10: `brand_service.stamped_preview`, last stage of `media_service.render_preview`,
cached with a fingerprint of its settings; a stamping failure is an error, never a clean preview). Originals are only
served by `GET /api/portal/download/…` for a **paid** order with a digital format (no watermark), staff thumbnails are clean.

### Branding (`brand_service`, Settings → Branding, admin only, default level + per school)
Logo, watermark image and 10x15 sheet background are uploaded files in `ASSETS_DIR` (re-encoded to PNG). Two levels
(2026-10-28): the default one and a school's own (`ASSETS_DIR/schools/{school}/`, watermark settings in app_kv
`brand_watermark:{school}`); `resolve(kind, school_id)` picks the school's file, else the default, asset by asset.
Routes take `scope=school`; the gallery asks `/api/brand?school=` once it knows the family. Until a default file
exists the app uses its placeholder: text logo (`components/BrandLogo.tsx` falls back to it), tiled "MEECONIC" text
watermark, the built-in sheet. The sheet template draws QR / code / class / photos at JSON positions (`card_service.DEFAULT_ZONES`).

### No personal names (project document V2, rule n°1)
The schools may not give us any first/last name. Nothing in the app collects, stores or shows one: a family is a
**code** attached to one or more **classes** (`school_classes`, typed by the operator; `students` rows carry only
`class_name`), an order carries the class chosen at checkout (`orders.class_name`, from `GET /api/portal/classes`) and
a mandatory e-mail. The legacy `first_name`/`last_name`/`family_name` columns stay for old rows and are never filled
or returned. There is no student CSV import. Do not reintroduce a name field "just for the label".
One exception (client 2026-11-23, `shipping_service`): an order sent HOME after the deadline stores the adult recipient's
name and French address in `orders.shipping_address`, shown only on the staff's order sheet, never to the portal, erased at
the school's retention. The delivery fee is inside `orders.total` (what Stripe charges) but outside every sales figure and
the school's share (`goods_total`). `home_delivery` off = the portal closes at the deadline as before.

### Family sheet (10x15 cm)
`services/card_service.py` draws the sheet as a PNG (Pillow, 3x, bundled fonts in `backend/fonts`, 100x150 mm, 305 dpi),
laid out in the coordinates of the client's printed leaflet (1135x1600; `SX`/`SY` scale it): school name from the school's
settings and its own logo top-left when uploaded (Settings → School, `brand_service.crest_path`, per school), intro, the child's photos (originals, uncropped) + QR, class chip +
access code, three big steps (the third with a screen showing the brand logo), order deadline and delivery, then the portal + contact line (no legal footer, the client's model has none).
Accent colour = the school's `brand_color`; type is the model's Montserrat Medium, squeezed
to 87 % like the model (`_sq`, measured line by line); the order deadline is the school's `order_deadline`, in red; the footer
carries the portal host + contact@meeconic.com (asked 2026-10-24). The
browser never lays it out again: preview, print sheet and `GET /api/admin/cards.zip` all show that PNG
(`/api/media/card/{school}/{code}.png`, signed like the admin thumbnails). A layout change happens in one place only.
The sheet names the children by folder ("CP A · Student 3"); the Cards tab lists school → class → Student N with a
"Generate" button (`GET /api/admin/cards`).
The QR must stay readable by the organizer (error level M, no Micro QR, 4-module quiet zone) — photographers shoot it.

### Manual loading, cards and merges (the current way photos arrive)
`services/upload_service.py`: a class = a folder; a photo uploaded to a class that is not validated waits in
`photos/.staging/{school}/{class}/`; **Validate the class** makes one pupil card per CHILD (photos sharing a child number are one card; a lone photo is a child;
family, class, `{Class}/Student N`, numbered in file-name order); a photo added afterwards is a card at once (journaled); the special Siblings folder
(`school_classes.kind='siblings'`) makes a card per photo at once. Duplicate = same bytes in the class. `GET /api/admin/cards`
is the grid (several classes, unlinked / single / family). A merge needs `confirm`, is recorded in `family_merges` and can
be undone (`family_service.unmerge`, with the cases it refuses). A sibling photo is not a class of the family. The Cards
explorer (`FileExplorer.tsx` + `ContextMenu.tsx`) works like a desktop one: click selects, double click opens, right-click
menu, Ctrl+X/C/V (`POST /api/admin/photos/transfer`, `/photos/child/move`, image files pasted from Windows are uploaded),
Delete. The trash (restore a batch) opens from the bin button of the Cards header; the Photos tab (search by date / hour /
photographer / class) is hidden unless the school turns `photos_tab` on. Deleting a class with cards needs `confirm=true`: photos to ONE trash batch, codes removed (a family with a child in
another class keeps its code), refused if one of its families PAID. Orders:
`order_service` (detail, lab folder `order-XXXX/{code}_{class}_{format}_x{qty}`, recap PDF), "Validate the order" is
`orders.validated_at`, never the batch status. Dashboards: `stats_service` (recap by product from the order lines, stats by
class with the sibling rules; the class a photo came from is stored on each order line).

### Roles, payment keys, products
`get_ctx(..., "operator")` also lets the admin in; `"admin"` alone closes a route to the operator. The operator never gets a
revenue figure (`null`). Payment keys: `payment_keys_service` (Fernet, only the last 4 characters leave the server, Journal
`critical`, the interface wins over `.env`). Products are ONE list (`school_formats`, with image, offered, order, editable kind: print / digital / pack = both for one price /
choice = the family buys print, file or both, three prices, `format_service.expand` makes `{id}`, `{id}:num`, `{id}:both`; a pack lists its
`components` [{format_id, qty}], one level, copied onto the order line and expanded by the lab zip / recap); an AI photo
is told by its filename, not by a special format; translation FR to EN/ES by `translate_service` (editable, French if down).
A product may have a print **template** (`template_service`, 2026-11-15): a PNG whose transparent zones receive the
same photo; the lab zip then holds the finished montage (JPEG, print size at 300 dpi, made lazily while the zip streams).
The order line keeps a copy of the template (content-named file under `PRODUCTS_DIR/{school}/templates/`, never
deleted); the portal never gets it (`portal_view` lists its keys).

### Photographer app (`/shoot`, `shoot_api.py`, `services/shoot_service.py`, `services/shoot_time.py`) — switched off by default
How photos find their child WITHOUT names and WITHOUT photographing a card first (not acceptable to the client). Two
ways, one per school (`shoot_assign`), a class keeps the one it started in:
- **counts** (default): the photographer scans the **class QR** (`MEEC:CLASS:{school}:{class}`) and after each child taps
  how many photos that child had. Closing a class takes a **fence**: the exact file list in the FTP folder at that
  moment. The organizer turns a closed class into children ONLY if declared total == fence size; otherwise nothing is
  assigned, the files are parked in `incoming/_unassigned/class-{id}/` and the operator is alerted. Each class owns its
  own fence, so a mistake never shifts the next class. Rules: more than `shoot_max_per_child` photos in one tap is
  refused; files with no class open are strays, parked after a wait, never guessed; events are folded in insertion
  order, never by their timestamp. `build_runs` is pure: test it.
- **time**: the camera clock is **calibrated** (the phone shows `MEEC:CAL:{school}:{ms}`, the camera shoots it, the
  organizer stores camera-minus-server offset) and after each child the photographer taps "last photo of this child".
  A photo goes to the child whose tap is the first at or after its CAPTURE time (EXIF, never arrival time); the end of
  the class is the last tap. A photo within `shoot_doubt_secs` after a tap, or a group above the maximum, is never
  guessed: it is parked in `incoming/_review/{id}/` and settled on the operator's review screen (Cards tab). Nothing
  is placed before calibration; a class is processed once quiet for `SETTLE_SECS`; stragglers are placed by time.
  `assign_by_time`, `offset_at`, `build_calibration` are pure: test them (`tests/test_shoot_time.py`).
Both: faces are never compared (biometric data of minors); every phone tap carries `at` (server clock) and `req` (so a
resent tap counts once); the phone shows its live checks ("declared N · received M" / marked, received, doubts).

### Siblings (`family_service.merge`)
Nothing can tell that two children are siblings (no names, faces never compared): someone who knows says it. The
operator ticks the pupils in the Cards tab (`POST /api/admin/families/merge`) or the parents type their second card's
code in the gallery (`POST /api/portal/link-sibling`, rate-limited like a code lookup). The second code becomes an
alias (`families.merged_into`) — a printed card keeps working — and its folders, classes, orders and consent move to
the kept code. Every place that takes a code from a family resolves aliases (`_get_family`, `ia.py`, orders).

### Parent journey and catalogue
Gallery first: two tiles, "Choose formats" and "Choose your future profession with AI" (asks which ORIGINAL when there
are several), plus ✨ per photo; the supports (print / digital / catalogue products) are chosen after, per photo. A generation always starts from an ORIGINAL (`ia.py` refuses `ia_*`
sources — project decision, drift risk). Every photo can be enlarged (`Lightbox`). The age-group selector was removed.
Extra products live in `school_products` (name FR/EN/ES, price, physical, example image re-encoded to WebP under
`PRODUCTS_DIR/{school}/`). FORMATS are an editable catalogue per school (`format_service`, `school_formats`): the 7
historical ids are built-in rows (their price stays in the `price_*` settings), new ones are `fmt-{id}` with a kind
(`print`/`digital`/`pack`) and a `magic` flag. The server validates every line against it and stores on the order what
the line delivers (`kind`, `digital`, names), so editing or deleting a format never changes a paid order.

### Frontend quality rules
Fonts are self-hosted (`@fontsource*`, never Google Fonts: GDPR). Pinch-zoom must stay enabled (no `user-scalable=no`).
Routes are `React.lazy` chunks (`App.tsx`); `ErrorBoundary` wraps the app and beacons to `POST /api/client-error`.
Global `:focus-visible` ring and `prefers-reduced-motion` live in `index.css`; modals use `role="dialog"` +
`useModalA11y` (Escape, focus return). Text colours must keep contrast >= 4.5 (`dim` = #5B6272). Service worker
(`public/sw.js`, production only) caches the shell and hashed assets, **never** `/api`, `/r` or signed media.
`npm test` (vitest) checks FR/EN/ES key parity; CI (`.github/workflows/ci.yml`) runs pytest, typecheck, tests, build.
API: GZip skips media/zips, security headers (X-Frame-Options, Permissions-Policy camera=self, HSTS in prod) are in
`main.py`. CSP must be set by whatever serves the built frontend (Stripe.js + Stripe frames need allowing).

### Money rules
Families pay TTC (VAT included); the school's share is `revenue_share_pct` of the HT = TTC / 1.20 (`config.VAT_PCT`, `stats_service.ht/school_share`, client 2026-11) — never of the TTC, and HT is TTC / 1.20, not TTC minus 20 %. Dashboard, statement PDF and the Statistics tab (admin only, same `SalesStats` component as the head teacher's page) show both.
Only `payment_status='paid'` orders count anywhere (stats, exports, labels, dashboard). The admin's **test orders** (`payment_status='test'`, Orders tab) only exist to download the lab zip without paying: listed (badged) and preparable, counted nowhere, never shown to the family. The server owns prices
(`format_service` / `school_products`) and validates every order line. **Card payments only** (client request):
`payment_method_types` comes from `config.STRIPE_PAYMENT_METHODS`, never "automatic" (Apple Pay / Google Pay pass as
`card` wallets); unpaid orders expire after
`UNPAID_ORDER_TTL_HOURS` and their PaymentIntent is cancelled. Stripe webhook: signature required in production,
amount checked, idempotent.

### Operations
`APP_ENV=production` refuses to start with weak secrets / missing Stripe keys / `STORAGE_BACKEND=s3` without its keys;
every start refuses if the photo storage does not answer (`storage.init()`). The monitor alerts if the bucket stops
answering; the daily cleanup reconciles the index and sweeps the cache. Photo backups are the MinIO admin's job; the
DATABASE copies itself hourly to `db-backups/` in MinIO (`backup_service`, read its docstring: encrypted with
`BACKUP_ENCRYPTION_KEY`, read back, restored daily into a throwaway database; `scripts/restore_backup.py`). Background tasks (cleanup, backup,
monitor, organizers) run only on the elected leader worker. Alerts go by e-mail (`alert_service`, cooldown per key).
RGPD retention is **per school** (`rgpd_days`) and every deletion is audited as `critical`.

## Conventions
- UI strings live in `frontend/src/i18n/translations.ts` in FR / EN / ES — add all three.
- Tests are pytest, never touch real data (`conftest.py` redirects every directory before the first import).
- Comments explain *why*, and the incident or bug that motivated a rule — keep that habit.
- Don't commit unless asked.

## graphify

This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.

Rules:
- When graphify-out/graph.json exists, run `graphify query "<question>"` before your first grep, search or source-file read for a codebase question, and put this rule in every subagent prompt that explores code. Read raw files only for lines the graph or an earlier read already located. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
- A committed graphify-out/graph.json is rewritten whole on every build, so a large diff to it in a pull request is expected. Do not flag it as churn or suggest skipping the graph rebuild or its hooks.
