Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion PROJECT_CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down Expand Up @@ -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 <shop>: <message>`). 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`).



9 changes: 5 additions & 4 deletions app/lib/protocols/contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -626,7 +626,7 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn =
plan {
publicDisplayName
}
billingAddress {
shopAddress {
countryCodeV2
}
}
Expand Down Expand Up @@ -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;
}

Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion docs/SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<iv>:<tag>:<ciphertext>`), createdAt, updatedAt |

> [!NOTE]
Expand Down
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ export function renderPrivacyHtml({ contactEmail = '' } = {}) {
<li><strong>Protocols and Share Tokens:</strong> Protocol titles, intro messages, selected product variant identifiers (GIDs and handles), recommended quantities, usage directions, and unguessable cryptographic share tokens.</li>
<li><strong>Aggregate Attribution Counts:</strong> Monthly aggregate order counts and attributed gross revenue per protocol and practice.</li>
<li><strong>Opted-In Shopper Contacts:</strong> 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. <em>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.</em></li>
<li><strong>Merchant Store Profile &amp; Feedback:</strong> 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 &amp; feedback"), we record their marketing consent and timestamp to reach out about feedback, custom work, and product updates. Merchants can also submit ratings (1&ndash;5) and feedback messages.</li>
<li><strong>Merchant Store Profile &amp; Feedback:</strong> 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 &amp; feedback"), we record their marketing consent and timestamp to reach out about feedback, custom work, and product updates. Merchants can also submit ratings (1&ndash;5) and feedback messages.</li>
<li><strong>Merchant Custom Feature Requests:</strong> 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.</li>
</ul>

Expand Down
23 changes: 21 additions & 2 deletions test/contacts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => ({
Expand All @@ -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' }
}
}
})
Expand All @@ -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');
Expand All @@ -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 () => {
Expand All @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion test/exchange.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' }
}
}
};
Expand Down
Loading