Skip to content

feat: forward Pricing Fallback price token to Checkout - #3415

Merged
lemagnetic merged 6 commits into
devfrom
feat/price-token
Jul 27, 2026
Merged

lemagnetic merged 6 commits into
devfrom
feat/price-token

Conversation

@lemagnetic

@lemagnetic lemagnetic commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

Pricing is a single point of failure in VTEX's sales flow. Pricing Fallback lets the storefront forward a signed price (JWT) so Checkout can trust the shelf price and keep closing orders even when the Pricing System is down. This PR makes FastStore forward the priceToken that Intelligent Search now emits, all the way into Checkout's add-to-cart.

How it works?

The signed token (commertialOffer.PriceToken from Intelligent Search) is piped through the existing offer → cart → validateCart path, no new operations:

  • @faststore/api: expose priceToken on StoreOffer/IStoreOffer, resolve it from the search offer, and map it to Checkout's OrderFormInputItem.priceToken (only when present).
  • @faststore/core: request priceToken in the offer/cart fragments and send it on ValidateCartMutation. With enableClientOffer, the PDP prefers a fresh token from useOffer (IS fetched client-side) since the token is short-lived (~30 min).
  • @faststore/components: optional priceToken on SKU Matrix / Product Comparison offer types (typing only).

The field is fully optional: when Intelligent Search omits it (flag off / signing failure / non-IS offer), behavior is identical to today. Invalid/expired tokens are treated as unsigned by Checkout, with no storefront error.

Also fixes a cart validation loop: equals() in validateCart was comparing the full offer, so the browser-only priceToken (absent on the orderForm response) made carts never match, looping ValidateCartMutation. It now ignores priceToken.

How to test it?

  • Use an account with the Intelligent Search Pricing Fallback flag enabled.
  • Open a PDP and confirm the product query returns offers.offers[].priceToken.
  • Add to cart and check the ValidateCartMutation request: acceptedOffer[].priceToken carries the JWT.
  • Confirm the cart syncs and ValidateCartMutation does not loop.
  • On an account without the flag, confirm add-to-cart works with no priceToken sent.

Starters Deploy Preview

References

  • Jira:

Summary by CodeRabbit

  • New Features
    • Added pricing token support across product offers, carts, checkout payloads, and buy-button flows.
    • Updated PDP, product cards/details, search results, comparisons, and SKU matrix UI to fetch and forward pricing tokens.
    • Enhanced offer fetching so client results can refresh the active pricing token for add-to-cart.
  • Bug Fixes
    • Prevented pricing-token-only changes from causing false “cart changed” detections during cart validation.
    • Improved GraphQL/schema and resolver behavior when tokens are unavailable, ensuring consistent null handling.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5e095d41-bc34-4e0e-be43-582089dcedc9

📥 Commits

Reviewing files that changed from the base of the PR and between 307c68e and b2d6770.

⛔ Files ignored due to path filters (3)
  • packages/api/src/__generated__/schema.ts is excluded by !**/__generated__/** and included by packages/**
  • packages/core/@generated/gql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
  • packages/core/@generated/graphql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
📒 Files selected for processing (17)
  • packages/api/src/platforms/vtex/clients/commerce/types/OrderForm.ts
  • packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.ts
  • packages/api/src/platforms/vtex/resolvers/offer.ts
  • packages/api/src/platforms/vtex/resolvers/validateCart.ts
  • packages/api/src/platforms/vtex/typeDefs/offer.graphql
  • packages/components/src/organisms/ProductComparison/provider/ProductComparisonProvider.tsx
  • packages/components/src/organisms/SKUMatrix/provider/SKUMatrixProvider.tsx
  • packages/core/src/components/product/ProductCard/ProductCard.tsx
  • packages/core/src/components/search/SearchProductItem/SearchProductItem.tsx
  • packages/core/src/components/sections/ProductDetails/ProductDetails.tsx
  • packages/core/src/components/ui/ProductComparison/ProductComparisonSidebar.tsx
  • packages/core/src/components/ui/ProductDetails/ProductDetailsSettings.tsx
  • packages/core/src/components/ui/SKUMatrix/SKUMatrixSidebar.tsx
  • packages/core/src/pages/[slug]/p.tsx
  • packages/core/src/sdk/account/useReorder.ts
  • packages/core/src/sdk/cart/index.ts
  • packages/core/src/sdk/offer/index.ts
🚧 Files skipped from review as they are similar to previous changes (16)
  • packages/components/src/organisms/SKUMatrix/provider/SKUMatrixProvider.tsx
  • packages/api/src/platforms/vtex/typeDefs/offer.graphql
  • packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.ts
  • packages/core/src/components/sections/ProductDetails/ProductDetails.tsx
  • packages/components/src/organisms/ProductComparison/provider/ProductComparisonProvider.tsx
  • packages/core/src/pages/[slug]/p.tsx
  • packages/api/src/platforms/vtex/clients/commerce/types/OrderForm.ts
  • packages/core/src/components/ui/ProductComparison/ProductComparisonSidebar.tsx
  • packages/core/src/components/ui/ProductDetails/ProductDetailsSettings.tsx
  • packages/core/src/components/ui/SKUMatrix/SKUMatrixSidebar.tsx
  • packages/core/src/sdk/cart/index.ts
  • packages/api/src/platforms/vtex/resolvers/offer.ts
  • packages/core/src/components/search/SearchProductItem/SearchProductItem.tsx
  • packages/core/src/sdk/offer/index.ts
  • packages/core/src/sdk/account/useReorder.ts
  • packages/api/src/platforms/vtex/resolvers/validateCart.ts

Walkthrough

VTEX price tokens are added to offer contracts, exposed through GraphQL, refreshed on the PDP, propagated through product components and SDK cart items, and included in cart validation payloads.

Changes

VTEX pricing token flow

Layer / File(s) Summary
VTEX offer contracts and resolvers
packages/api/src/platforms/vtex/...
Commerce/search types and GraphQL offer types expose optional price tokens; resolvers map search tokens and cart validation preserves them while excluding them from stale-cart comparisons.
Offer and cart SDK propagation
packages/core/src/sdk/offer/index.ts, packages/core/src/sdk/cart/index.ts, packages/core/src/sdk/account/useReorder.ts
useOffer returns the best seller token, cart validation forwards tokens, and reorder payload handling adds nullable defaults.
Product offer data and buy-button wiring
packages/components/src/organisms/..., packages/core/src/components/...
Product fragments request priceToken, comparison and SKU Matrix models retain it, and product components pass it to useBuyButton.
PDP token refresh
packages/core/src/pages/[slug]/p.tsx
When client offers are enabled, server seller offers are retained while the first offer receives the latest client-fetched token.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant VTEXSearch
  participant StoreOffer
  participant ProductComponent
  participant useBuyButton
  participant validateCart
  VTEXSearch->>StoreOffer: Return PriceToken
  StoreOffer->>ProductComponent: Expose priceToken through GraphQL
  ProductComponent->>useBuyButton: Pass priceToken
  useBuyButton->>validateCart: Include priceToken in acceptedOffer
Loading

Possibly related PRs

  • vtex/faststore#3153: Modifies the reorder cart-item transformation extended here with priceToken handling.
  • vtex/faststore#3220: Modifies the VTEX offer resolver and isGift handling touched by this change.
  • vtex/faststore#3224: Also modifies cart revalidation and reorder flow handling.

Suggested reviewers: gabpaladino, eduardoformiga, emersonlaurentino, hellofanny

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: forwarding the Pricing Fallback price token to Checkout.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/price-token

Comment @coderabbitai help to get the list of available commands.

@codesandbox-ci

codesandbox-ci Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@pkg-pr-new

pkg-pr-new Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@b2d6770

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@b2d6770

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@b2d6770

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@b2d6770

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@b2d6770

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@b2d6770

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@b2d6770

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@b2d6770

commit: b2d6770

@lemagnetic lemagnetic added the enhancement New feature or request label Jul 17, 2026
@lemagnetic
lemagnetic marked this pull request as ready for review July 21, 2026 14:07
@lemagnetic
lemagnetic requested a review from a team as a code owner July 21, 2026 14:07
@lemagnetic
lemagnetic requested review from gabpaladino and renatomaurovtex and removed request for a team July 21, 2026 14:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/platforms/vtex/resolvers/validateCart.ts`:
- Line 81: Update the existing-item update flow in validateCart, where
itemsToUpdate are mapped through offerToOrderItemInput, to merge each matching
browser item’s priceToken into the offer before mapping changes. Preserve the
existing token when present and ensure quantity and parent/child updates forward
it; add regression coverage for this update path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a8dc1456-84f9-4ea6-b502-74606c60a724

📥 Commits

Reviewing files that changed from the base of the PR and between e0e8188 and d8aae85.

⛔ Files ignored due to path filters (3)
  • packages/api/src/__generated__/schema.ts is excluded by !**/__generated__/** and included by packages/**
  • packages/core/@generated/gql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
  • packages/core/@generated/graphql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
📒 Files selected for processing (17)
  • packages/api/src/platforms/vtex/clients/commerce/types/OrderForm.ts
  • packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.ts
  • packages/api/src/platforms/vtex/resolvers/offer.ts
  • packages/api/src/platforms/vtex/resolvers/validateCart.ts
  • packages/api/src/platforms/vtex/typeDefs/offer.graphql
  • packages/components/src/organisms/ProductComparison/provider/ProductComparisonProvider.tsx
  • packages/components/src/organisms/SKUMatrix/provider/SKUMatrixProvider.tsx
  • packages/core/src/components/product/ProductCard/ProductCard.tsx
  • packages/core/src/components/search/SearchProductItem/SearchProductItem.tsx
  • packages/core/src/components/sections/ProductDetails/ProductDetails.tsx
  • packages/core/src/components/ui/ProductComparison/ProductComparisonSidebar.tsx
  • packages/core/src/components/ui/ProductDetails/ProductDetailsSettings.tsx
  • packages/core/src/components/ui/SKUMatrix/SKUMatrixSidebar.tsx
  • packages/core/src/pages/[slug]/p.tsx
  • packages/core/src/sdk/account/useReorder.ts
  • packages/core/src/sdk/cart/index.ts
  • packages/core/src/sdk/offer/index.ts

@eduardoformiga eduardoformiga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job.
I just left some questions to double-check 😉

)
}

const { client, isValidating } = isClientOfferEnabled

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure the clients are using this isClientOfferEnabled feature, but it's ok to add here anyway

Comment on lines +77 to +79
quantity: item.quantity ?? 0,
seller: {
identifier: item.seller,
identifier: item.seller ?? '',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need these changes here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

não necessariamente, só corrigi pq essas linhas estavam vermelhas na validação do typescript, mas acho que não bloqueia o build não hehe

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boa! Meu receio é ter algum efeito colateral…

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

justo! acho melhor remover então

},
price: item.price ?? 0,
listPrice: item.price ?? 0,
priceToken: null,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this really be null?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

adicionei o priceToken null apenas para corrigir um erro de tipagem,
erro

Property 'priceToken' is missing in type '{ quantity: number; seller: { identifier: string; }; price: number; listPrice: number; itemOffered: { sku: string; image: { url: string; alternateName: string; }[]; name: string; additionalProperty: AdditionalProperties; }; }' but required in type 'IStoreOffer'

Mas parando pra pensar agora, realmente talvez precise mandar o priceToken aqui também, mas pra isso ele precisaria vir nessa API aqui /api/oms/user/orders/{orderId}. Ai conseguimos mandar na ação de Refazer o Pedido.

Valeu demais pela observação, vou consultar outros times para ver se essa API de orders vai receber o priceToken também!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consultei o time, não precisa do priceToken no ReOrder

@renatomaurovtex renatomaurovtex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — feat: forward Pricing Fallback price token to Checkout

Design is sound: the token rides the existing offer → cart → validateCart path with no new operations, the schema addition is optional/additive (backward compatible), and the whole feature fails open — no token, expired token, or invalid token all degrade to today's unsigned behavior. I verified the equals() fix is symmetric (pick strips priceToken from both the browser payload and the orderForm-derived items, and orderFormItemToOffer never produces one), so the ValidateCartMutation loop fix is correct. offerToOrderItemInput is the single mapping used for the updateOrderFormItems delta (adds/updates/deletes), so forwarding is covered on all item-change paths. Generated files (packages/api/src/__generated__/schema.ts, packages/core/@generated/*) are consistent fragment-by-fragment with the .graphql/gql() source changes — please just confirm they came from pnpm codegen.

packages/api/src/platforms/vtex/resolvers/validateCart.ts

🟠 [tests] No coverage for the two behaviors this PR exists for. The equals() token-omission fix addresses a real regression you hit (the validation loop), and offerToOrderItemInput conditionally forwarding priceToken is the core of the feature — neither has a test. packages/api/test/integration/mutations.test.ts + test/mocks/ValidateCartMutation.ts already exist; two cheap cases would lock this in:

  1. cart in sync except browser items carry priceToken → validateCart returns null (no loop);
  2. item change with priceToken set → the updateOrderFormItems payload includes it, and omits the key when absent.

packages/core/src/pages/[slug]/p.tsx

🟡 [edge case] withFreshPriceToken can attach seller A's token to seller B's offer. The fresh token comes from the client-side best seller (sellers[0] after bestOfferFirst in useOffer), but it's injected into serverOffers.offers[0] — the SSG-time first offer. When the best seller changes between build and client fetch (price/availability drift — exactly what enableClientOffer exists for), the token won't match the offer it's attached to. Checkout fails open (treats it as unsigned), so the cost is silently losing fallback protection, not breakage — but matching by seller would make the token actually valid in that scenario:

-  offers: serverOffers.offers.map((offerItem, index) =>
-    index === 0
-      ? { ...offerItem, priceToken: offer.priceToken ?? offerItem.priceToken }
-      : offerItem
-  ),
+  offers: serverOffers.offers.map((offerItem) =>
+    offerItem.seller.identifier === offer.bestSellerId
+      ? { ...offerItem, priceToken: offer.priceToken ?? offerItem.priceToken }
+      : offerItem
+  ),

(with useOffer returning the best seller's identifier alongside the token). If you consider the drift window acceptable, a comment stating the assumption is enough.

packages/core/src/sdk/account/useReorder.ts

💬 [hygiene] Does the defensive churn need to be in this diff? quantity: item.quantity ?? 0, identifier: item.seller ?? '', result?.validateCart ?? null, shouldSplitItem ?? undefined are behavior-neutral (the preceding .filter already guarantees those fields) and read like leftovers from fighting regenerated types. The only line this PR needs here is priceToken: null. Fine to keep if intentional, but worth a rebase check.

PR body

💬 The Jira link and Starters deploy preview are still TODO placeholders — please fill the Jira ref so the change is traceable, and a deploy preview would make the "token in ValidateCartMutation payload" test steps easy to verify.

Verdict: Approved with comments

Blocking (🔴/🟠):

  • Add the two validateCart test cases (loop-fix regression + conditional token forwarding) before merge.

Non-blocking (🟡/💬):

  • withFreshPriceToken seller-mismatch edge (or document the assumption).
  • useReorder unrelated defensive changes.
  • PR body TODOs (Jira / deploy preview).

Checks to confirm before merge: pnpm test in packages/api (with the new cases) · UI Tests (Chromatic) still pending at review time · pnpm size for core/components (expected ~neutral — fragments grow by one scalar field).

@sonar-workflows

Copy link
Copy Markdown

@lemagnetic
lemagnetic merged commit bc6cda2 into dev Jul 27, 2026
11 checks passed
@lemagnetic
lemagnetic deleted the feat/price-token branch July 27, 2026 17:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants