Resources & Tech · Laboratory Solutions

Two people, or it is not released. One function decides who sees what.

A consumer lab platform has to be right about two things that have nothing to do with e-commerce: who is legally authorised to order a test, and who is allowed to see a result. Both are enforced here as single, centralised functions rather than as checks scattered across surfaces — one release gate that the patient portal and the public share link both consult, and one redaction function that decides what every document shows.

Overview

The engineering record behind ordering authority, chain of custody, result verification and PHI redaction.

Technology stack by layer
LayerWhat runs thereWhy
Front endNext.js 15 App Router, React 19, TypeScript, with route groups splitting marketing, patient portal and staff surfacesRadix primitives wrapped locally, with per-page CSS modules rather than a single utility sheet. Data fetching is plain fetch with component state — no client cache library is present, whatever earlier documentation claimed.
ContentA headless CMS with query-language content fetching for marketing and editorial pagesMarketing content changes on a different cadence from product code, and should not require a deploy.
APINode.js and Express in TypeScript — around seventy route modulesA conventional REST surface; the complexity is in the compliance state machines, not the transport.
DatabaseMySQL via Prisma 6 — a single schema of ninety-plus models and enums, with forty-four migrationsMigrations run as an explicit deploy step rather than implicitly at boot, so a schema change is a decision someone makes rather than a side effect of a restart.
AuthTwo deliberately separate systems — a session-cookie framework for consumers, and a hand-written token layer for staffA patient session and a staff session are different trust levels with different lifetimes. Sharing one mechanism between them invites exactly one bug too many.
PaymentsCard payments and subscriptions on one primary rail, with a second wallet provider and bank linking alongsideAll webhook-verified before any handler runs. Subscription creation is idempotency-keyed at both the provider and the database.
DocumentsHand-drawn PDFs built with a primitives library — no HTML-to-PDF rendererA clinical report is a fixed-layout legal document with pagination rules. Drawing it directly means the layout cannot shift because a font loaded differently.
StorageObject storage under a single enforced key root, with public and private access chosen per file typeCustody photographs are stored privately because a specimen label carries a name and date of birth. That distinction is enforced in the upload path, not left to a bucket policy.
ShippingA fully built carrier integration — shipment creation, rating, tracking, a webhook and status texts, plus a scheduled syncKits move physically, and a patient who does not know where their kit is will call support.
Field encryptionAuthenticated symmetric encryption on payout banking fields specificallyScoped deliberately: this protects payout account details, and the page does not claim it as general encryption of all clinical data.
Deploy gateA deploy script that runs the full backend test suite and aborts on failure, plus a type-error ratchetThe ratchet fails only on new type errors above a committed baseline. That is an honest mechanism for a codebase improving from a real starting point rather than a pass-fail gate nobody can turn on.
Architecture

How the engine actually works

Each section describes a mechanism that exists in the codebase today, not a pattern we admire.

Authority

The legal basis for running a test without a per-patient order

A direct-to-consumer lab needs an answer to a specific question: under what authority is this test being run? The answer is modeled as a standing order — a versioned, dated protocol signed by a licensed physician with their identifier, scoping which panels, categories and states it authorises, valid for an effective window.

Catalog

Two axes, one derived value, and a rule about not editing it

The sellable catalog is a panel, and each panel carries two independent classification axes rather than one product type: how it is fulfilled — no kit, home collection, or mailed kit — and which subscription tier makes it free.

Custody

A kit, its specimens, and every step between

A kit is barcode-identified and moves through a defined status sequence from pending, through activation, collection and transit, to received and processed. It holds one or more specimens, each with its device lot and its stability deadline — because a sample that sat too long is not a result, it is a recollection.

Release

Four eyes, a director's signature, and one function that decides

A result carries two independent lifecycle enums on top of its clinical status: a verification track running from draft through pending verification and verified to released, and a lifecycle track marking it active, discrepant or amended. Both are null for legacy results, which are treated as already deliverable.

Privacy

One function decides who is shown, not what is shown

Redaction is a single documented authority with a profile union — full, no-PHI, share, and two analytics profiles — and one function returning what identity fields each profile may display. Full gets the complete name, full date of birth, record number and accession: the official medical document. No-PHI gets a first name and birth year only. The public share card gets initials. The analytics profiles get no patient identifiers at all.

Reporting

Opt-in per panel, and never by accident

Certain panels report a cleared result onward to an external industry clearance registry. Reporting is opt-in at the panel level, and the documentation is categorical about the two cases: panels that must report, and panels — home kits, general wellness, and community-specific panels — that must never.

Locations

Bookable and visible are different flags

A partner or company-operated draw site carries hours, coordinates, a timezone, capacity, and two deliberately independent flags: whether it is active, and whether it appears in the public locations menu.

