# Storefront-to-StudioOS Integration Brief

**Scope:** Read-only inspection of this storefront repository. This brief describes checked-in code and built-in defaults; it does not inspect private/live Firestore documents, confirm the deployed Firestore rules, or validate cPanel environment variables. “StudioOS” integration items below are recommendations, not existing routes or schemas.

## 1. Runtime & Architecture (Namecheap cPanel Node.js)

### Runtime and deployment

- **Startup entry:** cPanel runs [`app.js`](./app.js), which sets `NODE_ENV` to `production` if unset and imports `server.bundle.mjs`.
- **Server/framework:** [`server.ts`](./server.ts) uses Express 5.3. In production it serves the Vite-built `dist/` directory and falls back to `dist/index.html` for SPA routes. It listens on `process.env.PORT` or port `3000`, bound to `0.0.0.0`.
- **Build/start scripts** from [`package.json`](./package.json):
  - `npm start`: `node app.js`
  - `npm run build`: `vite build && esbuild server.ts --platform=node --format=esm --outfile=server.bundle.mjs`
  - `npm run dev`: `tsx server.ts`
  - `npm run lint`: `tsc --noEmit`
- **Frontend:** React 19 + Vite 6. The app uses hash routes (`#sensitive-skincare`, `#page/<slug>`, etc.) in [`src/App.tsx`](./src/App.tsx); it does not select a storefront based on the request hostname. The code contains links to `eczema.ljwellness.net` and `sip.nyalora.com`, but those are external URLs, not host-based routing in this app.
- **cPanel/subdirectory/CORS:** No Passenger-specific configuration, `.htaccess`, or CORS middleware/configuration was found. [`vite.config.ts`](./vite.config.ts) does not set a deployment `base` path. Frontend API calls are same-origin. A subdirectory deployment or subdomain-specific rendering is not configured in the inspected source.

### Environment and Firebase

- The server reads `PORT`, `GEMINI_API_KEY`, `RESEND_API_KEY`, `STUDIO_FROM_EMAIL`, and optional sender overrides `STUDIO_FROM_B2B`, `STUDIO_FROM_ECZEMA`, and `STUDIO_FROM_MENOPAUSE`. `NODE_ENV` also controls development/production behavior.
- There is no `.env.example` and no `dotenv` loading. Configure server-only values through cPanel Node.js environment variables. A local `.exp.local` file is git-ignored by `*.local`; the application does not load it.
- [`firebase-applet-config.json`](./firebase-applet-config.json) is imported by both client and server code. It contains Firebase web-app configuration, including a Firebase API key that is bundled for browser use. That web API key is public client configuration, not a server secret. The inspected Firebase project ID is `gen-lang-client-0026739848` and the Firestore database ID is `ai-studio-ljwellnessvs3-320d9eb8-9b66-4199-b3bc-b4ff49d09c1c`.
- No `VITE_*` secrets or Stripe SDK/API credentials were found in the frontend. Gemini and Resend credentials are read server-side from `process.env`.

### Data storage

- Storefront CMS and lead data use Firebase Firestore through the Firebase client SDK. There is no storefront SQL database, SQLite database, local JSON order store, or server-side order database in this repository.
- Relevant collections include `storeProducts`, `storePages`, `studioSettings/global`, `siteContent/home`, `tradeInquiries`, `collectionLeads`, `contactMessages`, `emailSubscribers`, and `businessAccounts`. The admin app also uses collections for documents, email drafts, CRM records, events, coupons, agent messages, and agent memory.
- The app subscribes to CMS data and writes form submissions from the browser. The Node server does not currently act as the general storefront data API.
- [`firestore.rules`](./firestore.rules) contains collection-level validation and authorization. Its checked-in contents are not evidence that the same rules are currently deployed.

## 2. Complete Product Catalog & SKU Map

**Identifier caveat:** No SKU field is defined in the catalog or `StoreProductRecord`. Built-in `id`/`slug` values are the available code identifiers; do not treat them as manufacturer or StudioOS SKUs. The admin CMS can add or override Firestore product records, and those private live records were not inspected. The tables below describe the checked-in catalog and seed defaults in [`src/data/catalog.ts`](./src/data/catalog.ts) and [`src/data/cmsHelpers.ts`](./src/data/cmsHelpers.ts).

### B2B closing-gift kits

| Code ID (not SKU) | Product / track | Included sizes or units | Code pricing and lead time | Stock / production tracking |
|---|---|---|---|---|
| `residence-welcome` | 01. The Residence Welcome — B2B builder / architect / developer / realtor | 8 oz candle, 6-cube melts, 50 ml hand cream, verification card | $98 CAD/box; 7–10 business days | No stock. Lead time is catalog copy, not a tracked production estimate. |
| `architectural-sanctuary` | 02. The Architectural Sanctuary — B2B | 12 oz + 6 oz candles, tray, 12-cube melts, 100 ml balm, dossier card | $165 CAD/box; 10–14 business days | No stock or batch records. |
| `bespoke-estate` | 03. The Bespoke Estate Box — B2B | Three candles (sizes unspecified), tray/coasters, warmer, 18-cube melts, hand-care set, linen trunk | $245 CAD/box; 14–21 business days | No stock or cure-ready tracking. |

Quote calculator defaults: minimum 5 boxes (10 for Jesmonite color-match option); volume discounts are 5% at 10+, 10% at 20+, 14% at 50+, and 18% at 100+ boxes. Default color-match setup fee is $95. Tier prices and setup fee can be edited in home CMS content. The quoted lead-time text for color matching or the Bespoke Estate tier says 14–21 business days / custom mineral pour and cure; it is not linked to a batch or cure date.

### B2B co-branding add-ons (not separate catalog products)

| Code ID (not SKU) | Add-on | Code price |
|---|---|---:|
| `monogram-linen-band` | Monogrammed Linen Belly Band | +$6/box |
| `embossed-arch-card` | Embossed Architectural Welcome Card | +$4/box |
| `jesmonite-color-match` | Jesmonite Vessel Color Match; 10-box minimum | +$12/box plus setup fee |
| `custom-estate-insert` | Custom Residence Care Dossier | +$5/box |
| `priority-white-glove` | Priority Closing-Date Staging | +$9/box |

The default site content also describes a $55 paid sample box, credited toward a first order of 10+ boxes. Its UI description lists a Jesmonite disc, unscented votive, 600gsm card stock, and barrier balm. It has no catalog SKU or stock record; the inquiry stores only a `requestSampleKit` boolean.

### Eczema / sensitive-skin products and bundles

| Code ID (not SKU) | Product | Format / variants | Code pricing and status |
|---|---|---|---|
| `oat-borage-barrier-balm` | Colloidal Oat & Borage Flare Barrier Balm | 50 ml, 100 ml, 200 ml | $28 / $48 / $82 CAD; base record says “Available Now · Small Batch” |
| `amino-lipid-gentle-wash` | Fragrance-Free Oat Amino Calm Wash | 250 ml, 500 ml | $34 / $58 CAD; base record says “Available Now · Small Batch” |
| `pocket-crease-flare-stick` | Pocket Hand & Crease Shield Stick | 30 g single, 2-pack | $26 / $46 CAD; base record says “Available Now · Small Batch” |
| `microbiome-recovery-mist` | Post-Flare Colloidal Hydro-Calm Mist | 100 ml | $36 CAD; “Upcoming Batch” / placeholder / pre-order wording |
| `unscented-bath-soak` | Silky Colloidal Oat & Marshmallow Bath Soak | 400 g | $32 CAD; “Upcoming Batch” / placeholder / pre-order wording |
| `home-air-safe-melt-set` | Sanctuary Bedroom Unscented Botanical Melts | 12-cube set | $28 CAD; “Upcoming Batch” / placeholder / pre-order wording |
| `calm-barrier-trio` | The Complete Calm Barrier Trio | Three full-size items: 250 ml wash, 100 ml balm, 30 g stick | $96 CAD |
| `daily-reactive-cleanse` | Daily Reactive Wash & Balm Pair | 250 ml wash + 100 ml balm | $74 CAD |
| `travel-flare-shield` | Pocket Flare Shield & Mini Balm Duo | 30 g stick + 50 ml balm | $48 CAD |

The first three products are marked active/available in built-in data; the next three are placeholders. Bundles are seeded active. There are no inventory quantities or per-batch availability fields. Variant prices for the standalone products are in the static catalog; `StoreProductRecord` itself has only one `priceCad` and cannot represent a variant-price list.

### Menopause / botanical-care concepts

