ハイブリッド実装向け Einstein アクティビティ

Reports & Dashboards を使用すると、B2C Commerce データに基づいて、時系列での傾向を把握し、より的確なビジネス上の意思決定を行うことができます。

Reports & Dashboards の分析は、Web アダプターのログまたは Einstein Activities API からのみ取得できます。デフォルトでは、SFRA と SiteGenesis の分析データは Web アダプターのログに保存され、PWA Kit は分析データを Einstein Activities API に送信します。

PWA Kit によって提供されるページと、SFRA または SiteGenesis によって提供されるページが混在するハイブリッド実装ガイダンスを進めていて、サイト全体で Reports & Dashboards を使用したい場合は、Einstein Activities API を使用するように SFRA または SiteGenesis の実装を更新する必要があります。これにより、買い物客が PWA Kit、SFRA、SiteGenesis のいずれを利用しているかにかかわらず、API で買い物客体験全体を取得できるようになります。

このページ内のリンクには、既存のお客様のみがアクセスできるものがあります。Commerce Cloud リポジトリにアクセスする方法については Salesforce Commerce Cloud GitHub リポジトリとアクセスを参照してください。

Tip

このガイドでは Einstein Activities API を SFRA の注文手続きに統合する方法を説明します。これにより、PWA Kit の注文手続きと同じアクティビティを送信できるようになります。

段階的なロールアウトで、SFRA または SiteGenesis 上に分析データを Web アダプターのログに送信するページが追加されている場合は、それらのページについても、このガイドで説明されているプロセスと同様の手順を実行できます。Retail React App の対応するページを確認し、どのアクティビティが送信されているかを確認してください。その後、SFRA または SiteGenesis ページで同じアクティビティを送信する必要があります。参考として、この Einstein アクティビティの概要では、それらのアクティビティをどこで使用することが想定されているかが示されています。

SiteGenesis とコンポーザブルストアフロントを組み合わせた実装は、公式にはサポートされていません。

Note

コード例について 

提供されているコード例を統合する場合はよく注意を払い、本番環境にプッシュする前に必ずコードを徹底的にテストしてください。

既存のコードに追加する行には加算 (+) 記号が付けられ、削除する行には減算 (-) 記号が付いています。

このチュートリアルのコマンドを実行する前に、プレースホルダーを実際の値に置き換えてください。プレースホルダーは、$PLACEHOLDER のような形式で記載されています。

手順 1: 注文手続きコントローラーの更新 

まず注文手続きコントローラーを更新して、現在の買い物カゴ ID を含めます。

1res.render('checkout/checkout', {
2+   basketId: currentBasket.UUID,
3    order: orderModel,
4    customer: accountModel,
5    ...
6});

手順 2: 注文手続きテンプレートの更新 

注文手続きに使用する ISML テンプレートを更新します。この変更により、買い物カゴ ID、商品項目、合計金額がブラウザー上で利用できるようになります。

1-    <div id="checkout-main" class="container data-checkout-stage <isif condition="${pdict.order.usingMultiShipping && pdict.order.shipping.length > 1}">multi-ship</isif>" data-customer-type="${pdict.customer.registeredUser ? 'registered' : 'guest'}" data-checkout-stage="${pdict.currentStage}" data-checkout-get-url="${URLUtils.https('CheckoutServices-Get')}">
2+    <div id="checkout-main" class="container data-checkout-stage <isif condition="${pdict.order.usingMultiShipping && pdict.order.shipping.length > 1}">multi-ship</isif>" data-customer-type="${pdict.customer.registeredUser ? 'registered' : 'guest'}" data-checkout-stage="${pdict.currentStage}" data-checkout-get-url="${URLUtils.https('CheckoutServices-Get')}" data-checkout-price-total="${pdict.order.priceTotal}" data-checkout-items="${JSON.stringify(pdict.order.items)}" data-basket-id="${pdict.basketId}">

手順 3: ヘルパーの作成 

ヘルパー関数を含む js/einsteinHelpers.js という名前の JavaScript ファイルを作成します。

プレースホルダー $YOUR_SITE_ID$YOUR_CLIENT_ID を必ず実際の値に置き換えてください。

Important

