Repository navigation
feat: forward Pricing Fallback price token to Checkout - #3415
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (3)
📒 Files selected for processing (17)
🚧 Files skipped from review as they are similar to previous changes (16)
WalkthroughVTEX 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. ChangesVTEX pricing token flow
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
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
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. |
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (3)
packages/api/src/__generated__/schema.tsis excluded by!**/__generated__/**and included bypackages/**packages/core/@generated/gql.tsis excluded by!**/@generated/**,!**/@generated/**and included bypackages/**packages/core/@generated/graphql.tsis excluded by!**/@generated/**,!**/@generated/**and included bypackages/**
📒 Files selected for processing (17)
packages/api/src/platforms/vtex/clients/commerce/types/OrderForm.tspackages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.tspackages/api/src/platforms/vtex/resolvers/offer.tspackages/api/src/platforms/vtex/resolvers/validateCart.tspackages/api/src/platforms/vtex/typeDefs/offer.graphqlpackages/components/src/organisms/ProductComparison/provider/ProductComparisonProvider.tsxpackages/components/src/organisms/SKUMatrix/provider/SKUMatrixProvider.tsxpackages/core/src/components/product/ProductCard/ProductCard.tsxpackages/core/src/components/search/SearchProductItem/SearchProductItem.tsxpackages/core/src/components/sections/ProductDetails/ProductDetails.tsxpackages/core/src/components/ui/ProductComparison/ProductComparisonSidebar.tsxpackages/core/src/components/ui/ProductDetails/ProductDetailsSettings.tsxpackages/core/src/components/ui/SKUMatrix/SKUMatrixSidebar.tsxpackages/core/src/pages/[slug]/p.tsxpackages/core/src/sdk/account/useReorder.tspackages/core/src/sdk/cart/index.tspackages/core/src/sdk/offer/index.ts
eduardoformiga
left a comment
There was a problem hiding this comment.
Good job.
I just left some questions to double-check 😉
| ) | ||
| } | ||
|
|
||
| const { client, isValidating } = isClientOfferEnabled |
There was a problem hiding this comment.
I'm not sure the clients are using this isClientOfferEnabled feature, but it's ok to add here anyway
| quantity: item.quantity ?? 0, | ||
| seller: { | ||
| identifier: item.seller, | ||
| identifier: item.seller ?? '', |
There was a problem hiding this comment.
Do we need these changes here?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Boa! Meu receio é ter algum efeito colateral…
There was a problem hiding this comment.
justo! acho melhor remover então
| }, | ||
| price: item.price ?? 0, | ||
| listPrice: item.price ?? 0, | ||
| priceToken: null, |
There was a problem hiding this comment.
Should this really be null?
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
Consultei o time, não precisa do priceToken no ReOrder
renatomaurovtex
left a comment
There was a problem hiding this comment.
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:
- cart in sync except browser items carry
priceToken→validateCartreturnsnull(no loop); - item change with
priceTokenset → theupdateOrderFormItemspayload 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
validateCarttest cases (loop-fix regression + conditional token forwarding) before merge.
Non-blocking (🟡/💬):
withFreshPriceTokenseller-mismatch edge (or document the assumption).useReorderunrelated 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).
307c68e to
b2d6770
Compare
|

0 New Issues
0 Fixed Issues
0 Accepted Issues
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
priceTokenthat Intelligent Search now emits, all the way into Checkout's add-to-cart.How it works?
The signed token (
commertialOffer.PriceTokenfrom Intelligent Search) is piped through the existing offer → cart →validateCartpath, no new operations:@faststore/api: exposepriceTokenonStoreOffer/IStoreOffer, resolve it from the search offer, and map it to Checkout'sOrderFormInputItem.priceToken(only when present).@faststore/core: requestpriceTokenin the offer/cart fragments and send it onValidateCartMutation. WithenableClientOffer, the PDP prefers a fresh token fromuseOffer(IS fetched client-side) since the token is short-lived (~30 min).@faststore/components: optionalpriceTokenon 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()invalidateCartwas comparing the full offer, so the browser-onlypriceToken(absent on the orderForm response) made carts never match, loopingValidateCartMutation. It now ignorespriceToken.How to test it?
offers.offers[].priceToken.ValidateCartMutationrequest:acceptedOffer[].priceTokencarries the JWT.ValidateCartMutationdoes not loop.priceTokensent.Starters Deploy Preview
References
Summary by CodeRabbit