sightbox/CLAUDE.md

460 lines
28 KiB
Markdown

# CLAUDE.md — Phase 0: Native ERPNext Deployment (First Real Client)
## Features at a Glance
Everything below ships without a custom Frappe app and without middleware.
The only custom code in this whole project is one small Flask service for
Stripe billing — everything else is native ERPNext/Frappe configuration.
| # | Feature | How it's built | Custom code? |
|---|---|---|---|
| 1 | Receiving, checkout, return, reconciliation (base guide) | Native Stock module — Warehouses, Items, Stock Entry | None |
| 2 | Signature capture | Customize Form field on Stock Entry | None |
| 3 | Photo evidence | Customize Form field on Stock Entry | None |
| 4 | Barcode/QR scanning | Native — Serial No as QR content | None |
| 5 | Reorder alerts | Native Reorder Level + Auto Material Request | None |
| 6 | Roles & Permissions | Native Role Permission Manager | None |
| 7 | Approval Workflow | Native Frappe Workflow builder | None |
| 8 | **Damage & Cost Report** | Customize Form field (Issue Reason) + a Query Report built in Desk | None |
| 9 | **Tool Kits** | A new DocType created in Desk UI + a Client Script | None |
| 10 | **Maintenance & Calibration Reminders** | Customize Form fields on Serial No + native Notification | None |
| 11 | **Billing (Stripe → enable/disable client access)** | A small Flask API in `backend/` | **Yes — the only custom code in Phase 0** |
**Explicitly deferred, not part of Phase 0:** the natural-language query/RAG
feature (now planned as a separate product — this client's ERPNext data
becomes one data source feeding an independently-built Bettersight RAG
pipeline later, alongside their other organizational documents, kept in
sync via change-triggered updates rather than built as a client-facing
query feature here), any custom Frappe app, any middleware, the earlier
multi-tenant Subscription/tier-gating model (this client is a dedicated
single-tenant VPS, not shared multi-tenant hosting — that model doesn't
apply here).
---
## Project Overview
This is the first real client deployment. The goal is a reliable, shippable
system built almost entirely from native Frappe/ERPNext capability, while
the deeper custom-app architecture (from the earlier, fuller CLAUDE.md) is
deliberately deferred until after this deployment builds real Frappe
fluency through the client's testing period. Nothing here is a placeholder
to be replaced later — this is meant to be a genuinely stable, correct
system on its own terms.
## Repository Structure
```
sightbox/
├── CLAUDE.md ← this file
├── playbook/ ← every guide, see "Client Profile & Marketing Handoff" below
│ ├── playbook.md ← index of all guides + their live artifact links
│ ├── ENTERPRISE_STANDARDS.md ← standing standard, applies to backend/ in full
│ ├── INSTALLATION_PLAYBOOK.md
│ ├── DEVELOPER_GUIDE.md
│ ├── CLIENT_DEMO_GUIDE.md
│ ├── CONSUMABLES_DEMO_GUIDE.md
│ ├── BACKUP_RESTORE.md
│ └── CICD_PLAYBOOK.md ← Gitea → Dokploy, gated on tests; Parts 1-2 are reusable
│ for any other project, not just this one
├── docker-compose.yml ← root-level launch path for local dev, see below
├── docker-compose.dokploy.yml ← GENERATED from docker-compose.yml — what Dokploy actually
│ points at, since its validator rejects docker-compose.yml's
│ `include:` directive (two open, unresolved upstream issues:
│ github.com/Dokploy/dokploy/issues/3116 and /1727). Regenerate
│ via ./generate-dokploy-compose.sh, never hand-edit.
├── generate-dokploy-compose.sh ← produces docker-compose.dokploy.yml; see its own header
│ comment for why --no-interpolate and --no-path-resolution
│ are both load-bearing, not incidental flags
├── docker-compose.data-dir.yml ← production-only: bind-mounts every volume under
│ $SIGHTBOX_DATA_DIR — layer this on top on the real (Linux)
│ host only, never on a macOS/Windows dev machine (see
│ playbook/BACKUP_RESTORE.md)
├── .env.example ← SIGHTBOX_DATA_DIR and the other root-level Compose vars
├── backup/ ← nightly snapshot → Cloudflare R2, and the matching restore
│ ├── backup.sh
│ ├── restore.sh
│ └── .env.example
├── erpnext-image/ ← optional: FROM frappe/erpnext, patches branding hooks/assets
│ ├── Dockerfile Website Settings can't reach — see CUSTOM_IMAGE/CUSTOM_TAG
│ └── build.sh in .env.example
├── provisioning/ ← every native customization from INSTALLATION_PLAYBOOK.md,
│ ├── provision_client.py replayed onto a fresh site in one idempotent pass
│ ├── provision_client.sh (Installation Playbook Stage 5)
│ ├── bettersight_logo.png
│ └── templates/ Stage 6's CSV templates (Item Group/Warehouse/Item) for
│ (3 files) Frappe's native Data Import tool — headers generated from
│ this ERPNext version's own Exporter, not hand-typed
├── backend/ ← the ONLY custom code in this project
│ ├── app.py
│ ├── Dockerfile
│ ├── build.sh ← builds + (if pointed at a registry path)
│ │ pushes + (if Dokploy API vars are set)
│ │ triggers the VPS redeploy — see its own
│ │ header comment. No backend/.env anymore;
│ │ its 4 values are plain environment: vars
│ │ in docker-compose.yml now (see .env.example)
│ ├── requirements.txt
│ └── tests/
├── scripts/ ← the two-script dev/ship workflow, see below
│ ├── dev.sh ← local iteration loop: builds both custom images for this
│ │ machine's own architecture (fast, no push) and recreates
│ │ the affected services. Run as often as you want.
│ ├── prod.sh ← ships what dev.sh already tested: runs backend/tests/,
│ │ rebuilds both images for linux/amd64 and pushes them, then
│ │ `git push origin main` (Dokploy's existing AutoDeploy
│ │ picks that up). Requires being on main, clean working tree,
│ │ and scripts/.env.prod (gitignored) with the real registry
│ │ paths — see scripts/.env.prod.example.
│ └── .env.prod.example
├── website/ ← three marketing/company sites, NOT part of the ERPNext
│ │ product — co-located in this repo only for convenience
│ │ (shared Gitea repo, shared Dokploy server), deployed as
│ │ its OWN Dokploy Compose app (Compose Path:
│ │ website/docker-compose.yml) — see website/README.md.
│ ├── index.html, assets/, backend/ ← bi.bettersight.io (Bettersight Intelligence, the
│ │ AI/RAG product — unrelated to Sightbox) + the
│ │ shared Flask /api/contact both sites below use
│ ├── website-bettersight.io/ ← bettersight.io, the parent company's own apex page
│ └── website-bettersightbox/ ← box.bettersight.io's marketing page — stays part of THIS
│ (ERPNext) app's own `marketing` service below, just
│ colocated here rather than loose at the repo root
└── frappe_docker/ ← official clone, native, unmodified
```
## Environment & Deployment
- **`frappe_docker/` stays exactly as cloned from `frappe/frappe_docker`.**
Nothing in this phase requires modifying it or building a custom image —
no custom app means no custom-app image build step is needed yet. This
is a real, meaningful simplification versus the earlier full plan.
- **The root `docker-compose.yml` is the single launch path.** Running
`docker compose up` from `sightbox/` — not from inside `frappe_docker/`
— brings up the whole deployment: the Frappe/ERPNext stack and the
`backend/` Flask service, on one shared Docker network, so the client
deployment is one command from one place.
- **Before writing the root compose file, inspect `frappe_docker/`'s own
actual compose configuration** (its exact file names and structure vary
by version — do not assume a specific layout) and reference or include
its service definitions from the root file rather than duplicating them.
The root file's job is to *add* the `backend` service and network them
together, not to reimplement what `frappe_docker` already provides.
- **`backend/` gets its own `Dockerfile`, built and pushed via `backend/build.sh`
— the VPS only ever pulls, never builds.** Same build-locally-test-locally
pattern as `erpnext-image/`: `docker-compose.yml` references
`${BACKEND_BILLING_IMAGE}:${BACKEND_BILLING_TAG}`, a bare local tag by
default (local dev, `pull_policy: never`) or a real registry path once
deploying for real. Confirmed the hard way this matters on Dokploy
specifically: AutoDeploy deletes and re-clones the whole git checkout on
every deploy, so building fresh from source there is one more thing that
can behave differently than what was actually tested locally — pre-built
and pushed means the exact bytes tested are the exact bytes that run.
- **Deployment target: Dokploy** — but it points at `docker-compose.dokploy.yml`,
**not** the root `docker-compose.yml`. Confirmed the hard way, on a real deploy:
Dokploy's own compose validator rejects `docker-compose.yml`'s top-level
`include:` directive outright ("Additional property include is not
allowed") — a known, unresolved Dokploy limitation, not a mistake in this
file. `docker-compose.dokploy.yml` is the same deployment, pre-flattened
(`include:` resolved, `frappe_docker`'s files merged in) by
`./generate-dokploy-compose.sh`. Regenerate it any time
`docker-compose.yml` changes, `frappe_docker`'s pinned commit moves
(`.gitmodules`), or — really — any time you deploy at all: it bakes the
current git commit SHA into the `marketing` service's content-hash
label so Dokploy's AutoDeploy recreates that container on every single
deploy, not just ones touching `bettersightbox-index.html`. Confirmed
the hard way that a content-only hash wasn't enough — Dokploy re-clones
the WHOLE checkout on every deploy regardless of what changed, which
orphans `marketing`'s `assets/` directory bind mount (building.jpg
starts 404ing) whenever the container itself doesn't also get
recreated in that same deploy. `scripts/prod.sh` already runs this
automatically on every ship, so this isn't a step you need to remember
(confirmed the hard way — see that service's own comment in
`docker-compose.yml`). It's committed, generated output — never
hand-edited.
- **One VPS can host multiple clients.** `docker compose up` stands up one
bench (the shared Frappe/ERPNext containers, MariaDB, Redis, and the
`backend-billing` service) — it doesn't imply one client. Each client is
a Frappe **site** on that bench (`bench new-site`), with its own
database and site folder inside the same shared volumes; `backend/`'s
`tenants.json` and its `tenant_slug`-scoped state store isolate each
client's billing state from the others on the same VPS. A brand-new VPS
and a brand-new site on an existing VPS both follow the exact same
`INSTALLATION_PLAYBOOK.md` stages — the only difference is whether
Stage 1 (bringing up the stack itself) has already happened for that
VPS. Nightly backup/restore (`backup/`) operate at the VPS/bench level,
not per-client: one archive captures every site on the box together.
See `INSTALLATION_PLAYBOOK.md`'s "Architecture" section for the full
picture. (A client can still be given a fully dedicated VPS instead,
simply by choosing not to add other clients' sites to that bench — both
are supported, and the choice is operational, not architectural.)
## What's Custom, and Why That Matters
Only `backend/` is code you're responsible for maintaining and testing.
`frappe_docker/` is upstream, unmodified, and safe to `git pull` for
updates without any merge conflict against your own work. Every rule
below in "Enterprise Standards Compliance" applies to `backend/` — it
does not apply to `frappe_docker/`, since nothing there is yours to hold
to that standard.
---
## Feature Specs
### 1-7. Base Guide Features (Signature, Photo, Barcode, Reorder, Roles, Approval)
No change from the existing `inventory-implementation-training-guide.docx`
— follow it directly. All native, all Customize Form / Role Permission
Manager / Workflow builder, no code.
### 8. Damage & Cost Report
- Customize Form → Stock Entry → add `Issue Reason` (Select: Consumed /
Lost / Damaged / Stolen), same mechanism as Signature and Photo.
- Build the report as a **Query Report** directly in the Desk UI (Report →
New → Query Report) — SQL against the Stock Ledger, grouped by Issue
Reason / Item / Warehouse. No Python controller file needed for a Query
Report; it's defined and stored as a Frappe record.
### 9. Tool Kits
- Create the `Tool Kit` DocType directly in the Desk UI (New DocType) —
Kit Name field, plus a child table (`Tool Kit Item`) listing which
Items belong in the kit.
- Add a `Tool Kit` link field to Stock Entry via Customize Form.
- Write a **Client Script** (Desk UI → Client Script → New, tied to Stock
Entry) that auto-populates the item rows when a Kit is selected — pure
JavaScript, stored as a Frappe record, no app or deploy required.
### 10. Maintenance & Calibration Reminders
- Customize Form → Serial No → add `Last Serviced Date` (Date),
`Maintenance Interval (Days)` (Int), `Next Due Date` (Date).
- Use a **Client Script or a simple Server Script** to recalculate `Next
Due Date` when `Last Serviced Date` changes.
- Use Frappe's native **Notification** doctype (Desk UI → Notification →
New) — condition-based, e.g. `Next Due Date <= frappe.utils.add_days(frappe.utils.nowdate(), 7)`
— to alert the assigned Stock Manager. No scheduled job code required;
Notification's own condition-check mechanism handles this natively.
### 11. Billing — Stripe Webhook (the one custom component)
**Purpose:** each client either has active, current billing or doesn't —
that binary active/inactive state is deliberately the entire billing
model for Phase 0. No tiers, no feature flags, no Subscription doctype —
that richer model belongs to the earlier, deferred design. This is a
different axis from how many clients share a VPS: `backend-billing` is
itself multi-tenant (one running service, one entry per client in
`tenants.json`, keyed by `tenant_slug`) specifically so it can serve
every client site on a bench, whether that bench holds one client or
several — see "Multi-client capacity" above.
**Mechanism:**
1. Stripe sends webhook events to `backend/`'s `/webhook/stripe` endpoint.
2. The endpoint verifies Stripe's signature against `STRIPE_WEBHOOK_SECRET`
(env var) before processing anything.
3. On `invoice.payment_failed`: query all currently-enabled Frappe Users
via the REST API **except Administrator** (Administrator must never be
disabled — it's the only guaranteed way back in). Store that exact list
of usernames (a simple local JSON file or SQLite table in `backend/` —
no new infrastructure needed for this). Disable each one
(`PUT /api/resource/User/{name}` with `enabled: 0`).
4. On `invoice.payment_succeeded`: re-enable exactly the stored list from
step 3 — not "all users," since some may have been legitimately
disabled for unrelated reasons before payment failed, and re-enabling
them incorrectly would be a real bug, not a cosmetic one.
5. All calls to Frappe's REST API from `backend/` authenticate with a
single API key/secret pair for one dedicated system-level Frappe user
with sufficient permission (System Manager) — stored in `backend/`'s
env vars. This is appropriate here specifically because it's one
trusted service talking to one single-tenant site, not the multi-client
shared-secret model from the deferred design.
**Folder layout for `backend/`** (proportionate to one real endpoint —
not the full routes/services/repositories split from the deferred
middleware design, but concerns still stay separated):
```
backend/
├── app.py — Flask app factory, registers TraceMiddleware first
├── stripe_webhook.py — route: signature verification, calls into billing.py
├── billing.py — the actual disable/re-enable logic
├── frappe_client.py — the Frappe REST API wrapper (the one outbound dependency)
├── state_store.py — the small persistent "who was enabled before disabling" store
├── Dockerfile
├── build.sh — builds + pushes + optionally triggers redeploy, see its own header
├── requirements.txt
└── tests/
├── test_stripe_webhook.py
└── test_billing.py
```
---
## Enterprise Standards Compliance — scoped to `backend/`
`backend/` is small — one real endpoint — but it's squarely in
`ENTERPRISE_STANDARDS.md`'s highest-scrutiny category: payment and
webhook intake. Nothing here is optional because the service is small.
- **TraceMiddleware first**, `trace_id` on every log line, `X-Trace-ID`
response header.
- **Webhook signature verified against `STRIPE_WEBHOOK_SECRET`** (env
var, never hardcoded) — return `403` immediately on missing or invalid
signature, before any business logic runs.
- **The Frappe API key/secret lives in env vars only**, `.env` never
committed, `.env.example` with placeholders in its place.
- **No raw stack traces in any response** — log internally, return a
generic message externally.
- **100% test coverage on `stripe_webhook.py` and `billing.py`** — this
is exactly the standard's "payment, auth, webhook intake" category, not
a reduced bar because the service is small. Mock both Stripe's webhook
payloads and Frappe's REST API in tests — no test hits either live.
- **Sentry via `SENTRY_DSN`** — silent failure on a billing action is
unacceptable regardless of how small the codebase is.
- **`GET /health`** — reports whether the Frappe API connection is
reachable, monitored, automated alert on failure.
- **Rollback, documented in the standard's own step format:**
```
Step 1: Verify Stripe signature
→ reject immediately if invalid, nothing has changed yet
Step 2: Fetch and store the list of currently-enabled Users
→ if this fails, stop — do not proceed to disabling anyone
without a confirmed, saved list to restore from later
Step 3: Disable each User in the list
→ if this fails partway, log exactly which Users were
successfully disabled before the failure; do not assume
all-or-nothing succeeded silently
```
- **Daily backup of `backend/`'s state store**, off-server, matching the
same discipline as the Frappe site's own backup.
- **Every function has a docstring stating data flow and numbered steps**,
matching the exact commenting standard and example already established
in the fuller CLAUDE.md — unchanged, still mandatory here.
- **No TypeScript** — N/A for this phase (no frontend code exists yet in
Phase 0), but the rule carries forward unchanged for when one is added.
---
## What's Explicitly Out of Scope for Phase 0
- Any custom Frappe app (`site_tools_extensions`, `bettersight_billing`
from the earlier design — not built yet, not needed yet)
- Any middleware
- The natural-language query / RAG feature
- The Subscription doctype, location-tier gating, or feature-flag model —
each client's billing is a binary active/inactive state, handled
entirely by `backend/`, regardless of how many clients share a VPS
- GPS tracking, offline mobile capture, photo-to-catalog AI cataloging —
unchanged from before, still future-phase ideas
## Build Order
1. Base guide (features 1-7) — get this genuinely solid and tested with
real client data before adding anything else.
2. Damage & Cost Report and Maintenance Reminders — pure Customize Form +
Notification + Query Report, lowest risk, no scripting beyond a small
recalculation script.
3. Tool Kits — the one native feature needing a Client Script; slightly
more involved, sequenced after the simpler ones are proven.
4. `backend/` billing service — build and fully test this against Stripe's
test-mode webhooks before ever pointing it at a live Stripe account.
Once this is live and the client is genuinely using it, the next phase is
not "add more features to `backend/`" — it's revisiting the full custom-app
architecture from the earlier CLAUDE.md with real deployment experience
behind it, not before.
---
## Client Profile & Marketing Handoff
This section exists for a *separate* future engagement: building a features-and-benefits
marketing website and sales pitch for this system. It's self-contained — a session picking this
up cold for that purpose shouldn't need anything else from this file except what's below.
### Who the client is
A **property developer** who does construction and maintenance work on **their own properties**
(leased commercial properties they manage, plus active construction sites) — not a general
contractor serving outside customers. Staff are **not computer-savvy**; the system has to work
for them with minimal training, which is why every daily workflow below is deliberately thin on
screen time for field staff.
### The three daily personas
- **Dispatcher** (office, system Role: `Stock User`) — logs jobs as they come in, raises a
Material Request against the property or site that needs it, and also fulfills approved
requests (creates the Stock Entry) — fulfillment isn't gatekept to the Store Manager alone.
- **Technician** (field, **no system account at all**) — signs for tools at checkout, does the
actual repair off-system, signs again at return; the signature is captured on whichever
transaction the Dispatcher or Store Manager is creating, not a transaction of the technician's
own. To check what's on hand at their site, they call the Dispatcher rather than logging in
themselves — deliberately zero screen time, not just close to it. (An earlier design gave
Technicians their own `Stock User` login for read-only stock lookups; dropped after review
surfaced that `Stock User` carries full create/submit/cancel rights with no restriction tying a
transaction to who it's "for" — nothing stopped a Technician from issuing stock to themselves.
Removing the account entirely closes that risk outright rather than trying to carve out a
narrower role for a need (self-service lookup) that phone-based reporting already covers.)
- **Store Manager** (system Role: `Stock Manager`) — approves requests, fulfills them (issues
parts, checks out tools with a signature and photo), receives returns, runs the physical store,
watches reorder and maintenance alerts, pulls the Damage & Cost Report.
- **Stock Viewer** (optional, system Role: `Stock Viewer`) — read-only visibility for a
stakeholder who isn't day-to-day staff (a board member, an investor): every stock report and
record, cost/value figures included, with no ability to create, edit, submit, cancel, or delete
anything. Not part of daily operations — provisioned per client only when that kind of
visibility is actually wanted.
Every guide below lives in [`playbook/`](./playbook/) — see
[`playbook/playbook.md`](./playbook/playbook.md) for the full index with live links and reading
order. Each is also published as a polished standalone page (re-share from the Artifacts gallery
if a link has gone private by the time this is picked up):
- [`playbook/CLIENT_DEMO_GUIDE.md`](./playbook/CLIENT_DEMO_GUIDE.md) — "Field Ops Runbook", the
three roles above working one tool-checkout job start to finish:
https://claude.ai/code/artifact/9619769a-ea27-41ca-b96c-e99e1cf2b608
- [`playbook/CONSUMABLES_DEMO_GUIDE.md`](./playbook/CONSUMABLES_DEMO_GUIDE.md) — "Consumables
Runbook", the other half of the store: issuing parts, an automatic reorder alert, and a damage
write-off feeding the Damage & Cost Report:
https://claude.ai/code/artifact/8d8ac4fc-230e-482a-b112-ad22a5bc718e
Both demos currently run against a local test company, **Joma Properties Test (JPT)** — not the
real client name. Rebuild both with the real client's company/property/site names before an
actual client-facing demo.
For standing up ERPNext for the *next* new client from scratch — bring-up, the real Setup
Wizard, then one script (`provisioning/provision_client.sh`) for every native
customization — see [`playbook/INSTALLATION_PLAYBOOK.md`](./playbook/INSTALLATION_PLAYBOOK.md),
also published: https://claude.ai/code/artifact/b6ee0ade-31fc-4d70-9a62-8ff6beac275f. It ends
exactly where the two demo guides above begin.
For adding new native customizations (buttons, dropdowns, automation) without a custom Frappe
app — or reproducing one by hand if the provisioning script above ever fails — see
[`playbook/DEVELOPER_GUIDE.md`](./playbook/DEVELOPER_GUIDE.md), also published:
https://claude.ai/code/artifact/2ab21473-8690-4e2a-b319-2728b5ac991c.
For the general-purpose engineering standard `backend/` is held to, see
[`playbook/ENTERPRISE_STANDARDS.md`](./playbook/ENTERPRISE_STANDARDS.md), also published:
https://claude.ai/code/artifact/ad74605c-a8af-4595-bd57-6b5147f5f85f.
For the nightly Cloudflare R2 backup and the restore-onto-any-new-VPS runbook, see
[`playbook/BACKUP_RESTORE.md`](./playbook/BACKUP_RESTORE.md), also published:
https://claude.ai/code/artifact/ab242378-ade7-46c3-b73b-34091136a59a.
### Features, framed as benefits (for marketing copy — not the technical table above)
| Feature | The pitch |
|---|---|
| Signature capture | Every tool checkout and return is signed for, right on the transaction — no disputes over who has what. |
| Photo evidence | Deliveries and damage get a photo attached automatically, permanent proof on the record itself. |
| Barcode / QR scanning | A tool's label *is* its serial number as a QR code — a phone camera fills the field in under a second. |
| Reorder alerts | Consumables reorder themselves before the store actually runs out — nobody has to remember to check. |
| Tool Kits | One click issues an entire crew's kit — no forgotten tools on the truck. |
| Maintenance & calibration reminders | Service due-dates are tracked automatically and nothing falls through the cracks. |
| Damage & Cost Report | Real-time visibility into what loss and damage is actually costing, by property or by site. |
| Approval workflow | Big requests get a manager's sign-off automatically; small day-to-day ones don't get held up. |
| Full chain of custody | Every physical tool's entire history — receipt, checkout, transfer, return — assembles itself onto one screen, with no separate log to maintain. |
### Positioning notes
- This is a **dedicated, single-tenant deployment** — the client isn't sharing infrastructure with
anyone else, and isn't paying for a shared-platform's feature bloat.
- Almost the entire system is **native ERPNext configuration**, not custom software — which means
it's inexpensive to build, stable, and safe to extend later without fighting a fragile codebase.
- The one piece of custom code in the whole deployment is billing (Stripe-driven access control) —
everything the client's staff actually touches day to day is proven, off-the-shelf Frappe/ERPNext.