# DECISIONS

Decisiones de diseño y en qué se aparta este proyecto de `hec-photo-app` (la referencia de arquitectura).

## Igual que HEC

- **Layout de fotos** como HEC hasta 2026-10-17 (`photos/{colegio}/{fotógrafo}/{CÓDIGO}/`, que se sigue leyendo); desde
  entonces `photos/{colegio}/{Clase}/Student N/` (petición del cliente, ver abajo). Igual que HEC: `.qr/` para la foto de la
  tarjeta, `.protect/` para la caché de caras difuminadas y papelera en `photos/.trash/{colegio}/` (borrar mueve, no destruye).
- **Lector de QR**: la misma cascada (puerta detect|detectMulti, multi-decode, CLAHE, Otsu, enfoque, OCR de rescate con los
  prefijos del colegio + los que ya hay en disco), QR pegajoso por fotógrafo, fotógrafo por prefijo del archivo, carpeta
  `_errors`, purga de no-imágenes conservando `.dat`, espera de estabilidad FTP, estado por colegio, backoff, banner de dos niveles.
- **Protección**: caras en servidor (KIS) + overlay lens/puzzle en el navegador; configuración con los mismos nombres y rangos.
- **Códigos** `PREFIJO-XXX-XXX` con alfabeto sin caracteres ambiguos; búsqueda tolerante a guiones; redirección `/r/{código}`.
- **Escaneo de fotogramas** en servidor (jsQR primero, OpenCV + OCR como respaldo cada ~3 s).
- Herramientas de fotos: buscar por fecha/hora (en la hora del evento), mover, papelera con restauración.
- `utils/retry.with_retries` para StoryFace, `ai_health` para que un fallo de fondo llegue a pantalla, `core/config` como único
  lugar donde se leen las variables de entorno.

## Distinto de HEC (y por qué)

| Tema | HEC | Aquí | Motivo |
|---|---|---|---|
| Si KIS falla | se sirve la foto **sin proteger** (fail-open) | se sirve una vista previa reducida (con la **marca de agua** encima, como toda vista previa desde 2026-10-17) | aquí el original es el producto que se vende; la familia sigue pudiendo ver y comprar, pero nunca recibe el original gratis |
| Servir fotos | montajes estáticos de `/photos` | endpoint con URL **firmada y con caducidad**; originales solo tras pagar | los estáticos permitían descargar cualquier original conociendo la ruta |
| Base de datos | MySQL + SQLAlchemy async | MySQL/MariaDB + SQLAlchemy 2.0 **síncrono** (PyMySQL, pool) tras `core.db.get_db()` | mismo servidor y variables `MYSQL_*` que HEC, pero cleanup, organizer, líder y rate limit corren en hilos y ya usaban `get_db()` síncrono: reescribirlo todo a async no aportaba nada. Se empezó en SQLite y se migró (`scripts/migrate_sqlite_to_mysql.py`) porque el servidor de producción no trabaja con SQLite |
| Multi-tenant | un subdominio por cliente | un `school_id` (cabecera `X-School` o token) | el operador gestiona todos los colegios desde un único panel y un único despliegue |
| Fotógrafo sin configurar | las fotos van a `_errors` | un fotógrafo implícito acepta todo | una instalación con un solo fotógrafo (la actual) sigue funcionando al actualizar |
| IA anticipada y ojos cerrados | hooks del organizer | **no portados** | aquí la IA la pide la familia y tiene cuota; pre-generar gastaría créditos sin venta asegurada |
| Fondo (nobg/canvas) | sí | no | fuera de alcance de este producto |
| Cálculo en el organizer | el análisis corría en el hilo del event loop | análisis y esperas en hilos (`asyncio.to_thread`) | un lote grande bloqueaba toda la API durante segundos |
| Código de familia | `PREFIJO-XXX-XXX` | igual, con el prefijo configurable por colegio | el formato antiguo `AAA-0000` (10 000 combinaciones) se podía adivinar; los códigos ya impresos siguen valiendo |
| Tarjeta de familia | React `QRCard` + espejo en Pillow (`qr_service`), sincronizados a mano y con tests de espejo | **una sola fuente**: `card_service` dibuja el PNG (Pillow a 3×, fuentes empaquetadas, 85,6×54 mm a 374 DPI) y el navegador solo lo muestra (vista previa, hoja de impresión, ZIP) | un segundo layout en el navegador es justo lo que se desincroniza; con un único render no hay nada que espejar. Se conserva de HEC: medidas en px CSS ×3, texto por baseline, letter-spacing glifo a glifo, QR igual que `/api/qr.svg` |

## Compatibilidad con la instalación anterior
- Las fotos en `photos/{CÓDIGO}/` se siguen leyendo, borrando por RGPD y vendiendo; nada se escribe ya en ese layout.
- El colegio migrado conserva la raíz de `incoming/` como carpeta FTP (no hay que cambiar la cámara); los colegios nuevos usan
  `incoming/{colegio}/`.
- Las tarjetas ya impresas (código `AAA-0000`, URL `/?code=`) siguen funcionando.

## 2026-10-10 — Expert review pass
| Decision | Why |
|---|---|
| Self-hosted fonts via `@fontsource` | Google Fonts leaks visitor IPs (GDPR); cards already bundle Inter. |
| `brand_color` per school, validated for white-text contrast >= 4.5 | Branding without letting a school make its card unreadable. Only the card header uses it for now (e-mails/portal still Meeconic navy). |
| `GET /api/admin/setup` checklist | Adapting a new school was the main friction; the list tells the operator what is missing and opens the right tab. |
| ZIP of purchased originals (`/api/portal/download-zip/{order}`) | Families with several photos no longer click one by one; stored, not deflated (JPEG). |
| Portal-facing API `detail` messages stay French | They are shown to families as-is; logs, admin and service errors are English (project rule). Next step: return error codes and translate in the UI. |
| Playwright E2E, CSP header, Sentry browser SDK: not done | Need the real deployment host / DSN; listed as follow-ups. |

