-
Notifications
You must be signed in to change notification settings - Fork 82
feat(core): add RecommendationShelf section with personalization tracking #3403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 32 commits
6c426a8
5f3999b
1f92187
961112a
c0495e5
1108aa3
4caead7
70e3b83
ec92aef
e369181
fab2acc
91e14d0
402816e
4658ec0
814da62
4c934e8
f3ef796
1ea6afa
3a52956
7b4e2d2
6ea9e5f
060d0a0
3214947
acb4bf4
daa57c5
9de413f
a43bf23
d89732b
1852ee1
0e36d26
fd3006a
80773f5
be3f6b4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import type { Product } from '../../search/types/ProductSearchResult' | ||
|
|
||
| /** | ||
| * Raw response of the VTEX Recommendations BFF | ||
| * (`GET /api/recommend-bff/v2/recommendations`). | ||
| * | ||
| * The BFF already returns the products fully hydrated in the same Intelligent | ||
| * Search shape (`Product`) used by the `search` query, so the resolver can map | ||
| * them straight to the normalized `StoreProduct` shape via `pickBestSku` + | ||
| * `enhanceSku` — no extra round-trip to search is needed. | ||
| */ | ||
| export interface RecommendationResult { | ||
| products: Product[] | ||
| correlationId: string | ||
| campaign: RecommendationBffCampaign | ||
| } | ||
|
|
||
| export interface RecommendationBffCampaign { | ||
| id: string | ||
| title?: string | ||
| type: string | ||
| } | ||
|
|
||
| /** Response of `POST /api/recommend-bff/v2/users/start-session`. */ | ||
| export interface StartRecommendationSessionResult { | ||
| recommendationsUserId: string | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { BadRequestError } from '../../errors' | ||
| import type { QueryRecommendationsArgs } from '../../../__generated__/schema' | ||
| import type { GraphqlContext } from '../index' | ||
| import { enhanceSku, type EnhancedSku } from '../utils/enhanceSku' | ||
| import { pickBestSku } from '../utils/sku' | ||
|
|
||
| // Structural check for a recommendations campaign VRN | ||
| // (`vrn:recommendations:<account>:<campaign-type>:<campaign-id>`). Kept generic | ||
| // on purpose: the authoritative campaign taxonomy lives in `@faststore/core`, | ||
| // and `@faststore/api` must not depend on it, so we only validate the shape. | ||
| const RECOMMENDATION_VRN_PATTERN = /^vrn:recommendations:[^:]+:[^:]+:[^:]+$/ | ||
|
|
||
| /** | ||
| * Resolves personalized recommendations for a campaign. | ||
| * | ||
| * The VTEX Recommendations BFF already returns the products fully hydrated in | ||
| * the same Intelligent Search shape used by the `search` query. We map them | ||
| * straight to the normalized `StoreProduct` shape (`pickBestSku` + `enhanceSku`) | ||
| * so recommendation shelves render identical cards to regular shelves, while | ||
| * preserving the recommendation order returned by the BFF. | ||
| */ | ||
| export const recommendations = async ( | ||
| _: unknown, | ||
| { campaignVrn, userId, products }: QueryRecommendationsArgs, | ||
| ctx: GraphqlContext | ||
| ) => { | ||
| const { | ||
| clients: { commerce }, | ||
| } = ctx | ||
|
|
||
| const { salesChannel } = ctx.storage.channel | ||
|
|
||
| // Validate inputs server-side so only clean, well-formed payloads reach the | ||
| // Recommendations BFF (see @faststore/api server-side validation principle). | ||
| const normalizedCampaignVrn = campaignVrn?.trim() | ||
| if ( | ||
| !normalizedCampaignVrn || | ||
| !RECOMMENDATION_VRN_PATTERN.test(normalizedCampaignVrn) | ||
| ) { | ||
| throw new BadRequestError(`Invalid campaignVrn: "${campaignVrn}"`) | ||
| } | ||
|
|
||
| const normalizedUserId = userId?.trim() | ||
| if (userId != null && !normalizedUserId) { | ||
| throw new BadRequestError('Invalid userId: must be a non-empty string') | ||
| } | ||
|
|
||
| if ( | ||
| products != null && | ||
| (!Array.isArray(products) || products.some((product) => !product?.trim())) | ||
| ) { | ||
| throw new BadRequestError( | ||
| 'Invalid products: must be an array of non-empty strings' | ||
| ) | ||
| } | ||
|
|
||
| const response = await commerce.recommendation.recommendations({ | ||
| campaignVrn: normalizedCampaignVrn, | ||
| userId: normalizedUserId || undefined, | ||
| products: products ?? [], | ||
| salesChannel: salesChannel ?? undefined, | ||
| locale: ctx.storage.locale, | ||
| }) | ||
|
|
||
| const { campaign, correlationId } = response | ||
|
|
||
| const orderedProducts = (response.products ?? []) | ||
| .map((product) => { | ||
| const sku = pickBestSku(product.items) | ||
|
|
||
| return sku ? enhanceSku(sku, product) : null | ||
| }) | ||
| .filter((sku): sku is EnhancedSku => Boolean(sku)) | ||
|
|
||
| return { | ||
| products: orderedProducts, | ||
| correlationId, | ||
| campaign, | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import type { GraphqlContext } from '../index' | ||
|
|
||
| /** | ||
| * Starts (or updates) the anonymous personalization session for the current | ||
| * shopper via the Recommendations BFF. | ||
| * | ||
| * The BFF replies with the `vtex-rec-user-id`/`vtex-rec-user-start-session` | ||
| * Set-Cookie headers, which the client forwards to the browser through | ||
| * `ctx.storage.cookies`. Returns `true` once the session has been started. | ||
| */ | ||
| export const startRecommendationSession = async ( | ||
| _: unknown, | ||
| __: unknown, | ||
| ctx: GraphqlContext | ||
| ) => { | ||
| const result = | ||
| await ctx.clients.commerce.recommendation.startRecommendationSession() | ||
|
|
||
| // The BFF may not be ready on the first call and can resolve without a | ||
| // session payload. Only report success once a session actually exists (its | ||
| // `recommendationsUserId`); otherwise surface an error so the caller retries | ||
| // instead of treating an empty response as a started session. | ||
| if (!result?.recommendationsUserId) { | ||
| throw new Error( | ||
| 'Failed to start recommendation session: no session data returned' | ||
| ) | ||
| } | ||
|
|
||
| return true | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -529,6 +529,15 @@ type Query { | |
| Returns the items in an orderForm by its ID. | ||
| """ | ||
| orderFormItems(orderFormId: String!): [StoreOrderFormCartItem!]! @auth | ||
| """ | ||
| Returns personalized product recommendations for a given campaign. | ||
| """ | ||
| recommendations( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Where is the implementation for this recommendations query? |
||
| campaignVrn: String! | ||
| userId: String | ||
| products: [String!] | ||
| ): RecommendationResponse! | ||
| @cacheControl(scope: "private", sMaxAge: 120, staleWhileRevalidate: 3600) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A recomendação é feita pra cada usuário (userId)? Acho que, nesse caso, faz sentido ser private: ficar no browser do usuário e não "vazar" para cdn ou outra camada compartilhada. Caso contrário, seria melhor public. |
||
| } | ||
|
|
||
| type ValidateUserData { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| type RecommendationResponse { | ||
| products: [StoreProduct!]! | ||
| correlationId: String! | ||
| campaign: RecommendationCampaign! | ||
| } | ||
|
|
||
| type RecommendationCampaign { | ||
| id: String! | ||
| title: String | ||
| type: String! | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.