@tbox.cn/app-module-activity-play 0.3.1 → 0.4.0

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 (51) hide show
  1. package/INTEGRATION.md +57 -66
  2. package/README.md +13 -5
  3. package/dist/chunk-GDHTMID6.js +185 -0
  4. package/dist/chunk-XIDGKP5D.js +1154 -0
  5. package/dist/client/index.d.ts +2 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +38 -10
  9. package/dist/server/index.d.ts +593 -85
  10. package/dist/server/index.js +37 -9
  11. package/package.json +5 -5
  12. package/skills/activity-play/SKILL.md +41 -15
  13. package/src/client/cards/activity-play/ActivityPlayCard.tsx +3 -3
  14. package/src/client/cards/activity-play-prize/ActivityPlayPrizeDetailCard.tsx +44 -0
  15. package/src/client/cards/activity-play-prize/ActivityPlayPrizeListCard.tsx +62 -0
  16. package/src/client/cards/activity-play-prize/index.ts +8 -0
  17. package/src/client/cards/view.ts +6 -3
  18. package/src/client/index.ts +6 -0
  19. package/src/server/cards/activity-play/meta.ts +5 -4
  20. package/src/server/cards/activity-play/samples.ts +43 -18
  21. package/src/server/cards/activity-play-prize-detail/meta.ts +29 -0
  22. package/src/server/cards/activity-play-prize-detail/samples.ts +54 -0
  23. package/src/server/cards/activity-play-prize-list/meta.ts +41 -0
  24. package/src/server/cards/activity-play-prize-list/samples.ts +78 -0
  25. package/src/server/cards/index.ts +5 -1
  26. package/src/server/errors.ts +9 -28
  27. package/src/server/index.ts +48 -11
  28. package/src/server/ports.ts +4 -25
  29. package/src/server/prizes/cards.ts +79 -0
  30. package/src/server/prizes/errors.ts +88 -0
  31. package/src/server/prizes/ports.ts +35 -0
  32. package/src/server/prizes/query.ts +104 -0
  33. package/src/server/prizes/routes.ts +139 -0
  34. package/src/server/prizes/subject.ts +29 -0
  35. package/src/server/prizes/tools.ts +180 -0
  36. package/src/server/query.ts +47 -28
  37. package/src/server/routes.ts +44 -230
  38. package/src/server/tools.ts +36 -31
  39. package/tbox.module.json +16 -6
  40. package/tests/cards-capture.test.ts +3 -4
  41. package/tests/ports.test.ts +57 -0
  42. package/tests/prizes-routes.test.ts +230 -0
  43. package/tests/prizes-tools.test.ts +216 -0
  44. package/tests/prizes.test.ts +375 -0
  45. package/tests/routes.test.ts +89 -16
  46. package/tests/samples.test.ts +2 -2
  47. package/tests/smoke.test.ts +8 -4
  48. package/tests/tools.test.ts +50 -31
  49. package/dist/chunk-CM4OEPC3.js +0 -689
  50. package/dist/chunk-HUBEOW44.js +0 -98
  51. package/tests/entry.test.ts +0 -458
@@ -13,6 +13,10 @@ import {
13
13
  type ActivityPlayQueryPort,
14
14
  } from '@tbox.cn/app-contracts-mall';
15
15
  import { resolveActivityPlayQueryPort } from '../src/server/ports';
16
+ import { resolveActivityPlayPrizePort } from '../src/server/prizes/ports';
17
+ import { ACTIVITY_PLAY_PRIZES_SERVICE } from '@tbox.cn/app-contracts-mall';
18
+ import type { ActivityPlayPrizeQueryPort } from '@tbox.cn/app-contracts-mall';
19
+ import { ActivityPlayPrizeHttpError, toActivityPlayPrizeError } from '../src/server/prizes/errors';
16
20
  import { ActivityPlayHttpError, toActivityPlayHttpError } from '../src/server/errors';
17
21
 
18
22
  const stubCtx = (integrations?: unknown): ServerContext =>
@@ -81,3 +85,56 @@ describe('toActivityPlayHttpError 映射守门', () => {
81
85
  expect(toActivityPlayHttpError({}).httpStatus).toBe(502);
82
86
  });
83
87
  });
