diff --git a/app/lib/protocols/handout.js b/app/lib/protocols/handout.js index 65bdb0c..0c459a0 100644 --- a/app/lib/protocols/handout.js +++ b/app/lib/protocols/handout.js @@ -1,7 +1,7 @@ import { generateQrSvg } from './qr.js'; -import { escapeHtml } from './proxy.js'; +import { escapeHtml, normalizeVariantId } from './proxy.js'; -export { generateQrSvg, escapeHtml }; +export { generateQrSvg, escapeHtml, normalizeVariantId }; /** * Builds self-contained, print-ready HTML/CSS for US Letter and A4 handouts. @@ -44,19 +44,47 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '', const lines = Array.isArray(protocol.lines) ? protocol.lines : []; const linesMarkup = lines.map((line, idx) => { - const itemTitle = escapeHtml( - line.title || - line.productTitle || - (line.variantTitle ? `Product (${line.variantTitle})` : `Item ${idx + 1}`) - ); + const rawVariant = line.variantGid || line.variantId || line.id || ''; + const normVariantId = normalizeVariantId(rawVariant); + const productHandle = line.productHandle ? String(line.productHandle).trim() : ''; + + const isEnriched = Boolean(line.title || line.productTitle || line.name); + const hasHandle = Boolean(productHandle); + const isMissingProduct = !isEnriched && !hasHandle; + const isAvailable = !isMissingProduct && line.available !== false && line.inStock !== false && line.isDeleted !== true; + + let itemTitle = 'Unavailable product'; + if (line.title) { + itemTitle = line.title; + } else if (line.productTitle) { + const vTitle = line.variantTitle && line.variantTitle !== 'Default Title' ? ` - ${line.variantTitle}` : ''; + itemTitle = `${line.productTitle}${vTitle}`; + } else if (line.name) { + itemTitle = line.name; + } else if (line.variantTitle && line.variantTitle !== 'Default Title') { + itemTitle = `Product (${line.variantTitle})`; + } else if (hasHandle) { + itemTitle = 'Loading product...'; + } else { + itemTitle = 'Unavailable product'; + } + const qty = Number.isInteger(line.quantity) && line.quantity >= 1 ? line.quantity : 1; const usage = line.usageNote ? escapeHtml(line.usageNote) : ''; + const statusBadge = isMissingProduct + ? `
Unavailable product
` + : (!isAvailable ? `
Out of stock
` : ''); + return ` - + ${idx + 1} -
${itemTitle}
+
${escapeHtml(itemTitle)}
+ ${statusBadge} ${usage ? `
${usage}
` : ''} ${qty} @@ -202,6 +230,28 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '', margin-top: 3px; font-style: italic; } + .line-row-unavailable { + opacity: 0.65; + } + .line-row-unavailable .item-title { + text-decoration: line-through; + color: #6b7280; + } + .handout-badge-unavailable { + display: inline-block; + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + padding: 2px 6px; + border-radius: 4px; + background: #fee2e2; + color: #991b1b; + margin-top: 3px; + } + .item-status { + margin-top: 2px; + } .instructions-box { border: 1px dashed #d1d5db; background-color: #fafafa; @@ -298,7 +348,7 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '',
- +
@@ -341,6 +391,148 @@ export function renderHandoutHtml({ protocol, practiceName = '', shareUrl = '',
Order directly from the official store at standard retail pricing.
${safeDisclaimer ? `
${safeDisclaimer}
` : ''}
+ + `; } diff --git a/app/lib/protocols/routes.js b/app/lib/protocols/routes.js index 922d8ed..bb7ad7b 100644 --- a/app/lib/protocols/routes.js +++ b/app/lib/protocols/routes.js @@ -870,8 +870,20 @@ export async function handleAppProxyRequest(db, request, options = {}) { ); } + const isHandout = urlObj.searchParams.get('handout') === '1'; + // 4. If no token provided on App Proxy root (/apps/protocols), render Practitioner Portal (M3 / M9b-2) if (!token) { + if (isHandout) { + return new Response('Protocol not found', { + status: 404, + headers: { + 'Content-Type': 'text/plain; charset=utf-8', + 'X-Robots-Tag': 'noindex, nofollow' + } + }); + } + if (method === 'GET' && action === 'contacts_csv') { if (!customerGid) { return Response.json( @@ -1133,7 +1145,6 @@ export async function handleAppProxyRequest(db, request, options = {}) { } } - const isHandout = urlObj.searchParams.get('handout') === '1'; let handoutText = ''; let footerDisclaimer = ''; if (isHandout && shop && db) { diff --git a/test/handout.test.js b/test/handout.test.js index 662dd4a..0049ee6 100644 --- a/test/handout.test.js +++ b/test/handout.test.js @@ -96,13 +96,39 @@ describe('Print Handout & QR Generator (app/lib/protocols/handout.js)', () => { footerDisclaimer: 'Custom practitioner guidelines only.' }); - assert.ok(html.includes('window.print()'), 'Must contain user-initiated window.print()'); + assert.ok(!html.includes('onclick='), 'Print button must have no inline onclick handler'); + assert.ok(html.includes('')); + const printCallSites = html.match(/window\.print\s*\(/g) || []; + assert.equal(printCallSites.length, 1, 'Must contain exactly one window.print( call site'); 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 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('onclick='), 'Rendered Print button must have no inline onclick attribute'); + assert.ok(html.includes('')); + + const printMatches = html.match(/window\.print\s*\(/g) || []; + assert.equal(printMatches.length, 1, 'Output must contain exactly one window.print( call site'); + + // Zero unescaped Liquid delimiters {{ or {% anywhere in entire document (including inside script) + assert.ok(!html.includes('{{'), 'Document must contain no {{ anywhere'); + assert.ok(!html.includes('}}'), 'Document must contain no }} anywhere'); + assert.ok(!html.includes('{%'), 'Document must contain no {% anywhere'); + assert.ok(!html.includes('%}'), 'Document must contain no %} anywhere'); + }); + it('escapes untrusted content in protocol and practice name', () => { const maliciousProtocol = { name: 'Protocol ', @@ -162,6 +188,10 @@ describe('Print Handout & QR Generator (app/lib/protocols/handout.js)', () => { assert.ok(!bodyWithoutStyle.includes('{%'), 'Handout must contain zero {% outside style block'); assert.ok(!bodyWithoutStyle.includes('%}'), 'Handout must contain zero %} outside style block'); + // Assert zero unescaped Liquid delimiters in the entire document (including inside script) + assert.ok(!html.includes('{{'), 'Handout must contain zero {{ anywhere including inside script'); + assert.ok(!html.includes('{%'), 'Handout must contain zero {% anywhere including inside script'); + // Assert literal characters appear as escaped entities assert.ok(html.includes('{{ shop.name }}')); assert.ok(html.includes('{% assign x = 1 %}')); @@ -176,6 +206,81 @@ describe('Print Handout & QR Generator (app/lib/protocols/handout.js)', () => { assert.ok(html.includes('{{ customer.id }}')); }); + it('falls back to "Unavailable product" instead of "Item 1" for genuinely unresolvable lines', () => { + const unresolvableProto = { + name: 'Mystery Regimen', + lines: [ + { + quantity: 1, + usageNote: 'Take once daily' + } + ] + }; + + const html = renderHandoutHtml({ + protocol: unresolvableProto, + practiceName: 'Wellness Center', + shareUrl: 'https://example.com/apps/protocols/tok_test' + }); + + assert.ok(!html.includes('Item 1'), 'Must not render "Item 1" fallback'); + assert.ok(html.includes('Unavailable product'), 'Must render "Unavailable product" fallback'); + assert.ok(html.includes('line-row-unavailable'), 'Must apply line-row-unavailable class'); + assert.ok(html.includes('handout-badge-unavailable'), 'Must render unavailable badge'); + }); + + it('renders "Loading product..." with data attributes and hydration script when productHandle is present', () => { + const hydrationProto = { + name: 'Hydration Regimen', + lines: [ + { + variantGid: 'gid://shopify/ProductVariant/777888', + productHandle: 'daily-vitamin-d3', + quantity: 2, + usageNote: '2 drops morning' + } + ] + }; + + const html = renderHandoutHtml({ + protocol: hydrationProto, + practiceName: 'Wellness Center', + shareUrl: 'https://example.com/apps/protocols/tok_test' + }); + + assert.ok(!html.includes('Item 1'), 'Must not render "Item 1"'); + assert.ok(html.includes('Loading product...'), 'Must render "Loading product..." initial placeholder'); + assert.ok(html.includes('data-product-handle="daily-vitamin-d3"'), 'Must include data-product-handle'); + assert.ok(html.includes('data-variant-id="777888"'), 'Must include normalized data-variant-id'); + assert.ok(html.includes('data-variant-gid="gid://shopify/ProductVariant/777888"'), 'Must include data-variant-gid'); + assert.ok(html.includes('/products/'), 'Must include client-side hydration script'); + assert.ok(html.includes('.line-row[data-product-handle]'), 'Script must target data-product-handle rows'); + }); + + it('renders out-of-stock badge and line-row-unavailable when available is false', () => { + const outOfStockProto = { + name: 'Stack with OOS item', + lines: [ + { + title: 'Organic Zinc Drops', + quantity: 1, + available: false + } + ] + }; + + const html = renderHandoutHtml({ + protocol: outOfStockProto, + practiceName: 'Wellness Center', + shareUrl: 'https://example.com/apps/protocols/tok_test' + }); + + assert.ok(html.includes('Organic Zinc Drops')); + assert.ok(html.includes('line-row-unavailable')); + assert.ok(html.includes('Out of stock')); + assert.ok(html.includes('handout-badge-unavailable')); + }); + it('throws if protocol is missing', () => { assert.throws(() => renderHandoutHtml({ protocol: null }), /Protocol object is required/); }); diff --git a/test/routes.test.js b/test/routes.test.js index eb37b59..ebaeb6d 100644 --- a/test/routes.test.js +++ b/test/routes.test.js @@ -3108,6 +3108,229 @@ describe('HTTP Routes & Request Handlers (app/lib/protocols/routes.js)', () => { assert.ok(text.includes('Protocol not found')); }); + it('GET /apps/protocols/?handout=1 with stub variantResolver enriches lines with real titles and does not show Item 1 / Item 2', async () => { + const titleProto = { + id: 'proto_handout_enriched', + shop: testShop, + token: 'tok_handout_enriched', + name: 'Client Optimal Health Stack', + ownerType: 'customer', + ownerId: customerGid, + createdBy: customerGid, + status: 'active' + }; + db.state.protocols.push(titleProto); + db.state.lines.push( + { + id: 'line_enriched_1', + protocolId: titleProto.id, + position: 0, + variantGid: 'gid://shopify/ProductVariant/11111', + productHandle: 'snowboard', + quantity: 2, + usageNote: 'Use twice daily' + }, + { + id: 'line_enriched_2', + protocolId: titleProto.id, + position: 1, + variantGid: 'gid://shopify/ProductVariant/22222', + productHandle: 'ski-wax', + quantity: 1, + usageNote: 'Apply once weekly' + } + ); + + const stubResolver = { + resolveVariants: async (_shop, gids) => { + const map = new Map(); + map.set('gid://shopify/ProductVariant/11111', { + productTitle: 'Snowboard', + variantTitle: 'Oxygen', + title: 'Snowboard - Oxygen', + price: '120.00', + currency: 'USD', + availableForSale: true, + isDeleted: false, + isPublished: true + }); + map.set('gid://shopify/ProductVariant/22222', { + productTitle: 'Ski Wax', + variantTitle: 'Default Title', + title: 'Ski Wax', + price: '15.00', + currency: 'USD', + availableForSale: true, + isDeleted: false, + isPublished: true + }); + return map; + } + }; + + const proxyParams = { + shop: testShop, + token: titleProto.token, + handout: '1', + path_prefix: '/apps/protocols', + timestamp: '1729500000' + }; + const sig = calculateAppProxySignature(proxyParams, apiSecret); + const url = `https://${testShop}/apps/protocols?shop=${testShop}&token=${titleProto.token}&handout=1&path_prefix=%2Fapps%2Fprotocols×tamp=1729500000&signature=${sig}`; + + const res = await handleAppProxyRequest(db, new Request(url), { + apiSecret, + variantResolver: stubResolver + }); + assert.equal(res.status, 200); + const html = await res.text(); + + assert.ok(html.includes('Snowboard - Oxygen'), 'Must show real variant name'); + assert.ok(html.includes('Ski Wax'), 'Must show real product name'); + assert.ok(!html.includes('Item 1'), 'Must not show Item 1'); + assert.ok(!html.includes('Item 2'), 'Must not show Item 2'); + assert.ok(html.includes('Use twice daily')); + assert.ok(html.includes('Apply once weekly')); + }); + + it('GET /apps/protocols/?handout=1 with production wiring (variantResolver: undefined) renders data-product-handle, Loading product... placeholder, and hydration script without Item 1', async () => { + const prodWiringProto = { + id: 'proto_handout_prod', + shop: testShop, + token: 'tok_handout_prod', + name: 'Production Health Stack', + ownerType: 'customer', + ownerId: customerGid, + createdBy: customerGid, + status: 'active' + }; + db.state.protocols.push(prodWiringProto); + db.state.lines.push({ + id: 'line_prod_1', + protocolId: prodWiringProto.id, + position: 0, + variantGid: 'gid://shopify/ProductVariant/33333', + productHandle: 'snowboard-oxygen', + quantity: 2, + usageNote: 'Take 2 daily' + }); + + const proxyParams = { + shop: testShop, + token: prodWiringProto.token, + handout: '1', + path_prefix: '/apps/protocols', + timestamp: '1729500000' + }; + const sig = calculateAppProxySignature(proxyParams, apiSecret); + const url = `https://${testShop}/apps/protocols?shop=${testShop}&token=${prodWiringProto.token}&handout=1&path_prefix=%2Fapps%2Fprotocols×tamp=1729500000&signature=${sig}`; + + // Exactly like production server.js: variantResolver is undefined + const res = await handleAppProxyRequest(db, new Request(url), { + apiSecret, + variantResolver: undefined + }); + assert.equal(res.status, 200); + const html = await res.text(); + + assert.ok(!html.includes('Item 1'), 'Must not render Item 1 in production wiring'); + assert.ok(html.includes('Loading product...'), 'Must render Loading product... initial placeholder'); + assert.ok(html.includes('data-product-handle="snowboard-oxygen"'), 'Must render data-product-handle for client hydration'); + assert.ok(html.includes('data-variant-id="33333"'), 'Must render normalized variant ID'); + assert.ok(html.includes('/products/'), 'Must include client-side hydration script'); + assert.ok(html.includes('window.print()'), 'Must include window.print()'); + }); + + it('GET /apps/protocols/?handout=1 handles unavailable or deleted variants with badge and line-row-unavailable', async () => { + const unavailProto = { + id: 'proto_handout_unavail', + shop: testShop, + token: 'tok_handout_unavail', + name: 'Discontinued Items Stack', + ownerType: 'customer', + ownerId: customerGid, + createdBy: customerGid, + status: 'active' + }; + db.state.protocols.push(unavailProto); + db.state.lines.push( + { + id: 'line_unavail_1', + protocolId: unavailProto.id, + position: 0, + variantGid: 'gid://shopify/ProductVariant/88888', + productHandle: 'vintage-herb', + quantity: 1, + usageNote: '1 drop' + }, + { + id: 'line_unavail_2', + protocolId: unavailProto.id, + position: 1, + variantGid: 'gid://shopify/ProductVariant/99999', + // Missing productHandle and unresolvable + quantity: 1 + } + ); + + const stubResolver = { + resolveVariants: async (_shop, gids) => { + const map = new Map(); + map.set('gid://shopify/ProductVariant/88888', { + productTitle: 'Vintage Herb', + variantTitle: 'Default Title', + title: 'Vintage Herb', + price: '25.00', + currency: 'USD', + availableForSale: false, + isDeleted: false, + isPublished: true + }); + // 99999 is not in catalog at all (deleted or missing) + return map; + } + }; + + const proxyParams = { + shop: testShop, + token: unavailProto.token, + handout: '1', + path_prefix: '/apps/protocols', + timestamp: '1729500000' + }; + const sig = calculateAppProxySignature(proxyParams, apiSecret); + const url = `https://${testShop}/apps/protocols?shop=${testShop}&token=${unavailProto.token}&handout=1&path_prefix=%2Fapps%2Fprotocols×tamp=1729500000&signature=${sig}`; + + const res = await handleAppProxyRequest(db, new Request(url), { + apiSecret, + variantResolver: stubResolver + }); + assert.equal(res.status, 200); + const html = await res.text(); + + assert.ok(html.includes('line-row-unavailable'), 'Unavailable item must receive line-row-unavailable styling'); + assert.ok(html.includes('Out of stock'), 'Out of stock item must receive Out of stock badge'); + assert.ok(html.includes('Vintage Herb')); + assert.ok(!html.includes('Item 1'), 'Must not render Item 1'); + assert.ok(!html.includes('Item 2'), 'Must not render Item 2'); + }); + + it('GET /apps/protocols?handout=1 without token returns 404 Protocol not found', async () => { + const proxyParams = { + shop: testShop, + handout: '1', + path_prefix: '/apps/protocols', + timestamp: '1729500000' + }; + const sig = calculateAppProxySignature(proxyParams, apiSecret); + const url = `https://${testShop}/apps/protocols?shop=${testShop}&handout=1&path_prefix=%2Fapps%2Fprotocols×tamp=1729500000&signature=${sig}`; + + const res = await handleAppProxyRequest(db, new Request(url), { apiSecret }); + assert.equal(res.status, 404); + const text = await res.text(); + assert.equal(text, 'Protocol not found'); + }); + describe('Protocol Lifecycle Actions via App Proxy: archive, restore, duplicate (M9b-3b)', () => { let lifecycleProto; let starterTemplate;