Skip to content

Engineering notes (why each rule exists)

Frozen reference. CLAUDE.md keeps only the rules, one or two lines each. This page is the reasoning behind them as it stood on 2026-09-13, moved verbatim so nothing was lost. It is not updated with each change: new behaviour is documented on the module page it belongs to, and a new rule gets its one line in CLAUDE.md.

Frontend State: Context Hierarchy (migrating to Zustand)

Section titled “Frontend State: Context Hierarchy (migrating to Zustand)”

State is composed in src/App.tsx. The key insight is that ServiceContext is the main aggregation layer — it loads all data from D1 on boot and provides a unified API to everything else. The database is the single source of truth.

Migration in progress: domain state has been moved out of React Context into Zustand stores (src/stores/) so components subscribe to narrow slices instead of the useServiceContext mega-object, which re-rendered all 87 consumers on any change. Stores now own the state for every stateful domain:

  • requestsStore.ts — requests & invoices
  • systemStore.ts — settings, cancellation rules, logs (PWA state + the theme side-effect stay in SystemContext, which is React-bound)
  • entityStore.ts — clients, employees, services, fiscal entities, leads, addons (the former useEntityCrud lives here)
  • payrollStore.ts — payroll entries/runs/cash-reserve state (the cross-domain orchestration actions stay in PayrollContext)

OperationsContext intentionally stays a context: it holds no state, only composed action hooks. Each migrated context is now a thin wrapper over its store exposing the same hook API (useRequests, useSystem, useEntities, usePayroll) plus granular selector hooks (e.g. useRequestsList, useClients, useSystemIdentity). Store actions emit toasts through src/shared/toastBridge.ts (since they run outside React). The consumer migration is done — the re-render cascade is gone. useSettingsController still calls useServiceContext, but only to hand the aggregate to useSettingsModals; leave it. When migrating a new domain, follow this pattern: store as source of truth, keep the context hook API for compatibility, add selector hooks, prefer selectors in new code.

Context load order matters:

  1. AuthContext → JWT token and user identity
  2. EntityContext → Clients, Staff, Services, Fiscal Entities, Leads (CRUD)
  3. OperationsContext → Service Requests, Invoices, Payroll, Shifts
  4. BillingContext → Invoice state machine
  5. SystemContext → App settings, AI config, cancellation rules
  6. ServiceContext → Aggregates all the above; calls /api/boot on init and exposes refreshData()

Data flow: on boot, DataService.loadInitialData() calls /api/boot which returns the full D1 state. Every mutation (reschedule, cancel, allocate, etc.) applies an optimistic update to local state immediately, then fires a fire-and-forget atomic persist to D1 — per-resource endpoints under functions/api/atomic/ via EntitiesApiClient / syncAtomic (helper at src/shared/api/syncAtomic.ts). On failure a “Sync Failed” toast is shown. refreshData() re-calls /api/boot to resync from the database. (The whole-state snapshot sync — /api/sync, useSync, forceSync — was unused and is deleted; only syncSettings, the settings writer, survives in functions/api/atomic/syncSettings.ts.)

Settings are saved through /atomic/settings, never the snapshot. The Settings page POSTs only the configs being edited (EntitiesApiClient.saveSettings); it is the only settings editor — the chat’s settings panel shows device preferences and WhatsApp health and links to Settings → Communication Hub, since its second copy of the bot, limits, quick replies and business hours was removed. Both used to call forceSync, which ships the entire database through one Zod schema in functions/api/sync.ts: a single invalid request or invoice anywhere returned 400 before any write, so saving an unrelated checkbox silently changed nothing. Two rules follow. The snapshot endpoint no longer exists; do not bring it back. And when reading a CloudClient.post result, remember 4xx bodies resolve rather than throw and carry error with no success field — use assertMutationOk, or a refused write will be reported as saved.

Clients, employees and requests are owned by the TanStack Query cache. /api/boot seeds it (seedQueryCacheFromBoot) so boot stays the single fetch on startup, and useStoreQuerySync projects the cache onto the Zustand stores that most components still read — the stores are a derived view, not a second source. Every mutation path therefore has to mirror into the cache, via src/shared/api/queryCacheSync.ts: syncAtomic, EntitiesApiClient and RequestsApiClient all do. A write that reaches only a store is not merely slow to appear — the next refetch reverts it. The query hooks are gated on an authenticated session, so they never fire on the login screen.

LocalStorage is used only for UI preferences (sidebar state, notification settings, PWA banner flags) — never for business data.

src/routes/AppRoutes.tsx is the single routing file. All pages are lazy-loaded via React.lazy + Suspense. Route access is gated by role (ADMIN, MANAGER, or all authenticated users).

All API endpoints live in functions/api/ and are built on Hono (handlers construct a Hono app and validate input with Zod). The pattern:

  • functions/api/boot.ts — initial parallel load of all D1 tables on app startup
  • functions/api/atomic/ — CRUD endpoints for each domain entity (clients, employees, requests, etc.)
  • functions/api/auth/ — JWT login, logout, Google OAuth, password reset, impersonation
  • functions/api/db/schema.ts — Drizzle ORM table definitions (the query/type layer; migrations are hand-written in db/migrations/ — see Database below)
  • functions/api/common/mappers.ts — converts raw D1 records (which store complex data as _json fields) into domain objects

The D1 binding variable is env.DB, accessed through Drizzle ORM. Complex nested data (financials, chat messages, checklists, incidents) is stored as JSON strings in *_json columns.

Business logic is in stateless service classes/modules — they don’t hold state, they compute. Services live inside their feature folder (src/features/<domain>/services/); only dataService.ts, src/services/analytics/ and src/services/api/ remain under src/services/. Key services:

  • AvailabilityService / ConflictService / RecurrenceService — src/features/scheduling/services/: time slots with transit buffers, overlap/vacancy detection, recurring occurrence generation
  • StaffMatchingService / RecurrenceIntelligenceService — src/features/field-operations/services/: staff scoring by affinity and proximity
  • AIService — src/shared/ai/AIService.ts: Gemini API bridge (chat translation and reply suggestions, incident analysis, roster rescue, recovery letters). The route order and the WhatsApp bot call Gemini on their own paths. The feedback “sentiment radar” and five methods nothing called were removed — prefer removing an unused AI path to maintaining it
  • StabilityService — src/features/system/services/: audits data for drift (impossible transit times, fiscal gaps, relationship risks). The transit alert takes each cleaner’s earliest next job (it used find, so any later job could stand in), and the idle-staff alert covers field staff only and counts PENDING assignments as upcoming — the office roles never have visits and were reported idle on every audit
  • BillingLogic / InvoiceStateLogic / ProfitLogic — src/features/billing/services/
  • PayrollLogic / PayrollPeriodService / PayrollSettlementLogic — src/features/payroll/services/
  • There is no FinancialService facade any more (it spread ProfitLogic + BillingLogic + BillingAnalyticsLogic + PayrollLogic “for compatibility”); import the module that owns the function.

The request status transition table has a single source of truth in src/shared/validTransitions.ts, imported by both the frontend (src/utils/constants.ts) and the backend (functions/api/atomic/requests.ts). Keep that file dependency-free — it is compiled under both tsconfigs. Invoices have their own, narrower one in src/shared/invoiceTransitions.ts, shared the same way by InvoiceRowCard and functions/api/atomic/invoices.ts.

Every list endpoint fans out from “the rows this user may see” to inArray(column, ids), and D1 answers too many SQL variables at 101 bound parameters — where local SQLite and node:sqlite accept 999. So each of those queries has a table size past which it returns 500, and nothing about the query looks wrong until the table crosses it. The 272-client import crossed it for /atomic/clients (which chunked at 200, a round number rather than the cap) and would have crossed it next for /atomic/requests and the chat inbox.

Never hand inArray a list whose length is the row count. Route it through fetchInChunks in functions/api/common/d1Chunk.ts, passing reserved for the other parameters the same statement binds — eq(addresses.ownerType, 'CLIENT') costs one, and a slice sized to the full 100 overflows by exactly that.