1"use strict";
2
3/**
4 * Get the value of a cookie
5 * Source: https://gist.github.com/wpsmith/6cf23551dd140fb72ae7
6 * @param  {string} name  The name of the cookie
7 * @return {string | undefined}       The cookie value
8 */
9function getCookie(name) {
10  var value = "; " + document.cookie;
11  var parts = value.split("; " + name + "=");
12  var result;
13
14  if (parts.length === 2) {
15    result = parts.pop().split(";").shift();
16  }
17  return result;
18}
19
20/**
21 * Fire a given Einstein activity with the provided data.
22 *
23 * @param {string} name - The name of the activity.
24 * @param {Object} data - The activity payload.
25 */
26function fireEinsteinActivity(name, data) {
27  // NOTE: These should be placed in the custom preferences of BM. This will help
28  // avoid any code deployments if you need to change these values.
29  // NOTE 2: this is _Einstein_ site id (not the same as SFRA one like RefArch).
30  var SITE_ID = "$YOUR_SITE_ID";
31  var CLIENT_ID = "$YOUR_CLIENT_ID";
32  // Reports & Dashboards will only show data that's been tagged as `prd` (production)
33  var INSTANCE_TYPE = "prd";
34
35  // Assign the realm to the data.
36  var activityData = Object.assign(data, {
37    realm: SITE_ID.split("-")[0],
38    instanceType: INSTANCE_TYPE,
39  });
40
41  var userId = data.userId;
42  var cookieId = data.cookieId;
43
44  // Apply payload information for logged in users.
45  if (userId) {
46    activityData = Object.assign(activityData, {
47      userId: userId,
48    });
49  }
50
51  if (cookieId) {
52    activityData = Object.assign(activityData, {
53      cookieId: cookieId,
54    });
55  }
56
57  var url = "https://api.cquotient.com/v3/activities" + "/" + SITE_ID + "/" + name;
58
59  try {
60    fetch(url, {
61      headers: {
62        "Content-Type": "application/json",
63        "x-cq-client-id": CLIENT_ID,
64      },
65      method: "POST",
66      body: JSON.stringify(activityData),
67    });
68  } catch (e) {
69    console.error(e);
70  }
71}
72
73var exports = {
74  fireEinsteinActivity: fireEinsteinActivity,
75  getCookie: getCookie,
76};
77
78module.exports = exports;

手順 4: アクティビティの記録 

checkout.js のスクリプトを更新してアクティビティを記録します。次の require() 呼び出しを注文手続きスクリプトの先頭に追加する必要があり、既存の import がある場合は、その後に記述してください。

1var einsteinHelpers = require('../einsteinHelpers');

注文手続きステージが変更されたときに checkoutStep アクティビティをトリガーします。次のコードを updateUrl メソッドの末尾に追加します。

1/**
2 * @returns {boolean} whether the current customer is registered or not
3 */
4function isRegisteredCustomer() {
5  return $(".data-checkout-stage").data("customer-type") === "registered";
6}
7
8/**
9 * Get the cookieId, which is a unique identifier used for linking subsequent activities to the same user.
10 * If the cookieId is not defined, then Reports & Dashboards will treat the activity as coming from an anonymous user.
11 * @returns {string | undefined} value of the cookieId param for Einstein Activities API
12 */
13function getCookieId() {
14  var siteId = window.CQuotient && window.CQuotient.siteId;
15  // This usid cookie is set by either PWA or plugin_slas
16  return (
17    einsteinHelpers.getCookie("usid_" + siteId) || einsteinHelpers.getCookie("usid") || undefined
18  );
19}
20
21/**
22 * Get the userId, which is for linking registered users across different devices.
23 * @returns {string | undefined} value of the userId param for Einstein Activities API
24 */
25function getUserId() {
26  var siteId = window.CQuotient && window.CQuotient.siteId;
27  // This enc_user_id is set by PWA
28  return (
29    window.localStorage.getItem("enc_user_id_" + siteId) ||
30    window.localStorage.getItem("enc_user_id") ||
31    undefined
32  );
33}
34
35/**
36 * Updates the URL to determine stage
37 * @param {number} currentStage - The current stage the user is currently on in the checkout
38 */
39function updateUrl(currentStage) {
40  // ...
41
42  var cookieId = getCookieId();
43  var userId = isRegisteredCustomer() ? getUserId() : undefined;
44
45  einsteinHelpers.fireEinsteinActivity("checkoutStep", {
46    basketId: $("#checkout-main").data("basket-id"),
47    stepName: checkoutStages[currentStage],
48    stepNumber: currentStage,
49    cookieId: cookieId,
50    userId: userId,
51  });
52}

updateUrl メソッドで checkoutStep アクティビティをトリガーすると、ある注文手続きのステージから次の (または前の) ステージへのすべての遷移が追跡されます。

Note

注文手続きコードの initialize 関数の末尾で、beginCheckout アクティビティをトリガーします。

1//
2// Send Einstein `beginCheckout` activity
3//
4// Parse total amount value
5var amount = $("#checkout-main").data("checkout-price-total");
6amount = Number(amount.replace(/[^0-9.-]+/g, ""));
7
8var products = $("#checkout-main")
9  .data("checkout-items")
10  .items.map(function (item) {
11    return {
12      id: item.id,
13      price: Number(item.priceTotal.price.replace(/[^0-9.-]+/g, "")),
14      quantity: item.quantity,
15    };
16  });
17
18var cookieId = getCookieId();
19var userId = isRegisteredCustomer() ? getUserId() : undefined;
20
21einsteinHelpers.fireEinsteinActivity("beginCheckout", {
22  products: products,
23  amount: amount,
24  cookieId: cookieId,
25  userId: userId,
26});

beginCheckout アクティビティは、注文手続き中のページ読み込みごとに 1 回だけトリガーされます。アクティビティデータの準備は自動的に処理されます。

Note

以上で完了です。Einstein アクティビティと SFRA の注文手続きの統合は正常に完了しました。Reports & Dashboards の設定を完了するには、Reports & Dashboards の手順を実施してください。

その他の参照項目: