-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathuse-einstein.js
More file actions
625 lines (560 loc) · 21.6 KB
/
use-einstein.js
File metadata and controls
625 lines (560 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {useMemo, useState} from 'react'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {
useCommerceApi,
useAccessToken,
useUsid,
useEncUserId,
useCustomerType,
useDNT
} from '@salesforce/commerce-sdk-react'
import {keysToCamel} from '@salesforce/retail-react-app/app/utils/utils'
import logger from '@salesforce/retail-react-app/app/utils/logger-instance'
export class EinsteinAPI {
constructor({host, einsteinId, siteId, isProduction, dnt}) {
this.dnt = dnt
this.siteId = siteId
this.isProduction = isProduction
this.host = host
this.einsteinId = einsteinId
}
/**
* Given a POJO append the correct site and environment values
*
* @param {object} params
* @returns {object} The decorated body object.
*/
_buildBody(params) {
const instanceType_prd = 'prd'
const instanceType_sbx = 'sbx'
const body = {...params}
// The first part of the siteId is the realm
if (this.siteId) {
body.realm = this.siteId.split('-')[0]
}
if (this.isProduction) {
body.instanceType = instanceType_prd
} else {
body.instanceType = instanceType_sbx
}
return body
}
/**
* Given a product or item source, returns the product data that Einstein requires
*/
_constructEinsteinProduct(product) {
// Handle variants for PDP / viewProduct
// Assumes product is a Product object from SCAPI Shopper-Products:
// https://developer.salesforce.com/docs/commerce/commerce-api/references/shopper-products?meta=type%3AProduct
if (product.type) {
// In case of variant, send the "sku" attribute
if (product.type.variant) {
return {
id: product.master.masterId,
price: product.price,
sku: product.id
}
}
// In case of variation group, send the "altId" and "type" attributes
if (product.type.variationGroup) {
return {
altId: product.id,
id: product.master.masterId,
price: product.price,
sku: product.id,
type: 'vgroup'
}
}
// Handle non-variant products, like master, set, bundle, item.
// This code follows the implementation in the plugin_einstein_api.
// https://github.com/SalesforceCommerceCloud/plugin_einstein_api/blob/c8168d5b8e2e34bfb9413da73969d59b0f3adabd/plugin_einstein_api/cartridge/scripts/helpers/RecommendationsHelper.js#L315
return {
id: product.id,
price: product.price
}
}
// Handle variants & sets for PLP / viewCategory & viewSearch
// Assumes product is a ProductSearchHit from SCAPI Shopper-Search:
// https://developer.salesforce.com/docs/commerce/commerce-api/references/shopper-search?meta=type%3AProductSearchHit
if (product.hitType) {
return {
id: product.productId,
sku: product.productId, //TODO: Should we switch this to product.representedProduct.id once we allow non-master products in search results?
altId: '',
altIdType: ''
}
}
// handles non-variants
return {
id: product.id,
sku: '',
altId: '',
altIdType: ''
}
}
/**
* Given a cart item, returns the data that Einstein requires
*
* Assumes item is a ProductItemfrom SCAPI Shopper-Baskets:
* https://developer.salesforce.com/docs/commerce/commerce-api/references/shopper-baskets?meta=type%3AProductItem
*
* This code follows the implementation in the plugin_einstein_api.
* https://github.com/SalesforceCommerceCloud/plugin_einstein_api/blob/c8168d5b8e2e34bfb9413da73969d59b0f3adabd/plugin_einstein_api/cartridge/scripts/helpers/RecommendationsHelper.js#L315
*/
_constructEinsteinItem(item) {
const {product, productId, price, quantity} = item
// In case of variant, send the "sku" attribute
if (product?.type?.variant) {
return {
id: product.master.masterId,
quantity: quantity,
price: price,
sku: product.id
}
}
// In case of variation group, send the "altId" and "type" attributes
if (product?.type?.variationGroup) {
return {
id: product.master.masterId,
quantity: quantity,
price: price,
sku: product.id,
type: 'vgroup',
altId: product.id
}
}
// Otherwise send default attributes.
return {
id: productId,
price: price,
quantity: quantity
}
}
async einsteinFetch(endpoint, method, body) {
if (this.dnt !== false) return {}
const headers = {
'Content-Type': 'application/json',
'x-cq-client-id': this.einsteinId
}
if (body) {
body = this._buildBody(body)
}
let response
try {
response = await fetch(`${this.host}/v3${endpoint}`, {
method: method,
headers: headers,
...(body && {
body: JSON.stringify(body)
})
})
} catch (error) {
logger.error('Einstein request failed', {
namespace: 'useEinstein.einsteinFetch',
additionalProperties: {error: error}
})
return {}
}
if (!response?.ok) {
return {}
}
try {
const responseJson = await response.json()
return keysToCamel(responseJson)
} catch (error) {
logger.error('Error parsing response JSON', {
namespace: 'useEinstein.einsteinFetch',
additionalProperties: {error: error}
})
return {}
}
}
/**
* Tells the Einstein engine when a user views a product.
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async sendViewProduct(product, args) {
const endpoint = `/activities/${this.siteId}/viewProduct`
const method = 'POST'
const body = {
product: this._constructEinsteinProduct(product),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user views search results.
**/
async sendViewSearch(searchText, searchResults, args) {
const endpoint = `/activities/${this.siteId}/viewSearch`
const method = 'POST'
const products =
searchResults?.hits?.map((product) => this._constructEinsteinProduct(product)) ?? []
const body = {
searchText,
products,
showProducts: Boolean(products.length), // Needed by Reports and Dashboards to differentiate searches with results vs no results
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user clicks on a search result.
**/
async sendClickSearch(searchText, product, args) {
const endpoint = `/activities/${this.siteId}/clickSearch`
const method = 'POST'
const body = {
searchText,
product: this._constructEinsteinProduct(product),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user views a category.
**/
async sendViewCategory(category, searchResults, args) {
const endpoint = `/activities/${this.siteId}/viewCategory`
const method = 'POST'
const products = searchResults?.hits?.map((product) =>
this._constructEinsteinProduct(product)
)
const body = {
category: {
id: category.id
},
products,
showProducts: true, // Needed by Reports and Dashboards to differentiate searches with results vs no results
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user clicks a product from the category page.
* Not meant to be used when the user clicks a category from the nav bar.
**/
async sendClickCategory(category, product, args) {
const endpoint = `/activities/${this.siteId}/clickCategory`
const method = 'POST'
const body = {
category: {
id: category.id
},
product: this._constructEinsteinProduct(product),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user views a set of recommendations
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async sendViewReco(recommenderDetails, products, args) {
const endpoint = `/activities/${this.siteId}/viewReco`
const method = 'POST'
const {__recoUUID, recommenderName} = recommenderDetails
const body = {
recommenderName,
__recoUUID,
products: products,
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user clicks on a recommendation
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async sendClickReco(recommenderDetails, product, args) {
const endpoint = `/activities/${this.siteId}/clickReco`
const method = 'POST'
const {__recoUUID, recommenderName} = recommenderDetails
const body = {
recommenderName,
__recoUUID,
product: this._constructEinsteinProduct(product),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user views a page.
* Use this only for pages where another activity does not fit. (ie. on the PDP, use viewProduct rather than this)
**/
async sendViewPage(path, args) {
const endpoint = `/activities/${this.siteId}/viewPage`
const method = 'POST'
const body = {
currentLocation: path,
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user starts the checkout process.
**/
async sendBeginCheckout(basket, args = {}) {
const endpoint = `/activities/${this.siteId}/beginCheckout`
const method = 'POST'
const products = basket.productItems.map((item) => this._constructEinsteinItem(item))
const subTotal = basket.productSubTotal
const body = {
products: products,
amount: subTotal,
checkoutType: 'traditional', // Default to traditional for backward compatibility
...args // Allow override (e.g., checkoutType: 'one-click')
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user reaches the given step during checkout.
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async sendCheckoutStep(stepName, stepNumber, basket, args = {}) {
const endpoint = `/activities/${this.siteId}/checkoutStep`
const method = 'POST'
const body = {
stepName,
stepNumber,
basketId: basket.basketId,
checkoutType: 'traditional', // Default to traditional for backward compatibility
...args // Allow override (e.g., checkoutType: 'one-click')
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Tells the Einstein engine when a user adds an item to their cart.
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async sendAddToCart(items, args) {
const endpoint = `/activities/${this.siteId}/addToCart`
const method = 'POST'
const body = {
products: items.map((item) => this._constructEinsteinItem(item)),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Get a list of recommenders that can be used in recommendation requests.
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async getRecommenders() {
const endpoint = `/personalization/recommenders/${this.siteId}`
const method = 'GET'
const body = null
return this.einsteinFetch(endpoint, method, body)
}
/**
* Get a set of recommendations
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async getRecommendations(recommenderName, products, args) {
const endpoint = `/personalization/recs/${this.siteId}/${recommenderName}`
const method = 'POST'
const body = {
products: products?.map((product) => this._constructEinsteinProduct(product)),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
/**
* Get a set of recommendations for a zone
* https://developer.salesforce.com/docs/commerce/einstein-api/references#einstein-recommendations:Summary
**/
async getZoneRecommendations(zoneName, products, args) {
const endpoint = `/personalization/${this.siteId}/zones/${zoneName}/recs`
const method = 'POST'
const body = {
products: products?.map((product) => this._constructEinsteinProduct(product)),
...args
}
return this.einsteinFetch(endpoint, method, body)
}
}
const useEinstein = () => {
const api = useCommerceApi()
const {effectiveDnt} = useDNT()
const {getTokenWhenReady} = useAccessToken()
const {
app: {einsteinAPI: config = {}}
} = getConfig()
const {host, einsteinId, siteId, isProduction} = config
const {getUsidWhenReady} = useUsid()
const {getEncUserIdWhenReady} = useEncUserId()
const {isRegistered} = useCustomerType()
const einstein = useMemo(
() =>
new EinsteinAPI({
host,
einsteinId,
siteId,
isProduction,
dnt: effectiveDnt
}),
[host, einsteinId, siteId, isProduction, effectiveDnt]
)
const [isLoading, setIsLoading] = useState(false)
const [recommendations, setRecommendations] = useState([])
const fetchRecProductDetails = async (reco) => {
const ids = reco.recs?.map((rec) => rec.id)
if (ids?.length > 0) {
try {
const token = await getTokenWhenReady()
// Fetch the product details for the recommendations
const products = await api.shopperProducts.getProducts({
parameters: {
ids: ids.join(','),
allImages: true,
perPricebook: true,
expand: [
'availability',
'links',
'promotions',
'options',
'images',
'prices',
'variations'
]
},
headers: {
Authorization: `Bearer ${token}`
}
})
// Einstein is not aware of items that becomes unavailable from BM
// we want to make sure to filter out any recs that is not available
// before merging getProducts data in
const recs = reco.recs
.filter((rec) => {
return !!products?.data?.find((product) => product.id === rec.id)
})
.map((rec) => {
const product = products?.data?.find((product) => product.id === rec.id)
return {
...rec,
...product,
productId: rec.id,
image: {disBaseLink: rec.imageUrl, alt: rec.productName}
}
})
// Merge the product detail into the recommendations response
return {
...reco,
recs: recs
}
} catch (error) {
logger.error('Error fetching product details for recommendations', {
namespace: 'useEinstein.fetchRecProductDetails',
additionalProperties: {error: error}
})
}
}
return reco
}
const getEventUserParameters = async () => {
return {
cookieId: await getUsidWhenReady(),
userId: isRegistered ? await getEncUserIdWhenReady() : undefined
}
}
return {
isLoading,
recommendations,
async sendViewProduct(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendViewProduct(...args.concat(userParameters))
},
async sendViewSearch(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendViewSearch(...args.concat(userParameters))
},
async sendClickSearch(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendClickSearch(...args.concat(userParameters))
},
async sendViewCategory(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendViewCategory(...args.concat(userParameters))
},
async sendClickCategory(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendClickCategory(...args.concat(userParameters))
},
async sendViewPage(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendViewPage(...args.concat(userParameters))
},
async sendBeginCheckout(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendBeginCheckout(...args.concat(userParameters))
},
async sendCheckoutStep(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendCheckoutStep(...args.concat(userParameters))
},
async sendViewReco(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendViewReco(...args.concat(userParameters))
},
async sendClickReco(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendClickReco(...args.concat(userParameters))
},
async sendAddToCart(...args) {
const userParameters = await getEventUserParameters()
return einstein.sendAddToCart(...args.concat(userParameters))
},
async getRecommenders(...args) {
return einstein.getRecommenders(...args)
},
async getRecommendations(recommenderName, products, ...args) {
setIsLoading(true)
try {
const userParameters = await getEventUserParameters()
const reco = await einstein.getRecommendations(
recommenderName,
products,
...args.concat(userParameters)
)
reco.recommenderName = recommenderName
const recommendations = await fetchRecProductDetails(reco)
setRecommendations(recommendations)
} catch (err) {
logger.error('Error in getRecommendations', {
namespace: 'useEinstein.getRecommendations',
additionalProperties: {error: err}
})
} finally {
setIsLoading(false)
}
},
async getZoneRecommendations(zoneName, products, ...args) {
setIsLoading(true)
try {
const userParameters = await getEventUserParameters()
const reco = await einstein.getZoneRecommendations(
zoneName,
products,
...args.concat(userParameters)
)
const recommendations = await fetchRecProductDetails(reco)
setRecommendations(recommendations)
} catch (err) {
logger.error('Error in getZoneRecommendations', {
namespace: 'useEinstein.getRecommendations',
additionalProperties: {error: err}
})
} finally {
setIsLoading(false)
}
}
}
}
export default useEinstein