@tbox.cn/app-module-promotion 1.0.0-alpha.16 → 1.0.0-alpha.18

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.
@@ -7,7 +7,7 @@ import {
7
7
  resolvePromotionEntitlementsPort,
8
8
  resolvePromotionOffersPort,
9
9
  serverModule
10
- } from "../chunk-2S7WUHX4.js";
10
+ } from "../chunk-AVRCLENB.js";
11
11
  export {
12
12
  InMemoryPromotionService,
13
13
  inMemoryPromotion,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-module-promotion",
3
- "version": "1.0.0-alpha.16",
3
+ "version": "1.0.0-alpha.18",
4
4
  "type": "module",
5
5
  "description": "商圈营销模块:资格校验、推荐降级链、券卡(codegen 源)。",
6
6
  "exports": {
@@ -20,16 +20,16 @@
20
20
  "dependencies": {
21
21
  "jsbarcode": "^3.12.3",
22
22
  "qrcode": "^1.5.4",
23
- "@tbox.cn/app-contracts": "1.0.0-alpha.16",
24
- "@tbox.cn/app-contracts-mall": "1.0.0-alpha.16",
25
- "@tbox.cn/app-agent-sdk-server": "1.0.0-alpha.16",
26
- "@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.16"
23
+ "@tbox.cn/app-contracts": "1.0.0-alpha.18",
24
+ "@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.18",
25
+ "@tbox.cn/app-agent-sdk-server": "1.0.0-alpha.18",
26
+ "@tbox.cn/app-contracts-mall": "1.0.0-alpha.18"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@phosphor-icons/react": "2.1.10",
30
30
  "react": "18.3.1",
31
31
  "zod": "3.25.76",
32
- "@tbox.cn/app-agent-ui-kit": "^1.0.0-alpha.16"
32
+ "@tbox.cn/app-agent-ui-kit": "^1.0.0-alpha.18"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/express": "4.17.25",
@@ -50,7 +50,7 @@ routingTerms:
50
50
 
51
51
  触发:"有什么优惠""有没有券""现在有什么折扣""推荐优惠""有没有满减"。
52
52
 
53
- 用户问“有什么可领取/可领优惠券”时,必须调 `listCoupons` 且传 `mode=CLAIMABLE`,出可领取优惠券列表;不得调用 `listEntitlements`,不得把已领取券包当作答案。只有出现“我的/已领取/券包/持有”才进入 OWNED 流程。泛优惠(包含活动、团购)才调 `searchOffers`。用户想了解某张券的详情(面额/门槛/有效期/适用规则)时,调 `getOfferDetail`。
53
+ 用户问“有什么可领取/可领优惠券”时,必须调 `listCoupons` 且传 `mode=CLAIMABLE`,出可领取优惠券列表;不得调用 `listEntitlements`,不得把已领取券包当作答案。只有出现“我的/我有什么卡券/已领取/券包/持有”才进入 OWNED 流程。泛优惠(包含活动、团购)才调 `searchOffers`。用户想了解某张券的详情(面额/门槛/有效期/适用规则)时,调 `getOfferDetail`。
54
54
 
55
55
  **数据禁编**:面额、门槛、库存、有效期一律从工具返回读取,禁止推断或声称任何未查得数据——券规则说错一条,结账时就有一场纠纷。
56
56
 
@@ -79,9 +79,11 @@ routingTerms:
79
79
 
80
80
  ### 三:查"我的券"
81
81
 
82
- 触发:"我有哪些券""我的卡包""我领了什么券""券码是什么"。
82
+ 触发:"我有什么卡券""我有哪些券""我的卡包""我领了什么券""券码是什么"。
83
83
 
84
- 调 `listEntitlements`,返回非空时**必须**出 `promotion-entitlement-list` 卡,不得只在正文列券而省略卡片引用。只有出现“我的/已领取/券包/券码”语义时才进入此流程;“可领取/有什么优惠”永远走上面的 CLAIMABLE 流程。
84
+ 调 `listEntitlements`,出参含 `promotion-entitlement-list` 时**必须**引用该卡。带 `showAlipayWallet` 的卡片有商场券时展示列表和「去卡包查看神券」入口,空列表时展示神券引导卡。正文可简述商场券查询结果,并引导前往支付宝卡包查看神券,不得只在正文列券而省略卡片引用。只有出现“我的/我有什么卡券/已领取/券包/券码”语义时才进入此流程;“可领取/有什么优惠”永远走上面的 CLAIMABLE 流程。
85
+
86
+ 用户询问“刚才那张券领到了吗”时,先定位对应的券与领取记录。持有券列表为空仅表示当前没有查到商场券,不能据此断言上次领取失败;支付宝神券可到卡包核实。
85
87
 
86
88
  **未入会分支**:用户已登录但未入会时,`listEntitlements`/`listCoupons(mode=OWNED)` 出参已含 `member-enrollment-cta` 引导卡——**直接引用该卡 id 即可**,无需再调 member 域 `queryEnrollmentCta`;正文简述“点击卡片完成入会后可查看券包”。
87
89
 
@@ -89,13 +91,15 @@ routingTerms:
89
91
 
90
92
  触发:"哪个优惠最合适""满减怎么算最省""帮我算最优组合""怎么买划算"。
91
93
 
92
- 调 `calculateBestDeal`(需传 `currentAmountCents` 消费金额)。厂商支持时返回确定性最优方案;厂商不支持时只返回文字说明,不得构造 `promotion-best-deal` 旧卡或伪造测算结论。
94
+ 只有消费金额时先问打算在哪家店消费;已有门店或券时沿用,不重复问。用户问自己能用哪张券先查持有券,问可领或可购优惠则查对应列表。
95
+ 有测算工具且条件齐全时,按工具支持的范围使用 `calculateBestDeal`(`currentAmountCents` 单位为分)。缺少测算能力时,仍可根据本轮查到的同一张券、适用门店、门槛和面额给出单券估算。付费购买的代金券需计入购券成本;券规则、可叠加性或适用时段未知时指出缺少的条件,最终金额以结算页为准。
96
+ “这张”“第二个”“还有吗”应对照上一轮展示顺序识别目标,再用本轮结果核实。候选有歧义时列出简称请用户选。仅推荐本次结果中确有的券,不把空结果解释成已下架,不推断售罄、可叠加或最低价。
93
97
 
94
98
  ### 五:查询活动
95
99
 
96
100
  用户问「有什么活动」「活动中心」「查询活动列表」或活动详情时,使用活动玩法域的
97
101
  `listActivityPlays` / `getActivityPlayDetail`,不使用优惠搜索或营销专题替代活动查询。
98
- 活动玩法未装配或查询失败时如实说明,不返回演示活动。
102
+ 追问“这个活动”且上轮只有一个明确目标时沿用该活动标识;多个目标无法区分时先请用户选。活动玩法未装配或查询失败时如实说明,不返回演示活动。
99
103
 
100
104
  ### 六:查营销专题/促销活动
101
105
 
@@ -1,6 +1,6 @@
1
- import { CalendarBlank, CaretDown, Copy, MapPinLine, NavigationArrow, ShieldCheck, Ticket } from '@phosphor-icons/react';
1
+ import { CalendarBlank, CaretDown, CaretRight, Copy, MapPinLine, NavigationArrow, ShieldCheck, Ticket, Wallet } from '@phosphor-icons/react';
2
2
  import { useEffect, useRef, useState } from 'react';
3
- import { callJsapi, httpGet } from '@tbox.cn/app-agent-sdk-client';
3
+ import { callJsapi, httpGet, isInAlipayShell } from '@tbox.cn/app-agent-sdk-client';
4
4
  import type { PromotionEntitlementListCardData } from '@tbox.cn/app-contracts-mall';
5
5
  import { CouponSheet } from '../../components/CouponSheet';
6
6
  import { CouponBarcode, CouponQrCode } from '../../components/CouponQrCode';
@@ -14,6 +14,41 @@ import {
14
14
  PROMOTION_CHIP_COUPON_OFF_CLASS,
15
15
  } from '../../components/class-names';
16
16
 
17
+ const ALIPAY_WALLET_APP_ID = '20000021';
18
+ const ALIPAY_WALLET_QUERY = 'tabPage=voucher';
19
+ const ALIPAY_WALLET_URL = `alipays://platformapi/startapp?appId=${ALIPAY_WALLET_APP_ID}&${ALIPAY_WALLET_QUERY}`; // guard-vendor-neutrality: allow(支付宝公共卡包入口)
20
+
21
+ function AlipayWalletLink() {
22
+ const [failed, setFailed] = useState(false);
23
+ return (
24
+ <footer className="px-3.5 py-3">
25
+ <a
26
+ href={ALIPAY_WALLET_URL}
27
+ className="flex min-h-12 w-full items-center justify-center gap-2 rounded-xl bg-[#edf3e7] px-4 py-3 text-sm font-semibold leading-5 text-[#355638] no-underline hover:brightness-[0.97] active:brightness-95 focus-visible:outline-2 focus-visible:outline-offset-[-3px]"
28
+ onClick={async (event) => {
29
+ if (!isInAlipayShell()) return;
30
+ event.preventDefault();
31
+ setFailed(false);
32
+ try {
33
+ await callJsapi('navigateToMiniProgram', { appId: ALIPAY_WALLET_APP_ID, query: ALIPAY_WALLET_QUERY });
34
+ } catch {
35
+ try {
36
+ await callJsapi('ap.openURL', { url: ALIPAY_WALLET_URL });
37
+ } catch {
38
+ setFailed(true);
39
+ }
40
+ }
41
+ }}
42
+ >
43
+ <Wallet size={18} weight="duotone" aria-hidden="true" />
44
+ 去卡包查看神券
45
+ <CaretRight size={14} weight="bold" aria-hidden="true" />
46
+ </a>
47
+ {failed && <p role="status" className="px-4 py-2 text-xs text-secondary-foreground">暂时无法打开,请在支付宝首页进入「卡包」。</p>}
48
+ </footer>
49
+ );
50
+ }
51
+
17
52
  export function PromotionEntitlementListCard(props: {
18
53
  data: PromotionEntitlementListCardData;
19
54
  cardId?: string;
@@ -63,11 +98,16 @@ export function PromotionEntitlementListCard(props: {
63
98
  <Ticket weight="fill" />
64
99
  <h3 className="text-base font-bold leading-[21px] text-[#2f3a22] [overflow-wrap:anywhere]">我的优惠券</h3>
65
100
  </div>
66
- <p className="mt-1 text-xs leading-4 text-[#626b5c]">当前账户 · 券包权益</p>
101
+ <p className="mt-1 text-xs leading-4 text-[#626b5c]">{data.showAlipayWallet ? '我的商场券' : '当前账户 · 券包权益'}</p>
67
102
  </div>
68
103
  </header>
69
- {!data.items.length ? <div className="promotion-card__empty flex min-h-[94px] items-center justify-center gap-2 p-5 text-xs leading-[normal] text-secondary-foreground"><Ticket size={28} weight="duotone" /><span>{data.noResultsReason ?? '当前账户暂无可用权益'}</span></div> : (
70
- <div ref={listRef} className={`promotion-list__items overflow-hidden px-3.5 pb-1 ${expanded ? ' promotion-list__items--expanded transition-none' : ' transition-[max-height] duration-[320ms] ease-[ease]'}`} style={{ maxHeight }} onTransitionEnd={onTransitionEnd}>
104
+ {!data.items.length && !data.showAlipayWallet && (
105
+ <div className="promotion-card__empty flex min-h-[94px] items-center justify-center gap-2 p-5 text-xs leading-[normal] text-secondary-foreground">
106
+ <Ticket size={28} weight="duotone" /><span>{data.noResultsReason ?? '当前账户暂无可用权益'}</span>
107
+ </div>
108
+ )}
109
+ {data.items.length > 0 && (
110
+ <div ref={listRef} className={`promotion-list__items overflow-hidden px-3.5 ${data.showAlipayWallet && data.items.length <= maxItems ? '[&+footer]:pt-0.5' : 'pb-1'} ${expanded ? ' promotion-list__items--expanded transition-none' : ' transition-[max-height] duration-[320ms] ease-[ease]'}`} style={{ maxHeight }} onTransitionEnd={onTransitionEnd}>
71
111
  {visibleItems.map((item) => (
72
112
  <article
73
113
  key={item.entitlementRef}
@@ -109,6 +149,7 @@ export function PromotionEntitlementListCard(props: {
109
149
  {expanded ? '收起' : `查看更多(${data.items.length - maxItems} 条)`}
110
150
  </button>
111
151
  )}
152
+ {data.showAlipayWallet && <AlipayWalletLink />}
112
153
  {data.items.length > maxItems && <div ref={bottomRef} className="promotion-list__bottom-anchor h-0 flex-none scroll-mb-[max(96px,calc(var(--tbox-chat-bottom-height,0px)_+_24px))]" aria-hidden="true" />}
113
154
  {sheetTarget && (() => {
114
155
  const facts = [
@@ -29,6 +29,7 @@ export const samples: CardSample<PromotionEntitlementListCardData>[] = [
29
29
  note: '待使用、已使用、已过期三态及动作降级同屏',
30
30
  group: '我的券',
31
31
  data: {
32
+ showAlipayWallet: true,
32
33
  items: [
33
34
  { entitlementRef: 'ent:effective', title: '瑞幸咖啡|30元饮品代金券', imageUrl: IMG.coffee, entitlementType: 'COUPON', status: 'EFFECTIVE', codeMasked: '**** 6688', benefitText: '¥30', thresholdText: '无门槛', usageNotice: '1F · 到店点单可用', validUntilText: '2026-09-27 到期' },
34
35
  { entitlementRef: 'ent:used', title: 'KKV 120元优惠券', imageUrl: IMG.lifestyle, entitlementType: 'COUPON', status: 'USED', codeMasked: '**** 1058', benefitText: '¥105 · 8.8折', usageNotice: '已于 2026-08-26 使用', validUntilText: '已使用' },
@@ -45,8 +46,8 @@ export const samples: CardSample<PromotionEntitlementListCardData>[] = [
45
46
  },
46
47
  {
47
48
  label: '我的券·空态',
48
- note: '账户没有券时保留去领券的语义引导',
49
+ note: '无商场券时在卡头下直接展示通栏卡包入口',
49
50
  group: '我的券',
50
- data: { items: [], noResultsReason: '还没有优惠券,先去看看本周神券吧' },
51
+ data: { items: [], showAlipayWallet: true },
51
52
  },
52
53
  ];
@@ -16,6 +16,7 @@ import {
16
16
  activityDetail,
17
17
  activitySummary,
18
18
  entitlementSummary,
19
+ entitlementListResult,
19
20
  offerDetail,
20
21
  offerSummary,
21
22
  } from './tools';
@@ -27,7 +28,7 @@ import { resolveDealRecallPort } from './deal-recall-tools';
27
28
  * 为 QuickCommands 固定句补偿,「活动」子串保留于域内长词以维持卡按钮 value 路由) */
28
29
  export const PROMOTION_INTENTS = {
29
30
  'list-entitlements': {
30
- patterns: ['我的优惠券', '我的券包', '我的券', '已领取的券', '已领优惠券', '持有的优惠券'],
31
+ patterns: ['我有什么卡券', '我有哪些卡券', '我的卡券', '我有哪些券', '我有什么优惠券', '我的优惠券', '我的券包', '我的券', '已领取的券', '已领优惠券', '持有的优惠券'],
31
32
  description: '查询当前会员已拥有的优惠券',
32
33
  },
33
34
  'search-offers': {
@@ -62,7 +63,7 @@ const PROMOTION_RESOLVE_ROUTES: IntentRoute[] = [
62
63
  },
63
64
  ];
64
65
 
65
- const OWNED_INTENT_HINTS = ['我的优惠券', '我的券包', '我的券', '已领取', '已领优惠券', '持有的优惠券'];
66
+ const OWNED_INTENT_HINTS = ['我的卡券', '我的优惠券', '我的券包', '我的券', '已领取', '已领优惠券', '持有的优惠券'];
66
67
  const CLAIMABLE_INTENT_HINTS = ['有什么优惠', '可领取', '可领', '领取优惠券', '领券'];
67
68
 
68
69
  function intentContent(payload: unknown): string {
@@ -90,6 +91,10 @@ function resolveIntent(payload: unknown): ResolvedIntent | null {
90
91
  // → 返回 null 由 handle 放行 LLM,不以 search-offers 兜底吞轮(bumpin/member/guide 同惯例)。
91
92
  if (content.startsWith(NAVIGATION_SENTENCE_PREFIX)) return null;
92
93
  // 先处理业务边界,再交给 BM25:可领取与已领取是互斥查询轴,避免“优惠券”宽词把首页入口落到券包。
94
+ const phrase = content.trim().replace(/[??!!。]+$/u, '');
95
+ if (PROMOTION_INTENTS['list-entitlements'].patterns.some((pattern) => pattern === phrase)) {
96
+ return { kind: 'list-entitlements' };
97
+ }
93
98
  const owned = OWNED_INTENT_HINTS.some((hint) => content.includes(hint));
94
99
  const claimable = CLAIMABLE_INTENT_HINTS.some((hint) => content.includes(hint));
95
100
  if (claimable && !owned) return { kind: 'search-coupons' };
@@ -340,35 +345,29 @@ export function createPromotionIntentHandler(
340
345
  if (gate) return { cards: gate.card ? [gate.card] : [], text: gate.notice };
341
346
  const service = await resolvePromotionEntitlementsPort(reqCtx, ctx);
342
347
  const page = await service.listEntitlements(q, { limit: 50 });
343
- if (page.items.length === 0) {
344
- // 空券降级推荐走 offers 槽(双槽分支:entitlements 查 + offers 推荐)
345
- const offersService = await resolvePromotionOffersPort(reqCtx, ctx);
346
- const offers = await offersService.searchOffers(q, { offerTypes: ['COUPON'], limit: 50 });
347
- const items = offers.items.filter((item) => item.availability.status === 'AVAILABLE');
348
- if (items.length > 0) {
349
- return {
350
- cards: [{ cardType: 'promotion-offer-list', data: {
351
- presentation: 'coupon', mode: 'claimable', items: items.map(offerSummary),
352
- } }],
353
- text: `你的券包里还没有优惠券,为你找到 ${items.length} 条可领优惠`,
354
- };
348
+ const result = entitlementListResult(page, q);
349
+ if (result.cards) {
350
+ let text = `你的券包里有 ${page.items.length} 张优惠券`;
351
+ if (page.showAlipayWallet) {
352
+ text = page.items.length
353
+ ? `查到 ${page.items.length} 张商场优惠券,神券可到支付宝卡包查看。`
354
+ : '暂无商场优惠券,你可以去支付宝卡包查看神券。';
355
355
  }
356
- return { cards: [], text: '你的券包里还没有优惠券,当前也没有可领取优惠' };
356
+ return { cards: result.cards, text };
357
357
  }
358
- return {
359
- cards: [
360
- {
361
- cardType: 'promotion-entitlement-list',
362
- data: {
363
- mallId: q.scope.mallId,
364
- miniAppId: q.scope.miniAppId,
365
- items: page.items.map(entitlementSummary),
366
- ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
367
- },
368
- },
369
- ],
370
- text: `你的券包里有 ${page.items.length} 张优惠券`,
371
- };
358
+ // 空券降级推荐走 offers 槽(双槽分支:entitlements 查 + offers 推荐)
359
+ const offersService = await resolvePromotionOffersPort(reqCtx, ctx);
360
+ const offers = await offersService.searchOffers(q, { offerTypes: ['COUPON'], limit: 50 });
361
+ const items = offers.items.filter((item) => item.availability.status === 'AVAILABLE');
362
+ if (items.length > 0) {
363
+ return {
364
+ cards: [{ cardType: 'promotion-offer-list', data: {
365
+ presentation: 'coupon', mode: 'claimable', items: items.map(offerSummary),
366
+ } }],
367
+ text: `你的券包里还没有优惠券,为你找到 ${items.length} 条可领优惠`,
368
+ };
369
+ }
370
+ return { cards: [], text: '你的券包里还没有优惠券,当前也没有可领取优惠' };
372
371
  }
373
372
  case 'list-activities': {
374
373
  const delegated = await delegateLinkedActivity(ctx, payload, reqCtx);
@@ -65,7 +65,7 @@ const excludedDealIdsSchema = z.array(z.string().min(1).max(128)).default([]);
65
65
  * - silent:不发前端事件;结果 reminder 注入 + cards 经 capture 入本轮候选池;
66
66
  * - 出参体积门:CLAIMABLE 出参 build 期实测 ≤ 2KB(promotion pretool 测试断言),超限即撤本 preTool。
67
67
  */
68
- const OWNED_INTENT_RE = /我的券|已领|券包|券码/;
68
+ const OWNED_INTENT_RE = /我的(?:优惠券|卡券|券)|已领|券包|券码|^我(?:有什么|有哪些)(?:优惠券|卡券|券)[??!!。]*$/u;
69
69
  const EXTERNAL_DEAL_INTENT_RE = /支付宝神券|外部团购/;
70
70
 
71
71
  const listCouponsPreTool = definePreTool(tools.listCoupons, {
@@ -13,6 +13,7 @@ import type {
13
13
  PromotionActivityPort,
14
14
  PromotionEntitlement,
15
15
  PromotionEntitlementPort,
16
+ PromotionEntitlementPage,
16
17
  PromotionOffer,
17
18
  PromotionOfferQueryPort,
18
19
  PromotionQueryContext,
@@ -40,6 +41,22 @@ function withCards<T extends Record<string, unknown>>(facts: T, cardType: string
40
41
  return { ...facts, cards: [{ cardType, data: facts, note }] };
41
42
  }
42
43
 
44
+ export function entitlementListResult(page: PromotionEntitlementPage, q: PromotionQueryContext) {
45
+ const facts = {
46
+ mallId: q.scope.mallId,
47
+ miniAppId: q.scope.miniAppId,
48
+ items: page.items.map(entitlementSummary),
49
+ ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
50
+ ...(page.showAlipayWallet ? { showAlipayWallet: true } : {}),
51
+ ...(!page.items.length ? {
52
+ noResultsReason: page.showAlipayWallet ? '暂无商场优惠券' : '还没有优惠券,可让我帮你找找可领优惠',
53
+ } : {}),
54
+ };
55
+ if (!facts.items.length && !page.showAlipayWallet) return { ...facts, cards: undefined };
56
+ const first = facts.items[0];
57
+ return withCards(facts, 'promotion-entitlement-list', first ? `我的优惠券 ${facts.items.length} 张 · ${first.title}` : '暂无商场优惠券,可去卡包查看神券');
58
+ }
59
+
43
60
  function dateText(value?: string): string | undefined {
44
61
  if (!value) return undefined;
45
62
  const date = new Date(value);
@@ -324,6 +341,23 @@ const activityDetailInput = coerce(
324
341
  z.object({ activityRef: z.string().optional(), keyword: z.string().optional() }),
325
342
  );
326
343
 
344
+ // Detail lookups need a reference selected by the user or a concrete name from the conversation.
345
+ const needsSelection = { found: false, needsSelection: true, message: '请先确认具体的活动或优惠名称,再查详情。' } as const;
346
+
347
+ function hasDetailTarget(ref: unknown, keyword: unknown): boolean {
348
+ if (typeof ref === 'string' && ref.trim()) return true;
349
+ if (typeof keyword !== 'string' || !keyword.trim()) return false;
350
+ return !/^(?:刚才的?|上面的?|这(?:个|张|场|次)?|那(?:个|张|场|次)?|该|它)(?:活动|促销|优惠券?|券|专题|礼包)?[??。!!]*$/.test(keyword.trim());
351
+ }
352
+
353
+ function uniqueResult<T extends { title: string }>(page: { items: readonly T[]; hasMore: boolean }, keyword: string) {
354
+ if (!page.items.length) return null;
355
+ if (page.hasMore) return needsSelection;
356
+ if (page.items.length === 1) return page.items[0];
357
+ const exact = page.items.filter((item) => item.title === keyword.trim());
358
+ return exact.length === 1 ? exact[0] : needsSelection;
359
+ }
360
+
327
361
  export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
328
362
  /** 活动工具与确定性活动意图共用联单分流;未启用策略/未装模块返回 undefined。 */
329
363
  const delegateLinkedActivity = async (reqCtx: RequestContext) => {
@@ -354,15 +388,15 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
354
388
  args: Record<string, unknown>,
355
389
  offerTypes?: readonly OfferType[],
356
390
  ) => {
357
- if (typeof args.offerRef === 'string' && args.offerRef) {
391
+ if (typeof args.offerRef === 'string' && args.offerRef.trim()) {
358
392
  return service.getOfferDetail(q, { offerRef: args.offerRef });
359
393
  }
360
394
  const page = await service.searchOffers(q, {
361
395
  keyword: args.keyword as string | undefined,
362
396
  offerTypes,
363
- limit: 1,
397
+ limit: 2,
364
398
  });
365
- return page.items[0] ?? null;
399
+ return uniqueResult(page, String(args.keyword));
366
400
  };
367
401
  const resolveActivity = async (
368
402
  service: PromotionActivityPort,
@@ -372,9 +406,10 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
372
406
  if (typeof args.activityRef === 'string' && args.activityRef) {
373
407
  return service.getActivityDetail(q, args.activityRef);
374
408
  }
375
- const page = await service.listActivities(q, { keyword: args.keyword as string | undefined, limit: 1 });
376
- const first = page.items[0];
377
- return first ? service.getActivityDetail(q, first.activityRef) : null;
409
+ const page = await service.listActivities(q, { keyword: args.keyword as string, limit: 2 });
410
+ const selected = uniqueResult(page, String(args.keyword));
411
+ if (!selected || 'needsSelection' in selected) return selected;
412
+ return service.getActivityDetail(q, selected.activityRef);
378
413
  };
379
414
  const search = (
380
415
  service: PromotionOfferQueryPort,
@@ -389,7 +424,7 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
389
424
  limit: args.limit ? Number(args.limit) : 50,
390
425
  offerTypes,
391
426
  });
392
- const entitlementFacts = async (
427
+ const listOwnedCoupons = async (
393
428
  service: PromotionEntitlementPort,
394
429
  q: PromotionQueryContext,
395
430
  args: Record<string, unknown>,
@@ -412,13 +447,7 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
412
447
  cursor: args.cursor as string | undefined,
413
448
  limit: args.limit ? Number(args.limit) : 50,
414
449
  });
415
- return {
416
- mallId: q.scope.mallId,
417
- miniAppId: q.scope.miniAppId,
418
- items: page.items.map(entitlementSummary),
419
- ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
420
- ...(page.items.length === 0 ? { noResultsReason: '还没有优惠券,可让我帮你找找可领优惠' } : {}),
421
- };
450
+ return entitlementListResult(page, q);
422
451
  };
423
452
 
424
453
  const listActivityCategories = createTool({
@@ -499,12 +528,14 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
499
528
  description: '查询指定活动详情、时间、名额和参与条件。',
500
529
  inputSchema: activityDetailInput,
501
530
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
531
+ if (!hasDetailTarget(args.activityRef, args.keyword)) return needsSelection;
502
532
  const reqCtx = requireToolRequestContext(execCtx, 'getActivityDetail');
503
533
  const delegated = await delegateLinkedActivity(reqCtx);
504
534
  if (delegated) return delegated;
505
535
  const { service, q } = await requireService(execCtx, resolvePromotionActivitiesPort);
506
536
  const detail = await resolveActivity(service, q, args);
507
537
  if (!detail) return { found: false, message: '未找到该活动' };
538
+ if ('needsSelection' in detail) return detail;
508
539
  const facts = { found: true as const, ...activityDetail(detail, 'detail') };
509
540
  return withCards(facts, 'promotion-activity-detail', `活动详情:${detail.title}`);
510
541
  },
@@ -515,12 +546,14 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
515
546
  description: '查询指定活动的可选场次,只返回只读状态,不执行报名。',
516
547
  inputSchema: activityDetailInput,
517
548
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
549
+ if (!hasDetailTarget(args.activityRef, args.keyword)) return needsSelection;
518
550
  const reqCtx = requireToolRequestContext(execCtx, 'listActivitySessions');
519
551
  const delegated = await delegateLinkedActivity(reqCtx);
520
552
  if (delegated) return delegated;
521
553
  const { service, q } = await requireService(execCtx, resolvePromotionActivitiesPort);
522
554
  const detail = await resolveActivity(service, q, args);
523
555
  if (!detail) return { found: false, message: '未找到该活动' };
556
+ if ('needsSelection' in detail) return detail;
524
557
  const sessions = service.listActivitySessions
525
558
  ? await service.listActivitySessions(q, detail.activityRef)
526
559
  : detail.sessions;
@@ -534,12 +567,14 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
534
567
  description: '查询指定活动的报名条件和参与步骤,不执行报名。',
535
568
  inputSchema: activityDetailInput,
536
569
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
570
+ if (!hasDetailTarget(args.activityRef, args.keyword)) return needsSelection;
537
571
  const reqCtx = requireToolRequestContext(execCtx, 'getActivityGuide');
538
572
  const delegated = await delegateLinkedActivity(reqCtx);
539
573
  if (delegated) return delegated;
540
574
  const { service, q } = await requireService(execCtx, resolvePromotionActivitiesPort);
541
575
  const detail = await resolveActivity(service, q, args);
542
576
  if (!detail) return { found: false, message: '未找到该活动' };
577
+ if ('needsSelection' in detail) return detail;
543
578
  const facts = activityDetail(detail, 'guide');
544
579
  return withCards(facts, 'promotion-activity-detail', `活动参与方式:${detail.title}`);
545
580
  },
@@ -571,6 +606,7 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
571
606
  z.object({ offerRef: z.string().optional(), entitlementRef: z.string().optional(), keyword: z.string().optional() }),
572
607
  ),
573
608
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
609
+ if (!args.entitlementRef && !hasDetailTarget(args.offerRef, args.keyword)) return needsSelection;
574
610
  const { service, q, reqCtx } = await requireService(execCtx, resolvePromotionOffersPort);
575
611
  // entitlementRef 反查 = 我的券详情(属人):仅该分支门禁;offerRef/keyword 公共反查不拦
576
612
  if (typeof args.entitlementRef === 'string' && args.entitlementRef) {
@@ -601,14 +637,7 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
601
637
  inputSchema: searchInput,
602
638
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
603
639
  const { service, q, reqCtx } = await requireService(execCtx, resolvePromotionEntitlementsPort);
604
- const facts = await entitlementFacts(service, q, args, reqCtx);
605
- return facts.items.length
606
- ? withCards(
607
- facts,
608
- 'promotion-entitlement-list',
609
- `我的优惠券 ${facts.items.length} 张${facts.items[0] ? ` · ${facts.items[0].title}` : ''}`,
610
- )
611
- : facts;
640
+ return listOwnedCoupons(service, q, args, reqCtx);
612
641
  },
613
642
  });
614
643
 
@@ -636,9 +665,11 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
636
665
  description: '按营销专题标识或关键词精确查询活动详情。',
637
666
  inputSchema: detailInput,
638
667
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
668
+ if (!hasDetailTarget(args.offerRef, args.keyword)) return needsSelection;
639
669
  const { service, q } = await requireService(execCtx, resolvePromotionOffersPort);
640
670
  const offer = await resolveOffer(service, q, args, ['PROMOTION']);
641
671
  if (!offer) return { found: false, message: '未找到该营销专题' };
672
+ if ('needsSelection' in offer) return offer;
642
673
  const facts = { found: true as const, ...offerDetail(offer, false, 'promotion') };
643
674
  return withCards(facts, 'promotion-offer-detail', `营销活动详情:${offer.title}`);
644
675
  },
@@ -649,9 +680,11 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
649
680
  description: '查询营销专题的厂商参与步骤,不执行报名或领取。',
650
681
  inputSchema: detailInput,
651
682
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
683
+ if (!hasDetailTarget(args.offerRef, args.keyword)) return needsSelection;
652
684
  const { service, q } = await requireService(execCtx, resolvePromotionOffersPort);
653
685
  const offer = await resolveOffer(service, q, args, ['PROMOTION']);
654
686
  if (!offer) return { found: false, message: '未找到该营销专题' };
687
+ if ('needsSelection' in offer) return offer;
655
688
  const facts = { found: true as const, ...offerDetail(offer, false, 'promotion-guide') };
656
689
  return withCards(facts, 'promotion-offer-detail', `参与方式:${offer.title}`);
657
690
  },
@@ -659,7 +692,7 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
659
692
 
660
693
  const listCoupons = createTool({
661
694
  id: 'listCoupons',
662
- description: '查询优惠券列表。默认只查询当前可领取优惠券(CLAIMABLE);只有用户明确说“我的券/已领取/券包”时才传 mode=OWNED。mode=OWNED 已登录未入会时返回入会引导卡(member-enrollment-cta),无需再调 member 域 queryEnrollmentCta。',
695
+ description: '查询优惠券列表。默认只查询当前可领取优惠券(CLAIMABLE);只有用户明确说“我有什么卡券/我的券/已领取/券包”时才传 mode=OWNED。mode=OWNED 已登录未入会时返回入会引导卡(member-enrollment-cta),无需再调 member 域 queryEnrollmentCta。',
663
696
  inputSchema: coerce(
664
697
  z.object({
665
698
  mode: z.enum(['CLAIMABLE', 'OWNED']).default('CLAIMABLE'),
@@ -672,10 +705,7 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
672
705
  // 模式分流双槽(017):OWNED = 我的券 → entitlements 槽;CLAIMABLE = 可领券 → offers 槽
673
706
  if (args.mode === 'OWNED') {
674
707
  const { service, q, reqCtx } = await requireService(execCtx, resolvePromotionEntitlementsPort);
675
- const facts = await entitlementFacts(service, q, args, reqCtx);
676
- return facts.items.length
677
- ? withCards(facts, 'promotion-entitlement-list', `我的优惠券 ${facts.items.length} 张${facts.items[0] ? ` · ${facts.items[0].title ?? ''}` : ''}`)
678
- : facts;
708
+ return listOwnedCoupons(service, q, args, reqCtx);
679
709
  }
680
710
  const { service, q, reqCtx } = await requireService(execCtx, resolvePromotionOffersPort);
681
711
  const [page, dealRecall] = await Promise.all([
@@ -703,9 +733,11 @@ export function createPromotionTools(opts: { getCtx: () => ServerContext }) {
703
733
  description: '查询组合礼包及其子权益。',
704
734
  inputSchema: detailInput,
705
735
  execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
736
+ if (!hasDetailTarget(args.offerRef, args.keyword)) return needsSelection;
706
737
  const { service, q } = await requireService(execCtx, resolvePromotionOffersPort);
707
738
  const offer = await resolveOffer(service, q, args, ['BUNDLE']);
708
739
  if (!offer) return { found: false, message: '未找到该优惠礼包' };
740
+ if ('needsSelection' in offer) return offer;
709
741
  const facts = {
710
742
  found: true as const,
711
743
  ...offerDetail(offer, supportsAcquire(service), 'package'),
@@ -2,7 +2,7 @@
2
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 { httpPost, navigateToAlipayPage, sendCardAction } from '@tbox.cn/app-agent-sdk-client';
5
+ import { callJsapi, isInAlipayShell, httpPost, navigateToAlipayPage, sendCardAction } from '@tbox.cn/app-agent-sdk-client';
6
6
  import {
7
7
  PromotionActivityCategoryListCard,
8
8
  PromotionActivityDetailCard,
@@ -18,12 +18,14 @@ 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, httpPost: vi.fn(), navigateToAlipayPage: vi.fn(() => Promise.resolve()), sendCardAction: vi.fn() };
21
+ return { ...mod, isInAlipayShell: vi.fn(() => false), callJsapi: vi.fn(), 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(isInAlipayShell).mockReturnValue(false);
28
+ vi.mocked(callJsapi).mockReset();
27
29
  vi.mocked(httpPost).mockReset();
28
30
  vi.mocked(sendCardAction).mockReset();
29
31
  vi.mocked(navigateToAlipayPage).mockReset();
@@ -336,11 +338,12 @@ describe('legacy 19 个营销展示语义', () => {
336
338
  });
337
339
 
338
340
  it('entitlement-list 恢复钱包、状态、券码和安全提示', () => {
339
- const host = render(<PromotionEntitlementListCard data={{ items: [{ entitlementRef: 'e1', title: '停车券', entitlementType: 'COUPON', status: 'EFFECTIVE', codeMasked: '****8888', validUntilText: '有效期至 2026-12-31' }] } as never} cardId="c1" />);
341
+ const host = render(<PromotionEntitlementListCard data={{ showAlipayWallet: true, items: [{ entitlementRef: 'e1', title: '停车券', entitlementType: 'COUPON', status: 'EFFECTIVE', codeMasked: '****8888', validUntilText: '有效期至 2026-12-31' }] } as never} cardId="c1" />);
340
342
  expect(host.querySelector('.promotion-entitlements')?.classList.contains('promotion-list--coupon')).toBe(true);
341
343
  expect(host.querySelector('.promotion-list--offers')).toBeNull();
342
344
  expect(host.querySelector('.promotion-coupon__header')?.textContent).toContain('我的优惠券');
343
- expect(host.querySelector('.promotion-coupon__header')?.textContent).toContain('当前账户 · 券包权益');
345
+ expect(host.querySelector('.promotion-coupon__header')?.textContent).toContain('我的商场券');
346
+ expect(host.querySelector('a')?.textContent).toContain('去卡包查看神券');
344
347
  expect(host.querySelector('.promotion-activity__header-art')).toBeNull(); // 素材变量链:头图 img 已转 CSS background
345
348
  // 券码不再摊在行上:一屏几张券,脱敏码谁也用不上,点开浮层才需要
346
349
  expect(host.querySelector('.promotion-coupon-row')?.textContent).not.toContain('****8888');
@@ -351,6 +354,27 @@ describe('legacy 19 个营销展示语义', () => {
351
354
  expect(host.querySelector('.promotion-card__footer')).toBeNull();
352
355
  });
353
356
 
357
+ it('无商场券时展示卡包入口,支付宝壳优先唤起卡包,失败时回退并提示', async () => {
358
+ vi.mocked(isInAlipayShell).mockReturnValue(true);
359
+ vi.mocked(callJsapi).mockRejectedValue(new Error('unavailable'));
360
+ const host = render(<PromotionEntitlementListCard data={{ items: [], showAlipayWallet: true }} />);
361
+ expect(host.querySelector('.promotion-card__empty')).toBeNull();
362
+ expect(host.textContent).not.toContain('暂无商场优惠券');
363
+ expect(host.querySelector('.promotion-coupon__header')?.textContent).toContain('我的优惠券');
364
+ expect(host.querySelector('.promotion-list__items')).toBeNull();
365
+ const link = host.querySelector<HTMLAnchorElement>('header + footer a')!;
366
+ expect(link.textContent).toContain('去卡包查看神券');
367
+ expect(link.getAttribute('href')).toBe('alipays://platformapi/startapp?appId=20000021&tabPage=voucher'); // guard-vendor-neutrality: allow(支付宝公共卡包入口)
368
+ await act(async () => link.click());
369
+ expect(callJsapi).toHaveBeenNthCalledWith(1, 'navigateToMiniProgram', { appId: '20000021', query: 'tabPage=voucher' });
370
+ expect(callJsapi).toHaveBeenNthCalledWith(2, 'ap.openURL', { url: link.href });
371
+ expect(host.querySelector('[role=status]')).not.toBeNull();
372
+ vi.mocked(callJsapi).mockResolvedValueOnce({});
373
+ await act(async () => link.click());
374
+ expect(callJsapi).toHaveBeenCalledTimes(3);
375
+ expect(host.querySelector('[role=status]')).toBeNull();
376
+ });
377
+
354
378
  it('我的优惠券默认最多展示 4 条,maxItems 可配置', () => {
355
379
  const items = Array.from({ length: 5 }, (_, index) => ({
356
380
  entitlementRef: `e${index}`,