購物車如何告訴促購「這位會員符合什麼條件」

Cart 把本次計算取得的會員資料轉成幾個字串。活動規則讀取這些字串,先判斷資格,再選擇回饋門檻。

User.Tags 是本次促購請求中的可比對字串集合,不是一張額外的會員貼標籤資料表。它只提供判斷線索;是否符合活動、要套用哪組回饋,仍由各活動規則決定。

同一份 tags,有兩種不同用法

使用者有某個 tag,不代表活動一定會檢查它。圖中列出本文追查到的用途。
tag本次計算代表什麼活動可能怎麼用
CrmShopMemberCard:5此次採用的 CRM 卡 ID 是 5限定卡別資格,或卡別給點門檻
FirstPurchaseCart 查到會員符合首購旗標活動要求首購時檢查
AllUserScopeCart 固定附上的通用 key部分回饋規則用來找通用門檻

「活動對象不限」使用的是 AllUserScope scope,該 scope 直接回傳 true,不檢查使用者是否有同名 tag。AllUserScope tag 的作用是讓部分回饋規則找到通用門檻。兩者同名,判斷位置不同。

用一筆回饋活動走一次

模擬輸入

會員ID 123,CRM 卡 ID 5,符合首購
活動限卡別 5、需首購,滿 800 元給 80 點
購物車符合活動的商品售價合計 900 元
這是依程式碼建立的靜態模擬情境,不是實際資料庫中的活動或服務執行紀錄。

資格與門檻依序通過

此例的規則只有一組通用門檻。若同時存在通用與卡別兩組門檻,選取順序見「優先序」分頁。

Shopping 傳入 CRM 欄位時還沒有貼 tag。Cart 的 GetUserTags 才組成 ["AllUserScope", "CrmShopMemberCard:5", "FirstPurchase"]。引擎先用卡別與首購判斷活動資格,再以 AllUserScope 找到滿 800 元給 80 點的門檻;符合活動的商品售價 900 元達標。後續結果仍受活動其他設定與完整計算流程影響。

Shopping 傳會員卡資料,尚未產生 User.Tags

購物車建立流程先查商店 CRM 合約,再取得會員卡。Cart 收到的是卡別欄位,之後才把它轉成 tag。

CRM 卡別資料怎麼進入 Cart

卡 ID 為 0 時,會員 service 會先清快取重取;仍查無有效資料或發生例外,Shopping processor 才改用最低等級卡。

ProcessorDefinitionCenter.CartCreateProcessorLayers 把 GetCrmMemberTierProcessor 排在 CartCreateProcessor 前。這裡傳送 HasCrmShopContract、CrmShopMemberCardList、CrmMemberTier,沒有傳 UserTags 字串。

建車方式CartCreateProcessor 呼叫
一般下單api/carts/create
代客下單api/carts/assist-create
查看 Shopping 的資料來源與例外處理
位置處理
GetShopContractSetting讀商店是否啟用 CRM 合約
VIPMemberService.GetCrmShopMemberCardDataFromWebStoreDB從 VipMember_CrmShopMemberCardId 與商店卡別清單組出會員卡 ID、名稱
GetCrmMemberTierProcessor捕捉 CrmMemberTierException 或其他例外,選 CrmShopMemberCardLevel 最低的一張卡

因此 CrmShopMemberCard:5 也可能代表回退後的最低等級卡,不能單憑 tag 斷定它是會員原始 CRM 等級。

Cart 在促購計算前,把會員資料組成 tags

回饋活動的主要執行點是 CalculatePromotionProcessor.ExecuteAsync。GetUserTags 是它呼叫的 service 方法,本身不是 processor。

回饋活動促購計算的呼叫順序

LogisticCalculateProcessorLayers

CalculatePromoCodeProcessor 之後執行 CalculatePromotionProcessor。

ArrangePromotionPayloadAsync

建立 CalculateRequestEntity,其中的 User 由 ArrangeUserEntityAsync 組成。

GetUserTags

讀取 CRM 合約、卡 ID 與會員首購旗標,寫入 User.Tags。

CalculateAsync

PromotionHttpClient.Calculate 將含 tags 的請求送往 Frontend API。

若 AssistType 是 FreeOfChargeAssistOrder,CalculatePromotionProcessor 會在組請求前返回。

GetUserTags 如何決定輸出

只有拿到會員資料時,方法才會更新 context.Data.IsMemberFirstPurchase;無會員資料會在首購判斷前返回。

會員首購旗標來自 VipMemberInfo_IsFirstPurchase。VIPMemberService.GetVipMemberBriefDataAsync 先查 300 秒的 Redis cache,未命中時查 Webstore 唯讀庫,再以讀寫庫回退。若查不到會員且商店不允許免登,ArrangeUserEntityAsync 會拋出 ArgumentNullException,不會正常送出促購請求。

