1({
2 loadProductRecommendations: function (cmp, event, helper) {
3 try {
4 cmp.set("v.loading", true);
5 var action = cmp.get("c.getRecs");
6 action.setParams({
7 recommender: cmp.get("v.recommender"),
8 anchorValues: cmp.get("v.anchorValues"),
9 cookie: document.cookie,
10 });
11 // Create a callback that is executed after
12 // the server-side action returns
13 action.setCallback(this, function (response) {
14 var state = response.getState();
15 if (state === "SUCCESS") {
16 try {
17 let data = JSON.parse(response.getReturnValue());
18 let products = data.productPage.products;
19 // Keep it simple, only show 4 products
20 cmp.set("v.products", products.slice(0, 4));
21 cmp.set("v.uuid", data.uuid);
22 cmp.set("v.loading", false);
23 let showProducts = products.length > 0;
24 cmp.set("v.showProducts", showProducts);
25 // Only send the viewReco activity when we display the product
26 // recommendations
27 if (showProducts) {
28 helper.sendViewRecoActivity(cmp, helper);
29 }
30 } catch (err) {
31 console.error("Error fetching recommendations", err);
32 cmp.set("v.loading", false);
33 }
34 }
35 });
36 $A.enqueueAction(action);
37 } catch (error) {
38 console.error("Failed to load recommendations: ", error);
39 cmp.set("v.loading", false);
40 }
41 },
42 // The recommender names we pass into the Connect API are in a different format
43 // than the recommender names we pass into the activities api.
44 recommenderNames: {
45 RecentlyViewed: "recently-viewed",
46 SimilarProducts: "similar-products",
47 MostViewedByCategory: "most-viewed-by-category",
48 TopSelling: "top-selling",
49 Upsell: "upsell",
50 },
51
52 formatPrice: function (price, curr) {
53 return new Intl.NumberFormat("en-US", { style: "currency", currency: curr }).format(price);
54 },
55
56 sendViewRecoActivity: function (cmp, helper) {
57 let trackViewReco = cmp.find("activitiesApi").trackViewReco;
58 let recName = helper.recommenderNames[cmp.get("v.recommender")];
59 let products = cmp.get("v.products").map((p) => ({ id: p.id }));
60 let uuid = cmp.get("v.uuid");
61 trackViewReco(recName, uuid, products);
62 },
63
64 getProductDetailProductId: function () {
65 let pageProductIdMatch = window.location.href.match(new RegExp("01t[a-zA-Z0-9]{15}"));
66 let pid = pageProductIdMatch ? pageProductIdMatch[0] : null;
67 return pid;
68 },
69});