diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index 0d6eccc..5057361 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -1175,8 +1175,26 @@ Run the five spikes in a day or two on a dev store; write the answers into secti - Allowed optional `fetchFn` in `createRequestListener(options)` for deterministic testing. 3. **Automated Test Coverage:** - Added unit test in `test/server.test.js` verifying `GET /api/auth/callback` sends `expiring: 1` to `https://${shop}/admin/oauth/access_token` and persists the computed `expires` Date in the `Session` table. - - 582 unit tests passing across 132 suites (`npm test`). Zero failures. - - 593 tests across 133 suites in `npm run test:all` (582 passing, 11 skipped live DB integration tests). + - Added unit tests in `test/admin.test.js` verifying the "How to Use" guide tab (`?tab=guide`), storefront menu setup guidance, 3-role breakdown, 5-minute testing checklist, FAQ, and the storefront portal onboarding card on the Practitioners tab. + - 584 unit tests passing across 132 suites (`npm test`). Zero failures. + - 595 tests across 133 suites in `npm run test:all` (584 passing, 11 skipped live DB integration tests). + +--- + +### In-App Usage Guide Tab (`feat/admin-usage-guide-tab`) +1. **Storefront Navigation & Onboarding:** + - Added dedicated "How to Use" tab (`?tab=guide`) to embedded Polaris Admin. + - Direct Storefront Portal Link: `https://${safeShop}/apps/protocols` with one-click clipboard copy (`.copy-portal-btn`) and fallback support. + - Step-by-step merchant setup guide on linking `/apps/protocols` under Shopify Admin → **Online Store → Navigation** (`/admin/menus`). +2. **Three Roles & Complete Workflow Architecture:** + - **Role 1 (Merchant / Store Admin):** Practitioner approvals, practice display names, starter templates, commission & attribution reports, compliance/emergency controls. + - **Role 2 (Practitioner / Provider):** Passwordless 6-digit email OTP login, catalog search, protocol builder (dosages, notes, discounts), client sharing (link, PDF handout, QR code). + - **Role 3 (Client / Shopper):** Personalized protocol landing page, 1-click Add All to Cart, native Shopify Checkout, automated order attribution. +3. **Interactive & Practical Utilities:** + - 5-Minute End-to-End Walkthrough checklist for testing with test gateway. + - Practitioner onboarding callout card on default `Practitioners` tab linking to the guide. + - Comprehensive FAQ answering staff permissions, stock handling, commission payouts, and identity modes. + - Zero-PII barrier preserved, App Bridge token/query preservation on tab links. diff --git a/README.md b/README.md index 6cfb5c4..89661a4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ > **Open-Source (MIT)** | Built for the Shopify Merchant & Developer Community | Open for PRs & Discussions > -> ⚙️ **Status: Complete Engine, Admin & Storefront Modules Verified (582/582 Unit Tests Passing across 132 Suites)** | **Live PostgreSQL Integration (11 integration tests run against a live PostgreSQL instance (they skip with a notice when none is reachable))** | **Live Railway Hosting with Postgres** | **Dev Store Spikes Verified (S2, S3, S4, S5 Answered; S1 Answered on Plus Dev Store Only; S6 Answered on Dev Store)** | **Milestones M9a, M9b-1, M9b-2, M9b-3a & M9b-3b Verified Live on Dev Store** +> ⚙️ **Status: Complete Engine, Admin & Storefront Modules Verified (584/584 Unit Tests Passing across 132 Suites)** | **Live PostgreSQL Integration (11 integration tests run against a live PostgreSQL instance (they skip with a notice when none is reachable))** | **Live Railway Hosting with Postgres** | **Dev Store Spikes Verified (S2, S3, S4, S5 Answered; S1 Answered on Plus Dev Store Only; S6 Answered on Dev Store)** | **Milestones M9a, M9b-1, M9b-2, M9b-3a & M9b-3b Verified Live on Dev Store**

