From cbb0a3a3312a11170209555f34c0abaec80d335d Mon Sep 17 00:00:00 2001 From: arsalan-arshad Date: Fri, 6 Nov 2026 02:09:39 +0500 Subject: [PATCH] fix(profile): use shopAddress for store country --- PROJECT_CONTEXT.md | 21 ++++++++++++++++++++- app/lib/protocols/contacts.js | 9 +++++---- docs/SPEC.md | 2 +- server.js | 2 +- test/contacts.test.js | 23 +++++++++++++++++++++-- test/exchange.test.js | 2 +- 6 files changed, 49 insertions(+), 10 deletions(-) diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index d3563d2..63de185 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -1043,7 +1043,7 @@ Run the five spikes in a day or two on a dev store; write the answers into secti 5. **Merchant Profile & Contact Preferences (`ShopProfile`):** - Migration `20261105_add_shop_profile_and_feedback_rating/migration.sql` creates `ShopProfile` (id, shop unique, shopName, ownerName, email, planName, country, installedAt, uninstalledAt, marketingOptIn default false, marketingOptInAt, createdAt, updatedAt) and adds `rating` (1–5) to `MerchantFeedback`. - Registered in `scripts/migrate.js` and mirrored in `prisma/schema.prisma`. - - Admin GraphQL `shop` query (`name, email, shopOwnerName, plan.publicDisplayName, billingAddress.countryCodeV2`) synchronized on OAuth code exchange and on admin load if stale (> 7 days). No additional Shopify scopes required (`read_orders` only). + - Admin GraphQL `shop` query (`name, email, shopOwnerName, plan.publicDisplayName, shopAddress.countryCodeV2`) synchronized on OAuth code exchange and on admin load if stale (> 7 days). No additional Shopify scopes required (`read_orders` only). - Failed GraphQL profile sync logs a single non-PII warning and never blocks installation. - Reinstallation clears `uninstalledAt = NULL` while strictly preserving existing `marketingOptIn` and `marketingOptInAt`. 6. **Polaris Admin Settings "Contact & feedback" Card:** @@ -1099,4 +1099,23 @@ Run the five spikes in a day or two on a dev store; write the answers into secti - Added `test/exchange.test.js` covering RFC 8693 request parameter compliance, encrypted session write, profile sync, second-request bypass, in-flight concurrency lock deduplication, negative cache cooldown, 400 non-blocking render, privacy logging, `app/uninstalled` session cleanup, UI disabled state, and friendly root page. - 578 unit tests passing across 132 suites (`npm test`). Zero failures. +### 2026-11-06: Shop Profile GraphQL Field Migration (`shopAddress` vs `billingAddress`) (Branch fix/shop-profile-query) +1. **Root Cause Resolution (Empty ShopProfile on Live Store):** + - Live testing confirmed token exchange created the `Session` row successfully, but `ShopProfile` remained empty. + - Investigation revealed `syncShopProfile` in `app/lib/protocols/contacts.js` queried `billingAddress { countryCodeV2 }` on the `Shop` object. In current Shopify Admin GraphQL schemas, `billingAddress` is deprecated and rejected on modern API versions, causing Shopify to reject the entire GraphQL query with an error and preventing `ShopProfile` from being populated. + - Verified against current Shopify Admin GraphQL schema using Dev MCP tooling: `shopAddress { countryCodeV2 }` is the valid store address field, while `name`, `email`, `shopOwnerName`, and `plan { publicDisplayName }` exist and remain fully valid. +2. **GraphQL Query & Resolver Update:** + - Updated `syncShopProfile` to query `shopAddress { countryCodeV2 }` and read `shopData.shopAddress?.countryCodeV2`. + - Maintained 5-second `AbortController` timeout and non-blocking failure semantics. +3. **Non-PII GraphQL Error Logging:** + - Updated error handling on GraphQL `errors` response to log a single non-PII warning line containing the first error's message truncated to 200 characters (`[ShopProfile] GraphQL error for : `). Never logs tokens, emails, or response bodies. +4. **Privacy Text & Documentation Alignment:** + - Verified and aligned `/privacy` page text in `server.js`, `docs/SPEC.md`, and `PROJECT_CONTEXT.md` to accurately state that store country is retrieved from the shop address. +5. **Test Suite & Verification:** + - Updated test mocks in `test/exchange.test.js` and `test/contacts.test.js` to return `shopAddress`. + - Added assertions verifying that the GraphQL request body contains `shopAddress { countryCodeV2 }` and strictly does not contain `billingAddress`. + - Added test verifying truncated single-line logging on GraphQL `errors`. + - 578 unit tests passing across 132 suites (`npm test`). + + diff --git a/app/lib/protocols/contacts.js b/app/lib/protocols/contacts.js index cd600aa..55a0289 100644 --- a/app/lib/protocols/contacts.js +++ b/app/lib/protocols/contacts.js @@ -591,7 +591,7 @@ export async function updateShopMarketingOptIn(db, { shop, marketingOptIn }) { /** * Synchronizes shop profile data from Shopify Admin GraphQL API. - * Uses query GetShopProfile: { shop { name email shopOwnerName plan { publicDisplayName } billingAddress { countryCodeV2 } } } + * Uses query GetShopProfile: { shop { name email shopOwnerName plan { publicDisplayName } shopAddress { countryCodeV2 } } } * Never throws or blocks install if fetch fails; logs a single non-PII warning. * * @param {any} db @@ -626,7 +626,7 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn = plan { publicDisplayName } - billingAddress { + shopAddress { countryCodeV2 } } @@ -657,7 +657,8 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn = const json = await res.json(); if (json.errors && json.errors.length > 0) { - console.warn(`[ShopProfile] GraphQL error fetching shop profile for ${shop}`); + const firstMsg = String(json.errors[0]?.message || 'Unknown error').slice(0, 200); + console.warn(`[ShopProfile] GraphQL error for ${shop}: ${firstMsg}`); return null; } @@ -668,7 +669,7 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn = const email = shopData.email || null; const ownerName = shopData.shopOwnerName || null; const planName = shopData.plan?.publicDisplayName || null; - const country = shopData.billingAddress?.countryCodeV2 || null; + const country = shopData.shopAddress?.countryCodeV2 || null; return await upsertShopProfile(db, { shop, diff --git a/docs/SPEC.md b/docs/SPEC.md index 132c3e5..0cc1172 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -62,7 +62,7 @@ Always `noindex`. Prices are always the store's live retail price — a protocol | `Setting` | shop, mode, footer disclaimer, handout text | | `ShopperContact` | id, shop, ownerId, email (lowercased, max 254), firstName (optional, max 60), consentText, consentVersion, consentedAt, source ('protocol_page'), createdAt — **explicit opt-in only**; unique (shop, ownerId, email) | | `MerchantFeedback` | id, shop, shopName, ownerName, replyEmail, planName, country, message (max 1000), rating (1–5, optional), kind ('feedback' / 'custom_request'), createdAt | -| `ShopProfile` | id, shop (unique), shopName, ownerName, email, planName, country, installedAt, uninstalledAt (nullable), marketingOptIn (boolean), marketingOptInAt (nullable), createdAt, updatedAt — synchronized via Admin GraphQL `shop` query | +| `ShopProfile` | id, shop (unique), shopName, ownerName, email, planName, country (store country from `shopAddress.countryCodeV2`), installedAt, uninstalledAt (nullable), marketingOptIn (boolean), marketingOptInAt (nullable), createdAt, updatedAt — synchronized via Admin GraphQL `shop` query | | `Session` | id, shop, state, isOnline, scope, accessToken (**encrypted at rest using AES-256-GCM**, `enc:v1:::`), createdAt, updatedAt | > [!NOTE] diff --git a/server.js b/server.js index 613f191..24e2d58 100644 --- a/server.js +++ b/server.js @@ -608,7 +608,7 @@ export function renderPrivacyHtml({ contactEmail = '' } = {}) {
  • Protocols and Share Tokens: Protocol titles, intro messages, selected product variant identifiers (GIDs and handles), recommended quantities, usage directions, and unguessable cryptographic share tokens.
  • Aggregate Attribution Counts: Monthly aggregate order counts and attributed gross revenue per protocol and practice.
  • Opted-In Shopper Contacts: If and only if a shopper explicitly opts in via the "Stay in touch" form on a protocol recommendation page, the app stores their email address, optional first name, the exact canonical consent text, consent version, timestamp, and the associated practice. Purpose: to enable the merchant or practice to send product recommendations and offers directly through their own communication tools (emails are never sent by this application). Legal basis: explicit consent. The app stores NO protocolId, NO order ID, NO purchased product data, NO IP address, and NO user agent with the contact. Note: The application does not send email or perform email verification; merchants and practitioners export contacts to confirm via double opt-in in their own email marketing systems.
  • -
  • Merchant Store Profile & Feedback: Basic store profile details (shop name, owner name, contact email, plan name, country) retrieved via the Shopify Admin API. If the merchant opts in via Settings ("Contact & feedback"), we record their marketing consent and timestamp to reach out about feedback, custom work, and product updates. Merchants can also submit ratings (1–5) and feedback messages.
  • +
  • Merchant Store Profile & Feedback: Basic store profile details (shop name, owner name, contact email, plan name, store country from the shop address) retrieved via the Shopify Admin API. If the merchant opts in via Settings ("Contact & feedback"), we record their marketing consent and timestamp to reach out about feedback, custom work, and product updates. Merchants can also submit ratings (1–5) and feedback messages.
  • Merchant Custom Feature Requests: When a merchant submits a feature request in the admin Settings tab, we store the message and optional reply email. This counts as consent to reply strictly to that inquiry and never turns on marketing opt-in.
  • diff --git a/test/contacts.test.js b/test/contacts.test.js index 60aefaa..b464cc7 100644 --- a/test/contacts.test.js +++ b/test/contacts.test.js @@ -668,8 +668,10 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', // 1. Success path let capturedSignal = null; + let capturedBody = null; const fakeFetchSuccess = async (url, options) => { capturedSignal = options?.signal; + capturedBody = JSON.parse(options?.body || '{}'); return { ok: true, json: async () => ({ @@ -679,7 +681,7 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', email: 'info@holistic.com', shopOwnerName: 'Alice Green', plan: { publicDisplayName: 'Advanced' }, - billingAddress: { countryCodeV2: 'GB' } + shopAddress: { countryCodeV2: 'GB' } } } }) @@ -690,6 +692,9 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', assert.ok(res); assert.ok(capturedSignal, 'Must pass AbortSignal to GraphQL fetch'); assert.equal(typeof capturedSignal.aborted, 'boolean'); + assert.ok(capturedBody.query, 'Must send GraphQL query in body'); + assert.match(capturedBody.query, /shopAddress\s*\{\s*countryCodeV2\s*\}/, 'Query must select shopAddress { countryCodeV2 }'); + assert.doesNotMatch(capturedBody.query, /billingAddress/, 'Query must not select billingAddress'); assert.equal(res.shopName, 'Holistic Care'); assert.equal(res.email, 'info@holistic.com'); assert.equal(res.ownerName, 'Alice Green'); @@ -710,7 +715,7 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', const failRes = await syncShopProfile(mockDb, { shop: 'holistic.myshopify.com', fetchFn: fakeFetchFail }); assert.equal(failRes, null); assert.equal(warnings.length, 1); - assert.match(warnings[0], /Failed to fetch shop profile/); + assert.match(warnings[0], /Failed to fetch shop profile for holistic\.myshopify\.com: HTTP 500/); // 3. Aborted/timed out fetch must be handled gracefully without throwing const fakeFetchTimeout = async () => { @@ -723,6 +728,20 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', assert.equal(timeoutRes, null); assert.equal(warnings.length, 2); assert.match(warnings[1], /The operation was aborted/); + + // 4. GraphQL errors response logs single line with truncated message and returns null + const longMessage = 'A'.repeat(300); + const fakeFetchGraphQLError = async () => ({ + ok: true, + json: async () => ({ + errors: [{ message: longMessage }] + }) + }); + + const gqlErrRes = await syncShopProfile(mockDb, { shop: 'holistic.myshopify.com', fetchFn: fakeFetchGraphQLError }); + assert.equal(gqlErrRes, null); + assert.equal(warnings.length, 3); + assert.match(warnings[2], /^\[ShopProfile\] GraphQL error for holistic\.myshopify\.com: A{200}$/); } finally { console.warn = origWarn; } diff --git a/test/exchange.test.js b/test/exchange.test.js index aff2585..f81e4d3 100644 --- a/test/exchange.test.js +++ b/test/exchange.test.js @@ -227,7 +227,7 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ email: 'owner@elitenaturalhealth.com', shopOwnerName: 'Dr. Jane Smith', plan: { publicDisplayName: 'Shopify Plus' }, - billingAddress: { countryCodeV2: 'CA' } + shopAddress: { countryCodeV2: 'CA' } } } };