diff --git a/.agents/skills/starter/SKILL.md b/.agents/skills/starter/SKILL.md index 7a90a0d..c721b69 100644 --- a/.agents/skills/starter/SKILL.md +++ b/.agents/skills/starter/SKILL.md @@ -36,17 +36,17 @@ my-starter/ Every starter must have: -| File | Purpose | -| --- | --- | -| `package.json` | `"type": "module"`, `engines`, `packageManager`, scripts | -| `pnpm-workspace.yaml` | Workspace packages + `catalog:` for shared dep versions | -| `.env.example` | Template with comments, no real values | -| `.gitignore` | Self-contained, covers all starter concerns | -| `.npmrc` | `enable-pre-post-scripts=true` (required for pnpm 10.x) | -| `.oxfmtrc.json` | `semi: false`, `singleQuote: true`, `printWidth: 100`, `bracketSpacing: false` | -| `README.md` | Getting started, prerequisites, project structure | -| `AGENT.md` | Agent context for Claude Code / Cursor / etc. | -| `CLAUDE.md` | Symlink to `AGENT.md` | +| File | Purpose | +| --------------------- | ------------------------------------------------------------------------------ | +| `package.json` | `"type": "module"`, `engines`, `packageManager`, scripts | +| `pnpm-workspace.yaml` | Workspace packages + `catalog:` for shared dep versions | +| `.env.example` | Template with comments, no real values | +| `.gitignore` | Self-contained, covers all starter concerns | +| `.npmrc` | `enable-pre-post-scripts=true` (required for pnpm 10.x) | +| `.oxfmtrc.json` | `semi: false`, `singleQuote: true`, `printWidth: 100`, `bracketSpacing: false` | +| `README.md` | Getting started, prerequisites, project structure | +| `AGENT.md` | Agent context for Claude Code / Cursor / etc. | +| `CLAUDE.md` | Symlink to `AGENT.md` | ## Environment Variables @@ -58,11 +58,11 @@ Single root `.env.local` cascades to all workspaces. Never committed. Loading patterns by context: -| Context | Pattern | -| --- | --- | -| Studio CLI (`sanity.cli.ts`) | `process.loadEnvFile(\`${__dirname}/../.env.local\`)` | -| Blueprint (`sanity.blueprint.ts`) | `readFileSync` + manual parse (jiti quirk) | -| Vite apps | `vite: { envDir: '..' }` pointing to root | +| Context | Pattern | +| --------------------------------- | ----------------------------------------------------- | +| Studio CLI (`sanity.cli.ts`) | `process.loadEnvFile(\`${__dirname}/../.env.local\`)` | +| Blueprint (`sanity.blueprint.ts`) | `readFileSync` + manual parse (jiti quirk) | +| Vite apps | `vite: { envDir: '..' }` pointing to root | ## Shared Config Packages @@ -121,13 +121,24 @@ Root `package.json` delegates to workspaces: ## GitHub Workflows -Each starter ships its own workflows for standalone use: +Each starter ships its own workflows under `/.github/workflows/` for standalone use (they run when the starter is cloned via `sanity init --template`): -- **`ci.yml`** — format check, lint, typecheck, test, validate -- **`deploy.yml`** — deploy Studio, functions, apps on push to main (path-filtered) +- **`ci.yml`** — format check, lint, typecheck, validate, and (if it has Functions) build + manifest extract + bundle-size check +- **`deploy.yml`** — deploy Studio, functions, and blueprint on push to main (path-filtered); build the frontend as a guard. The Next.js storefront itself deploys via Vercel (dashboard import), not this workflow. - **`eval.yml`** — manual triggers for quality evals (if applicable) -These also exist in the root `.github/workflows/ci.yml` for monorepo CI but scoped with `working-directory` and `cache-dependency-path`. +## Wiring a New Starter into the Monorepo + +The starter's own workflows do **not** run in this repo — the root `.github/workflows/ci.yml` runs CI for every starter. Adding a new starter is not complete until you do all of the following (it's easy to forget the root CI job — a starter with green local `pnpm validate` still has **zero** monorepo coverage without it): + +1. **Add a job to the root `.github/workflows/ci.yml`.** Mirror an existing starter job (e.g. `knowledge-base`): a Node 20/22 matrix, `environment: `, `defaults.run.working-directory: `, then `pnpm install` + format check + lint + typecheck + validate (+ functions build, manifest extract, and bundle-size check if it has Functions). Steps that touch the Content Lake read `SANITY_STUDIO_PROJECT_ID`/`SANITY_STUDIO_DATASET` from `${{ vars.SANITY_PROJECT_ID }}` / `${{ vars.SANITY_DATASET }}`. +2. **Create a GitHub Environment** named exactly after the starter (repo Settings → Environments) with: + - vars: `SANITY_PROJECT_ID`, `SANITY_DATASET` (add `SANITY_STACK_ID` if it deploys a blueprint) + - secrets: `SANITY_AUTH_TOKEN` (only if the starter deploys) +3. **Add a row** to the starters table in the root `README.md`. +4. **Husky needs no edit** — the root `.husky/pre-commit` hook auto-discovers each starter by its own `package.json` / `eslint.config.*`, so formatting and lint-fix scope automatically. + +Verify from the starter directory with `pnpm validate` (template compatibility) and confirm the new `` job appears in the PR's checks. ## Template Validation diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 777f7d3..a5471ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -166,16 +166,16 @@ jobs: done exit $failed - analytics-content-ops: - name: analytics-content-ops (Node ${{ matrix.node-version }}) + commerce-plp-management: + name: commerce-plp-management (Node ${{ matrix.node-version }}) runs-on: ubuntu-latest - environment: analytics-content-ops + environment: commerce-plp-management strategy: matrix: node-version: [20, 22] defaults: run: - working-directory: analytics-content-ops + working-directory: commerce-plp-management steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 @@ -194,6 +194,8 @@ jobs: SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} - name: Validate template run: pnpm run validate + - name: Build functions + run: pnpm --filter @starter/functions build - name: Manifest extract run: pnpm --filter studio exec sanity manifest extract env: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b26cca2..2abaec4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,11 +23,12 @@ Then customize it: When it's ready, wire it into the monorepo: -- Add a job to `.github/workflows/ci.yml` (with `environment: `) -- Create a GitHub Environment in repo settings with `SANITY_PROJECT_ID` and `SANITY_DATASET` (add `SANITY_AUTH_TOKEN` as a secret if the starter deploys) -- Add the starter name to the lint loop in `.husky/pre-commit` +- Add a job to `.github/workflows/ci.yml` (with `environment: `) — the starter's own workflows don't run here, so without this job the starter has no monorepo CI coverage +- Create a GitHub Environment in repo settings with `SANITY_PROJECT_ID` and `SANITY_DATASET` (add `SANITY_AUTH_TOKEN` as a secret, and `SANITY_STACK_ID` as a var, if the starter deploys) - Add a row to the table in `README.md` +The `.husky/pre-commit` hook auto-discovers starters — no manual edit needed. + The starter must work standalone when cloned via `sanity init --template`. Run `pnpm validate` to check. ## Conventions diff --git a/README.md b/README.md index 2306eea..a4230ef 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,14 @@ pnpm create sanity@latest --template sanity-labs/starters/ ## Starters -| Starter | Description | -| ------------------------------------------------ | ----------------------------------------------------------------------------------------- | -| [agent-ready-content](./agent-ready-content) | Serve HTML to humans and markdown to agents from the same URLs, in Next.js and Astro | -| [agentic-localization](./agentic-localization) | AI translation with glossaries, style guides, quality evals, and a translations dashboard | -| [ai-shopping-assistant](./ai-shopping-assistant) | Ecommerce storefront with a Claude chatbot powered by Context MCP | -| [analytics-content-ops](./analytics-content-ops) | Analytics signal → Studio triage, GROQ intelligence rails, and Content Agent overnight | -| [knowledge-base](./knowledge-base) | Governed knowledge base feeding external and internal AI chat surfaces from one dataset | + +| Starter | Description | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| [agentic-localization](./agentic-localization) | AI translation with glossaries, style guides, quality evals, and a translations dashboard | +| [ai-shopping-assistant](./ai-shopping-assistant) | Ecommerce storefront with a Claude chatbot powered by Context MCP | +| [knowledge-base](./knowledge-base) | Governed knowledge base feeding external and internal AI chat surfaces from one dataset | +| [analytics-content-ops](./analytics-content-ops) | Analytics signal → Studio triage, GROQ intelligence rails, and Content Agent overnight | +| [commerce-plp-management](./commerce-plp-management) | Editorial merchandising layer over Shopify PLPs — curation, badges, facets, custom collections | ## Repo structure diff --git a/commerce-plp-management/.env.example b/commerce-plp-management/.env.example new file mode 100644 index 0000000..7b3e948 --- /dev/null +++ b/commerce-plp-management/.env.example @@ -0,0 +1,33 @@ +# Copy this file to .env and fill in your values. +# +# This root file is loaded by the blueprint deploy (sanity.blueprint.ts, via +# dotenv/config) and the push-sync Function tooling. It holds the Sanity project +# coordinates plus the Shopify Admin credentials the push-sync needs. +# Never commit .env (it is gitignored). + +# --- Sanity --------------------------------------------------------------- +# From sanity.io/manage. `sanity init --template` fills these in for you. +SANITY_STUDIO_PROJECT_ID= +SANITY_STUDIO_DATASET=production + +# Write token (Editor+). Used by the seed script and the push-sync Function to +# update syncStatus on documents. Create at sanity.io/manage -> API -> Tokens. +SANITY_API_WRITE_TOKEN= + +# --- Shopify Admin API (push-sync: writes the sanity_plp_collection metaobject) +# Sensitive: server/Function only, never shipped to the browser. +# App needs scopes: write_metaobjects, write_metaobject_definitions, read_products. +SHOPIFY_STORE_DOMAIN=your-store.myshopify.com + +# Dev Dashboard app: Client ID + Secret are exchanged for a short-lived Admin +# token automatically (client credentials grant). Find them in the Dev Dashboard +# under your app -> Settings. See: +# https://shopify.dev/docs/apps/build/dev-dashboard/get-api-access-tokens +SHOPIFY_CLIENT_ID= +SHOPIFY_CLIENT_SECRET= + +# Legacy alternative: store-level custom app static token (shpat_...). Use this +# INSTEAD of the client credentials above if your app provides a static token. +# SHOPIFY_ADMIN_API_TOKEN= + +SHOPIFY_ADMIN_API_VERSION=2025-07 diff --git a/commerce-plp-management/.github/workflows/ci.yml b/commerce-plp-management/.github/workflows/ci.yml new file mode 100644 index 0000000..e50c4cc --- /dev/null +++ b/commerce-plp-management/.github/workflows/ci.yml @@ -0,0 +1,58 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + build: + name: Build & Validate (Node ${{ matrix.node-version }}) + runs-on: ubuntu-latest + environment: commerce-plp-management + strategy: + matrix: + node-version: [20, 22] + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + - run: pnpm install + - name: Format check + run: pnpm run format:check + - name: Lint + run: pnpm run lint + - name: Typecheck + run: pnpm run typecheck + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + - name: Validate template + run: pnpm run validate + - name: Build functions + run: pnpm --filter @starter/functions build + - name: Manifest extract + run: pnpm --filter studio exec sanity manifest extract + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + - name: Check function bundle sizes + run: | + max_kb=512 + failed=0 + for dir in functions/dist/*/; do + bundle="$dir/index.js" + [ -f "$bundle" ] || continue + size_kb=$(( $(wc -c < "$bundle") / 1024 )) + name=$(basename "$dir") + if [ "$size_kb" -gt "$max_kb" ]; then + echo "::error::$name bundle is ${size_kb} KB (max ${max_kb} KB)" + failed=1 + else + echo "$name: ${size_kb} KB ✓" + fi + done + exit $failed diff --git a/commerce-plp-management/.github/workflows/deploy.yml b/commerce-plp-management/.github/workflows/deploy.yml new file mode 100644 index 0000000..2b18694 --- /dev/null +++ b/commerce-plp-management/.github/workflows/deploy.yml @@ -0,0 +1,78 @@ +name: Deploy + +# Deploys the Sanity-hosted surfaces on push to main. The Next.js storefront is +# deployed by Vercel (see "Deploying" in the README) — this workflow only builds +# it as a guard. +# +# Requires these GitHub Environment values (Settings → Environments): +# vars: SANITY_PROJECT_ID, SANITY_DATASET, SANITY_STACK_ID +# secrets: SANITY_AUTH_TOKEN + +on: + push: + branches: [main] + paths: + - 'studio/**' + - 'packages/@starter/**' + - 'functions/**' + - 'sanity.blueprint.ts' + - 'frontend/**' + +jobs: + studio: + name: Deploy Studio + runs-on: ubuntu-latest + environment: commerce-plp-management + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter studio run deploy + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + SANITY_AUTH_TOKEN: ${{ secrets.SANITY_AUTH_TOKEN }} + + blueprint: + name: Deploy Blueprint + runs-on: ubuntu-latest + environment: commerce-plp-management + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter @starter/functions run build + - name: Deploy blueprints + uses: sanity-io/blueprints-actions/deploy@deploy-v3 + with: + sanity-token: ${{ secrets.SANITY_AUTH_TOKEN }} + stack-id: ${{ vars.SANITY_STACK_ID }} + project-id: ${{ vars.SANITY_PROJECT_ID }} + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + + frontend: + name: Build Frontend + runs-on: ubuntu-latest + environment: commerce-plp-management + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter frontend build + env: + NEXT_PUBLIC_SANITY_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + NEXT_PUBLIC_SANITY_DATASET: ${{ vars.SANITY_DATASET }} diff --git a/commerce-plp-management/.gitignore b/commerce-plp-management/.gitignore new file mode 100644 index 0000000..bdaa949 --- /dev/null +++ b/commerce-plp-management/.gitignore @@ -0,0 +1,43 @@ +# Dependencies +node_modules/ + +# Environment files — only .env.example is committed +.env +.env.* +!.env.example + +# Temporary Sanity runtime, generated by the CLI +.sanity/ + +# Sanity Functions build output +.build/ + +# Compiled Sanity Studio +dist/ + +# Next.js build output and generated files +.next/ +next-env.d.ts + +# Logs +*.log + +# OS files +.DS_Store + +# IDE +.vscode/ +.idea/ + +# TypeScript +*.tsbuildinfo + +# Generated Sanity artifacts +schema.json +sanity.types.ts + +# Claude Code +.claude/ + +# Internal +notes/ diff --git a/commerce-plp-management/.npmrc b/commerce-plp-management/.npmrc new file mode 100644 index 0000000..6c59086 --- /dev/null +++ b/commerce-plp-management/.npmrc @@ -0,0 +1 @@ +enable-pre-post-scripts=true diff --git a/commerce-plp-management/.oxfmtrc.json b/commerce-plp-management/.oxfmtrc.json new file mode 100644 index 0000000..9f3f91d --- /dev/null +++ b/commerce-plp-management/.oxfmtrc.json @@ -0,0 +1,6 @@ +{ + "semi": false, + "singleQuote": true, + "printWidth": 100, + "bracketSpacing": false +} diff --git a/commerce-plp-management/AGENT.md b/commerce-plp-management/AGENT.md new file mode 100644 index 0000000..356b44a --- /dev/null +++ b/commerce-plp-management/AGENT.md @@ -0,0 +1,112 @@ +# Commerce PLP management — Agent Guide + +Merchandiser-controlled category pages as a Sanity enrichment layer on top of +Shopify. Presence-based: a `collectionEnrichment` document activates the editorial +layer for a handle; no document means the storefront renders pure Shopify output. + +## Stack + +- **Studio** — Sanity Studio v5 (`studio/`): `collectionEnrichment` + `productBadge`, product picker, sync-status badge, merchandiser Structure views, Presentation. +- **Frontend** — Next.js 16 + React 19 + Tailwind v4 (`frontend/`): the Sanity Swag Store PLP with parallel fetch + merge. +- **Functions** — Sanity Functions (`functions/`): push-sync to Shopify metaobjects + badge re-sync. +- **Shared logic** — framework-agnostic package (`packages/@starter/commerce/`): Shopify adapter, merge logic, metaobject contract. Imported by both the frontend and the Functions. + +## Commands (run from repo root) + +- `pnpm install` — install all workspaces +- `pnpm shopify:setup` — create the Shopify metaobject definition (one time) +- `pnpm bootstrap` — deploy blueprint + schema, typegen, seed +- `pnpm dev` — Studio (3333), frontend (3000), functions +- `pnpm typegen` / `pnpm typecheck` / `pnpm lint` / `pnpm format` / `pnpm validate` + +## Environment setup (three files, never committed) + +```sh +cp .env.example .env +cp studio/.env.example studio/.env +cp frontend/.env.example frontend/.env +``` + +| File | Who loads it | Must set | +| --------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `.env` (root) | `sanity.blueprint.ts` (`dotenv/config`) | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET`, `SHOPIFY_STORE_DOMAIN`, `SHOPIFY_CLIENT_ID`, `SHOPIFY_CLIENT_SECRET` | +| `studio/.env` | `studio/sanity.cli.ts` | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET`, `SANITY_STUDIO_SHOPIFY_*` | +| `frontend/.env` | Next.js | `NEXT_PUBLIC_SANITY_*`, `NEXT_PUBLIC_SHOPIFY_*` | + +**Admin credentials are sensitive** — root `.env` and Function runtime only, never +the browser. Dev Dashboard apps use `SHOPIFY_CLIENT_ID` + `SHOPIFY_CLIENT_SECRET` +(exchanged for a short-lived token at runtime via the client credentials grant); a +legacy static `SHOPIFY_ADMIN_API_TOKEN` also works. **Storefront token** is public +(Studio picker + storefront reads). + +## Code style + +- ESM-first (`"type": "module"`), no semicolons, single quotes, no bracket spacing +- Format with `oxfmt`, lint with `eslint` +- Shared configs in `packages/@starter/` (eslint, tsconfig, sanity-types, commerce) + +## Content model (the key decisions) + +- **`collectionEnrichment`** — one per handle. `collectionType` is + `shopify-native` (Shopify owns membership; Sanity layers editorial) or + `sanity-custom` (Sanity owns membership + order via `productList`; Shopify + supplies product data by GID batch). `handle` is immutable after first publish. +- **`productBadge`** — shared vocabulary. Referenced from + `collectionEnrichment.badges` via `->`, so label/color edits are live on the pull + path without republishing collections. +- **Product references are GIDs.** The `product` object stores `productGid` (the + join key) plus a cached title/image for Studio display only. The storefront + always reads live product data from Shopify by GID. +- **`syncStatus`** — system field written by the push-sync Function + (`never | pending | synced | failed`). Read-only for merchandisers; rendered as a + status card via `SyncStatusInput`. +- **`variantOverrides`** — AHEAD OF PRODUCT interim for audience-targeted PLPs, + resolved at the storefront edge (`frontend/lib/audience.ts`). Non-sensitive + segments only. Migration target: Content Variants — do not persist past GA. + +## The merge (heart of the storefront) + +`packages/@starter/commerce/src/merge.ts` → `mergeCollection({shopify, enrichment, audienceTag})`: + +1. `enrichment == null` → return Shopify output untouched (`enriched: false`). +2. Resolve the audience variant, then build a badge map (date-gated by `now`). +3. Order products (custom → `productList` order; native → Shopify order). +4. Move the faceout to grid position 0; inject editorial tiles at their positions. +5. Reorder facets: promoted (from `facetConfig`) first, with label overrides. + +The storefront calls it from `frontend/lib/collection.ts` after fetching the +enrichment (GROQ) and products (Shopify Storefront API) in parallel. + +## The push-sync (Sanity → Shopify) + +- `functions/collection-sync/` — on publish of a `collectionEnrichment`: mark + `pending`, fetch the shaped enrichment, `ensureMetaobjectDefinition` + + `upsertCollectionMetaobject` (Admin API), then stamp `synced` / `failed`. +- `functions/badge-resync/` — on publish of a `productBadge`: re-upsert the + metaobject for every referencing collection (closes the push-path currency gap). +- The metaobject contract (`sanity_plp_collection`) lives in + `packages/@starter/commerce/src/shopify/metaobject.ts` and is version-controlled. + `pnpm shopify:setup` creates the definition idempotently. + +## Deploying functions + +Build from `functions/`, deploy the blueprint from the **repo root**: + +```sh +pnpm --filter @starter/functions build +npx sanity blueprints deploy # from repo root, not functions/ +``` + +The blueprint injects `SHOPIFY_*` env onto the Function runtime from the root `.env`. + +## Studio surfaces + +- **Product picker** (`ProductPickerInput`) — searches the Shopify catalog by name + via the public Storefront token; stores the GID. Reused by faceout, badges, + productList, pinnedRecs. +- **Sync-status card** (`SyncStatusInput`) — green / yellow / red per document. +- **Structure** (`structure.ts`) — All collections, Enriched (native), Custom + campaign collections, Badge vocabulary. +- **GID validation** — async warning when `productList` / faceout GIDs are inactive + in Shopify (`lib/shopifyStudio.ts`). +- **Content Releases** — native; use for coordinated multi-collection campaigns. diff --git a/commerce-plp-management/CLAUDE.md b/commerce-plp-management/CLAUDE.md new file mode 120000 index 0000000..ac534a3 --- /dev/null +++ b/commerce-plp-management/CLAUDE.md @@ -0,0 +1 @@ +AGENT.md \ No newline at end of file diff --git a/commerce-plp-management/README.md b/commerce-plp-management/README.md new file mode 100644 index 0000000..11460c8 --- /dev/null +++ b/commerce-plp-management/README.md @@ -0,0 +1,213 @@ +# Commerce PLP management + +Give your merchandising team the keys to the category page. This Sanity starter +adds an **editorial enrichment layer on top of Shopify** so merchandisers control +product curation, in-grid storytelling, badges, facet order, and custom campaign +collections — without a developer ticket. + +```sh +pnpm create sanity@latest --template sanity-labs/starters/commerce-plp-management --package-manager pnpm +``` + +> Using npm? Run `npm create sanity@latest -- --template sanity-labs/starters/commerce-plp-management` (note the extra `--`). + +The demo is styled as the **Sanity Swag Store** ("Sanity Shop®") — a brutalist, +monospace storefront — running on top of your own Shopify catalog. + +> Shopify stays canonical for products, pricing, and inventory. Sanity owns the +> layer on top: banners, faceouts, editorial tiles, badges, facet order, and the +> custom collections the rule-based model can't express. + +## How it works + +**Presence-based enrichment.** One `collectionEnrichment` document per collection +handle. If the document exists, the storefront merges it over the Shopify output. +If it doesn't, the collection renders as **pure Shopify** — so you enrich your +highest-traffic collections first and expand coverage as evidence accumulates. + +``` +Merchandiser edits collectionEnrichment in Studio + │ publish + ▼ +Sanity Functions (push sync) ── writes sanity_plp_collection metaobject to Shopify + │ └─ stamps syncStatus (green / red) on the document + ▼ +┌───────────────┐ ┌──────────────────────────────┐ +│ Shopify │ │ Sanity CDN │ +│ products, │ │ collectionEnrichment doc │ +│ price, │ │ (banner, tiles, badges, │ +│ inventory, │ │ facets, faceout, variants) │ +│ metaobjects │ └───────────────┬──────────────┘ +└──────┬─────────┘ │ GROQ (enrichment by handle) + │ Storefront API │ + │ (by collection or GID batch) │ + └──────────────┬───────────────────┘ + ▼ parallel fetch + merge at render time + Headless storefront (Next.js) + null-check → pure Shopify, or merge faceout | tiles | badges | facets | banner +``` + +## What it demonstrates + +| Persona | In this starter | +| ------------------------- | ------------------------------------------------------------------------------------------------------------ | +| **Digital Merchandiser** | Enrich a collection: banner, faceout, editorial tiles, date-gated badges, promoted facets — in one document. | +| **Campaign Merchandiser** | Build a `sanity-custom` collection (gift guide) where Sanity owns membership and curation order. | +| **Campaign coordinator** | Stage many collections into a **Content Release** and publish the whole campaign at once. | +| **Commerce Developer** | One-time setup: metaobject definition, push-sync Function, storefront merge. Then hands off. | +| **Shopper** | The Sanity Swag Store PLP — faceout at position 0, editorial tiles interleaved, badges live on schedule. | + +## Getting started + +Prerequisites: **Node ≥ 20.19**, **pnpm 10**, and a **Shopify store** (Storefront +API access; Admin API access for push-sync). + +```sh +pnpm install + +# 1. Create the three env files +cp .env.example .env +cp studio/.env.example studio/.env +cp frontend/.env.example frontend/.env + +# 2. Fill them in (see "Environment variables" below) + +# 3. Create the Shopify metaobject definition (one time) +pnpm shopify:setup + +# 4. Deploy schema + functions, generate types, seed badges + example collections +pnpm bootstrap + +# 5. Run Studio (:3333) + storefront (:3000) + functions +pnpm dev +``` + +Products live in Shopify, so the seed only provisions the Sanity side: the shared +badge vocabulary plus two store-agnostic example collections — `clothing` +(shopify-native) and `holiday-gift-guide-2026` (sanity-custom, empty to start). +Open them in Studio and use the **product picker** to attach real products from +your store. Point the `clothing` collection's handle at a real collection handle +in your store to see the merge. + +> Want a fully-merchandised reference to explore? `pnpm seed:demo` imports the +> "Sanity Swag Store" demo (faceout, badges, editorial tiles, and a curated gift +> guide). Its product references use one specific catalog, so swap in your own +> product GIDs via the picker if items don't resolve. + +## Environment variables + +Each workspace loads its own env file (never committed). + +| File | Loaded by | Key vars | +| --------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `.env` (root) | Blueprint deploy (`dotenv/config`), `shopify:setup` | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET`, `SANITY_API_WRITE_TOKEN`, `SHOPIFY_STORE_DOMAIN`, `SHOPIFY_CLIENT_ID`, `SHOPIFY_CLIENT_SECRET` | +| `studio/.env` | Studio CLI + `sanity dev` | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET`, `SANITY_STUDIO_SHOPIFY_STORE_DOMAIN`, `SANITY_STUDIO_SHOPIFY_STOREFRONT_TOKEN` | +| `frontend/.env` | Next.js | `NEXT_PUBLIC_SANITY_PROJECT_ID`, `NEXT_PUBLIC_SANITY_DATASET`, `NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN`, `NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN` | + +The **Admin credentials are sensitive** — Dev Dashboard apps use a Client ID + +Secret that the client exchanges for a short-lived Admin token at runtime (see +[Shopify docs](https://shopify.dev/docs/apps/build/dev-dashboard/get-api-access-tokens)). +They live only in the root `.env` and on the Function runtime (injected by the +blueprint), never in the browser. A legacy static `SHOPIFY_ADMIN_API_TOKEN` is +also supported. The **Storefront token** is public and safe in the Studio and frontend. + +## Deploying + +Three surfaces, deployed independently. + +### Studio + Functions (Sanity-hosted) + +```sh +# Studio → *.sanity.studio +pnpm --filter studio exec sanity deploy + +# Functions (push-sync) via the blueprint +pnpm --filter @starter/functions build +npx sanity blueprints deploy # from the repo root +``` + +CI can do this on push to `main` — see [`.github/workflows/deploy.yml`](./.github/workflows/deploy.yml), which needs `SANITY_PROJECT_ID`, `SANITY_DATASET`, `SANITY_STACK_ID` (vars) and `SANITY_AUTH_TOKEN` (secret) on a GitHub Environment. + +### Storefront (Vercel) + +The Next.js storefront deploys to Vercel. Import the repo at +[vercel.com/new](https://vercel.com/new) and configure: + +| Setting | Value | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Framework Preset** | Next.js | +| **Root Directory** | `commerce-plp-management/frontend` (or just `frontend` if you cloned via `sanity init --template`) — enable _Include files outside the root directory_ so the pnpm workspace resolves | +| **Build Command** | default (`next build`) | +| **Install Command** | default (`pnpm install`) | + +Add these **Environment Variables** (Production + Preview): + +| Variable | Notes | +| -------------------------------------------- | -------------------------------------------------- | +| `NEXT_PUBLIC_SANITY_PROJECT_ID` | | +| `NEXT_PUBLIC_SANITY_DATASET` | | +| `NEXT_PUBLIC_SANITY_API_VERSION` | e.g. `2025-07-13` | +| `SANITY_API_READ_TOKEN` | Viewer token — enables draft mode / Visual Editing | +| `NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN` | `your-store.myshopify.com` | +| `NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN` | public Storefront token | +| `NEXT_PUBLIC_SHOPIFY_STOREFRONT_API_VERSION` | e.g. `2025-07` | + +After the first deploy, add your Vercel domain to the project's CORS origins at +[sanity.io/manage](https://www.sanity.io/manage) (API → CORS origins) so Sanity +Live and Presentation can connect. + +> The **Shopify Admin** credentials (`SHOPIFY_CLIENT_ID/SECRET`) are **not** set on +> Vercel — push-sync runs in Sanity Functions, which get them from the blueprint. + +## Project structure + +``` +commerce-plp-management/ +├── studio/ # Sanity Studio v5 +│ ├── schemaTypes/ +│ │ ├── documents/ # collectionEnrichment, productBadge +│ │ └── objects/ # banner, faceout, editorialTile, badgeAssignment, facetConfig, variantOverride, product, syncState +│ ├── components/ # ProductPickerInput, SyncStatusInput +│ ├── structure.ts # merchandiser views (native / custom / vocabulary) +│ └── seed/ # badges + example collections +├── frontend/ # Next.js 16 + React 19 + Tailwind v4 (Sanity Swag Store) +│ ├── app/collections/[handle]/ # the PLP (parallel fetch + merge + null-check) +│ ├── lib/ # collection merge orchestration, audience, shopify client +│ └── components/ # Banner, ProductGrid, ProductCard, EditorialTileCard, BadgePill, FacetRail +├── functions/ # Sanity Functions (push sync) +│ ├── collection-sync/ # collectionEnrichment publish → Shopify metaobject + syncStatus +│ └── badge-resync/ # productBadge publish → re-sync affected collections +├── packages/@starter/commerce/ # framework-agnostic Shopify adapter + merge logic + metaobject contract +├── scripts/setup-metaobject.ts # one-time Shopify metaobject definition +└── sanity.blueprint.ts # functions + robot token +``` + +## Scripts + +| Command | Description | +| ---------------------- | -------------------------------------------------------- | +| `pnpm dev` | Studio + storefront + functions concurrently | +| `pnpm shopify:setup` | Create the `sanity_plp_collection` metaobject definition | +| `pnpm bootstrap` | Deploy blueprint + schema, typegen, seed | +| `pnpm seed` | Seed badge vocabulary + example collections | +| `pnpm seed:demo` | Seed the fully-merchandised "Sanity Swag Store" demo | +| `pnpm build` | Build all workspaces | +| `pnpm typegen` | Regenerate Sanity TypeGen types | +| `pnpm typecheck` | Type-check all workspaces | +| `pnpm lint` / `format` | Lint / format | +| `pnpm validate` | Validate the starter template structure | + +## Key design decisions + +- **One metaobject per collection, not per-product metafields.** The push-sync + writes a single `sanity_plp_collection` metaobject so the whole payload lands in + one Admin API call and is readable by the Shopify ecosystem. The definition is + version-controlled in `@starter/commerce` and treated as a contract. +- **Sanity is the authority for custom collection membership.** For + `sanity-custom` collections, Sanity owns which products are in the collection and + in what order; Shopify supplies live product data by GID batch. +- **Interim `variantOverrides` for personalization.** Audience-targeted PLPs use an + inline override array resolved at the storefront edge from a first-party cookie — + the designed interim ahead of Content Variants. Non-sensitive segments only. + +See [`AGENT.md`](./AGENT.md) for the full agent-facing guide. diff --git a/commerce-plp-management/eslint.config.mjs b/commerce-plp-management/eslint.config.mjs new file mode 100644 index 0000000..164f049 --- /dev/null +++ b/commerce-plp-management/eslint.config.mjs @@ -0,0 +1,8 @@ +import config from '@starter/eslint-config' + +export default [ + { + ignores: ['functions/**/vendor/', '**/dist/', '**/.sanity/', '**/sanity.types.ts', '**/.next/'], + }, + ...config, +] diff --git a/commerce-plp-management/frontend/.env.example b/commerce-plp-management/frontend/.env.example new file mode 100644 index 0000000..4c1cd26 --- /dev/null +++ b/commerce-plp-management/frontend/.env.example @@ -0,0 +1,25 @@ +# Copy this file to .env and fill in your values. +# Loaded by Next.js. + +# --- Sanity --------------------------------------------------------------- +NEXT_PUBLIC_SANITY_PROJECT_ID= +NEXT_PUBLIC_SANITY_DATASET=production + +# API version for the Sanity client (YYYY-MM-DD) +NEXT_PUBLIC_SANITY_API_VERSION=2025-07-13 + +# Read token with Viewer permissions, for draft mode / visual editing. +# Create at sanity.io/manage -> API -> Tokens. +# SANITY_API_READ_TOKEN= + +# Studio URL for the "Open in Studio" links / presentation origin. +# NEXT_PUBLIC_SANITY_STUDIO_URL=http://localhost:3333 + +# --- Shopify Storefront API (products, price, inventory, collections) -------- +# Public Storefront token. Safe to expose to the storefront runtime. +# Dev Dashboard apps don't show a static Storefront token — mint one with +# `pnpm shopify:storefront-token` (uses the Admin creds in the root .env). +# The Admin Client ID/Secret stay in the ROOT .env only, never here. +NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN=your-store.myshopify.com +NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN= +NEXT_PUBLIC_SHOPIFY_STOREFRONT_API_VERSION=2025-07 diff --git a/commerce-plp-management/frontend/app/api/draft-mode/enable/route.ts b/commerce-plp-management/frontend/app/api/draft-mode/enable/route.ts new file mode 100644 index 0000000..cf44886 --- /dev/null +++ b/commerce-plp-management/frontend/app/api/draft-mode/enable/route.ts @@ -0,0 +1,7 @@ +import {defineEnableDraftMode} from 'next-sanity/draft-mode' + +import {client, token} from '@/sanity/client' + +export const {GET} = defineEnableDraftMode({ + client: client.withConfig({token}), +}) diff --git a/commerce-plp-management/frontend/app/collections/[handle]/page.tsx b/commerce-plp-management/frontend/app/collections/[handle]/page.tsx new file mode 100644 index 0000000..69c6ff5 --- /dev/null +++ b/commerce-plp-management/frontend/app/collections/[handle]/page.tsx @@ -0,0 +1,72 @@ +import {notFound} from 'next/navigation' +import Link from 'next/link' + +import {getAudienceTag} from '@/lib/audience' +import {isShopifyConfigured} from '@/lib/shopify' +import {getMergedCollection} from '@/lib/collection' +import {Banner} from '@/components/Banner' +import {FacetRail} from '@/components/FacetRail' +import {ProductGrid} from '@/components/ProductGrid' + +export default async function CollectionPage({params}: {params: Promise<{handle: string}>}) { + const {handle} = await params + + if (!isShopifyConfigured()) { + return ( +
+
+ Setup +

Connect your Shopify store

+

+ Set NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN and{' '} + NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN in frontend/.env to load + products for this collection. +

+
+
+ ) + } + + const audienceTag = await getAudienceTag() + const collection = await getMergedCollection(handle, audienceTag) + + if (!collection) notFound() + + const productCount = collection.grid.filter((item) => item.kind === 'product').length + const hasFacets = collection.facets.length > 0 + + return ( +
+
+ + ← All collections + + {collection.enriched ? 'Enriched' : 'Pure Shopify'} + {collection.collectionType === 'sanity-custom' ? ( + Sanity-authored membership + ) : null} +
+ + {collection.banner ? ( +
+ +
+ ) : ( +

{collection.title}

+ )} + +
+ {hasFacets ? : null} +
+
+

{collection.title}

+ + {productCount} products + +
+ +
+
+
+ ) +} diff --git a/commerce-plp-management/frontend/app/globals.css b/commerce-plp-management/frontend/app/globals.css new file mode 100644 index 0000000..cbd279e --- /dev/null +++ b/commerce-plp-management/frontend/app/globals.css @@ -0,0 +1,55 @@ +@import 'tailwindcss'; +@plugin '@tailwindcss/typography'; + +/* + * Sanity Swag Store — brutalist, monospace, high-contrast color blocks. + * Palette pulls from the Sanity brand (warm near-black #0b0b0b, brand orange + * #ff560a) plus the swag-store poster colors: vivid yellow, blue, and gray. + */ +@theme { + --color-swag-yellow: #f5df00; + --color-swag-orange: #ff560a; + --color-swag-blue: #2540ff; + --color-swag-black: #0b0b0b; + --color-swag-gray: #7c7c7c; + --color-swag-paper: #ffffff; + + --font-mono: var(--font-plex-mono), ui-monospace, 'SF Mono', Menlo, monospace; + --font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif; + + --radius-sharp: 0px; +} + +:root { + color-scheme: light; +} + +body { + background: var(--color-swag-paper); + color: var(--color-swag-black); +} + +/* Poster-style metadata label: black chip, mono, uppercase. */ +.chip { + display: inline-flex; + align-items: center; + gap: 0.375rem; + background: var(--color-swag-black); + color: #fff; + font-family: var(--font-mono); + font-size: 0.6875rem; + letter-spacing: 0.08em; + text-transform: uppercase; + padding: 0.25rem 0.5rem; + line-height: 1; +} + +/* Halftone dot texture used behind color blocks. */ +.halftone { + background-image: radial-gradient(rgba(11, 11, 11, 0.18) 1px, transparent 1.2px); + background-size: 6px 6px; +} + +.hairline { + border: 1px solid var(--color-swag-black); +} diff --git a/commerce-plp-management/frontend/app/layout.tsx b/commerce-plp-management/frontend/app/layout.tsx new file mode 100644 index 0000000..dac9889 --- /dev/null +++ b/commerce-plp-management/frontend/app/layout.tsx @@ -0,0 +1,41 @@ +import './globals.css' + +import type {Metadata} from 'next' +import {Inter, IBM_Plex_Mono} from 'next/font/google' +import {draftMode} from 'next/headers' +import {VisualEditing} from 'next-sanity/visual-editing' + +import {SanityLive} from '@/sanity/live' +import {getAudienceTag} from '@/lib/audience' +import {SiteHeader} from '@/components/SiteHeader' +import {SiteFooter} from '@/components/SiteFooter' + +const inter = Inter({subsets: ['latin'], variable: '--font-inter'}) +const plexMono = IBM_Plex_Mono({ + subsets: ['latin'], + weight: ['400', '500', '600'], + variable: '--font-plex-mono', +}) + +export const metadata: Metadata = { + title: 'Sanity Shop® — Commerce PLP management', + description: + 'A Sanity Swag Store demo: merchandiser-controlled category pages on top of Shopify.', +} + +export default async function RootLayout({children}: {children: React.ReactNode}) { + const {isEnabled: isDraftMode} = await draftMode() + const audienceTag = await getAudienceTag() + + return ( + + + +
{children}
+ + + {isDraftMode && } + + + ) +} diff --git a/commerce-plp-management/frontend/app/page.tsx b/commerce-plp-management/frontend/app/page.tsx new file mode 100644 index 0000000..b17d3cb --- /dev/null +++ b/commerce-plp-management/frontend/app/page.tsx @@ -0,0 +1,60 @@ +import {sanityFetch} from '@/sanity/live' +import {allCollectionsQuery} from '@/sanity/queries' +import {CollectionCard} from '@/components/CollectionCard' +import {themeClasses} from '@/components/theme' + +const HERO_BLOCKS = [ + {theme: 'yellow', label: 'The Content Operating System'}, + {theme: 'gray', label: 'Merchandised in Sanity'}, + {theme: 'orange', label: 'Shipped from Shopify'}, + {theme: 'blue', label: 'No developer ticket'}, +] as const + +export default async function HomePage() { + const {data: collections} = await sanityFetch({query: allCollectionsQuery}) + + return ( +
+
+ {HERO_BLOCKS.map((block) => { + const t = themeClasses(block.theme) + return ( +
+

{block.label}

+
+ ) + })} +
+ +
+

Collections

+ + {collections.length} enriched + +
+ + {collections.length === 0 ? ( +
+ No collections yet. Run pnpm seed to add the + demo collections, then open Studio to attach products. +
+ ) : ( +
+ {collections.map((c) => ( + + ))} +
+ )} +
+ ) +} diff --git a/commerce-plp-management/frontend/components/AudienceSwitcher.tsx b/commerce-plp-management/frontend/components/AudienceSwitcher.tsx new file mode 100644 index 0000000..c930915 --- /dev/null +++ b/commerce-plp-management/frontend/components/AudienceSwitcher.tsx @@ -0,0 +1,49 @@ +'use client' + +import {useRouter} from 'next/navigation' +import {useTransition} from 'react' + +const COOKIE = 'swag_audience' + +const SEGMENTS = [ + {tag: '', label: 'Guest'}, + {tag: 'loyalty-member', label: 'Loyalty'}, +] + +/** + * Demo control for the interim variantOverrides personalization. Sets the + * first-party audience cookie the storefront reads at the edge. In production + * the segment comes from your identity/edge layer, not a visible switcher. + */ +export function AudienceSwitcher({current}: {current: string | null}) { + const router = useRouter() + const [pending, startTransition] = useTransition() + + function select(tag: string) { + document.cookie = `${COOKIE}=${tag}; path=/; max-age=${tag ? 60 * 60 * 24 * 30 : 0}` + startTransition(() => router.refresh()) + } + + return ( +
+ + Audience + + {SEGMENTS.map((seg) => { + const active = (current ?? '') === seg.tag + return ( + + ) + })} +
+ ) +} diff --git a/commerce-plp-management/frontend/components/BadgePill.tsx b/commerce-plp-management/frontend/components/BadgePill.tsx new file mode 100644 index 0000000..f7f1782 --- /dev/null +++ b/commerce-plp-management/frontend/components/BadgePill.tsx @@ -0,0 +1,21 @@ +import type {ResolvedBadge} from '@starter/commerce/types' + +const BADGE_BG: Record = { + sale: 'bg-swag-orange text-swag-black', + new: 'bg-swag-blue text-white', + 'final-sale': 'bg-swag-black text-white', + 'best-seller': 'bg-swag-yellow text-swag-black', + neutral: 'bg-swag-gray text-white', +} + +export function BadgePill({badge}: {badge: ResolvedBadge}) { + const cls = BADGE_BG[badge.color] ?? BADGE_BG.neutral + return ( + + {badge.icon ? {badge.icon} : null} + {badge.label} + + ) +} diff --git a/commerce-plp-management/frontend/components/Banner.tsx b/commerce-plp-management/frontend/components/Banner.tsx new file mode 100644 index 0000000..a93a551 --- /dev/null +++ b/commerce-plp-management/frontend/components/Banner.tsx @@ -0,0 +1,41 @@ +import type {Banner as BannerType} from '@starter/commerce/types' +import {themeClasses} from './theme' + +export function Banner({banner, audienceTag}: {banner: BannerType; audienceTag: string | null}) { + const t = themeClasses(banner.theme) + + return ( +
+
+ {banner.imageUrl ? ( + {banner.headline + ) : null} + +
+ {audienceTag ? ( + Audience · {audienceTag} + ) : ( + Collection + )} + {banner.headline ? ( +

+ {banner.headline} +

+ ) : null} + {banner.subhead ?

{banner.subhead}

: null} + {banner.ctaLabel ? ( + + {banner.ctaLabel} → + + ) : null} +
+
+ ) +} diff --git a/commerce-plp-management/frontend/components/CollectionCard.tsx b/commerce-plp-management/frontend/components/CollectionCard.tsx new file mode 100644 index 0000000..d0f151f --- /dev/null +++ b/commerce-plp-management/frontend/components/CollectionCard.tsx @@ -0,0 +1,46 @@ +import Link from 'next/link' +import {themeClasses, type ThemeValue} from './theme' + +type CollectionCardProps = { + handle: string + title: string + collectionType: 'shopify-native' | 'sanity-custom' + theme: ThemeValue + imageUrl?: string | null +} + +export function CollectionCard({ + handle, + title, + collectionType, + theme, + imageUrl, +}: CollectionCardProps) { + const t = themeClasses(theme) + + return ( + +
+ {imageUrl ? ( + + ) : null} + +
+ {collectionType === 'sanity-custom' ? 'Custom' : 'Collection'} +
+
+

{title}

+ + Select {title} → + +
+ + ) +} diff --git a/commerce-plp-management/frontend/components/EditorialTileCard.tsx b/commerce-plp-management/frontend/components/EditorialTileCard.tsx new file mode 100644 index 0000000..e9babd4 --- /dev/null +++ b/commerce-plp-management/frontend/components/EditorialTileCard.tsx @@ -0,0 +1,44 @@ +import type {ComponentProps} from 'react' +import {PortableText} from '@portabletext/react' +import type {EditorialTile} from '@starter/commerce/types' +import {themeClasses} from './theme' + +type PortableTextValue = ComponentProps['value'] + +export function EditorialTileCard({tile}: {tile: EditorialTile}) { + const t = themeClasses(tile.theme) + + return ( +
+ Editorial + + {tile.imageUrl ? ( + {tile.headline + ) : null} + +
+ {tile.headline ? ( +

{tile.headline}

+ ) : null} + {tile.body ? ( +
+ +
+ ) : null} + {tile.ctaLabel ? ( + + {tile.ctaLabel} → + + ) : null} +
+
+ ) +} diff --git a/commerce-plp-management/frontend/components/FacetRail.tsx b/commerce-plp-management/frontend/components/FacetRail.tsx new file mode 100644 index 0000000..81c22f3 --- /dev/null +++ b/commerce-plp-management/frontend/components/FacetRail.tsx @@ -0,0 +1,36 @@ +import type {MergedFacet} from '@starter/commerce/types' + +/** Non-interactive facet rail — demonstrates merchandiser-controlled order. */ +export function FacetRail({facets}: {facets: MergedFacet[]}) { + if (!facets.length) return null + + return ( + + ) +} diff --git a/commerce-plp-management/frontend/components/ProductCard.tsx b/commerce-plp-management/frontend/components/ProductCard.tsx new file mode 100644 index 0000000..a043a54 --- /dev/null +++ b/commerce-plp-management/frontend/components/ProductCard.tsx @@ -0,0 +1,59 @@ +import type {GridProductItem} from '@starter/commerce/types' +import {formatMoney} from './format' +import {BadgePill} from './BadgePill' + +export function ProductCard({item}: {item: GridProductItem}) { + const {product, badges, isFaceout, faceoutHeadline, faceoutImageUrl} = item + const imageUrl = faceoutImageUrl || product.featuredImage?.url + const onSale = product.compareAtPrice && product.compareAtPrice.amount > product.price.amount + + return ( +
+ {(badges.length > 0 || isFaceout) && ( +
+ {isFaceout ? Faceout : null} + {badges.map((b, i) => ( + + ))} +
+ )} + +
+ {imageUrl ? ( + {product.featuredImage?.altText + ) : ( +
+ NO IMAGE +
+ )} +
+ +
+ {faceoutHeadline ? ( +

+ {faceoutHeadline} +

+ ) : null} +

{product.title}

+
+ {formatMoney(product.price)} + {onSale && product.compareAtPrice ? ( + + {formatMoney(product.compareAtPrice)} + + ) : null} + {!product.availableForSale ? ( + Sold out + ) : null} +
+
+
+ ) +} diff --git a/commerce-plp-management/frontend/components/ProductGrid.tsx b/commerce-plp-management/frontend/components/ProductGrid.tsx new file mode 100644 index 0000000..360b964 --- /dev/null +++ b/commerce-plp-management/frontend/components/ProductGrid.tsx @@ -0,0 +1,25 @@ +import type {GridItem} from '@starter/commerce/types' +import {ProductCard} from './ProductCard' +import {EditorialTileCard} from './EditorialTileCard' + +export function ProductGrid({grid}: {grid: GridItem[]}) { + if (!grid.length) { + return ( +
+ No products in this collection yet. +
+ ) + } + + return ( +
+ {grid.map((item, index) => + item.kind === 'product' ? ( + + ) : ( + + ), + )} +
+ ) +} diff --git a/commerce-plp-management/frontend/components/SiteFooter.tsx b/commerce-plp-management/frontend/components/SiteFooter.tsx new file mode 100644 index 0000000..49e1dc9 --- /dev/null +++ b/commerce-plp-management/frontend/components/SiteFooter.tsx @@ -0,0 +1,21 @@ +export function SiteFooter({itemCount = 0, total = '$0'}: {itemCount?: number; total?: string}) { + return ( +
+
+ Sanity + Shop® +
+
+ + Total ({itemCount}): {total} + + +
+
+ ) +} diff --git a/commerce-plp-management/frontend/components/SiteHeader.tsx b/commerce-plp-management/frontend/components/SiteHeader.tsx new file mode 100644 index 0000000..5d88fc6 --- /dev/null +++ b/commerce-plp-management/frontend/components/SiteHeader.tsx @@ -0,0 +1,25 @@ +import Link from 'next/link' +import {AudienceSwitcher} from './AudienceSwitcher' + +export function SiteHeader({audienceTag}: {audienceTag: string | null}) { + return ( +
+
+ + Sanity + + Shop® +
+ + +
+ ) +} diff --git a/commerce-plp-management/frontend/components/format.ts b/commerce-plp-management/frontend/components/format.ts new file mode 100644 index 0000000..b3d6a77 --- /dev/null +++ b/commerce-plp-management/frontend/components/format.ts @@ -0,0 +1,12 @@ +import type {Money} from '@starter/commerce/types' + +export function formatMoney(money: Money): string { + try { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: money.currencyCode || 'USD', + }).format(money.amount) + } catch { + return `$${money.amount.toFixed(2)}` + } +} diff --git a/commerce-plp-management/frontend/components/theme.ts b/commerce-plp-management/frontend/components/theme.ts new file mode 100644 index 0000000..f11ea69 --- /dev/null +++ b/commerce-plp-management/frontend/components/theme.ts @@ -0,0 +1,15 @@ +export type ThemeValue = 'yellow' | 'orange' | 'blue' | 'black' | 'gray' | string | null | undefined + +type ThemeClasses = {bg: string; text: string; isDark: boolean} + +const MAP: Record = { + yellow: {bg: 'bg-swag-yellow', text: 'text-swag-black', isDark: false}, + orange: {bg: 'bg-swag-orange', text: 'text-swag-black', isDark: false}, + blue: {bg: 'bg-swag-blue', text: 'text-white', isDark: true}, + black: {bg: 'bg-swag-black', text: 'text-white', isDark: true}, + gray: {bg: 'bg-swag-gray', text: 'text-white', isDark: true}, +} + +export function themeClasses(theme: ThemeValue): ThemeClasses { + return MAP[theme ?? 'yellow'] ?? MAP.yellow +} diff --git a/commerce-plp-management/frontend/lib/audience.ts b/commerce-plp-management/frontend/lib/audience.ts new file mode 100644 index 0000000..f2d7597 --- /dev/null +++ b/commerce-plp-management/frontend/lib/audience.ts @@ -0,0 +1,15 @@ +import {cookies} from 'next/headers' + +export const AUDIENCE_COOKIE = 'swag_audience' + +/** + * Resolve the visitor's audience segment at the edge from a first-party cookie. + * + * INTERIM: this is the storefront-side resolution for the ahead-of-product + * variantOverrides pattern. When Content Variants ships, the API resolves the + * correct variant and this cookie lookup goes away. + */ +export async function getAudienceTag(): Promise { + const store = await cookies() + return store.get(AUDIENCE_COOKIE)?.value ?? null +} diff --git a/commerce-plp-management/frontend/lib/collection.ts b/commerce-plp-management/frontend/lib/collection.ts new file mode 100644 index 0000000..d6dfa7c --- /dev/null +++ b/commerce-plp-management/frontend/lib/collection.ts @@ -0,0 +1,73 @@ +import {mergeCollection, type CollectionEnrichment, type MergedCollection} from '@starter/commerce' +import type {ShopifyCollection} from '@starter/commerce/types' +import {sanityFetch} from '@/sanity/live' +import {collectionEnrichmentQuery} from '@/sanity/queries' +import {getStorefront} from './shopify' + +type RawEnrichment = { + handle: string + collectionType: 'shopify-native' | 'sanity-custom' + title?: string | null + banner?: CollectionEnrichment['banner'] + faceout?: CollectionEnrichment['faceout'] + editorialTiles?: CollectionEnrichment['editorialTiles'] + badges?: CollectionEnrichment['badges'] + facetConfig?: CollectionEnrichment['facetConfig'] + productList?: {productGid: string}[] | null + variantOverrides?: CollectionEnrichment['variantOverrides'] + syncStatus?: CollectionEnrichment['syncStatus'] +} + +/** Array order is the curation order; derive explicit positions for the merge. */ +function mapEnrichment(raw: RawEnrichment): CollectionEnrichment { + return { + ...raw, + title: raw.title ?? undefined, + productList: raw.productList?.map((entry, index) => ({ + productGid: entry.productGid, + position: index, + })), + } +} + +/** + * Fetch a collection and merge the Sanity enrichment over the Shopify catalog. + * + * Runs the two systems in parallel semantics: + * - Sanity: the enrichment document (may be null → pure Shopify output). + * - Shopify: product data. For sanity-custom collections membership comes from + * Sanity (GID batch); otherwise Shopify owns membership by handle. + */ +export async function getMergedCollection( + handle: string, + audienceTag: string | null, +): Promise { + const {data: rawEnrichment} = await sanityFetch({ + query: collectionEnrichmentQuery, + params: {handle}, + }) + + const enrichment = rawEnrichment ? mapEnrichment(rawEnrichment as RawEnrichment) : null + const storefront = getStorefront() + + let shopify: ShopifyCollection | null + + if (enrichment?.collectionType === 'sanity-custom') { + const gids = enrichment.productList?.map((p) => p.productGid).filter(Boolean) ?? [] + const products = await storefront.getProductsByIds(gids) + shopify = { + id: `sanity-custom:${handle}`, + handle, + title: enrichment.title || handle, + description: null, + products, + facets: [], + } + } else { + shopify = await storefront.getCollectionByHandle(handle) + } + + if (!shopify) return null + + return mergeCollection({shopify, enrichment, audienceTag}) +} diff --git a/commerce-plp-management/frontend/lib/shopify.ts b/commerce-plp-management/frontend/lib/shopify.ts new file mode 100644 index 0000000..eff5b09 --- /dev/null +++ b/commerce-plp-management/frontend/lib/shopify.ts @@ -0,0 +1,28 @@ +import {createStorefrontClient, type StorefrontClient} from '@starter/commerce/shopify' + +let cached: StorefrontClient | null = null + +export function isShopifyConfigured(): boolean { + return Boolean( + process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN && + process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN, + ) +} + +/** Storefront client built from NEXT_PUBLIC_SHOPIFY_* env. Memoized per process. */ +export function getStorefront(): StorefrontClient { + if (cached) return cached + const domain = process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN + const token = process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN + if (!domain || !token) { + throw new Error( + 'Shopify is not configured. Set NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN and NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN in frontend/.env', + ) + } + cached = createStorefrontClient({ + domain, + token, + apiVersion: process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_API_VERSION || '2025-07', + }) + return cached +} diff --git a/commerce-plp-management/frontend/next.config.ts b/commerce-plp-management/frontend/next.config.ts new file mode 100644 index 0000000..f5c3cb7 --- /dev/null +++ b/commerce-plp-management/frontend/next.config.ts @@ -0,0 +1,11 @@ +import type {NextConfig} from 'next' + +const config: NextConfig = { + // @starter/commerce ships TypeScript source; transpile it for the server bundle. + transpilePackages: ['@starter/commerce'], + images: { + remotePatterns: [{hostname: 'cdn.sanity.io'}, {hostname: 'cdn.shopify.com'}], + }, +} + +export default config diff --git a/commerce-plp-management/frontend/package.json b/commerce-plp-management/frontend/package.json new file mode 100644 index 0000000..0764b15 --- /dev/null +++ b/commerce-plp-management/frontend/package.json @@ -0,0 +1,33 @@ +{ + "name": "frontend", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "next lint", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@portabletext/react": "^3.2.1", + "@sanity/image-url": "^1.1.0", + "@starter/commerce": "workspace:*", + "@starter/sanity-types": "workspace:*", + "next": "^16.1.6", + "next-sanity": "^12.1.1", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@starter/tsconfig": "workspace:*", + "@tailwindcss/postcss": "^4.2.1", + "@tailwindcss/typography": "^0.5.19", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "postcss": "^8.5.8", + "tailwindcss": "^4.2.1", + "typescript": "catalog:" + } +} diff --git a/commerce-plp-management/frontend/postcss.config.mjs b/commerce-plp-management/frontend/postcss.config.mjs new file mode 100644 index 0000000..a7f73a2 --- /dev/null +++ b/commerce-plp-management/frontend/postcss.config.mjs @@ -0,0 +1,5 @@ +export default { + plugins: { + '@tailwindcss/postcss': {}, + }, +} diff --git a/commerce-plp-management/frontend/sanity/client.ts b/commerce-plp-management/frontend/sanity/client.ts new file mode 100644 index 0000000..6ec7620 --- /dev/null +++ b/commerce-plp-management/frontend/sanity/client.ts @@ -0,0 +1,13 @@ +import {createClient} from 'next-sanity' + +export const client = createClient({ + projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, + dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, + apiVersion: process.env.NEXT_PUBLIC_SANITY_API_VERSION || '2025-07-13', + useCdn: true, + stega: { + studioUrl: process.env.NEXT_PUBLIC_SANITY_STUDIO_URL || '/studio', + }, +}) + +export const token = process.env.SANITY_API_READ_TOKEN diff --git a/commerce-plp-management/frontend/sanity/image.ts b/commerce-plp-management/frontend/sanity/image.ts new file mode 100644 index 0000000..607c034 --- /dev/null +++ b/commerce-plp-management/frontend/sanity/image.ts @@ -0,0 +1,8 @@ +import imageUrlBuilder from '@sanity/image-url' +import {client} from './client' + +const builder = imageUrlBuilder(client) + +export function urlForImage(source: Parameters[0]) { + return builder.image(source) +} diff --git a/commerce-plp-management/frontend/sanity/live.ts b/commerce-plp-management/frontend/sanity/live.ts new file mode 100644 index 0000000..43e151f --- /dev/null +++ b/commerce-plp-management/frontend/sanity/live.ts @@ -0,0 +1,11 @@ +import {defineLive} from 'next-sanity/live' + +// Load the generated query-result augmentation so sanityFetch is fully typed. +import '@starter/sanity-types' +import {client, token} from '@/sanity/client' + +export const {sanityFetch, SanityLive} = defineLive({ + client, + serverToken: token, + browserToken: token, +}) diff --git a/commerce-plp-management/frontend/sanity/queries.ts b/commerce-plp-management/frontend/sanity/queries.ts new file mode 100644 index 0000000..38d6c22 --- /dev/null +++ b/commerce-plp-management/frontend/sanity/queries.ts @@ -0,0 +1,58 @@ +import {defineQuery} from 'next-sanity' + +// Banner / faceout / tile projections, reused by the base doc and variant overrides. +const BANNER = `{"imageUrl": image.asset->url, headline, subhead, ctaLabel, ctaHref, theme}` +const FACEOUT = `{ + "productGid": product.productGid, + variantGid, + editorialHeadline, + "imageUrlOverride": imageOverride.asset->url +}` +const TILES = `{position, "imageUrl": image.asset->url, headline, body, ctaLabel, ctaHref, theme}` + +/** + * Enrichment for a single collection handle. Presence of this document activates + * the editorial layer; a null result means the storefront renders pure Shopify. + * Badges resolve the shared vocabulary via `->` so label/color edits are live. + */ +export const collectionEnrichmentQuery = defineQuery(` + *[_type == "collectionEnrichment" && handle.current == $handle][0]{ + "handle": handle.current, + collectionType, + title, + banner ${BANNER}, + faceout ${FACEOUT}, + editorialTiles[] ${TILES}, + badges[]{ + "productGid": product.productGid, + "badge": badge->{"slug": slug.current, label, color, icon}, + customLabel, + startDate, + endDate + }, + facetConfig[]{facetHandle, labelOverride}, + productList[]{"productGid": productGid}, + variantOverrides[]{ + audienceTag, + banner ${BANNER}, + faceout ${FACEOUT}, + editorialTiles[] ${TILES} + }, + "syncStatus": syncStatus.status + } +`) + +/** All enrichment documents, for the store landing page and route generation. */ +export const allCollectionsQuery = defineQuery(` + *[_type == "collectionEnrichment" && defined(handle.current)] | order(handle.current asc){ + "handle": handle.current, + "title": coalesce(title, handle.current), + collectionType, + "bannerImageUrl": banner.image.asset->url, + "theme": coalesce(banner.theme, "yellow") + } +`) + +export const collectionHandlesQuery = defineQuery(` + *[_type == "collectionEnrichment" && defined(handle.current)]{"handle": handle.current} +`) diff --git a/commerce-plp-management/frontend/tsconfig.json b/commerce-plp-management/frontend/tsconfig.json new file mode 100644 index 0000000..bf9927b --- /dev/null +++ b/commerce-plp-management/frontend/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@starter/tsconfig/base.json", + "compilerOptions": { + "plugins": [{"name": "next"}], + "paths": {"@/*": ["./*"]} + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/commerce-plp-management/functions/badge-resync/index.ts b/commerce-plp-management/functions/badge-resync/index.ts new file mode 100644 index 0000000..c5ee386 --- /dev/null +++ b/commerce-plp-management/functions/badge-resync/index.ts @@ -0,0 +1,68 @@ +// Badge vocabulary re-sync. +// +// On the pull path, changing a productBadge label/color is live immediately via +// the GROQ `->` join. On the push path (Shopify metaobjects), the badge label is +// baked into each collection's metaobject at sync time, so a badge edit does not +// propagate until the referencing collections are re-synced. +// +// This function closes that gap: on publish of a productBadge, it re-upserts the +// metaobject for every collectionEnrichment that references the badge. +import {documentEventHandler} from '@sanity/functions' +import {createClient} from '@sanity/client' +import {defineQuery} from 'groq' +import {env} from 'node:process' +import { + adminConfigFromEnv, + createAdminClient, + upsertCollectionMetaobject, +} from '@starter/commerce/shopify' +import type {CollectionEnrichment} from '@starter/commerce/types' + +type EventData = {_id: string} + +const AFFECTED_QUERY = defineQuery(` + *[_type == "collectionEnrichment" && $badgeId in badges[].badge._ref]{ + "handle": handle.current, + collectionType, + title, + banner{"imageUrl": image.asset->url, headline, subhead, ctaLabel, ctaHref, theme}, + faceout{ + "productGid": product.productGid, + variantGid, + editorialHeadline, + "imageUrlOverride": imageOverride.asset->url + }, + editorialTiles[]{position, "imageUrl": image.asset->url, headline, body, ctaLabel, ctaHref, theme}, + badges[]{ + "productGid": product.productGid, + "badge": badge->{"slug": slug.current, label, color, icon}, + customLabel, startDate, endDate + }, + facetConfig[]{facetHandle, labelOverride}, + productList[]{"productGid": productGid} + } +`) + +export const handler = documentEventHandler(async ({context, event}) => { + const data = event.data as EventData + const {SANITY_STUDIO_PROJECT_ID: projectId, SANITY_STUDIO_DATASET: dataset} = env + const token = context.clientOptions?.token + const adminConfig = adminConfigFromEnv(env) + + if (!projectId || !dataset || !token) throw new Error('Missing Sanity client configuration') + if (!adminConfig) throw new Error('Missing Shopify Admin credentials') + + const client = createClient({projectId, dataset, token, apiVersion: '2025-01-01', useCdn: false}) + const admin = createAdminClient(adminConfig) + + // The badge id may arrive as `badge-x` or `drafts.badge-x`; match the published ref. + const badgeId = data._id.replace(/^drafts\./, '') + const affected = (await client.fetch(AFFECTED_QUERY, {badgeId})) as CollectionEnrichment[] + + for (const enrichment of affected) { + if (!enrichment.handle) continue + await upsertCollectionMetaobject(admin, enrichment) + } + + console.log(`Re-synced ${affected.length} collection(s) after badge ${badgeId} changed`) +}) diff --git a/commerce-plp-management/functions/collection-sync/index.ts b/commerce-plp-management/functions/collection-sync/index.ts new file mode 100644 index 0000000..e2609ff --- /dev/null +++ b/commerce-plp-management/functions/collection-sync/index.ts @@ -0,0 +1,97 @@ +// Push-sync: Sanity -> Shopify. +// +// On publish of a collectionEnrichment document, write the whole enrichment +// payload to a single `sanity_plp_collection` metaobject in Shopify (per the +// PRD decision: one metaobject per collection, not per-product metafields), then +// stamp syncStatus on the Sanity document (green / red) so the merchandiser sees +// the result without leaving Studio. +// +// The Sanity CDN pull path is unaffected by push failures — the storefront still +// serves the enrichment correctly even if this metaobject write fails. +import {documentEventHandler} from '@sanity/functions' +import {createClient} from '@sanity/client' +import {defineQuery} from 'groq' +import {env} from 'node:process' +import { + adminConfigFromEnv, + createAdminClient, + ensureMetaobjectDefinition, + upsertCollectionMetaobject, +} from '@starter/commerce/shopify' +import type {CollectionEnrichment} from '@starter/commerce/types' + +type EventData = {_id: string; handle?: {current?: string}} + +const ENRICHMENT_QUERY = defineQuery(`*[_id == $id][0]{ + "handle": handle.current, + collectionType, + title, + banner{"imageUrl": image.asset->url, headline, subhead, ctaLabel, ctaHref, theme}, + faceout{ + "productGid": product.productGid, + variantGid, + editorialHeadline, + "imageUrlOverride": imageOverride.asset->url + }, + editorialTiles[]{position, "imageUrl": image.asset->url, headline, body, ctaLabel, ctaHref, theme}, + badges[]{ + "productGid": product.productGid, + "badge": badge->{"slug": slug.current, label, color, icon}, + customLabel, startDate, endDate + }, + facetConfig[]{facetHandle, labelOverride}, + productList[]{"productGid": productGid} +}`) + +export const handler = documentEventHandler(async ({context, event}) => { + const data = event.data as EventData + const {SANITY_STUDIO_PROJECT_ID: projectId, SANITY_STUDIO_DATASET: dataset} = env + const token = context.clientOptions?.token + + if (!projectId || !dataset || !token) { + throw new Error('Missing Sanity client configuration') + } + + const client = createClient({projectId, dataset, token, apiVersion: '2025-01-01', useCdn: false}) + + // Mark pending while we push. + await client + .patch(data._id) + .set({syncStatus: {status: 'pending'}}) + .commit() + + try { + const adminConfig = adminConfigFromEnv(env) + if (!adminConfig) { + throw new Error( + 'Missing Shopify Admin credentials (SHOPIFY_STORE_DOMAIN + SHOPIFY_CLIENT_ID/SHOPIFY_CLIENT_SECRET)', + ) + } + + const enrichment = (await client.fetch(ENRICHMENT_QUERY, { + id: data._id, + })) as CollectionEnrichment | null + if (!enrichment?.handle) { + throw new Error('Enrichment document has no handle') + } + + const admin = createAdminClient(adminConfig) + + await ensureMetaobjectDefinition(admin) + await upsertCollectionMetaobject(admin, enrichment) + + await client + .patch(data._id) + .set({syncStatus: {status: 'synced', lastSyncedAt: new Date().toISOString()}}) + .commit() + + console.log(`Synced collection "${enrichment.handle}" to Shopify metaobject`) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + await client + .patch(data._id) + .set({syncStatus: {status: 'failed', error: message, lastSyncedAt: new Date().toISOString()}}) + .commit() + throw error + } +}) diff --git a/commerce-plp-management/functions/package.json b/commerce-plp-management/functions/package.json new file mode 100644 index 0000000..245763f --- /dev/null +++ b/commerce-plp-management/functions/package.json @@ -0,0 +1,25 @@ +{ + "name": "@starter/functions", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "clean": "rm -rf dist", + "build": "pnpm run clean && rolldown -c rolldown.config.ts", + "typecheck": "tsc --noEmit", + "predev": "pnpm run build", + "dev": "sanity functions dev", + "predeploy": "pnpm run build", + "deploy": "sanity blueprints deploy" + }, + "devDependencies": { + "@sanity/client": "catalog:", + "@sanity/functions": "^1.3.1", + "@starter/commerce": "workspace:*", + "@starter/tsconfig": "workspace:*", + "@types/node": "^22.19.13", + "groq": "catalog:", + "rolldown": "^1.0.0-rc.8", + "sanity": "catalog:" + } +} diff --git a/commerce-plp-management/functions/rolldown.config.ts b/commerce-plp-management/functions/rolldown.config.ts new file mode 100644 index 0000000..42f85c8 --- /dev/null +++ b/commerce-plp-management/functions/rolldown.config.ts @@ -0,0 +1,16 @@ +import {defineConfig} from 'rolldown' + +const fn = (name: string) => + defineConfig({ + input: {index: `${name}/index.ts`}, + output: { + dir: `dist/${name}`, + cleanDir: true, + codeSplitting: false, + minify: true, + comments: false, + }, + platform: 'node', + }) + +export default [fn('collection-sync'), fn('badge-resync')] diff --git a/commerce-plp-management/functions/tsconfig.json b/commerce-plp-management/functions/tsconfig.json new file mode 100644 index 0000000..eb05580 --- /dev/null +++ b/commerce-plp-management/functions/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@starter/tsconfig/base.json", + "compilerOptions": { + "lib": ["esnext"], + "noEmit": true + }, + "include": ["**/*.ts"], + "exclude": [".build", "node_modules"] +} diff --git a/commerce-plp-management/package.json b/commerce-plp-management/package.json new file mode 100644 index 0000000..7a570d0 --- /dev/null +++ b/commerce-plp-management/package.json @@ -0,0 +1,60 @@ +{ + "name": "commerce-plp-management", + "version": "1.0.0", + "private": true, + "description": "Commerce PLP management starter. Give merchandising teams editorial control of the category page — product curation, in-grid storytelling, badges, facet order, and custom campaign collections — as a Sanity enrichment layer on top of Shopify. Presence-based: no enrichment document means pure Shopify output. Built with Sanity Studio v5, Next.js 16, and Sanity Functions.", + "keywords": [ + "Commerce", + "Content Operations", + "GROQ", + "Merchandising", + "Next.js", + "PLP", + "Sanity", + "Sanity Functions", + "Shopify" + ], + "homepage": "https://github.com/sanity-labs/starters/tree/main/commerce-plp-management#readme", + "bugs": { + "url": "https://github.com/sanity-labs/starters/issues" + }, + "license": "MIT", + "type": "module", + "scripts": { + "dev": "concurrently -n studio,frontend,functions -c '#f03e2f,#8b5cf6,#f5a623' 'pnpm --filter studio dev' 'pnpm --filter frontend dev' 'pnpm --filter @starter/functions build && sanity functions dev'", + "build": "pnpm -r build", + "test": "pnpm -r test", + "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ .", + "format": "oxfmt .", + "format:check": "oxfmt --check .", + "typegen": "pnpm --filter studio typegen", + "pretypecheck": "pnpm run typegen", + "typecheck": "pnpm -r typecheck", + "bootstrap": "pnpm --filter studio bootstrap", + "seed": "pnpm --filter studio seed", + "seed:demo": "pnpm --filter studio seed:demo", + "shopify:setup": "tsx scripts/setup-metaobject.ts", + "shopify:storefront-token": "tsx scripts/create-storefront-token.ts", + "validate": "sanity-template-validate" + }, + "devDependencies": { + "@sanity/blueprints": "^0.17.1", + "@sanity/client": "catalog:", + "@sanity/functions": "1.3.1", + "@sanity/template-validator": "^3.1.0", + "@starter/commerce": "workspace:*", + "@starter/eslint-config": "workspace:*", + "@types/node": "^22.19.13", + "concurrently": "^9.2.1", + "dotenv": "^17.4.2", + "eslint": "^9.39.3", + "groq": "catalog:", + "oxfmt": "^0.46.0", + "sanity": "catalog:", + "tsx": "^4.21.0" + }, + "engines": { + "node": ">=20.19 <22 || >=22.12" + }, + "packageManager": "pnpm@10.30.3" +} diff --git a/commerce-plp-management/packages/@starter/commerce/package.json b/commerce-plp-management/packages/@starter/commerce/package.json new file mode 100644 index 0000000..deb2755 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/package.json @@ -0,0 +1,21 @@ +{ + "name": "@starter/commerce", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./types": "./src/types.ts", + "./merge": "./src/merge.ts", + "./badges": "./src/badges.ts", + "./shopify": "./src/shopify/index.ts", + "./shopify/metaobject": "./src/shopify/metaobject.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@starter/tsconfig": "workspace:*", + "typescript": "catalog:" + } +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/badges.ts b/commerce-plp-management/packages/@starter/commerce/src/badges.ts new file mode 100644 index 0000000..092cff9 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/badges.ts @@ -0,0 +1,53 @@ +import type {BadgeAssignment, BadgeType, ResolvedBadge} from './types' + +/** + * A badge is active when now is within [startDate, endDate]. Missing bounds are + * treated as open-ended. Date-gating is enforced at render time so a scheduled + * "Final Sale" badge appears and disappears without republishing. + */ +export function isBadgeActive(assignment: BadgeAssignment, now: Date = new Date()): boolean { + const start = assignment.startDate ? new Date(assignment.startDate) : null + const end = assignment.endDate ? new Date(assignment.endDate) : null + if (start && now < start) return false + if (end && now > end) return false + return true +} + +function badgeTypeFromSlug(slug: string): BadgeType { + const known: BadgeType[] = ['sale', 'new', 'final-sale', 'best-seller'] + return known.includes(slug as BadgeType) ? (slug as BadgeType) : 'custom' +} + +/** + * Build a map of product GID -> active badges, resolving the referenced badge + * vocabulary. Assignments whose badge reference failed to resolve are skipped. + */ +export function resolveBadgeMap( + assignments: BadgeAssignment[] | null | undefined, + now: Date = new Date(), +): Map { + const map = new Map() + if (!assignments) return map + + for (const assignment of assignments) { + if (!assignment.productGid || !assignment.badge) continue + if (!isBadgeActive(assignment, now)) continue + + const type = badgeTypeFromSlug(assignment.badge.slug) + const label = + type === 'custom' && assignment.customLabel ? assignment.customLabel : assignment.badge.label + + const resolved: ResolvedBadge = { + type, + label, + color: assignment.badge.color, + icon: assignment.badge.icon ?? null, + } + + const existing = map.get(assignment.productGid) + if (existing) existing.push(resolved) + else map.set(assignment.productGid, [resolved]) + } + + return map +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/index.ts b/commerce-plp-management/packages/@starter/commerce/src/index.ts new file mode 100644 index 0000000..b7d6550 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/index.ts @@ -0,0 +1,7 @@ +export * from './types' +export {mergeCollection} from './merge' +export type {MergeInput} from './merge' +export {isBadgeActive, resolveBadgeMap} from './badges' +export {resolveEnrichmentForAudience} from './variants' +export type {ResolvedEnrichmentView} from './variants' +export * from './shopify' diff --git a/commerce-plp-management/packages/@starter/commerce/src/merge.ts b/commerce-plp-management/packages/@starter/commerce/src/merge.ts new file mode 100644 index 0000000..4f7c611 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/merge.ts @@ -0,0 +1,170 @@ +import {resolveBadgeMap} from './badges' +import {resolveEnrichmentForAudience} from './variants' +import type { + CollectionEnrichment, + EditorialTile, + GridItem, + GridProductItem, + MergedCollection, + MergedFacet, + ShopifyCollection, + ShopifyProduct, +} from './types' + +export type MergeInput = { + /** Canonical catalog. For sanity-custom collections this only supplies the + * product records (fetched by GID batch); membership/order come from Sanity. */ + shopify: ShopifyCollection + /** null => no enrichment document => pure Shopify output. */ + enrichment: CollectionEnrichment | null + /** Visitor audience segment resolved at the edge (interim personalization). */ + audienceTag?: string | null + /** Injected for deterministic badge date-gating (tests, SSR). */ + now?: Date +} + +/** + * Layer a Sanity enrichment document over Shopify catalog output. + * + * Presence-based: if `enrichment` is null the function returns the Shopify grid + * untouched (enriched: false). This is the null-check the PRD calls for — a + * collection with no Sanity document renders exactly like plain Shopify. + */ +export function mergeCollection(input: MergeInput): MergedCollection { + const {shopify, enrichment, audienceTag, now = new Date()} = input + + if (!enrichment) { + return { + handle: shopify.handle, + title: shopify.title, + description: shopify.description, + collectionType: 'shopify-native', + enriched: false, + audienceTag: null, + banner: null, + facets: shopify.facets.map((f) => ({...f, promoted: false})), + grid: shopify.products.map((p) => toProductItem(p)), + } + } + + const view = resolveEnrichmentForAudience(enrichment, audienceTag) + const badgeMap = resolveBadgeMap(enrichment.badges, now) + + const orderedProducts = orderProducts(shopify.products, enrichment) + const faceoutGid = view.faceout?.productGid ?? null + + // Faceout renders at grid position 0; remove it from its natural slot. + const withoutFaceout = faceoutGid + ? orderedProducts.filter((p) => p.id !== faceoutGid) + : orderedProducts + + const productItems: GridProductItem[] = [] + + if (faceoutGid) { + const faceoutProduct = orderedProducts.find((p) => p.id === faceoutGid) + if (faceoutProduct) { + productItems.push({ + ...toProductItem(faceoutProduct, badgeMap.get(faceoutProduct.id)), + isFaceout: true, + faceoutHeadline: view.faceout?.editorialHeadline ?? null, + faceoutImageUrl: view.faceout?.imageUrlOverride ?? null, + }) + } + } + + for (const product of withoutFaceout) { + productItems.push(toProductItem(product, badgeMap.get(product.id))) + } + + const grid = injectTiles(productItems, view.editorialTiles) + + return { + handle: enrichment.handle, + title: enrichment.title || shopify.title, + description: shopify.description, + collectionType: enrichment.collectionType, + enriched: true, + audienceTag: view.audienceTag, + banner: view.banner, + facets: mergeFacets(shopify, enrichment), + grid, + } +} + +function toProductItem( + product: ShopifyProduct, + badges: GridProductItem['badges'] = [], +): GridProductItem { + return {kind: 'product', product, badges, isFaceout: false} +} + +/** + * For sanity-custom collections Sanity is the authority for membership and + * order: sort by the explicit `productList` positions. For shopify-native + * collections keep Shopify's order (pinnedRecs is applied by rec slots, not grid). + */ +function orderProducts( + products: ShopifyProduct[], + enrichment: CollectionEnrichment, +): ShopifyProduct[] { + if (enrichment.collectionType !== 'sanity-custom' || !enrichment.productList?.length) { + return products + } + + const byGid = new Map(products.map((p) => [p.id, p])) + const ordered = [...enrichment.productList] + .sort((a, b) => a.position - b.position) + .map((entry) => byGid.get(entry.productGid)) + .filter((p): p is ShopifyProduct => Boolean(p)) + + return ordered +} + +/** + * Inject editorial tiles at their 1-based grid positions. Tiles displace product + * cards rather than replacing them; later tiles account for earlier insertions. + */ +function injectTiles(productItems: GridProductItem[], tiles: EditorialTile[]): GridItem[] { + if (!tiles.length) return productItems + + const grid: GridItem[] = [...productItems] + const sorted = [...tiles].sort((a, b) => a.position - b.position) + + for (const tile of sorted) { + const index = Math.max(0, Math.min(tile.position - 1, grid.length)) + grid.splice(index, 0, {kind: 'tile', tile}) + } + + return grid +} + +/** + * Reorder facets so promoted ones (from facetConfig) come first, in the + * configured order, with label overrides applied. Remaining Shopify facets + * follow in their original order. + */ +function mergeFacets(shopify: ShopifyCollection, enrichment: CollectionEnrichment): MergedFacet[] { + if (!enrichment.facetConfig?.length) { + return shopify.facets.map((f) => ({...f, promoted: false})) + } + + const byHandle = new Map(shopify.facets.map((f) => [f.handle, f])) + const promoted: MergedFacet[] = [] + + for (const config of enrichment.facetConfig) { + const facet = byHandle.get(config.facetHandle) + if (!facet) continue + promoted.push({ + ...facet, + label: config.labelOverride || facet.label, + promoted: true, + }) + byHandle.delete(config.facetHandle) + } + + const remaining: MergedFacet[] = shopify.facets + .filter((f) => byHandle.has(f.handle)) + .map((f) => ({...f, promoted: false})) + + return [...promoted, ...remaining] +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/shopify/admin.ts b/commerce-plp-management/packages/@starter/commerce/src/shopify/admin.ts new file mode 100644 index 0000000..2a16324 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/shopify/admin.ts @@ -0,0 +1,113 @@ +export type AdminConfig = { + domain: string + apiVersion?: string + /** + * Static Admin API access token (`shpat_...`) from a legacy store-level custom + * app. Optional — prefer clientId + clientSecret for Dev Dashboard apps. + */ + token?: string + /** Dev Dashboard app credentials. Exchanged for a short-lived access token. */ + clientId?: string + clientSecret?: string +} + +type GraphQLResponse = {data?: T; errors?: {message: string}[]} +type TokenResponse = {access_token: string; expires_in: number; scope?: string} + +/** + * Minimal Shopify Admin API client. Used by the push-sync Function to write the + * `sanity_plp_collection` metaobject. The Admin credentials are sensitive — this + * client must only ever run server-side / inside a Function, never in the browser. + * + * Auth: Dev Dashboard apps have no static token in the UI. Instead we exchange + * the Client ID + Client secret for a 24h access token via the client credentials + * grant, caching and refreshing it automatically. A legacy static `token` is also + * supported for store-level custom apps. + * See https://shopify.dev/docs/apps/build/dev-dashboard/get-api-access-tokens + */ +export function createAdminClient(config: AdminConfig) { + const apiVersion = config.apiVersion || '2025-07' + const endpoint = `https://${config.domain}/admin/api/${apiVersion}/graphql.json` + const tokenEndpoint = `https://${config.domain}/admin/oauth/access_token` + + let cachedToken: string | null = config.token ?? null + // Static tokens never expire from our side; client-credentials tokens do. + let expiresAt = config.token ? Number.POSITIVE_INFINITY : 0 + + async function getToken(): Promise { + if (cachedToken && Date.now() < expiresAt - 60_000) return cachedToken + + if (!config.clientId || !config.clientSecret) { + throw new Error( + 'Shopify Admin auth requires either a static token or clientId + clientSecret', + ) + } + + const res = await fetch(tokenEndpoint, { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + grant_type: 'client_credentials', + client_id: config.clientId, + client_secret: config.clientSecret, + }), + }) + if (!res.ok) { + const body = await res.text().catch(() => '') + throw new Error(`Shopify token request failed: ${res.status} ${res.statusText} ${body}`) + } + + const json = (await res.json()) as TokenResponse + cachedToken = json.access_token + expiresAt = Date.now() + json.expires_in * 1000 + return cachedToken + } + + async function request(query: string, variables?: Record): Promise { + const token = await getToken() + const res = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Shopify-Access-Token': token, + }, + body: JSON.stringify({query, variables}), + }) + if (!res.ok) { + const body = await res.text().catch(() => '') + throw new Error(`Shopify Admin API error: ${res.status} ${res.statusText} ${body}`) + } + const json = (await res.json()) as GraphQLResponse + if (json.errors?.length) { + throw new Error(`Shopify Admin API: ${json.errors.map((e) => e.message).join('; ')}`) + } + return json.data as T + } + + return {request} +} + +export type AdminClient = ReturnType + +/** + * Build an AdminConfig from a plain env bag (process.env or a Function's env). + * Prefers Dev Dashboard client credentials, falls back to a static token. + */ +export function adminConfigFromEnv(env: Record): AdminConfig | null { + const domain = env.SHOPIFY_STORE_DOMAIN + if (!domain) return null + + const clientId = env.SHOPIFY_CLIENT_ID + const clientSecret = env.SHOPIFY_CLIENT_SECRET + const token = env.SHOPIFY_ADMIN_API_TOKEN + + if (!token && !(clientId && clientSecret)) return null + + return { + domain, + apiVersion: env.SHOPIFY_ADMIN_API_VERSION, + token, + clientId, + clientSecret, + } +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/shopify/index.ts b/commerce-plp-management/packages/@starter/commerce/src/shopify/index.ts new file mode 100644 index 0000000..491ece3 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/shopify/index.ts @@ -0,0 +1,13 @@ +export {createStorefrontClient} from './storefront' +export type {StorefrontClient, StorefrontConfig} from './storefront' +export {createAdminClient, adminConfigFromEnv} from './admin' +export type {AdminClient, AdminConfig} from './admin' +export { + METAOBJECT_TYPE, + METAOBJECT_DEFINITION, + buildMetaobjectFields, + ensureMetaobjectDefinition, + upsertCollectionMetaobject, +} from './metaobject' +export type {MetaobjectField} from './metaobject' +export {createStorefrontAccessToken} from './storefrontToken' diff --git a/commerce-plp-management/packages/@starter/commerce/src/shopify/metaobject.ts b/commerce-plp-management/packages/@starter/commerce/src/shopify/metaobject.ts new file mode 100644 index 0000000..d895283 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/shopify/metaobject.ts @@ -0,0 +1,141 @@ +import type {AdminClient} from './admin' +import type {CollectionEnrichment} from '../types' + +/** + * The `sanity_plp_collection` metaobject is the contract between Sanity and + * Shopify. Per the PRD decision, the push-sync writes ONE metaobject per + * collection (not per-product metafields) so the whole enrichment payload lands + * in a single Admin API call and is readable by the Shopify ecosystem. + * + * This definition is version-controlled here and must be kept in sync with the + * Shopify Admin. `pnpm shopify:setup` idempotently creates/updates it. + */ +export const METAOBJECT_TYPE = 'sanity_plp_collection' + +export const METAOBJECT_DEFINITION = { + type: METAOBJECT_TYPE, + name: 'Sanity PLP Collection', + description: 'Editorial enrichment authored in Sanity and synced on publish.', + fieldDefinitions: [ + // NOTE: `handle` is reserved by Shopify (every metaobject has a built-in + // handle), so the collection handle is stored as `collection_handle`. The + // metaobject's own handle is also set to the collection handle on upsert. + {key: 'collection_handle', name: 'Collection handle', type: 'single_line_text_field'}, + {key: 'collection_type', name: 'Collection type', type: 'single_line_text_field'}, + {key: 'banner', name: 'Banner (JSON)', type: 'json'}, + {key: 'faceout', name: 'Faceout (JSON)', type: 'json'}, + {key: 'editorial_tiles', name: 'Editorial tiles (JSON)', type: 'json'}, + {key: 'badges', name: 'Badges (JSON)', type: 'json'}, + {key: 'facet_config', name: 'Facet config (JSON)', type: 'json'}, + {key: 'product_list', name: 'Product list (JSON)', type: 'json'}, + {key: 'synced_at', name: 'Synced at', type: 'date_time'}, + ], +} as const + +export type MetaobjectField = {key: string; value: string} + +/** Serialize an enrichment document into metaobject fields. */ +export function buildMetaobjectFields(enrichment: CollectionEnrichment): MetaobjectField[] { + const json = (value: unknown) => JSON.stringify(value ?? null) + return [ + {key: 'collection_handle', value: enrichment.handle}, + {key: 'collection_type', value: enrichment.collectionType}, + {key: 'banner', value: json(enrichment.banner)}, + {key: 'faceout', value: json(enrichment.faceout)}, + {key: 'editorial_tiles', value: json(enrichment.editorialTiles)}, + {key: 'badges', value: json(enrichment.badges)}, + {key: 'facet_config', value: json(enrichment.facetConfig)}, + {key: 'product_list', value: json(enrichment.productList)}, + {key: 'synced_at', value: new Date().toISOString()}, + ] +} + +/** + * Create the metaobject definition if it does not already exist. Idempotent: + * an "already taken" error is treated as success. + */ +export async function ensureMetaobjectDefinition(admin: AdminClient): Promise { + const query = /* GraphQL */ ` + mutation CreateDefinition($definition: MetaobjectDefinitionCreateInput!) { + metaobjectDefinitionCreate(definition: $definition) { + metaobjectDefinition { + id + type + } + userErrors { + field + message + code + } + } + } + ` + const data = await admin.request<{ + metaobjectDefinitionCreate: { + metaobjectDefinition: {id: string; type: string} | null + userErrors: {field: string[]; message: string; code: string}[] + } + }>(query, { + definition: { + type: METAOBJECT_DEFINITION.type, + name: METAOBJECT_DEFINITION.name, + description: METAOBJECT_DEFINITION.description, + fieldDefinitions: METAOBJECT_DEFINITION.fieldDefinitions.map((f) => ({ + key: f.key, + name: f.name, + type: f.type, + })), + }, + }) + + const errors = data.metaobjectDefinitionCreate.userErrors + const alreadyExists = errors.some((e) => e.code === 'TAKEN') + if (errors.length && !alreadyExists) { + throw new Error( + `Failed to create metaobject definition: ${errors.map((e) => e.message).join('; ')}`, + ) + } +} + +/** + * Upsert the collection's metaobject by handle. Uses `metaobjectUpsert` so the + * same call creates or updates. Returns the metaobject id. + */ +export async function upsertCollectionMetaobject( + admin: AdminClient, + enrichment: CollectionEnrichment, +): Promise { + const query = /* GraphQL */ ` + mutation UpsertMetaobject( + $handle: MetaobjectHandleInput! + $metaobject: MetaobjectUpsertInput! + ) { + metaobjectUpsert(handle: $handle, metaobject: $metaobject) { + metaobject { + id + handle + } + userErrors { + field + message + code + } + } + } + ` + const data = await admin.request<{ + metaobjectUpsert: { + metaobject: {id: string; handle: string} | null + userErrors: {field: string[]; message: string; code: string}[] + } + }>(query, { + handle: {type: METAOBJECT_TYPE, handle: enrichment.handle}, + metaobject: {fields: buildMetaobjectFields(enrichment)}, + }) + + const errors = data.metaobjectUpsert.userErrors + if (errors.length || !data.metaobjectUpsert.metaobject) { + throw new Error(`Failed to upsert metaobject: ${errors.map((e) => e.message).join('; ')}`) + } + return data.metaobjectUpsert.metaobject.id +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/shopify/storefront.ts b/commerce-plp-management/packages/@starter/commerce/src/shopify/storefront.ts new file mode 100644 index 0000000..8fa2449 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/shopify/storefront.ts @@ -0,0 +1,222 @@ +import type {ShopifyCollection, ShopifyProduct} from '../types' + +export type StorefrontConfig = { + domain: string + token: string + apiVersion?: string +} + +type GraphQLResponse = {data?: T; errors?: {message: string}[]} + +const PRODUCT_FRAGMENT = /* GraphQL */ ` + fragment ProductCard on Product { + id + handle + title + productType + availableForSale + featuredImage { + url + altText + width + height + } + priceRange { + minVariantPrice { + amount + currencyCode + } + } + compareAtPriceRange { + minVariantPrice { + amount + currencyCode + } + } + variants(first: 20) { + nodes { + id + title + availableForSale + price { + amount + currencyCode + } + } + } + } +` + +/** + * Minimal Shopify Storefront API client used by the storefront (products, price, + * inventory, collection membership) and the Studio product picker (search). + * Uses the public Storefront token — safe to expose to the browser. + */ +export function createStorefrontClient(config: StorefrontConfig) { + const apiVersion = config.apiVersion || '2025-07' + const endpoint = `https://${config.domain}/api/${apiVersion}/graphql.json` + + async function request(query: string, variables?: Record): Promise { + const res = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Shopify-Storefront-Access-Token': config.token, + }, + body: JSON.stringify({query, variables}), + }) + if (!res.ok) { + throw new Error(`Shopify Storefront API error: ${res.status} ${res.statusText}`) + } + const json = (await res.json()) as GraphQLResponse + if (json.errors?.length) { + throw new Error(`Shopify Storefront API: ${json.errors.map((e) => e.message).join('; ')}`) + } + return json.data as T + } + + return { + request, + + /** Fetch a native collection with its products. Returns null if not found. */ + async getCollectionByHandle( + handle: string, + options: {first?: number} = {}, + ): Promise { + const query = /* GraphQL */ ` + ${PRODUCT_FRAGMENT} + query CollectionByHandle($handle: String!, $first: Int!) { + collection(handle: $handle) { + id + handle + title + description + products(first: $first) { + nodes { + ...ProductCard + } + filters { + id + label + values { + id + label + count + } + } + } + } + } + ` + const data = await request<{collection: RawCollection | null}>(query, { + handle, + first: options.first ?? 48, + }) + if (!data.collection) return null + return normalizeCollection(data.collection) + }, + + /** Batch-fetch products by GID (for sanity-custom collection membership). */ + async getProductsByIds(ids: string[]): Promise { + if (!ids.length) return [] + const query = /* GraphQL */ ` + ${PRODUCT_FRAGMENT} + query ProductsByIds($ids: [ID!]!) { + nodes(ids: $ids) { + ... on Product { + ...ProductCard + } + } + } + ` + const data = await request<{nodes: (RawProduct | null)[]}>(query, {ids}) + return data.nodes.filter((n): n is RawProduct => Boolean(n)).map(normalizeProduct) + }, + + /** Search the catalog by name. Powers the Studio product picker. */ + async searchProducts(term: string, first = 10): Promise { + const query = /* GraphQL */ ` + ${PRODUCT_FRAGMENT} + query SearchProducts($query: String!, $first: Int!) { + products(first: $first, query: $query) { + nodes { + ...ProductCard + } + } + } + ` + const data = await request<{products: {nodes: RawProduct[]}}>(query, { + query: term ? `title:*${term}*` : '', + first, + }) + return data.products.nodes.map(normalizeProduct) + }, + } +} + +export type StorefrontClient = ReturnType + +// ── Normalization (Storefront GraphQL shape -> our flat types) ──────────────── + +type RawMoney = {amount: string; currencyCode: string} +type RawProduct = { + id: string + handle: string + title: string + productType: string | null + availableForSale: boolean + featuredImage: {url: string; altText: string | null; width?: number; height?: number} | null + priceRange: {minVariantPrice: RawMoney} + compareAtPriceRange: {minVariantPrice: RawMoney} + variants: {nodes: {id: string; title: string; availableForSale: boolean; price: RawMoney}[]} +} +type RawCollection = { + id: string + handle: string + title: string + description: string | null + products: { + nodes: RawProduct[] + filters: {id: string; label: string; values: {id: string; label: string; count: number}[]}[] + } +} + +function money(raw: RawMoney): {amount: number; currencyCode: string} { + return {amount: Number.parseFloat(raw.amount), currencyCode: raw.currencyCode} +} + +function normalizeProduct(raw: RawProduct): ShopifyProduct { + const compareAt = money(raw.compareAtPriceRange.minVariantPrice) + const price = money(raw.priceRange.minVariantPrice) + return { + id: raw.id, + handle: raw.handle, + title: raw.title, + productType: raw.productType, + availableForSale: raw.availableForSale, + featuredImage: raw.featuredImage, + price, + compareAtPrice: compareAt.amount > price.amount ? compareAt : null, + variants: raw.variants.nodes.map((v) => ({ + id: v.id, + title: v.title, + availableForSale: v.availableForSale, + price: money(v.price), + })), + } +} + +function normalizeCollection(raw: RawCollection): ShopifyCollection { + return { + id: raw.id, + handle: raw.handle, + title: raw.title, + description: raw.description, + products: raw.products.nodes.map(normalizeProduct), + facets: raw.products.filters.map((f) => ({ + handle: f.id, + label: f.label, + values: f.values.map((v) => ({handle: v.id, label: v.label, count: v.count})), + })), + } +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/shopify/storefrontToken.ts b/commerce-plp-management/packages/@starter/commerce/src/shopify/storefrontToken.ts new file mode 100644 index 0000000..a25aa89 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/shopify/storefrontToken.ts @@ -0,0 +1,45 @@ +import type {AdminClient} from './admin' + +/** + * Mint a public Storefront API access token via the Admin API. Dev Dashboard apps + * don't expose a static Storefront token in the UI, so we create one from the + * Admin credentials (which we already exchange via client credentials). The + * resulting token is public and safe to use in the Studio product picker and the + * storefront runtime. + * + * Requires the app to have Storefront API access (e.g. the + * `unauthenticated_read_product_listings` scope). + */ +export async function createStorefrontAccessToken( + admin: AdminClient, + title = 'Sanity PLP Storefront', +): Promise { + const query = /* GraphQL */ ` + mutation CreateStorefrontToken($input: StorefrontAccessTokenInput!) { + storefrontAccessTokenCreate(input: $input) { + storefrontAccessToken { + accessToken + title + } + userErrors { + field + message + } + } + } + ` + const data = await admin.request<{ + storefrontAccessTokenCreate: { + storefrontAccessToken: {accessToken: string; title: string} | null + userErrors: {field: string[]; message: string}[] + } + }>(query, {input: {title}}) + + const {storefrontAccessToken, userErrors} = data.storefrontAccessTokenCreate + if (userErrors.length || !storefrontAccessToken) { + throw new Error( + `Failed to create Storefront access token: ${userErrors.map((e) => e.message).join('; ')}`, + ) + } + return storefrontAccessToken.accessToken +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/types.ts b/commerce-plp-management/packages/@starter/commerce/src/types.ts new file mode 100644 index 0000000..1f5d030 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/types.ts @@ -0,0 +1,199 @@ +/** + * Shared commerce types. + * + * These describe two worlds that meet on the storefront: + * - Shopify* types: the canonical catalog (products, price, inventory, facets). + * - CollectionEnrichment*: the editorial layer authored in Sanity. + * - Merged*: the result of layering enrichment on top of the catalog. + * + * The package is intentionally framework-agnostic (no React, no Sanity client) + * so the storefront and the push-sync Function can both import it. + */ + +// ── Shopify (canonical catalog) ────────────────────────────────────────────── + +export type Money = { + amount: number + currencyCode: string +} + +export type ShopifyImage = { + url: string + altText: string | null + width?: number + height?: number +} + +export type ShopifyProductVariant = { + id: string + title: string + availableForSale: boolean + price: Money +} + +export type ShopifyProduct = { + /** Global ID, e.g. `gid://shopify/Product/123`. The join key for enrichment. */ + id: string + handle: string + title: string + featuredImage: ShopifyImage | null + price: Money + compareAtPrice: Money | null + availableForSale: boolean + productType: string | null + variants: ShopifyProductVariant[] +} + +export type ShopifyFacetValue = { + handle: string + label: string + count: number +} + +export type ShopifyFacet = { + handle: string + label: string + values: ShopifyFacetValue[] +} + +export type ShopifyCollection = { + id: string + handle: string + title: string + description: string | null + products: ShopifyProduct[] + facets: ShopifyFacet[] +} + +// ── Enrichment (authored in Sanity) ────────────────────────────────────────── + +export type CollectionType = 'shopify-native' | 'sanity-custom' + +export type BadgeType = 'sale' | 'new' | 'final-sale' | 'best-seller' | 'custom' + +export type SyncStatus = 'never' | 'pending' | 'synced' | 'failed' + +/** Shared badge vocabulary document (`productBadge`). */ +export type ProductBadge = { + slug: string + label: string + /** Design token name, e.g. `sale`, `new`. Maps to a storefront color. */ + color: string + icon?: string | null +} + +export type BadgeAssignment = { + productGid: string + /** Resolved via GROQ `->` join, so label/color changes are live. */ + badge: ProductBadge | null + /** Only used when the referenced badge is the `custom` type. */ + customLabel?: string | null + startDate?: string | null + endDate?: string | null +} + +export type Banner = { + imageUrl?: string | null + headline?: string | null + subhead?: string | null + ctaLabel?: string | null + ctaHref?: string | null + theme?: string | null +} + +export type Faceout = { + productGid: string + variantGid?: string | null + editorialHeadline?: string | null + imageUrlOverride?: string | null +} + +export type EditorialTile = { + /** 1-based grid slot the tile occupies. Product cards shift around it. */ + position: number + imageUrl?: string | null + headline?: string | null + /** Portable Text blocks; rendered on the storefront. */ + body?: unknown[] | null + ctaLabel?: string | null + ctaHref?: string | null + theme?: string | null +} + +export type FacetConfig = { + facetHandle: string + labelOverride?: string | null +} + +export type ProductListEntry = { + productGid: string + position: number +} + +/** + * Interim audience-targeted overrides, resolved at the storefront edge. + * Migration target: Content Variants (do not persist past Content Variants GA). + */ +export type VariantOverride = { + audienceTag: string + banner?: Banner | null + faceout?: Faceout | null + editorialTiles?: EditorialTile[] | null +} + +export type CollectionEnrichment = { + handle: string + collectionType: CollectionType + title?: string | null + banner?: Banner | null + faceout?: Faceout | null + editorialTiles?: EditorialTile[] | null + badges?: BadgeAssignment[] | null + facetConfig?: FacetConfig[] | null + /** Active only when `collectionType === 'sanity-custom'`. */ + productList?: ProductListEntry[] | null + pinnedRecs?: string[] | null + variantOverrides?: VariantOverride[] | null + syncStatus?: SyncStatus | null +} + +// ── Merged (what the storefront renders) ───────────────────────────────────── + +export type ResolvedBadge = { + type: BadgeType + label: string + color: string + icon?: string | null +} + +export type GridProductItem = { + kind: 'product' + product: ShopifyProduct + badges: ResolvedBadge[] + isFaceout: boolean + faceoutHeadline?: string | null + faceoutImageUrl?: string | null +} + +export type GridTileItem = { + kind: 'tile' + tile: EditorialTile +} + +export type GridItem = GridProductItem | GridTileItem + +export type MergedFacet = ShopifyFacet & {promoted: boolean} + +export type MergedCollection = { + handle: string + title: string + description: string | null + collectionType: CollectionType + /** False when no enrichment document exists (pure Shopify output). */ + enriched: boolean + /** The audience tag that was resolved, if any. */ + audienceTag: string | null + banner: Banner | null + facets: MergedFacet[] + grid: GridItem[] +} diff --git a/commerce-plp-management/packages/@starter/commerce/src/variants.ts b/commerce-plp-management/packages/@starter/commerce/src/variants.ts new file mode 100644 index 0000000..56bce85 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/src/variants.ts @@ -0,0 +1,44 @@ +import type {Banner, CollectionEnrichment, EditorialTile, Faceout, VariantOverride} from './types' + +export type ResolvedEnrichmentView = { + banner: Banner | null + faceout: Faceout | null + editorialTiles: EditorialTile[] + audienceTag: string | null +} + +/** + * Interim Content Variants resolution. + * + * Selects the matching `variantOverride` for the visitor's audience tag and + * layers it over the base enrichment. Because all variant content ships in the + * GROQ response, this is only appropriate for non-sensitive segmentation + * (loyalty vs. new visitor). When Content Variants ships, delete this file and + * resolve variants via the API instead — the `variantOverrides` array becomes a + * reference array to Content Variant documents. + */ +export function resolveEnrichmentForAudience( + enrichment: CollectionEnrichment, + audienceTag?: string | null, +): ResolvedEnrichmentView { + const base: ResolvedEnrichmentView = { + banner: enrichment.banner ?? null, + faceout: enrichment.faceout ?? null, + editorialTiles: enrichment.editorialTiles ?? [], + audienceTag: null, + } + + if (!audienceTag || !enrichment.variantOverrides?.length) return base + + const override: VariantOverride | undefined = enrichment.variantOverrides.find( + (v) => v.audienceTag === audienceTag, + ) + if (!override) return base + + return { + banner: override.banner ?? base.banner, + faceout: override.faceout ?? base.faceout, + editorialTiles: override.editorialTiles?.length ? override.editorialTiles : base.editorialTiles, + audienceTag, + } +} diff --git a/commerce-plp-management/packages/@starter/commerce/tsconfig.json b/commerce-plp-management/packages/@starter/commerce/tsconfig.json new file mode 100644 index 0000000..15a23b0 --- /dev/null +++ b/commerce-plp-management/packages/@starter/commerce/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "@starter/tsconfig/base.json", + "compilerOptions": { + "noEmit": true + }, + "include": ["src/**/*.ts"] +} diff --git a/commerce-plp-management/packages/@starter/eslint-config/index.js b/commerce-plp-management/packages/@starter/eslint-config/index.js new file mode 100644 index 0000000..1b8c8ba --- /dev/null +++ b/commerce-plp-management/packages/@starter/eslint-config/index.js @@ -0,0 +1,3 @@ +import studio from '@sanity/eslint-config-studio' + +export default [...studio] diff --git a/commerce-plp-management/packages/@starter/eslint-config/package.json b/commerce-plp-management/packages/@starter/eslint-config/package.json new file mode 100644 index 0000000..c6bd8fd --- /dev/null +++ b/commerce-plp-management/packages/@starter/eslint-config/package.json @@ -0,0 +1,12 @@ +{ + "name": "@starter/eslint-config", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./index.js" + }, + "dependencies": { + "@sanity/eslint-config-studio": "^6.0.0" + } +} diff --git a/commerce-plp-management/packages/@starter/sanity-types/package.json b/commerce-plp-management/packages/@starter/sanity-types/package.json new file mode 100644 index 0000000..5c489d0 --- /dev/null +++ b/commerce-plp-management/packages/@starter/sanity-types/package.json @@ -0,0 +1,9 @@ +{ + "name": "@starter/sanity-types", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./sanity.types.ts" + } +} diff --git a/commerce-plp-management/packages/@starter/tsconfig/base.json b/commerce-plp-management/packages/@starter/tsconfig/base.json new file mode 100644 index 0000000..990aefa --- /dev/null +++ b/commerce-plp-management/packages/@starter/tsconfig/base.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "es2024", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "Preserve", + "moduleDetection": "force", + "moduleResolution": "bundler", + "isolatedModules": true, + "verbatimModuleSyntax": true, + "jsx": "preserve", + "incremental": true + } +} diff --git a/commerce-plp-management/packages/@starter/tsconfig/package.json b/commerce-plp-management/packages/@starter/tsconfig/package.json new file mode 100644 index 0000000..bfc4e42 --- /dev/null +++ b/commerce-plp-management/packages/@starter/tsconfig/package.json @@ -0,0 +1,9 @@ +{ + "name": "@starter/tsconfig", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + "./base.json": "./base.json" + } +} diff --git a/commerce-plp-management/pnpm-workspace.yaml b/commerce-plp-management/pnpm-workspace.yaml new file mode 100644 index 0000000..a5c0141 --- /dev/null +++ b/commerce-plp-management/pnpm-workspace.yaml @@ -0,0 +1,17 @@ +packages: + - studio + - frontend + - functions + - packages/@starter/* + +catalog: + sanity: '^5.13.0' + '@sanity/client': '^7.16.0' + '@sanity/vision': '^5.13.0' + groq: '^5.13.0' + react: '^19.2.4' + react-dom: '^19.2.4' + '@types/react': '^19.2' + '@types/react-dom': '^19.2.3' + styled-components: '^6.3.11' + typescript: '^5.9.3' diff --git a/commerce-plp-management/sanity.blueprint.ts b/commerce-plp-management/sanity.blueprint.ts new file mode 100644 index 0000000..cda6867 --- /dev/null +++ b/commerce-plp-management/sanity.blueprint.ts @@ -0,0 +1,79 @@ +/// +import {defineBlueprint, defineDocumentFunction, defineRobotToken} from '@sanity/blueprints' +import 'dotenv/config' + +const { + SANITY_STUDIO_PROJECT_ID, + SANITY_STUDIO_DATASET, + SHOPIFY_STORE_DOMAIN, + SHOPIFY_CLIENT_ID, + SHOPIFY_CLIENT_SECRET, + SHOPIFY_ADMIN_API_TOKEN, + SHOPIFY_ADMIN_API_VERSION, +} = process.env + +if (!SANITY_STUDIO_PROJECT_ID || !SANITY_STUDIO_DATASET) { + throw new Error( + 'Missing required env vars for blueprint deploy: SANITY_STUDIO_PROJECT_ID and SANITY_STUDIO_DATASET must be set in .env', + ) +} + +// Shopify Admin credentials the push-sync functions need at runtime. These are +// sensitive; they live only on the Function runtime, never in the browser. Dev +// Dashboard apps use Client ID/Secret (exchanged for a short-lived token at +// runtime); a legacy static Admin token is also supported. +const shopifyEnv = { + SANITY_STUDIO_PROJECT_ID, + SANITY_STUDIO_DATASET, + SHOPIFY_STORE_DOMAIN: SHOPIFY_STORE_DOMAIN ?? '', + SHOPIFY_CLIENT_ID: SHOPIFY_CLIENT_ID ?? '', + SHOPIFY_CLIENT_SECRET: SHOPIFY_CLIENT_SECRET ?? '', + SHOPIFY_ADMIN_API_TOKEN: SHOPIFY_ADMIN_API_TOKEN ?? '', + SHOPIFY_ADMIN_API_VERSION: SHOPIFY_ADMIN_API_VERSION ?? '2025-07', +} + +export default defineBlueprint({ + resources: [ + defineRobotToken({ + name: 'commerce-plp-robot', + label: 'Commerce PLP Robot', + memberships: [ + { + resourceType: 'project', + resourceId: SANITY_STUDIO_PROJECT_ID, + roleNames: ['editor'], + }, + ], + }), + + // Push-sync: write the sanity_plp_collection metaobject on publish, then + // stamp syncStatus on the document. Fires on published (non-draft) writes. + defineDocumentFunction({ + name: 'collection-sync', + src: 'functions/dist/collection-sync', + event: { + on: ['create', 'update'], + filter: '_type == "collectionEnrichment" && !(_id in path("drafts.**"))', + projection: '{_id, handle}', + }, + timeout: 60, + robotToken: '$.resources.commerce-plp-robot.token', + env: shopifyEnv, + }), + + // Badge vocabulary re-sync: keep Shopify metaobjects current when a shared + // productBadge label/color changes. + defineDocumentFunction({ + name: 'badge-resync', + src: 'functions/dist/badge-resync', + event: { + on: ['create', 'update'], + filter: '_type == "productBadge" && !(_id in path("drafts.**"))', + projection: '{_id}', + }, + timeout: 120, + robotToken: '$.resources.commerce-plp-robot.token', + env: shopifyEnv, + }), + ], +}) diff --git a/commerce-plp-management/scripts/create-storefront-token.ts b/commerce-plp-management/scripts/create-storefront-token.ts new file mode 100644 index 0000000..881f787 --- /dev/null +++ b/commerce-plp-management/scripts/create-storefront-token.ts @@ -0,0 +1,35 @@ +/** + * Mint a public Shopify Storefront API access token from the Admin credentials in + * the root .env, then print the lines to paste into studio/.env and frontend/.env. + * + * Dev Dashboard apps don't expose a static Storefront token in the UI, so this + * creates one via the Admin API. Run once; re-running creates additional tokens. + * + * Usage: pnpm shopify:storefront-token + */ +import 'dotenv/config' +import { + adminConfigFromEnv, + createAdminClient, + createStorefrontAccessToken, +} from '@starter/commerce/shopify' + +const adminConfig = adminConfigFromEnv(process.env) + +if (!adminConfig) { + console.error( + 'Missing Shopify Admin credentials. Set SHOPIFY_STORE_DOMAIN and either\n' + + ' SHOPIFY_CLIENT_ID + SHOPIFY_CLIENT_SECRET, or SHOPIFY_ADMIN_API_TOKEN\n' + + 'in .env', + ) + process.exit(1) +} + +const admin = createAdminClient(adminConfig) +const token = await createStorefrontAccessToken(admin) + +console.log('\n✓ Storefront access token created. Add it to your env files:\n') +console.log('studio/.env:') +console.log(` SANITY_STUDIO_SHOPIFY_STOREFRONT_TOKEN=${token}\n`) +console.log('frontend/.env:') +console.log(` NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN=${token}\n`) diff --git a/commerce-plp-management/scripts/setup-metaobject.ts b/commerce-plp-management/scripts/setup-metaobject.ts new file mode 100644 index 0000000..40175c3 --- /dev/null +++ b/commerce-plp-management/scripts/setup-metaobject.ts @@ -0,0 +1,36 @@ +/** + * One-time Shopify setup: create the `sanity_plp_collection` metaobject + * definition that the push-sync writes to. Idempotent — safe to re-run. + * + * Reads Admin credentials from the root .env. Prefers Dev Dashboard client + * credentials (exchanged for a short-lived token automatically): + * SHOPIFY_STORE_DOMAIN, SHOPIFY_CLIENT_ID, SHOPIFY_CLIENT_SECRET + * or a legacy static token: + * SHOPIFY_STORE_DOMAIN, SHOPIFY_ADMIN_API_TOKEN + * + * Usage: pnpm shopify:setup + */ +import 'dotenv/config' +import { + adminConfigFromEnv, + createAdminClient, + ensureMetaobjectDefinition, + METAOBJECT_TYPE, +} from '@starter/commerce/shopify' + +const adminConfig = adminConfigFromEnv(process.env) + +if (!adminConfig) { + console.error( + 'Missing Shopify Admin credentials. Set SHOPIFY_STORE_DOMAIN and either\n' + + ' SHOPIFY_CLIENT_ID + SHOPIFY_CLIENT_SECRET (Dev Dashboard app), or\n' + + ' SHOPIFY_ADMIN_API_TOKEN (legacy custom app)\n' + + 'in .env', + ) + process.exit(1) +} + +const admin = createAdminClient(adminConfig) + +await ensureMetaobjectDefinition(admin) +console.log(`\n✓ Metaobject definition "${METAOBJECT_TYPE}" is ready in ${adminConfig.domain}\n`) diff --git a/commerce-plp-management/skills/merchandising/SKILL.md b/commerce-plp-management/skills/merchandising/SKILL.md new file mode 100644 index 0000000..c69eb55 --- /dev/null +++ b/commerce-plp-management/skills/merchandising/SKILL.md @@ -0,0 +1,49 @@ +--- +name: merchandising +description: 'Workflows for enriching Shopify collections and coordinating campaigns in this commerce-plp-management starter. Use when adding a banner/faceout/badge/tile to a collection, building a custom campaign collection, scheduling a multi-collection launch via Content Releases, or debugging the Shopify metaobject push-sync.' +--- + +# Merchandising workflows + +Concrete, starter-specific recipes for the `collectionEnrichment` model. + +## Enrich an existing Shopify collection + +1. Create a `collectionEnrichment` document; set `handle` to the exact Shopify + collection handle. Keep `collectionType` as `shopify-native`. +2. Add a `banner` (headline + color block), a `faceout` (pick the hero product), + `editorialTiles` (set 1-based `position`), and `badges` (pick product + badge + + optional start/end dates). +3. Publish. The storefront merges immediately (pull path). The push-sync Function + writes the Shopify metaobject and stamps `syncStatus`. + +Absence of a document = pure Shopify output. Delete the document to fully revert. + +## Build a custom campaign collection (gift guide) + +1. New `collectionEnrichment`; set `collectionType` to `sanity-custom` and choose a + fresh `handle` (e.g. `holiday-gift-guide-2026`). Handle is immutable after + publish. +2. Add products to `productList` with the picker; drag to set curation order + (array order is the order). Sanity owns membership; Shopify supplies live data. +3. Add editorial tiles at positions, and an optional `variantOverrides` entry for + a segment (e.g. `loyalty-member`). +4. Publish. The storefront routes `/collections/` to the custom path and + batch-fetches products by GID. + +## Coordinate a multi-collection campaign + +Use native **Content Releases**: add every affected `collectionEnrichment` to one +release, preview, then schedule. All documents publish atomically; the push-sync +runs per document within seconds. No custom code. + +## Debug the push-sync + +- Check the **Shopify sync** card on the document: `synced` (green), `pending` + (yellow), `failed` (red with error). +- The pull path (storefront) is unaffected by push failures. +- Metaobject definition drift → run `pnpm shopify:setup` to reconcile the + `sanity_plp_collection` definition. The contract lives in + `packages/@starter/commerce/src/shopify/metaobject.ts`. +- Badge label changed but Shopify metaobject stale? The `badge-resync` Function + re-syncs referencing collections on `productBadge` publish. diff --git a/commerce-plp-management/studio/.env.example b/commerce-plp-management/studio/.env.example new file mode 100644 index 0000000..1e4fde1 --- /dev/null +++ b/commerce-plp-management/studio/.env.example @@ -0,0 +1,20 @@ +# Copy this file to .env and fill in your values. +# Loaded by the Studio CLI (sanity.cli.ts -> process.loadEnvFile) and bootstrap. + +# Your Sanity project ID (from sanity.io/manage) +SANITY_STUDIO_PROJECT_ID=your-project-id + +# Dataset name (usually "production") +SANITY_STUDIO_DATASET=production + +# Storefront URL for the Presentation tool live preview +SANITY_STUDIO_PREVIEW_URL=http://localhost:3000 + +# --- Shopify Storefront API (product picker reads the catalog by name) ------- +# Public Storefront token is safe in Studio; it only reads the published catalog. +# Dev Dashboard apps don't show a static Storefront token — mint one with +# `pnpm shopify:storefront-token` (uses the Admin creds in the root .env). +# The Admin Client ID/Secret stay in the ROOT .env only, never here. +SANITY_STUDIO_SHOPIFY_STORE_DOMAIN=your-store.myshopify.com +SANITY_STUDIO_SHOPIFY_STOREFRONT_TOKEN= +SANITY_STUDIO_SHOPIFY_STOREFRONT_API_VERSION=2025-07 diff --git a/commerce-plp-management/studio/components/ProductPickerInput.tsx b/commerce-plp-management/studio/components/ProductPickerInput.tsx new file mode 100644 index 0000000..4240f67 --- /dev/null +++ b/commerce-plp-management/studio/components/ProductPickerInput.tsx @@ -0,0 +1,165 @@ +import {useCallback, useMemo, useState} 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' + +/** + * Object-level input that searches the Shopify catalog by name and stores the + * selected product's GID plus a cached title/image for display in Studio. + * + * Uses the public Storefront token (SANITY_STUDIO_SHOPIFY_*), so it runs safely + * in the browser. We call the Storefront API directly here rather than importing + * @starter/commerce to keep the Studio bundle free of the Node-oriented client. + */ + +type ProductValue = { + _type?: string + productGid?: string + productTitle?: string + productImageUrl?: string +} + +type Suggestion = {value: string; gid: string; title: string; imageUrl?: string} + +const DOMAIN = process.env.SANITY_STUDIO_SHOPIFY_STORE_DOMAIN +const TOKEN = process.env.SANITY_STUDIO_SHOPIFY_STOREFRONT_TOKEN +const API_VERSION = process.env.SANITY_STUDIO_SHOPIFY_STOREFRONT_API_VERSION || '2025-07' + +const SEARCH_QUERY = /* GraphQL */ ` + query PickerSearch($query: String!, $first: Int!) { + products(first: $first, query: $query) { + nodes { + id + title + featuredImage { + url + } + } + } + } +` + +async function searchShopify(term: string): Promise { + if (!DOMAIN || !TOKEN) return [] + const res = await fetch(`https://${DOMAIN}/api/${API_VERSION}/graphql.json`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Shopify-Storefront-Access-Token': TOKEN, + }, + body: JSON.stringify({ + query: SEARCH_QUERY, + variables: {query: term ? `title:*${term}*` : '', first: 10}, + }), + }) + if (!res.ok) return [] + const json = await res.json() + const nodes = json?.data?.products?.nodes ?? [] + return nodes.map((n: {id: string; title: string; featuredImage?: {url: string}}) => ({ + value: n.id, + gid: n.id, + title: n.title, + imageUrl: n.featuredImage?.url, + })) +} + +export function ProductPickerInput(props: ObjectInputProps) { + const {value, onChange, schemaType} = props + const [suggestions, setSuggestions] = useState([]) + const [loading, setLoading] = useState(false) + + 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) + if (!picked) return + onChange( + set({ + _type: schemaType.name, + productGid: picked.gid, + productTitle: picked.title, + productImageUrl: picked.imageUrl, + }), + ) + }, + [onChange, schemaType.name, suggestions], + ) + + const handleClear = useCallback(() => onChange(unset()), [onChange]) + + const options = useMemo( + () => suggestions.map((s) => ({value: s.value, title: s.title})), + [suggestions], + ) + + return ( + + {value?.productGid ? ( + + + {value.productImageUrl ? ( + + ) : null} + + + {value.productTitle || 'Selected product'} + + + {value.productGid} + + +