The fake D1 in tests/sqlite-d1-adapter.ts enforces the same cap, from the same constant, so an unchunked fan-out fails in CI instead of on the day the table grows. That is what d1BoundParamLimit.test.ts, channel_list_param_limit.test.ts and billingBatchParamLimit.test.ts drive: real routes, 120–150 rows each.

Optimistic locking: stored <= sent is deliberate

Section titled “Optimistic locking: stored <= sent is deliberate”

/atomic/clients, /atomic/employees and /atomic/requests guard writes with COALESCE(version,1) <= clientVersion and then store clientVersion + 1. Do not tighten that comparison to equality. It looks like an improvement and it takes out roughly thirty callers: TaskAtomicService, SchedulingAtomicService, RecurrenceService, InvoiceStateLogic and the billing, scheduling and field-op hooks all hand the endpoint an object whose version they already bumped, while the stores send the version they read. Both contracts are legitimate and only a permissive comparison tolerates both. Equality was shipped once and would have answered 409 to payment claims, clock-ins, reschedules and several client edits.

What closes the simultaneous-editor gap is the server owning the bump, not the comparison: two editors holding 5 both send their number, the first moves the row past it, and the second no longer satisfies stored <= sent. Both contracts are asserted in clientVersionConflict.test.ts and requestVersionConflict.test.ts, so reintroducing equality fails tests rather than production.

The query cache predicts the same +1 in one place — mirrorVersionedUpsert in queryCacheSync.ts. The cache is what useStoreQuerySync projects onto the stores, so mirroring the sent version parks the pre-save number where the store reads it back and the editor’s own next save looks stale.

A refund is not a void. Voiding says the invoice should never have existed — requests go back to unpaid and staffCollectedCash is cleared. A refund says money moved and is coming back: the invoice stays PAID and carries a negative-amount PaymentTransaction, financials.refundedAmount / refundedVatAmount record how much, and staffCollectedCash is left alone because the staff member did take that cash. RefundLogic owns this; the entry point is RefundPanel on the financials card, gated to ADMIN/MANAGER.

Refunds are partial by nature, so they are a quantity, not a status — paymentStatus: REFUNDED appears only on a full refund. Every revenue figure therefore subtracts rather than excludes; dropping a job refunded by 20% erases the 80% the client kept paying for. Do not re-add REFUNDED to the admin payment-status override: it records no amount, no VAT split and no transaction, and the reports read such a job as fully refunded only as a compatibility shim for records that predate the refund flow.

Absorbed VAT is the tax inside the price, not added on top. For a client.vatAbsorbed, useInvoiceGeneration and useInvoiceDispatch force isVatRegistered: false, so the invoice carries no VAT line and price is the whole consideration received — HMRC takes VAT out of it: £100 carries £16.67, not £20. financials.vatAmount is the wrong source for this; it is computed at request time against the real fiscal entity, before the invoice zeroes it. The rule lives once in src/features/billing/services/vatTreatment.ts and the margin report, the HMRC stats and the per-entity split all go through it.

Every job marked PAID carries actual_payment_method. FiscalAuditService declares revenue by method (Stripe, GoCardless, transfer, credit) and reports cash separately; a PAID job with no method counts in neither. Statement reconciliation and transfer-claim approval set PAID without one, so a whole class of bank transfers vanished from the HMRC figures. Any new path that marks a job paid must write the method and bump version — without the bump a stale copy saved later puts the old payment status back.

Reports count realised work only. isRealisedJob (ProfitLogic.ts) — a DONE job, or a cancellation that kept a fee — is the one set the P&L, the HMRC figures, the per-entity split and the revenue-by-service shares count. The P&L counted every non-cancelled job, so a month showed next week’s bookings as revenue and profit and disagreed with the split beside it. What is still owed is every realised job not PAID/REFUNDED — a finished job sits at NONE until it is invoiced, and counting only AWAITING/DRAFT showed it as cash in hand. The HMRC view declares PAID jobs paid by a traceable method only (voiding leaves actualPaymentMethod behind), includes a paid cancellation fee without labour cost, and counts a gateway fee once its invoice is PAID; its cash in hand is the declared figure itself. The per-entity split takes fees only from invoices covering the jobs in view (it added every invoice ever issued). BI and the margin report subtract refunds like every other revenue figure; BI’s margin is profit over revenue for the window, and a cleaner’s rating averages rated jobs only. Staff load is the current London week against the 48-hour weekly limit. The at-risk list and the churn score leave out a client with a visit booked. The at-risk list is CustomerRetentionService (Reports → Risk); the separate 0–100 churn score (RetentionIntelligenceService) went with Quality Control, and the ai_urgency_score/ai_sentiment columns on service_requests are no longer read or written. Endpoints with no caller are deleted, not kept “for later”: the daily briefing email, the billing reminder and receipt endpoints (a gateway or credit payment sends its own receipt when it settles), /api/leads/check-number, the one-off /api/admin/migrate-chat and /atomic/fiscalEntitySecrets went, with the client-side InvoiceDunningService that only its test used.

Finishing a job leaves paymentStatus at NONE. NONE is what makes a finished job billable — the dashboard’s invoice action and FiscalIntegrity’s revenue-leak check both key on it — and DRAFT means “on a draft invoice” (useInvoiceGeneration sets it, voiding resets it to NONE). The employee completion path used to set DRAFT server-side and in TaskAtomicService.finalize, so every job a cleaner finished looked invoiced with no invoice behind it: the invoice action silently did nothing and the audit called it a ghost, while the same job finished by an admin was billable. Do not reintroduce an automatic DRAFT on completion.

A failed boot says why, on the splash’s own screen. SystemScreen in App.tsx is the one full-screen system surface — Connecting Engine, Updating App and the boot-failure screen; the failure screen was a second hand-made layout that had drifted. classifyBootFailure (src/shared/bootFailure.ts) separates no connection, timeout, a refused session (401/403, which gets Sign in again) and a server fault, shows a code (BOOT-503, BOOT-NETWORK) and logs CLIENT_BOOT_ERROR with the kind and status. It used to say “check your internet” for every failure and record nothing, so a report of it could not be traced.

Switching sections does not cover the app with a loader. Each page is a lazy chunk and every deploy renames them all, so the first visit to a section after a deploy used to sit behind the full-screen Loading Engine (PageLoader), and a cached one flashed it for a frame. useViewNavigation sets the view inside startTransition, so React keeps the current screen until the next is ready; prefetchPages (AppRoutes.tsx) fetches the pages the role can open once the app is idle (all 16 for ADMIN/MANAGER, eight for cleaners and clients; none under Save-Data); and .splash-reveal delays drawing Loading Engine and Connecting Engine by 300 ms, so a load that finishes sooner never shows one. Updating App and the boot-failure screen show at once. The other slow path after a deploy is the update itself: the pending version is applied on the next screen change, which reloads the app and runs the boot again.

The admin board shows a section only when it has something in it. The “Board Layout” sheet (ten section switches, card/list mode, “show empty sections”) is gone with its list renderer (DashboardTable/DashboardListRow) and the per-section horizons; the upcoming roster and settled archives, off by default, left the board — Full Schedule and Service History are their pages.

One copy of each small helper. Money rounds through roundPence (src/shared/money.ts, dependency-free, imported by the Functions too — seven copies, four with a different formula); email HTML escapes through functions/lib/escapeHtml.ts; server JSON columns parse through parseJsonColumn; D1 datetimes through functions/lib/parseDbDate.ts; chat preview times through src/shared/chat/formatPreviewTime.ts; UK postcodes normalise through ukAddress.normalizeUkPostcode. CFStatCard folded into CFKpiCard. CFButton folded into Button (the one button component: secondary → variant="outline", success/dark/indigo → accent, its 48 px height → size="lg"); the source-text contracts assert loading={…}, not isLoading={…}.

