-
Notifications
You must be signed in to change notification settings - Fork 81
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
base: dev
Are you sure you want to change the base?
Changes from 20 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
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 |
|---|---|---|
| @@ -1,15 +1,18 @@ | ||
| import type { GraphqlContext } from '..' | ||
| import { VtexCommerce } from './commerce' | ||
| import { Recommendation } from './recommendation' | ||
| import { IntelligentSearch } from './search' | ||
|
|
||
| export type Clients = ReturnType<typeof getClients> | ||
|
|
||
| export const getClients = (options: Options, ctx: GraphqlContext) => { | ||
| const search = IntelligentSearch(options, ctx) | ||
| const commerce = VtexCommerce(options, ctx) | ||
| const recommendation = Recommendation(options, ctx) | ||
|
|
||
| return { | ||
| search, | ||
| commerce, | ||
| recommendation, | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import type { GraphqlContext } from '../..' | ||
| import { getStoreCookie, getWithCookie } from '../../utils/cookies' | ||
| import { fetchAPI } from '../fetch' | ||
| import type { | ||
| RecommendationResult, | ||
| StartRecommendationSessionResult, | ||
| } from './types/RecommendationResult' | ||
|
|
||
| // Identifies the storefront origin to the Recommendations BFF, as required by | ||
| // the API (`x-vtex-rec-origin` header). | ||
| const REC_ORIGIN_SUFFIX = 'storefront/vtex.recommendation-shelf@2.x' | ||
|
thiagopereira-vtex marked this conversation as resolved.
Outdated
|
||
|
|
||
| export interface RecommendationArgs { | ||
| campaignVrn: string | ||
| userId?: string | ||
| products?: string[] | ||
| salesChannel?: string | ||
| locale?: string | ||
| } | ||
|
|
||
| export const Recommendation = ( | ||
| { account, environment }: Options, | ||
| ctx: GraphqlContext | ||
| ) => { | ||
|
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. 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Verify whether `Options` is declared globally or should be imported from a shared VTEX module.
rg -n --type=ts '\b(interface|type)\s+Options\b|\bdeclare global\b' packages/api/src/platforms/vtex
sed -n '1,40p' packages/api/src/platforms/vtex/clients/recommendation/index.ts
fd -i 'index.ts' packages/api/src/platforms/vtex/clientsRepository: vtex/faststore Length of output: 1610 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '\n-- recommendation index --\n'
sed -n '1,220p' packages/api/src/platforms/vtex/clients/recommendation/index.ts
printf '\n-- search index --\n'
sed -n '1,220p' packages/api/src/platforms/vtex/clients/search/index.ts
printf '\n-- search ProductSearchResult types --\n'
sed -n '1,220p' packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.ts
printf '\n-- all Option type declarations under vtex clients --\n'
rg -n --type=ts '\b(interface|type)\s+Options\b' packages/api/src/platforms/vtex/clientsRepository: vtex/faststore Length of output: 12176 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '\n-- all exported Options types in repo --\n'
rg -n --type=ts 'export\s+(interface|type)\s+Options\b' packages
printf '\n-- all imports of Options in vtex clients --\n'
rg -n --type=ts "import type \{[^}]*\bOptions\b[^}]*\}" packages/api/src/platforms/vtex/clients packages/api/src/platforms/vtex
printf '\n-- recommendation client neighbors --\n'
sed -n '1,220p' packages/api/src/platforms/vtex/clients/index.ts
sed -n '1,220p' packages/api/src/platforms/vtex/clients/commerce/index.tsRepository: vtex/faststore Length of output: 302 Import the shared VTEX client options type. 🤖 Prompt for AI Agents |
||
| const base = `https://${account}.${environment}.com.br/api/recommend-bff/v2` | ||
| const withCookie = getWithCookie(ctx) | ||
| const storeCookies = getStoreCookie(ctx) | ||
|
|
||
| const headers: HeadersInit = withCookie({ | ||
| accept: 'application/json', | ||
| 'content-type': 'application/json', | ||
| 'x-vtex-rec-origin': `${account}/${REC_ORIGIN_SUFFIX}`, | ||
|
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. I believe it is best to forward all the cookies, otherwise you will need to open the segment and parse all the infos.
Contributor
Author
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. Good point — that's already what we do here. The client forwards all cookies through getWithCookie/withCookie: it sets the cookie header to the full normalized ctx.headers.cookie (including vtex_segment, checkout.vtex.com, etc.) merged with any updates from ctx.storage.cookies. So the BFF receives the whole segment and we never open/parse it here. The salesChannel/locale query params come pre-resolved from ctx.storage.channel/ctx.storage.locale (parsed once upstream by FastStore, not re-parsed in this client), so they're just a convenience on top of the forwarded cookies. Happy to drop them and rely solely on the forwarded vtex_segment if we're confident the recommend-bff reads them from the cookie — let me know and I'll simplify. |
||
| }) | ||
|
|
||
| const recommendations = ({ | ||
| campaignVrn, | ||
| userId, | ||
| products = [], | ||
| salesChannel, | ||
| locale, | ||
| }: RecommendationArgs): Promise<RecommendationResult> => { | ||
| const params = new URLSearchParams({ an: account, campaignVrn }) | ||
|
|
||
| if (userId) { | ||
| params.append('userId', userId) | ||
| } | ||
|
|
||
| if (products.length > 0) { | ||
| params.append('products', products.join(',')) | ||
| } | ||
|
|
||
| if (salesChannel) { | ||
| params.append('salesChannel', salesChannel) | ||
| } | ||
|
|
||
| if (locale) { | ||
| params.append('locale', locale) | ||
| } | ||
|
|
||
| return fetchAPI(`${base}/recommendations?${params.toString()}`, { headers }) | ||
| } | ||
|
|
||
| // Starts/updates the anonymous personalization session. The BFF resolves the | ||
| // orderForm from the forwarded `checkout.vtex.com` cookie and replies with the | ||
| // `vtex-rec-user-id`/`vtex-rec-user-start-session` Set-Cookie headers, which we | ||
| // forward to the browser through `ctx.storage.cookies`. | ||
| const startRecommendationSession = (): Promise< | ||
| StartRecommendationSessionResult | undefined | ||
| > => { | ||
| const params = new URLSearchParams({ an: account }) | ||
|
|
||
| return fetchAPI( | ||
| `${base}/users/start-session?${params.toString()}`, | ||
| { method: 'POST', headers }, | ||
| { storeCookies } | ||
| ) | ||
| } | ||
|
|
||
| return { | ||
| recommendations, | ||
| startRecommendationSession, | ||
| } | ||
| } | ||
| 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,49 @@ | ||
| import type { QueryRecommendationsArgs } from '../../../__generated__/schema' | ||
| import type { GraphqlContext } from '../index' | ||
| import { enhanceSku, type EnhancedSku } from '../utils/enhanceSku' | ||
| import { pickBestSku } from '../utils/sku' | ||
|
|
||
| /** | ||
| * 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: { recommendation }, | ||
| } = ctx | ||
|
|
||
| const { salesChannel } = ctx.storage.channel | ||
|
|
||
| const response = await recommendation.recommendations({ | ||
| campaignVrn, | ||
| userId: userId ?? undefined, | ||
| products: products ?? [], | ||
| salesChannel: salesChannel ?? undefined, | ||
| locale: ctx.storage.locale, | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| 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,19 @@ | ||
| 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 | ||
| ) => { | ||
| await ctx.clients.recommendation.startRecommendationSession() | ||
|
|
||
| return true | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -470,6 +470,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! | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Não existe uma regra específica, mas penso que em vez de ser um novo client para recommendations, poderia ser um namespace dentro do vtex Commerce client. Você enxerga mais operações existentes nesse cliente além das adicionadas até o momento? o que achas?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@thiagopereira-vtex essa acho que cabe mais como um namespace dentro do client de commerce que ja existe, ao invés de criar um novo client. O que achas?