Skip to content

feat: My Account Cards — Personal + Shared listing - #3443

Merged
ArthurTriis1 merged 14 commits into
devfrom
feat/my-account-cards
Aug 24, 2026
Merged

ArthurTriis1 merged 14 commits into
devfrom
feat/my-account-cards

Conversation

@ArthurTriis1

@ArthurTriis1 ArthurTriis1 commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds a "Cards" area to My Account (/pvt/account/cards) listing the buyer's personal payment cards and, when applicable, their Organization's/Contract's shared cards.

  • @faststore/api: new commerce.savedCards client + listCreditCards GraphQL query against the Saved-cards service; SavedCard.origin (personal | shared) added and mapped through, using the service's own tagging instead of a second endpoint/round trip; cardLabel (buyer/admin-set nickname, when the service has one on file) exposed and preferred over paymentSystemName for display; hasAdHocCardAccess query resolving the UseAdHocCard License Manager resource key for the current user (fail-open on any downstream error).
  • @faststore/core: MyAccountListCards component (Personal/Shared tabs, search, pagination, empty/error states) wired into the Cards page via SSR (mirrors the My Orders listing pattern); Personal and Shared cards are partitioned client-side from the single listCreditCards response by origin — no cards are de-duplicated across origins by design (a card present in both is shown in both tabs).
  • Personal-tab permission gate: useAdHocCard turned out to be a License Manager resource key resolved from roles, not a session-token claim as first assumed. The route itself and the sidebar entry are never gated — only the Personal tab's visibility is, via customerId + hasAdHocCardAccess. When a Unit/Contract-affiliated buyer lacks that permission, only the Shared list renders, with no tab chrome. The two remaining combinations without a Unit/Contract association are left exactly as the component already behaved, pending product confirmation on the intended render (tracked as O1 in the spec — see below).

Authorization-change approval: this permission-model correction (removing the route-level 404 gate, replacing it with Personal-tab visibility) was walked through and approved by Arthur Andrade in the implementing session before being built, per AGENTS.md's requirement for auth-mechanism changes.

Tests

  • packages/api/test/unit/platforms/vtex/resolvers/savedCards.test.ts: origin and cardLabel passthrough on listCreditCards.
  • packages/api/test/unit/platforms/vtex/resolvers/hasAdHocCardAccess.test.ts: grant / deny / error fail-open / non-boolean fail-open / no-userId short circuit / malformed-cookie regression.
  • packages/api/test/integration/vtex.cookies.test.ts, packages/core/test/utils/getCookie.test.ts: parseJwt no longer throws on a malformed auth cookie (both packages' copies).
  • packages/core/test/components/account/cards/MyAccountListCards.browser.test.tsx: tab switching, arrow-key nav, search (incl. by cardLabel), pagination, empty/error states, default badge, label precedence/fallback, the sharedOnly and no-org-association tab-chrome combinations.
  • packages/core/test/components/sections/Account/AccountListCards.browser.test.tsx, packages/core/test/pages/pvt/account/cards/index.test.ts, packages/core/test/sdk/account/getB2BSessionClaims.test.ts: section wrapper and getServerSideProps branch coverage.
  • packages/core/test/server/index.test.ts, packages/api/test/integration/schema.test.ts: schema query-list regression tests updated for the new queries.
  • SonarQube Quality Gate: passing, 94.10% coverage on new code.
  • Full suites green on every push; typecheck clean on every file touched.

Deviations

  • The parent implementation spec originally modeled the Personal-tab permission as a route-level 404 gate. That was corrected mid-implementation once useAdHocCard's real semantics (a resolved License Manager role, not a token claim) were confirmed — see the "Personal-tab permission gate" point above. The route and sidebar entry are never blocked; only Personal-tab visibility is conditional.
  • A related backend defect was found while testing against a live B2B account: GET /credit-card on the Saved-cards service returns a generic unhandled-exception 500 for at least one real session (reproduced independently via curl, isolating it from this BFF). Likely cause: RequestContextResolver.ResolveUserId() throws unhandled when User.UserId is absent, a path newly introduced by the service's own recent PR. Flagged to the Saved-cards team with trace IDs; since fixed on their end and reconfirmed working in this session.

Spec

  • vtex/faststore-dx-spec-kit#24 — my-account-cards.md, my-account-cards-gating-plan.md, my-account-cards-shared-listing-unblock.md

Summary by CodeRabbit

  • New Features
    • Added a My Account Cards page for viewing personal and shared saved payment cards.
    • Added card search, tabs, pagination, empty states, default-card indicators, and responsive layouts.
    • Added CMS configuration and navigation support for the Cards page.
    • Added access checks to control personal-card visibility.
  • Bug Fixes
    • Malformed authentication tokens are now handled safely without disrupting page rendering.
    • Card-service and permission errors provide appropriate fallback and recovery states.
  • Tests
    • Added coverage for card retrieval, access checks, authentication handling, and schema updates.

ArthurTriis1 and others added 2 commits July 29, 2026 10:24
Adds a new My Account page listing the buyer's saved credit cards,
split into Personal and Shared (B2B) tabs, backed by the Saved-cards
service via a new GraphQL listCreditCards query.

- API: commerce client + resolver for Saved-cards' GET /credit-card
- Core: MyAccountListCards component, SSR page, route registration
- B2B gate for the Shared tab and the ad-hoc-card access claim
- Fixes a latent fetchMyAccountPageContent bug where a brand-new
  content type with zero CMS entries resolved pageContent to
  undefined instead of falling back to an empty default

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The Saved-cards service now returns personal and shared cards merged in one
listing, each tagged `origin`, closing the "shared-cards data source
unconfirmed" risk from the parent spec: expose `origin` on `SavedCard` and
partition the single query response into personal/shared in the Cards page,
replacing the previous empty stub.

Separately, `useAdHocCard` was found to be a License Manager resource key
resolved from roles, not a session token claim as originally assumed - the
route-level 404 gate built on that assumption never actually enforced
anything and blocked the page outright once the real permission check landed.
Rectify it to gate only the Personal tab's visibility (customerId +
UseAdHocCard), never route access or the sidebar entry, per the corrected
PRD reading.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@ArthurTriis1
ArthurTriis1 requested a review from a team as a code owner August 11, 2026 22:09
@ArthurTriis1
ArthurTriis1 requested review from eduardoformiga and renatomaurovtex and removed request for a team August 11, 2026 22:09
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

The PR adds VTEX saved-card GraphQL APIs and a Cards My Account page. It adds personal/shared card rendering, access checks, CMS integration, route registration, JWT error handling, caching, and automated coverage.

Changes

Saved cards account flow

