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
22 changes: 16 additions & 6 deletions commerce-pdp-management/AGENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ written back to Shopify.
- **Frontend** — Next.js 16 + React 19 + Tailwind v4 (`frontend/`): the Sanity
Swag Store PDP with a pull-only resolver + merge.
- **Functions** — Sanity Functions (`functions/`): `cache-revalidate` (invalidate
the storefront CDN on publish) + `review-stamp` (stamp `reviewedAt` on approval).
the storefront CDN on publish) + `review-stamp` (stamp `reviewedAt` on approval,
clear it when a rule leaves `approved`).
- **Shared logic** — framework-agnostic package (`packages/@starter/commerce/`):
Shopify Storefront adapter, the attribute-rule resolver, and the merge. Imported
by both the frontend and the Functions.
Expand Down Expand Up @@ -69,13 +70,19 @@ cp frontend/.env.example frontend/.env
the org-level Content Agent prompt at setup.
- **Separate types over a unified enrichment type** — rules (1:many) and SKU
enrichment (1:1) have different workflows and Studio surfaces. The Review Queue
spans both via a `status` filter.
spans both via a `status != "approved"` filter.
- **Status flow** — `draft` → `in-review` → `approved` for rules, `draft` →
`approved` for SKU enrichment. Only `approved` reaches the storefront; anything
else is in the Review Queue, including a rule sent back to `draft` after approval.

## The resolver + merge (heart of the storefront)

`packages/@starter/commerce/src/resolvePdp.ts` → `resolveAttributeRules`:

1. Pick the priority list (a matching `productTypeScope` overrides the global list).
1. Pick the priority list (a matching `productTypeScope` overrides the global list:
the scope's rules first — including rules only in the scope — then the rest of
the global list). Dangling or unpublished references are skipped with a
`console.warn` naming the list they came from.
2. Walk in priority order; a rule matches when ALL `tags` are present and NO
`excludedTags` are.
3. First-match wins within a `category`.
Expand All @@ -96,7 +103,8 @@ by handle, then the control plane + SKU enrichment (GROQ) in parallel, then merg
/ `skuEnrichment`, POST the storefront `/api/revalidate` endpoint (secret-guarded)
so cached PDPs re-pull from Sanity's CDN. No push to Shopify.
- `functions/review-stamp/` — on `attributeRule` approval, stamp
`aiEnrichment.reviewedAt` (only when missing, so it does not loop).
`aiEnrichment.reviewedAt` (only when missing); when a rule leaves `approved`,
clear it so re-approval gets a fresh stamp. Neither patch re-fires itself.

## Deploying functions

Expand All @@ -112,10 +120,12 @@ the root `.env`.

## Studio surfaces

