@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.
- package/AGENTS.md +16 -0
- package/LICENSE +21 -0
- package/README.md +48 -0
- package/dist/bumpin-VKHLYCKG.css +527 -0
- package/dist/chunk-RM7IUA3M.js +634 -0
- package/dist/client/index.d.ts +11 -0
- package/dist/client/index.js +235 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +26 -0
- package/dist/linked-card-background-MVGUOJ7J.jpg +0 -0
- package/dist/server/index.d.ts +224 -0
- package/dist/server/index.js +28 -0
- package/package.json +69 -0
- package/schemas/credentials/alipay-open-v1.json +12 -0
- package/skills/alipay-activity/SKILL.md +59 -0
- package/src/client/assets/linked-card-background.jpg +0 -0
- package/src/client/assets.d.ts +10 -0
- package/src/client/cards/bumpin-activity/index.tsx +213 -0
- package/src/client/components/ImageWithFallback.tsx +37 -0
- package/src/client/index.ts +18 -0
- package/src/client/styles/bumpin.css +527 -0
- package/src/client/utils/sanitize-activity-html.ts +40 -0
- package/src/index.ts +1 -0
- package/src/server/cards/bumpin-activity/meta.ts +44 -0
- package/src/server/cards/bumpin-activity/samples.ts +164 -0
- package/src/server/handler.ts +87 -0
- package/src/server/index.ts +79 -0
- package/src/server/integrations/alipay/adapter.ts +210 -0
- package/src/server/integrations/alipay/client.ts +127 -0
- package/src/server/integrations/alipay/provider.ts +9 -0
- package/src/server/ports.ts +68 -0
- package/src/server/tools.ts +212 -0
- package/tbox.module.json +39 -0
- package/tests/adapter.test.ts +178 -0
- package/tests/bumpin-card-status.test.tsx +80 -0
- package/tests/client.test.ts +93 -0
- package/tests/intent-routing.test.ts +118 -0
- package/tests/ports.test.ts +160 -0
- package/tests/pretool-routing.test.ts +37 -0
- package/tests/samples.test.ts +29 -0
- package/tests/skill.test.ts +39 -0
- package/tests/tools.test.ts +193 -0
- package/tsconfig.json +8 -0
- package/tsup.config.ts +36 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 支付宝「碰出惊喜」Port 解析(配置面直读)。
|
|
3
|
+
* 配置真源 config/bumpin.json(chat/llm_provider 同族 fail-soft 配置面;无 provider 包供给、
|
|
4
|
+
* 无 transport/credential 语义——credentialRef 仅保留声明位,运行时零消费):
|
|
5
|
+
* gateway → AlipaySdk endpoint(预发/生产切换点)
|
|
6
|
+
* actSchemeId → 活动方案 ID(运营配置,无需发版)
|
|
7
|
+
* linkedCardBackgroundUrl → 联单活动全幅背景图(banner 投影消费,前端可 fallback 模块内置图)
|
|
8
|
+
* 路径由应用 entry 注入(configureAlipayBumpIn;沿 serverCtx 模块顶层单例先例——被 tsup 内联
|
|
9
|
+
* 的模块零路径魔法)。未注入/缺文件/缺字段 → null,工具层静默降级。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
12
|
+
import type { ServerContext } from '@tbox.cn/app-sdk/server';
|
|
13
|
+
import { expandEnvVars } from '@tbox.cn/app-sdk/server';
|
|
14
|
+
import { AlipayBumpInService } from './integrations/alipay/adapter';
|
|
15
|
+
import { createAlipaySdkClient } from './integrations/alipay/client';
|
|
16
|
+
|
|
17
|
+
/** bumpin.json 文件形状(模板 ENV.md 同步记载) */
|
|
18
|
+
export interface AlipayBumpInFileConfig {
|
|
19
|
+
readonly gateway: string;
|
|
20
|
+
readonly actSchemeId: string;
|
|
21
|
+
readonly linkedCardBackgroundUrl?: string;
|
|
22
|
+
readonly credentialRef?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 模块顶层单例:配置文件路径(entry 注入;沿 serverCtx 先例) */
|
|
26
|
+
let bumpinConfigPath: string | undefined;
|
|
27
|
+
|
|
28
|
+
/** 应用 entry 注入 bumpin 配置路径(CONFIG_DIR 锚定;模板 index.ts / 测试均可调用) */
|
|
29
|
+
export function configureAlipayBumpIn(configPath: string): void {
|
|
30
|
+
bumpinConfigPath = configPath;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 读取 bumpin 配置(fail-soft:未注入/缺文件/解析失败/缺必填字段 → null + warn) */
|
|
34
|
+
export function readAlipayBumpInConfig(ctx?: ServerContext): AlipayBumpInFileConfig | null {
|
|
35
|
+
if (!bumpinConfigPath || !existsSync(bumpinConfigPath)) return null;
|
|
36
|
+
let raw: Partial<AlipayBumpInFileConfig>;
|
|
37
|
+
try {
|
|
38
|
+
raw = JSON.parse(expandEnvVars(readFileSync(bumpinConfigPath, 'utf8'), process.env, bumpinConfigPath)) as Partial<AlipayBumpInFileConfig>;
|
|
39
|
+
} catch (e) {
|
|
40
|
+
ctx?.logger?.warn(`bumpin.json 解析失败(${(e as Error).message})`);
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const gateway = typeof raw.gateway === 'string' && raw.gateway ? raw.gateway : '';
|
|
44
|
+
const actSchemeId = typeof raw.actSchemeId === 'string' && raw.actSchemeId ? raw.actSchemeId : '';
|
|
45
|
+
if (!gateway || !actSchemeId) {
|
|
46
|
+
ctx?.logger?.warn('bumpin.json 已注入但 gateway / actSchemeId 缺失');
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
const linkedCardBackgroundUrl =
|
|
50
|
+
typeof raw.linkedCardBackgroundUrl === 'string' && raw.linkedCardBackgroundUrl
|
|
51
|
+
? raw.linkedCardBackgroundUrl
|
|
52
|
+
: undefined;
|
|
53
|
+
const credentialRef =
|
|
54
|
+
typeof raw.credentialRef === 'string' && raw.credentialRef ? raw.credentialRef : undefined;
|
|
55
|
+
return {
|
|
56
|
+
gateway,
|
|
57
|
+
actSchemeId,
|
|
58
|
+
...(linkedCardBackgroundUrl ? { linkedCardBackgroundUrl } : {}),
|
|
59
|
+
...(credentialRef ? { credentialRef } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function resolveAlipayBumpInService(ctx: ServerContext): Promise<AlipayBumpInService | null> {
|
|
64
|
+
const cfg = readAlipayBumpInConfig(ctx);
|
|
65
|
+
if (!cfg) return null;
|
|
66
|
+
const sdk = createAlipaySdkClient({ gateway: cfg.gateway, actSchemeId: cfg.actSchemeId }, bumpinConfigPath);
|
|
67
|
+
return sdk ? new AlipayBumpInService(sdk, cfg.actSchemeId) : null;
|
|
68
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 支付宝「碰出惊喜」工具集。
|
|
3
|
+
* getBumpInActivity:AI 对话工具,用户主动询问活动详情。
|
|
4
|
+
* getBumpInActivityBanner:首页 Banner 数据拉取,无需用户意图触发。
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import type { ServerContext, ToolExecContextLike } from '@tbox.cn/app-sdk/server';
|
|
8
|
+
import { createTool, withCardEmissionHint, requireToolRequestContext } from '@tbox.cn/app-sdk/server';
|
|
9
|
+
import { memberGateCardOf, toMallQueryContext } from '@tbox.cn/app-contracts-mall';
|
|
10
|
+
import type {
|
|
11
|
+
MemberStatusFactory,
|
|
12
|
+
PromotionActivityDetail,
|
|
13
|
+
PromotionBumpInActivityCardData,
|
|
14
|
+
} from '@tbox.cn/app-contracts-mall';
|
|
15
|
+
import { resolveAlipayBumpInService } from './ports';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 卡面 actStatus 收口(契约 z.enum 五值):detail.activityStatus 词表内透传
|
|
19
|
+
* (adapter 已归一);词表外/缺省按 PROCESSING 兜底——无法判定时按进行中展示,
|
|
20
|
+
* 终态必须显式下发,不凭缺省推断。
|
|
21
|
+
*/
|
|
22
|
+
const ACT_STATUS_VALUES = new Set(['NOT_START', 'INIT', 'PROCESSING', 'FINISH', 'RECEIVED']);
|
|
23
|
+
|
|
24
|
+
function toCardActStatus(raw: string | undefined): PromotionBumpInActivityCardData['actStatus'] {
|
|
25
|
+
return ACT_STATUS_VALUES.has(raw ?? '')
|
|
26
|
+
? (raw as PromotionBumpInActivityCardData['actStatus'])
|
|
27
|
+
: 'PROCESSING';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 解析支付宝自定义富文本格式 #{{"color":"#E84749","customStyle":true,"text":"2"}}# → 纯文本 "2"
|
|
32
|
+
*/
|
|
33
|
+
export function parseAlipayRichText(text: string | undefined): string {
|
|
34
|
+
if (!text) return '';
|
|
35
|
+
return text.replace(/#\{\{[^}]*"text":"([^"]*)"[^}]*\}\}#/g, '$1');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 将 PromotionActivityDetail 中 bumpIn 特有字段格式化为 card data。
|
|
40
|
+
* guide.conditions[1] 存 progressText,guide.notice 存序列化的 voucherList。
|
|
41
|
+
* @param backgroundUrl 可选,联单活动全幅背景图 URL;来自部署配置 linkedCardBackgroundUrl,不传时前端 fallback 到模块内置图
|
|
42
|
+
*/
|
|
43
|
+
// 返回类型锚定契约卡数据(banner 线缆唯一编译期检查:字段形状/枚举字面量在此收口;
|
|
44
|
+
// 无标注时三元字面量会被推断拓宽为 string,progressStyle 即因此漂移——由 mall 模板守卫首战命中)
|
|
45
|
+
export function toBumpInCardData(
|
|
46
|
+
detail: PromotionActivityDetail,
|
|
47
|
+
mode: 'detail' | 'banner',
|
|
48
|
+
backgroundUrl?: string,
|
|
49
|
+
): PromotionBumpInActivityCardData {
|
|
50
|
+
const progressText = detail.guide?.conditions[1] ?? '';
|
|
51
|
+
const [, progressTotal = '', progressUnit = '', progressCurrent = ''] =
|
|
52
|
+
progressText.match(/目标:(.+?)(.+?),已完成:(.+?)\2/) ??
|
|
53
|
+
progressText.match(/目标:(\S+?)(\S+),已完成:(\S+)/) ?? ['', '', '', ''];
|
|
54
|
+
|
|
55
|
+
let vouchers: Array<{
|
|
56
|
+
prizeId: string;
|
|
57
|
+
voucherName: string;
|
|
58
|
+
voucherType: string;
|
|
59
|
+
reductionAmount: string;
|
|
60
|
+
thresholdAmountText: string;
|
|
61
|
+
unit: string;
|
|
62
|
+
merchantName: string;
|
|
63
|
+
merchantLogo?: string;
|
|
64
|
+
itemLogo?: string;
|
|
65
|
+
}> = [];
|
|
66
|
+
|
|
67
|
+
if (detail.guide?.notice) {
|
|
68
|
+
try {
|
|
69
|
+
const raw = JSON.parse(detail.guide.notice) as Array<Record<string, unknown>>;
|
|
70
|
+
vouchers = raw.map((v) => ({
|
|
71
|
+
prizeId: String(v['prizeId'] ?? v['prize_id'] ?? ''),
|
|
72
|
+
voucherName: String(v['voucherName'] ?? v['voucher_name'] ?? ''),
|
|
73
|
+
voucherType: String(v['voucherType'] ?? v['voucher_type'] ?? ''),
|
|
74
|
+
reductionAmount: String(v['reductionAmount'] ?? v['reduction_amount'] ?? ''),
|
|
75
|
+
thresholdAmountText: String(v['thresholdAmountText'] ?? v['threshold_amount_text'] ?? ''),
|
|
76
|
+
unit: String(v['unit'] ?? ''),
|
|
77
|
+
merchantName: String(v['merchantName'] ?? v['merchant_name'] ?? ''),
|
|
78
|
+
merchantLogo:
|
|
79
|
+
v['merchantLogo'] != null
|
|
80
|
+
? String(v['merchantLogo'])
|
|
81
|
+
: v['merchant_logo'] != null
|
|
82
|
+
? String(v['merchant_logo'])
|
|
83
|
+
: undefined,
|
|
84
|
+
itemLogo:
|
|
85
|
+
v['itemLogo'] != null
|
|
86
|
+
? String(v['itemLogo'])
|
|
87
|
+
: v['item_logo'] != null
|
|
88
|
+
? String(v['item_logo'])
|
|
89
|
+
: undefined,
|
|
90
|
+
}));
|
|
91
|
+
} catch {
|
|
92
|
+
// notice 解析失败时降级为空
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const mainTitle = parseAlipayRichText(detail.subtitle);
|
|
97
|
+
|
|
98
|
+
// 联单活动识别:唯一真源 = detail.linkedOrder(adapter 由 raw actType=N_COUNT_TYPE 映射;
|
|
99
|
+
// 标题/副标题关键字判定已废弃——「碰出惊喜」类标题不含关键字导致首页联单进度漏展示)
|
|
100
|
+
const isLinkedActivity = detail.linkedOrder === true;
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
activityRef: detail.activityRef,
|
|
104
|
+
title: detail.title,
|
|
105
|
+
mainTitle: mainTitle || detail.title,
|
|
106
|
+
coverUrl: isLinkedActivity ? undefined : detail.coverUrl,
|
|
107
|
+
tagLabel: isLinkedActivity ? '碰一下联单' : undefined,
|
|
108
|
+
progressStyle: isLinkedActivity ? 'steps' : 'bar',
|
|
109
|
+
backgroundUrl: isLinkedActivity ? (backgroundUrl || undefined) : undefined,
|
|
110
|
+
actStatus: toCardActStatus(detail.activityStatus),
|
|
111
|
+
totalProgress: progressTotal || undefined,
|
|
112
|
+
currentProgress: progressCurrent || undefined,
|
|
113
|
+
progressUnit: progressUnit || undefined,
|
|
114
|
+
startAtText: detail.startAt ? new Date(detail.startAt).toLocaleDateString('zh-CN') : undefined,
|
|
115
|
+
endAtText: detail.endAt ? new Date(detail.endAt).toLocaleDateString('zh-CN') : undefined,
|
|
116
|
+
description: detail.description,
|
|
117
|
+
vouchers,
|
|
118
|
+
steps: isLinkedActivity ? (detail.guide?.steps as Array<{ title: string; description?: string }> | undefined) : undefined,
|
|
119
|
+
mode,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function createBumpInTools(getCtx: () => ServerContext) {
|
|
124
|
+
const getBumpInActivity = createTool({
|
|
125
|
+
id: 'getBumpInActivity',
|
|
126
|
+
description:
|
|
127
|
+
'查询我的碰出惊喜活动详情(碰出惊喜、碰一下、我的惊喜活动、支付宝互动营销活动)。返回活动标题、奖励池、完成进度与参与指引。',
|
|
128
|
+
inputSchema: z.object({}),
|
|
129
|
+
execute: async (_args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
|
|
130
|
+
const ctx = getCtx();
|
|
131
|
+
const reqCtx = requireToolRequestContext(execCtx, 'getBumpInActivity');
|
|
132
|
+
// 登录轴门禁:只拦匿名(登录 ≠ 入会——GUEST 的 attributes 含 openid,本就能查,不得误伤)
|
|
133
|
+
if (reqCtx.identity.source === 'anonymous') {
|
|
134
|
+
const factory = ctx.services?.resolve?.('member.status') as MemberStatusFactory | undefined;
|
|
135
|
+
const status = await factory?.(reqCtx).catch(() => undefined);
|
|
136
|
+
const card = status ? memberGateCardOf(reqCtx.identity.userId, status) : undefined;
|
|
137
|
+
return {
|
|
138
|
+
found: false as const,
|
|
139
|
+
noResultsReason: '请先登录后再查看碰出惊喜活动',
|
|
140
|
+
...(card ? { cards: [card] } : {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const service = await resolveAlipayBumpInService(ctx);
|
|
144
|
+
if (!service) return { supported: false, message: '碰出惊喜活动能力未装配,请联系运营配置凭证' };
|
|
145
|
+
|
|
146
|
+
const q = toMallQueryContext(reqCtx);
|
|
147
|
+
|
|
148
|
+
const page = await service.listActivities(q, {});
|
|
149
|
+
const detail = page.items[0] ?? null;
|
|
150
|
+
if (!detail) return { supported: true, message: '未找到碰出惊喜活动,请确认活动方案 ID 配置是否正确' };
|
|
151
|
+
|
|
152
|
+
const cardData = toBumpInCardData(detail as PromotionActivityDetail, 'detail');
|
|
153
|
+
return {
|
|
154
|
+
...cardData,
|
|
155
|
+
// note 契约(W7):标题 + 进度要点(cardData.totalProgress/currentProgress 由 guide 解析)
|
|
156
|
+
cards: [
|
|
157
|
+
{
|
|
158
|
+
cardType: 'promotion-bumpin-activity',
|
|
159
|
+
data: cardData,
|
|
160
|
+
note: `${detail.title}${
|
|
161
|
+
cardData.currentProgress ? ` · 已完成 ${cardData.currentProgress}/${cardData.totalProgress ?? '?'}` : ''
|
|
162
|
+
}`,
|
|
163
|
+
},
|
|
164
|
+
],
|
|
165
|
+
};
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const getBumpInActivityBanner = createTool({
|
|
170
|
+
id: 'getBumpInActivityBanner',
|
|
171
|
+
description:
|
|
172
|
+
'获取碰出惊喜首页 Banner 展示数据(供首页直接拉取,无需用户主动询问)。返回活动主图、奖励概览;mode=banner 仅展示顶部概览不展开列表。',
|
|
173
|
+
inputSchema: z.object({}),
|
|
174
|
+
execute: async (_args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
|
|
175
|
+
const ctx = getCtx();
|
|
176
|
+
const reqCtx = requireToolRequestContext(execCtx, 'getBumpInActivityBanner');
|
|
177
|
+
// 登录轴门禁:只拦匿名(Banner 数据同样属人——用户头像/进度个性化)
|
|
178
|
+
if (reqCtx.identity.source === 'anonymous') {
|
|
179
|
+
const factory = ctx.services?.resolve?.('member.status') as MemberStatusFactory | undefined;
|
|
180
|
+
const status = await factory?.(reqCtx).catch(() => undefined);
|
|
181
|
+
const card = status ? memberGateCardOf(reqCtx.identity.userId, status) : undefined;
|
|
182
|
+
return {
|
|
183
|
+
supported: false as const,
|
|
184
|
+
banner: null,
|
|
185
|
+
noResultsReason: '请先登录后再查看碰出惊喜活动',
|
|
186
|
+
...(card ? { cards: [card] } : {}),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
const service = await resolveAlipayBumpInService(ctx);
|
|
190
|
+
if (!service) return { supported: false, banner: null };
|
|
191
|
+
|
|
192
|
+
const q = toMallQueryContext(reqCtx);
|
|
193
|
+
|
|
194
|
+
const page = await service.listActivities(q, {});
|
|
195
|
+
const detail = page.items[0] ?? null;
|
|
196
|
+
if (!detail) return { supported: true, banner: null };
|
|
197
|
+
|
|
198
|
+
const cardData = toBumpInCardData(detail as PromotionActivityDetail, 'banner');
|
|
199
|
+
return {
|
|
200
|
+
supported: true,
|
|
201
|
+
banner: cardData,
|
|
202
|
+
cards: [{ cardType: 'promotion-bumpin-activity', data: cardData, note: `${detail.title} Banner` }],
|
|
203
|
+
};
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// W2(2026-09-01):出卡工具创建点单点 wrap——参与动作在卡上,getBumpInActivity 带 actions 句
|
|
208
|
+
return {
|
|
209
|
+
getBumpInActivity: withCardEmissionHint(getBumpInActivity, { actions: true }),
|
|
210
|
+
getBumpInActivityBanner: withCardEmissionHint(getBumpInActivityBanner),
|
|
211
|
+
};
|
|
212
|
+
}
|
package/tbox.module.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"name": "module-alipay-activity",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"kind": "business",
|
|
6
|
+
"risk": {
|
|
7
|
+
"level": "low",
|
|
8
|
+
"writeBoundary": "source"
|
|
9
|
+
},
|
|
10
|
+
"distribution": {
|
|
11
|
+
"defaultMode": "codegen"
|
|
12
|
+
},
|
|
13
|
+
"contributes": {
|
|
14
|
+
"handlers": ["alipay-activity"],
|
|
15
|
+
"tools": [
|
|
16
|
+
"getBumpInActivity",
|
|
17
|
+
"getBumpInActivityBanner"
|
|
18
|
+
],
|
|
19
|
+
"cards": [
|
|
20
|
+
{
|
|
21
|
+
"cardType": "promotion-bumpin-activity",
|
|
22
|
+
"schemaVersion": 1
|
|
23
|
+
}
|
|
24
|
+
],
|
|
25
|
+
"routes": [],
|
|
26
|
+
"pages": [],
|
|
27
|
+
"tabs": [],
|
|
28
|
+
"actions": []
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"modules": [
|
|
32
|
+
{
|
|
33
|
+
"id": "contracts-mall",
|
|
34
|
+
"required": true
|
|
35
|
+
}
|
|
36
|
+
]
|
|
37
|
+
},
|
|
38
|
+
"env": []
|
|
39
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import type { AlipaySdk } from 'alipay-sdk';
|
|
2
|
+
import type { PromotionQueryContext } from '@tbox.cn/app-contracts-mall';
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { AlipayBumpInService } from '../src/server/integrations/alipay/adapter.js';
|
|
5
|
+
import { toBumpInCardData } from '../src/server/tools.js';
|
|
6
|
+
|
|
7
|
+
const QUERY_CONTEXT = {
|
|
8
|
+
scope: { miniAppId: 'mall-app', mallId: 'mall-001' },
|
|
9
|
+
requestContext: {
|
|
10
|
+
identity: { userId: '2088123456789012', source: 'external' },
|
|
11
|
+
credentials: {
|
|
12
|
+
token: '',
|
|
13
|
+
provider: 'alipay-iap',
|
|
14
|
+
attributes: { openid: '2088123456789012' },
|
|
15
|
+
},
|
|
16
|
+
attributes: { mall: { miniAppId: 'mall-app', mallId: 'mall-001' } },
|
|
17
|
+
},
|
|
18
|
+
} satisfies PromotionQueryContext;
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
vi.restoreAllMocks();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe('AlipayBumpInService 奖励投影', () => {
|
|
25
|
+
it('将 activity.query 的真实 voucherList 逐项带入详情卡奖励', async () => {
|
|
26
|
+
vi.spyOn(console, 'info').mockImplementation(() => {});
|
|
27
|
+
const exec = vi.fn().mockResolvedValue({
|
|
28
|
+
code: '10000',
|
|
29
|
+
msg: 'Success',
|
|
30
|
+
actSchemeId: 'AS_REAL_REWARD',
|
|
31
|
+
actStatus: 'PROCESSING',
|
|
32
|
+
cardTitle: '碰一下联单赢好礼',
|
|
33
|
+
mainTitle: '累计支付 5 笔得惊喜券',
|
|
34
|
+
totalProgress: '5',
|
|
35
|
+
currentProgress: '2',
|
|
36
|
+
progressUnit: '笔',
|
|
37
|
+
voucherList: [
|
|
38
|
+
{
|
|
39
|
+
prizeId: 'PZ_REAL_001',
|
|
40
|
+
voucherName: '品牌通用满减券',
|
|
41
|
+
voucherType: 'ITEM_REDUCTION_AMOUNT',
|
|
42
|
+
reductionAmount: '20',
|
|
43
|
+
thresholdAmountText: '满100元可用',
|
|
44
|
+
unit: '元',
|
|
45
|
+
merchantName: '参与活动商户',
|
|
46
|
+
merchantLogo: 'https://img.example/merchant.png',
|
|
47
|
+
itemLogo: 'https://img.example/reward.png',
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
});
|
|
51
|
+
const service = new AlipayBumpInService({ config: { appId: 'mock-app-id' }, exec } as unknown as AlipaySdk, 'AS_REAL_REWARD');
|
|
52
|
+
|
|
53
|
+
const detail = await service.getActivityDetail(QUERY_CONTEXT, 'alipay:bumpin:AS_REAL_REWARD');
|
|
54
|
+
expect(exec).toHaveBeenCalledWith(
|
|
55
|
+
'alipay.commerce.iotnspplaycenter.activity.query',
|
|
56
|
+
{ bizContent: { user_id: '2088123456789012', act_scheme_id: 'AS_REAL_REWARD' } },
|
|
57
|
+
);
|
|
58
|
+
expect(detail?.offerRefs).toEqual(['alipay:bumpin:prize:PZ_REAL_001']);
|
|
59
|
+
|
|
60
|
+
const card = toBumpInCardData(detail!, 'detail');
|
|
61
|
+
expect(card.vouchers).toEqual([
|
|
62
|
+
{
|
|
63
|
+
prizeId: 'PZ_REAL_001',
|
|
64
|
+
voucherName: '品牌通用满减券',
|
|
65
|
+
voucherType: 'ITEM_REDUCTION_AMOUNT',
|
|
66
|
+
reductionAmount: '20',
|
|
67
|
+
thresholdAmountText: '满100元可用',
|
|
68
|
+
unit: '元',
|
|
69
|
+
merchantName: '参与活动商户',
|
|
70
|
+
merchantLogo: 'https://img.example/merchant.png',
|
|
71
|
+
itemLogo: 'https://img.example/reward.png',
|
|
72
|
+
},
|
|
73
|
+
]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('接口未返回 voucherList 时保持空奖励,不注入演示奖品', async () => {
|
|
77
|
+
vi.spyOn(console, 'info').mockImplementation(() => {});
|
|
78
|
+
const exec = vi.fn().mockResolvedValue({
|
|
79
|
+
code: '10000',
|
|
80
|
+
msg: 'Success',
|
|
81
|
+
actSchemeId: 'AS_NO_REWARD',
|
|
82
|
+
actStatus: 'PROCESSING',
|
|
83
|
+
cardTitle: '碰一下联单活动',
|
|
84
|
+
});
|
|
85
|
+
const service = new AlipayBumpInService({ config: { appId: 'mock-app-id' }, exec } as unknown as AlipaySdk, 'AS_NO_REWARD');
|
|
86
|
+
|
|
87
|
+
const detail = await service.getActivityDetail(QUERY_CONTEXT, 'alipay:bumpin:AS_NO_REWARD');
|
|
88
|
+
expect(toBumpInCardData(detail!, 'detail').vouchers).toEqual([]);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('actType=N_COUNT_TYPE → linkedOrder=true,标题无关键字也走 steps 联单形态', async () => {
|
|
92
|
+
vi.spyOn(console, 'info').mockImplementation(() => {});
|
|
93
|
+
const exec = vi.fn().mockResolvedValue({
|
|
94
|
+
code: '10000',
|
|
95
|
+
msg: 'Success',
|
|
96
|
+
actSchemeId: 'AS_LINKED_DEMO',
|
|
97
|
+
actType: 'N_COUNT_TYPE',
|
|
98
|
+
actStatus: 'PROCESSING',
|
|
99
|
+
cardTitle: 'XX广场 | 碰出惊喜',
|
|
100
|
+
mainTitle: '碰一下支付#{{"color":"#E84749","customStyle":true,"text":"2"}}##{{"color":"#E84749","customStyle":true,"text":"笔"}}# 得#{{"color":"#E84749","customStyle":true,"text":"碰返券"}}#',
|
|
101
|
+
totalProgress: '2',
|
|
102
|
+
currentProgress: '0',
|
|
103
|
+
progressUnit: '笔',
|
|
104
|
+
});
|
|
105
|
+
const service = new AlipayBumpInService({ config: { appId: 'mock-app-id' }, exec } as unknown as AlipaySdk, 'AS_LINKED_DEMO');
|
|
106
|
+
|
|
107
|
+
const detail = await service.getActivityDetail(QUERY_CONTEXT, 'alipay:bumpin:AS_LINKED_DEMO');
|
|
108
|
+
expect(detail?.linkedOrder).toBe(true);
|
|
109
|
+
|
|
110
|
+
const banner = toBumpInCardData(detail!, 'banner');
|
|
111
|
+
expect(banner.progressStyle).toBe('steps');
|
|
112
|
+
expect(banner.tagLabel).toBe('碰一下联单');
|
|
113
|
+
expect(banner.totalProgress).toBe('2');
|
|
114
|
+
expect(banner.currentProgress).toBe('0');
|
|
115
|
+
expect(banner.progressUnit).toBe('笔');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('actType 非 N_COUNT_TYPE 或缺省 → linkedOrder=false,卡片走普通 bar 形态', async () => {
|
|
119
|
+
vi.spyOn(console, 'info').mockImplementation(() => {});
|
|
120
|
+
const exec = vi.fn().mockResolvedValue({
|
|
121
|
+
code: '10000',
|
|
122
|
+
msg: 'Success',
|
|
123
|
+
actSchemeId: 'AS_PLAIN',
|
|
124
|
+
actType: 'SOME_OTHER_TYPE',
|
|
125
|
+
actStatus: 'PROCESSING',
|
|
126
|
+
cardTitle: '碰一下联单赢好礼',
|
|
127
|
+
totalProgress: '5',
|
|
128
|
+
currentProgress: '2',
|
|
129
|
+
progressUnit: '笔',
|
|
130
|
+
});
|
|
131
|
+
const service = new AlipayBumpInService({ config: { appId: 'mock-app-id' }, exec } as unknown as AlipaySdk, 'AS_PLAIN');
|
|
132
|
+
|
|
133
|
+
const detail = await service.getActivityDetail(QUERY_CONTEXT, 'alipay:bumpin:AS_PLAIN');
|
|
134
|
+
expect(detail?.linkedOrder).toBe(false);
|
|
135
|
+
expect(toBumpInCardData(detail!, 'detail').progressStyle).toBe('bar');
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe('碰出惊喜活动状态归一与四档文案(actStatus 权威词表对齐)', () => {
|
|
140
|
+
const makeDetail = async (rawActStatus: string | undefined) => {
|
|
141
|
+
vi.spyOn(console, 'info').mockImplementation(() => {});
|
|
142
|
+
const exec = vi.fn().mockResolvedValue({
|
|
143
|
+
code: '10000',
|
|
144
|
+
msg: 'Success',
|
|
145
|
+
actSchemeId: 'AS_STATUS',
|
|
146
|
+
cardTitle: '碰一下联单活动',
|
|
147
|
+
...(rawActStatus !== undefined ? { actStatus: rawActStatus } : {}),
|
|
148
|
+
});
|
|
149
|
+
const service = new AlipayBumpInService(
|
|
150
|
+
{ config: { appId: 'mock-app-id' }, exec } as unknown as AlipaySdk,
|
|
151
|
+
'AS_STATUS',
|
|
152
|
+
);
|
|
153
|
+
return service.getActivityDetail(QUERY_CONTEXT, 'alipay:bumpin:AS_STATUS');
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// [raw actStatus, 归一后 activityStatus, conditions[0] 文案]
|
|
157
|
+
it.each([
|
|
158
|
+
['NOT_START', 'NOT_START', '活动尚未开始'],
|
|
159
|
+
['INIT', 'INIT', '活动进行中,参与资格以支付宝实时校验为准'],
|
|
160
|
+
['PROCESSING', 'PROCESSING', '活动进行中,参与资格以支付宝实时校验为准'],
|
|
161
|
+
['FINISH', 'FINISH', '活动已结束'],
|
|
162
|
+
['RECEIVED', 'RECEIVED', '活动已结束,奖励已领取'],
|
|
163
|
+
['SOMETHING', 'FINISH', '活动已结束'],
|
|
164
|
+
[undefined, 'PROCESSING', '活动进行中,参与资格以支付宝实时校验为准'],
|
|
165
|
+
] as const)('actStatus=%s → activityStatus=%s、conditions[0]=%s', async (raw, normalized, statusLine) => {
|
|
166
|
+
const detail = await makeDetail(raw);
|
|
167
|
+
expect(detail?.activityStatus).toBe(normalized);
|
|
168
|
+
expect(detail?.guide?.conditions[0]).toBe(statusLine);
|
|
169
|
+
// 卡面投影:归一值词表内透传(detail → card data enum 收口)
|
|
170
|
+
expect(toBumpInCardData(detail!, 'detail').actStatus).toBe(normalized);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('未知非空值不再误判为可参与(旧 ACTIVE_STATUSES 含 ONGOING/PUBLISH 的漂移已闭合)', async () => {
|
|
174
|
+
const detail = await makeDetail('PUBLISH');
|
|
175
|
+
expect(detail?.activityStatus).toBe('FINISH');
|
|
176
|
+
expect(detail?.guide?.conditions[0]).toBe('活动已结束');
|
|
177
|
+
});
|
|
178
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bumpin 卡片状态化渲染(碰一碰活动状态枚举对齐):
|
|
3
|
+
* actStatus 五态 → 角标显隐/文案变体(renderToStaticMarkup 纯字符串断言,node env 零 DOM 依赖)。
|
|
4
|
+
*/
|
|
5
|
+
import { describe, expect, it } from 'vitest';
|
|
6
|
+
import { renderToStaticMarkup } from 'react-dom/server';
|
|
7
|
+
import { AlipayActivityBumpInCard } from '../src/client/cards/bumpin-activity';
|
|
8
|
+
import type { AlipayActivityBumpInCardData } from '../src/server/cards/bumpin-activity/meta';
|
|
9
|
+
|
|
10
|
+
const BASE = {
|
|
11
|
+
activityRef: 'alipay:bumpin:AS_1',
|
|
12
|
+
title: '碰一下 | 出惊喜',
|
|
13
|
+
mainTitle: '碰一下支付 5 笔,得 88 元惊喜礼包',
|
|
14
|
+
tagLabel: '碰一下联单',
|
|
15
|
+
actStatus: 'PROCESSING',
|
|
16
|
+
totalProgress: '5',
|
|
17
|
+
currentProgress: '1',
|
|
18
|
+
progressUnit: '笔',
|
|
19
|
+
startAtText: '2026-08-01',
|
|
20
|
+
endAtText: '2026-08-31',
|
|
21
|
+
vouchers: [
|
|
22
|
+
{
|
|
23
|
+
prizeId: 'PZ_1',
|
|
24
|
+
voucherName: '88元惊喜礼包',
|
|
25
|
+
voucherType: 'ITEM_REDUCTION_AMOUNT',
|
|
26
|
+
reductionAmount: '88',
|
|
27
|
+
thresholdAmountText: '满100元可用',
|
|
28
|
+
unit: '元',
|
|
29
|
+
merchantName: '示例商户',
|
|
30
|
+
},
|
|
31
|
+
],
|
|
32
|
+
mode: 'detail',
|
|
33
|
+
progressStyle: 'bar',
|
|
34
|
+
} satisfies AlipayActivityBumpInCardData;
|
|
35
|
+
|
|
36
|
+
const render = (data: AlipayActivityBumpInCardData) => renderToStaticMarkup(<AlipayActivityBumpInCard data={data} />);
|
|
37
|
+
|
|
38
|
+
describe('bumpin 卡片状态化展示(actStatus 枚举对齐)', () => {
|
|
39
|
+
it('PROCESSING/INIT 进行态:无角标,维持「日前有效 + 已完成进度」现状', () => {
|
|
40
|
+
for (const actStatus of ['PROCESSING', 'INIT'] as const) {
|
|
41
|
+
const html = render({ ...BASE, actStatus });
|
|
42
|
+
expect(html).not.toContain('promotion-bumpin__status');
|
|
43
|
+
expect(html).toContain('8 月 31 日前有效');
|
|
44
|
+
expect(html).toContain('已完成 1 / 5 笔');
|
|
45
|
+
expect(html).toContain('奖励池');
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('NOT_START 未开始:「未开始」pending 角标 + 「日开始」有效期 + 「尚未开始」进度文案', () => {
|
|
50
|
+
const html = render({ ...BASE, actStatus: 'NOT_START', currentProgress: '0' });
|
|
51
|
+
expect(html).toContain('promotion-bumpin__status--pending');
|
|
52
|
+
expect(html).toContain('未开始');
|
|
53
|
+
expect(html).toContain('8 月 01 日开始');
|
|
54
|
+
expect(html).not.toContain('日前有效');
|
|
55
|
+
expect(html).toContain('尚未开始');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('FINISH 已结束:「已结束」terminal 角标;有效期行不切换(仍是截止日)', () => {
|
|
59
|
+
const html = render({ ...BASE, actStatus: 'FINISH' });
|
|
60
|
+
expect(html).toContain('promotion-bumpin__status--terminal');
|
|
61
|
+
expect(html).toContain('已结束');
|
|
62
|
+
expect(html).toContain('8 月 31 日前有效');
|
|
63
|
+
expect(html).not.toContain('尚未开始');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('RECEIVED 已领奖:金色「已领奖」角标 + 奖励池标题「已领取 · 」前缀', () => {
|
|
67
|
+
const html = render({ ...BASE, actStatus: 'RECEIVED', currentProgress: '5' });
|
|
68
|
+
expect(html).toContain('promotion-bumpin__status--received');
|
|
69
|
+
expect(html).toContain('已领奖');
|
|
70
|
+
expect(html).toContain('已领取 · 奖励池');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('banner 压缩形态:NOT_START 角标与「日开始」行仍可辨(横幅模式同样吃状态化)', () => {
|
|
74
|
+
const html = render({ ...BASE, actStatus: 'NOT_START', mode: 'banner', currentProgress: '0' });
|
|
75
|
+
expect(html).toContain('promotion-bumpin__status--pending');
|
|
76
|
+
expect(html).toContain('8 月 01 日开始');
|
|
77
|
+
// banner 模式无奖励池
|
|
78
|
+
expect(html).not.toContain('奖励池');
|
|
79
|
+
});
|
|
80
|
+
});
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bumpin 凭证通道优先级回归(离散 env > v2 文件 > env JSON 兜底):
|
|
3
|
+
* - 三键齐备(MINI_APP_ID/MINI_APP_PRIVATE_KEY/MINI_APP_ALIPAY_PUB_KEY)→ 离散 env 优先,
|
|
4
|
+
* 覆盖可用文件通道;
|
|
5
|
+
* - 三键缺任一 → 整体不命中(不与文件混拼),回落文件通道;
|
|
6
|
+
* - 三键全缺 → 回落 ALIPAY_BUMPIN env JSON;
|
|
7
|
+
* - 离散 env 含 PLACEHOLDER → 占位防伪返回 null;
|
|
8
|
+
* - 全通道缺失 → null 降级。
|
|
9
|
+
*/
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
11
|
+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { createAlipaySdkClient } from '../src/server/integrations/alipay/client';
|
|
15
|
+
|
|
16
|
+
const GATEWAY = 'https://openapi.alipay.com/gateway.do';
|
|
17
|
+
const FILE_CREDENTIAL = {
|
|
18
|
+
value: { appId: 'FILE_APP', privateKey: 'FILE_KEY', alipayPublicKey: 'FILE_PUB' },
|
|
19
|
+
};
|
|
20
|
+
const ENV_JSON_CREDENTIAL = {
|
|
21
|
+
value: { appId: 'ENVJSON_APP', privateKey: 'ENVJSON_KEY', alipayPublicKey: 'ENVJSON_PUB' },
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** 临时目录中模拟 v2 文件通道(bumpin.json + credentials/alipay-bumpin.json) */
|
|
25
|
+
function createFileChannelDir(): string {
|
|
26
|
+
const dir = mkdtempSync(path.join(tmpdir(), 'bumpin-cred-'));
|
|
27
|
+
mkdirSync(path.join(dir, 'credentials'));
|
|
28
|
+
writeFileSync(path.join(dir, 'credentials', 'alipay-bumpin.json'), JSON.stringify(FILE_CREDENTIAL));
|
|
29
|
+
writeFileSync(path.join(dir, 'bumpin.json'), JSON.stringify({ gateway: GATEWAY, actSchemeId: 'AS_DEMO' }));
|
|
30
|
+
return dir;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 断言 SDK 命中指定 appId 的凭证通道(AlipaySdk 自身不暴露 appId,经 config 透传读取) */
|
|
34
|
+
function expectAppId(sdk: ReturnType<typeof createAlipaySdkClient>, appId: string): void {
|
|
35
|
+
expect(sdk).not.toBeNull();
|
|
36
|
+
expect((sdk as unknown as { config: { appId: string } }).config.appId).toBe(appId);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('bumpin 凭证通道优先级', () => {
|
|
40
|
+
let fileDir: string;
|
|
41
|
+
|
|
42
|
+
beforeEach(() => {
|
|
43
|
+
vi.stubEnv('MINI_APP_ID', '');
|
|
44
|
+
vi.stubEnv('MINI_APP_PRIVATE_KEY', '');
|
|
45
|
+
vi.stubEnv('MINI_APP_ALIPAY_PUB_KEY', '');
|
|
46
|
+
vi.stubEnv('ALIPAY_BUMPIN', '');
|
|
47
|
+
fileDir = createFileChannelDir();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
afterEach(() => {
|
|
51
|
+
vi.unstubAllEnvs();
|
|
52
|
+
rmSync(fileDir, { recursive: true, force: true });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('三键齐备 → 离散 env 优先,覆盖可用文件通道', () => {
|
|
56
|
+
vi.stubEnv('MINI_APP_ID', 'DISCRETE_APP');
|
|
57
|
+
vi.stubEnv('MINI_APP_PRIVATE_KEY', 'DISCRETE_PRIVATE_KEY');
|
|
58
|
+
vi.stubEnv('MINI_APP_ALIPAY_PUB_KEY', 'DISCRETE_ALIPAY_PUBLIC_KEY');
|
|
59
|
+
|
|
60
|
+
const sdk = createAlipaySdkClient({ gateway: GATEWAY }, path.join(fileDir, 'bumpin.json'));
|
|
61
|
+
expectAppId(sdk, 'DISCRETE_APP');
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('三键缺任一 → 整体不命中(不与文件混拼),回落文件通道', () => {
|
|
65
|
+
vi.stubEnv('MINI_APP_ID', 'DISCRETE_APP');
|
|
66
|
+
vi.stubEnv('MINI_APP_PRIVATE_KEY', 'DISCRETE_PRIVATE_KEY');
|
|
67
|
+
// 缺 MINI_APP_ALIPAY_PUB_KEY
|
|
68
|
+
|
|
69
|
+
const sdk = createAlipaySdkClient({ gateway: GATEWAY }, path.join(fileDir, 'bumpin.json'));
|
|
70
|
+
expectAppId(sdk, 'FILE_APP');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('三键全缺 → 回落 ALIPAY_BUMPIN env JSON', () => {
|
|
74
|
+
vi.stubEnv('ALIPAY_BUMPIN', JSON.stringify(ENV_JSON_CREDENTIAL));
|
|
75
|
+
|
|
76
|
+
const sdk = createAlipaySdkClient({ gateway: GATEWAY }, '/nonexistent/config-dir');
|
|
77
|
+
expectAppId(sdk, 'ENVJSON_APP');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('离散 env 含 PLACEHOLDER → 占位防伪返回 null', () => {
|
|
81
|
+
vi.stubEnv('MINI_APP_ID', 'PLACEHOLDER_APP');
|
|
82
|
+
vi.stubEnv('MINI_APP_PRIVATE_KEY', 'PLACEHOLDER_KEY');
|
|
83
|
+
vi.stubEnv('MINI_APP_ALIPAY_PUB_KEY', 'PLACEHOLDER_PUB');
|
|
84
|
+
|
|
85
|
+
const sdk = createAlipaySdkClient({ gateway: GATEWAY }, '/nonexistent/config-dir');
|
|
86
|
+
expect(sdk).toBeNull();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('全通道缺失 → null 降级', () => {
|
|
90
|
+
const sdk = createAlipaySdkClient({ gateway: GATEWAY }, '/nonexistent/config-dir');
|
|
91
|
+
expect(sdk).toBeNull();
|
|
92
|
+
});
|
|
93
|
+
});
|