本次情境組出的 User.Tags/結果
允許免登、無 CRM 合約["AllUserScope"]
無 CRM 合約、首購["AllUserScope", "FirstPurchase"]
CRM 卡 ID 5、非首購["AllUserScope", "CrmShopMemberCard:5"]
CRM 卡 ID 5、首購["AllUserScope", "CrmShopMemberCard:5", "FirstPurchase"]
查不到會員且不允許免登拋錯,未送促購計算
查看其他會間接執行 GetUserTags 的路徑

CalculatePromoCodeProcessor 也會呼叫 ArrangePromotionPayloadAsync 來驗證優惠碼。CalculatePriceProcessor 透過 ArrangePriceCalculatePayloadAsync 進入 ArrangeUserEntityAsync。因此 CalculatePromotionProcessor 是本文回饋活動促購計算的主要入口,不是 GetUserTags 唯一可能的呼叫者。

Frontend API 把 tags 交給引擎判斷

請求進來後,Frontend API 建立引擎的 UserContext。引擎依序檢查會員資格,再選出回饋門檻並比較商品金額。

實際的 Promotion Rule JSON

以下是 Promotion Frontend API 的 src/Test/Nine1.Promotion.BL.Services.Test/Calculates/Groups/CustomRuleBasketGroupTests.cs 中,InlineData(5439, "RewardReachPriceWithPoint2", ...) 使用的完整規則。欄位和值來自測試程式,只調整縮排。這是實際用於測試的 JSON,不是前面「滿 800 元給 80 點」的模擬活動,也不是線上活動紀錄。

規則欄位這筆 JSON 的值引擎怎麼用
MatchedUserScopesAllUserScope scope活動對象不限,這裡不查同名 tag
VisibleUserScopesAllUserScope scope活動可見資格不限
ThresholdsAllUserScope:滿 150 元給 200 點用購物車的 AllUserScope tag 找到這組門檻
ConsumerTags此筆 JSON 沒有這個欄位這檔活動不要求首購 tag
展開完整的 Promotion Rule JSON
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
{
"TypeFullName": "NineYi.Msa.Promotion.Rule.RewardReachPriceWithPoint2",
"Id": 5439,
"Name": "👻訂單成立後固定給點Test",
"Enabled": true,
"Description": "訂單成立後固定給點Test",
"Since": "2024-05-07T17:40:00+08:00",
"Until": "2024-05-24T00:00:59.997+08:00",
"UpdatedAt": "2024-05-07T17:28:15.5781812+08:00",
"Cyclable": false,
"Accumulated": false,
"IncludedProductScopes": [
{
"ProductScopeType": "NineYi.Msa.Tagging.TagProductScope",
"Tag": "Collection:f_178558629881065728"
}
],
"ExcludedProductScopes": null,
"IncludeRegionScopes": [
{
"RegionScopeType": "NineYi.Msa.Promotion.Engine.AllCountryRegionScope"
}
],
"MatchedUserScopes": [
{
"UserScopeType": "NineYi.Msa.Promotion.Engine.AllUserScope"
}
],
"VisibleUserScopes": [
{
"UserScopeType": "NineYi.Msa.Promotion.Engine.AllUserScope"
}
],
"MatchedSalesChannels": 7,
"VisibleSalesChannels": 7,
"IncludedLocationScopes": null,
"Thresholds": {
"AllUserScope": {
"ReachPricePointPairs": [
{
"ReachPrice": 150.0,
"Point": 200.0
}
]
}
},
"PointUntil": {
"UntilType": 1,
"AfterDays": 14,
"UntilYearOffset": 0,
"UntilYearMonth": 12,
"FixedDate": "0001-01-01T00:00:00"
}
}

這份規則把同一個 AllUserScope 字串放在兩個不同位置。MatchedUserScopes 的 scope 直接通過資格判斷;Thresholds 的 key 則要由 User.Tags 命中。若活動另外要求首購,建立規則時才會加入 ConsumerTags: ["FirstPurchase"]。

Cart 請求在 Frontend API 的計算時序

此圖聚焦本文的會員資格與給點門檻。其他商品、通路、地區等規則仍會在完整計算流程中判斷。
判斷位置本例使用的資料結果
MatchedUserScopesCrmShopMemberCard:5卡別資格通過
ConsumerTagsFirstPurchase首購必要條件通過
ThresholdsAllUserScope取出滿 800 元給 80 點
IsMatch符合商品售價 900 元900 元達到 800 元門檻

MatchedUserScopes 決定是否符合活動對象,VisibleUserScopes 決定活動是否可見,兩者各自呼叫 scope 的 IsInScope。活動若要求首購,規則建立時會把 FirstPurchase 放進 ConsumerTags;引擎要求其中全部 tag 都存在。AllUserScope.IsInScope 直接回傳 true。

通用與卡別門檻的 key 在建立規則時決定

RewardReachPriceWithPoint2RuleService.GetPromotionEngineRule 在組成活動規則時建立 key。購物車計算時讀取既有規則,不在每次請求中重新建立門檻。