| Code ID (not SKU) | Product | Format | Code pricing / status |
|---|---|---|---|
| `peri-cooling-mist` | Thermal Calm Mineral Facial & Neck Mist | 100 ml | No fixed price; seed uses $0 / “Direct Studio Request” |
| `peri-night-candle` | Restorative Dusk Unscented Jesmonite Candle | 10 oz | No fixed price; seed uses $0 / “Direct Studio Request” |
| `meno-night-balm` | Deep Moisture Lipid Renewal Body Butter | 150 ml | No fixed price; seed uses $0 / “Direct Studio Request” |
| `meno-wax-melts` | Sanctuary Unscented Clean Wax Melts | 12-cube set | No fixed price; seed uses $0 / “Direct Studio Request” |
| `post-barrier-elixir` | Cellular Radiance Unscented Facial Elixir | 50 ml | No fixed price; seed uses $0 / “Direct Studio Request” |
| `post-hearth-duo` | Morning Stillness Vessel & Hand Ritual | Jesmonite candle + 100 ml hand balm | No fixed price; seed uses $0 / “Direct Studio Request” |

### Purity-line records

| Code ID (not SKU) | Product | Size | Seed price/status |
|---|---|---|---|
| `pure-hearth-candle` | Unscented Coconut-Soy Architectural Candle | No packaged size; 55+ hour burn claim | $0 / “Purity Verified” |
| `clean-botanical-melts` | Pure Botanical Safe Wax Melts | No size stated | $0 / “Purity Verified” |
| `barrier-hand-balm` | Fragrance-Free Barrier Hand & Body Balm | No size stated | $0 / “Purity Verified” |
| `jesmonite-vessels` | Hand-Cast Mineral Jesmonite Vessels & Trays | No size stated | $0 / “Purity Verified” |

The admin button imports 22 built-in product records (the 6 Eczema products, 3 bundles, 6 menopause concepts, 3 B2B tiers, and 4 Purity lines). The 5 co-branding add-ons are quote options, not product records.

**Readiness warning:** The code’s Eczema catalog says three products are available now, includes prices and “pre-order” copy for other products, and the B2B catalog describes priced kits, components, and lead times. The owner has stated that products and B2B binders have not been manufactured/sourced and Stripe is not set up. These code claims must not be interpreted as verified availability or production data. The Journal’s Oatstraw & Shea product copy supplied in the conversation is not a matching catalog in this repository; the built-in storefront catalog instead uses the names and IDs above.

## 3. Checkout, Quote & Order Flow

### Retail Eczema flow

1. The Eczema product page keeps the bag in React component state (`useState`); it is not persisted as a cart or order.
2. The bag computes a client-side subtotal from the selected item prices and quantities. It displays a $100 CAD free-shipping threshold, but this is presentation logic, not a shipping-rate calculation.
3. Submitting the “order/reservation” form writes a `collectionLeads` document directly from the browser. The item lines and notes are flattened into a string in `skinOrRitualFocus`; no structured order is created.
4. If `studioSettings.stripeEczemaCheckoutUrl` is populated, the page also offers a direct external link. It is not a server-created Checkout Session tied to the cart total, and the storefront does not receive a verified payment result.

### B2B quote and sample flow

1. The quote builder calculates units, tier price, options, volume discount, setup fee, and optional coupon in client code. These are estimates, not server-validated order totals.
2. Submitting writes a `tradeInquiries` document directly to Firestore with `status: "new"`. The owner/admin may update status, notes, and `paymentLinkUrl` later.
3. An optional sample-box link is an external URL in studio settings. It is not an order record or a payment callback. `requestSampleKit` on a quote is only a boolean; the $55 sample amount is not added as a structured line item to the inquiry total.
4. Business account data can include shipping/billing address and a free-text `taxOrResaleNote`. These fields do not drive tax or shipping calculations.

### Payment, tax, shipping, and language

- The app has no Stripe package, server-side Stripe API integration, payment intent/session creation, signed Stripe webhook, or paid-order record. The settings screen accepts optional external HTTPS URLs labeled as Stripe links; the local defaults are blank. The live Firestore values were not inspected. The owner has said payments are not set up.
- No TPS/GST, TVQ/QST, province detection, or tax calculation is implemented. No shipping-rate service or shipping charge is implemented. The Eczema $100 complimentary-shipping threshold is a UI message only. B2B lead-time strings are configurable/static copy, not fulfillment tracking.
- No bilingual checkout/inquiry schema or EN/FR field pair was found. The relevant forms and default product content are English.
- The storefront repository does not contain the separate Eczema Journal app or StudioOS. Its Eczema/menopause routes are storefront pages and external companion links.

## 4. Exact Order & Inquiry JSON Payloads

Source types and write paths: [`src/components/EczemaProductPage.tsx`](./src/components/EczemaProductPage.tsx), [`src/components/TradeQuoteForm.tsx`](./src/components/TradeQuoteForm.tsx), and [`src/types.ts`](./src/types.ts).

### Cart item / line item

The Eczema bag uses this in-memory TypeScript shape. It is not saved as a Firestore order line:

```ts
interface BagItem {
  key: string;
  productId: string;
  name: string;
  variantLabel: string;
  unitPriceCad: number;
  qty: number;
  isPlaceholder: boolean;
  isBundle: boolean;
}
```

There is no SKU, variant ID, currency field, tax, shipping, or production-batch ID on a bag line.

### Completed checkout / paid order

**No completed-checkout or paid-order interface, Firestore collection, Express route, or verified payment webhook exists in the inspected code.** There is therefore no exact paid-order JSON payload to provide.

### B2B quote / sample inquiry

`TradeInquiryRecord` fields are `id` (Firestore document ID added when reading), `ownerUid`, `referenceCode`, `contactName`, `firmName`, `partnerRole`, `email`, `phone`, `selectedTierId`, `estimatedUnits`, `estimatedTotal`, `coBrandingOptions`, `requestSampleKit`, `stagingMode`, `appliedCouponCode`, `discountApplied`, `targetDeliveryWindow`, `notes`, `status`, `adminNotes`, `paymentLinkUrl`, `createdAt`, and `updatedAt`.

The browser’s `addDoc` payload is structurally:

```ts
{
  ownerUid: auth.currentUser?.uid ?? '',
  referenceCode,
  contactName: cleanName,
  firmName: cleanFirm,
  partnerRole: config.partnerRole,
  email: cleanEmail,
  phone: cleanPhone,
  selectedTierId: config.tierId,
  estimatedUnits: Math.max(1, Math.min(5000, Math.round(config.units))),
  estimatedTotal: Number(config.estimatedSubtotal.toFixed(2)),
  coBrandingOptions: config.coBrandingOptions.slice(0, 5),
  requestSampleKit,
  stagingMode, // 'bulk_studio' | 'direct_homeowner' — fulfillment preference, not environment
  appliedCouponCode: config.appliedCouponCode || '',
  discountApplied: Number((config.couponDiscountAmount || 0).toFixed(2)),
  targetDeliveryWindow: cleanWindow || 'Next 30 Days',
  notes: cleanNotes,
  status: 'new',
  adminNotes: '',
  paymentLinkUrl: '',
  createdAt: serverTimestamp(),
  updatedAt: serverTimestamp(),
}
```

`requestSampleKit: true` is the sample-request representation; there is no separate sample inquiry schema. The generated Firestore document ID is not in the submitted object.

### Eczema order-request / collection-lead payload

The Eczema bag form writes a `CollectionLeadRecord`, not an order:

```ts
{
  collection: 'eczema_journal',
  menopausePhase: 'none',
  name: cleanName,
  email: cleanEmail,
  skinOrRitualFocus: serializedFocus, // bag summary and optional notes in one string
  status: 'new',
  adminNotes: '',
  createdAt: serverTimestamp(),
  updatedAt: serverTimestamp(),
}
```

The serialized string contains the bag subtotal and text lines (quantity, product name, variant label, line amount, and a “Pre-Order” marker for placeholders). The browser does not send structured items to Firestore.

### Staging versus production

No `staging.ljwellness.net` hostname check, `isTest`/environment field, or separate staging order schema was found. The `stagingMode` field above means bulk studio delivery versus direct-to-homeowner handover; it does **not** identify staging versus production. The checked-in Firebase config points to one Firebase project/database. The application cannot reliably distinguish test submissions from production submissions based on the current payload.

## 5. Existing Server Routes (`/api/*`)

The routes are defined in [`server.ts`](./server.ts). JSON requests use Express’s 1 MB body limit.

| Method + path | Auth / request | Response and behavior |
|---|---|---|
| `GET /api/health` | Public; no body | `{ "ok": true, "service": "ljwellness-admin-api" }` |
| `POST /api/admin/agent` | `Authorization: Bearer <Firebase ID token>` for a verified admin; JSON body `{ prompt: string, contextSnapshot?: unknown, history?: { role: "user" \| "model"; text: string }[] }` | `{ replyText, functionCalls, groundingSources, modelUsed }`. Errors include `{ error }` and, for model failures, `code` / `modelAttempted`. Calls Google Gemini; optional Google Search grounding is used for live search. Returned function calls are proposed actions, not server-side Firestore writes. |
| `POST /api/admin/send-email` | Same verified-admin Bearer auth; JSON body `{ to: string[], subject: string, bodyText: string, senderLine?: "default" \| "b2b" \| "eczema" \| "menopause" \| "custom", customPrefix?: string }` | Uses server-side Resend when `RESEND_API_KEY` is configured. Success is `{ sentViaServer: true, fromUsed, data }`; without the key, returns `{ sentViaServer: false, fromUsed, reason }`. Errors return `{ error }`. |
| Other `/api/*` paths | No route | JSON 404: `{ "error": "API route not found." }` |