Data model

The records underneath, and the rules that hold them true

Core entities and their invariants
EntityWhat it holdsRule that always holds
TestPanelThe sellable catalog product, referencing the assays it contains, with its fulfilment axis, subscription coverage and registry-reporting flag.The derived order-type fields must be re-derived from the two source axes, never hand-edited — stated in the schema comment and enforced by a backfill.
LabTestThe individual assay definition — criticality, whether it blocks clearance, and which report variants display it.The older free-text code field is deprecated in favour of standard coding fields.
TestResultThe result plus its whole compliance lifecycle — verification status, lifecycle status, ordering authority, director-signoff requirement, critical flag and amendment history.Null lifecycle values mean a legacy result treated as deliverable. Deliverability is decided by one shared module, never by a per-surface filter.
StandingOrderThe physician-signed authorization protocol, scoped by panel, category or state, with an effective window and the signed document retained.Renewal lineage links each version to the one it replaced, so authority has a history rather than a current value.
Kit · SpecimenThe physical collection kit and the samples within it, each carrying a device lot and a stability deadline.One kit maps to one order. A specimen belongs to exactly one kit.
CustodyEventThe append-only custody log — step, actor, role, photograph, barcode and notes.Recording is restricted at the router by role, because the service beneath applies no ownership scoping of its own.
PublicHealthReportA filing record opened automatically for reportable positives, tracked against its deadline.Unique per result and organism, so a re-release cannot duplicate a filing.
ResultShareThe public, revocable, expiring token behind a QR share link.Stores no patient identity — the redaction profile for this surface shows initials only.
PerformerResultShareInternal person-to-person or person-to-agency sharing, in one-time or continuous mode.Deliberately a separate model from the public share token, with different lifetime and revocation semantics.
Location · ProductAvailabilityA draw site and the per-panel bookability at it, with a slot template.Public menu visibility is independent of whether a site is active and bookable. Availability is unique per panel and location.
AdminUser · AdminUserRoleStaff identity with a many-to-many role assignment, including a distinct laboratory director role.Access is granted when the user is a super administrator or holds any required role — the director role gates the co-sign endpoint specifically.
AuditLogStaff-action audit trail carrying the action, resource, and before and after values.Written on every verification, release, critical acknowledgement, director sign-off and discrepancy mark.
Interfaces

What it exchanges, and in which direction

Optional integrations degrade gracefully: with no key configured the product still runs, it just does less.

Card payments and subscriptions

Bidirectional

The primary rail, with signature-verified webhooks across a dozen event types. Subscription creation is idempotency-keyed at the provider, and the database write is an upsert on the subscription identifier — belt and braces against a double submit.

Second payment provider

Bidirectional

A fully routed parallel integration including order creation, capture, cancellation, webhook and abandoned-order cleanup.

Bank account linking

Inbound

Used for payout-adjacent flows rather than consumer checkout.

Carrier shipping

Bidirectional

Shipment creation, rate calculation, tracking, a webhook and status text messages, plus a scheduled sync so a stalled tracking update does not go unnoticed.

External clearance registry

Outbound

An automated push for opted-in panels only. Worth being precise: this is a session-based integration against the registry's own web flow, not a documented API partnership, and the page does not present it as one.

Email and SMS

Outbound

Transactional email with inline branding, and messaging for one-time codes and tracking updates. Email degrades to a simulated send when no key is configured.

Object storage

Bidirectional

One enforced key root with per-function subdirectories, and access level chosen per file — private for anything carrying identity.

Product analytics

Outbound

Loaded client-side only when a key is configured, with a PHI strip applied to every event property before capture. Instrumented for page views.

Security

How access is decided and recorded

One release gate
A single module decides deliverability, consumed identically by the authenticated portal and the unauthenticated share endpoint. Staff bypass it explicitly to review pre-release results.
Four eyes
Verification, release and director sign-off each refuse when the acting administrator is the one who uploaded the result. Three separate checks, one principle.
Director co-sign
A distinct role gates the statutory co-sign on flagged results, with its own distinct-signer requirement. It is a role in the model, not a checkbox in a form.
One redaction authority
A single function and an explicit profile type decide which identity fields each surface and each document variant may show. The PDF generator consumes it directly rather than reimplementing the rules.
Custody access
Raw custody recording is restricted to staff roles at the router, with the reason documented in place — the service beneath does no ownership scoping.
Separate auth surfaces
Consumer sessions and staff sessions run on two different mechanisms, so a token from one cannot authenticate against the other.
Payout field encryption
Authenticated symmetric encryption on banking fields specifically, with a tolerant decrypt path during migration from plaintext.
Webhook verification
Payment webhooks verify the provider signature against the raw body before any handler runs, rejecting outright on failure.
Configuration discipline
A required-versus-optional environment helper makes missing critical configuration fail fast at boot, while optional integrations degrade explicitly. No inline fallback values.
Compliance posture
Designed for HIPAA obligations under a BAA. Results carry a laboratory's certification number and director name on the report footer, drawn from the laboratory record rather than typed into a template.