## 2026-10-11 — Project document V2 (school constraints) and MySQL
| Decision | Why |
|---|---|
| **No personal names anywhere**: classes typed in the back-office, family code attached to class(es), CSV student import removed | Rule n°1 of the document: schools may not send first/last names. Per-class statistics still work from `orders.class_name` / the attachment rows. |
| Checkout asks for the **class (dropdown from the school's list)** and a **mandatory e-mail**, both blocking | The class gives the stats without a name; the e-mail is where HD files without watermark are delivered (digital and magic pack). Siblings: one class is enough (hint under the field). |
| AI offered from the gallery, supports chosen afterwards; an AI photo is never the source of another generation | Document §3.1 (AI came too late in the flow) and point 11 (drift risk of re-generating a generated face). Enforced in `ia.py`, not only in the UI. |
| Family sheet is a 10x15 cm PNG with steps, QR, code, class(es) and the child's photos | Document §2 / point 6. Still drawn once, server-side, and shown as-is everywhere. |
| Age-group selector removed (not "toggleable") | It never changed what was generated (it only picked a static example that was never reached); Boulogne does not want it. |
| Catalogue products with an example image | Document §4.3. Server-side price check like the fixed formats; a product line needs a photo so the print shop knows what to put on it. |
| **MySQL/MariaDB instead of SQLite** (SQLAlchemy 2.0 + PyMySQL, `MYSQL_*` like HEC) | The production server does not work with SQLite. Sync engine behind `core.db.get_db()` because cleanup/organizer/leader/rate limit run in threads. `scripts/migrate_sqlite_to_mysql.py` copies an existing install. Backups are SQL dumps (`.sql.gz`) written in Python. |
| An order is never expired while Stripe says its PaymentIntent succeeded (`cleanup_service.expire_unpaid_orders`) | Two orders were charged but expired because the webhook secret was missing; they are now booked as paid through the webhook's own code path, and an alert says the webhook is not configured. |

## 2026-10-12 — Photographer app instead of cards in photos
| Decision | Why |
|---|---|
| **Class QR scanned on the photographer's phone** (`/shoot`) replaces both the HEC "photograph a card before each child" and OCR of the class slate | Client: photographing a card first is not valid. A class QR is exact, needs no handwriting OCR and no `tesseract` on the server. Photos still travel by FTP untouched (professional camera). |
| **Counts, never clocks**: one tap per child declares its photos; the server assigns files in capture order | A first version matched photos to phone events by time. The client rejected it: with any FTP delay a photo lands on the wrong child and nobody sees it. A declared count is checkable; a timestamp is not. |
| Each class is closed with a **fence** (the files in the folder at that moment) and assigned only if declared == fence size | A mismatch assigns nothing and parks the class, and cannot shift the next class. The phone shows declared vs received live so it is fixed while the child is still there. |
| More than `shoot_max_per_child` photos per tap is refused | That is exactly how two children end up merged on one code, which would show a child to another family. |
| Files with no open class are strays: parked, never guessed | A photo with no active class must not reach any family; the operator is alerted. |
| No face comparison, ever | Biometric processing of minors' faces. Siblings are therefore not merged automatically (a sibling photo keeps its own code; merging is an exceptional operator action). |
| `shoot_mode` is a school setting, default off | The card-in-photo organizer keeps working for schools that use it. |

## 2026-10-16 — /shoot: a second way to assign photos (time), next to counts
Setting `shoot_assign = counts | time`, one per school; a class keeps the mode it started in (recorded in its `class` event).

| Decision | Why |
|---|---|
| **Time mode coexists with "Counts, never clocks"** (which stays the default and is untouched) | The counts way needs the photographer to count; the client may prefer one tap. The earlier objection to clocks was FTP *arrival* delay. Time mode uses the camera's *capture* time (EXIF), which an FTP delay cannot move: a 12:09 photo that arrives at 12:11 still goes where 12:09 belongs. The client chooses. |
| **The camera is calibrated, never trusted**: the phone shows a QR carrying the server time, the camera photographs it once, the organizer reads QR + EXIF and stores the offset (clock error and time zone together). A second photo verifies the first (drift > 2 s = rejected) | Nothing is set on the camera, it can be repeated at any moment, and a drifting clock is detected instead of silently shifting children. Between two calibrations the drift is interpolated. |
| **One tap per child, "last photo of this child", right after the last shot; the end of the class acts as the last tap** | Photographing a QR to mark the next child is not acceptable (client rule). A tap after the last shot sits in the natural pause between children. |
| **Every tap carries its own moment (server clock, measured by a round trip) and an id** | A tap queued offline keeps the time it was made; a tap resent because the answer was lost is recorded once. |
| **Doubt zone**: a photo within `shoot_doubt_secs` after a tap is placed only if the gaps between shots settle it (burst on one side, pause on the other, or sandwiched between two shots of one child); otherwise it goes to review. A group larger than `shoot_max_per_child` is never assigned (two children on one code) | The failure that sank the first time-based design was a *silent* misplacement. Here every uncertain photo is held, where no family can see it, until the operator decides; the goal is that the review screen stays almost empty. |
| Review screen (Photos tab): one click for a doubtful photo (previous child / next child / set aside), cut points for an oversized group | Operator-only signed previews; every decision is audited (`shoot.review`). |
| Nothing is placed until the camera is calibrated and the class has been quiet for 45 s; late files are placed by capture time afterwards | FTP can be slow; waiting costs seconds, a wrong family costs trust. An alert fires if a closed class stays uncalibrated. |
| Faces are still never compared | Biometric data of minors. The only pixels read are the calibration QR. |

Audit of the phone app (same day), fixed: a tap queued while another was being replayed was erased; two overlapping replays sent the same tap twice; a tap the server refused vanished without a word (now reported, and 5xx/429 are retried); a tap whose answer was lost was counted twice (now idempotent by id); the screen could sleep between children (wake lock); a "tap again to force" stayed armed forever (now 4.5 s); every poll wrote a row to MySQL through the rate limiter and several phones behind one wifi shared a limit (now only failed links are counted); the phone test camera stripped the capture time (it now writes it).

## 2026-10-17 — Client requests (logo, layout, cards, watermark, AI tile, card payments, catalogue)

| Decision | Why |
|---|---|
| **Disk layout `photos/{school}/{Class}/Student N/`** (the client's structure), made by the organizer; `N` is the child's order in its class, handed out by MySQL (`child_folders`, under a named lock). The family stays a CODE; a table says which folders are its own | The client asked for school / class / student folders. A folder is never the identity: the QR, the orders and the downloads keep using the code, so a sibling family can own two folders (2A/Student 3 + 3B/Student 7). No name ever reaches the disk: "Student N" only. The two older layouts are still READ (they empty themselves with the RGPD retention); a code the database does not know (card mode) still goes to HEC's `photographer/CODE` so no photo is lost |
| Counts and time modes unchanged: they still decide where a child ends; only the destination changed | The user's call: "edit count, don't replace it" |
| **A file name is unique within a family** (`photo_service.unique_name`) | Photos are found by (code, name): two siblings' `DSC_0012.jpg` would hide each other |
| **Siblings = merging codes** (`family_service.merge`): by the operator before printing (Cards tab, tick the pupils) or by the parents afterwards ("another child at the school?": they type the second card's code). The merged code is kept as an alias (`families.merged_into`): a card already printed still opens the whole family. Orders, classes, consent move; a name clash is renamed on the merged side, in its order lines too | Without names nothing can tell that two children are siblings: someone who knows must say it. Knowing a code already opens that gallery, so the parents' link gives nobody more than they had; it is rate-limited like a code lookup |
| **Per-class view with a "Generate" button** (Cards tab): school → class → Student N → the 10x15 sheet; the sheet prints "CP A · Student 3" | The client's step 5. The teacher hands the sheet to the right child by its number |
| **Watermark on every pre-payment preview** (originals, siblings, AI), as the LAST stage of `media_service.render_preview` (`brand_service.stamped_preview`); paid downloads and the staff thumbnails stay clean | Client request; this reverses the earlier "no watermark, protection is the two axes". A failure to stamp is an error, never a clean preview |
| **Placeholders until the client's assets arrive**: text logo, tiled "MEECONIC" watermark, the built-in sheet. Settings → Branding uploads the real logo / watermark image / sheet background (+ JSON positions of QR, code, class, photos); re-encoded to PNG; global, operator only | The client will send them; the site must look finished meanwhile. The watermark's look is still to be confirmed by the client |
| **Card payments only**: `payment_method_types=["card"]` fixed in `config.STRIPE_PAYMENT_METHODS`; Apple Pay / Google Pay on in the Payment Element since 2026-10-24 (they are cards in a wallet) | Client request. Fixed in code so a Stripe dashboard change cannot add a method back. Apple Pay needs the portal domain registered in Stripe (Settings → Payment method domains). Bank account / Stripe account ("Myconic") is configuration, to confirm with Julio |
| **Editable catalogue of formats** (`format_service`, table `school_formats`): the 7 historical formats become rows (renamed, re-ordered, switched off, re-priced — their price still lives in the `price_*` settings, one source of truth), new formats/sizes are added with a kind (`print` / `digital` / `pack`) and an AI flag. The order line stores what it delivers (`kind`, `digital`, names) | Client: "create formats, sizes and products and set their prices ourselves". A format edited or deleted later never changes what a paid order gives |
| Settings page saves only the fields that changed | The catalogue writes the historical prices into the settings; a whole-page save would put back the stale value |
| **Gallery tiles** "Choose formats" / "Choose your future profession with AI" (the AI tile asks which ORIGINAL to use when there are several) | Client step 8; a generation still always starts from an original |

### 2026-10-17 (later) — UI audit: things that looked like they worked
| Decision | Why |
|---|---|
| Removed settings `closure_date`, `onsite_payment`, `postal_delivery`, `school_delivery`, `photographer_name`, `photographer_id`, `ftp_url` | Shown and saved, never read: orders were taken after the "closing date", the payment/delivery switches changed nothing in the portal (card only, prints always in class), the photographer text duplicated the real photographers list (with a fake "PIN ••••") |
| No postal address at checkout, never stored (`orders.shipping_address` stays NULL even if an old page sends one) | It was required for prints that are handed out in class, and nothing used it: personal data collected for nothing |
| Director: the "PDF statement, only action available" line removed | There was no such button |
| Cards tab in photographer-app mode: no hand-made codes, no per-code list; an "export every sheet" card instead | Families are made by the shooting; that list's class selector moved a code to another class but not its `Class/Student N` folder (now refused with 409 for a filed child) |
| Siblings: a "Sibling…" button on every pupil opening a dialog (pick class + pupil, both shown, confirm) | Checkboxes + a button that only appeared after ticking two: nobody found it |
| Photos tab: each photo shows its folder; moving = picking the pupil in a list | Typing a family code was the card-mode way |
| Settings: a field that cannot apply is hidden (doubt zone outside time mode, shooting options with the app off); AI on without the StoryFace key is flagged; settings tabs have a fixed width; "Offered" saves with the row's Save like the rest; "reset test data" moved to Access & system | Consistency; the destructive reset does not belong on the daily Orders screen |

## 2026-10-18 — FTP server for the cameras (Docker)
| Decision | Why |
|---|---|
| **SFTPGo in Docker Compose** (`deploy/ftp/`), writing into a plain server folder (`/var/ftp/meeconic/{school}/` = the backend's `INCOMING_DIR`) | Julio asked for a Docker FTP server; Docker makes it a one-command install. The backend is unchanged |
| **The FTP drop is a plain folder, not MinIO** | A MinIO *inbox* (SFTPGo → MinIO → backend poller) was built and removed the same day: the organizer reads the files with OpenCV/EXIF and watches the folder, both need local files. The photos themselves DO go to MinIO (next section). Note: MinIO Inc. stopped publishing free images/binaries in 2025 (`chainguard/minio` is the maintained rebuild) |
| Atomic uploads (`SFTPGO_COMMON__UPLOAD_MODE=1`, temp folder inside incoming) | The organizer never sees half a photo; the temp folder must be on the same disk (rename, not copy) |
| The FTP container runs as the backend's user (`FTP_UID`/`FTP_GID`) | Both write the same folders; the earlier "drop folder recreated by the wrong user" incident |
| FTP accounts: list/upload/overwrite/rename only — no download, delete or create_dirs | An account can only drop photos into its school. Sub-folders would hide photos from the organizer (it reads the school folder only), so a camera set to create them fails visibly on the camera instead |

## 2026-10-18 (later) — Photos stored in MinIO (`core/storage.py`)
The app server had almost no free disk; the MinIO box (Frank) has 2.5 TB. Not negotiable: every photo goes there.
| Decision | Why |
|---|---|
| **One storage layer, two backends** (`STORAGE_BACKEND=local|s3`); callers handle a `Key` (`photos/…`, `thumbs/…`), never a path | `photo_service` stays the only module that knows the layout; dev, tests and an install without MinIO keep the disk. boto3, not the MinIO SDK: works with any S3 if MinIO is ever dropped |
| **Everything in the bucket**: originals, trash, `.qr/`, `meta.json`, previews, protected copies, watermarked copies | The user asked for "everything in MinIO if possible". Local disk keeps only `incoming/` (FTP + organizer need real files, transient) and a cache |
| **Bounded local cache** (`STORAGE_CACHE_MB`, 2 GB, least recently used first; file name = key hash + etag) | Pillow/OpenCV/KIS need a file; the user set ~2 GB. The etag in the name means a replaced object is never served stale |
| **MySQL index `stored_objects`** (key, size, mtime, etag) answers every listing; `x-amz-meta-mtime` on each object | S3 resets LastModified on every upload/copy: the trash or a move would restart the RGPD clock. Listing from MySQL also avoids a bucket request per gallery. `reconcile()` (daily) rebuilds the index from the bucket and alerts on drift |
| **Move = copy + verify + delete**; a folder move (class rename) rolls back what moved if a copy fails | S3 has no rename. Half a renamed class would point at half its photos |
| **Organizer `_move` → `storage.ingest`** (upload, verify size, then delete from incoming); still returns False, never raises | The HEC rule. A crash between upload and delete is caught on the next pass (same name, size and arrival time already there → not stored again as `_1`) |
| **Paid downloads stream from the bucket**, the order zip is built while it is sent (deflate level 1) | No temp file on the full disk, and a zip of originals does not flush the previews out of the cache. Stored entries in a streamed zip need data descriptors some unzip tools refuse |
| Trash batch age from the date in its NAME | A bucket has no folder dates |
| What stays on the disk: `incoming/` and its parking folders (`_review`, `_unassigned`, `_ignored`, `_errors`) | The review screen and the organizer work on them; they are emptied by the retention. The monitor watches free space |
| Tests: the WHOLE suite runs twice (CI matrix `local` / `s3` with moto, in-process S3) | Every path of the app is exercised on a bucket without a MinIO; `isolated_storage` gives counting tests a store of their own |
| Photo backups are the MinIO admin's job (replication / `mc mirror`) | The app backs up the database only, as before; written in deploy/minio/README.md |

## 2026-10-19 — Order steps (operator request after the first real test on the dev server)
| Decision | Why |
|---|---|
| A print step can be set back by one (↶), an order can be cancelled (with a confirmation saying Stripe is NOT refunded) and restored | A click too many was final; "cancel" existed in the API but had no button |
| One e-mail to the family when its order becomes "Printed" (once per order, only if something is printed and paid), and "Printed — soon in class" in "My orders"; a digital-only paid order shows "Available" | Between the receipt and the hand-out the family saw "in preparation" for days with no news |
| A line above the orders table says the status is changed by clicking it | Nobody knew the pill was a button |

## 2026-10-22 — Client brief "Upgrades to the school photos tool" (Dario, 21 Oct 2026)
Eight sheets, built in the order the brief suggests. Cross-cutting rules of the brief: no pupil names, no facial recognition, codes that cannot be guessed, every merge / un-merge in the Journal, payment keys encrypted and admin-only.

| Decision | Why |
|---|---|
| **Three roles**: `admin` (ADMIN_PASSWORD, Dario), `operator` (OPERATOR_PASSWORD, Jonathan / Raphaël), `director`. `get_ctx` lets the admin through wherever the operator may go; routes that name `"admin"` alone are closed to the operator | Brief "Who sees what". The old `operator` token was the all-powerful one: it is now `admin`, so every older check kept working. Operator: no payment keys, no revenue (stats, schools list, dashboard, class sales are `null` / 403), products read-only, Journal read-only |
| **Payment keys in the interface** (`payment_keys_service`, table `app_secrets`, Fernet key from `SECRETS_KEY` or the JWT secret). Only the last 4 characters ever leave the server, an empty field keeps the key, a change is a `critical` Journal event naming the key but never its value, a "Test connection" calls Stripe. The key saved there wins over `.env`, which stays the fallback. The gallery gets the publishable key from `/api/portal/payment-config` | Brief sheet 2 ("without going through the developer"). Provider assumed **Stripe** (already integrated); Dario confirmed the keys are visible to the admin only. One set of keys for the whole installation (the school's commission is a percentage, not another account) |
| **Prefix = 2 to 6 digits or letters, assigned automatically** (random, unused, 3 digits) when a school has none; the "first 3 letters of the school name" rule is gone. An install that already printed cards keeps the prefix on them (startup migration) | Brief sheet 1: a code must have no link with any name. Letters stay valid because printed cards exist (`MAR-...`) |
| `school_address`, `head_teacher_*`, `notification_email` holds 1 to 3 addresses, `partner_name` removed | Sheets 1 and 2 (the payout calculation is unchanged) |
| **One list of products** (`school_formats`): the old `school_products` rows were merged in once (`migrate_legacy_products`, the old table stays as a backup), the three `magic-*` built-ins are hidden, an order line says it is an AI photo by its photo (`ia_...`) not by its format. Products have an image, an "offered" switch, an order (`PUT /api/admin/formats-order`) and are written by the admin only | Sheet 3: same product, same price for a classic or an AI photo. Old orders keep their own lines (names, kind, price), so history and the recap stay complete. The form also asks "what it delivers" (paper / digital file / pack): the brief does not list it but a download needs it |
| **Automatic translation** FR to EN / ES (`translate_service`): the free MyMemory service, no key; the fields fill in and stay editable; unavailable or over quota = the product is saved and shown in French | Sheet 3 and point 4 of the brief. The client left the tool open: any free one (decided 2026-10-22) |
| **Photographer mode is a switch**: switching it off revokes the phone link (`shoot_service.revoke_token`) and `/shoot` refuses every call while it is off; the settings stay in the code and are hidden in the interface | Sheet 4 + point 5 (revoke at once: yes). The link lets anyone send photos into the school |
| **AI themes per school** (`ai_themes` setting: `all` / `none` / ticked ids): the portal's `/portal/themes?code=` and the generation both filter on it; a theme StoryFace adds later is OFF until ticked | Sheet 4. Never configured = every theme, as before |
| **Manual loading** (`upload_service`): classes + a special "Siblings" folder (`school_classes.kind='siblings'`, shown as "Fratries" / "Siblings"). A photo uploaded to a class that is not validated waits in `photos/.staging/{school}/{class}/` (outside the school folder); **Validate the class** turns each waiting photo into a pupil card (family + class + `{Class}/Student N`, numbered in file-name order); a photo added afterwards becomes a card at once and is journaled; a photo in Siblings is a card at once. Duplicate = same bytes already in the class; refusals carry a reason (not a photo / unreadable / too large). **A child may have several photos** (client, 2026-10-22): waiting photos carry a child number, the same number = ONE card (`PUT /api/admin/classes/{id}/grouping`: by hand, or "N photos per child" in file order); a lone photo is a child of its own; after validation `?student=N` adds a photo to an existing child | Sheet 5 and point 2 of the brief (answered by the client: yes, several photos per child, hence one folder per student). The browser sends the files one by one: progress, one bad file never stops the rest |
| **Cards grid** (`GET /api/admin/cards`): several classes at once, Siblings filter, `unlinked` counter. **Merge needs `confirm: true`**, is recorded in `family_merges` and can be **undone** (`POST /api/admin/families/unmerge`): folders, classes, orders and aliases go back. Refused when the kept family was merged again since, when it has ordered since the merge, or when an old-layout folder was moved. A sibling photo adds no class to the family it joins. "Create cards for only children" confirms every still-unlinked pupil card (`families.card_state='single'`) and downloads their sheets | Sheet 6 / 6b. The kept code is the first ticked card's; the other codes are aliases (`merged_into`), as before |
| **Orders**: click opens the detail (card, product, quantity); the HD folder for the lab is `order-XXXX/{code}_{class}_{format}_x{qty}.jpg` (the FULL code, not its first two segments: two families could share those); a recap sheet PDF (Pillow, A4, a "Prepared" box per line); "Validate the order" = `orders.validated_at`, an internal Done marker, **separate from the batch status and sends no e-mail** (the "printed" e-mail stays tied to the batch status, once) | Sheet 7, point 3: the batch status already sends the e-mail, so a separate marker was needed |
| **Dashboards** (`stats_service`): the recap by product is built from the order lines (a hidden or deleted product stays, the lines add up to the gross sales); stats by class = cards created, families that ordered, rate, revenue. Sibling rules: a family of two classes is a buyer in each; a solo photo's revenue goes to the class stored on the line (`origin_class`, written when the order is made), the Siblings photo is split equally between the family's classes. PDF statement `GET /api/director/statement.pdf` | Sheet 8 |
| Removed: the card-mode list / "attach a code by hand" form in the Cards tab, the FTP "organizer stopped" check on the Orders tab, the partner field, and the "operation calendar" (photo day, delivery week) from Settings, the head teacher's dashboard, the PDF statement and the checklist (the client did not ask for it, 2026-10-22; the two settings stay in the database, the delivery slip still prints the delivery week) | The brief: no more FTP, no photographer. The backend code (organizer, shoot) stays behind the switch |

### 2026-10-22 (later) — Explorer, settings page
| Decision | Why |
|---|---|
| **The Cards tab opens with a file explorer** (`FileExplorer`): School > Class > Child, a tree on the left (keyboard: arrows, Home/End, Enter), the folder's content on the right, breadcrumb on top. Drop files anywhere on a class; waiting photos show as thumbnails grouped by child (drag a photo onto another child, or type the number); a child opens to its photos | Client: "like a traditional file explorer / drive", and bulk upload per class |
| **Bulk upload**: "photos per child" (1 = every photo is a child, so 30 photos make 30 children; k = every k consecutive photos in file-name order are one child) and "validate when the upload ends". In a class already validated the first photo of each group makes the card, the others join it by Student number | Client: "upload 30 photos and get 30 children if each child has one photo" |
| Waiting photos have signed thumbnails (`/api/media/staged-thumb/...`), cards list all their photos (`files`) | The explorer shows them before validation |
| **Settings: one save button, always on screen**, for every setting, the AI themes and the payment keys (sections register through `useSaver`; the sections that hold their own data stay mounted when you change tab). Products keep their own per-row buttons (a catalogue editor with uploads). The photographer app is the last block of Photos & AI; its "photo protection" panel is commented out in `SettingsTab.tsx`; photo retention is a small field in Access & system; the "magic photo" switch became "AI transformation" and lives with the themes (off = no theme list) | Client review of the settings page |
| Texts that explain the code to the developer ("this mode is a switch, the code is kept...") are not shown in the interface | The client has no reason to read them |


## 2026-10-28 — Every profession theme, every product deletable
| Decision | Why |
|---|---|
| **AI themes come from StoryFace app 26 ("Dream Job", `STORYFACE_APP_ID`)**: 50 professions, each with a child version (`prompt_id=1`, the child today in the outfit) and a grown-up one (`prompt_id=2`). Generation goes through `/api/v2/group-generation` and always sends `prompt_id` (without it StoryFace picks one at random). The portal lists the themes themselves (StoryFace picture + name, "Dream Job - " prefix dropped) instead of the 18 fixed jobs matched by keyword, and asks "as today / all grown up" | Client: "activate all the profession themes, and add any additional ones". App 1 mixed them with 800+ unrelated themes; the keyword list could only ever show 18. Reference: StoryFace's "¿Qué seré de mayor?" demo page |
| A school's ticked list that names none of today's themes (ticked when themes came from app 1) counts as "all" | Otherwise the AI offer would disappear without a word for that school |
| **Every product can be deleted, the 7 original ones too**. A deleted original keeps its row with `deleted_at` (else `_ensure_builtins` creates it again on the next read); a new product is really deleted. Deleting now asks for confirmation | Client: "why can some formats be deleted and not others". Paid orders carry their own name, kind and price on each line, so nothing reads the row back. What a product delivers (print / digital / pack) is still chosen at creation only, for every product |
| **What a product delivers is editable** (print / digital / print + digital), built-ins included; product rows open with an "Edit" button | A "Pack complet" made as a print gave the family no HD download nor the e-mail with the files. The kind IS the setting that decides it; it was only fixed at creation. Paid orders keep what they bought |
| **Branding per school**: a school may have its own logo, watermark (image + settings) and sheet template; what it does not set comes from the default level. The gallery shows the family's school logo once the code is known; the admin header keeps the default one | Client: "the branding must follow the school in use". The school's crest (Settings → School, top-left of the sheet) stays where it is |
| AI themes are ticked in a full-screen picker (5-6 columns of big pictures); portal product pictures are 96-112 px | Client: the small thumbnails did not show what is chosen / bought |
| **Class counters from the folders**: children = pupils' folders that still hold a photo, photos = originals in them + waiting ones. A validated class emptied of all its cards shows "Vide" and starts over (its next photos wait for "Validate") | Client page 1 (2026-10-28): CPB "3 children" and CP/CE1 "7 photos" after their photos were deleted; the left list and the folder tiles must agree |
| **Photos tab and photographer app commented out** of Settings and of the admin tabs (code kept, switched off) | Client page 3: "we don't need them" |
| Product description up to 500 characters (text area); the portal shows 2 lines, the whole text with the enlarged picture | Client page 2 |
| The portal address in big blue letters under "COMMANDEZ VOS PHOTOS" on the 10x15 sheet (the small footer line stays) | Client page 4 |
| "Download the complete order" = one zip: the prints' originals byte for byte + the recap PDF | Client page 5. Pack breakdown waits for a decision: a pack has no list of components yet |
| Payment-key fields use `autocomplete="new-password"` | Chrome filled the admin's saved password into the Stripe key field and the Settings Save button failed ("stripe_public_key: must start with pk_") |
| **A pack lists its products** (`school_formats.components` = [{format_id, qty}], one level, at most 10, edited in the product's "Edit" form). The order line keeps a copy; the lab zip has one file per product of the pack (`{code}_{class}_{pack}_{format}_x{n}`), the recap sheet shows the pack then one row per product with its box, "to print" counts the products | Client page 5, option A chosen by Dario 2026-10-28: the lab must know which photo, which format, how many. A product inside a pack can be "not offered" alone |
| **Kind "choice": print and/or file, the family chooses** (two prices: `price` for the print, `price_digital` for the file, both = the sum, no discount). `format_service.expand` turns it into `{id}` (print) and `{id}:num` (digital) for the portal and the order check; the portal shows the file as "+ HD digital version" under the print. "Pack" stays: both delivered for ONE price | Dario 2026-10-28: "pack = you pay for both; print + digital = you buy one, the other or both". Products had been set to the wrong kind (a "Numérique HD" product as a print) because one select mixed the two ideas |
| Kind "choice" has **three prices**: print (`price`), file (`price_digital`), print + file (`price_both`), variants `{id}`, `{id}:num`, `{id}:both`; in the portal the family picks ONE of the three per product | Dario 2026-10-28, same day: "printed with its price, digital with its price, both with its price, 3 separate prices" (replaces the sum of the two) |
| Kind "choice" (print / digital / both) switched off for new products; still shown on a product that has it | Dario 2026-10-28: a product with a size is a print, the file is "La photo numérique HD" |
| Class "prints to hand out" count a pack's prints (like the order's "to print") | Found by the end-to-end catalogue scenarios (`tests/test_catalogue_scenarios.py`): a pack counted as 1 |
| Theme pictures are served by us, 400 px WebP, fetched from StoryFace once (`/api/portal/theme-thumb/{id}/{n}.webp`); the theme picker is a portal on <body> with a filter, 6 columns | StoryFace's full-size examples slowed the picker; the app header covered the picker's header (no visible way to close it) |
| **Recap sheet redesigned**: navy band, order number, "paid" pill and date; three cards (school, family code ONCE, class it is handed out in); one row per print with the photo's thumbnail, its card and file; a pack is a gold block (its photo once) with its prints under it; a total card; footer with contact and page | Dario 2026-10-28: the first version repeated the code on every row, had no photo and cut long names |
| **Lab names are short** (`order_service.short_name` / `lab_token`): a print -> its size ("18×24"), an object -> the object (+ size: "Magnet 10×15", "Porte-clé", "Calendrier"), on the recap and in the zip file names | Dario: "only the format, 10x15, 18x24…; key ring and so on". A magnet keeps its word so it is not printed as a plain photo |
| Recap sheet: a control block at the foot of the last page ("Préparé par ____ · Date ____ · Remis à l'enseignant ☐"); page breaks planned by a dry run so the total and the block share the last page with at least one group of rows. Meeconic's logo is NOT printed until the client says they want it (code ready, `logo = None`) | Dario 2026-10-29 |
| **Print templates per product** (`template_service`, Settings → Sales, "Edit"): no template = the lab gets the photo; a PNG with transparent zones = the lab zip gets the finished montage as a JPEG at the product's print size, 300 dpi. The zones are found from the transparency (no zones to draw), the SAME photo fills every zone (cover, the frame raised: 35 % of the vertical overflow cut at the top), the PNG on top. The size comes from the PNG's dpi and is editable (the ID sheet PNG is 254 dpi: 20.3 × 15.2 cm = 2398 × 1795 px). The order line keeps a copy of the template (content-named file, never deleted): a replaced template never changes a paid order. Families never see a montage | Client 2026-11-15 (calendar 30 × 20, sheet of 6 ID photos + one 10 × 15), modelled on their own tool ateliermeeconic.com. Its "one photo per zone" mode (key-ring sheet of 8 children) is left out for now (Dario 2026-11-15) |
| **Test orders** (Orders tab, admin only): a card, one of its photos, some products → an order with `payment_status='test'`, built by the same `order_service.build_line` as a family's (same template snapshot, same lab zip). Listed with the sales under a "Test" badge, deletable (a real order is not); every sale count asks `'paid'`, so stats, school share, labels, exports and RGPD checks skip it; the portal never lists it, gives no file and sends no e-mail; Stripe is never called | Dario 2026-11-15: see the zip sent to print without spending money (switching the global Stripe keys to test mode would stop every school's real payments) |
