ハイブリッド実装のための Einstein Activities

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のチェックアウトと同じアクティビティを送信するようにします。

段階的なロールアウトで、分析データを Web アダプターログに送信する SFRA または SiteGenesis に関する追加のページがある場合は、これらのページでは、このガイドで説明するようなプロセスに従うことができます。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 =
58            'https://api.cquotient.com/v3/activities' +
59                '/' + SITE_ID +
60                '/' + name;
61
62    try {
63        fetch(url, {
64            headers: {
65                'Content-Type': 'application/json',
66                'x-cq-client-id': CLIENT_ID
67            },
68            method: 'POST',
69            body: JSON.stringify(activityData)
70        });
71    } catch (e) {
72        console.error(e);
73    }
74}
75
76var exports = {
77    fireEinsteinActivity: fireEinsteinActivity,
78    getCookie: getCookie
79};
80
81module.exports = exports;

ステップ 4: アクティビティの記録 

checkout.js のスクリプトを更新してアクティビティを記録します。この呼び出しを注文手続きスクリプトの先頭の require() に追加する必要があり、既存のインポートの後に表示しなければなりません。

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 einsteinHelpers.getCookie('usid_' + siteId) || einsteinHelpers.getCookie('usid') || undefined;
17}
18
19/**
20 * Get the userId, which is for linking registered users across different devices.
21 * @returns {string | undefined} value of the userId param for Einstein Activities API
22 */
23function getUserId() {
24    var siteId = window.CQuotient && window.CQuotient.siteId;
25    // This enc_user_id is set by PWA
26    return window.localStorage.getItem('enc_user_id_' + siteId) || window.localStorage.getItem('enc_user_id') || undefined;
27}
28
29/**
30 * Updates the URL to determine stage
31 * @param {number} currentStage - The current stage the user is currently on in the checkout
32 */
33function updateUrl(currentStage) {
34    // ...
35
36    var cookieId = getCookieId();
37    var userId = isRegisteredCustomer() ? getUserId() : undefined;
38
39    einsteinHelpers.fireEinsteinActivity('checkoutStep', {
40        basketId: $('#checkout-main').data('basket-id'),
41        stepName: checkoutStages[currentStage],
42        stepNumber: currentStage,
43        cookieId: cookieId,
44        userId: userId
45    });
46}

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 Activities と SFRA のチェックアウトが正常に統合されました。Reports & の設定を完了するにはダッシュボードで、Reports & の手順を実行します。ダッシュボード

その他の参照項目