diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index 5057361..79ec129 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -1,6 +1,6 @@ # Practitioner Protocols — Project Context (for Claude) -_Snapshot: 2026-11-05 · Live Railway deployment active (`practitioner-protocols-production.up.railway.app`) with internal Postgres & ledger migrations · Production app record "Practitioner Protocols" released (v2, Public distribution) · Production hardening complete · Milestones M9a, M9b-1, M9b-2, M9b-3a & M9b-3b VERIFIED LIVE on dev store · Milestone M11 (Shopper Opt-In & Merchant Contact Hardening) implemented · Pre-submission hardening complete · Spikes S2, S3, S4, S5, S6 resolved; S1 resolved on the Plus dev store only · Brand assets v2 & v3 produced and verified · 566 tests passing across 123 suites._ +_Snapshot: 2026-11-09 · Live Railway deployment active (`practitioner-protocols-production.up.railway.app`) with internal Postgres & ledger migrations · Production app record "Practitioner Protocols" released (v2, Public distribution) · Production hardening complete · Milestones M9a, M9b-1, M9b-2, M9b-3a & M9b-3b VERIFIED LIVE on dev store · Milestone M11 (Shopper Opt-In & Merchant Contact Hardening) implemented · Pre-submission hardening complete · Spikes S2, S3, S4, S5, S6 resolved; S1 resolved on the Plus dev store only · Brand assets v2 & v3 produced and verified · Demo gaps and accuracy fixes branch (`feat/demo-gaps-and-accuracy-fixes`) implemented with Liquid injection defense and App Bridge resource picker · 588 tests passing across 132 suites._ _Contains NO secrets. Never paste `.env` values or tokens into chat or docs._ ## 1. What this is @@ -51,6 +51,11 @@ The idea grew out of a client request. The owner decided to build their **own, g - Real database-backed admin session-token authentication and UI: Milestone M9a verified live on dev store `ai-agent-app-h9qwnwd8` (embedded `/`, `/admin`, `/app` served with App Bridge session tokens, bootstrap reload, empty states, and cross-shop 403 protection). - Practitioner self-enrolment and portal wiring: Milestones M9b-1 (`allowSelfEnrol` setting, migration, pending review table) and M9b-2 (enrol round trip, pending portal state, admin pending row with customer deep link, approval, approved portal, CSRF 415/400 rejections) verified live on dev store `ai-agent-app-h9qwnwd8`; per-customer rate limit, pending cap, `customers/redact` deletion, and `Sec-Fetch-Site` handling are covered by unit tests and not exercised live. - Milestone M9b-3 (Product search via Option A, authoring creation/updates in PostgreSQL, remove demo fake resolver from production `/api/proxy`): unblocked. +- Live dev store verification of demo gap fixes (`feat/demo-gaps-and-accuracy-fixes`): + - Storefront printable handout with inline SVG QR code (`?handout=1`). + - Browser clipboard copy behavior on protocol and starter template cards (`Copy Link`). + - Embedded Admin native Shopify Resource Picker (`shopify.resourcePicker({ type: 'product' })`) without `read_products` scope. + - Embedded Admin guide deep link to Shopify Admin `Content > Menus` (`/content/menus`). - Add `CODEOWNERS` file (required for the Code Owners rule on `protect-main` branch protection to take effect). - Decision on publishing `v0.1.0` GitHub Release. - App Store listing screenshots (must be real captures of the finished UI, Shopify rule 4.4.4/4.4.5). @@ -1196,6 +1201,52 @@ Run the five spikes in a day or two on a dev store; write the answers into secti - Comprehensive FAQ answering staff permissions, stock handling, commission payouts, and identity modes. - Zero-PII barrier preserved, App Bridge token/query preservation on tab links. +--- + +## 46. Demo Gaps & Accuracy Fixes (`feat/demo-gaps-and-accuracy-fixes`, 2026-11-09) + +Following a full live dev store demo recording, 7 discrepancies between documentation/guide claims and live behavior were identified and resolved in branch `feat/demo-gaps-and-accuracy-fixes`: + +1. **Printable Handout with QR Code (`?handout=1`):** + - Wired `handleAppProxyRequest` for `?handout=1` to invoke `renderHandoutHtml` (from `app/lib/protocols/handout.js`), rendering full practice branding, intro note, item usage notes, shop `handoutText`, footer disclaimer, and inline SVG QR code pointing to the absolute storefront share URL (`https://${shop}/apps/protocols/${token}`). + - Embedded print-specific CSS (@media print, US Letter and A4 page rules, `@page { size: auto; margin: 12mm; }`, page break protections) with user-initiated "Print" button. + - Enforced tenant and ownership isolation: requests for other shops' tokens return 404; inactive protocols return 404. + +2. **Storefront Clipboard Copy ("Copy Link"):** + - Replaced plain `` navigation on protocol cards and starter template cards with JavaScript clipboard copy intercepting clicks (`.copy-link-btn`). + - Uses `navigator.clipboard.writeText` with transparent fallback to hidden textarea `document.execCommand('copy')`. + - Provides momentary visual feedback ("Copied!") before reverting, while preserving valid `href` as fallback for disabled-JS browsers. + +3. **Admin Starter Template Modal & Native Resource Picker:** + - Moved search error notification (`#admin-starter-search-message`) into normal document flow (`display: block; position: static; margin-top: 0.75rem;`), eliminating overlapping of the "Advanced: Enter Variant GID directly" toggle. + - Automatic disclosure: automatically opens `#admin-starter-advanced-fields` whenever search fails or is unavailable. + - State reset: clearing the search input hides the error notice; Cancel and X buttons close the modal and reset all field states. + - Integrated native Shopify App Bridge resource picker via `shopify.resourcePicker({ type: 'product', multiple: true })` with fallback to `app.resourcePicker`. + - Hardened resource picker callback: rejects non-variant product GIDs (`gid://shopify/Product/...`), requires strictly `gid://shopify/ProductVariant/...`, displays in-flow warning if a selected product has no variants, and cleanly handles user cancellation (`undefined`/`null`). + - Verified scope constraint: no new scopes (`read_products`) requested; app scope remains strictly `read_orders`. Note: whether `resourcePicker` works live without `read_products` is explicitly documented as unverified pending live test. + +4. **Neutral Tone & Copy Accuracy (Anti-Health Claims & Commission Removal):** + - Removed all references to "healthcare providers", "patients", "treat", "cure", and health outcome claims across codebase, README, listing copy, and guide. + - Replaced health wording with neutral professional language ("professionals such as stylists, trainers, therapists, clinics"). + - Scrubbed all "commission" and "payout" claims; reworded features accurately to "aggregate attribution reports" and "CSV export of attributed orders by practice and protocol". + +5. **Guide Path & Authentic Flow Alignment:** + - Corrected navigation guidance in admin "How to Use" guide from legacy `Online Store > Navigation` (`/admin/menus`) to modern Shopify Admin `Content > Menus` (`https://admin.shopify.com/store/${shopHandle}/content/menus`). + - Wired deep link button to use App Bridge / `target="_top"` pattern for reliable iframe escape. + - Clarified handout format as print-ready HTML page (browser print or save as PDF) rather than server-generated PDF. + - Accurately documented Shopify Customer Account login flow, including immediate redirection to "Request Practitioner Access" for authenticated returning customers. + +6. **Attribution Currency Clarity:** + - Displayed ISO currency code alongside all monetary figures across KPI cards, attribution tables, and RFC 4180 CSV exports. + - Clarified metric semantics: "Net line-item revenue in store currency, excludes shipping and taxes" (summed from line items attributed to protocol tokens, excluding shipping and order-level taxes). + - Removed redundant currency code from KPI metric label (`Attributed Revenue`), keeping currency code cleanly in the formatted value (`USD 1,253.60`). + +7. **Regression Guard & Security Hardening (Review Follow-up):** + - **Liquid Injection Neutralization (Blocker 1):** Handout HTML rendered under `Content-Type: application/liquid; charset=utf-8` now escapes `{`, `}`, and `%` as `{`, `}`, `%` using shared `escapeHtml` imported from `proxy.js`. Neutralizes all practitioner and merchant dynamic fields (`protocol.name`, `introNote`, line `usageNote`, `practiceName`, `handoutText`, `footerDisclaimer`, `shareUrl`) to prevent template injection through Shopify's Liquid compiler. + - **Standards Mode DOCTYPE Order (Blocker 2):** Removed `` prepended before `` in `routes.js`. Injected `` inside `` in `renderHandoutHtml`, ensuring `{% layout none %}` is followed immediately by standards-mode ``. + - Comprehensive regression tests in `test/handout.test.js`, `test/routes.test.js`, `test/portal.test.js`, and `test/admin.test.js` bringing total passing unit tests to 588 across 132 suites with zero failures. + + diff --git a/app/lib/protocols/admin.js b/app/lib/protocols/admin.js index c1bff6c..5e0dad6 100644 --- a/app/lib/protocols/admin.js +++ b/app/lib/protocols/admin.js @@ -110,7 +110,7 @@ export function formatCurrencyMinor(minorUnits, currency = 'USD', locale = 'en-U const amount = isNaN(val) ? 0 : val / 100; const safeCurrency = (typeof currency === 'string' && currency.length === 3) ? currency.toUpperCase() : 'USD'; try { - return new Intl.NumberFormat(locale, { style: 'currency', currency: safeCurrency }).format(amount); + return new Intl.NumberFormat(locale, { style: 'currency', currency: safeCurrency, currencyDisplay: 'code' }).format(amount); } catch { return `${safeCurrency} ${amount.toFixed(2)}`; } @@ -1412,7 +1412,8 @@ export function renderAdminHtml(options = {}) { const safeShop = escapeAdminText(shop); const portalUrl = safeShop ? `https://${safeShop}/apps/protocols` : '/apps/protocols'; - const navUrl = safeShop ? `https://${safeShop}/admin/menus` : '#'; + const shopHandle = safeShop ? safeShop.replace(/\.myshopify\.com$/, '') : ''; + const navUrl = shopHandle ? `https://admin.shopify.com/store/${shopHandle}/content/menus` : (safeShop ? `https://${safeShop}/admin/menus` : '#'); const currentTab = ['practitioners', 'starters', 'attribution', 'contacts', 'settings', 'guide'].includes(activeTab) ? activeTab : 'practitioners'; @@ -1783,7 +1784,7 @@ export function renderAdminHtml(options = {}) {

Create Brand Starter Template

- +
@@ -1796,12 +1797,14 @@ export function renderAdminHtml(options = {}) {
-
- +
+ +
-
+ +
Advanced: Enter Variant GID directly
@@ -1831,7 +1834,7 @@ export function renderAdminHtml(options = {}) {
- +
@@ -1911,6 +1914,7 @@ export function renderAdminHtml(options = {}) {
${totalRev}
Attributed Revenue
+
Net line-item revenue in store currency, excludes shipping and taxes
${totalOrders}
@@ -1931,7 +1935,7 @@ export function renderAdminHtml(options = {}) { Protocol Orders Units - Revenue + Revenue (${escapeAdminText(currency)}) @@ -1949,7 +1953,7 @@ export function renderAdminHtml(options = {}) { Practice Name Orders Units - Revenue + Revenue (${escapeAdminText(currency)}) @@ -2222,7 +2226,7 @@ export function renderAdminHtml(options = {}) {
1
Open Shopify Navigation
-

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

+

In your Shopify Admin left navigation, click Content → Menus (or Online Store → Navigation on older admin layouts), or click the button below.

@@ -2262,8 +2266,8 @@ export function renderAdminHtml(options = {}) {
- - Open Online Store Navigation in Admin → + + Open Navigation Menus in Admin →
@@ -2272,7 +2276,7 @@ export function renderAdminHtml(options = {}) {

2. How the App Works: Three User Roles

- Practitioner Protocols connects your store with healthcare providers, coaches, and their clients: + Practitioner Protocols connects your store with professionals such as stylists, trainers, therapists, clinics, and specialists, and their clients:

@@ -2286,7 +2290,7 @@ export function renderAdminHtml(options = {}) {
  • 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.
  • +
  • Attribution & Sales Reports: Track attributed protocol sales, orders, and units, and download RFC 4180 CSV attribution reports in Attribution & Reports.
  • Compliance & Settings: Set disclaimer footers, choose Tag or Company identity mode, and manage store policies in Settings.
@@ -2295,14 +2299,14 @@ export function renderAdminHtml(options = {}) {
Role 2 - Practitioner (Provider) + Practitioner (Specialist)

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.
  • +
  • Customer Account Sign-In: Signs in through your store's native Shopify customer account login. A returning signed-in customer goes straight to the portal (or "Request Practitioner Access" to enrol).
  • 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.
  • +
  • Personalize Regimen: Sets product quantities, usage instructions, notes, and curated recommendations.
  • +
  • Share with Clients: Copies a private protocol link, prints a branded print-ready handout page (or saves as PDF), complete with a scannable QR code.
@@ -2314,10 +2318,10 @@ export function renderAdminHtml(options = {}) {

Purchases recommended products:

@@ -2350,10 +2354,10 @@ export function renderAdminHtml(options = {}) {
  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. Sign In & Request Access: Sign in via your store's Shopify customer account. Enter your practice name (e.g. "Alpine Wellness Studio") and submit your practitioner request.
  6. Merchant Approval: Switch back to this Admin app → Practitioners tab, find the pending registration, and click Approve.
  7. -
  8. 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.
  9. -
  10. 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!
  11. +
  12. 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 directions (e.g. "Take 1 capsule twice daily after meals"), and click Save Protocol.
  13. +
  14. Share with Clients: Click Copy Link to copy the client URL to your clipboard, or click Print Handout to open a print-ready regimen complete with an automated QR code!
@@ -2364,7 +2368,7 @@ export function renderAdminHtml(options = {}) { 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. Open Protocol Link: In a new tab, open the client protocol link. Notice the practitioner's practice header ("Recommended by Alpine Wellness Studio") alongside products, pricing, and directions.
  4. 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).
  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. Checkout: Complete checkout using Shopify's test gateway (Bogus gateway).
  7. @@ -2379,7 +2383,7 @@ export function renderAdminHtml(options = {}) {
    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. Export CSV: Click Export CSV (RFC 4180) to download an aggregate attribution report of orders, units, and net retail revenue by practice and protocol.
    6. Review Contacts: Open the Contacts tab to view shoppers who opted in to stay in touch with their prescribing practitioner.
    @@ -2391,12 +2395,12 @@ export function renderAdminHtml(options = {}) {
    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. + Practitioners authenticate through your storefront via standard Shopify customer accounts. 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?
    +
    How is protocol attribution tracked and reported?
    - 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. + 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 recommending practitioner. You can review aggregate sales, orders, and units in the Attribution & Reports tab and export an RFC 4180 CSV file for external accounting and reconciliation.
    Can I create brand templates for practitioners to use?
    @@ -2728,8 +2732,37 @@ ${appBridgeHead} Practitioner Protocols — Admin }); } + function resetStarterModalState() { + if (starterSearchInput) starterSearchInput.value = ''; + if (starterSearchDropdown) { + starterSearchDropdown.style.display = 'none'; + starterSearchDropdown.innerHTML = ''; + } + const msgEl = document.getElementById('admin-starter-search-message'); + if (msgEl) { + msgEl.style.display = 'none'; + msgEl.innerHTML = ''; + } + } + + function closeStarterModal() { + resetStarterModalState(); + const modal = document.getElementById('create-starter-modal'); + if (modal) modal.style.display = 'none'; + } + + document.querySelectorAll('.admin-starter-modal-close').forEach(function(el) { + el.addEventListener('click', closeStarterModal); + }); + function performStarterSearch() { const q = (starterSearchInput ? starterSearchInput.value : '').trim(); + const msgEl = document.getElementById('admin-starter-search-message'); + if (msgEl) { + msgEl.style.display = 'none'; + msgEl.innerHTML = ''; + } + if (q.length < 2 || !starterSearchDropdown) return; starterSearchDropdown.style.display = 'block'; starterSearchDropdown.innerHTML = '
    Searching...
    '; @@ -2777,8 +2810,19 @@ ${appBridgeHead} Practitioner Protocols — Admin }) .catch(function() { if (starterSearchDropdown) { - starterSearchDropdown.style.display = 'block'; - starterSearchDropdown.innerHTML = '
    Storefront catalog search is unavailable from the embedded admin iframe without storefront CORS. Please use the Advanced: Enter Variant GID directly section below to add product variants.
    '; + starterSearchDropdown.style.display = 'none'; + starterSearchDropdown.innerHTML = ''; + } + if (msgEl) { + msgEl.style.display = 'block'; + msgEl.style.background = '#fef3c7'; + msgEl.style.border = '1px solid #fcd34d'; + msgEl.style.color = '#92400e'; + msgEl.innerHTML = 'Storefront catalog search is unavailable from the embedded admin iframe without storefront CORS. Please click Browse Products above to open the native Shopify picker, or use the Advanced: Enter Variant GID directly section below (now opened).'; + } + const advDetails = document.getElementById('admin-starter-advanced-details'); + if (advDetails) { + advDetails.open = true; } }); } @@ -2789,8 +2833,8 @@ ${appBridgeHead} Practitioner Protocols — Admin return; } const vGid = variant.id ? (String(variant.id).startsWith('gid://') ? String(variant.id) : 'gid://shopify/ProductVariant/' + variant.id) : ''; - if (!vGid) { - alert('Invalid variant'); + if (!vGid || !vGid.startsWith('gid://shopify/ProductVariant/')) { + alert('Invalid variant: must be a product variant GID'); return; } if (starterItems.some(function(i) { return i.variantGid === vGid; })) { @@ -2805,8 +2849,7 @@ ${appBridgeHead} Practitioner Protocols — Admin quantity: 1, usageNote: '', }); - if (starterSearchDropdown) starterSearchDropdown.style.display = 'none'; - if (starterSearchInput) starterSearchInput.value = ''; + resetStarterModalState(); updateStarterRows(); } @@ -2825,6 +2868,49 @@ ${appBridgeHead} Practitioner Protocols — Admin }); } + const pickerBtn = document.getElementById('admin-starter-picker-btn'); + if (pickerBtn) { + pickerBtn.addEventListener('click', function() { + if (typeof window !== 'undefined' && window.shopify && typeof window.shopify.resourcePicker === 'function') { + window.shopify.resourcePicker({ type: 'product', multiple: true }).then(function(selected) { + if (selected === undefined || selected === null) return; + const list = Array.isArray(selected) ? selected : (selected && selected.selection ? selected.selection : []); + if (!list.length) return; + list.forEach(function(prod) { + const vars = Array.isArray(prod.variants) ? prod.variants : []; + if (vars.length > 0) { + vars.forEach(function(v) { + addVariantToStarter(prod, v, prod.handle); + }); + } else { + const msgEl = document.getElementById('admin-starter-search-message'); + if (msgEl) { + msgEl.style.display = 'block'; + msgEl.style.background = '#fef3c7'; + msgEl.style.border = '1px solid #fcd34d'; + msgEl.style.color = '#92400e'; + msgEl.textContent = 'This product has no selectable variants'; + } + } + }); + }).catch(function(err) { + console.warn('[resourcePicker] dismissed or error', err); + }); + } else { + const adv = document.getElementById('admin-starter-advanced-details'); + if (adv) adv.open = true; + const msgEl = document.getElementById('admin-starter-search-message'); + if (msgEl) { + msgEl.style.display = 'block'; + msgEl.style.background = '#fef3c7'; + msgEl.style.border = '1px solid #fcd34d'; + msgEl.style.color = '#92400e'; + msgEl.innerHTML = 'Shopify Resource Picker is active when viewed inside Shopify Admin. Please use the Advanced: Enter Variant GID directly section below to add variants.'; + } + } + }); + } + const manualGidInput = document.getElementById('admin-starter-manual-gid'); const manualHandleInput = document.getElementById('admin-starter-manual-handle'); const manualTitleInput = document.getElementById('admin-starter-manual-title'); @@ -2879,6 +2965,18 @@ ${appBridgeHead} Practitioner Protocols — Admin let debounceTimer; starterSearchInput.addEventListener('input', function() { clearTimeout(debounceTimer); + if (!starterSearchInput.value.trim()) { + const msgEl = document.getElementById('admin-starter-search-message'); + if (msgEl) { + msgEl.style.display = 'none'; + msgEl.innerHTML = ''; + } + if (starterSearchDropdown) { + starterSearchDropdown.style.display = 'none'; + starterSearchDropdown.innerHTML = ''; + } + return; + } debounceTimer = setTimeout(performStarterSearch, 300); }); } diff --git a/app/lib/protocols/handout.js b/app/lib/protocols/handout.js index d38fdc4..65bdb0c 100644 --- a/app/lib/protocols/handout.js +++ b/app/lib/protocols/handout.js @@ -1,22 +1,7 @@ import { generateQrSvg } from './qr.js'; +import { escapeHtml } from './proxy.js'; -export { generateQrSvg }; - -/** - * Escapes characters for safe HTML insertion. - * - * @param {unknown} str - * @returns {string} - */ -export function escapeHtml(str) { - if (str === null || str === undefined) return ''; - return String(str) - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} +export { generateQrSvg, escapeHtml }; /** * Builds self-contained, print-ready HTML/CSS for US Letter and A4 handouts. @@ -37,11 +22,13 @@ export function escapeHtml(str) { * }, * practiceName?: string, * shareUrl: string, - * qrSvg?: string + * qrSvg?: string, + * handoutText?: string, + * footerDisclaimer?: string * }} params * @returns {string} Complete HTML document string */ -export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '', qrSvg = '' }) { +export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '', qrSvg = '', handoutText = '', footerDisclaimer = '' }) { if (!protocol || typeof protocol !== 'object') { throw new TypeError('Protocol object is required'); } @@ -50,6 +37,8 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '', const safeTitle = escapeHtml(protocol.name || 'Product Protocol'); const safeIntro = escapeHtml(protocol.introNote || ''); const safeUrl = escapeHtml(shareUrl); + const safeHandoutText = escapeHtml(handoutText ? String(handoutText).trim() : ''); + const safeDisclaimer = escapeHtml(footerDisclaimer ? String(footerDisclaimer).trim() : ''); const activeQrSvg = qrSvg || (shareUrl ? generateQrSvg(shareUrl, { size: 160 }) : ''); const lines = Array.isArray(protocol.lines) ? protocol.lines : []; @@ -80,6 +69,7 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '', + ${safeTitle} — ${safePractice} +
    + +
    +
    ${safePractice}
    @@ -280,6 +314,8 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '',
    ` : ''}
    + ${safeHandoutText ? `
    ${safeHandoutText}
    ` : ''} +
    1

    Scan the QR code or visit the link below to review your practitioner's recommended routine. You can add all items to your cart in one tap.

    @@ -303,6 +339,7 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '',
    Direct Storefront Access:
    ${safeUrl ? `
    ${safeUrl}
    ` : ''}
    Order directly from the official store at standard retail pricing.
    + ${safeDisclaimer ? `
    ${safeDisclaimer}
    ` : ''}
    `; diff --git a/app/lib/protocols/portal.js b/app/lib/protocols/portal.js index 8c4430c..2261859 100644 --- a/app/lib/protocols/portal.js +++ b/app/lib/protocols/portal.js @@ -1,7 +1,7 @@ import { validateProtocolInput, ProtocolValidationError } from './validation.js'; import { canAccessProtocol } from './permissions.js'; import { generateQrSvg } from './qr.js'; -import { renderHandoutHtml, escapeHtml } from './handout.js'; +import { renderHandoutHtml } from './handout.js'; export { ProtocolValidationError }; @@ -771,6 +771,16 @@ function neutralizeLiquid(str) { .replace(/%\}/g, '%}'); } +function basicEscapeHtml(str) { + if (str === null || str === undefined) return ''; + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + /** * Safely HTML-escapes and neutralizes text. * @@ -778,7 +788,7 @@ function neutralizeLiquid(str) { * @returns {string} */ function safePortalText(str) { - return neutralizeLiquid(escapeHtml(str || '')); + return neutralizeLiquid(basicEscapeHtml(str || '')); } /** @@ -1344,6 +1354,7 @@ export function renderPortalLiquid(options = {}) { const protoId = safePortalText(p.id || ''); const items = typeof p.linesCount === 'number' ? p.linesCount : (p.lines?.length || 0); const shareUrl = `/apps/protocols/${token}`; + const absoluteShareUrl = shop ? `https://${shop}/apps/protocols/${token}` : shareUrl; const handoutUrl = `/apps/protocols/${token}?handout=1`; let actionButtons = ''; @@ -1351,7 +1362,7 @@ export function renderPortalLiquid(options = {}) { if (isStarter) { actionButtons = ` - Copy Link + Copy Link Print Handout `; } else if (isArchived) { @@ -1359,7 +1370,7 @@ export function renderPortalLiquid(options = {}) { `; } else { actionButtons = ` - Copy Link + Copy Link Print Handout `; @@ -1753,6 +1764,57 @@ ${protocolsJson} var cancelBtn = document.getElementById('protocol-editor-cancel-btn'); if (cancelBtn) cancelBtn.addEventListener('click', closeEditor); + // Copy Link handlers (copies absolute share URL with fallback and visual feedback) + function copyTextToClipboard(text) { + if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { + return navigator.clipboard.writeText(text); + } + return new Promise(function(resolve, reject) { + try { + var textarea = document.createElement('textarea'); + textarea.value = text; + textarea.setAttribute('readonly', ''); + textarea.style.position = 'fixed'; + textarea.style.left = '-9999px'; + textarea.style.top = '0'; + document.body.appendChild(textarea); + textarea.select(); + var successful = document.execCommand('copy'); + document.body.removeChild(textarea); + if (successful) { + resolve(); + } else { + reject(new Error('execCommand copy failed')); + } + } catch (err) { + reject(err); + } + }); + } + + var copyButtons = document.querySelectorAll('.portal-copy-link-btn'); + copyButtons.forEach(function(btn) { + btn.addEventListener('click', function(e) { + var targetUrl = btn.getAttribute('data-share-url') || btn.getAttribute('href'); + if (!targetUrl) return; + if (targetUrl.indexOf('http://') !== 0 && targetUrl.indexOf('https://') !== 0) { + if (typeof window !== 'undefined' && window.location && window.location.origin) { + targetUrl = window.location.origin + targetUrl; + } + } + e.preventDefault(); + var originalText = btn.textContent; + copyTextToClipboard(targetUrl).then(function() { + btn.textContent = 'Copied!'; + setTimeout(function() { + btn.textContent = originalText; + }, 2000); + }).catch(function() { + window.location.href = btn.getAttribute('href') || targetUrl; + }); + }); + }); + // Edit Protocol handlers var editButtons = document.querySelectorAll('.portal-edit-btn'); editButtons.forEach(function(btn) { diff --git a/app/lib/protocols/routes.js b/app/lib/protocols/routes.js index 388b473..922d8ed 100644 --- a/app/lib/protocols/routes.js +++ b/app/lib/protocols/routes.js @@ -39,6 +39,7 @@ import { } from './catalog.js'; import { generateShareToken } from './token.js'; import { renderPortalLiquid } from './portal.js'; +import { renderHandoutHtml } from './handout.js'; import { ensureOfflineSession } from './exchange.js'; import { saveShopperContact, @@ -1157,15 +1158,46 @@ export async function handleAppProxyRequest(db, request, options = {}) { } } + // If ?handout=1, render the dedicated print-ready handout with QR code + if (isHandout) { + if (!protocol) { + return new Response('Protocol not found', { + status: 404, + headers: { + 'Content-Type': 'text/plain; charset=utf-8', + 'X-Robots-Tag': 'noindex, nofollow' + } + }); + } + + const tokenStr = protocol?.token || token || ''; + const shareUrl = shop && tokenStr ? `https://${shop}/apps/protocols/${encodeURIComponent(tokenStr.trim())}` : ''; + const handoutHtml = renderHandoutHtml({ + protocol, + practiceName: protocol?.practiceName || '', + shareUrl, + handoutText, + footerDisclaimer + }); + + return new Response(`{% layout none %}\n${handoutHtml}`, { + status: 200, + headers: { + 'Content-Type': 'application/liquid; charset=utf-8', + 'X-Robots-Tag': 'noindex, nofollow' + } + }); + } + // 6. Render Liquid template const liquid = renderProtocolLiquid({ protocol, practiceName: protocol?.practiceName || '', shopName: shopDisplayName, - isLoggedInPractitioner: isHandout ? false : isLoggedInPractitioner, - isHandout, - handoutText, - footerDisclaimer + isLoggedInPractitioner, + isHandout: false, + handoutText: '', + footerDisclaimer: '' }); return new Response(liquid, { diff --git a/test/admin.test.js b/test/admin.test.js index 56bad55..84823b4 100644 --- a/test/admin.test.js +++ b/test/admin.test.js @@ -1104,12 +1104,12 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { assert.equal(report.summary.totalOrders, 17); assert.equal(report.summary.totalUnits, 34); assert.equal(report.summary.totalRevenueMinor, 35550); - assert.equal(report.summary.totalRevenueFormatted, '$355.50'); + assert.ok(report.summary.totalRevenueFormatted.includes('355.50') && report.summary.totalRevenueFormatted.includes('USD')); assert.equal(report.byPractice.length, 2); const drSmith = report.byPractice.find(p => p.ownerId === 'gid://shopify/Customer/101'); assert.equal(drSmith.orders, 12); - assert.equal(drSmith.revenueFormatted, '$245.50'); + assert.ok(drSmith.revenueFormatted.includes('245.50') && drSmith.revenueFormatted.includes('USD')); assert.equal(report.byProtocol.length, 2); const starterProto = report.byProtocol.find(p => p.protocolId === 'proto_2'); @@ -1312,7 +1312,7 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { const dashHtml = await dashRes.text(); // Assert real numbers in HTML - assert.ok(dashHtml.includes('$1,921.35'), 'HTML must render formatted revenue $1,921.35'); + assert.ok(dashHtml.includes('1,921.35') && dashHtml.includes('USD'), 'HTML must render formatted revenue 1,921.35 with currency code USD'); assert.ok(dashHtml.includes('Apex Integrative Wellness'), 'HTML must include practice name'); assert.ok(dashHtml.includes('Cellular Restoration Protocol'), 'HTML must include protocol name'); assert.ok(dashHtml.includes('>1<'), 'HTML must show 1 attributed order'); @@ -1478,6 +1478,8 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { assert.ok(html.includes('14')); // total orders assert.ok(html.includes('38')); // total units assert.ok(html.includes('/api/admin/attribution.csv')); + assert.ok(html.includes('
    Attributed Revenue
    '), 'KPI card label must not have duplicate currency'); + assert.ok(!html.includes('
    Attributed Revenue (USD)
    '), 'Duplicate currency code removed from KPI label'); }); it('renders emergency storewide disable button with warning styling in settings tab', () => { @@ -1586,11 +1588,25 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { assert.ok(html.includes('id="admin-starter-search-input"')); assert.ok(html.includes('id="admin-starter-search-btn"')); assert.ok(html.includes('id="admin-starter-search-dropdown"')); + assert.ok(html.includes('id="admin-starter-search-message"'), 'Must have normal-flow search message container'); + assert.ok(html.includes('id="admin-starter-advanced-details"'), 'Must have id on advanced details element'); + assert.ok(html.includes('admin-starter-modal-close'), 'Must have modal close handler class'); + assert.ok(html.includes('id="admin-starter-picker-btn"'), 'Must have product picker button'); assert.ok(html.includes('id="starter-lines-container"')); assert.ok(!html.includes('name="lines[0][variantGid]"')); assert.ok(!html.includes('placeholder="gid://shopify/ProductVariant/...')); }); + it('formats currency minor units with ISO currency code (Item 6)', () => { + const formattedUsd = formatCurrencyMinor(125360, 'USD', 'en-US'); + assert.ok(formattedUsd.includes('1,253.60')); + assert.ok(formattedUsd.includes('USD')); + + const formattedCad = formatCurrencyMinor(177000, 'CAD', 'en-US'); + assert.ok(formattedCad.includes('1,770.00')); + assert.ok(formattedCad.includes('CAD')); + }); + it('renders Individual Mode (Customer Account) option label in settings tab', () => { const html = renderAdminHtml({ shop: testShop, @@ -1807,15 +1823,16 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { // 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`)); + assert.ok(html.includes('Content → Menus')); + assert.ok(html.includes('https://admin.shopify.com/store/brand-store/content/menus')); + assert.ok(html.includes('target="_top"')); // 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('Practitioner (Specialist)')); assert.ok(html.includes('Role 3')); assert.ok(html.includes('Client / Shopper')); @@ -1833,7 +1850,7 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { // 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?')); + assert.ok(html.includes('How is protocol attribution tracked and reported?')); // Script syntax verification const matches = [...html.matchAll(/]*type=["']application\/json["'])>([\s\S]*?)<\/script>/gi)]; diff --git a/test/handout.test.js b/test/handout.test.js index 6a27679..662dd4a 100644 --- a/test/handout.test.js +++ b/test/handout.test.js @@ -86,6 +86,23 @@ describe('Print Handout & QR Generator (app/lib/protocols/handout.js)', () => { assert.ok(html.includes(' { + const shareUrl = 'https://my-brand.myshopify.com/apps/protocols/ghreset2026'; + const html = renderHandoutHtml({ + protocol: mockProtocol, + practiceName: 'Elite Functional Health', + shareUrl, + handoutText: 'Please keep this sheet on your refrigerator.', + footerDisclaimer: 'Custom practitioner guidelines only.' + }); + + assert.ok(html.includes('window.print()'), 'Must contain user-initiated window.print()'); + assert.ok(html.includes('no-print'), 'Must have .no-print utility class'); + assert.ok(html.includes('Please keep this sheet on your refrigerator.'), 'Must render handoutText'); + assert.ok(html.includes('Custom practitioner guidelines only.'), 'Must render footerDisclaimer'); + assert.ok(html.includes(' { const maliciousProtocol = { name: 'Protocol ', @@ -112,6 +129,53 @@ describe('Print Handout & QR Generator (app/lib/protocols/handout.js)', () => { assert.ok(html.includes('<script>evil()</script>')); }); + it('strictly neutralizes Liquid delimiters {{, }}, {% and %} in every dynamic field (Blocker 1 & 2)', () => { + const liquidInjectionProtocol = { + name: 'Protocol {{ shop.name }} {% assign x = 1 %}', + introNote: 'Intro {{ customer.email }} {% for i in (1..3) %}', + lines: [ + { + title: 'Line Title {{ shop.email }}', + variantTitle: 'Variant {% if true %}', + quantity: 2, + usageNote: 'Usage {% assign p = 2 %} {{ shop.currency }}' + } + ] + }; + + const html = renderHandoutHtml({ + protocol: liquidInjectionProtocol, + practiceName: 'Clinic {{ shop.domain }} {% endraw %}', + shareUrl: 'https://example.com/apps/protocols/tok?q={{shop.id}}&tag={%print%}', + handoutText: 'Handout note {{ shop.name }} {% assign a = 1 %}', + footerDisclaimer: 'Disclaimer {{ customer.id }} {% comment %}' + }); + + // Blocker 2: starts with + assert.ok(html.startsWith('')); + assert.ok(html.includes('')); + + // Blocker 1: Strip