Infrastructure is designed for HIPAA obligations under a BAA. We document the controls and hand over the runbooks; we do not claim a certification that does not exist for software.

Reliability

What keeps it correct under load

Idempotency at two layers
Subscription creation is keyed at the payment provider and upserted in the database on the provider's identifier, so neither a double click nor a webhook replay creates two subscriptions.
Idempotent public-health filings
Unique per result and organism with a no-op update, so re-releasing a result cannot open a second filing.
Retry by design, not by queue
The payment webhook relies on the provider's own redelivery on a non-success response, and the idempotent write means a partially processed first delivery self-heals. Simpler than a bespoke retry queue, and stated as the deliberate choice it is.
Rate limiting where it costs money
Alongside broad and authentication limiters, a per-user limiter caps document-extraction calls specifically, because that path spends third-party budget per request.
Explicit migration step
Schema migrations run as a deploy step rather than at application boot, so a restart never silently alters the schema.
Test gate on deploy
The deploy script runs the full backend suite and aborts on any failure, bypassable only through an explicit and loudly logged override.
A type-error ratchet
Rather than a pass-fail type gate nobody could switch on, the deploy compares against a committed per-workspace baseline and fails only on new errors — one workspace has already reached a full strict gate this way.
Redaction verified, not assumed
Report tooling includes an independent checker that opens the built artifacts, extracts every embedded image and confirms each declared redaction region is actually filled, with a control test proving the check can still fail.
Development record

The documents this was built from

Analysis, design discussion, implementation notes and QA written while the work happened. These are engineering artifacts in the product repository, not published pages — listed here so you can see what exists and ask for any of it.

Development-time documentation for Laboratory Solutions
DocumentKindDateWhat it covers
Result workflow — the engineering designdocs/reports/2026-06-22-result-workflow-FOR-PROGRAMMERS.htmlDesign2026-06-22The target architecture for the two-person verify-and-release gate, the audit trail, and amendment and recall handling. This is the document the release module was built from, and the code matches it.
Result handling guidelinedocs/reports/2026-06-22-result-handling-GUIDELINE.htmlReference2026-06-22The formal bilingual scope, conditions and required report elements for manual result handling.
Manual result compliance gap analysis and plandocs/reports/2026-06-22-manual-result-compliance-gap.html · -implementation-plan.htmlAnalysis2026-06-22Standard-operating-procedure requirements mapped against the actual editing workflow and report output, and the plan that closed the differences across schema, API, form, document and delivery.
Ordering authority feature recorddocs/reports/2026-06-24-wp9-standing-orders.htmlImplementation2026-06-24The standing-order work package end to end — schema, routes, administrative page and the release gate — corroborating the model and lookup verified directly in code.
Order-processing compliance audit and implementationdocs/reports/2026-06-25-order-processing-standing-order-audit.html · -compliance-implementation.htmlAnalysis2026-06-25A verification of the clinical order pipeline against the actual codebase across all order types, and the implementation report closing what it found — workflow automation, director co-sign, consent and public-health reporting.
End-to-end compliance pipeline testdocs/reports/2026-06-25-e2e-compliance-pipeline.htmlQA2026-06-25A full run of the pipeline against the live environment: order, positive result, release blocked, director sign-off, release, and public-health filing.
Redaction explainerdocs/clear-nophi-redaction-EN.html · -KO.htmlReference2026-06-07A bilingual explanation that the no-PHI variant redacts identifiers rather than hiding analytes — the same distinction the redaction function implements.
Registry reporting guide and relationship mapdocs/PASS_REPORTING_GUIDE.html · docs/PASS_CERTIFICATION_RELATIONSHIP.htmlReference2026-06-16What decides whether a result is reported onward, what the patient sees on their report, and the relationship map behind it — modelled directly from the schema.
Consumer order processingdocs/CONSUMER_ORDER_PROCESSING.md · docs/consumer-order-processing.htmlReference2026-06-16The canonical checkout flow for each direct-to-patient order type, in plain and styled form.
Incident analysis — discordant result and recalldocs/reports/2026-06-22-incident-response-discordant-recall.htmlAnalysis2026-06-22A worked analysis of a result reversal and a multi-patient recall scenario drawn from legacy data, written to inform how the current system handles both.
QA method playbookdocs/qa/METHOD.mdReferenceThe single source of truth for how a QA round is run — discover, smoke, probe, dig, fix, re-verify — with a canonical findings schema and severity definitions used across every round.
QA campaign historydocs/qa/HISTORY.mdQA2026-06-09 to 2026-08-01A chronological log of the whole QA campaign, one entry per phase across authorization rounds, acceptance rounds, console sweeps, performance and integrity work, each linking to its own findings folder.
Production QA rounds with a data ledgerdocs/qa/fulltest-2026080*/QA2026-08-01 to 2026-08-05Multi-agent rounds run against production under explicit rules of engagement, each carrying a ledger of every row written during testing and how it was reverted — the discipline that makes testing against production defensible rather than reckless.
Document subsystem auditdocs/qa/pdf-20260805/FINDINGS.mdQA2026-08-05A full audit of every document the platform generates, covering gating, completeness of long reports, and audit coverage on downloads.
Type-check ratchetdocs/ci/typecheck-ratchet.mdRunbookHow the deploy gate works — the full backend suite as a hard gate, and the type-error ratchet measured against a committed per-workspace baseline.
Legacy import history and cleanup runbooksdocs/migrations/legacy-import-history.md · docs/IMPORT_CLEANUP.md · docs/DNS_FLIP.md · docs/WIX_RETIREMENT.mdMigrationA watermarked record of every legacy import run with its paired scripts, plus the cutover and retirement runbooks from the previous platform.
Design systems — consumer and managerDESIGN.md · docs/design-theme-showcase.html · docs/MANAGER_DESIGN_SYSTEM.md · docs/ADMIN_DESIGN_SYSTEM.htmlDesign2026-06-11 to 2026-06-16Locked token and component references for the consumer surfaces and, separately, for the staff console.
Glossary