- **Review queue** — spans `attributeRule` (in-review) and `skuEnrichment` (draft).
- **Review queue** — every `attributeRule` and `skuEnrichment` whose `status` is
not `approved` (draft and in-review alike).
- **Attribute rules** — browsable by category for large rule sets.
- **Control plane / Brand voice** — pinned singletons (can't be created/deleted).
- **Product picker** (`ProductPickerInput`) — searches Shopify by name via the
public Storefront token; stores the GID for `skuEnrichment`.
public Storefront token; stores the GID for `skuEnrichment`. Type-ahead goes
through `hooks/useDebouncedSearch` (debounced + only the latest request lands).
- **Content Agent** — AI generation writes drafts (`aiGenerated: true`,
`status: in-review`) governed by the `brandVoice` context prompt.
5 changes: 4 additions & 1 deletion commerce-pdp-management/frontend/sanity/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@ const RULE = `{
* The control plane singleton: the prioritized list of active attribute rules.
* References resolve to approved rules in array (priority) order. A null result
* means no rules are active — every product renders as pure Shopify.
*
* Product-type scopes dereference their own rules too, so a rule that only
* appears in a scope (not in the global list) still reaches the resolver.
*/
export const controlPlaneQuery = defineQuery(`
*[_type == "controlPlane" && _id == "controlPlane"][0]{
"priorityList": priorityList[]->${RULE},
"productTypeScopes": productTypeScopes[]{
productType,
"ruleIds": priorityList[]._ref
"priorityList": priorityList[]->${RULE}
}
}
`)
Expand Down
37 changes: 26 additions & 11 deletions commerce-pdp-management/functions/review-stamp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
//
// When an attribute rule reaches `status: approved`, stamp `aiEnrichment.reviewedAt`
// if it isn't set yet, so the approval time is captured without the reviewer
// filling it in by hand. The patch only runs when the timestamp is missing, so it
// does not loop on its own resulting update event.
// filling it in by hand. When a rule leaves `approved` (sent back to draft or
// in-review), clear the stamp so the next approval records a fresh timestamp
// rather than the old one.
//
// Each patch only runs when the document is not already in the target state, so
// the function does not loop on its own resulting update event.
import {documentEventHandler} from '@sanity/functions'
import {createClient} from '@sanity/client'
import {defineQuery} from 'groq'
Expand All @@ -19,7 +23,6 @@ const RULE_QUERY = defineQuery(`*[_id == $id][0]{status, "reviewedAt": aiEnrichm

export const handler = documentEventHandler(async ({context, event}) => {
const data = event.data as EventData
if (data.status !== 'approved') return

const {SANITY_STUDIO_PROJECT_ID: projectId, SANITY_STUDIO_DATASET: dataset} = env
const token = context.clientOptions?.token
Expand All @@ -29,14 +32,26 @@ export const handler = documentEventHandler(async ({context, event}) => {

const client = createClient({projectId, dataset, token, apiVersion: '2025-01-01', useCdn: false})

// Re-read rather than trusting the event payload, so a stale event never
// stamps or clears against a status that has since changed.
const current = await client.fetch(RULE_QUERY, {id: data._id})
if (current?.status !== 'approved' || current?.reviewedAt) return

await client
.patch(data._id)
.setIfMissing({aiEnrichment: {}})
.set({'aiEnrichment.reviewedAt': new Date().toISOString()})
.commit()
if (!current) return

const isApproved = current.status === 'approved'
const hasStamp = Boolean(current.reviewedAt)

if (isApproved && !hasStamp) {
await client
.patch(data._id)
.setIfMissing({aiEnrichment: {}})
.set({'aiEnrichment.reviewedAt': new Date().toISOString()})
.commit()
console.log(`Stamped reviewedAt on approved rule ${data._id}`)
return
}

console.log(`Stamped reviewedAt on approved rule ${data._id}`)
if (!isApproved && hasStamp) {
await client.patch(data._id).unset(['aiEnrichment.reviewedAt']).commit()
console.log(`Cleared reviewedAt on rule ${data._id} (status: ${current.status})`)
}
})
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {AttributeRule, ControlPlane, ResolvedAttribute} from './types'
import type {AttributeRule, ControlPlane, PriorityList, ResolvedAttribute} from './types'

export type ResolveInput = {
/** Shopify product tags — the matching input. */
Expand Down Expand Up @@ -65,26 +65,51 @@ function ruleMatches(rule: AttributeRule, productTags: Set<string>): boolean {

/**
* Choose the effective priority list. If the product's type matches a
* `productTypeScope`, reorder the global rules by that scope's `ruleIds`
* (rules absent from the scope are appended in their global order).
* `productTypeScope`, that scope's rules come first in the scope's order —
* including rules that only appear in the scope — followed by any global rules
* the scope did not mention, in their global order.
*/
function selectPriorityList(
controlPlane: ControlPlane,
productType: string | null | undefined,
): AttributeRule[] {
const globalRules = compactPriorityList(controlPlane.priorityList, 'controlPlane.priorityList')

const scope = productType
? controlPlane.productTypeScopes?.find((s) => s.productType === productType)
: undefined
if (!scope?.ruleIds?.length) return controlPlane.priorityList
if (!scope) return globalRules

const scopedRules = compactPriorityList(
scope.priorityList,
`productTypeScope "${scope.productType}"`,
)
if (scopedRules.length === 0) return globalRules

const byId = new Map(controlPlane.priorityList.map((rule) => [rule._id, rule]))
const scoped: AttributeRule[] = []
for (const id of scope.ruleIds) {
const rule = byId.get(id)
if (rule) {
scoped.push(rule)
byId.delete(id)
}
const scopedIds = new Set(scopedRules.map((rule) => rule._id))
const unscopedGlobalRules = globalRules.filter((rule) => !scopedIds.has(rule._id))
return [...scopedRules, ...unscopedGlobalRules]
}

/**
* Drop unresolvable entries from a dereferenced priority list and say so. A
* `null` here means the control plane references a rule that no longer exists
* or is not published, so the merchandiser can fix the reference instead of
* wondering why a rule never renders.
*/
function compactPriorityList(
list: PriorityList | null | undefined,
source: string,
): AttributeRule[] {
const entries = list ?? []
const rules = entries.filter((rule): rule is AttributeRule => rule != null)

const unresolvedCount = entries.length - rules.length
if (unresolvedCount > 0) {
console.warn(
`[@starter/commerce] ${source} references ${unresolvedCount} attribute rule(s) that could not be resolved (deleted or unpublished). They were skipped.`,
)
}
return [...scoped, ...byId.values()]

return rules
}
15 changes: 12 additions & 3 deletions commerce-pdp-management/packages/@starter/commerce/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,19 @@ export type AttributeRule = {
status: ReviewStatus
}

/**
* A dereferenced priority list as GROQ returns it: a reference to a rule that
* was deleted or never published resolves to `null` rather than being omitted.
*/
export type PriorityList = Array<AttributeRule | null>

export type ProductTypeScope = {
productType: string
/** Ordered rule ids overriding the global priority for this product type. */
ruleIds: string[]
/**
* Rules overriding the global priority for this product type, dereferenced in
* resolution order. May include rules that are not in the global list.
*/
priorityList?: PriorityList | null
}

/**
Expand All @@ -107,7 +116,7 @@ export type ProductTypeScope = {
*/
export type ControlPlane = {
/** Approved attribute rules, in resolution priority order. */
priorityList: AttributeRule[]
priorityList?: PriorityList | null
productTypeScopes?: ProductTypeScope[] | null
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ export type AllSanitySchemaTypes =

// Source: ../frontend/sanity/queries.ts
// Variable: controlPlaneQuery
// Query: *[_type == "controlPlane" && _id == "controlPlane"][0]{ "priorityList": priorityList[]->{ _id, name, category, description, "iconUrl": icon.asset->url, "tags": coalesce(tags, []), "excludedTags": coalesce(excludedTags, []), language, "order": coalesce(order, 0), status}, "productTypeScopes": productTypeScopes[]{ productType, "ruleIds": priorityList[]._ref } }
// Query: *[_type == "controlPlane" && _id == "controlPlane"][0]{ "priorityList": priorityList[]->{ _id, name, category, description, "iconUrl": icon.asset->url, "tags": coalesce(tags, []), "excludedTags": coalesce(excludedTags, []), language, "order": coalesce(order, 0), status}, "productTypeScopes": productTypeScopes[]{ productType, "priorityList": priorityList[]->{ _id, name, category, description, "iconUrl": icon.asset->url, "tags": coalesce(tags, []), "excludedTags": coalesce(excludedTags, []), language, "order": coalesce(order, 0), status} } }
export type ControlPlaneQueryResult = {
priorityList: Array<{
_id: string
Expand All @@ -329,7 +329,18 @@ export type ControlPlaneQueryResult = {
}> | null
productTypeScopes: Array<{
productType: string | null
ruleIds: Array<string> | null
priorityList: Array<{
_id: string
name: string | null
category: 'care' | 'fit' | 'launch' | 'lifestyle' | 'spec' | null
description: BlockContent | null
iconUrl: string | null
tags: Array<string> | Array<never>
excludedTags: Array<string> | Array<never>
language: string | null
order: number | 0
status: 'approved' | 'draft' | 'in-review' | null
}> | null
}> | null
} | null

Expand Down Expand Up @@ -370,7 +381,7 @@ export type RULE_QUERY_RESULT =
import '@sanity/client'
declare module '@sanity/client' {
interface SanityQueries {
'\n *[_type == "controlPlane" && _id == "controlPlane"][0]{\n "priorityList": priorityList[]->{\n _id,\n name,\n category,\n description,\n "iconUrl": icon.asset->url,\n "tags": coalesce(tags, []),\n "excludedTags": coalesce(excludedTags, []),\n language,\n "order": coalesce(order, 0),\n status\n},\n "productTypeScopes": productTypeScopes[]{\n productType,\n "ruleIds": priorityList[]._ref\n }\n }\n': ControlPlaneQueryResult
'\n *[_type == "controlPlane" && _id == "controlPlane"][0]{\n "priorityList": priorityList[]->{\n _id,\n name,\n category,\n description,\n "iconUrl": icon.asset->url,\n "tags": coalesce(tags, []),\n "excludedTags": coalesce(excludedTags, []),\n language,\n "order": coalesce(order, 0),\n status\n},\n "productTypeScopes": productTypeScopes[]{\n productType,\n "priorityList": priorityList[]->{\n _id,\n name,\n category,\n description,\n "iconUrl": icon.asset->url,\n "tags": coalesce(tags, []),\n "excludedTags": coalesce(excludedTags, []),\n language,\n "order": coalesce(order, 0),\n status\n}\n }\n }\n': ControlPlaneQueryResult
'\n *[_type == "skuEnrichment" && status == "approved" && product.productGid == $gid][0]{\n "productGid": product.productGid,\n headline,\n editorialCopy,\n "lifestyleImages": lifestyleImages[]{\n "url": asset->url,\n "altText": asset->altText\n },\n launchBadge,\n status\n }\n': SkuEnrichmentByGidQueryResult
'*[_id == $id][0]{status, "reviewedAt": aiEnrichment.reviewedAt}': RULE_QUERY_RESULT
}
Expand Down
20 changes: 6 additions & 14 deletions commerce-pdp-management/studio/components/ProductPickerInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {useCallback, useMemo, useState} from 'react'
import {useCallback, useMemo} from 'react'
import {set, unset, type ObjectInputProps} from 'sanity'
import {Autocomplete, Box, Button, Card, Flex, Stack, Text} from '@sanity/ui'
import {SearchIcon, TrashIcon} from '@sanity/icons'
import {useDebouncedSearch} from '../hooks/useDebouncedSearch'

/**
* Object-level input that searches the Shopify catalog by name and stores the
Expand Down Expand Up @@ -39,7 +40,7 @@ const SEARCH_QUERY = /* GraphQL */ `
}
`

async function searchShopify(term: string): Promise<Suggestion[]> {
async function searchShopify(term: string, signal: AbortSignal): Promise<Suggestion[]> {
if (!DOMAIN || !TOKEN) return []
const res = await fetch(`https://${DOMAIN}/api/${API_VERSION}/graphql.json`, {
method: 'POST',
Expand All @@ -51,6 +52,7 @@ async function searchShopify(term: string): Promise<Suggestion[]> {
query: SEARCH_QUERY,
variables: {query: term ? `title:*${term}*` : '', first: 10},
}),
signal,
})
if (!res.ok) return []
const json = await res.json()
Expand All @@ -65,20 +67,10 @@ async function searchShopify(term: string): Promise<Suggestion[]> {

export function ProductPickerInput(props: ObjectInputProps<ProductValue>) {
const {value, onChange, schemaType} = props
const [suggestions, setSuggestions] = useState<Suggestion[]>([])
const [loading, setLoading] = useState(false)
const {results: suggestions, loading, search} = useDebouncedSearch(searchShopify)

const configured = Boolean(DOMAIN && TOKEN)

const handleSearch = useCallback(async (term: string) => {
setLoading(true)
try {
setSuggestions(await searchShopify(term))
} finally {
setLoading(false)
}
}, [])

const handleSelect = useCallback(
(gid: string) => {
const picked = suggestions.find((s) => s.gid === gid)
Expand Down Expand Up @@ -143,7 +135,7 @@ export function ProductPickerInput(props: ObjectInputProps<ProductValue>) {
options={options}
placeholder="Search products by name…"
filterOption={() => true}
onQueryChange={(q) => handleSearch(q ?? '')}
onQueryChange={(q) => search(q ?? '')}
onSelect={handleSelect}
renderOption={(option) => (
<Card as="button" padding={3} radius={2}>
Expand Down
Loading
Loading