規則建立時也會把 RewardPointRuleList 的 Condition 與 Point 組成 ReachPricePointPairs。條件無法轉為數字、點數缺失,或 Thresholds.Add 遇到重複 key,都會失敗。給點處理階段會再用同一個 GetThreshold 選點數。

與判斷對照的原始碼

以下程式碼分別來自 Promotion Frontend API 與它使用的 Promotion Engine。引擎的 IsMatch 在活動對象、必要 tag 等條件通過後,才取門檻並檢查金額。

接收請求並建立 UserContext:CalculateController、BaseProcessGroup

CalculateController.CartCalculateAsync 將請求交給計算 service;BaseProcessGroup.CreateShoppingCartContext 將 User.Tags 傳給引擎:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[HttpPost("cart-calculate")]
[ProducesResponseType(typeof(ApiResponseEntity<CalculateResponseEntity>), 200)]
[ProducesResponseType(typeof(ApiErrorResponseEntity<object>), 400)]
[ProducesResponseType(typeof(ApiErrorResponseEntity<object>), 500)]
public async Task<IActionResult> CartCalculateAsync([FromBody] CalculateRequestEntity request)
{
var result = await _calculateService.CalculateShoppingCartAsync(_traceContext.ShopId, request);

var response = new ApiResponseEntity<object>()
{
//// 詳細資訊
Data = result,
};

if (request.Options.IsVerbose == false)
{
//// 必要資訊
response.Data = result.ToParent();
}

return Ok(response);
}
1
var userContext = new UserContext(context.Calculate.User.Id, context.Calculate.User.Tags);
檢查資格:PromotionCommonRuleBase.IsMatch

會員 scope 不符或活動必要 tag 不齊,規則就返回 false。ConsumerTags 的檢查使用 All,代表活動要求的 tag 必須全部存在。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (!this.IsUserScopeMatched(context.Consumer))
{
return false;
}

if (this.IsBirthdayMonthEnabled && context.Consumer.Tags.Contains(UserTagConstants.CurrentBirthdayMonth) == false)
{
return false;
}

if (!this.IsConsumerTagMatched(context.Consumer))
{
return false;
}
1
2
3
4
if (this.ConsumerTags.All(tag => context.Tags.Contains(tag)) == false)
{
return false;
}

這兩段分別節錄自同一個引擎類別的 IsMatch 與 IsConsumerTagMatched;原方法還會檢查其他條件。

選門檻與檢查金額:RewardReachPriceWithPoint2

GetThreshold 枚舉使用者 tags,第一個命中的字典 key 就是本次使用的門檻。找不到或金額未達時,IsMatch 返回 false。

1
2
3
4
5
6
7
8
9
10
public override bool IsMatch(ShoppingCartContext context)
{
if (!base.IsMatch(context)) return false;

var threshold = this.GetThreshold(context.Consumer);
if (threshold == null) return false;

var minPricePair = threshold.ReachPricePointPairs.OrderBy(x => x.ReachPrice).FirstOrDefault();
return minPricePair != null && this.GetMatchedProductScopeItems(context).Sum(x => x.SalePrice) >= minPricePair.ReachPrice;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private RewardReachPriceWithPointThreshold GetThreshold(UserContext userContext)
{
if (Thresholds == null) return null;

foreach (var tag in userContext.Tags)
{
if (Thresholds.TryGetValue(tag, out var threshold))
{
return threshold;
}
}

return null;
}
建立門檻 key:RewardReachPriceWithPoint2RuleService

這是活動規則建立階段的程式碼。CrmShopMemberCardId = 0 會產生通用 key,其餘則產生卡別 key。

1
2
3
4
5
var crmShopMemberCard = rewardPointRule.CrmShopMemberCardId == 0 ?
nameof(AllUserScope) :
$"CrmShopMemberCard:{rewardPointRule.CrmShopMemberCardId}";

thresholds.Add(crmShopMemberCard, rewardReachPriceWithPointThreshold);

同時命中兩組門檻,程式沒有明訂誰優先

Cart 可能同時送出 AllUserScope 與卡別 tag。若活動也同時設定通用和卡別門檻,實際選取取決於引擎先枚舉到哪個 tag。

同一會員,兩條可能的門檻路徑

此圖是依程式碼的條件式推演,不是單次實測結果,也不代表兩組門檻會一起套用。

RewardReachPriceWithPoint2.GetThreshold 以 foreach (var tag in userContext.Tags) 找第一個命中值,找到就返回。Cart 雖先把 AllUserScope 放進陣列,Frontend API 建立 UserContext 時會轉成 HashSet<string>。目前沒有明確的卡別優先或通用優先規則,不能把集合枚舉順序當作業務保證。

若活動只設定一組 AllUserScope 門檻,Cart 固定附上的同名 tag 就能讓引擎找到它;若從 Cart 移除該 tag,活動對象設為「全部」仍可通過,但這類回饋規則會找不到通用門檻。