S.S. Plumbing
← All guide sections

Design & architecture

A technical overview of how the app is built — for developers and technically-minded readers, not day-to-day users. The source of truth isdocs/DESIGN.md in the repository; this page renders it so it's reachable without leaving the app, rather than keeping a second hand-maintained copy.

FuzailServiceDesk — Low-Level Design

This is the technical/architecture reference for engineers (and the

/help "Design & architecture" page, which links here). It describes what

the codebase actually does, each claim tied to a real file. It does not

repeat product scope (docs/PRODUCT.md), UX rules (docs/UX.md), the

print/document system (docs/DOCUMENTS.md), or the decision log

(docs/DECISIONS.md) — read those first; this document assumes them and

goes one level deeper into how.

Diagrams are inline below and also saved standalone under docs/diagrams/

as .mmd files (er-diagram, quotation-invoice-payment-states,

auth-rls-flow, request-lifecycle, component-tree,

deployment-topology) for reuse by the in-app help pages.

---

1. System context and request lifecycle

Three tiers, no custom backend (docs/ARCHITECTURE.md — "No custom

backend/API server in V1"):

  • Browser — a installed-or-not PWA running Astro-built static HTML plus

React islands.

  • Astro + React islands — each route under src/pages/*/.astro is a

statically generated shell (AppShellLayout.astro → BaseLayout.astro)

that hydrates one or two React components with client:load (never

client:visible/client:idle/client:only — confirmed by grepping

every client: directive across src/pages/*/.astro and

src/components/**: all 24 hits are client:load; see §2).

  • Supabase — Postgres + Auth + PostgREST + Row Level Security. The

browser talks to it directly via @supabase/supabase-js

(src/lib/supabase.ts); there is no server-side proxy or API route.

Where auth and the owner gate sit. Every business-data page calls

useBusinessGate() (src/lib/useBusinessGate.ts), which:

  1. Calls supabase.auth.getSession(); redirects to /login if there is

no session.

  1. Calls getBusinessAccessState() (src/lib/business.ts:51-62), which

fetches the caller's profiles row (RLS: profiles_select_own) and

returns one of linked / needs_setup / needs_join depending on

profile.business_id and the business_exists() RPC (a

SECURITY DEFINER function that leaks only a boolean, never business

data — supabase/migrations/20260824172716_business_exists_rpc.sql).

  1. On linked, sets gate = 'ready' and exposes businessId; on

anything else, redirects to /setup.

Every subsequent table query/RPC is then additionally scoped by Postgres

Row Level Security (§4) — the gate is a UX convenience (which screen to

show), RLS is the actual authorization boundary (docs/ARCHITECTURE.md:

"Never rely on frontend checks for data protection").

(docs/diagrams/request-lifecycle.mmd)

The RPC → UI trigger map for every app-callable function was already built

by Wave 0 — see docs/help/coverage-matrix.md's "RPC → UI trigger map"

table; reused here rather than re-derived.

---

2. Architecture: Astro routing + React islands

File-based routing only (docs/ARCHITECTURE.md: "Do not introduce React

Router") — every route is a file under src/pages/**, e.g.

src/pages/quotations/index.astro, src/pages/quotations/view.astro.

What's static vs. hydrated. BaseLayout.astro (head/fonts/PWA

manifest/dark-mode anti-flash inline script) and AppShellLayout.astro

are pure Astro (server-rendered at build time, zero client JS of their

own). Every page wraps its page-level React component in

AppShellLayout, which itself hydrates AppShell.tsx with client:load,

and the page's own component (e.g. QuotationsPage.tsx) is passed into

AppShell's <slot /> and also hydrated with its own client:load —

confirmed in src/layouts/AppShellLayout.astro:14 and e.g.

src/pages/quotations/index.astro:7. These are two independent React

roots on the same page (Astro's island model — a nested

client:-directed component hydrates separately from its parent), which

is why src/lib/queryClient.tsx's module-level QueryClient singleton

matters: it's what lets AppShell (branding) and the page island (list

data) share one cache despite not sharing a React tree.

Why client:load everywhere, not client:visible/client:idle.

Every page in this app is already gated behind an authenticated

business-data fetch (§1) — there is no above-the-fold/below-the-fold

split where deferring hydration would help, and the app's own perf work

(v3.1.0) found the real cost was JS chunk count, not hydration timing

(docs/plans/v3.1-perf.md). client:load is the simplest option that

matches that reality (ponytail: no directive tuning was ever shown to be

worth it here).

(full version: docs/diagrams/component-tree.mmd)

---

3. Data model

27 migration files in supabase/migrations/ (all read in full this pass,

from 20260824083813_business_and_profiles_foundation.sql through

20260929120000_v3_1_perf_indexes.sql). 13 tables, all business_id-scoped

except quotation_items/invoice_items (scoped transitively through their

parent).

(full column/constraint detail: docs/diagrams/er-diagram.mmd)

Key design choices, each traceable to a migration:

  • Singleton business. business_singleton_idx, a unique index on the

constant expression (true), enforces at most one row in public.business

regardless of RLS/app logic

(20260824083813_business_and_profiles_foundation.sql:55). See §4 for

the single-tenant-today implication.

  • Numbering. job_number/quotation_number/invoice_number come

from next_number(business_id, counter_name)

(20260825090000_number_counters.sql:34-51), an atomic

INSERT ... ON CONFLICT ... DO UPDATE ... RETURNING against

number_counters — the row-level lock from the UPDATE serializes

concurrent callers without an explicit SELECT ... FOR UPDATE. Never a

client-side SELECT max(number) + 1.

  • Trigger-derived money. quotation_items_set_amount() /

invoice_items_set_amount() compute amount = quantity * unit_price

on each item row; *_sync_parent() AFTER triggers roll that up into the

parent's subtotal; quotations_set_total() /

invoices_recalculate() derive total/amount_due from

subtotal - discount + tax (and, for invoices, auto-transition

status — see §4's state diagram). None of subtotal/total/

amount_paid/amount_due is ever client-writable (column grants

exclude them — 20260825120000_lock_financial_columns_and_issue_invoice_rpc.sql,

20260928140000_tighten_authenticated_grants.sql).

  • CHECK constraints as the real integrity layer.

quotations_discount_le_subtotal / invoices_discount_le_subtotal

(discount <= subtotal) and *_total_non_negative (total >= 0)

(20260826090000_financial_integrity_and_draft_lock.sql:47-57) prevent

a negative-total invoice/quotation at the database layer, not just the

UI — create_quotation()/create_invoice()/convert_quotation_to_invoice()

(the last since dropped, see below) insert items before applying the

caller's discount/tax so the CHECK evaluates against a real subtotal,

not the pre-items 0.

  • Draft-lock triggers. quotations_lock_after_draft() /

invoices_lock_after_draft() (header) and

quotation_items_lock_after_draft() / invoice_items_lock_after_draft()

(items) block writes once a document leaves draft, closing a

DevTools-level bypass of the UI's disabled inputs

(20260826090000_financial_integrity_and_draft_lock.sql:299-413). See

§4/the state diagram for exactly which columns.

  • Soft delete, not hard delete, for customers.is_archived

(20260825090700_customers_archive.sql) and quotations.is_archived

(20260927100000_quotations_soft_delete.sql) — consistent with every

other table in this schema having no DELETE grant at all except

quotation_items/invoice_items (line items, deletable while the

parent is still a draft).

  • Catalog is a convenience, not inventory. catalog_items has no

stock/valuation/supplier columns; default_price is copy-on-select

only — no FK from quotation_items/invoice_items back to

catalog_items, so editing a catalog price can never retroactively

change an already-saved document (20260919090000_catalog_items_and_customer_gstin.sql,

docs/DECISIONS.md D9). Uniqueness is (business_id, name, item_type),

not (business_id, name) — fixed in

20260926090000_catalog_item_name_uniqueness_per_type.sql after the

original constraint blocked a legitimate material/service name split.

  • Domain correction, schema-level. 20260919100000_purchase_list_bill_independence.sql

drops convert_quotation_to_invoice() and invoices.quotation_id

entirely, and makes quotations.customer_id nullable — Purchase Lists

and Bills are independent documents, not a pipeline (docs/DECISIONS.md

D13). invoices.customer_id stays NOT NULL.

  • Files are metadata-only. public.files stores storage_key (an R2

object key) but no binary ever touches Postgres; R2 itself isn't wired

up yet (§10).

Purchase List and Bill status, side by side. These are two

independent documents (D13, §3) — not a pipeline — so the diagram below

shows two disconnected state tracks, not one flow:

(full version: docs/diagrams/quotation-invoice-payment-states.mmd)

---

4. Authorization model

Posture: default-deny, explicit grant. Every table and function in

this schema requires an explicit GRANT to be reachable at all — Postgres

grants EXECUTE on every new function to PUBLIC by default, and

Supabase's own platform-level defaults were independently found (twice:

v2.2.6, v2.2.7) to have granted anon/authenticated far more than any

migration intended, including direct table DELETE and EXECUTE on

trigger functions, entirely outside this repo's version control

(AGENTS.md's "Database grants" section). 20260928120000_revoke_anon_grants_hardening.sql,

20260928130000_revoke_next_number_from_authenticated.sql, and

20260928140000_tighten_authenticated_grants.sql revoke everything from

anon/authenticated/PUBLIC first, then re-grant exactly the intended

table operations/columns and exactly the 9 real app-called RPCs (see

docs/help/coverage-matrix.md's RPC map), plus

ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ...

so a future table/function with no explicit grant also fails closed,

not open. AGENTS.md's own rule (every new table/RPC migration must

include its explicit grants in the same migration) exists because this

default-deny backstop is exactly that — a backstop, not a substitute.

RLS pattern, identical across every business-scoped table: a policy

`USING (EXISTS (SELECT 1 FROM profiles WHERE profiles.id = auth.uid() AND

profiles.business_id = <table>.business_id))`. Line-item tables

(quotation_items/invoice_items) have no business_id of their own —

their policies join through the parent (quotations/invoices) to reach

the same check. number_counters has RLS enabled with **no policies at

all** (default-deny), reachable only from inside next_number()

(SECURITY DEFINER, called only by create_job/create_quotation/

create_invoice).

Owner role. profiles.role ('owner' | 'member', not client-writable

— no column grant) was added in v3.0.0

(20260929090000_v3_business_settings_invites_and_owner_role.sql) because

business_update_members originally let any linked member update the

shared business row with no concept of who owns it. The first caller of

initialize_business() becomes owner; everyone else defaults to

member and stays that way until the account owner runs a one-time SQL

bootstrap (docs/onboarding-new-client.md step 4) — deliberately not

auto-guessed, matching the "never silently decide" principle in

AGENTS.md. business_update_owner (UPDATE only — SELECT stays open to

every member) and invites_select_owner/invites_insert_owner/

invites_delete_owner all gate on role = 'owner'.

(full version: docs/diagrams/auth-rls-flow.mmd)

Single-tenant today, multi-tenant-shaped tomorrow. business_singleton_idx

(§3) means this schema has no tenant_id anywhere — every table's

isolation key is business_id, which today can only ever hold one real

value per deployed instance (docs/ARCHITECTURE.md: "Single-business

deployment... reusable by cloning the repository"; CLAUDE.md's Product

direction: "One codebase, one copy per client today; multi-business SaaS

later... Keep business_id scoping intact everywhere"). Every RLS policy

already reads as "rows where business_id matches the caller's own" —

structurally the same shape a real multi-tenant schema would need, except

the unique index currently prevents more than one tenant from ever

existing in one database. Moving to true multi-tenant SaaS would mean

dropping business_singleton_idx and relaxing initialize_business()'s

"business is already initialized" guard — not a schema rewrite, because

the per-row scoping is already there. This is a real, deliberate

today-vs-later line, not an oversight.

---

5. Design patterns actually present

| Pattern | Where | What it buys us |

|---|---|---|

| Gate / guard hook | src/lib/useBusinessGate.ts (session + business-link check, extracted once a 4th call site needed it — see its own comment) | One auth/redirect flow instead of copy-pasted logic across every business-data page. |

| Shared query cache (module singleton) | src/lib/queryClient.tsx:11-18 — one QueryClient at module scope, imported by every island | Independent React roots (AppShell + page island, §2) share one cache without a shared component tree; clearQueryCache() wipes it on logout (src/lib/auth.ts). |

| Imperative cache read, no Provider needed | fetchCurrentUserProfile() (src/lib/business.ts:29-35) uses queryClient.query(...), TanStack's imperative API | Dedupes concurrent identical fetches (the gate check and Header.tsx both need the same profile) without wrapping every caller in <QueryProvider>. |

| Shared debounce hook | src/lib/useDebounce.ts — useDebouncedValue(value, 300) | Replaced 9 copy-pasted setTimeout blocks across list pages (v3.1.0, docs/plans/v3-state.md Wave 5 finding 1). |

| URL-synced filter state | src/lib/useListFilters.ts — readParamsFromUrl/writeParamsToUrl | Dedupes URLSearchParams/history.replaceState boilerplate; each page still owns its own filter shape/defaults (no shared "filter schema" abstraction was built — not needed). |

| Lazy singleton via Proxy | src/lib/supabase.ts:6-35 — the exported supabase is a Proxy whose get trap lazily constructs the real client on first property access | Importing the module during Astro's static prerendering never requires PUBLIC_SUPABASE_* env vars to be set; the "missing env var" error only surfaces when the client is actually used client-side. |

| Document shell / composition | src/components/documents/DocumentShell.tsx (A4 frame) + DocumentHeader.tsx (shared letterhead) composed by QuotationDocument.tsx; BillDocument.tsx reuses DocumentShell/DocumentHeader/BusinessLogo but hand-rolls its own table/totals/signature (deliberately not forced through DocumentItemsTable, which is tuned for the no-pricing Purchase List shape) | Real content differences (a Bill has pricing/signature, a Purchase List doesn't) stay out of a forced-shared abstraction, while the one genuinely shared piece (letterhead) is shared — see docs/DOCUMENTS.md's "Architecture" section and docs/DECISIONS.md D16. |

| Explicit variant over boolean default | src/components/shared/LineItemsEditor.tsx:41 — variant: LineItemsVariant ('purchase-list' \| 'bill'), required, no default | Supersedes an earlier showPricing?: boolean (default true) specifically to close off "a caller forgets to pass it and silently gets Bill behavior on a Purchase List" (docs/DECISIONS.md D15). |

| Trigger-as-invariant, RPC-as-the-only-write-path | next_number(), record_payment(), issue_invoice() — all SECURITY DEFINER, each the sole path for its operation | Financial invariants (atomic numbering, payment-vs-balance, draft→issued) live in one place the client cannot route around, not duplicated in app code (§7 covers the two concrete algorithms). |

| Manual chunk bundling as a deliberate, measured trade-off | astro.config.mjs:15-51 — manualChunks bundles components/{ui,data-table,form,shared}/ into shared-ui and src/lib/ into shared-lib | Turns ~20 per-component Rollup chunks into 2 content-hashed, browser-cached ones; accepted trade-off (a route also ships a few KB of other routes' lib code) documented in docs/plans/v3.1-perf.md, not reversed after review. |

---

6. SOLID assessment — honest

This is a small CRUD app with ~15 page-level components and a Postgres

backend doing most of the heavy lifting (triggers/RPCs), so classic OOP

SOLID doesn't map perfectly — the assessment below is about where the

same pressures (one reason to change, substitutability, minimal

interfaces, depending on abstractions) hold up or don't in a

function/component codebase.

Single Responsibility — mixed, with a real, named violation.

QuotationDetailPage.tsx (437 lines) and InvoiceDetailPage.tsx (447

lines) each do five jobs in one component: data fetching (load()),

header-field editing + save, line-item editing + batched save

(saveItems(), §7), tab-switching between edit/preview, and feeding the

loaded record into the document renderer. This was a deliberate choice,

not an oversight — docs/DOCUMENTS.md's own principle is "the edit form

and the document are different render paths," and the two are visually

separated (hidden/print:block pairing) — but they still live in the

same component file with the same state. The cost: a change to either

the edit flow or the document feed risks touching the same 400+ line

file, and the two detail pages are near-duplicates of each other (same

five responsibilities, different domain) rather than sharing a generic

"document detail page" shell. No refactor was attempted here (out of

scope for a docs-only pass), but it's a real candidate if either page

needs to grow further — contrast with src/lib/queryClient.tsx (3

single-purpose exports) or src/lib/useDebounce.ts (1 function, 1 job),

which are genuinely narrow.

**Open/Closed — the variant prop is the honest version of this, and it

cuts both ways.** LineItemsEditor.tsx's `variant: 'purchase-list' |

'bill'` (§5) correctly refuses a silent default, but every behavior

difference between the two variants is an if (isBill) branch inside one

393-line file (confirmed: grep variant shows the branch logic, not a

strategy-object split). Adding a third document variant — plausible

given the app already has Purchase List and Bill as separate line-item

shapes — means editing this file again, not extending it from outside.

That's an accepted trade-off for a 2-variant, unlikely-to-grow-to-5-variant

app (AGENTS.md: "Do not over-engineer"), not evidence the principle was

satisfied.

**Liskov substitution — holds, because there's little inheritance to

violate.** No class hierarchies exist in src/; the closest analogue is

the shared desktop-table/mobile-card pattern (docs/UX.md: "same

dual-render pattern as every other list") — every list page's table

component (CustomerTable, QuotationTable, InvoiceTable, JobTable)

honors the same hidden md:block / flex md:hidden contract, so any one

of them can be read/maintained with the same mental model. No violation

found.

Interface segregation — mostly fine, one real counter-example.

src/lib/business.ts (263 lines) exports profile fetching, business

CRUD, branding, and invite CRUD from one module — three product

concerns (account/session, business settings, team invites) behind one

import surface. A consumer that only needs useBusinessBranding() still

pulls in the invite functions' module graph (mitigated, not eliminated,

by the manualChunks bundling in §5, which already puts all of

src/lib/** in one chunk regardless). Most other lib modules

(useDebounce.ts, useListFilters.ts, files.ts) are properly narrow —

this is a business.ts-specific issue, not a pattern across the codebase.

Dependency inversion — genuinely strong, worth crediting. Every

financial write goes through an RPC (record_payment, issue_invoice,

create_invoice, create_quotation) that the client calls by name and

never otherwise depends on the implementation of (§7); src/lib/*.ts

functions are the only things that know the Supabase query shape, and

every React component depends on those functions, never on supabase

directly for business tables (confirmed by the consistent

src/lib/<domain>.ts → component import direction across every list/

detail page). The one inversion that's missing is also a known,

accepted one: quotations.status has no RPC gating it at all (§3/§7) —

any value transition is a plain column UPDATE, which is a deliberate

"this is just a label" decision (20260825120000_lock_financial_columns_and_issue_invoice_rpc.sql's

own comment), not an inconsistency with the invoice side, which does

need one because money is at stake there and isn't here.

---

7. Data structures and algorithms actually present

This is a CRUD billing app, not an algorithms showcase — most of what

would be "data structures" is the relational schema itself (§3). The

list below is what's genuinely there, nothing invented:

  • Debounce + AbortController on every list page's search.

useDebouncedValue(value, 300) (src/lib/useDebounce.ts) delays the

re-fetch; list query functions (e.g. listQuotations) accept a real

AbortSignal so a superseded in-flight request is actually cancelled

over the wire, not just ignored (v3.1.0, docs/releases/v3.1.0.md).

  • Atomic counter via row-lock UPDATE, not max()+1.

next_number() (20260825090000_number_counters.sql:34-51, detailed

in §3) — the one piece of genuinely concurrency-sensitive logic in the

schema, and it's handled with a single atomic statement rather than an

explicit lock.

  • Index selection, verified with real EXPLAIN output. Three indexes

added in 20260929120000_v3_1_perf_indexes.sql

(quotations(business_id, issue_date), `catalog_items(business_id,

is_active), payments(business_id, payment_date)); docs/plans/v3.1-perf.md`

has the actual EXPLAIN (ANALYZE, BUFFERS) output confirming 2 of 3

were picked by the planner directly (`Index Scan Backward using

quotations_business_id_issue_date_idx`,

payments_business_id_payment_date_idx), and documents why the

third (catalog is_active) wasn't chosen for the tested query shape

(an existing (business_id, name, item_type) index already satisfied

the ORDER BY name) without pretending it was.

  • Atomic multi-row write via jsonb_array_elements.

create_quotation/create_invoice accept line items as a single

jsonb array parameter and insert all of them in one

INSERT ... SELECT ... FROM jsonb_array_elements(...) statement

(20260825090200_quotations.sql:330-338), rather than one round trip

per item.

  • Batched line-item edits via Promise.all. saveItems() in

QuotationDetailPage.tsx:183-218 and the equivalent in

InvoiceDetailPage.tsx diff the current draft against the last-saved

state into delete/add/update buckets, then fire all three buckets

together: `await Promise.all([...toDelete.map(deleteItem), ...toAdd.map(addItem),

...toUpdate.map(updateItem)]) (QuotationDetailPage.tsx:207-211`) —

not sequential awaits (v3.1.0 fix, docs/plans/v3-state.md Wave 5

finding 1).

  • N+1 eliminated via join, not a cache. JobDetailPage.tsx:80 does

Promise.all([getJob(jobId), fetchRelated(jobId)]) and reads

j.customers?.phone directly off getJob()'s own result

(JobDetailPage.tsx:114) — getJob() already joins the customer row,

so there's no second query for the phone number at all (the earlier

version, per docs/plans/v3-state.md Wave 5, fetched it separately).

  • Manual chunk bundling — covered in §5/§8 (it's a build-tool

configuration, not a runtime algorithm, but it's the single biggest

lever on this app's measured performance, so it belongs in both

sections).

  • Not applicable / genuinely absent: no custom sorting/search

algorithm (Postgres ORDER BY/ILIKE does it all), no client-side

pagination math beyond DataTablePagination's page-number arithmetic,

no caching eviction policy beyond TanStack Query's own staleTime

(§5), no graph/tree algorithm anywhere in the domain model.

---

8. Performance budget

e2e/network-budget.spec.ts asserts each of 8 list-page routes

(/customers, /jobs, /quotations, /invoices, /payments,

/expenses, /items, /files) issues **no more than 70% of its

v3.0.0-era baseline request count** (BUDGETS map in the spec file,

e.g. /customers: 32 baseline → budget floor(32*0.7) = 22), counted

via page.on('response', ...) after `page.goto(route, { waitUntil:

'networkidle' }) against a production build + astro preview` (not dev

mode).

v3.1.0 results (docs/plans/v3.1-perf.md, reproduced in

docs/releases/v3.1.0.md):

| route | before | after | reduction |

|---|---|---|---|

| /customers | 32 | 21 | 34% |

| /jobs | 33 | 22 | 33% |

| /quotations | 35 | 22 | 37% |

| /invoices | 33 | 22 | 33% |

| /payments | 34 | 22 | 35% |

| /expenses | 34 | 21 | 38% |

| /items | 36 | 21 | 42% |

| /files | 26 | 17 | 35% |

The data-layer fixes alone (shared TanStack Query cache for the

business row/current-user-profile, batched line-item saves, the

JobDetailPage N+1 fix) only moved request counts by ~3% — the dominant

cost turned out to be ~20 separate tiny JS chunks per page from Astro's

default per-component code-splitting (docs/plans/v3.1-perf.md's "Network

budget results" section). The actual fix was astro.config.mjs's

manualChunks (§5), which did the rest. The accepted trade-off (a route

now also ships a few KB of other routes' own src/lib/* code) is

reviewed and documented there, not re-litigated here.

To re-measure: `npm run build && npx playwright test --project=desktop

e2e/network-budget.spec.ts` (production build + preview server, matching

how the v3.1.0 numbers were produced — not astro dev).

Deployment topology (why the build that gets measured above is the

one users actually get): GitHub hosts the repo; Cloudflare Pages builds

and serves the static Astro output via its own native Git integration —

confirmed by the absence of any deploy step in

.github/workflows/ (only ci.yml, backup.yml,

supabase-keepalive.yml exist, read in full this pass; none runs

wrangler/a Pages deploy command). ci.yml only lints/type-checks/builds/

audits and conditionally runs the money-RPC script (§9) — it gates merges,

it doesn't deploy. Supabase is the only backend, reached directly from

the browser (§1). backup.yml (daily cron) dumps + age-encrypts the

database to a separate private repo (docs/BACKUP.md); R2 (files, §10)

isn't wired up yet.

(full version: docs/diagrams/deployment-topology.mmd)

---

9. Testing strategy

Playwright projects (playwright.config.ts:63-85): setup (auth

state), desktop (Chrome, full functional suite), android (Pixel 7,

full functional suite), iphone (iPhone 14, only runs specs tagged

@layout, via grep: /@layout/ on that project — WebKit is used for

print/mobile-layout coverage only, not a third full run of business

logic, since desktop+android already cover that on Blink).

Production guard. e2e/env.ts:30-57's loadE2eEnv() loads

.env.e2e, then hard-throws if PUBLIC_SUPABASE_URL contains the

production project ref (hczloofxdwwsdxrfwyun) or if E2E_EMAIL/

E2E_PASSWORD are missing — called once by playwright.config.ts:9,

before any webServer starts or any test runs, and the same resolved env

is passed into the spawned preview server's env (playwright.config.ts:57-61),

so both the runner and the app-under-test are guaranteed to be pointed at

the same non-production project.

Release gates (CLAUDE.md): the @layout tag and the desktop print

pixel-regression (e2e/print-fix.spec.ts:134-144, `toHaveScreenshot('desktop-print-purchase-list.png',

{ maxDiffPixelRatio: 0.01 })`) — never skipped or weakened to unblock a

release.

**A real, dedicated money-RPC test exists, separate from the e2e suite —

worth correcting here since the coverage matrix's own framing implied

there wasn't one.** scripts/test-money-rpcs.mjs, run by

.github/workflows/ci.yml:42-48 (conditional on the TEST_SUPABASE_URL

secret being set — so it runs in CI once that secret exists, and is

skipped gracefully otherwise), asserts directly against create_invoice,

create_quotation, record_payment, and issue_invoice: correct

subtotal/discount/tax/total/amount_due arithmetic, the

discount <= subtotal CHECK rejecting both an RPC call and a direct

UPDATE, Purchase List/Bill independence (convert_quotation_to_invoice

no longer exists, a Purchase List can be created without a customer),

draft-lock triggers rejecting header/item writes on a non-draft

document, and payment edge cases (zero amount, overpayment, exact

final-balance payment, payment against an already-paid invoice). This is

real assert.strict-based coverage of exactly the invariants §3/§7

describe — it just lives outside the Playwright suite, which is why

docs/help/coverage-matrix.md (built by grepping e2e/ and src/, not

scripts/) didn't surface it.

*What is still a real gap, confirmed by this pass:* the v3.0.0

feature set (owner-only Settings gating, invites CRUD, Purchase-List

draft-edit customer, print toggles, WhatsApp share, logout scopes — the

A–K items in docs/plans/v3-state.md) has **no Playwright e2e coverage

at all** yet — docs/plans/v3-state.md's own "M prep" checklist lists

every item as "No e2e yet." e2e/logout.spec.ts exists but

test.skip()s pending a dedicated E2E_LOGOUT_EMAIL/E2E_LOGOUT_PASSWORD

TESTING account that nobody has been able to provision (two attempted

sign-ups both hit Supabase's email rate limit — docs/plans/v3-state.md's

Wave 3 blocker note).

---

10. Known limitations and deferred work

Pulled from docs/STATUS.md's "Remaining work" sections and this pass's

own findings — nothing invented:

  • Production owner-role bootstrap is a manual one-statement SQL step

the account owner must run once per deployment

(docs/onboarding-new-client.md step 4) — deliberately not

auto-guessed (§4).

  • e2e/logout.spec.ts account provisioning is blocked on Supabase's

signup rate limit; the test skips gracefully in the meantime (§9).

  • R2 file storage is not configured. src/lib/files.ts:12:

export const R2_CONFIGURED = false — the public.files metadata

table and its RLS are fully built (§3), but no upload path exists; the

/files page shows a "storage not configured" banner

(docs/help/coverage-matrix.md's Files section) rather than faking an

upload.

  • business.brand_color/business.default_unit are unconsumed.

Both columns exist (20260929090000_v3_business_settings_invites_and_owner_role.sql),

are writable from Business Settings, and round-trip through

src/lib/database.types.ts — but grepping src/ for any reader of

either column outside the settings form itself and the generated types

file finds nothing. They're stored, not yet applied anywhere in the UI.

  • CSP nonce work is backlogged, not missing by accident: public/_headers

uses script-src 'unsafe-inline' because this is a fully static

Cloudflare Pages deployment with no per-request server to mint a nonce,

and Astro/Partytown's own inline bootstrap scripts vary per route/build

— a hash-based CSP would need per-variant hashes that silently break on

any framework version bump. The app's own code has zero XSS sinks

(docs/STATUS.md's security-audit findings), so this is a documented,

reviewed trade-off, not an oversight (docs/STATUS.md lines ~670,

1009, 1293).

  • convert_quotation_to_invoice has zero UI call sites. The RPC was

dropped from the schema entirely in

20260919100000_purchase_list_bill_independence.sql (§3) — there is

nothing left to call. (If this phrase is confusing: an earlier version

of this finding worried the function was dead code; it isn't — it no

longer exists. The only residual reference is scripts/test-money-rpcs.mjs's

own assertion that calling it now fails, which is testing its absence,

not its presence.)

  • **Credential rotation, dashboard-settings verification, and a manual

real-device print check** remain standing items from prior releases,

untouched by v3.0.0/v3.1.0 (docs/STATUS.md's v3.1.0 "Remaining work").

  • quotations.status has no state machine, only a draft/not-draft

lock on the other header columns (§4/§6) — any of the 6 status values

can transition to any other, including back to draft (which

re-enables item edits). This is confirmed-deliberate (no financial

invariant depends on it), but it's worth flagging precisely because

invoices.status is a real, RPC-gated state machine — the asymmetry

is easy to assume is a bug if you only read one of the two tables.

  • invoices.status's overdue and cancelled values are unreachable.

Both are valid per the CHECK constraint and the InvoiceStatus

TypeScript union (src/lib/invoices.ts:8), but no RPC or column grant

ever sets either — isOverdue() (src/lib/invoices.ts:56-62) is a

pure client-side display override that never writes to the database.

Not a bug today (nothing depends on the DB value being accurate), but

dead enum surface worth knowing about before building anything that

assumes status = 'overdue' is ever actually stored.

---

*Diagrams: docs/diagrams/er-diagram.mmd,

docs/diagrams/quotation-invoice-payment-states.mmd,

docs/diagrams/auth-rls-flow.mmd, docs/diagrams/request-lifecycle.mmd,

docs/diagrams/component-tree.mmd, docs/diagrams/deployment-topology.mmd

— all validated by rendering with @mermaid-js/mermaid-cli (see the

commit/report for details).*

Diagrams

Request lifecycle

View source (.mmd)
PostgresSupabase PostgREST + RLSsupabase-js client (src/lib/supabase.ts)queryClient (TanStack Query, module singleton)useBusinessGate()QuotationsPage.tsx (client:load, React rootAppShell.tsx (client:load, React rootAstro page (SSG shell)BrowserPostgresSupabase PostgREST + RLSsupabase-js client (src/lib/supabase.ts)queryClient (TanStack Query, module singleton)useBusinessGate()QuotationsPage.tsx (client:load, React rootAppShell.tsx (client:load, React rootAstro page (SSG shell)BrowserBoth islands import the same queryClient module,so the business-row fetch above happens once per page,not once per island (src/lib/queryClient.tsx).GET /quotationsStatic HTML + two island hydration scripts (build-time SSG)hydrate (client:load)hydrate (client:load, separate React root, same JS module cache)useBusinessGate()auth.getSession()sessionfetchCurrentUserProfile() (queryKey ['profile'])from('profiles').select('*').eq('id', uid)GET /rest/v1/profiles?id=eq.<uid>SELECT ... USING profiles_select_own RLS (auth.uid() = id)profile rowprofile JSONprofile (cached, staleTime 5min)profilegate='ready', businessIduseBusiness() (queryKey ['business'])from('business').select('*').single()GET /rest/v1/business?select=*SELECT ... USING business_select_members RLSbusiness rowbusiness JSONcached business row (shared with Shell's own useBusinessBranding())business (currency, prefixes, branding)listQuotations(businessId, filters, AbortSignal)GET /rest/v1/quotations?business_id=eq....&issue_date=gte...SELECT ... USING quotations_select_members RLS\n(index: quotations_business_id_issue_date_idx)rowsrows JSONQuotationWithCustomer[]render DataTable / mobile cards

Auth & row-level security flow

View source (.mmd)

No

Yes

No

false

true

Yes

no match

match

No

Yes

Yes, caller is member

Yes, caller is owner

No owner check needed

Yes

No

Business-data page loads
(e.g. /customers)

supabase.auth.getSession()
returns a session?

window.location = /login
(useBusinessGate.ts)

fetchCurrentUserProfile()
TanStack Query, cached
RLS: profiles_select_own

profile.business_id set?

business_exists() RPC
(SECURITY DEFINER,
returns boolean only)

/setup: first-run form
initialize_business()
first caller becomes role='owner'

/setup: Join Business screen
join_business() requires a
matching unused unexpired
invite for the caller's email

gate = 'ready', businessId known

Client issues a table query
or RPC (e.g. listCustomers,
create_invoice)

RLS policy:
profiles.business_id = row.business_id
(via EXISTS subquery on every policy)

Zero rows / RLS denies
(fails closed, not an error)

Column-level GRANT allows
the specific column(s) written?

permission denied for column X
(e.g. subtotal, amount_paid, status
on invoices — trigger/RPC-owned only)

Operation requires role='owner'?
(business UPDATE, invites INSERT/
SELECT/DELETE)

RLS denies
(business_update_owner /
invites_*_owner policies)

Operation proceeds

Header/item write on a
quotation or invoice that is
no longer 'draft'?

quotations_lock_after_draft /
invoices_lock_after_draft /
*_items_lock_after_draft
raise an exception

Write succeeds;
trigger-maintained columns
(subtotal/total/amount_due/status)
recompute automatically

Component tree

View source (.mmd)

src/pages/quotations/index.astro
(file-based route, SSG)

BaseLayout.astro
(head, fonts, PWA manifest — static)

AppShellLayout.astro

AppShell.tsx
client:load — React root #1

Sidebar.tsx
useBusinessBranding() -> BusinessLogo.tsx

Header.tsx
fetchCurrentUserProfile(), theme toggle, user menu

(Astro passthrough)

QuotationsPage.tsx
client:load — React root #2
(separate hydration root, shares queryClient module)

useBusinessGate()
(src/lib/useBusinessGate.ts)

useBusiness()
(TanStack Query, src/lib/business.ts)

useDebouncedValue()
(src/lib/useDebounce.ts)

readParamsFromUrl/writeParamsToUrl
(src/lib/useListFilters.ts)

form/Input, form/DatePicker, form/Select
(search box, date-range filter)

ui/Button, ui/Alert

data-table/DataTableSkeleton
data-table/DataTableEmpty
data-table/DataTableError
data-table/DataTablePagination

QuotationTable.tsx
(desktop table, hidden md:block)

QuotationTable.tsx mobile cards
(flex flex-col md:hidden, same component)

Entity-relationship diagram

View source (.mmd)

business_id

business_id

business_id

business_id

business_id

business_id

business_id

business_id

business_id

business_id

business_id

customer_id

customer_id (nullable)

customer_id

customer_id (denormalized)

customer_id (nullable)

job_id (nullable)

job_id (nullable)

job_id (nullable)

quotation_id

quotation_id (nullable)

invoice_id

invoice_id

invoice_id (nullable)

created_by

business

uuid

id

PK

text

name

text

business_type

text

owner_name

text

phone

text

whatsapp

text

email

text

address

text

logo_url

text

gstin

text

currency

text

invoice_prefix

text

quotation_prefix

jsonb

branding

text

brand_color

text

default_unit

boolean

tax_enabled

text

bill_terms

text

purchase_list_terms

boolean

show_signatures

boolean

show_total_in_words

text

signature_customer_label

text

signature_business_label

text

upi_id

text

upi_payee_name

profiles

uuid

id

PK

FK to auth.users

uuid

business_id

FK

nullable

text

full_name

text

role

owner or member, not client-writable

customers

uuid

id

PK

uuid

business_id

FK

text

name

text

phone

text

whatsapp

unused, D1/D8

text

email

text

address

text

notes

text

gstin

boolean

is_archived

jobs

uuid

id

PK

uuid

business_id

FK

uuid

customer_id

FK

text

job_number

unique per business, next_number()

text

title

text

description

text

status

new/scheduled/in_progress/completed/cancelled

text

priority

timestamptz

scheduled_at

timestamptz

completed_at

text

address

text

notes

quotations

uuid

id

PK

uuid

business_id

FK

uuid

customer_id

FK

nullable, D13

uuid

job_id

FK

nullable

text

quotation_number

unique per business

text

status

draft/sent/accepted/rejected/expired/cancelled, label only

date

issue_date

date

valid_until

text

notes

numeric

subtotal

trigger-maintained

numeric

discount

CHECK discount <= subtotal

numeric

tax

numeric

total

CHECK total >= 0, trigger-maintained

boolean

is_archived

invoices

uuid

id

PK

uuid

business_id

FK

uuid

customer_id

FK

not null

uuid

job_id

FK

nullable

text

invoice_number

unique per business

text

status

draft/issued/partially_paid/paid/overdue/cancelled

date

issue_date

date

due_date

text

notes

numeric

subtotal

trigger-maintained

numeric

discount

CHECK discount <= subtotal

numeric

tax

numeric

total

CHECK total >= 0

numeric

amount_paid

only via record_payment()

numeric

amount_due

trigger: total - amount_paid

payments

uuid

id

PK

uuid

business_id

FK

uuid

invoice_id

FK

uuid

customer_id

FK

numeric

amount

CHECK > 0

date

payment_date

text

payment_method

cash/bank_transfer/upi/cheque/other

text

reference

text

notes

expenses

uuid

id

PK

uuid

business_id

FK

text

category

text

description

numeric

amount

CHECK > 0

date

expense_date

text

payment_method

text

notes

files

uuid

id

PK

uuid

business_id

FK

uuid

customer_id

FK

nullable

uuid

job_id

FK

nullable

uuid

quotation_id

FK

nullable

uuid

invoice_id

FK

nullable

text

file_name

text

content_type

bigint

size

CHECK > 0

text

storage_key

R2 object key, not yet wired up

catalog_items

uuid

id

PK

uuid

business_id

FK

text

name

text

item_type

material or service

text

unit

numeric

default_price

nullable, prefill only

boolean

is_active

invites

uuid

id

PK

uuid

business_id

FK

text

email

timestamptz

expires_at

timestamptz

used_at

nullable, single-use

uuid

created_by

FK

profiles.id, owner only

number_counters

uuid

business_id

PK

text

counter_name

PK

job/quotation/invoice

int

next_value

internal only, no client grant

quotation_items

uuid

id

PK

uuid

quotation_id

FK

text

description

numeric

quantity

CHECK > 0

text

unit

numeric

unit_price

CHECK >= 0

numeric

amount

trigger: quantity * unit_price

int

sort_order

invoice_items

uuid

id

PK

uuid

invoice_id

FK

text

description

numeric

quantity

CHECK > 0

text

unit

numeric

unit_price

CHECK >= 0

numeric

amount

trigger: quantity * unit_price

int

sort_order

Purchase List / Bill / payment state machine

View source (.mmd)

Purchase List (quotations.status) — free label, not a gate

Bill (invoices.status) — real, trigger-driven state machine

create_quotation()

plain UPDATE (status column)

plain UPDATE

plain UPDATE

plain UPDATE

plain UPDATE

plain UPDATE (no trigger blocks this)

plain UPDATE (no trigger blocks this)

create_invoice()

issue_invoice() RPC (only path off draft)

record_payment() where 0 < amount_due

record_payment() (further partial)

record_payment() drives amount_due to 0

record_payment() for the full balance in one payment

no conversion to a Bill (D13 — convert_quotation_to_invoice dropped)

draft (header + items editable)

sent

accepted

rejected

expired

cancelled

quotations_lock_after_draft trigger blocks
customer_id/job_id/discount/tax/dates once
old.status <> 'draft'. quotation_items_lock_after_draft
blocks all item writes once status <> 'draft'.
status and notes stay freely editable in either
direction — there is no enforced workflow, only a
draft/not-draft lock on the OTHER columns.

draft (header + items editable)

issued

partially_paid

paid

invoices_lock_after_draft / invoice_items_lock_after_draft
block header/item writes once status <> 'draft'.
invoices_recalculate() trigger derives status from
amount_due on every subtotal/discount/tax/amount_paid
change — status is never set directly by the client
(no column grant on invoices.status at all).
'overdue' and 'cancelled' are valid CHECK values and
TypeScript union members but UNREACHABLE: no RPC or
grant ever sets them. isOverdue() (src/lib/invoices.ts)
is a client-side display override only — it never
writes to the database.

Deployment topology

View source (.mmd)

push/PR

native Git integration
(no workflow file in repo)

supabase-js
PUBLIC_SUPABASE_URL/ANON_KEY

daily cron / workflow_dispatch

SUPABASE_DB_URL (session pooler)

push encrypted .sql.gz.age
via BACKUP_REPO_DEPLOY_KEY

daily cron 03:17 UTC

service-role key,
GET /rest/v1/customers?limit=1

future

Developer / agent
git push to master

GitHub repository
(fuzail-service-desk)

GitHub Actions: ci.yml
lint -> check -> build -> npm audit
+ scripts/test-money-rpcs.mjs
(only if TEST_SUPABASE_URL secret set)

Cloudflare Pages
static Astro build
PUBLIC_SUPABASE_URL / ANON_KEY
per-client env vars

End user's browser
(PWA, offline shell)

Supabase project
(hosted Postgres + Auth + RLS + PostgREST)

GitHub Actions: backup.yml
supabase db dump -> gzip -> age-encrypt

Private backup repo
(fuzail-service-desk-backups)
backups/YYYY-MM-DD/*.sql.gz.age

GitHub Actions:
supabase-keepalive.yml

Cloudflare R2
(planned, NOT wired up —
files.ts R2_CONFIGURED = false)