Settings → Maintenance is the data check only. Its “System Purge” (a log flush that only showed a toast, a photo purge that blanked browser memory until the next refresh) and “Factory Reset” (localStorage.clear(), which holds UI preferences, not data) did nothing their labels said and are gone with useMaintenanceOperations.

Integrity repairs never invent records. MISSING_TELEMETRY (a visit running with no check-in) asks for a manual confirmation; its “repair” wrote a check-in at central London timed at the booked start — an attendance record nobody made. The VAT repair and the conflict board’s compress-day announce success only after RequestsApiClient.save (compress-day counts refusals with countRefusedSaves), and auto-assign leaves the outcome to confirmAllocation.

The management menu is one entry per job. Daily Desk (Messages, Full Schedule, Operations, Service History), Sales (Leads, Quotes), Finance (Billing Center, Staff Payroll), Team (Team & Clients), Insights (Reports). Folded screens are tabs and keep their routes, so notifications and deep links still land: Staff Availability and Supplies are Operations tabs (STAFF_AVAILABILITY/SUPPLY_HUB open them); a manager’s Financials is Reports → Revenue, and REPUTATION_HUB/MARKETING_HUB open Reports → Staff/Trust, with the at-risk client list under Risk; ACCOUNTING_HUB opens Billing → Cash check. The Accounting Hub itself was reachable from no menu or button, so the crew cash count, the financial integrity alerts and the QuickBooks retry were unusable; they are in Billing now (its “Bank Feeds” tab was a hard-coded empty list — statement reconciliation is Billing’s Reconcile statement). Quality Control, Marketing (with its AI review-invitation writer) and the loyalty engine behind them are deleted. Service History stays: Billing lists no paid invoices.

No setting without a reader. Removed because nothing read them: the Settings “AI Engine” tab (“Logistics AI”, “Review Intelligence”), the chat panel’s “Auto-Quote Bot” and “Review Sentiments”, and the WhatsApp “Hub trainer only” box (cancel/reschedule modes and incident keywords — only the deleted simulator used them), with their fields in AiConfig/WhatsAppConfig. Supplies no longer asks the model for a “risk audit” (it rewrote the reminder buildReplenishmentNotice already sends), and Reports’ “Active accounts” counts clients with a finished visit in six months (it summed review figures). Also gone for the same reason: “Admin Fixed Fee / Task” (no payroll or invoice charges it), the chat “direct client–staff messaging” switch and “data retention horizon” (nothing moderates or deletes by them), the business-hours UTC offset, and type-only leftovers (autoReplyTemplate, bookingFlowId, RecurrenceConfig.dayOfMonth, TaskWidgetConfig). Identity’s “support email” and “website” went too. Before adding a setting, add the code that reads it.

Free late changes are a yearly allowance, counted — never a stored balance. Settings → Profit & Liquidity “Free late changes per year” (yearlyAllowanceStandard, default 2 in src/shared/freePasses.ts). calculatePolicyFee(rules, request, freeChangesAvailable, context) waives the fee only when the policy would charge one (grace period and early changes never count — the old per-client bonusCancellations token was spent on those too), and the waived change is stamped on the visit as financials.allowanceUse. What is left is the allowance less the stamps of the last 12 months: freeChangesLeft in the browser, a json_extract count in /scheduling/client-change. A declined or reverted cancellation (restorePrice) or a rejected reschedule (withoutFreeChange) drops the stamp, giving the change back. clients.bonus_cancellations stays in D1, unread.

One set of settings defaults. src/constants/settingsDefaults.ts holds them (fresh… returns a copy); the store and the boot fallback in DataService both read it. They were two copies that had drifted — “CleanFlow” vs “PRIME CROWN”, and removed chat fields still in the boot copy. Re-engaging a lapsed client lives in Reports → Risk only: the finance integrity audit no longer raises LTV_STAGNATION with an AI outreach draft, and the continuity conflict card shows each cleaner’s share of the client’s finished visits instead of an AI paragraph.

No loyalty tier or points in the app. Nothing awarded points and the tier was a hand-set label, so both left the client form, lists, filters, CSV import/export and the client screens. The loyalty_tier/loyalty_points columns stay in D1; the server still reads loyalty_tier = 'LEAD' only as the legacy marker isSafeProvisionalDuplicate (WhatsApp contact linking) checks. “VIP Account” (isFavorite) is separate and stays. Screen copy is plain English: no “Mission”, “Protocol”, “Signal”, “Fleet” or “nominal”.

Screens show only what the data says. Removed as unneeded: the Settings WhatsApp simulator (a hard-coded menu bot that was not the real server bot — only the real Send test stays), the AI growth-strategy button in Leads (it sent the model three counts), the second AI call that wrote “reasoning” over an optimised route, and literal figures presented as metrics (Marketing “Brand Trust 98%” / “Elite, top 5% in Surrey”, Leads “Market reach 85%”, a fixed 15% route saving). The client chat does not score message urgency. Prefer removing a feature that is broken or unfed to rebuilding it.

Evidence files are deleted after the visit stops pointing at them. The report tab awaits RequestsApiClient.save before deleteFromR2, and the shift-closure wizard deletes only photos taken in the wizard (a saved photo’s removal is saved only when the wizard completes). Both used to delete first, so a refused save or a closed wizard left the visit pointing at a missing file.

Finalising a visit is announced once it is saved. finalizeShift awaits RequestsApiClient.save before “Visit Finalized”; a refusal says the visit is still open (the save’s resync puts the screen back). Re-pricing a job on a draft invoice goes through BillingLogic.repriceDraftInvoice, which finds the job’s line by requestId — by position, a reschedule-fee line shifted every later job and the price landed on the wrong line — and adds no VAT for a VAT-absorbing client, as generation does.

What a cleaner may write. /atomic/requests lets an assigned EMPLOYEE clock in, complete, update a running visit, and — on a SCHEDULED or DONE visit — only append incidents (nothing else is written, and none may be removed). The supplies they report at shift close go through /api/field/shopping-list, which merges into the client’s list by label; /atomic/clients is manager-only and used to refuse them silently. Adding a cleaner from an incident recomputes the logistics for the new crew rather than reusing the old labour costs (which paid the first cleaner in full and the second on top).

Statements about money wait for the writes they describe. Approving or rejecting a transfer claim (verifyInvoicePayment), confirming a crew cash count (reconcileStaffBatch) and settling directly all await assertMutationOk on each save before any toast — and before the client is told “payment received”; a refusal restores the invoice and jobs and says why. Generating an invoice saves the invoice before its jobs are marked DRAFT, so a refused save (another device took the number) no longer leaves jobs “on a draft invoice” with no invoice behind them. reconcileInvoice (which wrote a bank reference into quickbooksId) and rejectPaymentConfirmation had no caller and are gone.

A fiscal entity in use cannot be deleted. DELETE /atomic/fiscalEntities answers 409 while any invoice, visit or client points at it (D1 enforces no foreign keys, so the delete orphaned invoices — no bank details, no VAT rule), and the store shows the server’s reason when it restores the row.

Billing emails escape what they interpolate. Invoice, reminder, receipt and reconciliation emails pass client names, invoice numbers, item descriptions and bank details through escapeHtml; send-invoice refuses a VOID invoice (409); a receipt is dated by the invoice’s last COMPLETED transaction, not the day it is (re)sent. Settling a short-paid invoice from a bank statement stays allowed on purpose — the matcher only pre-ticks exact amounts, so it takes a deliberate click.

