@tbox.cn/app-module-promotion 1.0.0-alpha.13 → 1.0.0-alpha.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INTEGRATION.md +1 -0
- package/dist/{chunk-5GWOZC6X.js → chunk-2S7WUHX4.js} +225 -81
- package/dist/chunk-HK4U3I7K.js +1547 -0
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.js +1 -1
- package/dist/index.js +2 -2
- package/dist/server/index.d.ts +376 -263
- package/dist/server/index.js +1 -1
- package/package.json +6 -6
- package/src/client/cards/index.ts +1 -0
- package/src/client/cards/promotion-deal-recall/index.tsx +60 -0
- package/src/client/cards/promotion-entitlement-list/index.tsx +10 -30
- package/src/client/cards/promotion-offer-list/NearbyDealsPanel.tsx +120 -0
- package/src/client/cards/promotion-offer-list/index.tsx +57 -68
- package/src/client/components/CouponListRow.tsx +51 -0
- package/src/client/components/CouponListToggle.tsx +22 -0
- package/src/client/components/use-coupon-list-expansion.ts +41 -0
- package/src/client/index.ts +2 -0
- package/src/deal-recall-card.ts +17 -0
- package/src/server/cards/index.ts +2 -0
- package/src/server/cards/promotion-deal-recall/meta.ts +16 -0
- package/src/server/deal-recall-tools.ts +70 -0
- package/src/server/handler.ts +10 -3
- package/src/server/index.ts +36 -1
- package/src/server/tools.ts +10 -3
- package/tbox.module.json +14 -1
- package/tests/cards-render.test.tsx +152 -3
- package/tests/promotion.test.ts +23 -0
- package/dist/chunk-OCTPGK3E.js +0 -1340
package/src/client/index.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
PromotionActivityDetailCard,
|
|
13
13
|
PromotionActivityCategoryListCard,
|
|
14
14
|
PromotionBestDealCard,
|
|
15
|
+
PromotionDealRecallCard,
|
|
15
16
|
} from './cards';
|
|
16
17
|
|
|
17
18
|
const cards = {
|
|
@@ -22,6 +23,7 @@ const cards = {
|
|
|
22
23
|
'promotion-activity-detail': PromotionActivityDetailCard as CardComponent,
|
|
23
24
|
'promotion-activity-category-list': PromotionActivityCategoryListCard as CardComponent,
|
|
24
25
|
'promotion-best-deal': PromotionBestDealCard as CardComponent,
|
|
26
|
+
'promotion-deal-recall': PromotionDealRecallCard as CardComponent,
|
|
25
27
|
} as const;
|
|
26
28
|
|
|
27
29
|
export const clientModule = {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
export const dealRecallCardSchema = z.object({
|
|
4
|
+
title: z.string(),
|
|
5
|
+
partial: z.boolean().optional(),
|
|
6
|
+
items: z.array(z.object({
|
|
7
|
+
id: z.string(),
|
|
8
|
+
kind: z.enum(['item', 'shop']),
|
|
9
|
+
title: z.string(),
|
|
10
|
+
subtitle: z.string().optional(),
|
|
11
|
+
imageUrl: z.string().max(2048).startsWith('https://').optional(),
|
|
12
|
+
price: z.string().optional(),
|
|
13
|
+
url: z.string().max(2048).startsWith('alipays://platformapi/startapp?').optional(),
|
|
14
|
+
})).min(1).max(6),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export type DealRecallCardData = z.infer<typeof dealRecallCardSchema>;
|
|
@@ -6,6 +6,7 @@ import promotionActivityList from './promotion-activity-list/meta';
|
|
|
6
6
|
import promotionActivityDetail from './promotion-activity-detail/meta';
|
|
7
7
|
import promotionActivityCategoryList from './promotion-activity-category-list/meta';
|
|
8
8
|
import promotionBestDeal from './promotion-best-deal/meta';
|
|
9
|
+
import promotionDealRecall from './promotion-deal-recall/meta';
|
|
9
10
|
|
|
10
11
|
export const promotionCards = {
|
|
11
12
|
'promotion-offer-list': promotionOfferList,
|
|
@@ -15,5 +16,6 @@ export const promotionCards = {
|
|
|
15
16
|
'promotion-activity-detail': promotionActivityDetail,
|
|
16
17
|
'promotion-activity-category-list': promotionActivityCategoryList,
|
|
17
18
|
'promotion-best-deal': promotionBestDeal,
|
|
19
|
+
'promotion-deal-recall': promotionDealRecall,
|
|
18
20
|
} as const;
|
|
19
21
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { CardMeta } from '@tbox.cn/app-contracts';
|
|
2
|
+
import { dealRecallCardSchema } from '../../../deal-recall-card';
|
|
3
|
+
|
|
4
|
+
const meta: CardMeta<typeof dealRecallCardSchema> = {
|
|
5
|
+
cardType: 'promotion-deal-recall',
|
|
6
|
+
schemaVersion: 1,
|
|
7
|
+
displayName: '团购推荐',
|
|
8
|
+
description: '附近的团购商品或指定门店的团购列表',
|
|
9
|
+
dataSchema: dealRecallCardSchema,
|
|
10
|
+
sampleData: {
|
|
11
|
+
title: '附近团购',
|
|
12
|
+
items: [{ id: 'item:demo', kind: 'item', title: '双人下午茶', subtitle: '示例门店', price: '¥29.90' }],
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export default meta;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { isExpectedProviderAbsence, type RequestContext } from '@tbox.cn/app-contracts';
|
|
2
|
+
import { mallScopeOf, PROMOTION_DEAL_RECALL_SERVICE, type PromotionDealRecallPort } from '@tbox.cn/app-contracts-mall';
|
|
3
|
+
import { createTool, requireToolRequestContext, withCardEmissionHint, type ServerContext } from '@tbox.cn/app-agent-sdk-server';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
export const dealRecallNotices = {
|
|
7
|
+
disabled: '当前商场暂未开通外部团购推荐。',
|
|
8
|
+
'login-required': '请先在支付宝内登录,再查询团购。',
|
|
9
|
+
'location-required': '团购推荐需要城市和位置,请在支付宝内允许定位后再试。',
|
|
10
|
+
'mall-location-required': '暂时无法确认商场位置,无法查询附近神券。',
|
|
11
|
+
'shop-unmapped': '这家门店暂未开通定向团购查询,可以问我附近有什么团购。',
|
|
12
|
+
unavailable: '团购服务暂不可用,请稍后再试。',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export async function resolveDealRecallPort(ctx: ServerContext, request: RequestContext): Promise<PromotionDealRecallPort | undefined> {
|
|
16
|
+
const integrations = ctx.integrations;
|
|
17
|
+
if (!integrations?.raw?.config.services[PROMOTION_DEAL_RECALL_SERVICE]) return;
|
|
18
|
+
try {
|
|
19
|
+
return await integrations.resolveService({
|
|
20
|
+
service: PROMOTION_DEAL_RECALL_SERVICE, scope: mallScopeOf(request), request,
|
|
21
|
+
}) as PromotionDealRecallPort;
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (!isExpectedProviderAbsence(error)) throw error;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createDealRecallTools(getCtx: () => ServerContext) {
|
|
28
|
+
const run = async (input: Parameters<PromotionDealRecallPort['recall']>[0], execution: Parameters<typeof requireToolRequestContext>[0]) => {
|
|
29
|
+
const reqCtx = requireToolRequestContext(execution);
|
|
30
|
+
try {
|
|
31
|
+
const service = await resolveDealRecallPort(getCtx(), reqCtx);
|
|
32
|
+
if (!service) return { found: false, message: dealRecallNotices.disabled };
|
|
33
|
+
const result = await service.recall(input);
|
|
34
|
+
if (result.status !== 'ok') return { found: false, message: dealRecallNotices[result.status] };
|
|
35
|
+
if (!result.items.length) return { found: false, message: '暂未找到匹配的团购,可以换个条件试试。' };
|
|
36
|
+
return {
|
|
37
|
+
found: true,
|
|
38
|
+
count: result.items.length,
|
|
39
|
+
partial: result.partial === true,
|
|
40
|
+
cards: [{
|
|
41
|
+
cardType: 'promotion-deal-recall',
|
|
42
|
+
data: { title: input.shopName ? '门店团购' : '附近团购', items: result.items, partial: result.partial },
|
|
43
|
+
note: `${input.shopName ? '指定门店' : '附近'}团购结果 ${result.items.length} 条`,
|
|
44
|
+
}],
|
|
45
|
+
};
|
|
46
|
+
} catch {
|
|
47
|
+
return { found: false, message: dealRecallNotices.unavailable };
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const nearbyInput = z.object({
|
|
52
|
+
query: z.string().trim().min(1).max(200),
|
|
53
|
+
search: z.boolean().optional().describe('只有用户给出具体商品或品类条件时设为 true;泛推荐时可省略。'),
|
|
54
|
+
});
|
|
55
|
+
const shopInput = z.object({ shopName: z.string().trim().min(1).max(80) });
|
|
56
|
+
return {
|
|
57
|
+
recallNearbyDeals: withCardEmissionHint(createTool({
|
|
58
|
+
id: 'recallNearbyDeals',
|
|
59
|
+
description: '查询附近可跳转官方页查看的外部团购套餐。只返回推荐,可用于用户明确请求外部团购的场景。',
|
|
60
|
+
inputSchema: nearbyInput,
|
|
61
|
+
execute: (input, execution) => run(nearbyInput.parse(input), execution),
|
|
62
|
+
})),
|
|
63
|
+
recallShopDeals: withCardEmissionHint(createTool({
|
|
64
|
+
id: 'recallShopDeals',
|
|
65
|
+
description: '查询用户指定门店的外部团购套餐。使用门店名称,服务端校验门店映射。',
|
|
66
|
+
inputSchema: shopInput,
|
|
67
|
+
execute: (input, execution) => run({ query: '', ...shopInput.parse(input) }, execution),
|
|
68
|
+
})),
|
|
69
|
+
};
|
|
70
|
+
}
|
package/src/server/handler.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
offerSummary,
|
|
21
21
|
} from './tools';
|
|
22
22
|
import { parsePromotionNavigationQuery } from './navigation';
|
|
23
|
+
import { resolveDealRecallPort } from './deal-recall-tools';
|
|
23
24
|
|
|
24
25
|
/** 意图路由 patterns(collectIntentRoutes 装配收集;BM25 路由词同源;收窄:删跨域泛词——
|
|
25
26
|
* 「便宜/折扣/团购/市集/展览」独立泛词经 bigram 泄漏致无关长句误入直出卡;「活动中心」
|
|
@@ -315,14 +316,20 @@ export function createPromotionIntentHandler(
|
|
|
315
316
|
}
|
|
316
317
|
case 'search-coupons': {
|
|
317
318
|
const service = await resolvePromotionOffersPort(reqCtx, ctx);
|
|
318
|
-
const page = await
|
|
319
|
+
const [page, dealRecall] = await Promise.all([
|
|
320
|
+
service.searchOffers(q, { offerTypes: ['COUPON'], limit: 50 }),
|
|
321
|
+
resolveDealRecallPort(ctx, reqCtx).catch(() => undefined),
|
|
322
|
+
]);
|
|
319
323
|
const items = page.items.filter((item) => item.availability.status === 'AVAILABLE');
|
|
320
|
-
if (items.length === 0) return { cards: [], text: '当前商场暂未找到可领取优惠券' };
|
|
324
|
+
if (items.length === 0 && !dealRecall?.enabled) return { cards: [], text: '当前商场暂未找到可领取优惠券' };
|
|
321
325
|
return {
|
|
322
326
|
cards: [{ cardType: 'promotion-offer-list', data: {
|
|
323
327
|
presentation: 'coupon', mode: 'claimable', items: items.map(offerSummary),
|
|
328
|
+
...(dealRecall?.enabled ? { showDealRecall: true } : {}),
|
|
324
329
|
} }],
|
|
325
|
-
text:
|
|
330
|
+
text: dealRecall?.enabled
|
|
331
|
+
? dealRecall.offersIntro ?? '今日优惠可以按神券和商场优惠查看。'
|
|
332
|
+
: `为你找到 ${items.length} 张可领取优惠券`,
|
|
326
333
|
};
|
|
327
334
|
}
|
|
328
335
|
case 'list-entitlements': {
|
package/src/server/index.ts
CHANGED
|
@@ -8,7 +8,8 @@ import type { ServerContext, ServerModule, PreToolDef } from '@tbox.cn/app-agent
|
|
|
8
8
|
import { definePreTool, getRequestContext, loadModuleSkills } from '@tbox.cn/app-agent-sdk-server';
|
|
9
9
|
import { Router } from 'express';
|
|
10
10
|
import type { Request, Response } from 'express';
|
|
11
|
-
import {
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { PROMOTION_DEAL_RECALL_SERVICE, toMallQueryContext, withMallScopeFromQuery } from '@tbox.cn/app-contracts-mall';
|
|
12
13
|
import { inMemoryPromotion, resolvePromotionEntitlementsPort } from './ports';
|
|
13
14
|
import promotionOfferListMeta from './cards/promotion-offer-list/meta';
|
|
14
15
|
import promotionOfferDetailMeta from './cards/promotion-offer-detail/meta';
|
|
@@ -17,6 +18,8 @@ import promotionActivityListMeta from './cards/promotion-activity-list/meta';
|
|
|
17
18
|
import promotionActivityDetailMeta from './cards/promotion-activity-detail/meta';
|
|
18
19
|
import promotionActivityCategoryListMeta from './cards/promotion-activity-category-list/meta';
|
|
19
20
|
import promotionBestDealMeta from './cards/promotion-best-deal/meta';
|
|
21
|
+
import promotionDealRecallMeta from './cards/promotion-deal-recall/meta';
|
|
22
|
+
import { createDealRecallTools, dealRecallNotices, resolveDealRecallPort } from './deal-recall-tools';
|
|
20
23
|
import { createPromotionTools, entitlementSummary } from './tools';
|
|
21
24
|
import { createPromotionActions } from './actions';
|
|
22
25
|
import { createPromotionIntentHandler } from './handler';
|
|
@@ -52,6 +55,8 @@ const tools = {
|
|
|
52
55
|
recommendOffers: allTools.recommendOffers,
|
|
53
56
|
calculateBestDeal: allTools.calculateBestDeal,
|
|
54
57
|
};
|
|
58
|
+
const dealRecallTools = createDealRecallTools(getCtx);
|
|
59
|
+
const excludedDealIdsSchema = z.array(z.string().min(1).max(128)).default([]);
|
|
55
60
|
|
|
56
61
|
/**
|
|
57
62
|
* 可领券问句确定性预执行(2026-09-01):券意图轮零 LLM 预执行出券列表卡。
|
|
@@ -61,12 +66,16 @@ const tools = {
|
|
|
61
66
|
* - 出参体积门:CLAIMABLE 出参 build 期实测 ≤ 2KB(promotion pretool 测试断言),超限即撤本 preTool。
|
|
62
67
|
*/
|
|
63
68
|
const OWNED_INTENT_RE = /我的券|已领|券包|券码/;
|
|
69
|
+
const EXTERNAL_DEAL_INTENT_RE = /支付宝神券|外部团购/;
|
|
64
70
|
|
|
65
71
|
const listCouponsPreTool = definePreTool(tools.listCoupons, {
|
|
66
72
|
routing: { mode: 'keywords', terms: ['优惠券', '领券', '有什么券', '可领'] },
|
|
67
73
|
decide: ({ text }) => {
|
|
68
74
|
if (!text?.trim()) return { decision: 'skip', reason: '空文本' };
|
|
69
75
|
if (OWNED_INTENT_RE.test(text)) return { decision: 'skip', reason: 'OWNED 意图(模型传 mode)' };
|
|
76
|
+
if (EXTERNAL_DEAL_INTENT_RE.test(text) && serverCtx?.integrations?.raw?.config.services[PROMOTION_DEAL_RECALL_SERVICE]) {
|
|
77
|
+
return { decision: 'skip', reason: '外部团购意图' };
|
|
78
|
+
}
|
|
70
79
|
return { decision: 'run', args: { mode: 'CLAIMABLE' as const } };
|
|
71
80
|
},
|
|
72
81
|
silent: true,
|
|
@@ -85,6 +94,7 @@ const cards = {
|
|
|
85
94
|
'promotion-activity-detail': promotionActivityDetailMeta,
|
|
86
95
|
'promotion-activity-category-list': promotionActivityCategoryListMeta,
|
|
87
96
|
'promotion-best-deal': promotionBestDealMeta,
|
|
97
|
+
'promotion-deal-recall': promotionDealRecallMeta,
|
|
88
98
|
} as const;
|
|
89
99
|
|
|
90
100
|
/**
|
|
@@ -110,11 +120,36 @@ export const serverModule = {
|
|
|
110
120
|
for (const tool of Object.values(tools)) {
|
|
111
121
|
ctx.tools.register(tool);
|
|
112
122
|
}
|
|
123
|
+
if (ctx.integrations?.raw?.config.services[PROMOTION_DEAL_RECALL_SERVICE]) {
|
|
124
|
+
for (const tool of Object.values(dealRecallTools)) ctx.tools.register(tool);
|
|
125
|
+
}
|
|
113
126
|
ctx.cards.registerMap(cards);
|
|
114
127
|
ctx.handlers.register(createPromotionIntentHandler(ctx, { legacyActivities: false }));
|
|
115
128
|
|
|
116
129
|
// 券码详情弹窗按需调用独立 provider 能力;列表接口只负责券包索引。
|
|
117
130
|
const router = Router();
|
|
131
|
+
router.post('/nearby-deals', async (req: Request, res: Response) => {
|
|
132
|
+
const request = getRequestContext(req);
|
|
133
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
134
|
+
if (!request || request.identity.source === 'anonymous') {
|
|
135
|
+
res.status(401).json({ status: 'login-required', message: dealRecallNotices['login-required'] });
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const excludedDealIds = excludedDealIdsSchema.safeParse(req.body?.excludedDealIds);
|
|
139
|
+
if (!excludedDealIds.success) {
|
|
140
|
+
res.status(400).json({ error: 'invalid_excluded_deal_ids' });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const service = await resolveDealRecallPort(ctx, request);
|
|
145
|
+
const result = service ? await service.recall({
|
|
146
|
+
query: '附近有什么团购', limit: 20, excludedDealIds: excludedDealIds.data,
|
|
147
|
+
}) : { status: 'disabled' as const };
|
|
148
|
+
res.json(result.status === 'ok' ? result : { status: result.status, message: dealRecallNotices[result.status] });
|
|
149
|
+
} catch {
|
|
150
|
+
res.status(503).json({ status: 'unavailable', message: dealRecallNotices.unavailable });
|
|
151
|
+
}
|
|
152
|
+
});
|
|
118
153
|
router.get('/entitlement-detail', async (req: Request, res: Response) => {
|
|
119
154
|
const entitlementRef = typeof req.query['entitlementRef'] === 'string' ? req.query['entitlementRef'].trim() : '';
|
|
120
155
|
if (!entitlementRef) {
|
package/src/server/tools.ts
CHANGED
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
resolvePromotionActivitiesPort,
|
|
27
27
|
} from './ports';
|
|
28
28
|
import { promotionNavigationQuery } from './navigation';
|
|
29
|
+
import { resolveDealRecallPort } from './deal-recall-tools';
|
|
29
30
|
|
|
30
31
|
function coerce<T extends z.ZodTypeAny>(schema: T): T {
|
|
31
32
|
return z.preprocess(coerceStringifiedFields, schema) as unknown as T;
|
|
@@ -676,18 +677,24 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
|
|
|
676
677
|
? withCards(facts, 'promotion-entitlement-list', `我的优惠券 ${facts.items.length} 张${facts.items[0] ? ` · ${facts.items[0].title ?? ''}` : ''}`)
|
|
677
678
|
: facts;
|
|
678
679
|
}
|
|
679
|
-
const { service, q } = await requireService(execCtx, resolvePromotionOffersPort);
|
|
680
|
-
const page = await
|
|
680
|
+
const { service, q, reqCtx } = await requireService(execCtx, resolvePromotionOffersPort);
|
|
681
|
+
const [page, dealRecall] = await Promise.all([
|
|
682
|
+
search(service, q, args, ['COUPON']),
|
|
683
|
+
resolveDealRecallPort(opts.getCtx(), reqCtx).catch(() => undefined),
|
|
684
|
+
]);
|
|
681
685
|
const items = page.items.filter((item) => item.availability.status === 'AVAILABLE');
|
|
682
686
|
const facts = {
|
|
683
687
|
presentation: 'coupon' as const,
|
|
684
688
|
mode: 'claimable' as const,
|
|
685
689
|
summary: '可领取优惠券',
|
|
690
|
+
...(dealRecall?.enabled ? { showDealRecall: true as const } : {}),
|
|
686
691
|
items: items.map(offerSummary),
|
|
687
692
|
...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
|
|
688
693
|
...(items.length === 0 ? { noResultsReason: '当前商场暂未返回可领优惠券' } : {}),
|
|
689
694
|
};
|
|
690
|
-
return items.length
|
|
695
|
+
return items.length || dealRecall?.enabled
|
|
696
|
+
? withCards(facts, 'promotion-offer-list', `可领优惠券 ${items.length} 张${items[0] ? ` · ${items[0].title}` : ''}`)
|
|
697
|
+
: facts;
|
|
691
698
|
},
|
|
692
699
|
});
|
|
693
700
|
|
package/tbox.module.json
CHANGED
|
@@ -35,7 +35,9 @@
|
|
|
35
35
|
"listCoupons",
|
|
36
36
|
"getPackageDetail",
|
|
37
37
|
"recommendOffers",
|
|
38
|
-
"calculateBestDeal"
|
|
38
|
+
"calculateBestDeal",
|
|
39
|
+
"recallNearbyDeals",
|
|
40
|
+
"recallShopDeals"
|
|
39
41
|
],
|
|
40
42
|
"cards": [
|
|
41
43
|
{
|
|
@@ -65,6 +67,10 @@
|
|
|
65
67
|
{
|
|
66
68
|
"cardType": "promotion-best-deal",
|
|
67
69
|
"schemaVersion": 1
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"cardType": "promotion-deal-recall",
|
|
73
|
+
"schemaVersion": 1
|
|
68
74
|
}
|
|
69
75
|
],
|
|
70
76
|
"routes": [],
|
|
@@ -78,6 +84,10 @@
|
|
|
78
84
|
"promotion"
|
|
79
85
|
],
|
|
80
86
|
"consumes": [
|
|
87
|
+
{
|
|
88
|
+
"service": "promotion.deal-recall",
|
|
89
|
+
"optional": true
|
|
90
|
+
},
|
|
81
91
|
{
|
|
82
92
|
"service": "promotion.offers",
|
|
83
93
|
"optional": false,
|
|
@@ -120,6 +130,9 @@
|
|
|
120
130
|
}
|
|
121
131
|
],
|
|
122
132
|
"owns": [
|
|
133
|
+
{
|
|
134
|
+
"service": "promotion.deal-recall"
|
|
135
|
+
},
|
|
123
136
|
{
|
|
124
137
|
"service": "promotion.offers"
|
|
125
138
|
},
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @vitest-environment happy-dom
|
|
2
|
-
import { act } from 'react';
|
|
2
|
+
import { act, StrictMode } from 'react';
|
|
3
3
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
4
4
|
import { createRoot } from 'react-dom/client';
|
|
5
|
-
import { navigateToAlipayPage, sendCardAction } from '@tbox.cn/app-agent-sdk-client';
|
|
5
|
+
import { httpPost, navigateToAlipayPage, sendCardAction } from '@tbox.cn/app-agent-sdk-client';
|
|
6
6
|
import {
|
|
7
7
|
PromotionActivityCategoryListCard,
|
|
8
8
|
PromotionActivityDetailCard,
|
|
@@ -18,12 +18,13 @@ import { sanitizeActivityHtml } from '../src/client/utils/sanitize-activity-html
|
|
|
18
18
|
|
|
19
19
|
vi.mock('@tbox.cn/app-agent-sdk-client', async (importOriginal) => {
|
|
20
20
|
const mod = await importOriginal<typeof import('@tbox.cn/app-agent-sdk-client')>();
|
|
21
|
-
return { ...mod, navigateToAlipayPage: vi.fn(() => Promise.resolve()), sendCardAction: vi.fn() };
|
|
21
|
+
return { ...mod, httpPost: vi.fn(), navigateToAlipayPage: vi.fn(() => Promise.resolve()), sendCardAction: vi.fn() };
|
|
22
22
|
});
|
|
23
23
|
|
|
24
24
|
// 浮层 portal 到 body,用例间不清就会互相看见对方的残留
|
|
25
25
|
afterEach(() => {
|
|
26
26
|
document.body.innerHTML = '';
|
|
27
|
+
vi.mocked(httpPost).mockReset();
|
|
27
28
|
vi.mocked(sendCardAction).mockReset();
|
|
28
29
|
vi.mocked(navigateToAlipayPage).mockReset();
|
|
29
30
|
vi.mocked(navigateToAlipayPage).mockResolvedValue(undefined);
|
|
@@ -115,6 +116,108 @@ describe('legacy 19 个营销展示语义', () => {
|
|
|
115
116
|
// 素材变量链(主题轨 T-2.3):coupon 头图经 CSS background + --tbox-asset-promotion-coupon-header;
|
|
116
117
|
// 资产值断言归构建链(css url 相对引用),渲染层断言 img 不再渲染(防回归)
|
|
117
118
|
expect(header?.querySelector('.promotion-activity__header-art')).toBeNull();
|
|
119
|
+
expect(host.querySelector('[aria-label="今日优惠分类"]')).toBeNull();
|
|
120
|
+
expect(httpPost).not.toHaveBeenCalled();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('历史今日优惠直接回看已保存的商场优惠,打开详情时只显示快照', () => {
|
|
124
|
+
const host = render(<PromotionOfferListCard isHistory data={{
|
|
125
|
+
mode: 'claimable', presentation: 'coupon', showDealRecall: true, items: [{
|
|
126
|
+
...offer, claimActionLabel: '抢购', purchaseUrl: 'alipays://platformapi/startapp?appId=demo&page=pages%2Fcoupon',
|
|
127
|
+
}],
|
|
128
|
+
} as never} />);
|
|
129
|
+
expect(host.querySelector('h3')?.textContent).toBe('历史优惠');
|
|
130
|
+
expect(host.querySelector('[aria-label="今日优惠分类"]')).toBeNull();
|
|
131
|
+
expect(host.textContent).toContain(offer.title);
|
|
132
|
+
expect(host.textContent).not.toContain('加载神券');
|
|
133
|
+
const row = host.querySelector<HTMLElement>('.promotion-coupon-row')!;
|
|
134
|
+
expect(row.querySelector('.promotion-chip--coupon')?.textContent).toBe('查看详情');
|
|
135
|
+
|
|
136
|
+
act(() => row.click());
|
|
137
|
+
const sheet = document.querySelector('.promotion-sheet');
|
|
138
|
+
expect(sheet?.textContent).toContain(offer.title);
|
|
139
|
+
expect(sheet?.textContent).not.toContain('去小程序抢购');
|
|
140
|
+
expect(httpPost).not.toHaveBeenCalled();
|
|
141
|
+
expect(navigateToAlipayPage).not.toHaveBeenCalled();
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('历史今日优惠缺少快照时只显示简短提示', () => {
|
|
145
|
+
const host = render(<PromotionOfferListCard isHistory data={{
|
|
146
|
+
mode: 'claimable', showDealRecall: true, items: [], noResultsReason: '当前商场暂未返回可领优惠券',
|
|
147
|
+
}} />);
|
|
148
|
+
expect(host.querySelector('h3')?.textContent).toBe('历史优惠');
|
|
149
|
+
expect(host.textContent).toContain('暂无可回看的优惠');
|
|
150
|
+
expect(host.querySelector('[aria-label="今日优惠分类"]')).toBeNull();
|
|
151
|
+
expect(host.querySelector('button')).toBeNull();
|
|
152
|
+
expect(httpPost).not.toHaveBeenCalled();
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it('开通神券后默认请求一次并展示,切换商场优惠后可回到已有结果', async () => {
|
|
156
|
+
const url = 'alipays://platformapi/startapp?appId=demo&page=pages%2Fdetail';
|
|
157
|
+
let finishLoading!: () => void;
|
|
158
|
+
const loading = new Promise<void>((resolve) => { finishLoading = resolve; });
|
|
159
|
+
vi.mocked(httpPost).mockImplementation(async () => {
|
|
160
|
+
await loading;
|
|
161
|
+
return {
|
|
162
|
+
status: 200,
|
|
163
|
+
data: { status: 'ok', items: [{ id: 'i1', kind: 'item', title: '附近咖啡团购', subtitle: '咖啡店', price: '¥9.4', url }] },
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
const host = render(<PromotionOfferListCard cardId="coupon-tabs" data={{
|
|
167
|
+
mode: 'claimable', presentation: 'coupon', items: [offer], showDealRecall: true,
|
|
168
|
+
} as never} />);
|
|
169
|
+
const status = host.querySelector('[role="status"].promotion-deals-loading');
|
|
170
|
+
expect(status?.textContent).toBe('正在找附近神券…');
|
|
171
|
+
expect(status?.querySelector('.promotion-deals-loading__mascot')).not.toBeNull();
|
|
172
|
+
await act(async () => { finishLoading(); });
|
|
173
|
+
expect(host.querySelector('.promotion-deals-loading')).toBeNull();
|
|
174
|
+
const [nearby, mall] = host.querySelectorAll<HTMLButtonElement>('[aria-label="今日优惠分类"] button');
|
|
175
|
+
expect([nearby.textContent, mall.textContent]).toEqual(['神券', '商场优惠']);
|
|
176
|
+
expect(nearby.getAttribute('aria-pressed')).toBe('true');
|
|
177
|
+
expect(host.textContent).toContain('附近咖啡团购');
|
|
178
|
+
expect(host.textContent).not.toContain(offer.title);
|
|
179
|
+
const dealRow = host.querySelector<HTMLElement>('.promotion-coupon-row')!;
|
|
180
|
+
expect(dealRow.querySelector('.promotion-coupon-row__thumb')?.classList.contains('promotion-image--fallback')).toBe(true);
|
|
181
|
+
expect(dealRow.querySelector('.promotion-coupon-row__sub')?.textContent).toBe('咖啡店');
|
|
182
|
+
expect(dealRow.querySelector('.promotion-coupon-row__price')?.textContent).toBe('¥9.4');
|
|
183
|
+
expect(dealRow.querySelector('.promotion-chip--coupon')?.textContent).toBe('抢购');
|
|
184
|
+
act(() => dealRow.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
|
|
185
|
+
expect(sendCardAction).toHaveBeenCalledWith('coupon-tabs', { type: 'openLink', url });
|
|
186
|
+
|
|
187
|
+
act(() => mall.click());
|
|
188
|
+
expect(mall.getAttribute('aria-pressed')).toBe('true');
|
|
189
|
+
expect(host.textContent).toContain(offer.title);
|
|
190
|
+
expect(host.querySelector('[hidden]')?.textContent).toContain('附近咖啡团购');
|
|
191
|
+
const mallRow = host.querySelector('.promotion-list__items:not(ul) .promotion-coupon-row')!;
|
|
192
|
+
expect(mallRow.className).toBe(dealRow.className);
|
|
193
|
+
expect(mallRow.querySelector('.promotion-chip--coupon')?.className).toBe(dealRow.querySelector('.promotion-chip--coupon')?.className);
|
|
194
|
+
act(() => nearby.click());
|
|
195
|
+
expect(nearby.getAttribute('aria-pressed')).toBe('true');
|
|
196
|
+
expect(httpPost).toHaveBeenCalledTimes(1);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it.each(['offers', 'entitlements'])('%s 历史回放只挂载可见行,只有手动展开或收起才滚动', (kind) => {
|
|
200
|
+
const scroll = vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(() => {});
|
|
201
|
+
try {
|
|
202
|
+
const items = Array.from({ length: 6 }, (_, i) => ({
|
|
203
|
+
...offer, offerRef: `o${i}`, entitlementRef: `e${i}`, status: 'EFFECTIVE',
|
|
204
|
+
}));
|
|
205
|
+
const host = render(<StrictMode>{kind === 'offers'
|
|
206
|
+
? <PromotionOfferListCard isHistory data={{ mode: 'claimable', presentation: 'coupon', items } as never} />
|
|
207
|
+
: <PromotionEntitlementListCard isHistory data={{ items } as never} />}</StrictMode>);
|
|
208
|
+
const rows = () => host.querySelectorAll('.promotion-coupon-row');
|
|
209
|
+
expect(rows()).toHaveLength(4);
|
|
210
|
+
act(() => rows()[0]!.dispatchEvent(new Event('transitionend', { bubbles: true })));
|
|
211
|
+
expect(scroll).not.toHaveBeenCalled();
|
|
212
|
+
const toggle = host.querySelector<HTMLButtonElement>('.promotion-list__toggle')!;
|
|
213
|
+
act(() => toggle.click());
|
|
214
|
+
expect(rows()).toHaveLength(6);
|
|
215
|
+
act(() => toggle.click());
|
|
216
|
+
expect(rows()).toHaveLength(4);
|
|
217
|
+
expect(scroll).toHaveBeenCalledTimes(2);
|
|
218
|
+
} finally {
|
|
219
|
+
scroll.mockRestore();
|
|
220
|
+
}
|
|
118
221
|
});
|
|
119
222
|
|
|
120
223
|
it('券列表默认最多展示 4 条,并支持查看更多/收起', () => {
|
|
@@ -151,6 +254,52 @@ describe('legacy 19 个营销展示语义', () => {
|
|
|
151
254
|
}
|
|
152
255
|
});
|
|
153
256
|
|
|
257
|
+
it('神券直接显示完整首批,只提供继续召回', async () => {
|
|
258
|
+
const items = Array.from({ length: 7 }, (_, index) => ({
|
|
259
|
+
id: `deal-${index}`,
|
|
260
|
+
kind: 'item',
|
|
261
|
+
title: `测试神券 ${index + 1}`,
|
|
262
|
+
}));
|
|
263
|
+
vi.mocked(httpPost).mockResolvedValue({ status: 200, data: { status: 'ok', items } });
|
|
264
|
+
const host = render(<PromotionOfferListCard data={{ mode: 'claimable', presentation: 'coupon', items: [], showDealRecall: true }} />);
|
|
265
|
+
await act(async () => {});
|
|
266
|
+
expect(host.querySelectorAll('ul.promotion-list__items li')).toHaveLength(7);
|
|
267
|
+
expect([...host.querySelectorAll('.promotion-list__toggle')].map((button) => button.textContent)).toEqual(['查看更多']);
|
|
268
|
+
expect(httpPost).toHaveBeenCalledTimes(1);
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it('继续召回时去重并追加新神券,保留已有列表顺序', async () => {
|
|
272
|
+
const items = Array.from({ length: 5 }, (_, index) => ({
|
|
273
|
+
id: `item:${index}`, kind: 'item', title: `神券 ${index}`, distanceDesc: `${100 + index}m`,
|
|
274
|
+
}));
|
|
275
|
+
const additional = { id: 'item:extra', kind: 'item', title: '追加神券', distanceDesc: '70m' };
|
|
276
|
+
const post = vi.mocked(httpPost);
|
|
277
|
+
post.mockResolvedValueOnce({ status: 200, data: { status: 'ok', items, scannedDealIds: ['item:too-far'] } })
|
|
278
|
+
.mockRejectedValueOnce(new Error('offline'))
|
|
279
|
+
.mockResolvedValueOnce({ status: 200, data: { status: 'ok', items: [items[0], additional, additional] } })
|
|
280
|
+
.mockResolvedValueOnce({ status: 200, data: { status: 'ok', items: [additional] } });
|
|
281
|
+
const host = render(<PromotionOfferListCard data={{ mode: 'claimable', items: [], showDealRecall: true }} />);
|
|
282
|
+
const findButton = (label: string) => [...host.querySelectorAll('button')].find((button) => button.textContent === label);
|
|
283
|
+
const visibleCount = () => host.querySelectorAll('ul.promotion-list__items li').length;
|
|
284
|
+
await act(async () => {});
|
|
285
|
+
|
|
286
|
+
expect(visibleCount()).toBe(5);
|
|
287
|
+
expect(post).toHaveBeenCalledTimes(1);
|
|
288
|
+
await act(async () => { findButton('查看更多')?.click(); });
|
|
289
|
+
expect(visibleCount()).toBe(5);
|
|
290
|
+
expect(findButton('重试查看更多')).toBeDefined();
|
|
291
|
+
expect(post.mock.calls[1]?.[1]).toMatchObject({ excludedDealIds: [...items.map((item) => item.id), 'item:too-far'] });
|
|
292
|
+
await act(async () => { findButton('重试查看更多')?.click(); });
|
|
293
|
+
expect(visibleCount()).toBe(6);
|
|
294
|
+
const displayedTitles = [...host.querySelectorAll('ul.promotion-list__items .promotion-coupon-row__title')].map((title) => title.textContent);
|
|
295
|
+
expect(displayedTitles).toEqual([...items.map((item) => item.title), additional.title]);
|
|
296
|
+
await act(async () => { findButton('查看更多')?.click(); });
|
|
297
|
+
expect(post.mock.calls[3]?.[1]).toMatchObject({ excludedDealIds: [...items.map((item) => item.id), additional.id, 'item:too-far'] });
|
|
298
|
+
expect(visibleCount()).toBe(6);
|
|
299
|
+
expect(findButton('查看更多')).toBeUndefined();
|
|
300
|
+
expect(findButton('收起')).toBeUndefined();
|
|
301
|
+
});
|
|
302
|
+
|
|
154
303
|
it('recommendation 恢复推荐主视觉、依据和候选', () => {
|
|
155
304
|
const host = render(<PromotionOfferListCard data={{ mode: 'recommend', presentation: 'recommendation', summary: '综合资格和优惠力度', items: [offer, { ...offer, offerRef: 'o2' }] } as never} cardId="c1" />);
|
|
156
305
|
expect(host.querySelector('.promotion-recommendation__main')).not.toBeNull();
|
package/tests/promotion.test.ts
CHANGED
|
@@ -427,6 +427,29 @@ describe('promotion 确定性意图路由', () => {
|
|
|
427
427
|
expect((result.cards[0]?.data as { items: unknown[] }).items).toHaveLength(6);
|
|
428
428
|
});
|
|
429
429
|
|
|
430
|
+
it('今日优惠快捷入口展示可用的神券页签,即使商场优惠为空', async () => {
|
|
431
|
+
const service = new InMemoryPromotionService();
|
|
432
|
+
vi.spyOn(service, 'searchOffers').mockResolvedValue({ items: [], hasMore: false });
|
|
433
|
+
mockAllSlotsPersist(service);
|
|
434
|
+
const recall = vi.fn();
|
|
435
|
+
const ctx = {
|
|
436
|
+
...createPromotionTestContext(),
|
|
437
|
+
integrations: {
|
|
438
|
+
raw: { config: { services: { 'promotion.deal-recall': {} } } },
|
|
439
|
+
resolveService: vi.fn().mockResolvedValue({ enabled: true, offersIntro: '为你推荐以下优惠', recall }),
|
|
440
|
+
},
|
|
441
|
+
} as unknown as ReturnType<typeof createPromotionTestContext>;
|
|
442
|
+
const handler = createPromotionIntentHandler(ctx);
|
|
443
|
+
const result = await handler.handle('intent', { content: '现在有什么优惠?' }, ctx, testRequestContext());
|
|
444
|
+
|
|
445
|
+
expect(result.cards[0]).toMatchObject({
|
|
446
|
+
cardType: 'promotion-offer-list',
|
|
447
|
+
data: { presentation: 'coupon', showDealRecall: true, items: [] },
|
|
448
|
+
});
|
|
449
|
+
expect(result.text).toBe('为你推荐以下优惠');
|
|
450
|
+
expect(recall).not.toHaveBeenCalled();
|
|
451
|
+
});
|
|
452
|
+
|
|
430
453
|
it('纯券搜索统一投影为券列表,避免回落到活动与优惠卡', async () => {
|
|
431
454
|
const service = new InMemoryPromotionService();
|
|
432
455
|
vi.spyOn(service, 'searchOffers').mockResolvedValue({
|