88
+
89
+ describe('resolveActivityPlayPrizePort 解析守门(任务07 奖品槽)', () => {
90
+ const prizeReqCtx = (mallId?: string): RequestContext =>
91
+ mallId
92
+ ? withMallScopeFromQuery({ identity: { userId: 'u', source: 'guest' } }, { mallId })
93
+ : { identity: { userId: 'u', source: 'guest' } };
94
+ it('无商圈 → SCOPE_REQUIRED(本域 400 域错误,非裸 throw)', async () => {
95
+ await expect(resolveActivityPlayPrizePort(prizeReqCtx(), stubCtx({ resolveService: async () => ({}) as ActivityPlayPrizeQueryPort })))
96
+ .rejects.toMatchObject({ code: 'SCOPE_REQUIRED', httpStatus: 400 });
97
+ });
98
+
99
+ it('integrations registry 缺席(未装配/未激活 prize slot)→ NOT_CONFIGURED 503', async () => {
100
+ await expect(resolveActivityPlayPrizePort(prizeReqCtx('mall-a'), stubCtx(undefined)))
101
+ .rejects.toMatchObject({ code: 'NOT_CONFIGURED', httpStatus: 503 });
102
+ });
103
+
104
+ it('resolveService 入参契约:奖品槽常量 + flat scope + request 原样;Annex 返回 Port', async () => {
105
+ const prizePort = {} as ActivityPlayPrizeQueryPort;
106
+ const resolveService = vi.fn(async (): Promise<ActivityPlayPrizeQueryPort> => prizePort);
107
+ const ctx = prizeReqCtx('mall-a');
108
+ const got = await resolveActivityPlayPrizePort(ctx, stubCtx({ resolveService }));
109
+ expect(got).toBe(prizePort);
110
+ expect(resolveService).toHaveBeenCalledWith({
111
+ service: ACTIVITY_PLAY_PRIZES_SERVICE,
112
+ scope: { mallId: 'mall-a' },
113
+ request: ctx,
114
+ });
115
+ });
116
+
117
+ it('供给错误原样上抛(映射归路由/工具层收口),奖品面错误分类经 toActivityPlayPrizeError', async () => {
118
+ const err = Object.assign(new Error('cfg broken'), { code: 'PROVIDER_INSTANCE_DISABLED' });
119
+ await expect(
120
+ resolveActivityPlayPrizePort(prizeReqCtx('mall-a'), stubCtx({ resolveService: async () => { throw err; } })),
121
+ ).rejects.toMatchObject({ code: 'PROVIDER_INSTANCE_DISABLED' });
122
+ });
123
+
124
+ it('toActivityPlayPrizeError 守门:本域认证错误原样透传(不降格 502);供给码归 503;未知码归 502', () => {
125
+ const authError = ActivityPlayPrizeHttpError.loginRequired('缺用户');
126
+ const mappedAuth = toActivityPlayPrizeError(authError);
127
+ expect(mappedAuth).toBe(authError);
128
+ expect(mappedAuth.code).toBe('LOGIN_REQUIRED');
129
+ expect(mappedAuth.httpStatus).toBe(401);
130
+
131
+ const mappedCfg = toActivityPlayPrizeError(Object.assign(new Error('x'), { code: 'PROVIDER_SERVICE_NOT_CONFIGURED' }));
132
+ expect(mappedCfg.httpStatus).toBe(503);
133
+ expect(mappedCfg.code).toBe('NOT_CONFIGURED');
134
+
135
+ const mappedUp = toActivityPlayPrizeError(new Error('anything sensitive'));
136
+ expect(mappedUp.httpStatus).toBe(502);
137
+ expect(mappedUp.code).toBe('PROVIDER_ERROR');
138
+ expect(toActivityPlayPrizeError('plain string').httpStatus).toBe(502);
139
+ });
140
+ });
@@ -0,0 +1,230 @@
1
+ /**
2
+ * 本人奖品 HTTP 接口行为测试(任务07——supertest 装配真实 Router(含活动主路由组合)
3
+ * + 会话上下文中间件;供给经 ctx.integrations.resolveService 替身注入,查询核心/解析器
4
+ * 为真实实现——不经 vi.mock 桩跳层)。
5
+ * 覆盖风险≡验收点:
6
+ * - 主体纪律:缺可信上下文/anonymous → 401 LOGIN_REQUIRED 且零供给解析(评审验收 2);
7
+ * - scope 冲突/补齐/缺商圈错误族(SCOPE_REQUIRED/SCOPE_MISMATCH);
8
+ * - 错误域区分(503/502/404/400)+ 错误信封形状 + 恒 no-store;
9
+ * - 标识原样:敛 path 参数('001'/' record-001 ' 原值达 Port——URL 编码面解码后原样);
10
+ * - 成功响应 DTO 面 = 契约 strict 面(无 itemActions/noResultsReason——出卡适配层专属)。
11
+ */
12
+ import { describe, expect, it, vi } from 'vitest';
13
+ import express from 'express';
14
+ import type { Express, Request, Response, NextFunction } from 'express';
15
+ import request from 'supertest';
16
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
17
+ import type { RequestContext } from '@tbox.cn/app-contracts';
18
+ import { ACTIVITY_PLAY_PRIZES_SERVICE } from '@tbox.cn/app-contracts-mall';
19
+ import type {
20
+ ActivityPlayPrizeQueryContext,
21
+ ActivityPlayPrizeQueryPort,
22
+ } from '@tbox.cn/app-contracts-mall';
23
+ import { createActivityPlayRouter } from '../src/server/routes';
24
+
25
+ /** 会话基础上下文(登录态 local——本人奖品主体) */
26
+ const baseReqCtx = (userId = '2088000000000001'): RequestContext => ({
27
+ identity: { userId, source: 'local' },
28
+ });
29
+
30
+ interface PortCall {
31
+ q: ActivityPlayPrizeQueryContext;
32
+ prizeRecordRef?: string;
33
+ }
34
+
35
+ /** 可观测 Port 替身(记录调用 + 可配置返回/抛错) */
36
+ function makePort(overrides: Partial<ActivityPlayPrizeQueryPort> = {}) {
37
+ const calls: PortCall[] = [];
38
+ const defaults: ActivityPlayPrizeQueryPort = {
39
+ async listMyPrizes() { return { total: 0, items: [] }; },
40
+ async getMyPrizeDetail() { return null; },
41
+ };
42
+ const port: ActivityPlayPrizeQueryPort = {
43
+ async listMyPrizes(q) {
44
+ calls.push({ q });
45
+ return (overrides.listMyPrizes ?? defaults.listMyPrizes)(q);
46
+ },
47
+ async getMyPrizeDetail(q, prizeRecordRef) {
48
+ calls.push({ q, prizeRecordRef });
49
+ return (overrides.getMyPrizeDetail ?? defaults.getMyPrizeDetail)(q, prizeRecordRef);
50
+ },
51
+ };
52
+ return { port, calls };
53
+ }
54
+
55
+ const RECORD = {
56
+ prizeRecordRef: 'prize-demo-001',
57
+ title: '咖啡兑换券',
58
+ prizeType: 'COUPON',
59
+ claimStatus: 'CLAIMED',
60
+ useStatus: 'UNUSED',
61
+ };
62
+ const DETAIL = {
63
+ ...RECORD,
64
+ redemptionMethod: '门店柜台',
65
+ redemptionInstruction: '请按活动页面的领取及使用指引操作',
66
+ };
67
+
68
+ interface HarnessOpts {
69
+ reqCtx?: RequestContext | undefined;
70
+ port?: ActivityPlayPrizeQueryPort;
71
+ resolveError?: unknown;
72
+ }
73
+
74
+ interface Harness {
75
+ app: Express;
76
+ calls: PortCall[];
77
+ resolveService: ReturnType<typeof vi.fn>;
78
+ }
79
+
80
+ /** 装配被测 App:auth 形中间件写入 reqCtx → 挂活动主 Router(内含 prizes 子路由)。 */
81
+ function makeApp(opts: HarnessOpts): Harness {
82
+ const { port: defaultPort, calls } = makePort();
83
+ const resolveService = vi.fn(async () => {
84
+ if (opts.resolveError) throw opts.resolveError;
85
+ return opts.port ?? defaultPort;
86
+ });
87
+ const ctxStub = {
88
+ integrations: { resolveService },
89
+ logger: { warn: vi.fn() },
90
+ } as unknown as ServerContext;
91
+ const app = express();
92
+ app.use((req: Request, _res: Response, next: NextFunction) => {
93
+ if (opts.reqCtx) (req as unknown as Record<string, unknown>)['tboxAuthContext'] = opts.reqCtx;
94
+ next();
95
+ });
96
+ app.use(createActivityPlayRouter(ctxStub));
97
+ return { app, calls, resolveService };
98
+ }
99
+
100
+ const resHeaders = { 'cache-control': 'no-store' };
101
+
102
+ describe('GET /api/m/activity-play/prizes(本人奖品列表)', () => {
103
+ it('正常查询:200 {data:{total,items}} no-store;主体/商圈注入供给;DTO 面零出卡件', async () => {
104
+ const { port, calls } = makePort({ listMyPrizes: async () => ({ total: 1, items: [RECORD] }) });
105
+ const h = makeApp({ reqCtx: baseReqCtx(), port });
106
+ const res = await request(h.app).get('/prizes?mallId=mall-a').set('Accept', 'application/json');
107
+ expect(res.status).toBe(200);
108
+ expect(res.headers['cache-control']).toBe('no-store');
109
+ expect(res.body).toEqual({ data: { total: 1, items: [RECORD] } });
110
+ expect(calls[0]?.q.subjectId).toBe('2088000000000001');
111
+ expect(h.resolveService).toHaveBeenCalledWith(
112
+ expect.objectContaining({ service: ACTIVITY_PLAY_PRIZES_SERVICE, scope: { mallId: 'mall-a' } }),
113
+ );
114
+ });
115
+
116
+ it('供应商成功无记录:200 {data:{total:0,items:[]}}(空态 DTO——非错误非伪造)', async () => {
117
+ const h = makeApp({ reqCtx: baseReqCtx() });
118
+ const res = await request(h.app).get('/prizes?mallId=mall-a');
119
+ expect(res.status).toBe(200);
120
+ expect(res.body).toEqual({ data: { total: 0, items: [] } });
121
+ });
122
+
123
+ it('缺可信请求上下文/anonymous → 401 LOGIN_REQUIRED 且零供给解析+零 Port 调用', async () => {
124
+ for (const reqCtx of [
125
+ undefined,
126
+ { identity: { userId: 'u1', source: 'anonymous' as const } } as RequestContext,
127
+ ]) {
128
+ const h = makeApp({ reqCtx });
129
+ const res = await request(h.app).get('/prizes?mallId=mall-a');
130
+ expect(res.status).toBe(401);
131
+ expect(res.headers['cache-control']).toBe('no-store');
132
+ expect(res.body.error.code).toBe('LOGIN_REQUIRED');
133
+ expect(h.resolveService).not.toHaveBeenCalled();
134
+ expect(h.calls).toHaveLength(0);
135
+ }
136
+ });
137
+
138
+ it('请求商圈与已绑定上下文冲突 → 403 SCOPE_MISMATCH;缺商圈 → 400 SCOPE_REQUIRED', async () => {
139
+ const h = makeApp({
140
+ reqCtx: { ...baseReqCtx(), attributes: { mall: { mallId: 'mall-bound' } } },
141
+ });
142
+ const res = await request(h.app).get('/prizes?mallId=mall-a');
143
+ expect(res.status).toBe(403);
144
+ expect(res.body.error.code).toBe('SCOPE_MISMATCH');
145
+
146
+ const h2 = makeApp({ reqCtx: baseReqCtx() });
147
+ const res2 = await request(h2.app).get('/prizes');
148
+ expect(res2.status).toBe(400);
149
+ expect(res2.body.error.code).toBe('SCOPE_REQUIRED');
150
+ expect(h2.calls).toHaveLength(0);
151
+ });
152
+
153
+ it('供给未配置(SERVICE_NOT_CONFIGURED)→ 503 NOT_CONFIGURED;上游失败 → 502 PROVIDER_ERROR(失败不伪装未中奖)', async () => {
154
+ const h = makeApp({
155
+ reqCtx: baseReqCtx(),
156
+ resolveError: Object.assign(new Error('slot absent'), { code: 'PROVIDER_SERVICE_NOT_CONFIGURED' }),
157
+ });
158
+ const res = await request(h.app).get('/prizes?mallId=mall-a');
159
+ expect(res.status).toBe(503);
160
+ expect(res.body.error.code).toBe('NOT_CONFIGURED');
161
+ expect(res.headers['cache-control']).toBe('no-store');
162
+
163
+ const h2 = makeApp({
164
+ reqCtx: baseReqCtx(),
165
+ resolveError: Object.assign(new Error('HTTP 500'), { code: 'PROVIDER_TRANSPORT_FAILURE' }),
166
+ });
167
+ const res2 = await request(h2.app).get('/prizes?mallId=mall-a');
168
+ expect(res2.status).toBe(502);
169
+ expect(res2.body.error.code).toBe('PROVIDER_ERROR');
170
+ });
171
+
172
+ it('供给输出契约不过(坏 total 伪装空结果)→ 502(供给数据非法不折损为未中奖)', async () => {
173
+ const h = makeApp({
174
+ reqCtx: baseReqCtx(),
175
+ port: makePort({ listMyPrizes: async () => ({ total: -1, items: [] } as never) }).port,
176
+ });
177
+ const res = await request(h.app).get('/prizes?mallId=mall-a');
178
+ expect(res.status).toBe(502);
179
+ expect(res.body.error.code).toBe('PROVIDER_ERROR');
180
+ });
181
+ });
182
+
183
+ describe('GET /api/m/activity-play/prizes/:prizeRecordRef(本人奖品详情)', () => {
184
+ it('正常查询:200 {data:PrizeDetail} 平铺;主体与原样标识注入供给', async () => {
185
+ const { port, calls } = makePort({ getMyPrizeDetail: async (_q, ref) => ({ ...DETAIL, prizeRecordRef: ref }) });
186
+ const h = makeApp({ reqCtx: baseReqCtx(), port });
187
+ const res = await request(h.app).get('/prizes/prize-demo-001?mallId=mall-a');
188
+ expect(res.status).toBe(200);
189
+ expect(res.headers['cache-control']).toBe('no-store');
190
+ expect(res.body.data).toEqual(DETAIL);
191
+ expect(calls[0]?.prizeRecordRef).toBe('prize-demo-001');
192
+ });
193
+
194
+ it('标识原样:『 record-001 』(URL 编码 %20 收敛解码)与『001』原值达 Port——不改写不数字化', async () => {
195
+ const { port, calls } = makePort({ getMyPrizeDetail: async (_q, ref) => ({ ...DETAIL, prizeRecordRef: ref } as never) });
196
+ const h = makeApp({ reqCtx: baseReqCtx(), port });
197
+ const res = await request(h.app).get('/prizes/%20record-001%20?mallId=mall-a');
198
+ expect(res.status).toBe(200);
199
+ expect(calls[0]?.prizeRecordRef).toBe(' record-001 ');
200
+ expect(res.body.data.prizeRecordRef).toBe(' record-001 ');
201
+
202
+ const { port: port2, calls: calls2 } = makePort({ getMyPrizeDetail: async (_q, ref) => ({ ...DETAIL, prizeRecordRef: ref } as never) });
203
+ const h2 = makeApp({ reqCtx: baseReqCtx(), port: port2 });
204
+ await request(h2.app).get('/prizes/001?mallId=mall-a');
205
+ expect(calls2[0]?.prizeRecordRef).toBe('001');
206
+ });
207
+
208
+ it('不存在/不可见 → 404 PRIZE_NOT_FOUND(供给 null——同文案不区分)', async () => {
209
+ const h = makeApp({ reqCtx: baseReqCtx() });
210
+ const res = await request(h.app).get('/prizes/prize-none?mallId=mall-a');
211
+ expect(res.status).toBe(404);
212
+ expect(res.body.error.code).toBe('PRIZE_NOT_FOUND');
213
+ });
214
+
215
+ it('全空白/超长标识 → 400 INVALID_REQUEST 且零 Port 调用', async () => {
216
+ const h = makeApp({ reqCtx: baseReqCtx() });
217
+ const res = await request(h.app).get('/prizes/%20%20%20?mallId=mall-a').set(resHeaders);
218
+ expect(res.status).toBe(400);
219
+ expect(res.body.error.code).toBe('INVALID_REQUEST');
220
+ expect(h.calls).toHaveLength(0);
221
+ });
222
+
223
+ it('登录态缺失(anonymous)→ 401 LOGIN_REQUIRED 零 Port 调用(主体检查先于供给——任务07 钉死)', async () => {
224
+ const h = makeApp({ reqCtx: { identity: { userId: 'u1', source: 'anonymous' } } });
225
+ const res = await request(h.app).get('/prizes/prize-demo-001?mallId=mall-a');
226
+ expect(res.status).toBe(401);
227
+ expect(h.calls).toHaveLength(0);
228
+ expect(h.resolveService).not.toHaveBeenCalled();
229
+ });
230
+ });
@@ -0,0 +1,216 @@
1
+ /**
2
+ * 本人奖品工具行为测试(任务07——直接 execute 真实工具实例 + stub integrations ctx,
3
+ * 查询核心/解析器为真实实现——不经 vi.mock 桩跳层)。
4
+ * 覆盖风险≡验收点:
5
+ * - 输入契约:无 mallId/userId 等 scope/身份字段;prizeRecordRef 原字符串收参
6
+ * ('001'/'1.20'/' record-001 ' 不折叠——与 HTTP 同参同果);
7
+ * - 上下文纪律:requireToolRequestContext 在 try 外——缺运行上下文抛平台 AuthError
8
+ * (非失败事实、非 502 兜底);主体检查先于供给解析(缺用户/anonymous → 零供给接触);
9
+ * - 出卡契约:成功(含空态)恒出卡(列表卡含空态 noResultsReason——api.md 钉死);
10
+ * 详情平铺卡;失败路径无 cards 键;失败 fact 含可辨识 errorCode,原始异常不透出;
11
+ * - 失败≠未中奖(NOT_CONFIGURED/PROVIDER_ERROR/LOGIN_REQUIRED/PRIZE_NOT_FOUND 分类)。
12
+ */
13
+ import { describe, expect, it, vi } from 'vitest';
14
+ import { createToolExecContext } from '@tbox.cn/app-agent-sdk-server';
15
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
16
+ import { requireToolRequestContext } from '@tbox.cn/app-agent-sdk-server';
17
+ import type { RequestContext } from '@tbox.cn/app-contracts';
18
+ import {
19
+ activityPlayPrizeDetailCardDataSchema,
20
+ activityPlayPrizeListCardDataSchema,
21
+ } from '@tbox.cn/app-contracts-mall';
22
+ import {
23
+ createActivityPlayPrizeTools,
24
+ } from '../src/server/prizes/tools';
25
+
26
+ /** reqCtx:登录态 local + 绑定商圈(工具路径无 query 注入——scope 恒取上下文绑定) */
27
+ const reqCtxOf = (mallId: string, userId = '2088000000000001'): RequestContext => ({
28
+ identity: { userId, source: 'local' },
29
+ attributes: { mall: { mallId } },
30
+ });
31
+
32
+ const RECORD = {
33
+ prizeRecordRef: 'prize-demo-001',
34
+ title: '咖啡兑换券',
35
+ prizeType: 'COUPON',
36
+ claimStatus: 'CLAIMED',
37
+ useStatus: 'UNUSED',
38
+ activityTitle: '幸运转盘',
39
+ };
40
+ const DETAIL = {
41
+ ...RECORD,
42
+ redemptionMethod: '门店柜台',
43
+ redemptionInstruction: '请按活动页面的领取及使用指引操作',
44
+ };
45
+
46
+ function makeHarness(port: unknown, resolveError?: unknown): {
47
+ tools: ReturnType<typeof createActivityPlayPrizeTools>;
48
+ resolveService: ReturnType<typeof vi.fn>;
49
+ } {
50
+ const resolveService = vi.fn(async () => {
51
+ if (resolveError) throw resolveError;
52
+ return port;
53
+ });
54
+ const ctx = { integrations: { resolveService } } as unknown as ServerContext;
55
+ return { tools: createActivityPlayPrizeTools({ getCtx: () => ctx }), resolveService };
56
+ }
57
+
58
+ /** 真实供给替身(记录调用——主体/标识断言锚点) */
59
+ function listPort(items: readonly unknown[], total = items.length) {
60
+ const calls: Array<{ q: { subjectId?: string }; ref?: string }> = [];
61
+ return {
62
+ calls,
63
+ port: {
64
+ async listMyPrizes(q: { subjectId?: string }) {
65
+ calls.push({ q });
66
+ return { total, items: [...items] };
67
+ },
68
+ async getMyPrizeDetail(q: { subjectId?: string }, ref: string) {
69
+ calls.push({ q, ref });
70
+ return (items as Array<{ prizeRecordRef?: string }>).find((i) => i.prizeRecordRef === ref) ?? null;
71
+ },
72
+ },
73
+ };
74
+ }
75
+
76
+ describe('listMyPrizes', () => {
77
+ it('非空:found 事实 + 列表卡(data 过卡契约;note ≤120);标识事实原样(无 itemActions 混入 facts)', async () => {
78
+ const { calls, port } = listPort([RECORD]);
79
+ const { tools } = makeHarness(port);
80
+ const result = await tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
81
+
82
+ expect(result['found']).toBe(true);
83
+ expect(result['total']).toBe(1);
84
+ expect(result['mallId']).toBe('mall-a');
85
+ expect((result['items'] as Array<{ prizeRecordRef: string }>).map((i) => i.prizeRecordRef))
86
+ .toEqual(['prize-demo-001']);
87
+ const cards = result['cards'] as Array<{ cardType: string; data: unknown; note: string }>;
88
+ expect(cards).toHaveLength(1);
89
+ expect(cards[0]?.cardType).toBe('activity-play-prize-list');
90
+ expect(cards[0]?.note.length).toBeLessThanOrEqual(120);
91
+ activityPlayPrizeListCardDataSchema.parse(cards[0]?.data);
92
+ // 主体注入:供给收到的 = 可信上下文 subjectId
93
+ expect(calls[0]?.q.subjectId).toBe('2088000000000001');
94
+ });
95
+
96
+ it('供应商成功无记录:空态事实 found=false + 空态列表卡(noResultsReason 在卡 data——api.md 钉死)', async () => {
97
+ const { port } = listPort([]);
98
+ const { tools } = makeHarness(port);
99
+ const result = await tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
100
+ expect(result['found']).toBe(false);
101
+ expect(result['noResultsReason']).toContain('暂无');
102
+ const cards = result['cards'] as Array<{ cardType: string; data: { noResultsReason?: string } }>;
103
+ expect(cards).toHaveLength(1);
104
+ expect(cards[0]?.data.noResultsReason).toContain('暂无中奖记录');
105
+ activityPlayPrizeListCardDataSchema.parse(cards[0]?.data);
106
+ });
107
+
108
+ it('缺用户(anonymous)→ 失败事实 LOGIN_REQUIRED、无 cards、零供给解析接触(先于 registry)', async () => {
109
+ const { port } = listPort([RECORD]);
110
+ const { tools, resolveService } = makeHarness(port);
111
+ const anonCtx: RequestContext = { identity: { userId: 'u1', source: 'anonymous' }, attributes: { mall: { mallId: 'mall-a' } } };
112
+ const execCtx = createToolExecContext(anonCtx) as never;
113
+ const result = await tools.listMyPrizes.execute!({}, execCtx) as Record<string, unknown>;
114
+ // anonymous 工具上下文:query 层 requirePrizeQueryContext 拒绝——事实面失败而 AuthError 不出现
115
+ expect(result['found']).toBe(false);
116
+ expect(result['errorCode']).toBe('LOGIN_REQUIRED');
117
+ expect(result['cards']).toBeUndefined();
118
+ expect(resolveService).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it('缺绑定商圈 → SCOPE_REQUIRED 失败事实(工具路径无 query 注入面)', async () => {
122
+ const { port } = listPort([RECORD]);
123
+ const { tools } = makeHarness(port);
124
+ const result = await tools.listMyPrizes.execute!({}, createToolExecContext({ identity: { userId: 'u1', source: 'local' } } as never) as never) as Record<string, unknown>;
125
+ expect(result['errorCode']).toBe('SCOPE_REQUIRED');
126
+ expect(result['cards']).toBeUndefined();
127
+ });
128
+
129
+ it('供给未配置 → NOT_CONFIGURED 失败事实;上游失败 → PROVIDER_ERROR——均不出「未中奖」卡(失败≠无记录)', async () => {
130
+ const notConfigured = makeHarness(listPort([]).port, Object.assign(new Error('x'), { code: 'PROVIDER_SERVICE_NOT_CONFIGURED' }));
131
+ const r1 = await notConfigured.tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
132
+ expect(r1['errorCode']).toBe('NOT_CONFIGURED');
133
+ expect(r1['cards']).toBeUndefined();
134
+
135
+ const upstream = makeHarness(listPort([]).port, Object.assign(new Error('HTTP 500'), { code: 'PROVIDER_TRANSPORT_FAILURE' }));
136
+ const r2 = await upstream.tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
137
+ expect(r2['errorCode']).toBe('PROVIDER_ERROR');
138
+ expect(r2['cards']).toBeUndefined();
139
+ });
140
+
141
+ it('连续/并发 A/B 主体不串数据(每 execute 各自上下文解析)', async () => {
142
+ const { calls, port } = listPort([RECORD]);
143
+ const { tools } = makeHarness(port);
144
+ await tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a', 'user-A')) as never);
145
+ await tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a', 'user-B')) as never);
146
+ expect(calls.map((c) => c.q.subjectId)).toEqual(['user-A', 'user-B']);
147
+ });
148
+
149
+ it('超过展示上限:卡面截断 + truncated 标记,total 保留真实值(事实面 count/total 同步)', async () => {
150
+ const items = Array.from({ length: 51 }, (_, i) => ({ ...RECORD, prizeRecordRef: `prize-${String(i).padStart(3, '0')}` }));
151
+ const { port } = listPort(items, 51);
152
+ const { tools } = makeHarness(port);
153
+ const result = await tools.listMyPrizes.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
154
+ expect(result['total']).toBe(51);
155
+ expect(result['truncated']).toBe(true);
156
+ const cards = result['cards'] as Array<{ data: { items: unknown[]; total: number; truncated?: boolean } }>;
157
+ expect(cards[0]?.data.items).toHaveLength(50);
158
+ expect(cards[0]?.data.total).toBe(51);
159
+ expect(cards[0]?.data.truncated).toBe(true);
160
+ activityPlayPrizeListCardDataSchema.parse(cards[0]?.data);
161
+ });
162
+ });
163
+
164
+ describe('getMyPrizeDetail', () => {
165
+ it('非空:详情事实 + 平铺卡(data 过卡契约);每次按当前用户真实查询(不拿快照)', async () => {
166
+ const { calls, port } = listPort([DETAIL]);
167
+ const { tools } = makeHarness(port);
168
+ const result = await tools.getMyPrizeDetail.execute!({ prizeRecordRef: 'prize-demo-001' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
169
+ expect(result['found']).toBe(true);
170
+ expect(result['redemptionMethod']).toBe('门店柜台');
171
+ const cards = result['cards'] as Array<{ cardType: string; data: object }>;
172
+ expect(cards[0]?.cardType).toBe('activity-play-prize-detail');
173
+ activityPlayPrizeDetailCardDataSchema.parse(cards[0]?.data);
174
+ expect(calls[0]?.ref).toBe('prize-demo-001');
175
+ expect(calls[0]?.q.subjectId).toBe('2088000000000001');
176
+ });
177
+
178
+ it('prizeRecordRef 原字符串收参(『001』『1.20』『 record-001 』不折叠);标识原样达 Port', async () => {
179
+ for (const ref of ['001', '1.20', ' record-001 ']) {
180
+ const { calls, port } = listPort([{ ...DETAIL, prizeRecordRef: ref }]);
181
+ const { tools } = makeHarness(port);
182
+ const result = await tools.getMyPrizeDetail.execute!({ prizeRecordRef: ref }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
183
+ expect((result as { prizeRecordRef?: string })['prizeRecordRef']).toBe(ref);
184
+ expect(calls[0]?.ref).toBe(ref);
185
+ }
186
+ });
187
+
188
+ it('不存在/不可见 → PRIZE_NOT_FOUND 失败事实、无 cards(不误称可读他人记录)', async () => {
189
+ const { port } = listPort([]);
190
+ const { tools } = makeHarness(port);
191
+ const result = await tools.getMyPrizeDetail.execute!({ prizeRecordRef: 'prize-none' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
192
+ expect(result['found']).toBe(false);
193
+ expect(result['errorCode']).toBe('PRIZE_NOT_FOUND');
194
+ expect(result['cards']).toBeUndefined();
195
+ });
196
+
197
+ it('标识非法(全空白)→ INVALID_REQUEST 失败事实(与 HTTP 同参同果)', async () => {
198
+ const { port } = listPort([DETAIL]);
199
+ const { tools } = makeHarness(port);
200
+ const result = await tools.getMyPrizeDetail.execute!({ prizeRecordRef: ' ' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
201
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
202
+ });
203
+ });
204
+
205
+ describe('运行上下文读取(平台语义保留——认证错误不进 502 兜底)', () => {
206
+ it('缺运行上下文 → requireToolRequestContext 抛平台 AuthError(非工具失败事实)', async () => {
207
+ const { port } = listPort([RECORD]);
208
+ const { tools } = makeHarness(port);
209
+ // 无 requestContext 的 execCtx:getToolRequestContext → undefined → AuthError
210
+ await expect(
211
+ tools.listMyPrizes.execute!({}, {} as never),
212
+ ).rejects.toMatchObject({ name: 'AuthError' });
213
+ // 同纪律单点确认:读取器本身对空 execCtx 的行为
214
+ expect(() => requireToolRequestContext(undefined, 'x')).toThrow();
215
+ });
216
+ });