Payroll shares profit once per job. Profit share and the cash-reserve deposit come from PayrollSettlementLogic.unsharedPeriodProfit: completed jobs in the period that no payroll entry has taken yet. Re-running a period is how a late job gets paid, and computing profit from every completed job in the period paid everyone’s share — and deposited the reserve — a second time. Period dates arrive as bare YYYY-MM-DD and must go through parseDate (local day), never new Date() (UTC midnight, the previous day west of Greenwich — the admin generates from Brazil). Cash the crew collected is deducted as financials.staffCollectedCash when recorded, not totalWithVat, which a VAT-absorbing client never pays. An advance is deducted once: paying an entry settles only advances created up to that entry’s created_at, and a new entry deducts none while the employee still has a DRAFT/APPROVED one. calculateProfitShare works from the same unshared profit (it takes the existing entries); summing every completed job was the double-share rule. Paying an entry reports the jobs it locked and the advances it deducted — it used to count every open advance, which the server does not settle. Closing a run checks for open visits between the London midnights that bound the period (londonPeriodBounds in payrollRuns.ts): the app stores the period as London-midnight instants, and date(period_end, '+1 day') cut the summer value to the UTC date, leaving the last London day out of the check.

QuickBooks: one company per fiscal entity, synced on its own. Each fiscal entity connects its own QuickBooks Online company from Settings → Fiscal Entities → QuickBooks (ADMIN). One Intuit app serves them all; the consent screen is where the admin picks the company, and functions/api/billing/quickbooks-callback.ts stores that entity’s tokens encrypted in quickbooks_connections (0136). The OAuth state is signed and names the entity and the admin who started it — the callback re-checks the account is still ADMIN rather than trusting a cookie. Tokens are refreshed in QuickBooksApi with a write conditional on the old refresh token, because Intuit rotates it and two concurrent refreshes would otherwise lock the entity out.

syncInvoiceToQuickBooks (functions/lib/quickbooks/) never throws and records every outcome in quickbooks_invoice_sync. queueQuickBooksSync runs it after the response on dispatch, void and task removal (invoice-operation), any non-draft invoice save (/atomic/invoices), statement reconciliation and every settled checkout (Stripe, GoCardless, account credit); the button in the sync modal is the retry. The rules it encodes:

  • Drafts are skipped; a voided invoice is voided in QuickBooks; an invoice with a CASH or EMPLOYEE_ACCOUNT transaction is EXCLUDED (off the books).
  • Customers are mapped per entity and realm in quickbooks_customers — matched by email, then by a name no other client of ours already holds, else created.
  • The invoice is found by DocNumber before creating one, so a lost response updates instead of duplicating. PAID adds one Payment linked to it (grand_total + applied_fee).
  • VAT on top goes TaxExcluded at the standard code; an absorbed-VAT client of a registered entity goes TaxInclusive at the standard code, so QuickBooks takes £16.67 out of £100 — the same rule as vatTreatment, and the CSV export now does the same. A company with no 20% code refuses those invoices with a reason rather than posting them untaxed.

Graph checks (npm run deadcode, npm run budget)

Section titled “Graph checks (npm run deadcode, npm run budget)”

Typecheck and lint are per-file. The defects they keep missing live between files, in the import graph:

  • A hook that returned values no consumer read survived a commit whose message was “clear the unused-variable debt and enforce the rule” — the values were returned, so lint saw them used, and ~140 lines of unreachable Leaflet code plus a Nominatim request per mount stayed live.
  • 15 components compiled, linted and type-checked cleanly while being reachable from no route. A mass refactor spent effort editing one of them.
  • manualChunks was syntactically fine and shipped 204 kB gzip of jsPDF and Leaflet to the login screen.

So two graph-level gates run inside npm run check:

  • npm run deadcode — knip (knip.json), scoped to files,dependencies, unlisted,unresolved,exports. Unused exports are now gated at zero; the backlog that used to sit behind this (38 of them) is triaged and gone. Two patterns came out of that triage and both matter more than the deletions:

    • Most of what knip reports is not dead code — it is something exported that only its own file uses. The fix is to drop the export keyword, not the declaration. 25 of the 38 were this.
    • The genuine false positives are re-exports and mirrors knip cannot see: barrel and facade completeness, a constant asserted by name in check-pwa-readiness.mjs, and three literals duplicated in public/widget.js. Tag those /** @public <reason> */ — knip honours it — and always with the reason, since the next reader has no other way to know why an unimported export is deliberate.

    Unused exported types stay out of the gate: 59 remain and nearly all are component props interfaces or the domain vocabulary under src/types/, where exporting is the convention and un-exporting would only stop consumers naming a type. Audit everything with npm run deadcode:all.

  • npm run budget — see Code Splitting above.