`verifyAdminFromBearer` checks the Firebase ID token, verified email, and admin authorization. Admin Agent function calls are returned to the frontend; [`adminToolExecutor.ts`](./src/components/admin/adminToolExecutor.ts) executes approved CRUD after the inline HITL approval flow, using the Firebase client SDK.

**StudioOS-related routes:** None. No inbound stock/catalog sync endpoint, outbound order/inquiry webhook, generic webhook receiver, `X-Bridge-Key`/HMAC verification, or StudioOS API client was found. Form submissions go directly from browser to Firestore rather than through these Express routes.

## 6. Security & Readiness Checklist for 2-Way Sync

### Confirmed from this codebase

- [x] The Firebase web API key is in client-bundled configuration. It is public Firebase client configuration, not a private service credential. No Gemini, Resend, Stripe secret, or `VITE_*` secret was found in client source.
- [x] Gemini and Resend keys are read from server environment variables. There is no `.env.example`; `.exp.local` is ignored and not loaded by the application.
- [x] There is no StudioOS credential, bridge key, webhook signature, or sync route.
- [x] Firestore permits validated public creates for inquiries/leads/messages/subscribers while limiting reads and later mutations to admins/owners in the checked-in rules. These records contain personal information; `skinOrRitualFocus` may contain sensitive skin/health details.
- [x] `EmailSubscriberRecord` stores a `status` and timestamps but no consent timestamp, policy version, or source metadata. The inspected subscribe write does not persist consent evidence.
- [x] The optional email sender overrides are server environment values, but the code strips line breaks rather than enforcing that override addresses use the verified sender domain. Validate sender domains before configuring those overrides.
- [x] Settings fields described as Stripe links accept HTTPS URLs; they do not prove a Stripe payment or constrain the destination to Stripe.
- [x] No code-level rate limiter or Firebase App Check initialization was found. Firestore rules validate payload shape/size, but public form writes can still be a spam/abuse surface.

### Required work before a 2-way connection

1. **Agree on canonical product identity and data ownership.** Assign real SKUs and define how variants map to a product. Extend the storefront product schema and Firestore validation to represent the agreed SKU, variant, stock/reservation, and batch/cure-ready information. Decide whether StudioOS owns availability/pricing while the storefront CMS owns marketing copy and images. No such fields currently exist.
2. **Resolve product-readiness truth first.** Reconcile the active/placeholder status and price claims in the built-in catalog with the owner’s stated manufacturing and payment status. Do not let a sync turn seeded/static claims into confirmed inventory or sellable offers.
3. **Choose a trusted push path for B2B inquiries.** Browser writes currently bypass Express, so a `X-Bridge-Key` or HMAC secret must never be placed in frontend code. Route submissions through an authenticated server path or use a trusted backend trigger that reads the committed Firestore record. Define the StudioOS endpoint and payload jointly; neither exists in this repository.
4. **Add reliable server-to-server delivery.** Store StudioOS credentials only in cPanel/server secrets. For HMAC, agree on canonical bytes, timestamp, replay window, key rotation, and signature header. Add idempotency, retry/backoff, delivery status/audit records, and a recovery path for failed pushes. Do not push an “order” until an actual order/payment source exists.
5. **Verify payments before calling anything paid.** If retail or sample orders are introduced, implement a payment provider flow and signed webhook verification before creating a paid order or sending it to StudioOS. Current external payment URLs and client-generated totals are not payment verification.
6. **Design the inbound catalog/availability sync.** Add a signed webhook receiver or scheduled server-side pull, then validate and allow-list updates before changing Firestore. Agree on conflict handling, versioning, and whether StudioOS is authoritative for stock, pricing, and cure-ready dates. No inbound or pull mechanism exists now.
7. **Separate staging from production explicitly.** Use intentionally separated environment configuration (including distinct credentials/data stores where appropriate) and a reliable test-order marker. Do not use the current `stagingMode` field or hostname alone as a production/test discriminator.
8. **Minimize shared personal data.** Decide whether StudioOS truly needs customer notes or skin/health-related text. Share only necessary inquiry/order fields, define consent and retention, and restrict access on both sides.

**Practical sequence:** Start with a defined B2B inquiry sync (not “orders”), since `tradeInquiries` is the only structured quote workflow. Next agree on product IDs/SKUs and StudioOS-owned availability/pricing/cure fields. Add a verified paid-order flow only after products are actually ready and payments are configured.