Terms used on this page

Panel
The sellable product — a set of assays sold together, classified by how it is fulfilled and which membership covers it.
Assay
An individual test within a panel, with its own criticality and reporting rules.
Standing order
A physician-signed, versioned protocol pre-authorising a scope of tests, standing in for a per-patient order.
Ordering authority
The legal basis under which a laboratory may run a test — stamped onto the result at release.
Four-eyes gate
The rule that whoever verifies or releases a result must not be whoever entered it.
Director sign-off
A statutory co-signature by a laboratory director required before certain results may be released.
Verification status
The track a result moves along from draft through verified to released.
Lifecycle status
Whether a result is active, on a discrepancy hold, or amended after release.
Discrepant
A hold state that blocks delivery until a human clears it.
Amended
A previously released result that was corrected, with prior versions retained.
Critical value
A result requiring explicit acknowledgement before it can be released.
Chain of custody
The append-only log tracking a kit and its specimens through defined steps from collection to the laboratory.
Stability deadline
The point after which a specimen is no longer valid to run — a recollection, not a result.
Full report
The official document variant carrying complete identity — name, date of birth, record number and accession.
No-PHI report
The shareable variant showing the same analytes with identifiers redacted to a first name and birth year.
Redaction profile
The named policy deciding which identity fields a given surface or document may display.
Share token
A public, revocable, expiring link to one result, showing initials only.
Public-health filing
The record opened automatically for a reportable positive, tracked against its filing deadline.
Accession
The laboratory's own identifier for a received specimen, printed on the official report.
Ratchet
A gate that compares against a committed baseline and fails only on regression, used to improve a codebase without blocking it.
Questions

Asked by the people who evaluate this

Why does one function decide what a patient can see?

Because the alternative has a specific failure mode. When the portal and the public share link each write their own filter, they drift, and the drift shows up as a result correctly blocked in one place and visible in the other. Here both surfaces call the same two functions, so 'released' means one thing everywhere. Staff bypass it explicitly, which is a visible decision rather than a gap.

What does the four-eyes rule actually prevent?

A single person entering a result and releasing it without anyone else reading it. It is enforced at three separate points — verify, release and director sign-off — and each refuses when the acting user is the one who uploaded. That is a workflow control, not a UI convention, so it cannot be skipped by using a different screen.

Is 'no PHI' the same as hiding results?

No, and conflating the two is the common mistake. The shareable variant shows the same analytes; what it removes is the identity — full name, record number, full date of birth. The project's own explainer makes that distinction explicitly, and the redaction function implements it, so both documents are generated from one policy rather than two templates that might diverge.

How do you know a result is not reported to a registry by accident?

Because reporting is opt-in per panel and the documentation is categorical about which panels must never report. A registry push is effectively irreversible, so the default has to be off. Naming the integration honestly matters too: it runs against the registry's own web flow rather than a documented API partnership, and this page does not claim otherwise.

You test against production. Is that safe?

It is defensible only with discipline, which is why every production round carries a data ledger recording each row created during testing and how it was reverted, alongside written rules of engagement. Report tooling also runs an independent pixel-level check that every declared redaction in a shared document is actually filled, with a control test proving the check can still fail.