The src/features/*/index.ts barrels are in knip’s ignore: nothing imports them (the codebase imports deep paths like @billing/hooks/useBillingActions), but they are a deliberate convention. They are not inert — they re-export by name, so deleting a service breaks them and typecheck is what catches it.

npm run lint is Biome, and it is clean — keep it that way. noUnusedImports and noUnusedVariables are enforced.

Biome is the only formatter, and npm run check now verifies it. In Biome, lint and format are separate commands, so biome lint says nothing about formatting — and for a long time nothing else did either. Meanwhile .vscode/settings.json still ran format-on-save through esbenp.prettier-vscode, a formatter that had stopped being a dependency when Biome replaced Prettier and ESLint. The result: 187 of 1004 files under src sat outside biome format, so anyone running npm run format turned a three-file change into a 190-file diff. The editor config now points at biomejs.biome, .prettierrc and the four orphaned eslint* devDependencies are gone, and npm run format:check (biome format src, no --write) runs inside npm run check.

All four source directories are covered — src, functions, tests, scripts, 1510 files. Keep them that way; adding a fifth means adding it to lint, lint:fix, format and format:check together, or it silently drifts the way the first three did.

Assertions on raw source text are what formatting breaks, and this repo has several. Two rounds of it so far:

  • CSS quoting is pinned to single in biome.json because scroll_region_contract.test.ts and pwa_doctor_contract.test.ts match the raw text of src/index.css; Biome’s double-quote default rewrites [data-platform='ios'] and reds them both on a change that alters nothing.
  • check-pwa-readiness.mjs counted atomicServerError(getDb(c.env.DB), as a contiguous substring across functions/. Formatting that directory wrapped two calls in notifications.ts past 120 columns and the count fell from 10 to 8 — the gate went red with no defect anywhere. Those three sites now use a whitespace-tolerant regex, rebuilt per call because /g carries lastIndex across .test(). When adding a check to the doctor, match with a regex that tolerates whitespace, never .includes() of a call expression — otherwise the next long line breaks it, formatter or not.

loose(snippet) in the doctor is the tool for this: it re-derives whitespace (required between two word characters, optional everywhere else) and tolerates the trailing comma a wrap inserts before a closing bracket. Use it for any new assertion that spans more than one token of code.

Negated guards are the ones that matter. A positive assertion announces itself when formatting breaks it — the gate goes red and someone reads the label. !source.includes('<forbidden code>') fails the other way: the moment the code it forbids comes back at a different indentation, the guard is trivially true and says nothing. Two were already in that state, spelling an exact indentation the file no longer had, and four more spanned code that a wrap would have split. All six now go through loose(), verified by injecting the forbidden construct inline and wrapped and confirming the gate reds on both.

The remaining positive .includes() assertions are left alone deliberately. Line length is not the criterion — Biome wraps at operator boundaries and moves a short call as a unit, so getDepthFromHistoryState(event.state) on a 120-column line was never at risk. Only a pattern reaching into the argument list of a call long enough to wrap internally breaks, which is what happened to atomicServerError(getDb(c.env.DB), and to nothing else in a full reformat of all four directories. Strings are immune throughout: the formatter never edits inside a literal, so Tailwind class lists and message text are stable.

Deliberate rule exceptions live in biome.json overrides, scoped per file rather than as scattered biome-ignore comments: noTemplateCurlyInString off for check-pwa-readiness.mjs (it greps for ${...} inside single-quoted strings — it is itself a linter), and noAssignInExpressions off for migration_schema_drift.test.ts and scripts/import/emit.mjs (a match-and-branch chain and a ??= grouping, where hoisting the assignment would run every regex on every statement).

The eslint-disable comments left in src are inert notes about why a dependency list is deliberate. They are not converted to biome-ignore: useExhaustiveDependencies is off, so there is nothing to suppress.

useExhaustiveDependencies is deliberately off. All 20 violations it reports were reviewed and none is a real defect: some are effects that key off a ref on purpose (prevChannelId.current, mapRef.current — refs are not reactive and must not be dependencies), some list specific fields rather than a whole object to avoid recomputing on identity changes. Nineteen of the sites carry a comment saying the dep list is deliberate; they used to say eslint-disable-line react-hooks/exhaustive-deps, which suppressed nothing — ESLint has not been a dependency since the Biome migration, and Biome’s own answer to a suppression for a disabled rule is suppressions/unused: Suppression comment has no effect. Do not convert them to biome-ignore while the rule is off; that trades a dead directive for a live warning. Enabling it would report twenty deliberate patterns forever and teach the team to scroll past lint output. Reach for it as a one-off audit (npx biome lint --only=correctness/useExhaustiveDependencies src) when hunting a stale-closure bug, not as a gate.

The a11y rules are on — they come with preset: recommended, and biome.json disables none of them — and the whole group is at zero across src: npx biome lint --only=a11y src is clean. This paragraph used to describe a 429-violation backlog sitting behind rules believed to be off; that debt is paid, so the count is a gate now rather than a to-do list. Two lessons from that audit still apply:

  • Never bulk-autofix useButtonType (it was 286 of the 429, and looks like a free codemod). A <button> inside a <form> defaults to type="submit", and some of our forms rely on that default instead of spelling it out — blanket type="button" stops them saving. src/components/ui/buttonType.test.tsx holds the line; each new button still gets read, not autofixed.
  • role on one of our own components is not an ARIA role — but check before you write the report off. The four useValidAriaRole hits here were logged as false positives on exactly that reasoning, and the reasoning was wrong: UserAvatar never accepted a role prop, so all four were dead props being rendered nowhere, and the lint was pointing straight at them. All five sites (the rule only saw the four passing a literal) now pass roleTag, the prop UserAvatar really renders. When the rule fires on a component of ours, read its props first.

Vite is configured with manual chunk splitting in vite.config.ts, by the package a file belongs to (a function, not the { chunk: [packages] } form — that form assigns a package with its dependencies, and it had put React’s own code in query-vendor):

  • ui-vendor → date-fns
  • react-vendor → react, react-dom, scheduler (every subpath)
  • query-vendor → @tanstack/react-query, @tanstack/query-core

lucide-react is deliberately unnamed. Named, every icon any screen uses joined the first load — ~18 kB gzip for pages the login cannot reach. Unnamed, the boot path’s few icons ride the entry (+6 kB re-downloaded per deploy) and the rest load with the lazy chunks that use them: first load 239.9 → 227.9 kB. date-fns stays named because the boot path needs about half of it; unnamed, that half would be re-downloaded on every deploy to save 5 kB once.

The last two exist for cache stability rather than size: they change only on a dependency bump, while the app entry changes every deploy, so a release re-downloads ~307 kB instead of ~532 kB. Matching the package path covers every subpath; the old object form needed react-dom/client spelled out, or most of react-dom stayed in the app chunk because the entry imports that subpath.

Naming a chunk makes it eager — that is the trap here. Rollup places its CommonJS interop helpers (commonjsGlobal, getDefaultExportFromCjs) inside the named chunk, and because the app entry needs those helpers it ends up statically importing the whole thing. There used to be a pdf-vendor (jsPDF + html2canvas) and a map-vendor (Leaflet), both commented as “loaded only when needed”; measured on a cold login screen they were downloaded every time, making a 415 kB gzip first load of which 204 kB was PDF export and maps that the login form cannot use. Removing both names dropped it to 211 kB, and the libraries now arrive only when the feature opens (verified: calling PdfExportService.exportToPdf is what pulls jspdf). Do not add them back.

Do not add react-hook-form or zod to a vendor chunk either: they are only reached from lazily-loaded forms, and naming them pulls ~100 kB into the initial load. (There is no ai-vendor; @google/genai was removed when the Gemini call moved behind /api/ai.)

Use dynamic import() when adding new large dependencies to keep the main bundle lean.

Tailwind CSS (v3) is compiled at build time via PostCSS — config in tailwind.config.js, PostCSS in postcss.config.js. The custom theme (the prime color scale, soft/luxury/inner-soft shadows, font) lives in tailwind.config.js. Global CSS, the @tailwind directives, and keyframe animations live in src/index.css, imported from index.tsx. Plus Jakarta Sans Variable is bundled locally through @fontsource-variable/plus-jakarta-sans; do not add a runtime Google Fonts dependency.

Leaflet’s CSS is not from a CDN — src/hooks/ui/useLeafletMap.ts does import 'leaflet/dist/leaflet.css', so Vite emits it as a CSS chunk that loads with that hook. Every map must therefore go through useLeafletMap: calling L.map() directly gets you an unstyled container whose tiles only line up if some other map happened to mount first and pull the stylesheet in.

Safe area insets for notched devices use CSS variables --safe-top / --safe-bottom and utility classes .pt-safe / .pb-safe.

The operation is in London; the admin works from Brazil and clients book from anywhere. Every time a person reads or types is London’s, whatever zone the browser (or a Worker, which runs in UTC) is in. Before this, a manager in São Paulo typing 09:00 booked 13:00 London, “today” ended three hours early, a summer 13:30 job counted as morning in the public quote, and the WhatsApp send window and business hours ran an hour late all summer.

  • src/shared/time/london.ts is the rule. londonDate(x) is the same instant with London getters/setters (getHours, getDay, setHours…); a bare YYYY-MM-DD is London midnight, a zoneless YYYY-MM-DDTHH:mm is London wall clock, a SQLite YYYY-MM-DD HH:mm:ss is UTC. londonWallClock(date, time) is how a typed date/time becomes a Date; londonDateKey/londonTimeKey are the input values and day keys; LONDON_TIME_ZONE goes into every toLocale* and Intl.DateTimeFormat. It is a TZDate subclass (LondonDate) that serialises as a plain …Z instant — TZDate prints +01:00, and an offset string saved next to Z strings breaks every D1 text range query.
  • date-fns is imported only from @shared/time/dateFns, which binds each calendar function to London (format, startOfDay, isSameDay, addDays… with { in: london }). The server imports the same modules by relative path.
  • tests/londonTimeGuard.test.ts refuses a direct date-fns import, a toLocale*/Intl.DateTimeFormat without timeZone, new Date(\${d}T${t}`)ornew Date(y, m, d), a UTC day key (toISOString().slice(0, 10)), and new Date()followed bysetHours/setDate`.
  • The whole suite runs in America/Sao_Paulo (vitest.config.ts), so a test that lets the machine’s zone decide a London time fails. Write fixtures as London times (londonDate('2026-07-14T09:00'), or +01:00 in summer), never zoneless new Date('…T09:00:00').
  • The UTC-offset settings (WhatsApp send window, business hours) are no longer read or shown; both use London’s clock.
Surface Minimum Declared in
iOS — native app and installed PWA iOS 17 IPHONEOS_DEPLOYMENT_TARGET = 17.0 in ios/App/App.xcodeproj (asserted by check-ios-readiness.mjs). cap sync regenerates CapApp-SPM/Package.swift from that value.
Android native Android 7 (minSdkVersion = 24) android/variables.gradle
Browsers and WebViews Chrome / Android WebView 108+, Safari 17+, Firefox 104+ build.target in vite.config.ts and browserslist in package.json (autoprefixer). Change them together. 108 rather than Vite’s default 107 because the layout sizes the page in dvh, which Chrome shipped in 108.

npm run test:browsers runs the production build in Chromium (as a Pixel 7), WebKit (as an iPhone 15) and Firefox, served by wrangler pages dev so the real Functions, _headers and _redirects are in play:

  • boot.browser.ts — the login screen renders with no uncaught error, the page fills the screen (dvh), and the manifest link and iOS launch images are there. API calls are answered 401, as for a signed-out visitor.
  • app.browser.ts — signs in through the real form and reaches the dashboard, books a quote from the week view, and proposes a new time for a seeded visit through Propose a new time to the client, then accepts it from the public /proposal link and checks the visit moved. The seeded client has no phone and no WhatsApp consent, so nothing is ever delivered. It runs against a throwaway D1 that scripts/e2e-seed.mjs recreates on every run in .wrangler-e2e/ (git-ignored) from db/schema.sql, seeded with the test-only admin in tests/browsers/e2e-user.json — an account that exists nowhere else. JWT_SECRET is a test-only binding; the rest of .dev.vars loads exactly as for npm run pages:dev.

It is kept out of npm run check because it needs the Playwright browsers (npx playwright install chromium firefox webkit, ~1 GB in ~/Library/Caches/ms-playwright). Run it after touching index.html, src/index.css, vite.config.ts, the auth flow or the supported range. Tests are tests/browsers/*.browser.ts, a suffix Vitest’s *.test.* discovery skips.

The build lowers syntax to that range and ships no polyfills. An API newer than the range needs a runtime guard: src/shared/platform/idleWork.ts for requestIdleCallback (absent from Safari), and createUuid in src/shared/uuid.ts for identifiers. uuidUsage.test.ts fails on a bare crypto.randomUUID call anywhere else.

iOS launches an installed PWA on white unless an apple-touch-startup-image in index.html matches the screen exactly; it never reads the manifest’s background_color. scripts/generate-brand-icons.mjs writes one per iPhone screen iOS 17 runs on, and tests/iosStartupImages.test.ts checks every file’s pixel size against its media query. Add the screen there when a new iPhone size ships, or that model launches white.

Content filters can edit the page in transit. AdGuard’s HTTPS filtering on Android stripped <link rel="manifest">, so Chrome installed a plain shortcut with a white splash and status bar that no manifest or theme-color change could reach. The inline script in index.html and ensureManifestLink (src/shared/pwa/manifestLink.ts) recreate the link — keep both. When a device reports PWA chrome that production does not reproduce, compare the HTML the device actually receives before editing CSS or the manifest.

Online payments (Stripe, GoCardless, account credit)

Section titled “Online payments (Stripe, GoCardless, account credit)”

Only a gateway’s signed webhook marks an invoice paid. The checkout hooks used to mark invoices PAID in browser state with an invented transaction id and no gateway call, and the GoCardless webhook accepted unsigned posts naming a (sequential) invoice number. The flow now:

  1. POST /api/payments/checkout (functions/api/payments/checkout.ts) works out the amount and any pass-through fee on the server, records a payment_checkouts row (0135) and returns the hosted page — Stripe Checkout, or GoCardless Instant Bank Pay (a mandate charge when the client has one). Staff may start one for any invoice, a client for their own, and a /pay/<id> link for that one invoice.
  2. The gateway calls /api/webhooks/stripe?entity=<fiscal entity id> or /api/webhooks/gocardless?entity=<id>. The signature is checked against that entity’s webhook secret before the body is read; GoCardless payments are also read back from its API. settleCheckout then settles every invoice on the checkout in one D1 transaction guarded by a per-run token, so a retried webhook settles nothing twice. Money for an invoice voided in the meantime is logged as GATEWAY_PAYMENT_FOR_CLOSED_INVOICE_ERROR, never applied.
  3. Account credit (/api/payments/wallet) writes a DEBIT to wallet_transactions — the ledger the balance is recomputed from — only if the ledger covers it, in the same transaction that settles the invoices.
  4. “I’ve paid by transfer” (/api/payments/transfer-claim) moves invoices to PENDING_REVIEW with a PENDING transaction and their jobs to PENDING_CONFIRMATION, all or nothing, for a manager to approve. Nothing is marked paid.

What a CLIENT may write. /atomic/invoices, /atomic/clients and request updates are staff-only, so a client-facing money action must go through /api/payments/*. The browser used to save a client’s transfer claim through the atomic endpoints and got 403 — the claim never reached anyone. “Staff Collection” in the checkout is staff-only for the same reason. A client creating a booking goes through clientBookingFields (functions/api/atomic/clientBooking.ts): the server prices it (hours × the client’s rate for the service, else the service default, else £20 — the calculateBasePrice chain) on the client’s own fiscal entity and resets every payment and staff-owned field. The payload used to be stored as sent, so a client could book at any price or send the job in already paymentStatus: 'PAID'. Staff saving a client can add wallet CREDIT entries (walletHistory → wallet_transactions); that is the top-up path and it is staff-only.

A client’s own cancel or reschedule goes through /api/scheduling/client-change. The Cancel and Reschedule buttons a client sees used to save through /atomic/requests, which refuses CLIENT updates — so the visit snapped back with an error and the loyalty credit was never spent (/atomic/clients is staff-only too). The endpoint takes only the intent: the fee comes from the stored cancellation policy (calculatePolicyFee, shared with the browser), a credit is spent there with a conditional decrement, and the visit lands in CANCELLATION_REVIEW or — a scheduled one moved — PENDING_REVIEW, with the series following when asked. Declining a cancellation restores the price (restorePrice), since the request already moved the fee into it. What a rejected reschedule returns to is the current start unless a review is still pending: originalDateTime is read off the edit history, which keeps every past original, so taking it unconditionally sent a rejected move back months.

A batch of saves counts refusals, not just network failures. countRefusedSaves (src/shared/api/refusedSaves.ts) is how every multi-visit flow (quote series, extending and resuming a series) tells how many rows the server did not keep: CloudClient resolves a 4xx, so a refused occurrence arrives fulfilled with error. The quote-series flow counted only rejections and announced refused weeks as created.

A series week the crew cannot work is created unassigned, never dropped. RecurrenceService used to skip it — silently when extending or resuming a series. It is now a PENDING visit with nobody on it (a vacant visit on the conflict board), the rule SeriesPlanService already applied to quote series; only a date the client is already booked on is skipped. Extending (useRecurringManagementController) and resuming (useOpsCommanderController) a series also only wrote to the store, so the visits vanished on the next refresh — both now save each one through RequestsApiClient.save.

Rows are scoped by role in common/scoping.ts; fields by common/roleRedaction.ts. Every scoped row used to go out whole: a client’s own visit carried financials.cost/profit and manualLaborCosts (what each cleaner is paid), and a cleaner saw colleagues’ pay on a shared job, the company’s margin, and the client’s wallet, negotiated rates and GoCardless ids. /api/boot and the GETs of /atomic/requests and /atomic/clients now pass every row through redactRequestForViewer / redactClientForViewer: an EMPLOYEE keeps the price and only their own manualLaborCosts line (the dashboard’s “your pay”), a CLIENT keeps what they pay; cost and profit read 0 for both. Any new endpoint that returns requests or clients to a non-manager must go through the same functions.

mapRecord parses JSON columns in both shapes: financials_json (raw D1 rows, as /api/boot reads them) and financialsJson (Drizzle rows, every /atomic/* GET). Only the first was recognised, so a request refetched through /atomic/requests — which the query cache does after every write — came back at price 0 with no checklist, incidents, recurrence or labour costs, and the raw string leaked under the storage key.

Per-entity credentials live in payment_configs_json and never reach the browser: functions/lib/payments/gatewaySecrets.ts lists them (API key/token and webhook signing secret for each gateway), boot turns each into an …Set flag, and the fiscal-entity upsert merges rather than overwrites — the form never holds a secret, so writing its config as-is erased them. A gateway is offered only when both its key and its webhook secret are saved (gatewayReady); otherwise a payment could be taken that no webhook can record. Settings → Billing shows each entity’s webhook URL to paste into the gateway dashboard.

A stored secret is removed from Settings with Remove beside it (Keep undoes it before saving): the form sends that secret as null, the one value the merge treats as “delete”. Settings used to be able only to replace a key — the endpoint that cleared one (/atomic/fiscalEntitySecrets) had no caller and is gone. The flag list lives once in src/shared/gatewaySecretFlags.ts, shared by the Functions and the browser, and saveFiscalEntity keeps the browser copy through withoutGatewaySecrets: a typed key goes to the server and nowhere else, and the …Set flags show what the server now holds (they stayed false until the next reload, so a correctly saved gateway read “hidden from clients”). To stop offering a gateway without deleting its keys, switch it off with Enable.

  • A session’s role is the account’s role, read on every request. getSessionUser takes role from the auth_accounts row, not from the JWT, and saving someone in the roster writes their role to their login account. Before, the token kept the role it was minted with for an hour, and only a roster save that also set a password copied the role across — so promoting or demoting staff changed nothing until they logged in again, and refresh re-minted the old role indefinitely. Tests must therefore seed one account per role; a token “claiming” another role on the same account id proves nothing.
  • Impersonation uses the person’s own account when they have one (real accounts have UUID ids). It inserted a placeholder under AUTH-<id> blindly; the email collided with the real account, the insert was ignored, and the token named an account that did not exist.
  • Magic-link requests are throttled like password resets (3 per identifier, 15 per IP, per hour; same neutral answer). Each request sends an email or a WhatsApp to whoever the identifier names.
  • Changing your password keeps this device signed in: every other session is revoked, and this one gets a fresh token pair.
  • Calendar feeds follow access. /api/calendar/ics tokens never expire, so every refresh re-checks the subscriber (loadAuthGateByAccountId + accountSessionDenialReason): a blocked or deactivated account gets 401, and someone else’s schedule needs a current ADMIN/MANAGER role (403 otherwise). It used to be the signature alone, so a blocked person or a demoted manager kept client names and addresses in their calendar indefinitely.
  • Ending access ends the pushes. Remote logout, blocking, a deletion request and deleting a person all remove every push device of theirs — browsers and native apps — through forgetPushDevices (functions/api/common/pushDevices.ts). They used to leave devices registered (deleting removed only the browser rows), so message previews kept reaching the phone of someone who no longer had access. Registering a device goes through getSessionUser, not a bare signature check, so a revoked token cannot re-register one.
  • /api/ai is metered per account. Every role reaches it (clients translate chat and draft reviews, cleaners analyse incidents), so it cannot be role-gated; it was unmetered and anyone signed in — a self-registered lead included — could run the company’s Gemini key as a free LLM. Each account gets 200 calls per 10 minutes (ADMIN/MANAGER) or 60 (everyone else) through consumePublicRateLimit with subject: user.id, prompts are capped at 50,000 characters, and Gemini’s error text stays in the log.
  • Refresh tokens detect reuse (0137). Rotation marks the old row used_at instead of deleting it. The same token presented again within 30 s is a race (two tabs) and just gets 401; later, it means one of two holders is not the owner, so the whole family — that one sign-in — is deleted and the event lands in system_logs as AUTH_REFRESH_TOKEN_REUSED. Other devices of the account are other families and keep working.
Variable Where Used
GEMINI_API_KEY .env → Vite → frontend AIService
JWT_SECRET Cloudflare secret → auth functions
CRON_SECRET Cloudflare secret on both the Pages project and the chat-do Worker → bearer for the scheduled calls (/api/cron/*, /api/whatsapp/process-queue), checked by isCronCaller in functions/api/common/cronAuth.ts. JWT_SECRET is still accepted there until CRON_SECRET is set; after that, remove JWT_SECRET from the Worker — the session-signing key has no business in a second Worker or on the wire every five minutes.
RESEND_API_KEY Cloudflare secret → email functions
GOOGLE_CLIENT_ID Cloudflare secret → Google OAuth
EVOLUTION_BASE_URL / EVOLUTION_INSTANCE Pages plain var → WhatsApp functions. In production these come from the Pages dashboard, not from wrangler.toml [vars] — the two can diverge silently.
EVOLUTION_API_KEY Cloudflare secret → WhatsApp functions
CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET Cloudflare secret → required: the Evolution host sits behind a Cloudflare Access application, so every call needs this service token or Access answers with its HTML sign-in page. Sent by evolutionHeaders() in functions/lib/evolutionApi.ts, the single place Evolution headers are built.
QUICKBOOKS_CLIENT_ID / QUICKBOOKS_CLIENT_SECRET Cloudflare secret → the one Intuit app every fiscal entity connects through. Without both, Settings says QuickBooks is not set up and invoices are not queued.
QUICKBOOKS_ENVIRONMENT Pages plain var → production for live companies; anything else (or unset) is the Intuit sandbox.
QUICKBOOKS_REDIRECT_URI Optional override. Defaults to <origin>/api/billing/quickbooks-callback, which must be registered on the Intuit app character for character.

Secrets are not part of any deploy. They live in the Bitwarden vault (item prime-crown:<KEY>, the source of truth — see SECRETS.md) and in Cloudflare, which is write-only. deploy:web sends code only; every deploy’s Functions read what is already stored. To add or rotate one: store it in the vault first, then export BW_SESSION=$(bw unlock --raw) and npm run secrets:sync:bw. That pushes every key .dev.vars.example lists, and writes CRON_SECRET to the chat-do Worker as well, since it must match there. JWT_SECRET rotates only through scripts/rotate-jwt-secret.sh. Never write a value in the repo; the pre-push blocks one in SECRETS.md. Native releases read their signing keys from the vault at release time; those never go to Cloudflare.

  • Sign-in links are stored hashed. Password-reset, magic and access links put hashToken(token) (SHA-256 — the same function hashes refresh tokens) in password_reset_tokens.token; only the link carries the raw value. Any new link type must hash on insert and on lookup, and a test inserting a token row must insert the hash.
  • login_attempts holds several throttles with different windows — the login’s 15 minutes and the hourly magic:/pwreset: counters. A cleanup must use the longest window (60 minutes); cleaning at 15 once turned the hourly limits into 15-minute ones.
  • A clock-in far from the address is flagged, not refused. checkInVerdict (functions/api/field/checkInDistance.ts) measures it on the server and stores serverDistanceMeters/outOfRadius in checkIn, logging CHECK_IN_OUT_OF_RADIUS. Indoor GPS is often a street off, so blocking would strand real cleaners; the manager sees Off-site in the activity log and history.
  • Knowing a phone number is not owning it. /api/leads/chat-initiate resolves the visitor by the number typed, and for an existing client that is the client’s own conversation. So it issues the guest-chat token only when asked (issueGuestToken, default false — neither the quote form nor widget.js reads it), /api/leads/chat-messages returns only messages since that token was issued and never an INTERNAL_NOTE, and the form cannot rename a client whose name is confirmed or withdraw their WhatsApp consent. Before, anyone could read a client’s whole private thread, internal notes included, by typing their number.
  • Declining a lead quote only declines an OPEN one (conditional update; the route answers 409 otherwise) — a late tap on a confirmed quote used to flip it to DECLINED and post a “declined” note into the new client’s conversation.
  • Confirming a lead quote claims it first (UPDATE … WHERE status = 'OPEN' RETURNING) and releases it on failure; two confirmations in flight used to create two clients.
  • Schedule-proposal slots are London wall-clock times (londonWallClock), validated strictly, and a link carrying from is refused once the visit has moved. A visit in progress cannot be moved.
  • The public statement never lists a DRAFT invoice.
  • The office sends the statement, rating and proposal links through /api/client-links (ADMIN/MANAGER only): it signs the link and posts it in the client’s conversation via sendSystemWhatsApp, so it goes out over WhatsApp. The buttons are Send statement (client modal, 30 days), Ask the client to rate this visit (finished, unrated visit, 14 days) and Propose a new time to the client (service logistics; the link lasts until the end of the proposed day, a week at most, and signs from). A visit is rated once, and only when DONE; the client’s accept or decline lands in their conversation as an INTERNAL_NOTE. WhatsApp buttons (Meta templates with quick replies) are the planned next step; the pages stay as their destination.
  • One Google review link: GOOGLE_REVIEW_URL in src/shared/googleReview.ts, the business’s Maps listing with the reviews panel open. The five copies it replaced were Google’s documentation place id (its Sydney office) and unchecked g.page links, so clients were sent to review someone else. tests/googleReviewLink.test.ts refuses an inlined review URL.

Uploaded files are served from the app’s origin

Section titled “Uploaded files are served from the app’s origin”
  • /api/upload stores the Content-Type the extension allows (contentTypeForUpload in functions/api/common/mediaTypes.ts), not the one the browser declares. A declared type is kept only when it fits — .mp4/.webm stay audio or video as declared, because the WhatsApp forwarder routes voice notes on the stored type.
  • /api/uploads/* always sends X-Content-Type-Options: nosniff, and anything that is not an image, PDF, audio or video goes out as application/octet-stream with Content-Disposition: attachment — whoever stored it, webhooks included. A quote.pdf declared as text/html used to be stored as HTML and, opened from the chat, ran as a page of the app with the manager’s session.

Full dev→staging→prod flow, migration discipline (expand/contract) and the go-live checklist live in DEVELOPMENT.md.

Does this change need a new native release?

Section titled “Does this change need a new native release?”

Usually no. capacitor.config.ts sets server.url to the production origin, so the packaged apps load the very bundle Pages serves — a push to main reaches Android and iOS users when they reopen the app, with no store review. Cutting a release for a web-only change buys nothing and costs a review cycle.

A new binary is required only when the native container changes: anything under android/ (Android only), under ios/ (iOS only), capacitor.config.ts, or adding/removing/upgrading a Capacitor plugin (both). npm run release:check decides this per store, diffing against that platform’s newest release tag, prints the next build number, shows a loud banner, and fires a macOS Notification Center alert when a release is needed (exit 2 — advisory). It runs from the pre-push hook and deploy:web without blocking either, so a plugin bump cannot be pushed and quietly forgotten. Disable the notification with PRIME_CROWN_NOTIFY=0. Pass a ref to ask about a different baseline: npm run release:check -- 401faa6, or --platform android|ios to narrow it.

Android and iOS share one counter and one version line, in scripts/native-version.mjs. The build number is max(any android-v*/ios-v*) + 1 and the versionName/MARKETING_VERSION is bumped from the newest tag of either platform, so a number identifies one build across the product instead of meaning two different things per store. Publishing the same commit to the second store reuses that commit’s number and name rather than taking the next one — ship both together and both stores carry identical numbers. iOS injects them at build time (MARKETING_VERSION / CURRENT_PROJECT_VERSION on the xcodebuild line), the same way Android gets -PprimeCrownVersionCode, so no bump is ever committed and project.pbxproj keeps Capacitor’s defaults. Inspect with npm run native:version -- next / list.

