sightbox/playbook/INSTALLATION_PLAYBOOK.md

374 lines
22 KiB
Markdown

# New Client Installation Playbook
Standing up ERPNext for a new client, start to finish. A client is a Frappe **site**, not
necessarily a whole new stack — this VPS's bench can hold one client or several, isolated from
each other by site + `tenants.json`, not by a separate Docker Compose project per client. See
"Architecture" below before Stage 1 if that's new to you. Finish this playbook, then move to the
Field Ops Runbook (with this client's real names) to run the actual demo.
**This is the fast path.** Every native customization this deployment relies on — Custom Fields,
Client/Server Scripts, the Workflow, both Notifications, the Damage & Cost Report, permissions,
audit hardening — is automated by
[`provisioning/provision_client.py`](../provisioning/provision_client.py) (Stage 5
below), not typed by hand. If that script ever fails, produces something wrong, or you need to
reproduce one piece of it manually to debug or extend it, **[`DEVELOPER_GUIDE.md`](./DEVELOPER_GUIDE.md)
is the detailed reference** — the exact Desk UI steps and full content for every single thing the
script creates, plus the general methodology for building more of these yourself.
## Architecture: one VPS, one or many clients
One `docker compose up` (Stage 1) brings up one **bench** — the shared Frappe/ERPNext containers,
MariaDB, Redis, and the `backend-billing` service. That's a one-time, per-VPS event, not a
per-client one. Each **client** is a Frappe **site** on that bench (`bench new-site`, Stage 2):
its own database (inside the shared `db-data` volume) and its own site folder (inside the shared
`sites` volume), invisible to any other site on the box.
```
VPS (one docker compose stack = one bench, one Stage 1)
├── backend-billing ← one shared service for every client below
│ └── tenants.json ← one entry per client, keyed by tenant_slug (Stage 9)
├── db (MariaDB) ← one shared container, one database per site
│ ├── acme site's database
│ └── beta site's database
├── sites/ ← one shared volume, one folder per site
│ ├── acme.localhost/
│ └── beta.localhost/
└── backup.sh → one nightly archive → R2 (every site above, together — see Stage 10)
```
**Bringing on client #1:** Stage 1 (bring up the stack) → Stage 2 (create the site) → ... →
Stage 9 (register it as a tenant) → Stage 10 (wire up backups, once).
**Bringing on client #2, months later, same VPS:** skip Stage 1 — the stack, and Stage 10's
backup cron, are already running. Jump straight to Stage 2 with the new site name, run Stage 5's
provisioning script against *that* site, and give it its own `tenants.json` entry in Stage 9.
Stage 10 needs nothing further — its backup already captures every site under `$SIGHTBOX_DATA_DIR`
indiscriminately, this new one included, from the next nightly run onward.
**Want a client fully isolated on their own hardware instead?** Nothing above is mandatory —
just run this entire playbook, Stage 1 included, against a separate VPS. Both models use the
identical set of stages; the only variable is whether Stage 1 has already happened for the VPS
you're targeting.
**Restoring after a VPS failure or provider migration:** `restore.sh` (see
[`BACKUP_RESTORE.md`](./BACKUP_RESTORE.md)) brings every client site on that VPS back at once,
from the one shared nightly archive — there's no per-client restore, because there's no
per-client backup.
## Prerequisites
- This repo's structure copied to wherever this VPS's stack will live (skip if it already exists
— see "Architecture" above).
- Decided: the site name (a real domain in production, `<client>.localhost` for local testing),
a DB password, and an Administrator password.
---
## Stage 1 — Bring up the stack
**Adding another client to a VPS that's already running one?** Skip this entire stage — one
bench serves every client on it (see "Architecture" above) — and go straight to Stage 2 with the
new site name.
**Optional — this product's own branding (recommended for a real client), before the first
`docker compose up`.** Stock ERPNext shows its own name and logo in a few spots Website Settings
can't reach — confirmed by reading Frappe's own source, not guessed (see
[`DEVELOPER_GUIDE.md`](./DEVELOPER_GUIDE.md)'s "Patching the image itself" section for exactly
which spots and why). Skip this and stay on stock branding, or build the patched image once per
VPS:
```
./erpnext-image/build.sh
```
It prints three variables — `CUSTOM_IMAGE`, `CUSTOM_TAG`, `PULL_POLICY=never` — set them in
`.env` (see `.env.example`) before bringing up the stack below. Every Frappe-image service
(`backend`, `frontend`, `queue-*`, `scheduler`, `websocket`, `configurator`) then builds from this
image instead of the stock one, via frappe_docker's own `CUSTOM_IMAGE`/`CUSTOM_TAG` mechanism —
no edits to `frappe_docker/` or this repo's own `docker-compose.yml`. Re-run `build.sh` any time
`ERPNEXT_VERSION` in `.env` changes; its own build-time checks fail loudly if a version bump means
the patches no longer apply cleanly, rather than silently shipping unpatched branding.
**Real client, on the production Linux VPS:** every persistent volume this stack uses (site
data, the database, the billing state) gets bind-mounted to one visible host directory instead of
Docker's own opaque storage — this is what makes Stage 10's backups possible at all, and it has
to be set up *before* the first `docker compose up`, not retrofitted onto an already-running
site later (retrofitting means migrating live volume data by hand — safe, but unnecessary
work if this is done up front). Bind mounts don't auto-create their target directories the way a
named volume does, so create them first:
```
mkdir -p /opt/sightbox/data/{sites,db-data,redis-queue-data,billing-state}
echo "SIGHTBOX_DATA_DIR=/opt/sightbox/data" >> .env
docker compose -f docker-compose.yml -f docker-compose.data-dir.yml up -d
```
**Local dev / testing (`<client>.localhost`):** skip the `data-dir` file entirely — just
```
docker compose up -d
```
⚠ **Confirmed the hard way: never layer `docker-compose.data-dir.yml` on a macOS/Windows dev
machine.** Docker Desktop's bind mount runs the container's view of that directory through the
*host's* filesystem semantics, and macOS's default filesystem is case-insensitive — MariaDB
silently sets `lower_case_table_names=2` against it, which doesn't match how the data's tables
were actually created, and every query starts failing with `doesn't exist in engine`. Docker's
own named-volume storage (what a bare `docker compose up -d` uses) lives inside the Desktop VM's
own Linux filesystem regardless of host OS, so it never hits this. See
[`BACKUP_RESTORE.md`](./BACKUP_RESTORE.md) for the full explanation — this was found and fixed by
actually migrating a real running site's data onto this setup and watching it break.
Either way, wait for `db` to report healthy: `docker compose ps`.
⚠ **This is also what brings the QR code image-generation service (`backend-billing`) online** —
it's defined in the same `docker-compose.yml` as the Frappe containers, so a bare
`docker compose up -d` (not naming individual services) starts it automatically, before any site
even exists. It's genuinely tenant-agnostic — no per-client config needed for QR generation
itself — so once it's up here, it's already reachable and ready. Stage 5's provisioning script
only creates the *Frappe-side* Server/Client Scripts that call out to it; it never touches this
container, the same way it never touches MariaDB or Redis. If QR codes aren't generating on a new
site, confirm this container is actually running (`docker compose ps`) before suspecting the
provisioning script.
## Stage 2 — Create the site
```
docker compose exec backend bench new-site <site-name> \
--mariadb-user-host-login-scope=% \
--db-root-username root \
--db-root-password '<DB_PASSWORD>' \
--install-app erpnext \
--admin-password '<ADMIN_PASSWORD>'
```
## Stage 3 — Complete the real Setup Wizard — do not script around this
Log in as Administrator at `http://<site>/login` and walk through the actual browser wizard:
company name, abbreviation, currency, country, domain.
**Bypassing this causes confirmed bugs**, all discovered the hard way:
1. No default language set → a Frappe locale crash (`UnboundLocalError`). This isn't limited to
Stock Entry rate calculations — it fires from *any* code path that touches date formatting,
including Server Script creation, so Stage 5's provisioning script will fail confusingly
partway through on an un-wizarded site.
2. Serial/batch tracking left off → a Stock Entry with a serialized item can end up
`docstatus=1` ("submitted") while posting **zero** actual stock ledger entries — a silent, not
a loud, failure.
3. No Chart of Accounts → "Please enter Difference Account" blocks every Stock Entry outright.
The wizard sets up all three correctly in one pass. There is no shortcut worth taking here.
## Stage 4 — Enable Server Scripts bench-wide
Already done for this VPS if another client's site already went through this stage — the `-g`
flag below makes it bench-wide, not per-site. Safe to run again regardless; skip if unsure.
```
bench set-config -g server_script_enabled true
```
⚠ **Confirmed the hard way:** this flag lives in `common_site_config.json` (bench-global) — *not*
`site_config.json` (per-site). Running `bench --site <site> set-config server_script_enabled
true` writes it to the wrong file, silently has no effect, and every Server Script the next stage
creates fails with `ServerScriptNotEnabled` — with **no Error Log entry at all**, since the check
happens before the script body ever runs. There is no Desk UI setting for this either. Always use
the `-g` flag, and always run it before Stage 5.
## Stage 5 — Run the provisioning script
```
./provisioning/provision_client.sh <site-name>
```
This one command replays every site-generic native customization onto the fresh site:
- Stock Settings flags (serial/batch tracking, auto-reorder, barcode field)
- System Settings toggles (scheduler enabled, standard email footer disabled)
- The Tool Kit DocType and its child table
- Customize Form fields on Stock Entry (Signature, Photo, Issue Reason, Tool Kit — Signature and
Photo mandatory) and Serial No (maintenance date fields)
- Every Client Script (Tool Kit auto-populate, maintenance-date recalculation, the QR
"Regenerate" button, the Item → Serial No dropdown)
- Every Server Script (QR auto-attach on tool receipt, the QR "Regenerate" API)
- The Material Request Approval Workflow, with its states and actions
- Both Notifications (maintenance due, low stock), each with a full professional HTML email
template
- The Damage & Cost Report
- The Stock Manager permission elevation on Item/Warehouse (create + write, never delete)
- Audit trail hardening (change tracking on Material Request, Deleted Document lockdown)
- The `Trial Expired` lockout Role (no Desk access, redirects to `/billing`)
- The Custom Field `System Settings.billing_tenant_slug` — set once per site in Stage 9, step 6
- The `Daily Trial Expiry Check` Scheduled Server Script and the `Get Billing Status` API Server
Script (both call out to `backend-billing`, both read the same `billing_tenant_slug`)
- The public `/billing` Web Page (status, days-to-next-bill, receipts, the reactivation Payment
Link — see Stage 9, steps 7-8 for the optional data that populates it)
- A "Billing" shortcut on the Stock Workspace, so `/billing` is discoverable from Desk by any
normal staff member — not just reachable by a locked-out User's automatic redirect
It's idempotent — safe to re-run against a site that already has some or all of this; every step
checks before creating. Verified for real against a genuine second site on this bench: exact
parity with the original site across every one of the items above.
⚠ **This script only ever touches the Frappe site's database — never Docker infrastructure.**
The two QR-related Server Scripts it creates *call out to* `backend-billing`, but the script has
no awareness of that container's existence, whether it's built, or whether it's running — that's
entirely Stage 1's job. If QR generation doesn't work right after provisioning, the scripts
themselves are almost certainly fine (this is exactly the kind of thing Stage 5's own verification
step should catch) — check that `backend-billing` is actually up first.
**If the script fails, or you need to create/fix one piece of this by hand** — a Desk UI walk-
through for every single item above, with full code, is in
[`DEVELOPER_GUIDE.md`](./DEVELOPER_GUIDE.md)'s "Manual fallback" section. That's also where the
methodology lives for building *new* customizations beyond what's listed here.
## Stage 6 — Stock module foundation (client-specific — stays manual)
The provisioning script deliberately does not touch this — it's real business data, not a
generic customization. Per the training guide's Implementation Steps:
- **Item Groups**: Consumable Parts, Tools & Equipment (parent: All Item Groups)
- **Warehouses**: Main Store, plus one per leased property and one per active construction site,
plus a **Damaged** warehouse — damaged tools get transferred here (not written off outright)
so they stay trackable while a repair-or-replace decision gets made
- **Items**: `has_serial_no` + a `serial_no_series` pattern (e.g. `TOOL-.#####`) on Tools &
Equipment only; Reorder Level/Qty on Consumable Parts that need auto-reordering
## Stage 7 — Email delivery & the scheduler
Two of these are the provisioning script's job (system settings toggles); these two are not,
since they need real per-client credentials or are host-level CLI-only:
1. **Email Account** (fully UI-configurable): Desk → Settings → **Email Account** → New.
For Resend specifically: Email Address = your verified sender, check **"Use different Email
ID"** and set Login ID to the literal string `resend` (not the email address), Password = the
Resend API key, SMTP Server `smtp.resend.com`, Port `587`, check **Use TLS**, check **Enable
Outgoing** and **Default Outgoing**. Any other SMTP provider works the same way with its own
host/port/credentials.
2. **CLI-only, no UI equivalent:** run `bench --site <site> scheduler resume` once, from the
server. This clears a separate `pause_scheduler` flag that lives in `site_config.json` on
disk — it is host-level configuration, not application data, so nothing in Desk can reach it.
A brand-new site has this paused by default.
⚠ **Gotcha, confirmed the hard way:** a Notification's **Channel** field locks after the record
is first saved — this only matters if you're recreating a Notification by hand (see the
Developer's Guide); the provisioning script already sets Channel correctly on creation.
**Verify, don't assume:** trigger a Notification's condition for real, and confirm the resulting
Email Queue record actually reaches `status: Sent` (Desk → Email Queue) — not just that it was
created. A queued-but-never-flushed email (step 2 above missed) looks identical to a working one
until you check.
## Stage 8 — Roles & staff accounts
Create real staff Users, assign **Stock User** (technicians/dispatchers who raise requests and
view stock) or **Stock Manager** (whoever runs the store), and set each one's **Default
Workspace** to **Stock** — except Administrator, which stays on the general home page.
**Worth knowing:** ERPNext's native Stock Entry permissions give Stock User full
create/write/submit/cancel rights, identical to Stock Manager — this is left as the default.
Stock Manager's *elevated* rights (Item/Warehouse create+write, never delete) are already handled
by Stage 5's provisioning script.
## Stage 9 — Wire up billing
`backend-billing` is **multi-tenant** — one running service serves every client site on this
bench, isolated by its own entry in `backend/tenants.json`. QR generation needs no per-client
setup at all; it's already tenant-agnostic.
1. Create one dedicated System Manager User for this client (e.g.
`billing-service@<client>.local`), no welcome email.
⚠ **Confirmed the hard way:** on `invoice.payment_failed` (or the trial-expiry check below),
`backend-billing` locks out every currently-unlocked User — and this account authenticates
every one of those API calls. Early testing had it lock itself out along with everyone else,
which invalidated its own API token mid-sweep and cascaded into 401s (and a tripped circuit
breaker) for the rest of the list, meaning **no one** actually got locked out. Fixed in
`frappe_client.py`: the client resolves its own username once (`GET
/api/method/frappe.auth.get_logged_user`) and excludes it from every lock/restore sweep, the
same way it excludes Administrator. Nothing to configure — this is automatic for whatever
email you use in this step — but worth knowing why this account stays untouched even during a
real payment failure.
**How "locked out" actually works, worth knowing before you see it happen:** a locked-out User
is never disabled (`enabled` stays `1`) — they can still log in. What changes is their Role,
swapped to a single `Trial Expired` Role with no Desk access, which redirects them straight to
the `/billing` page instead. ⚠ **Confirmed the hard way:** a User's own `default_workspace`
field (set in Stage 8 below) silently overrides that redirect if left in place — Frappe checks
it *after* resolving the Role's redirect and blindly sends the User to their old workspace
anyway, which then 403s since Desk access is gone. `frappe_client.py`'s lock/restore always
moves Roles and `default_workspace` together in one call for exactly this reason; nothing to
configure here either.
2. Generate its API key/secret: Settings → My Settings → API Access, or
`bench --site <site> execute frappe.core.doctype.user.user.generate_keys --args "['<email>']"`.
3. Add one entry to `backend/tenants.json` (copy the shape from `tenants.example.json`), keyed by
a slug for this client:
```json
{
"acme": {
"frappe_api_url": "http://frontend:8080",
"frappe_api_key": "<from step 2>",
"frappe_api_secret": "<from step 2>",
"stripe_webhook_secret": "<from this client's own Stripe Dashboard>"
}
}
```
`tenants.json` is gitignored and mounted read-only into the container — never baked into the
image. `frappe_api_url` must resolve to *this* client's own site: once more than one site
shares the `frontend` container, that means this client's actual domain, not the generic
service name.
4. In this client's own Stripe Dashboard, register the webhook endpoint as
`https://<your-domain>/webhook/stripe/<slug>`.
5. `docker compose up -d backend-billing`, then confirm `GET /health` returns
`{"status": "ok", "checks": {"frappe_api": {"<slug>": true, ...}}}`.
6. Desk → Settings → **System Settings** → set **Billing Tenant Slug** to the same slug used in
step 3 (e.g. `acme`). This is how the two Server Scripts Stage 5 already created — the daily
trial-expiry check and the billing page's status lookup — know which `tenants.json` entry is
theirs. ⚠ **Confirmed the hard way:** this can't live in `site_config.json` instead —
`frappe.conf` is not reachable at all from inside a Server Script's sandbox (neither the
render nor exec safe-globals expose it), unlike `frappe.db.get_single_value`, which is. Every
client uses the exact same script text; only this one Desk field differs per site.
7. **Optional — the independent trial timer.** Add `trial_start_date` (ISO 8601, e.g.
`"2026-01-01T00:00:00+00:00"`) and `trial_days` (integer) to this tenant's `tenants.json`
entry. Once that window elapses, the daily Scheduled Server Script locks the client out the
same way a real `invoice.payment_failed` would — independently of whether a Stripe
subscription exists yet. Leave both unset for a client who shouldn't be trial-gated at all.
8. **Optional — the billing status page's live Stripe data.** The `/billing` page (Stage 5,
redirected to automatically once a client is locked out, or visited anytime by any logged-in
staff — see `CLIENT_DEMO_GUIDE.md`'s positioning notes) shows subscription status, days until
next bill, and downloadable receipts if these three fields are also set on the tenant:
- `stripe_restricted_key` — a Stripe **Restricted key**, **Read**-only on Invoices and
Subscriptions, nothing else. Never the full secret key: this code only ever looks, never
charges, refunds, or modifies anything. Dashboard → Developers → API keys → Create
restricted key.
- `stripe_customer_id` — this client's Stripe Customer id.
- `stripe_payment_link_url` — a Stripe Payment Link (Dashboard → Payment Links) the page shows
as a "Manage Billing" button. Leave its own trial-period option off if `trial_days` above is
already handling the trial independently — that keeps the two mechanisms from double-trialing
a client who resubscribes.
Leave all three unset for a client who doesn't need this yet — the page shows an "unconfigured"
state rather than erroring.
## Stage 10 — Wire up backups
**Real client only — skip entirely for local dev/testing.** Nightly snapshot of this whole
deployment to Cloudflare R2, restorable onto any brand-new Linux VPS with one script. Full design
and every gotcha found building it: [`BACKUP_RESTORE.md`](./BACKUP_RESTORE.md).
1. `cp backup/.env.example backup/.env`, fill in:
- `SIGHTBOX_APP_DIR` / `SIGHTBOX_DATA_DIR` — the same paths used in Stage 1.
- `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_BUCKET` — from Cloudflare's
R2 dashboard. ⚠ The headline `cfat_`-prefixed value R2 shows first is a general Cloudflare
API Token, not S3-compatible — rclone rejects it outright. The real Access Key ID
(32 characters) and Secret Access Key (64 characters) are separate fields on the same
screen; see `BACKUP_RESTORE.md` for exactly where to look.
- Retention days, if you want something other than 14 daily / 8 weekly (56 days).
2. Test one backup by hand — `./backup/backup.sh` — confirm it completes and the archive shows up
in the R2 bucket's `daily/` prefix before trusting it to cron.
3. Add the cron job:
```
crontab -e
# nightly at 3am server time
0 3 * * * /opt/sightbox/app/backup/backup.sh >> /var/log/sightbox-backup.log 2>&1
```
## Stage 11 — Done — hand off
Installation is complete. Move to the **Field Ops Runbook** artifact (rebuilt with this client's
real property/site/item names) to actually demo the system.