Layer / File(s) Summary
Saved-card API contracts
packages/api/src/platforms/vtex/clients/commerce/index.ts, packages/api/src/platforms/vtex/resolvers/query.ts, packages/api/src/platforms/vtex/typeDefs/*, packages/api/test/*
Adds saved-card retrieval and License Manager access queries. Adds GraphQL types, private caching, fail-open handling, and resolver and schema coverage.
Cards page data loading
packages/core/src/pages/pvt/account/cards/index.tsx, packages/core/src/sdk/account/*, packages/core/src/utils/getCookie.ts, packages/core/test/pages/*, packages/core/test/sdk/*, packages/core/test/utils/*
Adds server-side card loading, JWT claim extraction, access gating, error handling, and personal/shared card partitioning.
Cards list rendering
packages/core/src/components/account/cards/MyAccountListCards/*, packages/core/src/components/sections/Account/AccountListCards.tsx, packages/core/test/components/*
Adds localized labels, accessible personal/shared tabs, search, pagination, keyboard navigation, error states, responsive styling, and card rendering.
Account navigation and CMS wiring
packages/core/src/sdk/account/getMyAccountRoutes.ts, packages/core/src/server/cms/myAccountDefaultSections.ts, packages/core/src/components/cms/account/Components.ts, packages/core/src/components/account/Layout/Layout.tsx, packages/core/test/sdk/account/getMyAccountRoutes.test.ts
Adds the Cards route, native CMS section mapping, component registration, route tests, and route visibility documentation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant ListCardsPage
  participant GraphQLAPI
  participant VTEXCommerce
  participant LicenseManager
  Browser->>ListCardsPage: request Cards account route
  ListCardsPage->>GraphQLAPI: request cards, profile, and ad-hoc access
  GraphQLAPI->>VTEXCommerce: fetch saved credit cards
  VTEXCommerce-->>GraphQLAPI: return SavedCard[]
  GraphQLAPI->>LicenseManager: check UseAdHocCard for userId
  LicenseManager-->>GraphQLAPI: return access boolean
  GraphQLAPI-->>ListCardsPage: return card data and access state
  ListCardsPage-->>Browser: render personal/shared card lists
Loading

Possibly related PRs

  • vtex/faststore#3354: Modifies related account layout, CMS registry, page context, and My Account composition.
  • vtex/faststore#3406: Connects My Account schema and content additions to the CMS merge flow.
  • vtex/faststore#3411: Modifies related My Account routing and default CMS section infrastructure.

Suggested labels: enhancement

Suggested reviewers: renatomaurovtex, eduardoformiga

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.37% 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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding a My Account Cards area for personal and shared card listings.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/my-account-cards

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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: 5

🧹 Nitpick comments (2)
packages/core/src/components/account/cards/MyAccountListCards/index.ts (1)

1-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Re-export the labels contract from the barrel.

MyAccountListCardsProps.labels is typed as MyAccountListCardsSectionLabels, but the barrel does not export that type or defaultMyAccountListCardsLabels. packages/core/src/components/sections/Account/AccountListCards.tsx therefore imports the component from the barrel and the labels from the deep path. Export the labels surface here so consumers use one entry point.

📦 Proposed addition
 export { default as MyAccountListCards } from './MyAccountListCards'
 export type {
   MyAccountListCardsProps,
   SavedCardItem,
   CardsTabVariant,
 } from './MyAccountListCards'
+export {
+  defaultMyAccountListCardsLabels,
+  resolveMyAccountListCardsLabels,
+} from './myAccountListCardsLabels'
+export type { MyAccountListCardsSectionLabels } from './myAccountListCardsLabels'
🤖 Prompt for 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.

In `@packages/core/src/components/account/cards/MyAccountListCards/index.ts`
around lines 1 - 6, Update the MyAccountListCards barrel exports to include the
MyAccountListCardsSectionLabels type and defaultMyAccountListCardsLabels value
from MyAccountListCards, so consumers can import the component and its labels
contract from one entry point.
packages/core/src/components/sections/Account/AccountListCards.tsx (1)

12-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the duplicated label defaults.

resolveMyAccountListCardsLabels already merges the defaults, and MyAccountListCards calls it at line 90 of packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx. This section repeats the same merge as 14 destructuring defaults. The defaults now exist in two places, so a future label addition must be edited twice. Pass the props through and let the child resolve them.

♻️ Proposed refactor
-const AccountListCards = ({
-  pageTitle = defaultMyAccountListCardsLabels.pageTitle,
-  personalTabLabel = defaultMyAccountListCardsLabels.personalTabLabel,
-  sharedTabLabel = defaultMyAccountListCardsLabels.sharedTabLabel,
-  searchPlaceholder = defaultMyAccountListCardsLabels.searchPlaceholder,
-  paginationOfLabel = defaultMyAccountListCardsLabels.paginationOfLabel,
-  previousPageLabel = defaultMyAccountListCardsLabels.previousPageLabel,
-  nextPageLabel = defaultMyAccountListCardsLabels.nextPageLabel,
-  noPersonalCardsLabel = defaultMyAccountListCardsLabels.noPersonalCardsLabel,
-  noSharedCardsLabel = defaultMyAccountListCardsLabels.noSharedCardsLabel,
-  noResultsLabel = defaultMyAccountListCardsLabels.noResultsLabel,
-  errorTitleLabel = defaultMyAccountListCardsLabels.errorTitleLabel,
-  tryAgainLabel = defaultMyAccountListCardsLabels.tryAgainLabel,
-  sharedCardsTooltipLabel = defaultMyAccountListCardsLabels.sharedCardsTooltipLabel,
-  defaultCardLabel = defaultMyAccountListCardsLabels.defaultCardLabel,
-}: AccountListCardsProps) => {
+const AccountListCards = (labels: AccountListCardsProps) => {

Then pass labels={labels} at line 44 and drop the defaultMyAccountListCardsLabels import on line 3.

🤖 Prompt for 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.

In `@packages/core/src/components/sections/Account/AccountListCards.tsx` around
lines 12 - 27, Remove the 14 default label values from the AccountListCards
props destructuring and pass the label props through unchanged, allowing
MyAccountListCards to resolve them via resolveMyAccountListCardsLabels. Update
the child invocation to pass labels={labels} and remove the now-unused
defaultMyAccountListCardsLabels import.
🤖 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/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx`:
- Around line 264-272: Update the card label rendering in MyAccountListCards so
a null paymentSystemName no longer falls back to labels.pageTitle (“Cards”); use
the appropriate dedicated card-brand label if available, otherwise render no
fallback text, while preserving the existing default-card badge behavior.
- Around line 148-180: Complete the ARIA tabs pattern in MyAccountListCards:
give both tabs unique id and matching aria-controls values, wrap the card grid
and empty state in a role="tabpanel" element with aria-labelledby for the active
tab, and add ArrowLeft/ArrowRight handling on the tablist with wraparound focus
movement. Move the shared-tab Tooltip trigger outside the tab button so it
remains keyboard reachable without nesting an interactive control inside the
tab.
- Around line 231-241: Replace the retry LinkButton with the `@faststore/ui`
Button and remove the href-based navigation behavior. In the MyAccountListCards
component, use next/router’s useRouter and trigger the reload through the router
while preserving the existing retry label and data-fs-list-cards-retry
attribute.
- Around line 96-105: Update MyAccountListCards so tab availability is derived
directly from canViewPersonalCards and hasOrgAssociation: preserve shared-only
behavior for organizational users without personal access, but introduce a
noTabAvailable state when neither personal nor shared cards are permitted. When
noTabAvailable is true, skip the tab bar and card grid and render the
component’s dedicated empty or unauthorized state instead.

In `@packages/core/src/sdk/account/getB2BSessionClaims.ts`:
- Around line 36-41: The JWT decoding flows must handle malformed authentication
cookies without throwing. In
packages/core/src/sdk/account/getB2BSessionClaims.ts lines 36-41, update
parseJwt or its caller so invalid structure, base64, or JSON produces null and
preserves the existing no-B2B-claims fallback. In
packages/api/src/platforms/vtex/resolvers/query.ts lines 632-633, apply the same
null-on-invalid behavior so malformed cookies resolve as no user; use the
existing JWT decoder symbols and do not alter valid-cookie handling.

---

Nitpick comments:
In `@packages/core/src/components/account/cards/MyAccountListCards/index.ts`:
- Around line 1-6: Update the MyAccountListCards barrel exports to include the
MyAccountListCardsSectionLabels type and defaultMyAccountListCardsLabels value
from MyAccountListCards, so consumers can import the component and its labels
contract from one entry point.

In `@packages/core/src/components/sections/Account/AccountListCards.tsx`:
- Around line 12-27: Remove the 14 default label values from the
AccountListCards props destructuring and pass the label props through unchanged,
allowing MyAccountListCards to resolve them via resolveMyAccountListCardsLabels.
Update the child invocation to pass labels={labels} and remove the now-unused
defaultMyAccountListCardsLabels import.
🪄 Autofix

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 Plus

Run ID: 68b46bce-3a3d-416e-9970-d64123bf146b

📥 Commits

Reviewing files that changed from the base of the PR and between 74e2d50 and 0e676b9.

⛔ Files ignored due to path filters (4)
  • 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/**
  • packages/core/public/icons.svg is excluded by !**/*.svg and included by packages/**
📒 Files selected for processing (20)
  • packages/api/src/platforms/vtex/clients/commerce/index.ts
  • packages/api/src/platforms/vtex/resolvers/query.ts
  • packages/api/src/platforms/vtex/typeDefs/query.graphql
  • packages/api/src/platforms/vtex/typeDefs/savedCard.graphql
  • packages/api/test/unit/platforms/vtex/resolvers/hasAdHocCardAccess.test.ts
  • packages/api/test/unit/platforms/vtex/resolvers/savedCards.test.ts
  • packages/core/src/components/account/Layout/Layout.tsx
  • packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx
  • packages/core/src/components/account/cards/MyAccountListCards/index.ts
  • packages/core/src/components/account/cards/MyAccountListCards/myAccountListCardsLabels.ts
  • packages/core/src/components/account/cards/MyAccountListCards/styles.module.scss
  • packages/core/src/components/cms/account/Components.ts
  • packages/core/src/components/sections/Account/AccountListCards.tsx
  • packages/core/src/pages/pvt/account/cards/index.tsx
  • packages/core/src/sdk/account/accountPageContext.ts
  • packages/core/src/sdk/account/getB2BSessionClaims.ts
  • packages/core/src/sdk/account/getMyAccountRoutes.ts
  • packages/core/src/server/cms/fetchMyAccountPageContent.ts
  • packages/core/src/server/cms/myAccountDefaultSections.ts
  • packages/core/test/server/index.test.ts

Comment on lines +96 to +105
const sharedOnly = !canViewPersonalCards && hasOrgAssociation

const [activeTab, setActiveTab] = useState<CardsTabVariant>(
sharedOnly ? 'shared' : 'personal'
)
const [search, setSearch] = useState('')
const [page, setPage] = useState(1)

const isShared = activeTab === 'shared'
const allCards = isShared ? sharedCards : personalCards

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.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

The Personal tab still renders when canViewPersonalCards is false and hasOrgAssociation is false.

sharedOnly requires both conditions. If the buyer cannot view personal cards and has no organization association, sharedOnly is false. The component then renders the tab bar, selects 'personal', and lists personalCards. The SSR partition in packages/core/src/pages/pvt/account/cards/index.tsx fills personalCards from the service response regardless of canViewPersonalCards, so denied cards become visible.

Derive tab availability from canViewPersonalCards directly, and render a dedicated empty or unauthorized state when neither tab is available.

🔐 Proposed direction
-  const sharedOnly = !canViewPersonalCards && hasOrgAssociation
+  const canViewSharedCards = hasOrgAssociation
+  const sharedOnly = !canViewPersonalCards && canViewSharedCards
+  const noTabAvailable = !canViewPersonalCards && !canViewSharedCards
 
   const [activeTab, setActiveTab] = useState<CardsTabVariant>(
     sharedOnly ? 'shared' : 'personal'
   )
   const [search, setSearch] = useState('')
   const [page, setPage] = useState(1)
 
   const isShared = activeTab === 'shared'
-  const allCards = isShared ? sharedCards : personalCards
+  const allCards = noTabAvailable ? [] : isShared ? sharedCards : personalCards

Then skip the tab bar and the grid when noTabAvailable is true.

🤖 Prompt for 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.

In
`@packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx`
around lines 96 - 105, Update MyAccountListCards so tab availability is derived
directly from canViewPersonalCards and hasOrgAssociation: preserve shared-only
behavior for organizational users without personal access, but introduce a
noTabAvailable state when neither personal nor shared cards are permitted. When
noTabAvailable is true, skip the tab bar and card grid and render the
component’s dedicated empty or unauthorized state instead.

Comment on lines +36 to +41
const authCookie = parse(headers?.cookie ?? '')?.[
'VtexIdclientAutCookie_' + account
]
const jwt = parseJwt(authCookie)

return { hasOrgAssociation: !!jwt?.unitId, hasCustomerId: !!jwt?.customerId }

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle malformed authentication cookies without throwing.

A non-empty malformed VtexIdclientAutCookie_* makes parseJwt throw. The SSR page then returns a 500 before its cards error state can render. Make each JWT decoder return null for invalid structure, base64, or JSON. Preserve the existing no-user fallback behavior.

  • packages/core/src/sdk/account/getB2BSessionClaims.ts#L36-L41: treat an invalid cookie as no B2B claims.
  • packages/api/src/platforms/vtex/resolvers/query.ts#L632-L633: treat an invalid cookie as no resolvable user.
📍 Affects 2 files
  • packages/core/src/sdk/account/getB2BSessionClaims.ts#L36-L41 (this comment)
  • packages/api/src/platforms/vtex/resolvers/query.ts#L632-L633
🤖 Prompt for 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.

In `@packages/core/src/sdk/account/getB2BSessionClaims.ts` around lines 36 - 41,
The JWT decoding flows must handle malformed authentication cookies without
throwing. In packages/core/src/sdk/account/getB2BSessionClaims.ts lines 36-41,
update parseJwt or its caller so invalid structure, base64, or JSON produces
null and preserves the existing no-B2B-claims fallback. In
packages/api/src/platforms/vtex/resolvers/query.ts lines 632-633, apply the same
null-on-invalid behavior so malformed cookies resolve as no user; use the
existing JWT decoder symbols and do not alter valid-cookie handling.

ArthurTriis1 and others added 2 commits August 11, 2026 19:16
# Conflicts:
#	packages/api/src/__generated__/schema.ts
#	packages/api/src/platforms/vtex/resolvers/query.ts
#	packages/core/@generated/gql.ts
#	packages/core/@generated/graphql.ts
#	packages/core/src/components/account/Layout/Layout.tsx
#	packages/core/src/sdk/account/getMyAccountRoutes.ts
#	packages/core/src/server/cms/fetchMyAccountPageContent.ts
…test

main landed Quotes (and other features) since this branch was cut; regenerate
the merged GraphQL schema/types via codegen instead of hand-resolving the
generated-file conflicts, and update getMyAccountRoutes.test.ts's exact route
list assertion, which didn't know about CARDS_ROUTE yet.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@codesandbox-ci

codesandbox-ci Bot commented Aug 11, 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 Aug 11, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

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

@faststore/cli

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

@faststore/components

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

@faststore/core

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

@faststore/diagnostics

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

@faststore/lighthouse

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

@faststore/sdk

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

@faststore/ui

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

commit: 9508a94

ArthurTriis1 and others added 2 commits August 11, 2026 19:29
# Conflicts:
#	CHANGELOG.md
#	lerna.json
#	packages/api/CHANGELOG.md
#	packages/api/package.json
#	packages/cli/CHANGELOG.md
#	packages/cli/package.json
#	packages/components/CHANGELOG.md
#	packages/components/package.json
#	packages/core/CHANGELOG.md
#	packages/core/package.json
#	packages/diagnostics/CHANGELOG.md
#	packages/diagnostics/package.json
#	packages/lighthouse/CHANGELOG.md
#	packages/lighthouse/package.json
#	packages/sdk/CHANGELOG.md
#	packages/sdk/package.json
#	packages/storybook/CHANGELOG.md
#	packages/storybook/package.json
#	packages/ui/CHANGELOG.md
#	packages/ui/package.json
…-list assertion

Mirrors the same fix already applied to packages/core/test/server/index.test.ts
- this integration test has its own hardcoded query list and didn't know about
either query yet, failing CI's `pnpm test`.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@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: 3

🧹 Nitpick comments (7)
packages/core/test/sdk/account/getMyAccountRoutes.test.ts (1)

32-38: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover already-prefixed routes.

This test covers only the missing-prefix branch. Add a case with route: '/pvt/custom' and assert that the route remains unchanged. This protects the already-prefixed branch in packages/core/src/sdk/account/getMyAccountRoutes.ts.

Suggested test
+  it('keeps routes with /pvt prefix unchanged', () => {
+    const result = getMyAccountRoutes({
+      routes: [{ title: 'Custom', route: '/pvt/custom' }],
+    })
+
+    expect(result.find((r) => r.title === 'Custom')?.route).toBe(
+      '/pvt/custom'
+    )
+  })
🤖 Prompt for 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.

In `@packages/core/test/sdk/account/getMyAccountRoutes.test.ts` around lines 32 -
38, Add a test alongside the existing getMyAccountRoutes case using a route
already set to “/pvt/custom”, and assert the returned Custom route remains
exactly “/pvt/custom”, covering the already-prefixed branch in
getMyAccountRoutes.
packages/core/src/components/ui/ProductGallery/ProductGallery.tsx (1)

162-179: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Optional: gate the storage reads on the loading state.

pages and selectedFacets are arrays from the search context. When their identity changes on a render, this effect re-runs and performs one synchronous sessionStorage.getItem per active page. resolveReservedGalleryHeight already returns 0 once hasProductsLoaded is true, so the reads are only useful while products load. An early return keeps the hot path free of storage access.

♻️ Proposed guard
   useEffect(() => {
+    if (hasProductsLoaded) {
+      setReservedGalleryHeight(0)
+      return
+    }
     setReservedGalleryHeight(
       resolveReservedGalleryHeight(hasProductsLoaded, pages, {
🤖 Prompt for 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.

In `@packages/core/src/components/ui/ProductGallery/ProductGallery.tsx` around
lines 162 - 179, Update the reserved-gallery-height useEffect around
reservedGalleryHeight and resolveReservedGalleryHeight to return early when
hasProductsLoaded is true, before accessing pages or sessionStorage-backed
resolution. Preserve the existing resolution behavior and dependency tracking
while products are still loading.
packages/core/test/components/skeletons/ProductGridSkeleton.browser.test.tsx (2)

8-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use one module-path style in this test file.

Line 8 mocks with the src/... alias. Line 13 imports the component with a relative path. GalleryPageHeightLock.browser.test.tsx uses the alias for both. Align this file on the alias so the mock target and the import resolve through the same path convention.

♻️ Proposed import alignment
-import ProductGridSkeleton from '../../../src/components/skeletons/ProductGridSkeleton/ProductGridSkeleton'
+import ProductGridSkeleton from 'src/components/skeletons/ProductGridSkeleton/ProductGridSkeleton'
🤖 Prompt for 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.

In `@packages/core/test/components/skeletons/ProductGridSkeleton.browser.test.tsx`
around lines 8 - 13, Update the ProductGridSkeleton import in the test to use
the same src/... alias as the ProductCardSkeleton mock, keeping the mock target
and component import on one module-path convention.

15-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for the default count.

The default ITEMS_PER_PAGE path guards every existing caller that omits count. Add one assertion for it.

💚 Proposed test addition
+  it('falls back to ITEMS_PER_PAGE placeholders', () => {
+    render(<ProductGridSkeleton loading />)
+
+    expect(screen.getAllByTestId('product-card-skeleton')).toHaveLength(
+      ITEMS_PER_PAGE
+    )
+  })

Import the constant:

+import { ITEMS_PER_PAGE } from 'src/constants'
🤖 Prompt for 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.

In `@packages/core/test/components/skeletons/ProductGridSkeleton.browser.test.tsx`
around lines 15 - 32, Add a test case in the ProductGridSkeleton suite covering
rendering without an explicit count, import the existing ITEMS_PER_PAGE
constant, render ProductGridSkeleton with loading enabled and no count, and
assert the product-card-skeleton elements match that default count.
packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx (1)

193-229: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the persist path.

Both tests exercise the lock and the release. Neither asserts the write. In jsdom getBoundingClientRect().height is 0, so the measurement branch returns before writeGalleryPageHeight runs. Stub getBoundingClientRect on the lock element and flush the animation frame, then assert the new sessionStorage value. This also guards the measurement timing discussed on GalleryPageHeightLock.tsx lines 175-190.

🤖 Prompt for 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.

In
`@packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx`
around lines 193 - 229, Add coverage in the “releases minHeight once product
cards are mounted” test for the persistence path: stub the lock element’s
getBoundingClientRect() to return a positive height, flush the
requestAnimationFrame callback after rerendering with the product card, and
assert that sessionStorage contains the newly written gallery height via the
existing key. Ensure the assertion exercises writeGalleryPageHeight rather than
only verifying minHeight release.
packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx (1)

191-224: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Remove the duplicated selector and measure logic, and reduce observer churn.

Two points:

  1. The product-card selector and the measure-then-persist block each appear twice (lines 163-167 and 199-205; lines 180-186 and 206-210). Extract a PRODUCT_CARD_SELECTOR constant, a MIN_MEASURABLE_PAGE_HEIGHT constant, and a single persistHeight helper.
  2. children is a new element on every parent render, so both observers are disconnected and recreated on each ProductGallery render, once per rendered page. The MutationObserver already covers the skeleton-to-grid swap in the browser. If the dependency exists only for jsdom reliability, prefer a stable signal such as a boolean "has products" state instead of the children identity.
♻️ Proposed extraction
+const PRODUCT_CARD_SELECTOR =
+  '[data-fs-product-card], a[data-testid="product-link"]'
+const MIN_MEASURABLE_PAGE_HEIGHT = 80
-        if (
-          !el.querySelector(
-            '[data-fs-product-card], a[data-testid="product-link"]'
-          )
-        ) {
-          return
-        }
-        const height = el.getBoundingClientRect().height
-        if (height < 80) return
-        const rounded = Math.round(height)
-        writeGalleryPageHeight(storageKey, rounded)
-        setPendingMinHeight(rounded)
+        if (!el.querySelector(PRODUCT_CARD_SELECTOR)) return
+        persistHeight(el)
🤖 Prompt for 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.

In `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx`
around lines 191 - 224, In the GalleryPageHeightLock effect, extract the
repeated product-card selector into PRODUCT_CARD_SELECTOR, the minimum height
threshold into MIN_MEASURABLE_PAGE_HEIGHT, and the shared measure-and-persist
behavior into a persistHeight helper reused by both observers. Remove children
from the effect dependencies and use a stable product-presence boolean or
another stable signal only if needed for jsdom synchronization, while retaining
MutationObserver coverage for browser skeleton-to-grid updates.
packages/core/test/sdk/ui/useScrollRestoration.browser.test.ts (1)

469-490: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the test title with the assertions.

The title states "ignores non-product clicks and same-path PDP clicks". The second case uses /office, which is a non-PDP link. The same-path PDP guard at line 514 of useScrollRestoration.tsx (destPath === globalThis.location.pathname) is not covered. Rename the test, then add a case that clicks an <a href="/office/p"> while location.pathname is /office/p.

🤖 Prompt for 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.

In `@packages/core/test/sdk/ui/useScrollRestoration.browser.test.ts` around lines
469 - 490, The test title and coverage in “ignores non-product clicks and
same-path PDP clicks” are inconsistent. Rename the test to describe non-product
clicks, then add a separate case creating and clicking an anchor with href
“/office/p” while the current location pathname is “/office/p”, asserting the
scroll storage remains unset to cover the destPath ===
globalThis.location.pathname guard in useScrollRestoration.
🤖 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/core/src/components/templates/SearchPage/SearchWrapper.tsx`:
- Around line 50-55: Reset the redirect guard in the SearchWrapper effect when
redirectUrl is empty, so a later identical redirect can call router.replace
again. Update
packages/core/src/components/templates/SearchPage/SearchWrapper.tsx lines 50-55
accordingly; add coverage in
packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx
lines 87-115 for redirect URL → no redirect URL → the same redirect URL,
expecting two router.replace calls.

In `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx`:
- Around line 169-173: Update syncFromDom’s hasProducts handling in
GalleryPageHeightLock so a loaded empty ProductGrid releases the height lock
instead of restoring the stored minHeight. Distinguish an active skeleton from a
completed zero-product state using the existing skeleton marker, preserving the
reserved height only while the skeleton is present and clearing the lock after
loading finishes empty.
- Around line 175-190: Update the unlock measurement flow in the component
containing syncFromDom so it waits until React has committed the
setIsLocked(false) style change, using an additional animation-frame or
equivalent post-commit scheduling step before reading getBoundingClientRect().
Track the scheduled frame handle and cancel it during effect cleanup/unmount,
preventing stale measurements and writes through writeGalleryPageHeight after
teardown.

---

Nitpick comments:
In `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx`:
- Around line 191-224: In the GalleryPageHeightLock effect, extract the repeated
product-card selector into PRODUCT_CARD_SELECTOR, the minimum height threshold
into MIN_MEASURABLE_PAGE_HEIGHT, and the shared measure-and-persist behavior
into a persistHeight helper reused by both observers. Remove children from the
effect dependencies and use a stable product-presence boolean or another stable
signal only if needed for jsdom synchronization, while retaining
MutationObserver coverage for browser skeleton-to-grid updates.

In `@packages/core/src/components/ui/ProductGallery/ProductGallery.tsx`:
- Around line 162-179: Update the reserved-gallery-height useEffect around
reservedGalleryHeight and resolveReservedGalleryHeight to return early when
hasProductsLoaded is true, before accessing pages or sessionStorage-backed
resolution. Preserve the existing resolution behavior and dependency tracking
while products are still loading.

In
`@packages/core/test/components/skeletons/ProductGridSkeleton.browser.test.tsx`:
- Around line 8-13: Update the ProductGridSkeleton import in the test to use the
same src/... alias as the ProductCardSkeleton mock, keeping the mock target and
component import on one module-path convention.
- Around line 15-32: Add a test case in the ProductGridSkeleton suite covering
rendering without an explicit count, import the existing ITEMS_PER_PAGE
constant, render ProductGridSkeleton with loading enabled and no count, and
assert the product-card-skeleton elements match that default count.

In
`@packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx`:
- Around line 193-229: Add coverage in the “releases minHeight once product
cards are mounted” test for the persistence path: stub the lock element’s
getBoundingClientRect() to return a positive height, flush the
requestAnimationFrame callback after rerendering with the product card, and
assert that sessionStorage contains the newly written gallery height via the
existing key. Ensure the assertion exercises writeGalleryPageHeight rather than
only verifying minHeight release.

In `@packages/core/test/sdk/account/getMyAccountRoutes.test.ts`:
- Around line 32-38: Add a test alongside the existing getMyAccountRoutes case
using a route already set to “/pvt/custom”, and assert the returned Custom route
remains exactly “/pvt/custom”, covering the already-prefixed branch in
getMyAccountRoutes.

In `@packages/core/test/sdk/ui/useScrollRestoration.browser.test.ts`:
- Around line 469-490: The test title and coverage in “ignores non-product
clicks and same-path PDP clicks” are inconsistent. Rename the test to describe
non-product clicks, then add a separate case creating and clicking an anchor
with href “/office/p” while the current location pathname is “/office/p”,
asserting the scroll storage remains unset to cover the destPath ===
globalThis.location.pathname guard in useScrollRestoration.
🪄 Autofix

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 Plus

Run ID: ba98a3e3-3905-4ee9-b860-ec4ed420b4d0

📥 Commits

Reviewing files that changed from the base of the PR and between 0e676b9 and 9f450b8.

⛔ Files ignored due to path filters (6)
  • CHANGELOG.md is excluded by none and included by none
  • lerna.json is excluded by none and included by none
  • 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/**
  • packages/core/public/icons.svg is excluded by !**/*.svg and included by packages/**
📒 Files selected for processing (37)
  • packages/api/CHANGELOG.md
  • packages/api/package.json
  • packages/api/src/platforms/vtex/clients/commerce/index.ts
  • packages/api/src/platforms/vtex/resolvers/query.ts
  • packages/api/src/platforms/vtex/typeDefs/query.graphql
  • packages/cli/CHANGELOG.md
  • packages/cli/package.json
  • packages/components/CHANGELOG.md
  • packages/components/package.json
  • packages/core/CHANGELOG.md
  • packages/core/package.json
  • packages/core/src/components/account/Layout/Layout.tsx
  • packages/core/src/components/product/ProductGrid/ProductGrid.tsx
  • packages/core/src/components/skeletons/ProductGridSkeleton/ProductGridSkeleton.tsx
  • packages/core/src/components/templates/SearchPage/SearchWrapper.tsx
  • packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx
  • packages/core/src/components/ui/ProductGallery/ProductGallery.tsx
  • packages/core/src/sdk/account/getMyAccountRoutes.ts
  • packages/core/src/sdk/ui/useScrollRestoration.tsx
  • packages/core/src/server/cms/myAccountDefaultSections.ts
  • packages/core/src/styles/global/index.scss
  • packages/core/test/components/skeletons/ProductGridSkeleton.browser.test.tsx
  • packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx
  • packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx
  • packages/core/test/sdk/account/getMyAccountRoutes.test.ts
  • packages/core/test/sdk/ui/useScrollRestoration.browser.test.ts
  • packages/core/test/server/index.test.ts
  • packages/diagnostics/CHANGELOG.md
  • packages/diagnostics/package.json
  • packages/lighthouse/CHANGELOG.md
  • packages/lighthouse/package.json
  • packages/sdk/CHANGELOG.md
  • packages/sdk/package.json
  • packages/storybook/CHANGELOG.md
  • packages/storybook/package.json
  • packages/ui/CHANGELOG.md
  • packages/ui/package.json
🚧 Files skipped from review as they are similar to previous changes (7)
  • packages/core/test/server/index.test.ts
  • packages/core/src/server/cms/myAccountDefaultSections.ts
  • packages/core/src/sdk/account/getMyAccountRoutes.ts
  • packages/api/src/platforms/vtex/clients/commerce/index.ts
  • packages/api/src/platforms/vtex/typeDefs/query.graphql
  • packages/core/src/components/account/Layout/Layout.tsx
  • packages/api/src/platforms/vtex/resolvers/query.ts

Comment on lines +50 to +55
useEffect(() => {
if (!redirectUrl || lastRedirectedUrl.current === redirectUrl) return

lastRedirectedUrl.current = redirectUrl
void router.replace(redirectUrl)
}, [redirectUrl, router])

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reset the redirect guard when redirect state clears.

Line 51 retains lastRedirectedUrl for the mounted SearchWrapper. If a non-redirecting search occurs and a later search resolves to the same URL, the effect suppresses router.replace. Lines 75-83 then keep rendering EmptySearch without navigation.

  • packages/core/src/components/templates/SearchPage/SearchWrapper.tsx#L50-L55: Clear the marker when redirectUrl is empty, or scope the marker to the source search state.
  • packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx#L87-L115: Add coverage for redirect URL → no redirect URL → same redirect URL and expect two router.replace calls.
Proposed fix
 useEffect(() => {
-  if (!redirectUrl || lastRedirectedUrl.current === redirectUrl) return
+  if (!redirectUrl) {
+    lastRedirectedUrl.current = null
+    return
+  }
+
+  if (lastRedirectedUrl.current === redirectUrl) return
 
   lastRedirectedUrl.current = redirectUrl
   void router.replace(redirectUrl)
 }, [redirectUrl, router])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (!redirectUrl || lastRedirectedUrl.current === redirectUrl) return
lastRedirectedUrl.current = redirectUrl
void router.replace(redirectUrl)
}, [redirectUrl, router])
useEffect(() => {
if (!redirectUrl) {
lastRedirectedUrl.current = null
return
}
if (lastRedirectedUrl.current === redirectUrl) return
lastRedirectedUrl.current = redirectUrl
void router.replace(redirectUrl)
}, [redirectUrl, router])
📍 Affects 2 files
  • packages/core/src/components/templates/SearchPage/SearchWrapper.tsx#L50-L55 (this comment)
  • packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx#L87-L115
🤖 Prompt for 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.

In `@packages/core/src/components/templates/SearchPage/SearchWrapper.tsx` around
lines 50 - 55, Reset the redirect guard in the SearchWrapper effect when
redirectUrl is empty, so a later identical redirect can call router.replace
again. Update
packages/core/src/components/templates/SearchPage/SearchWrapper.tsx lines 50-55
accordingly; add coverage in
packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx
lines 87-115 for redirect URL → no redirect URL → the same redirect URL,
expecting two router.replace calls.

Comment on lines +169 to +173
if (!hasProducts) {
// Skeleton / empty — keep (or restore) the reserved minHeight.
setIsLocked(true)
return
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Release the lock when a page finishes loading with zero products.

syncFromDom treats "no product card" as "still loading". ProductGrid also renders the skeleton whenever products.length === 0. If the same storage key previously stored a height and the query now returns no products, the reserved minHeight stays applied and the page keeps a tall empty block.

Consider distinguishing "skeleton present" from "loaded and empty", for example by checking for the skeleton marker instead of only the product-card marker.

🤖 Prompt for 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.

In `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx`
around lines 169 - 173, Update syncFromDom’s hasProducts handling in
GalleryPageHeightLock so a loaded empty ProductGrid releases the height lock
instead of restoring the stored minHeight. Distinguish an active skeleton from a
completed zero-product state using the existing skeleton marker, preserving the
reserved height only while the skeleton is present and clearing the lock after
loading finishes empty.

Comment on lines +175 to +190
// Products are visible: drop the lock so natural height can shrink on
// resize, then persist the unconstrained content height for next back-nav.
setIsLocked(false)

// Measure after minHeight is cleared (next frame).
requestAnimationFrame(() => {
const height = el.getBoundingClientRect().height
if (height < 80) return
const rounded = Math.round(height)
writeGalleryPageHeight(storageKey, rounded)
setPendingMinHeight(rounded)
})
}

syncFromDom()

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Measure after React commits the unlock, and cancel the frame on cleanup.

setIsLocked(false) runs inside a MutationObserver callback, so React commits the style removal asynchronously. The single requestAnimationFrame callback can run before the inline minHeight is removed. The measurement then returns the locked height and persists it, so the stored value never shrinks. The frame is also never cancelled, so it can run after unmount.

🐛 Proposed fix: measure only when the lock is cleared, and track the frame
 useEffect(() => {
   const el = ref.current
   if (!el) return
 
+  let frame = 0
+
   const syncFromDom = () => {
@@
     setIsLocked(false)
 
-    // Measure after minHeight is cleared (next frame).
-    requestAnimationFrame(() => {
-      const height = el.getBoundingClientRect().height
-      if (height < 80) return
-      const rounded = Math.round(height)
-      writeGalleryPageHeight(storageKey, rounded)
-      setPendingMinHeight(rounded)
-    })
+    // Measure only after React has actually cleared minHeight.
+    cancelAnimationFrame(frame)
+    frame = requestAnimationFrame(() => {
+      if (el.style.minHeight) {
+        // Commit not flushed yet — retry on the next frame.
+        frame = requestAnimationFrame(syncFromDom)
+        return
+      }
+      const height = el.getBoundingClientRect().height
+      if (height < MIN_MEASURABLE_PAGE_HEIGHT) return
+      const rounded = Math.round(height)
+      writeGalleryPageHeight(storageKey, rounded)
+      setPendingMinHeight(rounded)
+    })
   }
@@
   return () => {
+    cancelAnimationFrame(frame)
     mutationObserver.disconnect()
     resizeObserver?.disconnect()
   }
🤖 Prompt for 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.

In `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx`
around lines 175 - 190, Update the unlock measurement flow in the component
containing syncFromDom so it waits until React has committed the
setIsLocked(false) style change, using an additional animation-frame or
equivalent post-commit scheduling step before reading getBoundingClientRect().
Track the scheduled frame handle and cancel it during effect cleanup/unmount,
preventing stale measurements and writes through writeGalleryPageHeight after
teardown.

ArthurTriis1 and others added 2 commits August 12, 2026 10:48
- Harden parseJwt (core + api) to return null instead of throwing on a
  malformed auth cookie, so a bad VtexIdclientAutCookie_* 500s the request
  instead of falling back to the graceful no-session/error states already
  in place.
- MyAccountListCards: complete the WAI-ARIA tabs pattern (tabpanel,
  aria-controls, arrow-key navigation, tooltip trigger moved out of the tab
  button); replace the retry action's anchor-styled-as-button with a real
  Button wired to the Next router's reload(); stop falling back to the page
  title ("Cards") as a card's brand label when paymentSystemName is absent.
- Re-export the labels contract from the MyAccountListCards barrel so
  consumers have one entry point.
- Add a same-day regression case to getMyAccountRoutes.test.ts for the
  already-prefixed-route branch.

Not applied: the suggestion to also hide the Personal tab when
canViewPersonalCards and hasOrgAssociation are both false. That combination
is one of the two rows my-account-cards-gating-plan.md explicitly leaves
unconfirmed with product (O1) — inventing a render for it here would guess
past that open question, and the Saved-cards service already never returns
personal cards to a non-granted user regardless of what this tab shows.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
# Conflicts:
#	CHANGELOG.md
#	lerna.json
#	packages/api/CHANGELOG.md
#	packages/api/package.json
#	packages/cli/CHANGELOG.md
#	packages/cli/package.json
#	packages/components/CHANGELOG.md
#	packages/components/package.json
#	packages/core/CHANGELOG.md
#	packages/core/package.json
#	packages/diagnostics/CHANGELOG.md
#	packages/diagnostics/package.json
#	packages/lighthouse/CHANGELOG.md
#	packages/lighthouse/package.json
#	packages/sdk/CHANGELOG.md
#	packages/sdk/package.json
#	packages/storybook/CHANGELOG.md
#	packages/storybook/package.json
#	packages/ui/CHANGELOG.md
#	packages/ui/package.json

@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: 2

🤖 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/test/integration/vtex.cookies.test.ts`:
- Around line 10-35: Rename packages/api/test/integration/vtex.cookies.test.ts
to cookies.int.test.ts and packages/api/test/integration/schema.test.ts to
schema.int.test.ts, preserving their test contents so pnpm test:int discovers
them and each filename matches its corresponding source module.

In
`@packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx`:
- Around line 5-6: Update the `@faststore/ui` import in MyAccountListCards to
alias Button as UIButton, then replace the Button usage in the component render
flow around lines 273-279 with UIButton while preserving its existing props and
behavior.
🪄 Autofix

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 Plus

Run ID: 3cbdac10-a8bb-4b00-a966-84666331ed35

📥 Commits

Reviewing files that changed from the base of the PR and between 9f450b8 and e1ee8cf.

📒 Files selected for processing (13)
  • packages/api/src/platforms/vtex/utils/cookies.ts
  • packages/api/test/integration/schema.test.ts
  • packages/api/test/integration/vtex.cookies.test.ts
  • packages/api/test/unit/platforms/vtex/resolvers/hasAdHocCardAccess.test.ts
  • packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx
  • packages/core/src/components/account/cards/MyAccountListCards/index.ts
  • packages/core/src/components/account/cards/MyAccountListCards/myAccountListCardsLabels.ts
  • packages/core/src/components/account/cards/MyAccountListCards/styles.module.scss
  • packages/core/src/components/sections/Account/AccountListCards.tsx
  • packages/core/src/utils/getCookie.ts
  • packages/core/test/sdk/account/getB2BSessionClaims.test.ts
  • packages/core/test/sdk/account/getMyAccountRoutes.test.ts
  • packages/core/test/utils/getCookie.test.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/core/src/components/account/cards/MyAccountListCards/index.ts
  • packages/core/test/sdk/account/getMyAccountRoutes.test.ts
  • packages/api/test/unit/platforms/vtex/resolvers/hasAdHocCardAccess.test.ts
  • packages/core/src/components/account/cards/MyAccountListCards/myAccountListCardsLabels.ts
  • packages/core/src/components/account/cards/MyAccountListCards/styles.module.scss
  • packages/core/src/components/sections/Account/AccountListCards.tsx

Comment on lines +10 to +35
parseJwt,
updatesContextStorageCookies,
updatesCookieValueByKey,
} from '../../src/platforms/vtex/utils/cookies'

describe('parseJwt', () => {
it('returns null for an empty token', () => {
expect(parseJwt('')).toBeNull()
})

it('decodes a well-formed token payload', () => {
const payload = { userId: 'user-1' }
const token = `header.${Buffer.from(JSON.stringify(payload)).toString('base64')}.signature`

expect(parseJwt(token)).toEqual(payload)
})

it('returns null instead of throwing for a malformed token', () => {
expect(parseJwt('not-a-jwt')).toBeNull()
})

it('returns null instead of throwing when the payload segment is not valid base64/JSON', () => {
expect(parseJwt('header.%%%not-base64%%%.signature')).toBeNull()
})
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Rename the integration tests to the required convention.

These integration tests use .test.ts. Rename them to .int.test.ts so pnpm test:int selects them. Rename vtex.cookies.test.ts to cookies.int.test.ts to also match packages/api/src/platforms/vtex/utils/cookies.ts.

  • packages/api/test/integration/vtex.cookies.test.ts#L10-L35: Rename the file to cookies.int.test.ts.
  • packages/api/test/integration/schema.test.ts#L76-L77: Rename the file to schema.int.test.ts.

As per coding guidelines, @faststore/api integration tests use *.int.test files, and test files must match the source filename with a .test. infix.

📍 Affects 2 files
  • packages/api/test/integration/vtex.cookies.test.ts#L10-L35 (this comment)
  • packages/api/test/integration/schema.test.ts#L76-L77
🤖 Prompt for 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.

In `@packages/api/test/integration/vtex.cookies.test.ts` around lines 10 - 35,
Rename packages/api/test/integration/vtex.cookies.test.ts to cookies.int.test.ts
and packages/api/test/integration/schema.test.ts to schema.int.test.ts,
preserving their test contents so pnpm test:int discovers them and each filename
matches its corresponding source module.

Source: Coding guidelines

Comment on lines +5 to +6
import {
Button,

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the required UI import alias.

Alias Button as UIButton, then use UIButton at lines 273-279. This prevents local component-name collisions.

As per coding guidelines, imports from @faststore/ui must use the UI prefix in component code.

🤖 Prompt for 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.

In
`@packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx`
around lines 5 - 6, Update the `@faststore/ui` import in MyAccountListCards to
alias Button as UIButton, then replace the Button usage in the component render
flow around lines 273-279 with UIButton while preserving its existing props and
behavior.

Source: Coding guidelines

ArthurTriis1 and others added 2 commits August 12, 2026 11:15
- Extract TabsHeader/CardsGrid/PanelBody from MyAccountListCards so the
  component's cognitive complexity drops from 24 to under the 15 limit;
  each extracted piece also collapses what were nested ternaries into
  early returns.
- Move the tab keydown handler off the tablist container onto the
  focusable tab buttons themselves — the container had no other reason to
  need to be focusable.
- Mark every extracted component's props as Readonly.
- Cards page: drop two non-null assertions on listCards.errors — execute()
  already types it as a non-optional array, so the assertions were no-ops;
  and switch a named `{ default as X }` import to a plain default import.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
New-code coverage on this PR sat at ~11% (gate requires 75%), since
@faststore/core has no prior component-test convention to build on. Add:

- MyAccountListCards.browser.test.tsx: tab switching, arrow-key nav, search,
  pagination, empty/error states, default badge, generic-label fallback, the
  sharedOnly and no-org-association tab-chrome combinations.
- AccountListCards.browser.test.tsx: reads accountPageData, defaults missing
  card arrays, forwards CMS label overrides.
- pages/pvt/account/cards/index.test.ts: getServerSideProps branches (feature
  flag redirect, 401/403 redirect, non-auth error state, origin partitioning,
  canViewPersonalCards derivation, hasAdHocCardAccess fail-open default) with
  every SSR dependency mocked.

Coverage on the touched files: MyAccountListCards.tsx 95%, cards/index.tsx
93%, AccountListCards.tsx/getB2BSessionClaims.ts/getMyAccountRoutes.ts 100%.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@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.

♻️ Duplicate comments (1)
packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx (1)

274-285: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Prevent Personal-card rendering when Personal access is denied.

If canViewPersonalCards is false and hasOrgAssociation is false, sharedOnly is false. The component selects the Personal tab and renders personalCards. The SSR page can still provide those cards. This exposes cards after the access check denies them.

  • packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx#L274-L285: add a no-access state. Do not select or render personalCards unless canViewPersonalCards is true.
  • packages/core/test/components/account/cards/MyAccountListCards.browser.test.tsx#L161-L176: replace the current expectation with assertions that Personal cards and the Personal tab are unavailable in this state.
  • packages/core/test/pages/pvt/account/cards/index.test.ts#L138-L149: add a case with hasCustomerId: true and hasAdHocCardAccess: false to verify that the permission alone disables Personal cards without redirecting the route.
🤖 Prompt for 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.

In
`@packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx`
around lines 274 - 285, Prevent personal-card access when canViewPersonalCards
is false: update MyAccountListCards so it enters a no-access state and neither
selects the Personal tab nor renders personalCards, while preserving shared-card
behavior. In
packages/core/test/components/account/cards/MyAccountListCards.browser.test.tsx:161-176,
replace the existing expectation with assertions that the Personal tab and cards
are unavailable. In
packages/core/test/pages/pvt/account/cards/index.test.ts:138-149, add coverage
for hasCustomerId true with hasAdHocCardAccess false, confirming the route
remains accessible while Personal cards are disabled.
🤖 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.

Duplicate comments:
In
`@packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx`:
- Around line 274-285: Prevent personal-card access when canViewPersonalCards is
false: update MyAccountListCards so it enters a no-access state and neither
selects the Personal tab nor renders personalCards, while preserving shared-card
behavior. In
packages/core/test/components/account/cards/MyAccountListCards.browser.test.tsx:161-176,
replace the existing expectation with assertions that the Personal tab and cards
are unavailable. In
packages/core/test/pages/pvt/account/cards/index.test.ts:138-149, add coverage
for hasCustomerId true with hasAdHocCardAccess false, confirming the route
remains accessible while Personal cards are disabled.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 59f807c7-150e-4368-9135-614a012de51f

📥 Commits

Reviewing files that changed from the base of the PR and between dd54ebe and 12e15a8.

📒 Files selected for processing (5)
  • packages/core/src/components/account/cards/MyAccountListCards/MyAccountListCards.tsx
  • packages/core/src/pages/pvt/account/cards/index.tsx
  • packages/core/test/components/account/cards/MyAccountListCards.browser.test.tsx
  • packages/core/test/components/sections/Account/AccountListCards.browser.test.tsx
  • packages/core/test/pages/pvt/account/cards/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/pages/pvt/account/cards/index.tsx

ArthurTriis1 and others added 2 commits August 12, 2026 16:29
The service already returns an optional cardLabel (buyer/admin-set nickname,
e.g. "Team lunch card") on cards that have one — confirmed against a live
account. It went unused: absent from the SavedCard GraphQL type, the
listCreditCards resolver, the page query, and the component, which always
displayed paymentSystemName instead.

Expose cardLabel end-to-end and prefer it over the brand name in the card
grid and in search matching, falling back to paymentSystemName and then the
generic label exactly as before when the service has no nickname on file.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The Cards feature mirrored Orders' code-level i18n flow correctly
(fetchMyAccountPageContent already threads context.locale through, and
AccountListCards already destructures CMS section props with English
defaults) — but no CMS component/content-type schema existed for it, unlike
Orders' cms_component__accountorderslist.jsonc /
cms_content_type__myaccountorders.jsonc pair.

Without that schema, a CMS editor had no way to author a translated (or even
just customized) myAccountCards entry for any locale: getSingleContent finds
nothing to return, and every string in MyAccountListCards silently falls
back to its hardcoded English default regardless of context.locale.

Add the matching pair for AccountListCards, exposing every string in
myAccountListCardsLabels.ts as a CMS-editable field with the same defaults,
so Cards gets the same per-locale override path Orders already has.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
// Partition here rather than de-duplicating: a card present under both
// origins is intentionally rendered in both tabs.
const allCards = hasError ? [] : (listCards.data?.listCreditCards?.list ?? [])
const personalCards = allCards.filter((card) => card.origin === 'personal')

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.

Aqui, personalCards sempre é serializado no payload SSR (__NEXT_DATA__), mesmo quando canViewPersonalCards é false, hoje só a UI oculta a aba, os dados continuam chegando ao cliente. Isso deixa uma lacuna com a intenção de "esconder" da PRD (REQ-6).

Não bloqueia o merge, apenas uma sugestão de melhoria.

const personalCards = canViewPersonalCards
  ? allCards.filter((card) => card.origin === 'personal')
  : []

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Boa pegada, valeu! Corrigido em d2cb3b0 — personalCards agora só é populado quando canViewPersonalCards é true, exatamente como sugerido. Adicionei um teste cobrindo esse caso especificamente (dados presentes no backend mas canViewPersonalCards: false → array vazio no payload).

…uyer

canViewPersonalCards already hid the Personal tab, but personalCards was
still always partitioned onto accountPageData and shipped in __NEXT_DATA__
regardless — so a buyer without access could still find their own personal
cards in the page source, undermining REQ-6's "hide" intent.

Empty the array server-side instead of relying on the UI not to render it.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@rodrigo-tavares rodrigo-tavares 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.

Um ponto de regressão no strip de personalCards do SSR: o filtro usa canViewPersonalCards, mas a aba Personal ainda renderiza quando não há org (O1 / B2C).

Comment on lines +213 to +215
const personalCards = canViewPersonalCards
? allCards.filter((card) => card.origin === 'personal')
: []

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.

O strip de personalCards quando canViewPersonalCards é false está correto no caso sharedOnly (!canViewPersonalCards && hasOrgAssociation) — a aba Personal some e os dados não devem ir no __NEXT_DATA__.

Fora desse caso a aba Personal continua visível: sharedOnly exige hasOrgAssociation (MyAccountListCards.tsx L283). Comprador B2C / “neither” (sem customerId, sem unitId) cai em O1: tab bar + aba Personal, agora com personalCards = [].

Isso quebra FR-7 (“B2C buyers (no unitId) are never subject to the check”) e o “keep as-is” do O1 — antes do d2cb3b02 esses buyers viam os cartões; agora veem empty state.

Strip só quando a UI de fato esconde a aba:

const personalCards =
  !canViewPersonalCards && hasOrgAssociation
    ? []
    : allCards.filter((card) => card.origin === 'personal')

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Boa pegada, obrigado — meu fix anterior era largo demais e quebrava exatamente o caso que você descreveu. Corrigido em 9508a94: agora usa a mesma condição sharedOnly = !canViewPersonalCards && hasOrgAssociation do componente, em vez de só canViewPersonalCards. Adicionei um teste específico pro caso B2C/"neither" que você apontou, garantindo que os cartões pessoais continuam no payload quando hasOrgAssociation é falso.

The previous fix (d2cb3b0) stripped personalCards from the SSR payload
whenever canViewPersonalCards was false — but the UI only actually hides the
Personal tab in one combination, sharedOnly (!canViewPersonalCards &&
hasOrgAssociation). The two "kept as-is" O1 combinations (no unitId) still
render the tab, and per FR-7 a B2C buyer must never be subject to this check
at all. The broader strip silently emptied their real cards.

Mirror MyAccountListCards.tsx's sharedOnly condition exactly instead of
canViewPersonalCards alone, so the SSR payload only drops what the chrome
actually hides.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@sonar-workflows

Copy link
Copy Markdown

@ArthurTriis1
ArthurTriis1 merged commit 6dded69 into dev Aug 24, 2026
10 checks passed
ArthurTriis1 added a commit that referenced this pull request Aug 24, 2026
## What's the purpose of this pull request?

Resolves **O1**, the open question left in #3443: what the Cards page
should render for the combinations *without* a Unit/Contract
association. Those combinations were deliberately left "exactly as the
component already behaved, pending product confirmation".

Testing the released `4.7.0-dev.0` against a plain B2C shopper surfaced
what that behaviour actually is, and it is not good:

- The sidebar advertises **Cards** to every shopper, including ones with
no card capability at all.
- The page renders a **lone, inert "Personal" tab** — a single
`role="tab"` button with nothing to switch to. The component already
avoids this on the other side (`sharedOnly` returns a plain label, no
tab chrome), so it was asymmetric.
- Underneath that tab, `listCreditCards` answers **500**: the
Saved-cards service has no customer record for a buyer with no
association. The buyer gets "We couldn't load your cards" on a page they
were never able to use.

## How it works?

Cards is now org-gated the same way Quotes already is.

**Sidebar** — `CARDS_ROUTE` joins `ROUTES_ONLY_FOR_B2B_MEMBERS`. Both
consumers (`account/Layout` and `OrganizationDrawerBody`) already filter
that list by `isOrgMember`, so no new wiring.

**Route** — `getServerSideProps` redirects to `/pvt/account/404` when
`hasOrgAssociation` is false. The gate sits **ahead of the query** so a
buyer who cannot reach the page never costs a round trip to the service
that 500s for them.

The comment in `Layout.tsx` that asserted the opposite ("the sidebar
entry always stays visible") was rewritten.

`useAdHocCard` is untouched and remains the finer, separate gate over
Personal-tab rendering only. It still never hides the entry.

### Note for reviewers: two follow-ups I did not fold in

- **Divergence with Quotes.** Quotes redirects non-members to
`/pvt/account/403` (`quotes/index.tsx:201`); this uses
`/pvt/account/404` — the gate #3443 originally removed. Two behaviours
now exist for the same condition. Worth aligning, in whichever
direction.
- **Now-dead branches.** With the route gated, `hasOrgAssociation`
always arrives `true` in `MyAccountListCards`, so its
`{hasOrgAssociation && ...}` guards and the `sharedOnly` path are
always-true. Left in place as defensive code rather than widening this
PR.

## How to test it?

- Sign in as a shopper **without** a Unit/Contract association:
- **Cards** must be absent from the My Account sidebar and from the
Organization drawer.
- Hitting `/pvt/account/cards` directly must land on `/pvt/account/404`.
  - No request should reach the Saved-cards service.
- Sign in as a buyer **with** an association: Cards behaves exactly as
it did in #3443, including the `useAdHocCard` Personal-tab gating.

## References

- Follows up #3443 (released in `4.7.0-dev.0`), which tracked this as
O1.

**Authorization-change approval**: #3443 deliberately removed the
route-level gate; this reinstates it on a different condition (org
membership rather than `useAdHocCard`). Per `AGENTS.md`, that change was
walked through and approved by Arthur Andrade before being built.

## Checklist

**PR Title and Commit Messages**

- [x] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification

**PR Description**

- [ ] Added a label according to the PR goal

**Dependencies**

- [x] No package changes, so no `pnpm-lock.yaml` change

**Documentation**

- [x] PR description

## Tests

Full `@faststore/core` suite: **687 passing**.
(`test/server/index.test.ts` and `test/server/rootSpan.test.ts` fail to
load with `Cannot find package 'cross-inspect'` — verified pre-existing
on `dev`, unrelated to this change.)

Added:
- `getMyAccountRoutes.test.ts` — Cards is marked B2B-only.
- `Layout.test.tsx` — entry hidden without an org unit, shown with one.
- `cards/index.test.ts` — no-association redirects to `/pvt/account/404`
and `execute` is never called.

Changed, and worth a look during review:
- Two tests used `hasOrgAssociation: false` as an incidental scenario;
moved to `true` so they keep exercising what they were written for
instead of hitting the new gate.
- `keeps personal cards in the payload when there is no org association
(FR-7...)` was **removed** — it asserted precisely the behaviour this PR
reverses, and its scenario can no longer occur. A comment marks the
spot.
- `never gates the route` renamed to `does not gate the route on
useAdHocCard`, which is still true.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Restricted the Cards area to eligible business accounts with an
organization association.
* Users without an organization association are now redirected to the
404 page instead of seeing card-related content.
* Clarified that personal card availability is controlled separately
within the Cards page.
* **Tests**
* Added coverage for route visibility and 404 behavior for ineligible
accounts.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5 <[email protected]>
lariciamota added a commit that referenced this pull request Aug 24, 2026
…Cards page

SonarQube flagged skipLazyLoading as declared but never used. It was not a false
positive: the flag sat on the Props interface shared with the default
RenderSections export, which never reads it — passing it there would have been
silently dropped. Move it to a props type belonging to RenderSectionsBase alone.

Scoping it is also the correct behavior, not just tidier typing: RenderSections
renders the global sections (CartSidebar, RegionModal, RegionSlider) whose lazy
loading is load-bearing, so it must never be opted out wholesale.

Also set the flag on the My Account Cards page, which arrived on dev in #3443
after this branch was cut. The invariant is that no My Account section goes
through ViewportObserver.

Co-Authored-By: Claude Opus 5 <[email protected]>
thiagopereira-vtex pushed a commit that referenced this pull request Aug 25, 2026
## Summary

Adds a "Cards" area to My Account (`/pvt/account/cards`) listing the
buyer's personal payment cards and, when applicable, their
Organization's/Contract's shared cards.

- **`@faststore/api`**: new `commerce.savedCards` client +
`listCreditCards` GraphQL query against the Saved-cards service;
`SavedCard.origin` (`personal` | `shared`) added and mapped through,
using the service's own tagging instead of a second endpoint/round trip;
`cardLabel` (buyer/admin-set nickname, when the service has one on file)
exposed and preferred over `paymentSystemName` for display;
`hasAdHocCardAccess` query resolving the `UseAdHocCard` License Manager
resource key for the current user (fail-open on any downstream error).
- **`@faststore/core`**: `MyAccountListCards` component (Personal/Shared
tabs, search, pagination, empty/error states) wired into the Cards page
via SSR (mirrors the My Orders listing pattern); Personal and Shared
cards are partitioned client-side from the single `listCreditCards`
response by `origin` — no cards are de-duplicated across origins by
design (a card present in both is shown in both tabs).
- **Personal-tab permission gate**: `useAdHocCard` turned out to be a
License Manager resource key resolved from roles, not a session-token
claim as first assumed. The route itself and the sidebar entry are never
gated — only the Personal tab's visibility is, via `customerId +
hasAdHocCardAccess`. When a Unit/Contract-affiliated buyer lacks that
permission, only the Shared list renders, with no tab chrome. The two
remaining combinations without a Unit/Contract association are left
exactly as the component already behaved, pending product confirmation
on the intended render (tracked as O1 in the spec — see below).

**Authorization-change approval**: this permission-model correction
(removing the route-level 404 gate, replacing it with Personal-tab
visibility) was walked through and approved by Arthur Andrade in the
implementing session before being built, per `AGENTS.md`'s requirement
for auth-mechanism changes.

## Tests

- `packages/api/test/unit/platforms/vtex/resolvers/savedCards.test.ts`:
`origin` and `cardLabel` passthrough on `listCreditCards`.
-
`packages/api/test/unit/platforms/vtex/resolvers/hasAdHocCardAccess.test.ts`:
grant / deny / error fail-open / non-boolean fail-open / no-`userId`
short circuit / malformed-cookie regression.
- `packages/api/test/integration/vtex.cookies.test.ts`,
`packages/core/test/utils/getCookie.test.ts`: `parseJwt` no longer
throws on a malformed auth cookie (both packages' copies).
-
`packages/core/test/components/account/cards/MyAccountListCards.browser.test.tsx`:
tab switching, arrow-key nav, search (incl. by `cardLabel`), pagination,
empty/error states, default badge, label precedence/fallback, the
`sharedOnly` and no-org-association tab-chrome combinations.
-
`packages/core/test/components/sections/Account/AccountListCards.browser.test.tsx`,
`packages/core/test/pages/pvt/account/cards/index.test.ts`,
`packages/core/test/sdk/account/getB2BSessionClaims.test.ts`: section
wrapper and `getServerSideProps` branch coverage.
- `packages/core/test/server/index.test.ts`,
`packages/api/test/integration/schema.test.ts`: schema query-list
regression tests updated for the new queries.
- SonarQube Quality Gate: passing, 94.10% coverage on new code.
- Full suites green on every push; typecheck clean on every file
touched.

## Deviations

- The parent implementation spec originally modeled the Personal-tab
permission as a route-level 404 gate. That was corrected
mid-implementation once `useAdHocCard`'s real semantics (a resolved
License Manager role, not a token claim) were confirmed — see the
"Personal-tab permission gate" point above. The route and sidebar entry
are never blocked; only Personal-tab visibility is conditional.
- A related backend defect was found while testing against a live B2B
account: `GET /credit-card` on the Saved-cards service returns a generic
unhandled-exception 500 for at least one real session (reproduced
independently via `curl`, isolating it from this BFF). Likely cause:
`RequestContextResolver.ResolveUserId()` throws unhandled when
`User.UserId` is absent, a path newly introduced by the service's own
recent PR. Flagged to the Saved-cards team with trace IDs; **since fixed
on their end** and reconfirmed working in this session.

## Spec

- vtex/faststore-dx-spec-kit#24 — `my-account-cards.md`,
`my-account-cards-gating-plan.md`,
`my-account-cards-shared-listing-unblock.md`

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Added a My Account Cards page for viewing personal and shared saved
payment cards.
- Added card search, tabs, pagination, empty states, default-card
indicators, and responsive layouts.
  - Added CMS configuration and navigation support for the Cards page.
  - Added access checks to control personal-card visibility.
- **Bug Fixes**
- Malformed authentication tokens are now handled safely without
disrupting page rendering.
- Card-service and permission errors provide appropriate fallback and
recovery states.
- **Tests**
- Added coverage for card retrieval, access checks, authentication
handling, and schema updates.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
thiagopereira-vtex pushed a commit that referenced this pull request Aug 25, 2026
## What's the purpose of this pull request?

Resolves **O1**, the open question left in #3443: what the Cards page
should render for the combinations *without* a Unit/Contract
association. Those combinations were deliberately left "exactly as the
component already behaved, pending product confirmation".

Testing the released `4.7.0-dev.0` against a plain B2C shopper surfaced
what that behaviour actually is, and it is not good:

- The sidebar advertises **Cards** to every shopper, including ones with
no card capability at all.
- The page renders a **lone, inert "Personal" tab** — a single
`role="tab"` button with nothing to switch to. The component already
avoids this on the other side (`sharedOnly` returns a plain label, no
tab chrome), so it was asymmetric.
- Underneath that tab, `listCreditCards` answers **500**: the
Saved-cards service has no customer record for a buyer with no
association. The buyer gets "We couldn't load your cards" on a page they
were never able to use.

## How it works?

Cards is now org-gated the same way Quotes already is.

**Sidebar** — `CARDS_ROUTE` joins `ROUTES_ONLY_FOR_B2B_MEMBERS`. Both
consumers (`account/Layout` and `OrganizationDrawerBody`) already filter
that list by `isOrgMember`, so no new wiring.

**Route** — `getServerSideProps` redirects to `/pvt/account/404` when
`hasOrgAssociation` is false. The gate sits **ahead of the query** so a
buyer who cannot reach the page never costs a round trip to the service
that 500s for them.

The comment in `Layout.tsx` that asserted the opposite ("the sidebar
entry always stays visible") was rewritten.

`useAdHocCard` is untouched and remains the finer, separate gate over
Personal-tab rendering only. It still never hides the entry.

### Note for reviewers: two follow-ups I did not fold in

- **Divergence with Quotes.** Quotes redirects non-members to
`/pvt/account/403` (`quotes/index.tsx:201`); this uses
`/pvt/account/404` — the gate #3443 originally removed. Two behaviours
now exist for the same condition. Worth aligning, in whichever
direction.
- **Now-dead branches.** With the route gated, `hasOrgAssociation`
always arrives `true` in `MyAccountListCards`, so its
`{hasOrgAssociation && ...}` guards and the `sharedOnly` path are
always-true. Left in place as defensive code rather than widening this
PR.

## How to test it?

- Sign in as a shopper **without** a Unit/Contract association:
- **Cards** must be absent from the My Account sidebar and from the
Organization drawer.
- Hitting `/pvt/account/cards` directly must land on `/pvt/account/404`.
  - No request should reach the Saved-cards service.
- Sign in as a buyer **with** an association: Cards behaves exactly as
it did in #3443, including the `useAdHocCard` Personal-tab gating.

## References

- Follows up #3443 (released in `4.7.0-dev.0`), which tracked this as
O1.

**Authorization-change approval**: #3443 deliberately removed the
route-level gate; this reinstates it on a different condition (org
membership rather than `useAdHocCard`). Per `AGENTS.md`, that change was
walked through and approved by Arthur Andrade before being built.

## Checklist

**PR Title and Commit Messages**

- [x] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification

**PR Description**

- [ ] Added a label according to the PR goal

**Dependencies**

- [x] No package changes, so no `pnpm-lock.yaml` change

**Documentation**

- [x] PR description

## Tests

Full `@faststore/core` suite: **687 passing**.
(`test/server/index.test.ts` and `test/server/rootSpan.test.ts` fail to
load with `Cannot find package 'cross-inspect'` — verified pre-existing
on `dev`, unrelated to this change.)

Added:
- `getMyAccountRoutes.test.ts` — Cards is marked B2B-only.
- `Layout.test.tsx` — entry hidden without an org unit, shown with one.
- `cards/index.test.ts` — no-association redirects to `/pvt/account/404`
and `execute` is never called.

Changed, and worth a look during review:
- Two tests used `hasOrgAssociation: false` as an incidental scenario;
moved to `true` so they keep exercising what they were written for
instead of hitting the new gate.
- `keeps personal cards in the payload when there is no org association
(FR-7...)` was **removed** — it asserted precisely the behaviour this PR
reverses, and its scenario can no longer occur. A comment marks the
spot.
- `never gates the route` renamed to `does not gate the route on
useAdHocCard`, which is still true.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Restricted the Cards area to eligible business accounts with an
organization association.
* Users without an organization association are now redirected to the
404 page instead of seeing card-related content.
* Clarified that personal card availability is controlled separately
within the Cards page.
* **Tests**
* Added coverage for route visibility and 404 behavior for ineligible
accounts.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants