@tbox.cn/app-module-alipay-activity 0.2.3

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.
Files changed (44) hide show
  1. package/AGENTS.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +48 -0
  4. package/dist/bumpin-VKHLYCKG.css +527 -0
  5. package/dist/chunk-RM7IUA3M.js +634 -0
  6. package/dist/client/index.d.ts +11 -0
  7. package/dist/client/index.js +235 -0
  8. package/dist/index.d.ts +7 -0
  9. package/dist/index.js +26 -0
  10. package/dist/linked-card-background-MVGUOJ7J.jpg +0 -0
  11. package/dist/server/index.d.ts +224 -0
  12. package/dist/server/index.js +28 -0
  13. package/package.json +69 -0
  14. package/schemas/credentials/alipay-open-v1.json +12 -0
  15. package/skills/alipay-activity/SKILL.md +59 -0
  16. package/src/client/assets/linked-card-background.jpg +0 -0
  17. package/src/client/assets.d.ts +10 -0
  18. package/src/client/cards/bumpin-activity/index.tsx +213 -0
  19. package/src/client/components/ImageWithFallback.tsx +37 -0
  20. package/src/client/index.ts +18 -0
  21. package/src/client/styles/bumpin.css +527 -0
  22. package/src/client/utils/sanitize-activity-html.ts +40 -0
  23. package/src/index.ts +1 -0
  24. package/src/server/cards/bumpin-activity/meta.ts +44 -0
  25. package/src/server/cards/bumpin-activity/samples.ts +164 -0
  26. package/src/server/handler.ts +87 -0
  27. package/src/server/index.ts +79 -0
  28. package/src/server/integrations/alipay/adapter.ts +210 -0
  29. package/src/server/integrations/alipay/client.ts +127 -0
  30. package/src/server/integrations/alipay/provider.ts +9 -0
  31. package/src/server/ports.ts +68 -0
  32. package/src/server/tools.ts +212 -0
  33. package/tbox.module.json +39 -0
  34. package/tests/adapter.test.ts +178 -0
  35. package/tests/bumpin-card-status.test.tsx +80 -0
  36. package/tests/client.test.ts +93 -0
  37. package/tests/intent-routing.test.ts +118 -0
  38. package/tests/ports.test.ts +160 -0
  39. package/tests/pretool-routing.test.ts +37 -0
  40. package/tests/samples.test.ts +29 -0
  41. package/tests/skill.test.ts +39 -0
  42. package/tests/tools.test.ts +193 -0
  43. package/tsconfig.json +8 -0
  44. package/tsup.config.ts +36 -0
@@ -0,0 +1,164 @@
1
+ /**
2
+ * promotion-bumpin-activity 附加预览样本(沉淀自 mall dev-gallery 首页场景画廊)。
3
+ *
4
+ * 一张卡两种模式(detail = 对话流完整卡 / banner = 压缩形态)× 两种进度样式
5
+ * (steps 圆形节点 / bar 线性进度条),加奖励池有无与活动状态交叉成下面的样本集。
6
+ *
7
+ * 方法论(迁移自画廊维护约定):
8
+ * - 覆盖基准是组件实际读取的 data 分支(进度节点点亮/达成语气/多券截断/空奖励池收口/
9
+ * 长文案撑高/终态措辞),而非 sampleData 的形状;
10
+ * - 视觉等价的输入合并为一格,note 列全合并口径;
11
+ * - 样本即契约:data 必须 dataSchema 校验通过且无 shape 外键(tests/samples.test.ts 双断言)。
12
+ */
13
+ import type { CardSample } from '@tbox.cn/app-contracts';
14
+ import type { PromotionBumpInActivityCardData } from '@tbox.cn/app-contracts-mall';
15
+
16
+ /** 一张券:奖励池的最小单元,多券样本在此基础上改名与面额。 */
17
+ const VOUCHER = {
18
+ prizeId: 'PZ1741674669',
19
+ voucherName: '88元惊喜礼包',
20
+ voucherType: 'ITEM_REDUCTION_AMOUNT',
21
+ reductionAmount: '88',
22
+ thresholdAmountText: '满100元可用',
23
+ unit: '元',
24
+ merchantName: '示例商户',
25
+ };
26
+
27
+ /** 与 meta.ts 的 sampleData 同源的基准形态。 */
28
+ const BASE = {
29
+ activityRef: 'demo:bumpin:activity:1',
30
+ title: '碰一下 | 出惊喜',
31
+ mainTitle: '碰一下支付 5 笔,得 88 元惊喜礼包',
32
+ tagLabel: '碰一下联单',
33
+ actStatus: 'PROCESSING',
34
+ totalProgress: '5',
35
+ currentProgress: '1',
36
+ progressUnit: '笔',
37
+ startAtText: '2026-08-01',
38
+ endAtText: '2026-08-31',
39
+ vouchers: [VOUCHER],
40
+ mode: 'detail' as const,
41
+ progressStyle: 'steps' as const,
42
+ } satisfies PromotionBumpInActivityCardData;
43
+
44
+ export const samples: CardSample<PromotionBumpInActivityCardData>[] = [
45
+ // ── detail 模式:对话流里的完整详情 ──
46
+ {
47
+ label: '详情·联单进行中',
48
+ note: '基准形态:steps 圆形节点 1/5、单券奖励池。未下发 backgroundUrl 时头部回落到模块自带的联单背景图',
49
+ group: '详情形态(mode=detail)',
50
+ data: BASE,
51
+ },
52
+ {
53
+ label: '详情·接近达成',
54
+ note: 'currentProgress=4/5——节点轨道点亮到倒数第二环,检查末环与数值的收口',
55
+ group: '详情形态(mode=detail)',
56
+ data: { ...BASE, currentProgress: '4' },
57
+ },
58
+ {
59
+ label: '详情·已达成',
60
+ note: '5/5——全部节点点亮,奖励池应是可领而非待解锁的语气',
61
+ group: '详情形态(mode=detail)',
62
+ data: { ...BASE, currentProgress: '5' },
63
+ },
64
+ {
65
+ label: '详情·多券奖励池',
66
+ note: '三档券并列——检查券行的截断与面额对齐,以及卡片纵向是否被撑得过长',
67
+ group: '详情形态(mode=detail)',
68
+ data: {
69
+ ...BASE,
70
+ currentProgress: '3',
71
+ vouchers: [
72
+ VOUCHER,
73
+ { ...VOUCHER, prizeId: 'PZ2', voucherName: '30元通用券', reductionAmount: '30', thresholdAmountText: '满50元可用' },
74
+ { ...VOUCHER, prizeId: 'PZ3', voucherName: '10元咖啡券', reductionAmount: '10', thresholdAmountText: '无门槛', merchantName: '日光咖啡' },
75
+ ],
76
+ },
77
+ },
78
+ {
79
+ label: '详情·无奖励池',
80
+ note: 'vouchers 为空——契约允许,卡片应收口而不是留一块空区',
81
+ group: '详情形态(mode=detail)',
82
+ data: { ...BASE, vouchers: [] },
83
+ },
84
+ {
85
+ label: '详情·bar 进度',
86
+ note: "progressStyle='bar'——线性进度条而非圆形节点;同时不再回落联单背景图,头部形态随之不同",
87
+ group: '详情形态(mode=detail)',
88
+ data: { ...BASE, progressStyle: 'bar' as const, currentProgress: '2' },
89
+ },
90
+ {
91
+ label: '详情·带参与步骤',
92
+ note: 'steps 数组下发时渲染参与说明——与进度节点是两回事,检查两者不打架',
93
+ group: '详情形态(mode=detail)',
94
+ data: {
95
+ ...BASE,
96
+ steps: [
97
+ { title: '打开支付宝碰一下', description: '在商场任意收银台完成支付' },
98
+ { title: '累计 5 笔支付', description: '同一活动期内累计,跨门店有效' },
99
+ { title: '领取惊喜礼包', description: '达成后在本卡片领取' },
100
+ ],
101
+ },
102
+ },
103
+ {
104
+ label: '详情·活动未开始',
105
+ note: "actStatus='NOT_START' + 起止时间——头部「未开始」角标、有效期行改「日开始」、进度不诱导参与",
106
+ group: '详情形态(mode=detail)',
107
+ data: { ...BASE, actStatus: 'NOT_START', currentProgress: '0' },
108
+ },
109
+ {
110
+ label: '详情·活动已结束',
111
+ note: "actStatus='FINISH'——终态角标「已结束」,检查是否仍在鼓励继续支付",
112
+ group: '详情形态(mode=detail)',
113
+ data: { ...BASE, actStatus: 'FINISH', currentProgress: '3' },
114
+ },
115
+ {
116
+ label: '详情·已领奖',
117
+ note: "actStatus='RECEIVED'——用户级终态:金色「已领奖」角标 + 奖励池标题「已领取」前缀",
118
+ group: '详情形态(mode=detail)',
119
+ data: { ...BASE, actStatus: 'RECEIVED', currentProgress: '5' },
120
+ },
121
+ {
122
+ label: '详情·长标题与长描述',
123
+ note: '主标题与描述都超长——检查换行撑高与截断,别把奖励池挤出首屏',
124
+ group: '详情形态(mode=detail)',
125
+ data: {
126
+ ...BASE,
127
+ mainTitle: '碰一下支付满 5 笔即可解锁 88 元惊喜礼包,活动期内跨门店累计有效,先到先得',
128
+ description: '活动最终解释权归主办方所有;礼包数量有限,达成后请在活动结束前完成领取,逾期视为放弃。',
129
+ },
130
+ },
131
+ {
132
+ label: '详情·历史卡',
133
+ note: 'isHistory——卡内动作禁用,信息照常呈现',
134
+ group: '详情形态(mode=detail)',
135
+ data: { ...BASE, currentProgress: '3' },
136
+ isHistory: true,
137
+ },
138
+
139
+ // ── banner 模式:压缩形态 ──
140
+ {
141
+ label: '横幅·联单进行中',
142
+ note: "mode='banner'——压缩成一条,与首页海报是同一活动的两种呈现",
143
+ group: '横幅形态(mode=banner)',
144
+ data: { ...BASE, mode: 'banner' as const, currentProgress: '2' },
145
+ },
146
+ {
147
+ label: '横幅·bar 进度',
148
+ note: 'banner + bar——最紧凑的一档,检查进度条与文案在一行内的挤压',
149
+ group: '横幅形态(mode=banner)',
150
+ data: { ...BASE, mode: 'banner' as const, progressStyle: 'bar' as const, currentProgress: '2' },
151
+ },
152
+ {
153
+ label: '横幅·已达成',
154
+ note: 'banner 终态——5/5,检查压缩形态下达成语气是否仍然清楚',
155
+ group: '横幅形态(mode=banner)',
156
+ data: { ...BASE, mode: 'banner' as const, currentProgress: '5' },
157
+ },
158
+ {
159
+ label: '横幅·未开始',
160
+ note: 'banner + NOT_START——压缩形态下「未开始」角标与「日开始」行仍需可辨',
161
+ group: '横幅形态(mode=banner)',
162
+ data: { ...BASE, mode: 'banner' as const, actStatus: 'NOT_START', currentProgress: '0' },
163
+ },
164
+ ];
@@ -0,0 +1,87 @@
1
+ /**
2
+ * 支付宝「碰出惊喜」意图处理器。
3
+ * 意图 bumpin-activity:用户主动询问碰出惊喜活动。
4
+ * 意图路由收窄(BM25 bigram 泄漏防护):patterns 只保留碰/惊字族域词、不含「支付宝」/「活动」
5
+ * 子串——pattern 内子串会经 bigram 展开泄漏为子串敏感(「支付宝互动活动」曾致「支付宝哪里
6
+ * 可以充值」类无关长句误入本模块直出卡);「支付宝碰一下」/「我的惊喜活动」等句式仍可靠
7
+ * 碰一/一下/惊喜 bigram 桥接命中。
8
+ */
9
+ import type { HandlerDefinition, ServerContext } from '@tbox.cn/app-sdk/server';
10
+ import { memberGateCardOf, toMallQueryContext, PROMOTION_ACTIVITY_ROUTING_POLICY } from '@tbox.cn/app-contracts-mall';
11
+ import type {
12
+ MemberStatusFactory,
13
+ PromotionActivityDetail,
14
+ PromotionActivityRoutingPolicy,
15
+ } from '@tbox.cn/app-contracts-mall';
16
+ import { resolveAlipayBumpInService } from './ports';
17
+ import { toBumpInCardData } from './tools';
18
+
19
+ /** 碰出惊喜域词(handler 洋葱守卫:intent 命中但 content 无域词 = 外层误命中 → 放行 LLM) */
20
+ const BUMPIN_DOMAIN_HINTS = ['碰出惊喜', '碰一下', '碰一碰', '惊喜'];
21
+
22
+ /** provider 通过 TIER1 策略声明活动中心是否由本模块承接。 */
23
+ function isLinkedActivityScope(ctx: ServerContext, reqCtx: NonNullable<Parameters<HandlerDefinition['handle']>[3]>): boolean {
24
+ const policy = ctx.services.resolve<PromotionActivityRoutingPolicy>(PROMOTION_ACTIVITY_ROUTING_POLICY);
25
+ return policy?.(reqCtx) ?? false;
26
+ }
27
+
28
+ /** 碰出惊喜 intent patterns(collectIntentRoutes 装配收集;顶层确定性档——品牌固定句 exact 直出,
29
+ * 自然语言问句(「碰一下怎么参加」等)走 LLM → getBumpInActivity 工具编排,不再 BM25 语义截断) */
30
+ export const BUMPIN_INTENTS = {
31
+ 'bumpin-activity': {
32
+ patterns: ['碰出惊喜', '碰一下', '碰一碰'],
33
+ description: '查询支付宝碰出惊喜活动',
34
+ },
35
+ } as const;
36
+
37
+ export function createAlipayActivityHandler(ctx: ServerContext): HandlerDefinition {
38
+ return {
39
+ id: 'alipay-activity',
40
+ intents: Object.values(BUMPIN_INTENTS).map(({ patterns }) => ({ patterns: [...patterns], match: 'exact' as const })),
41
+ handle: async (action, payload, _ctx, reqCtx) => {
42
+ // 洋葱守卫(洋葱定律 1:未识别 = 失败 = 放行不吞——同 member/shopping-guide 惯例):
43
+ // content 无碰/惊域词 = 外层 BM25 误命中(收窄后罕见残留碰撞)→ continueWith 放行
44
+ // LLM 主路径,不吐卡不吞轮。
45
+ const content =
46
+ typeof (payload as { content?: unknown } | undefined)?.content === 'string'
47
+ ? (payload as { content: string }).content.trim()
48
+ : '';
49
+ // promotion 模块的活动意图在专属 provider 场景经此动作统一到联单卡;未启用时返回放行信号,
50
+ // 由调用方保留原有 provider 活动卡行为。该动作不声明为顶层 intent,避免改变路由优先级。
51
+ if (action === 'activity-router') {
52
+ if (!reqCtx || !isLinkedActivityScope(ctx, reqCtx)) {
53
+ return { cards: [], continueWith: { content } };
54
+ }
55
+ }
56
+ if (!BUMPIN_DOMAIN_HINTS.some((hint) => content.includes(hint))) {
57
+ if (action === 'activity-router') {
58
+ // 分流动作不要求用户使用“碰一下”品牌词;活动中心固定句也应展示同一张联单卡。
59
+ } else {
60
+ return { cards: [], continueWith: { content } };
61
+ }
62
+ }
63
+ if (!reqCtx) return { cards: [], text: '支付宝活动服务不可用(缺少运行上下文)' };
64
+ // 登录轴门禁:只拦匿名(登录 ≠ 入会——GUEST 的 attributes 含 openid,本就能查)
65
+ if (reqCtx.identity.source === 'anonymous') {
66
+ const factory = ctx.services?.resolve?.('member.status') as MemberStatusFactory | undefined;
67
+ const status = await factory?.(reqCtx).catch(() => undefined);
68
+ const card = status ? memberGateCardOf(reqCtx.identity.userId, status) : undefined;
69
+ return { cards: card ? [card] : [], text: '请先登录后再查看碰出惊喜活动' };
70
+ }
71
+ const q = toMallQueryContext(reqCtx);
72
+
73
+ const bumpInService = await resolveAlipayBumpInService(ctx);
74
+ if (!bumpInService) return { cards: [], text: '碰出惊喜活动能力未装配,请联系运营配置凭证' };
75
+
76
+ const page = await bumpInService.listActivities(q, {});
77
+ const detail = page.items[0] ?? null;
78
+ if (!detail) return { cards: [], text: '未找到碰出惊喜活动,请确认活动方案 ID 配置是否正确' };
79
+
80
+ const cardData = toBumpInCardData(detail as PromotionActivityDetail, 'detail');
81
+ return {
82
+ cards: [{ cardType: 'promotion-bumpin-activity', data: cardData }],
83
+ text: `已找到碰出惊喜活动:${detail.title}`,
84
+ };
85
+ },
86
+ };
87
+ }
@@ -0,0 +1,79 @@
1
+ import type { ServerContext, ServerModule, PreToolDef } from '@tbox.cn/app-sdk/server';
2
+ import { definePreTool, loadModuleSkills } from '@tbox.cn/app-sdk/server';
3
+ import bumpInActivityMeta from './cards/bumpin-activity/meta';
4
+ import { createBumpInTools } from './tools';
5
+ import { alipayBumpInAuthStrategy } from './integrations/alipay/client';
6
+ import { createAlipayActivityHandler } from './handler';
7
+
8
+ export { resolveAlipayBumpInService, readAlipayBumpInConfig, configureAlipayBumpIn } from './ports';
9
+ export type { AlipayBumpInFileConfig } from './ports';
10
+ export { createBumpInTools, toBumpInCardData, parseAlipayRichText } from './tools';
11
+ export { createAlipayActivityHandler } from './handler';
12
+ export { AlipayBumpInService } from './integrations/alipay/adapter';
13
+ export { alipayBumpInAuthStrategy } from './integrations/alipay/client';
14
+ export { default as bumpInActivityMeta } from './cards/bumpin-activity/meta';
15
+ export type { AlipayActivityBumpInCardData } from './cards/bumpin-activity/meta';
16
+
17
+ /** 模块级 ServerContext 引用(register 期赋值,工具 execute 内读取) */
18
+ let serverCtx: ServerContext | undefined;
19
+ const getCtx = (): ServerContext => {
20
+ if (!serverCtx) throw new Error('alipay-activity 模块未注册(ServerContext 未绑定)');
21
+ return serverCtx;
22
+ };
23
+
24
+ const tools = createBumpInTools(getCtx);
25
+
26
+ const cards = {
27
+ 'promotion-bumpin-activity': bumpInActivityMeta,
28
+ } as const;
29
+
30
+ /** 本地 skill(009 文件化:包内 skills/alipay-activity/;map 化回填声明式通道) */
31
+ const skills = Object.fromEntries(
32
+ (await loadModuleSkills('@tbox.cn/app-module-alipay-activity', import.meta.url)).map((s) => [s.name, s]),
33
+ );
34
+
35
+ /**
36
+ * 碰一碰活动静默前置工具:碰词族问句预执行 getBumpInActivity(零参数——userId/openId
37
+ * 从会话上下文自动推导,含匿名登录卡兜底)。
38
+ * - routing keywords:碰词族(碰一碰/碰一下/碰出惊喜/碰惊喜/惊喜活动/NFC)——窄品牌词,
39
+ * 与营销券词/政策词零交集;
40
+ * - silent:不发前端事件、不落 inputs.preTools,仅本轮 reminder 数据块注入;
41
+ * - 详情卡经 capture 入本轮候选池(碰词轮正文转述 + 引用卡 id 即出卡,无需模型再调工具);
42
+ * - 与 exact intent(碰出惊喜/碰一下/碰一碰三词直出)无冲突:意图命中轮零预执行。
43
+ */
44
+ const bumpInPreTool = definePreTool(tools.getBumpInActivity, {
45
+ routing: {
46
+ mode: 'keywords',
47
+ terms: ['碰一碰', '碰一下', '碰出惊喜', '碰惊喜', '惊喜活动', 'NFC'],
48
+ },
49
+ decide: ({ text }) =>
50
+ text && text.trim().length > 0
51
+ ? { decision: 'run', args: {} }
52
+ : { decision: 'skip', reason: '空文本' },
53
+ silent: true,
54
+ });
55
+
56
+ const preTools = {
57
+ 'getBumpInActivity': bumpInPreTool,
58
+ } satisfies Record<string, PreToolDef>;
59
+
60
+ export const serverModule = {
61
+ declaration: {
62
+ moduleId: 'alipay-activity',
63
+ },
64
+ cards,
65
+ skills,
66
+ preTools,
67
+ register(ctx: ServerContext): void {
68
+ serverCtx = ctx;
69
+ ctx.authStrategies.register(alipayBumpInAuthStrategy);
70
+ for (const tool of Object.values(tools)) {
71
+ ctx.tools.register(tool);
72
+ }
73
+ ctx.cards.registerMap(cards);
74
+ // 注册碰出惊喜意图 handler(intent-route 引擎依据 patterns 命中后分发)
75
+ ctx.handlers.register(createAlipayActivityHandler(ctx));
76
+ },
77
+ } satisfies ServerModule;
78
+
79
+ export default serverModule;
@@ -0,0 +1,210 @@
1
+ /**
2
+ * 支付宝「碰出惊喜」互动营销活动 adapter。
3
+ *
4
+ * 实现 PromotionActivityPort(listActivities / getActivityDetail)。
5
+ * 调用支付宝开放平台 IoT NSP PlayCenter 活动查询接口:
6
+ * alipay.commerce.iotnspplaycenter.activity.query
7
+ */
8
+ import type { AlipaySdk } from 'alipay-sdk';
9
+ import type {
10
+ ActivitySession,
11
+ PromotionActivity,
12
+ PromotionActivityCategoryRecord,
13
+ PromotionActivityDetail,
14
+ PromotionActivityPage,
15
+ PromotionActivityPort,
16
+ PromotionQueryContext,
17
+ } from '@tbox.cn/app-contracts-mall';
18
+
19
+ /** 真实 API 响应体中的优惠券条目(alipay-sdk camelcase:true 转换后) */
20
+ interface BumpInVoucher {
21
+ readonly prizeId: string;
22
+ readonly voucherName: string;
23
+ readonly voucherType: string;
24
+ readonly reductionAmount: string;
25
+ readonly thresholdAmountText: string;
26
+ readonly unit: string;
27
+ readonly merchantName: string;
28
+ readonly merchantLogo?: string;
29
+ readonly itemLogo?: string;
30
+ }
31
+
32
+ /** alipay.commerce.iotnspplaycenter.activity.query 响应体(alipay-sdk camelcase:true 转换后) */
33
+ interface BumpInActivityResponse {
34
+ readonly code: string;
35
+ readonly msg: string;
36
+ readonly subCode?: string;
37
+ readonly subMsg?: string;
38
+ readonly actSchemeId?: string;
39
+ readonly actStatus?: string;
40
+ readonly actType?: string;
41
+ readonly cardTitle?: string;
42
+ readonly mainTitle?: string;
43
+ readonly cardLogo?: string;
44
+ readonly mainPrizeImage?: string;
45
+ readonly activityRuleDetail?: string;
46
+ readonly gmtStart?: number;
47
+ readonly gmtExpired?: number;
48
+ readonly totalProgress?: string;
49
+ readonly currentProgress?: string;
50
+ readonly progressUnit?: string;
51
+ readonly voucherList?: readonly BumpInVoucher[];
52
+ }
53
+
54
+ /**
55
+ * 碰出惊喜活动状态权威词表(支付宝 IoT NSP):
56
+ * NOT_START 未开始 / INIT 初始化 / PROCESSING 进行中 / FINISH 已完成 / RECEIVED 已领奖(用户级终态)。
57
+ */
58
+ const ACT_STATUS_VALUES = new Set(['NOT_START', 'INIT', 'PROCESSING', 'FINISH', 'RECEIVED']);
59
+
60
+ /** 可参与态(其余:NOT_START 未开始 / FINISH·RECEIVED 终态) */
61
+ const ACTIVE_STATUSES = new Set(['INIT', 'PROCESSING']);
62
+
63
+ /**
64
+ * 状态归一:词表内原样透传;词表外非空值保守归 FINISH(不诱导参与);
65
+ * 缺省归 PROCESSING(code=10000 查询成功即活动在期)。
66
+ */
67
+ function normalizeActStatus(raw: string | undefined): string {
68
+ if (ACT_STATUS_VALUES.has(raw ?? '')) return raw as string;
69
+ return raw === undefined ? 'PROCESSING' : 'FINISH';
70
+ }
71
+
72
+ /** 毫秒时间戳转 ISO 字符串,无效值返回 undefined */
73
+ function msToIso(ms: number | undefined): string | undefined {
74
+ if (typeof ms !== 'number' || ms <= 0) return undefined;
75
+ return new Date(ms).toISOString();
76
+ }
77
+
78
+ function mapBumpInActivity(actSchemeId: string, raw: BumpInActivityResponse): PromotionActivity {
79
+ const offerRefs = (raw.voucherList ?? []).map((v) => `alipay:bumpin:prize:${v.prizeId}`);
80
+ return {
81
+ activityRef: `alipay:bumpin:${actSchemeId}`,
82
+ title: raw.cardTitle ?? '碰出惊喜',
83
+ subtitle: raw.mainTitle,
84
+ coverUrl: raw.mainPrizeImage ?? raw.cardLogo,
85
+ categoryId: 'bumpin',
86
+ registrationRequired: false,
87
+ startAt: msToIso(raw.gmtStart),
88
+ endAt: msToIso(raw.gmtExpired),
89
+ offerRefs,
90
+ // 联单判定唯一真源:actType=N_COUNT_TYPE(累计 N 笔解锁型);标题关键字判定已废弃
91
+ linkedOrder: raw.actType === 'N_COUNT_TYPE',
92
+ // 活动生命周期状态(归一后透传;tools 层据此驱动卡片状态化展示)
93
+ activityStatus: normalizeActStatus(raw.actStatus),
94
+ };
95
+ }
96
+
97
+ function mapBumpInActivityDetail(actSchemeId: string, raw: BumpInActivityResponse): PromotionActivityDetail {
98
+ const activity = mapBumpInActivity(actSchemeId, raw);
99
+ const activityStatus = normalizeActStatus(raw.actStatus);
100
+ const isActive = ACTIVE_STATUSES.has(activityStatus);
101
+ const progressText =
102
+ raw.totalProgress !== undefined
103
+ ? `目标:${raw.totalProgress}${raw.progressUnit ?? ''},已完成:${raw.currentProgress ?? '0'}${raw.progressUnit ?? ''}`
104
+ : undefined;
105
+
106
+ const voucherDescriptions = (raw.voucherList ?? []).map(
107
+ (v) => `${v.voucherName}(${v.merchantName},${v.thresholdAmountText})`,
108
+ );
109
+
110
+ const statusLine = isActive
111
+ ? '活动进行中,参与资格以支付宝实时校验为准'
112
+ : activityStatus === 'NOT_START'
113
+ ? '活动尚未开始'
114
+ : activityStatus === 'RECEIVED'
115
+ ? '活动已结束,奖励已领取'
116
+ : '活动已结束';
117
+
118
+ const conditions: string[] = [
119
+ statusLine,
120
+ ...(progressText ? [progressText] : []),
121
+ ];
122
+
123
+ const steps: Array<{ readonly title: string; readonly description?: string }> = [
124
+ { title: '碰一下支付', description: '使用支付宝「碰一下」功能完成支付即可参与活动' },
125
+ ...(voucherDescriptions.length > 0
126
+ ? [{ title: '奖励说明', description: `可得优惠券:${voucherDescriptions.join(';')}` }]
127
+ : []),
128
+ ];
129
+
130
+ return {
131
+ ...activity,
132
+ description: raw.activityRuleDetail,
133
+ sessions: [],
134
+ guide: {
135
+ conditions,
136
+ steps,
137
+ notice: raw.voucherList && raw.voucherList.length > 0 ? JSON.stringify(raw.voucherList) : undefined,
138
+ },
139
+ };
140
+ }
141
+
142
+ export class AlipayBumpInService implements PromotionActivityPort {
143
+ constructor(
144
+ private readonly sdk: AlipaySdk,
145
+ private readonly actSchemeId: string,
146
+ ) {}
147
+
148
+ async listActivities(
149
+ q: PromotionQueryContext,
150
+ _input: {
151
+ keyword?: string;
152
+ cursor?: string;
153
+ limit?: number;
154
+ categoryId?: string;
155
+ dataScope?: string;
156
+ registrationRequired?: boolean;
157
+ startsAfter?: string;
158
+ endsBefore?: string;
159
+ },
160
+ ): Promise<PromotionActivityPage> {
161
+ const detail = await this.getActivityDetail(q, `alipay:bumpin:${this.actSchemeId}`);
162
+ if (!detail) return { items: [], hasMore: false };
163
+ return { items: [detail], hasMore: false };
164
+ }
165
+
166
+ async getActivityDetail(
167
+ q: PromotionQueryContext,
168
+ activityRef: string,
169
+ ): Promise<PromotionActivityDetail | null> {
170
+ const actSchemeId = activityRef.replace('alipay:bumpin:', '');
171
+ if (!actSchemeId || actSchemeId === activityRef) return null;
172
+ if (actSchemeId !== this.actSchemeId) return null;
173
+
174
+ const credAttrs = q.requestContext.credentials?.attributes as Record<string, unknown> | undefined;
175
+ const alipayOpenId = typeof credAttrs?.['openid'] === 'string' ? credAttrs['openid'] : '';
176
+ const isAlipayUserId = alipayOpenId.startsWith('2088');
177
+ const bizContent = {
178
+ ...(isAlipayUserId ? { user_id: alipayOpenId } : { open_id: alipayOpenId }),
179
+ act_scheme_id: actSchemeId,
180
+ };
181
+ // appId 取 SDK 实际初始化值(凭证通道三源:离散 env > v2 文件 > env JSON 兜底——
182
+ // 验签类排障必须记录实际生效的 appId,否则无法判断签名密钥与平台登记是否匹配)
183
+ console.info('[AlipayBumpIn] exec request', {
184
+ appId: this.sdk.config.appId,
185
+ method: 'alipay.commerce.iotnspplaycenter.activity.query',
186
+ bizContent,
187
+ });
188
+
189
+ const result = await this.sdk.exec('alipay.commerce.iotnspplaycenter.activity.query', { bizContent });
190
+ const raw = result as BumpInActivityResponse | undefined;
191
+ console.info('[AlipayBumpIn] exec response', { appId: this.sdk.config.appId, code: raw?.code, msg: raw?.msg, subCode: raw?.subCode, raw });
192
+
193
+ if (!raw || raw.code !== '10000') return null;
194
+
195
+ const detail = mapBumpInActivityDetail(actSchemeId, raw);
196
+ console.info('[AlipayBumpIn] mapped detail', detail);
197
+ return detail;
198
+ }
199
+
200
+ async listActivitySessions(
201
+ _q: PromotionQueryContext,
202
+ _activityRef: string,
203
+ ): Promise<readonly ActivitySession[]> {
204
+ return [];
205
+ }
206
+
207
+ async listActivityCategories(): Promise<readonly PromotionActivityCategoryRecord[]> {
208
+ return [{ categoryId: 'bumpin', name: '碰出惊喜' }];
209
+ }
210
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * 支付宝开放平台 SDK 客户端工厂与认证策略声明。
3
+ *
4
+ * alipayBumpInAuthStrategy:占位认证策略,仅用于向 ctx.authStrategies 注册 credentialType,
5
+ * 让 SDK integrations registry 创建 transport 时不抛"未知认证类型"。
6
+ * 实际请求由 AlipaySdk 自行签名,SDK transport 不会被调用。
7
+ *
8
+ * 凭证通道(离散 env > v2 文件 > env JSON 兜底):
9
+ * 离散 env——MINI_APP_ID / MINI_APP_PRIVATE_KEY / MINI_APP_ALIPAY_PUB_KEY 三键齐备时优先
10
+ * (缺任一则整体不命中,防半套凭证与文件通道错配 key 对);
11
+ * v2 文件——`configureAlipayBumpIn` 注入的 bumpin.json 同目录 `credentials/<ref stem>.json`
12
+ * (ref = `secret://alipay-bumpin` 直引 stem);
13
+ * env JSON 兜底——`ALIPAY_BUMPIN` 键(存量派生形态保留,与素材文件名 glob 派生一致)。
14
+ * 格式:{ "value": { "appId", "privateKey", "alipayPublicKey" } };type 统一 = `alipay-open-v1`。
15
+ *
16
+ * gateway(endpoint)与 actSchemeId 由 provider instance config 注入,不从凭证或代码硬编码读取:
17
+ * gateway 预发: https://openapi-sandbox.dl.alipaydev.com/gateway.do
18
+ * gateway 生产: https://openapi.alipay.com/gateway.do
19
+ */
20
+ import { existsSync, readFileSync } from 'node:fs';
21
+ import path from 'node:path';
22
+ import { AlipaySdk } from 'alipay-sdk';
23
+ import type { ProviderAuthStrategy } from '@tbox.cn/app-sdk/server';
24
+ import type { AlipayBumpInProviderConfig } from './provider';
25
+
26
+ /** 凭证 JSON 文件的 value 结构 */
27
+ interface AlipayCredentialValue {
28
+ readonly appId: string;
29
+ readonly privateKey: string;
30
+ readonly alipayPublicKey: string;
31
+ }
32
+
33
+ /** 从 credentialRef + bumpin.json 同目录文件解析凭证(v2 文件源优先) */
34
+ function parseAlipayCredentialFromFile(configPath: string | undefined): AlipayCredentialValue | null {
35
+ if (!configPath) return null;
36
+ const dir = path.dirname(configPath);
37
+ const file = path.join(dir, 'credentials', 'alipay-bumpin.json');
38
+ if (!existsSync(file)) return null;
39
+ try {
40
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { value?: unknown };
41
+ const value = parsed.value;
42
+ if (
43
+ value &&
44
+ typeof value === 'object' &&
45
+ typeof (value as Record<string, unknown>).appId === 'string' &&
46
+ typeof (value as Record<string, unknown>).privateKey === 'string' &&
47
+ typeof (value as Record<string, unknown>).alipayPublicKey === 'string'
48
+ ) {
49
+ return value as AlipayCredentialValue;
50
+ }
51
+ } catch {
52
+ // 解析失败视为凭证缺失
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /** 从离散环境变量解析凭证(最高优先级:三键齐备才命中,缺失任一则整体不命中) */
58
+ function parseAlipayCredentialFromDiscreteEnv(): AlipayCredentialValue | null {
59
+ const appId = process.env.MINI_APP_ID;
60
+ const privateKey = process.env.MINI_APP_PRIVATE_KEY;
61
+ const alipayPublicKey = process.env.MINI_APP_ALIPAY_PUB_KEY;
62
+ if (!appId || !privateKey || !alipayPublicKey) return null;
63
+ return { appId, privateKey, alipayPublicKey };
64
+ }
65
+
66
+ /** 从环境变量 ALIPAY_BUMPIN 解析凭证(v2 env 兜底),解析失败返回 null */
67
+ function parseAlipayCredentialFromEnv(): AlipayCredentialValue | null {
68
+ const raw = process.env.ALIPAY_BUMPIN;
69
+ if (!raw) return null;
70
+ try {
71
+ const parsed = JSON.parse(raw) as { value?: unknown };
72
+ const value = parsed.value;
73
+ if (
74
+ value &&
75
+ typeof value === 'object' &&
76
+ typeof (value as Record<string, unknown>).appId === 'string' &&
77
+ typeof (value as Record<string, unknown>).privateKey === 'string' &&
78
+ typeof (value as Record<string, unknown>).alipayPublicKey === 'string'
79
+ ) {
80
+ return value as AlipayCredentialValue;
81
+ }
82
+ } catch {
83
+ // 解析失败视为凭证缺失
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * 创建 AlipaySdk 实例。
90
+ * 离散 env 优先,文件通道次之,env JSON 兜底;凭证缺失或占位时返回 null,调用方降级。
91
+ */
92
+ export function createAlipaySdkClient(config: AlipayBumpInProviderConfig, configPath?: string): AlipaySdk | null {
93
+ const credential =
94
+ parseAlipayCredentialFromDiscreteEnv() ??
95
+ parseAlipayCredentialFromFile(configPath) ??
96
+ parseAlipayCredentialFromEnv();
97
+ if (!credential) return null;
98
+
99
+ const { appId, privateKey, alipayPublicKey } = credential;
100
+ if (
101
+ appId.startsWith('PLACEHOLDER') ||
102
+ privateKey.startsWith('PLACEHOLDER') ||
103
+ alipayPublicKey.startsWith('PLACEHOLDER')
104
+ ) {
105
+ return null;
106
+ }
107
+
108
+ return new AlipaySdk({
109
+ appId,
110
+ privateKey,
111
+ alipayPublicKey,
112
+ keyType: 'PKCS8',
113
+ signType: 'RSA2',
114
+ camelcase: true,
115
+ gateway: config.gateway,
116
+ });
117
+ }
118
+
119
+ /**
120
+ * 占位认证策略(credentialType = alipay-open-v1,与凭据文件 .type 统一键)。
121
+ * 仅用于向 ctx.authStrategies 注册,让 SDK integrations registry 在创建 transport 时
122
+ * 不抛"未知认证类型"。alipay-bumpin 的实际签名由 AlipaySdk 自行完成,SDK transport 不会被调用。
123
+ */
124
+ export const alipayBumpInAuthStrategy: ProviderAuthStrategy = {
125
+ credentialType: 'alipay-open-v1',
126
+ apply: () => ({}),
127
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 支付宝「碰出惊喜」SDK client 配置形状。
3
+ * 仅在本模块内使用,不上升到 contracts-mall(config 真源 = 应用 config/bumpin.json)。
4
+ */
5
+
6
+ export interface AlipayBumpInProviderConfig {
7
+ readonly gateway: string;
8
+ readonly actSchemeId: string;
9
+ }