1import { LightningElement, api, track, wire } from 'lwc';
2import { ProductRecommendationsAdapter, ANCHOR_TYPES } from 'commerce/recommendationsApi';
3import { navigate, NavigationContext } from 'lightning/navigation';
4import { trackClickReco, trackViewReco } from 'commerce/activitiesApi';
5
6export default class RecommendationsSample extends LightningElement {
7
8 @api products = [];
9 @api productId;
10
11 recommenderName = 'similar-products';
12 anchorType = ANCHOR_TYPES.PRODUCT;
13 get anchorValue() {
14 return [this.productId];
15 };
16
17 @wire(ProductRecommendationsAdapter, {
18 recommenderName: '$recommenderName',
19 anchorType: '$anchorType',
20 anchorValue: '$anchorValue',
21 })
22 async loadRecommendation(response) {
23 let { data, error } = response;
24
25 if (data && data.recoUUID && data.products && data.products.length > 0) {
26 this.products = data.products;
27 this.recoUUID = data.recoUUID;
28
29 if (this.canDisplayRecommendations) {
30 this.sendViewReco();
31 }
32 } else if (error) {
33 // unable to load recommendation, handle accordingly
34 this.products = { data: [] };
35 console.error('Unable to load product recommendations');
36 }
37 }
38
39 get canDisplayRecommendations() {
40 return this.products.length > 0;
41 }
42
43 // NavigationContext allows us to click a link to get to new Product page
44 @wire(NavigationContext)
45 navContext;
46
47 handleClickProduct(event) {
48 const pid = event.currentTarget.getAttribute('pid');
49 const product = this.products.filter(p => p.id === pid)[0];
50
51 trackClickReco(this.recommenderName, this.recoUUID, {
52 id: product.id,
53 sku: product.sku,
54 });
55
56 // go to the Product Detail Page for the product clicked
57 navigate(this.navContext, {
58 type: 'standard__recordPage',
59 attributes: {
60 objectApiName: 'Product2',
61 recordName: product.fields.Name.replace(' ', '-'),
62 name: 'recordId',
63 recordId: pid,
64 },
65 });
66 }
67
68 sendViewReco() {
69 trackViewReco(
70 this.recommenderName,
71 this.recoUUID,
72 this.products.map((product) => {
73 return {
74 id: product.id,
75 sku: product.sku,
76 };
77 })
78 );
79 }
80}