A platform with no tag at all is treated as not published and never raises the alarm — that is iOS today, so release:check stays quiet about it instead of nagging on every push. The day ios-v1 exists it is checked like Android, with no code edit.

Tag every published release — android-v<build> / ios-v<build>, annotated with what shipped. The tag is the only record of what is live: Android releases 1–3 predate this and their commits are unknown, which is exactly the gap it closes.

When a release is needed, prefer the auto path (detects, numbers, bumps patch versionName, unlocks Bitwarden if needed, then publishes):

Terminal window
npm run android:release:auto -- --yes --track alpha
Terminal window
npm run ios:release:auto -- --yes

Both are scripts/release-native-auto.sh --platform <p> — one script, because two near-identical ones is how the numbering diverged in the first place. --minor / --major change the bump; omit --yes to confirm interactively. bw unlock is the only step that still needs you when the session file is cold. The pre-push hook asks the same question on a TTY after an Android native change (set PRIME_CROWN_AUTO_RELEASE=0 to silence the prompt); it does not offer to submit to Apple, where review and processing make a push-time prompt meaningless. Explicit control:

Terminal window
bw unlock --raw > /tmp/prime-crown-bw-session && chmod 600 /tmp/prime-crown-bw-session
npm run android:release:bw -- 1.3.0 --track alpha

scripts/release-android-bw.sh and scripts/release-ios-bw.sh derive the build number from the shared counter (never a free-form guess; guessing produced a wrong tag once). Override only with --version-code N when the baseline is broken. Android pulls the keystore and the Play service account from Bitwarden, builds signed and uploads through the androidpublisher API (scripts/publish-play.mjs); iOS pulls APPLE_TEAM_ID plus the App Store Connect API key (APP_STORE_CONNECT_KEY_ID / _ISSUER_ID / _PRIVATE_KEY_BASE64), archives with xcodebuild and uploads with xcrun altool. Both tag only after the store accepts. Tagging before upload makes release:check lie and the next run skip a number — if that happens, delete the premature tag and re-run. --dry-run is a real rehearsal on both: Play uploads and assigns the track without edits.commit (an uncommitted edit expires on its own), iOS runs altool --validate-app and submits nothing. --rollout 0.1 stages Android at 10%.

The iOS path has never been executed. It mirrors Android line for line, but this machine has no Xcode (only Command Line Tools) and the project has no DEVELOPMENT_TEAM, so the first run will be the first real test — expect to fix signing details, not the numbering.

The app is deployed by npm run deploy:web, not by the Cloudflare Pages Git integration and not by GitHub Actions — see Deploying at the top. The Git build is to be paused in the dashboard (prime-crown → Settings → Builds); while it is on, each push starts one that fails or would publish a second time. What guards main is the local .githooks/pre-push hook, which runs npm run check (typecheck + lint + tests) and aborts the push on failure; deploy:web only publishes a commit that is on origin/main. Don’t git push --no-verify on main.

Solo workflow (no team, Actions dormant): npm run backend:check / the pre-push hook detect pending db/migrations/** or chat-do/** against the newest backend-v<N> tag (banner + macOS notification + optional “apply now?”). npm run deploy:backend applies them and only then creates the next backend-v* tag — same contract as the stores’ android-v* / ios-v*.

GitHub Actions workflows under .github/workflows/ are manual escape hatches only (workflow_dispatch) — they do not run on push/PR. Prefer the local commands above. npm run deploy is an alias of deploy:web (the old deploy.sh, which applied migrations without the backend-v* tag, is gone).

Seed files:

  • db/seed_minimal_local.sql — for local development
  • db/seed.sql / db/seed_production.sql — full data

Migrations are hand-written in db/migrations/, and that is the only migration path. Wrangler picks them up automatically (migrations_dir in wrangler.toml). They reach the production D1 via deploy.yml — or, while Actions is blocked, via npm run deploy:backend (see Deployment). Drizzle is used as the query and type layer only — drizzle-kit is not a dependency and there is no migration generation. It was removed deliberately: drizzle-kit’s SQLite strategy rewrites tables via DROP/recreate, which is unsafe on a D1 with no automatic rollback and conflicts with the expand/contract discipline in DEVELOPMENT.md.

Three files must be kept in step when the schema changes:

  1. db/migrations/NNNN_*.sql — the delta that actually runs against the database.
  2. db/schema.sql — the full baseline, used by npm run db:init to build the local database. Mirror every migration here, or local dev silently diverges from production.
  3. functions/api/db/schema.ts — the Drizzle table definitions that 77 files build queries from.

tests/schema_drift.test.ts guards steps 2 and 3 against each other: it loads db/schema.sql into an in-memory SQLite and asserts every table, column and index declared in schema.ts exists there. It does not know about step 1, so a migration mirrored into neither file still passes — mirror as you go.

That gap has already been paid once, and the residue is still in production. service_requests carries three columns declared in neither file — chat_messages_json, last_read_at_json and is_support_channel — left behind when chat moved into channels/messages (see the comment at db/schema.sql line 723). They are inert: Drizzle cannot read a column it does not declare, and a census of production found chat_messages_json empty on every row, so no conversation is sitting there unaudited. They are recorded here because the drift is invisible by construction — the test compares the two files with each other and never with the database, so nothing in npm run check can see a column that exists only in production. Dropping them is a contract-phase migration on a D1 with no rollback, for no functional gain; leaving them documented is the cheaper half.