A curated list card of generic unbranded wellness products converging into a single coral QR code link node on deep teal background. @@ -28,7 +28,7 @@ **Privacy by design:** Protocols never accept or store health, medical, or diagnostic data. Browsing shoppers have zero personal information collected or stored. Under an explicit owner decision (dated 2026-11-05), the zero-PII rule is relaxed strictly for an explicit, opt-in "Stay in touch" contact submitted by the shopper on a protocol recommendation page (email, optional first name, timestamp, and verifiable consent text). No protocol, order, or product data is ever linked to the contact. Attribution is tracked solely via aggregate monthly counters. A public privacy policy is served at [`/privacy`](file:///Users/macbook/work/shopify/04-practitioner-protocols/server.js) documenting data handling, explicit consent, compliance webhooks, and sub-processors. -**Current build stage:** The pure engine logic, security controls, cryptographic primitives, Liquid renderers, catalog resolver, rate limiters, validation barriers, and PostgreSQL database queries are fully built and covered by 507 automated unit tests across 111 suites using mock database interfaces. Real PostgreSQL query execution, transaction behavior, constraints, row-level locking (`FOR UPDATE`), and migrations are verified against a live PostgreSQL instance via `npm run test:db` (11 integration tests run against a live PostgreSQL instance, skipping with a notice when none is reachable). The app is deployed live on Railway (`practitioner-protocols-production.up.railway.app`) with internal PostgreSQL and automated migration tracking. Spikes S2 (sitemap exclusion, `noindex`, and proxy header), S3 (hidden line property attribution persistence in storefront checkout and `orders/paid` webhook payload), S4 (20 lines in a single cart batch add), S5 (retail vs B2B pricing), and S6 (storefront predictive search and variant hydration contract; Option A chosen) are verified on live dev store `ai-agent-app-h9qwnwd8.myshopify.com`; Spike S1 is verified on the Plus dev store only. In production mode with `DATABASE_URL` configured, the embedded merchant admin is verified live on the dev store (Milestone M9a; `GET /`, `GET /admin`, `GET /app` served via App Bridge ID tokens and HS256 session verification), including the self-enrolment toggle and pending practitioner review table with customer admin deep links (Milestone M9b-1; verified live on dev store); for Milestone M9b-2, verified live on the dev store: enrol round trip (JSON POST through the App Proxy), pending portal state with requested name, admin pending row with customer deep link, merchant approval, approved portal display, form-encoded and `text/plain;application/json` POSTs returning 415, and unknown action returning 400 (the per-customer rate limit of 5/hr, the pending cap of 200, `customers/redact` profile deletion, and `Sec-Fetch-Site` handling are covered by automated unit tests and were not exercised live); for Milestone M9b-3a (protocol authoring and client page hydration), VERIFIED LIVE on the dev store: editor search with real products and CAD prices, protocol save, share-page hydration, Add all with _protocol_token/_protocol_id/_protocol_usage in the cart, checkout to orders/paid (webhook 200, stat row written), edit round trip (qty and note persisted, token unchanged), list card item count, handout page layout; migration adding nullable `productHandle` to `ProtocolLine`, validation and persistence, client-side predictive search (`/search/suggest.json`) and variant hydration (`/products/.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/.js`, and removal of `createFakeVariantResolver` from the production App Proxy pipeline. Follow-up hotfix loaded protocol lines on portal queries (`json_agg` + `linesCount`) to eliminate edit data loss, removed fake retail total (`$0.00`) from cards to show only item count, and implemented print-friendly handout mode (`?handout=1`) in `renderProtocolLiquid`. Milestone M9b-3b (protocol lifecycle: archive, restore, duplicate-as-template for starters with CSRF, duplicate-from-starter, Rule 4 ownership isolation, in-page confirm UI, and Archived section) is VERIFIED LIVE on the dev store. Remaining NOT-verified live list: logged-out guest view, handoutText/footerDisclaimer rendering, real printing, live cross-owner/cross-shop denial, non-Latin handles (known limitation), discounted-order attribution live, and new CSP inside real admin iframe. Note: the admin attribution report page displayed zeros for live data until a contract mismatch between `getAttributionReport` and `renderAttributionTab` was resolved by unifying `{ month, summary, rows, byPractice, byProtocol }` across the data service, renderer, demo data, and RFC 4180 CSV export with `Intl.NumberFormat` currency formatting. Pre-submission hardening is complete with HMAC-signed OAuth state cookies, public `/privacy` page, `Strict-Transport-Security` on all responses, expanded embedded App Bridge CSP, admin starter catalog product search UX, individual mode settings label, and `.github/CODEOWNERS`. Milestone M11 implements shopper opt-in contact capture (server-defined canonical consent text, dedicated 5/hr rate limiter, case-insensitive email deduplication, RFC 4180 CSV export with `Verified = "no"`) and merchant contact & feedback (`ShopProfile` sync via Admin GraphQL, AES-256-GCM session token encryption at rest, "Contact & feedback" card with 1–5 rating and marketing opt-in checkbox, `scripts/contacts.mjs` and `scripts/stats.mjs`). Under Shopify Managed Installation, authentication uses App Bridge token exchange (RFC 8693) to acquire expiring offline access tokens (1-hour lifetime, `expiring: 1`) without interactive redirects, with encrypted storage at rest via AES-256-GCM, non-PII failure logging, friendly status 200 root page, and fallback legacy OAuth. The app holds a short-lived (1 hour) offline access token, re-acquired on admin load when missing or expiring within 5 minutes, and deleted on uninstallation; no refresh token is stored (fewer secrets at rest) and no separate refresh flow is built because the app makes no Admin API calls outside embedded-admin requests. Covered by 582 automated unit tests across 132 suites. +**Current build stage:** The pure engine logic, security controls, cryptographic primitives, Liquid renderers, catalog resolver, rate limiters, validation barriers, and PostgreSQL database queries are fully built and covered by 507 automated unit tests across 111 suites using mock database interfaces. Real PostgreSQL query execution, transaction behavior, constraints, row-level locking (`FOR UPDATE`), and migrations are verified against a live PostgreSQL instance via `npm run test:db` (11 integration tests run against a live PostgreSQL instance, skipping with a notice when none is reachable). The app is deployed live on Railway (`practitioner-protocols-production.up.railway.app`) with internal PostgreSQL and automated migration tracking. Spikes S2 (sitemap exclusion, `noindex`, and proxy header), S3 (hidden line property attribution persistence in storefront checkout and `orders/paid` webhook payload), S4 (20 lines in a single cart batch add), S5 (retail vs B2B pricing), and S6 (storefront predictive search and variant hydration contract; Option A chosen) are verified on live dev store `ai-agent-app-h9qwnwd8.myshopify.com`; Spike S1 is verified on the Plus dev store only. In production mode with `DATABASE_URL` configured, the embedded merchant admin is verified live on the dev store (Milestone M9a; `GET /`, `GET /admin`, `GET /app` served via App Bridge ID tokens and HS256 session verification), including the self-enrolment toggle and pending practitioner review table with customer admin deep links (Milestone M9b-1; verified live on dev store); for Milestone M9b-2, verified live on the dev store: enrol round trip (JSON POST through the App Proxy), pending portal state with requested name, admin pending row with customer deep link, merchant approval, approved portal display, form-encoded and `text/plain;application/json` POSTs returning 415, and unknown action returning 400 (the per-customer rate limit of 5/hr, the pending cap of 200, `customers/redact` profile deletion, and `Sec-Fetch-Site` handling are covered by automated unit tests and were not exercised live); for Milestone M9b-3a (protocol authoring and client page hydration), VERIFIED LIVE on the dev store: editor search with real products and CAD prices, protocol save, share-page hydration, Add all with _protocol_token/_protocol_id/_protocol_usage in the cart, checkout to orders/paid (webhook 200, stat row written), edit round trip (qty and note persisted, token unchanged), list card item count, handout page layout; migration adding nullable `productHandle` to `ProtocolLine`, validation and persistence, client-side predictive search (`/search/suggest.json`) and variant hydration (`/products/.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/.js`, and removal of `createFakeVariantResolver` from the production App Proxy pipeline. Follow-up hotfix loaded protocol lines on portal queries (`json_agg` + `linesCount`) to eliminate edit data loss, removed fake retail total (`$0.00`) from cards to show only item count, and implemented print-friendly handout mode (`?handout=1`) in `renderProtocolLiquid`. Milestone M9b-3b (protocol lifecycle: archive, restore, duplicate-as-template for starters with CSRF, duplicate-from-starter, Rule 4 ownership isolation, in-page confirm UI, and Archived section) is VERIFIED LIVE on the dev store. Remaining NOT-verified live list: logged-out guest view, handoutText/footerDisclaimer rendering, real printing, live cross-owner/cross-shop denial, non-Latin handles (known limitation), discounted-order attribution live, and new CSP inside real admin iframe. Note: the admin attribution report page displayed zeros for live data until a contract mismatch between `getAttributionReport` and `renderAttributionTab` was resolved by unifying `{ month, summary, rows, byPractice, byProtocol }` across the data service, renderer, demo data, and RFC 4180 CSV export with `Intl.NumberFormat` currency formatting. Pre-submission hardening is complete with HMAC-signed OAuth state cookies, public `/privacy` page, `Strict-Transport-Security` on all responses, expanded embedded App Bridge CSP, admin starter catalog product search UX, individual mode settings label, and `.github/CODEOWNERS`. Milestone M11 implements shopper opt-in contact capture (server-defined canonical consent text, dedicated 5/hr rate limiter, case-insensitive email deduplication, RFC 4180 CSV export with `Verified = "no"`) and merchant contact & feedback (`ShopProfile` sync via Admin GraphQL, AES-256-GCM session token encryption at rest, "Contact & feedback" card with 1–5 rating and marketing opt-in checkbox, `scripts/contacts.mjs` and `scripts/stats.mjs`). Under Shopify Managed Installation, authentication uses App Bridge token exchange (RFC 8693) to acquire expiring offline access tokens (1-hour lifetime, `expiring: 1`) without interactive redirects, with encrypted storage at rest via AES-256-GCM, non-PII failure logging, friendly status 200 root page, and fallback legacy OAuth. The app holds a short-lived (1 hour) offline access token, re-acquired on admin load when missing or expiring within 5 minutes, and deleted on uninstallation; no refresh token is stored (fewer secrets at rest) and no separate refresh flow is built because the app makes no Admin API calls outside embedded-admin requests. Covered by 584 automated unit tests across 132 suites. Includes dedicated "How to Use" guide tab (`?tab=guide`) covering storefront navigation menu setup, 3-role workflows, and 5-minute testing walkthrough. --- diff --git a/app/lib/protocols/admin.js b/app/lib/protocols/admin.js index 5d5f6df..c1bff6c 100644 --- a/app/lib/protocols/admin.js +++ b/app/lib/protocols/admin.js @@ -1411,7 +1411,9 @@ export function renderAdminHtml(options = {}) { if (settings) assertNoPii(settings); const safeShop = escapeAdminText(shop); - const currentTab = ['practitioners', 'starters', 'attribution', 'contacts', 'settings'].includes(activeTab) + const portalUrl = safeShop ? `https://${safeShop}/apps/protocols` : '/apps/protocols'; + const navUrl = safeShop ? `https://${safeShop}/admin/menus` : '#'; + const currentTab = ['practitioners', 'starters', 'attribution', 'contacts', 'settings', 'guide'].includes(activeTab) ? activeTab : 'practitioners'; @@ -1592,6 +1594,65 @@ export function renderAdminHtml(options = {}) { .Polaris-Banner__Dismiss:hover { opacity: 1; } + .Polaris-Step-Number { + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border-radius: 50%; + background: var(--p-color-primary); + color: #ffffff; + font-weight: 700; + font-size: 0.8125rem; + margin-right: 0.75rem; + flex-shrink: 0; + } + .Polaris-Step-Row { + display: flex; + align-items: flex-start; + margin-bottom: 1.15rem; + } + .Polaris-Step-Content { + flex: 1; + } + .Polaris-Step-Title { + font-weight: 600; + font-size: 0.9375rem; + margin: 0 0 0.25rem 0; + } + .Polaris-Step-Desc { + font-size: 0.875rem; + color: var(--p-color-text-subdued); + margin: 0; + line-height: 1.45; + } + .Polaris-Role-Card { + background: #f9fafb; + border: 1px solid var(--p-color-border); + border-radius: 6px; + padding: 1.25rem; + } + .Polaris-Role-Title { + font-size: 1rem; + font-weight: 600; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + .Polaris-Faq-Question { + font-weight: 600; + font-size: 0.9375rem; + margin: 0 0 0.25rem 0; + color: var(--p-color-text); + } + .Polaris-Faq-Answer { + font-size: 0.875rem; + color: var(--p-color-text-subdued); + margin: 0 0 1.25rem 0; + line-height: 1.5; + } `; // Tab 1: Practitioners List @@ -1647,6 +1708,21 @@ export function renderAdminHtml(options = {}) { }).join(''); return ` +

+

Storefront Practitioner Portal

+

+ Practitioners sign in, build client protocols, and manage regimens on your storefront at: +

+
+ ${escapeAdminText(portalUrl)} + + Open Portal → +
+

+ Need help adding this link to your storefront menu or learning the 3 user workflows? + Read the How to Use Guide → +

+

Practitioner Directory & Approvals

Manage approved practitioners and configure practice display names.

@@ -2116,11 +2192,237 @@ export function renderAdminHtml(options = {}) {
`; }; + // Tab 6: How to Use Guide + const renderGuideTab = () => { + return ` + +
+

Storefront Practitioner Portal

+

+ Both practitioners and clients interact with your store through this single App Proxy storefront URL. Practitioners sign in via passwordless email verification, while clients access their personalized protocol regimens. +

+
+ ${escapeAdminText(portalUrl)} + + Open Portal → +
+
+ Tip: You don't need any special backend URL — Shopify securely routes requests from /apps/protocols on your storefront to the app proxy automatically. +
+
+ + +
+

1. Storefront Menu Setup (How Users Find the App)

+

+ When you install Practitioner Protocols, Shopify creates the secure /apps/protocols proxy route, but does not modify your storefront theme header or footer menu automatically. Follow these steps to add a link to your navigation menu: +

+ +
+
1
+
+
Open Shopify Navigation
+

In your Shopify Admin left navigation, click Online Store → Navigation (or click the button below).

+
+
+ +
+
2
+
+
Choose Your Menu
+

Click on Main menu (for header navigation) or Footer menu (for footer links).

+
+
+ +
+
3
+
+
Add Menu Item
+

Click Add menu item at the bottom of the items list.

+
+
+ +
+
4
+
+
Configure Name and Link
+

+ Enter Name: Practitioner Portal (or Client Protocols).
+ Enter Link: /apps/protocols (or the full URL: ${escapeAdminText(portalUrl)}). +

+
+
+ +
+
5
+
+
Save Menu
+

Click Add, then click Save menu. Practitioners and returning clients will now see the portal link in your store navigation!

+
+
+ +
+ + Open Online Store Navigation in Admin → + +
+
+ + +
+

2. How the App Works: Three User Roles

+

+ Practitioner Protocols connects your store with healthcare providers, coaches, and their clients: +

+ +
+ +
+
+ Role 1 + Merchant (Store Owner) +
+

Controls the app from this Admin Dashboard:

+
    +
  • Approve Practitioners: Review registrations in the Practitioners tab and assign professional practice names.
  • +
  • Starter Templates: Publish brand-approved protocol templates in Starter Templates that practitioners can clone.
  • +
  • Attribution & Commission: Track protocol sales, calculate commissions, and download RFC 4180 CSV reports in Attribution & Reports.
  • +
  • Compliance & Settings: Set disclaimer footers, choose Tag or Company identity mode, and manage store policies in Settings.
  • +
+
+ + +
+
+ Role 2 + Practitioner (Provider) +
+

Builds protocols on your storefront portal:

+
    +
  • Passwordless Login: Enters their email on /apps/protocols to receive a 6-digit one-time code (OTP). No passwords to remember.
  • +
  • Search Catalog: Searches all active products directly from your store catalog.
  • +
  • Personalize Regimen: Sets product dosages, instructions, notes, and optional protocol discounts.
  • +
  • Share with Clients: Copies a private protocol link, prints a branded PDF handout, or shares a scannable QR code.
  • +
+
+ + +
+
+ Role 3 + Client / Shopper +
+

Purchases recommended products:

+
    +
  • Dedicated Landing Page: Opens the protocol link to see prescribed items, schedules, and personalized notes under your store branding.
  • +
  • 1-Click Add All to Cart: Adds all recommended products and specified quantities with a single tap.
  • +
  • Native Shopify Checkout: Checks out securely via Shopify Checkout with any protocol bundle discount pre-applied.
  • +
  • Automated Attribution: Cart line-item properties attribute the completed order to the prescribing practitioner.
  • +
+
+
+
+ + +
+

3. Complete Step-by-Step App Walkthrough (All 3 Roles across 4 Acts)

+

+ Follow this 4-act journey to test and experience the entire app lifecycle on your store: +

+ + +
+
+ Act 1 + The Store Owner (Shopify Admin Setup) +
+
    +
  1. Enable Self-Enrolment: Open the Settings tab in this app, ensure "Allow Practitioner Self-Enrolment" is checked, and save settings.
  2. +
  3. (Optional) Curate Starter Templates: In the Starter Templates tab, click Create Starter Template (e.g. "Daily Essentials Stack"). Add products and default directions so practitioners can clone them with one tap.
  4. +
+
+ + +
+
+ Act 2 + The Practitioner (Storefront Portal) +
+
    +
  1. Access Portal: In an incognito / private browser window, navigate to ${escapeAdminText(portalUrl)}.
  2. +
  3. Sign In & Request Access: Enter an email to receive a 6-digit one-time code (OTP). Enter your practice name (e.g. "Holistic Care Clinic") and submit your registration.
  4. +
  5. Merchant Approval: Switch back to this Admin app → Practitioners tab, find the pending registration, and click Approve.
  6. +
  7. Build Protocol: Refresh the portal in your incognito tab to view the active Practitioner Dashboard. Click + Create New Protocol, search products from your store catalog, specify dosages (e.g. "Take 1 capsule twice daily after meals"), and click Save Protocol.
  8. +
  9. Share with Clients: Click Copy Link to get the client URL, or click Print Handout to generate a clean, printable PDF regimen with an automated QR code!
  10. +
+
+ + +
+
+ Act 3 + The Shopper / Client (Seamless 1-Click Purchase) +
+
    +
  1. Open Protocol Link: In a new tab, open the client protocol link. Notice the practitioner's practice header ("Recommended by Holistic Care Clinic") alongside products, pricing, and directions.
  2. +
  3. 1-Click Add All to Cart: Click Add All to Cart. All recommended products are added directly into the Shopify cart in a single batch, tagged with hidden attribution properties (_protocol_token).
  4. +
  5. (Optional) Opt-In: Test the "Stay in touch" box at the bottom of the protocol page by entering an email to opt into updates.
  6. +
  7. Checkout: Complete checkout using Shopify's test gateway (Bogus gateway).
  8. +
+
+ + +
+
+ Act 4 + Sales Attribution & Reports (Back to Merchant Admin) +
+
    +
  1. View Attribution: In this Admin app, open the Attribution & Reports tab. The order count, units sold, and revenue are immediately attributed to the practitioner and protocol!
  2. +
  3. Export CSV: Click Export CSV (RFC 4180) to download a clean financial accounting spreadsheet for commission payouts.
  4. +
  5. Review Contacts: Open the Contacts tab to view shoppers who opted in to stay in touch with their prescribing practitioner.
  6. +
+
+
+ + +
+

4. Frequently Asked Questions

+ +
Do practitioners need a Shopify customer or staff account?
+
+ No! Practitioners authenticate through the storefront portal using passwordless 6-digit email OTPs. They do not require a Shopify staff account, nor do they ever have access to your Shopify admin or backend settings. +
+ +
How are commissions tracked and paid?
+
+ When a client adds items to their cart through a protocol link, hidden cart line-item properties tag the products. When Shopify processes payment, the app webhook attributes the order to the practitioner. You can review commission totals in the Attribution & Reports tab and export an RFC 4180 CSV file to process payouts via PayPal, direct deposit, or your preferred payment method. +
+ +
Can I create brand templates for practitioners to use?
+
+ Yes! Go to the Starter Templates tab to create standard product combinations. Any approved practitioner can clone your starter templates with one click to quickly build regimens for their clients. +
+ +
What happens if a product in a protocol is out of stock?
+
+ The protocol page automatically displays an out-of-stock badge on unavailable items and disables their add-to-cart checkbox, while allowing clients to easily purchase all other in-stock items in the regimen. +
+ +
What is the difference between Tag and Company identity modes?
+
+ In Tag Mode (default), protocols are owned by individual practitioners. In Company Mode, protocols are owned centrally by your store/clinic, ensuring protocols remain accessible even if individual practitioners leave. You can switch this in the Settings & Emergency tab. +
+
+ `; + }; + let tabContent = ''; if (currentTab === 'starters') tabContent = renderStartersTab(); else if (currentTab === 'attribution') tabContent = renderAttributionTab(); else if (currentTab === 'contacts') tabContent = renderContactsTab(); else if (currentTab === 'settings') tabContent = renderSettingsTab(); + else if (currentTab === 'guide') tabContent = renderGuideTab(); else tabContent = renderPractitionersTab(); const appBridgeHead = apiKey @@ -2148,6 +2450,7 @@ ${appBridgeHead} Practitioner Protocols — Admin Attribution & Reports Contacts Settings & Emergency + How to Use
@@ -2169,8 +2472,8 @@ ${appBridgeHead} Practitioner Protocols — Admin return params.get('id_token') || ''; } - // Preserve query params and session token across Polaris tabs - document.querySelectorAll('a.Polaris-Tab').forEach(function(link) { + // Preserve query params and session token across Polaris tabs and in-page guide links + document.querySelectorAll('a.Polaris-Tab, a.Polaris-Tab-Link').forEach(function(link) { link.addEventListener('click', async function(e) { e.preventDefault(); const currentUrl = new URL(window.location.href); @@ -2189,6 +2492,39 @@ ${appBridgeHead} Practitioner Protocols — Admin }); }); + // Copy portal URL button handling + function fallbackCopy(text, btn) { + try { + const tempInput = document.createElement('input'); + tempInput.value = text; + document.body.appendChild(tempInput); + tempInput.select(); + document.execCommand('copy'); + document.body.removeChild(tempInput); + const prev = btn.textContent; + btn.textContent = 'Copied!'; + setTimeout(function() { btn.textContent = prev; }, 2000); + } catch (e) {} + } + + document.querySelectorAll('.copy-portal-btn').forEach(function(btn) { + btn.addEventListener('click', function() { + const url = btn.getAttribute('data-url') || ''; + if (!url) return; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(url).then(function() { + const prev = btn.textContent; + btn.textContent = 'Copied!'; + setTimeout(function() { btn.textContent = prev; }, 2000); + }).catch(function() { + fallbackCopy(url, btn); + }); + } else { + fallbackCopy(url, btn); + } + }); + }); + // Intercept forms document.querySelectorAll('form').forEach(function(form) { form.addEventListener('submit', async function(e) { diff --git a/docs/BUILD_PLAN.md b/docs/BUILD_PLAN.md index c1a6633..c041ade 100644 --- a/docs/BUILD_PLAN.md +++ b/docs/BUILD_PLAN.md @@ -122,7 +122,7 @@ - Lifecycle: `app/uninstalled` deletes the `Session` row while keeping `ShopProfile` with `uninstalledAt` timestamp; `shop/redact` purges all shop records. - UI: Settings opt-in card displays a disabled checkbox with `"Your store contact email is still being loaded. Reload this page."` when `ShopProfile.email` is absent (never displays `"this email"`), and custom request cards prefill `replyEmail` when present. Shopper consent text uses `ShopProfile.shopName` when available. - Friendly root landing page: `GET /` (or `/admin`, `/app`) outside admin iframe with no session serves status 200 HTML with `"Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin's Apps list."`, link to `/privacy`, and zero login or shop domain input fields. - - Automated unit test coverage: 582 passing tests across 132 suites (`npm test`). + - Automated unit test coverage: 584 passing tests across 132 suites (`npm test`). Dedicated "How to Use" guide tab (`?tab=guide`) for storefront menu onboarding and 3-role workflows. ## Later Practitioner application form · aggregate "client orders" count on protocol cards · protocol version history · Salesforce rollup via Bridge Recipes. diff --git a/test/admin.test.js b/test/admin.test.js index 6fd19b0..56bad55 100644 --- a/test/admin.test.js +++ b/test/admin.test.js @@ -1788,6 +1788,75 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { ); } }); + + it('renders How to Use guide tab with 3 roles, menu instructions, test walkthrough, and FAQ', () => { + const html = renderAdminHtml({ + shop: testShop, + activeTab: 'guide' + }); + + // Navigation tab check + assert.ok(html.includes('href="?tab=guide"'), 'Must render guide navigation tab'); + assert.ok(html.includes('Polaris-Tab--selected">How to Use'), 'Must mark guide tab as selected'); + + // Card 1: Storefront Portal Link + assert.ok(html.includes('Storefront Practitioner Portal')); + assert.ok(html.includes(`https://${testShop}/apps/protocols`)); + assert.ok(html.includes('copy-portal-btn')); + assert.ok(html.includes('Open Portal →')); + + // Card 2: Storefront Menu Setup + assert.ok(html.includes('1. Storefront Menu Setup (How Users Find the App)')); + assert.ok(html.includes('Online Store → Navigation')); + assert.ok(html.includes(`https://${testShop}/admin/menus`)); + + // Card 3: 3 User Roles + assert.ok(html.includes('2. How the App Works: Three User Roles')); + assert.ok(html.includes('Role 1')); + assert.ok(html.includes('Merchant (Store Owner)')); + assert.ok(html.includes('Role 2')); + assert.ok(html.includes('Practitioner (Provider)')); + assert.ok(html.includes('Role 3')); + assert.ok(html.includes('Client / Shopper')); + + // Card 4: End-to-End Walkthrough across 4 Acts + assert.ok(html.includes('3. Complete Step-by-Step App Walkthrough (All 3 Roles across 4 Acts)')); + assert.ok(html.includes('Act 1')); + assert.ok(html.includes('The Store Owner (Shopify Admin Setup)')); + assert.ok(html.includes('Act 2')); + assert.ok(html.includes('The Practitioner (Storefront Portal)')); + assert.ok(html.includes('Act 3')); + assert.ok(html.includes('The Shopper / Client (Seamless 1-Click Purchase)')); + assert.ok(html.includes('Act 4')); + assert.ok(html.includes('Sales Attribution & Reports (Back to Merchant Admin)')); + + // Card 5: FAQ + assert.ok(html.includes('4. Frequently Asked Questions')); + assert.ok(html.includes('Do practitioners need a Shopify customer or staff account?')); + assert.ok(html.includes('How are commissions tracked and paid?')); + + // Script syntax verification + const matches = [...html.matchAll(/]*type=["']application\/json["'])>([\s\S]*?)<\/script>/gi)]; + for (let i = 0; i < matches.length; i++) { + assert.doesNotThrow( + () => new vm.Script(matches[i][1]), + `Admin guide script index ${i} must parse without SyntaxError` + ); + } + }); + + it('renders storefront portal onboarding card on the Practitioners tab with quick copy button and link to guide', () => { + const html = renderAdminHtml({ + shop: testShop, + activeTab: 'practitioners' + }); + + assert.ok(html.includes('Storefront Practitioner Portal')); + assert.ok(html.includes(`https://${testShop}/apps/protocols`)); + assert.ok(html.includes('copy-portal-btn')); + assert.ok(html.includes('href="?tab=guide"')); + assert.ok(html.includes('Read the How to Use Guide →')); + }); }); describe('Admin Session Token Verification', () => {