@tbox.cn/app-provider-mock 0.2.0 → 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.
- package/README.md +38 -0
- package/dist/server/index.d.ts +38 -64
- package/dist/server/index.js +269 -136
- package/package.json +6 -5
- package/schemas/mall-info.config.json +11 -0
- package/schemas/member.config.json +13 -0
- package/schemas/parking.config.json +19 -0
- package/schemas/promotion.config.json +13 -0
- package/schemas/shopping.config.json +12 -0
- package/src/server/config.ts +26 -0
- package/src/server/index.ts +39 -16
- package/src/server/mall-info.ts +27 -12
- package/src/server/member.ts +45 -17
- package/src/server/mock-enroll-route.ts +11 -10
- package/src/server/parking.ts +78 -49
- package/src/server/promotion.ts +77 -56
- package/src/server/shopping.ts +41 -3
- package/tbox.module.json +36 -17
- package/tests/config-schema.test.ts +92 -0
- package/tests/integrations-e2e.test.ts +164 -30
- package/tests/mall-info.test.ts +11 -2
- package/tests/mock-impl.test.ts +121 -18
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"title": "Mock 会员域实例配置",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"properties": {
|
|
6
|
+
"memberName": { "type": "string", "title": "会员名称", "description": "资料标签展示", "default": "示例会员" },
|
|
7
|
+
"cardName": { "type": "string", "title": "会员卡名称", "description": "卡面与积分标签", "default": "示例会员卡" },
|
|
8
|
+
"levelName": { "type": "string", "title": "等级名称", "description": "空串 = 不展示等级区", "default": "" },
|
|
9
|
+
"initialPoints": { "type": "integer", "minimum": 0, "title": "初始积分", "description": "入会后余额;流水金额同源派生", "default": 300 },
|
|
10
|
+
"enrollUrl": { "type": "string", "title": "入会落地页深链", "description": "alipays:// 或 H5", "default": "alipays://platformapi/startapp?appId=demo&page=v/index/index" },
|
|
11
|
+
"loginUrl": { "type": "string", "title": "登录页深链", "description": "alipays:// 或 H5", "default": "alipays://platformapi/startapp?appId=demo&page=v/login/index" }
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"title": "Mock 停车域实例配置",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"properties": {
|
|
6
|
+
"parkName": { "type": "string", "title": "停车场名称", "description": "信息卡标题 + 缴费记录", "default": "示例停车场" },
|
|
7
|
+
"feeName": { "type": "string", "title": "费用项名称", "default": "停车费(3 小时)" },
|
|
8
|
+
"feeCents": { "type": "integer", "minimum": 0, "title": "停车费(分)", "default": 1500 },
|
|
9
|
+
"remainingSpaces": { "type": "integer", "minimum": 0, "title": "剩余车位", "default": 128 },
|
|
10
|
+
"firstHourRate": { "type": "string", "title": "首小时费率文案", "default": "免费" },
|
|
11
|
+
"memberBenefitEnabled": { "type": "boolean", "title": "会员折扣权益开关", "description": "关闭 = 权益列表少一项 + reprice 不变", "default": true },
|
|
12
|
+
"memberBenefitDiscountCents": { "type": "integer", "minimum": 0, "title": "会员折扣权益预估减免(分)", "default": 75 },
|
|
13
|
+
"pointsBenefitEnabled": { "type": "boolean", "title": "积分抵扣权益开关", "description": "关闭 = 权益列表少「积分抵 5 元」项(积分入口)", "default": true },
|
|
14
|
+
"invoiceEnabled": { "type": "boolean", "title": "开票入口开关", "description": "关闭 = 缴费卡无开票按钮", "default": true },
|
|
15
|
+
"vehicleFloor": { "type": "string", "title": "寻车楼层", "default": "B1" },
|
|
16
|
+
"vehicleZone": { "type": "string", "title": "寻车区域", "default": "A 区" },
|
|
17
|
+
"vehicleSpaceNo": { "type": "string", "title": "寻车车位号", "default": "A-128" }
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"title": "Mock 营销域实例配置",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"properties": {
|
|
6
|
+
"couponTitle": { "type": "string", "title": "券标题", "description": "列表/详情/资产同源", "default": "满 100 减 20 元券" },
|
|
7
|
+
"couponValueCents": { "type": "integer", "minimum": 0, "title": "券面额(分)", "default": 2000 },
|
|
8
|
+
"couponThresholdCents": { "type": "integer", "minimum": 0, "title": "券门槛(分)", "default": 10000 },
|
|
9
|
+
"couponValidityDays": { "type": "integer", "minimum": 1, "maximum": 365, "title": "券有效期(天)", "default": 30 },
|
|
10
|
+
"grouponEnabled": { "type": "boolean", "title": "团购演示项开关", "description": "关闭 = 优惠列表仅券", "default": true },
|
|
11
|
+
"activityTitle": { "type": "string", "title": "活动标题", "default": "示例商场周年庆" }
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"title": "Mock 导购域实例配置",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"properties": {
|
|
6
|
+
"extraShopName": { "type": "string", "title": "追加门店名", "description": "空串 = 不追加", "default": "" },
|
|
7
|
+
"extraShopCategory": { "type": "string", "title": "追加门店类目", "default": "餐饮" },
|
|
8
|
+
"extraShopFloor": { "type": "string", "enum": ["B1", "1 楼", "2 楼", "3 楼", "4 楼"], "title": "追加门店楼层", "default": "3 楼" },
|
|
9
|
+
"extraShopUnit": { "type": "string", "title": "追加门店铺位号", "default": "304" },
|
|
10
|
+
"extraShopOpen": { "type": "boolean", "title": "追加门店营业状态", "default": true }
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mock 实例配置快照(fail-soft 单源):provider-mock 全部 config 消费的唯一读取面。
|
|
3
|
+
* - 只透出 defaults 键(构造性防死字段);defaults 键 ≡ 被消费键;
|
|
4
|
+
* - 非法回退缺省:类型族不符 / NaN / intKeys 键非整数 / 空串(统一「空串 = 缺省」语义);
|
|
5
|
+
* - intKeys 显式列举而非按 default 值推断(JS 中 30.0 === 30,推断式必误拒分式经纬度);
|
|
6
|
+
* - schema 是表单引导非门禁——守卫在消费侧(五层浅合并由平台侧完成,本层零合并逻辑)。
|
|
7
|
+
* 双锁测试(tests/config-schema.test.ts)保证 schema.properties ≡ DEFAULTS 键集与 default 值。
|
|
8
|
+
*/
|
|
9
|
+
export type CfgDefaults = Readonly<Record<string, string | number | boolean>>;
|
|
10
|
+
|
|
11
|
+
export function resolveConfig<T extends CfgDefaults>(
|
|
12
|
+
raw: unknown,
|
|
13
|
+
defaults: T,
|
|
14
|
+
intKeys: readonly string[] = [],
|
|
15
|
+
): T {
|
|
16
|
+
const src = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
|
17
|
+
const out: Record<string, string | number | boolean> = {};
|
|
18
|
+
for (const [key, fallback] of Object.entries(defaults)) {
|
|
19
|
+
const value = src[key];
|
|
20
|
+
const ok = typeof value === typeof fallback
|
|
21
|
+
&& (typeof value !== 'number' || (Number.isFinite(value) && (!intKeys.includes(key) || Number.isInteger(value))))
|
|
22
|
+
&& (typeof value !== 'string' || value !== '');
|
|
23
|
+
out[key] = ok ? (value as string | number | boolean) : fallback;
|
|
24
|
+
}
|
|
25
|
+
return out as T;
|
|
26
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -12,21 +12,29 @@
|
|
|
12
12
|
* (catalog 空 + shop/category/directory 纯 mock 数据);assistance/navigation 本地知识库域
|
|
13
13
|
* 归模块本地 adapter,不属 provider 供给面。
|
|
14
14
|
*
|
|
15
|
+
* config 消费:五域工厂透传 input.config → 各 impl 构造期 fail-soft 快照
|
|
16
|
+
* (src/server/config.ts;键集/缺省双锁 tests/config-schema.test.ts);零配置 = 零行为变化。
|
|
17
|
+
*
|
|
18
|
+
* 隐式默认单实例(零拓扑部署兜底):register 期经 ctx.integrations.declareProviderInstances
|
|
19
|
+
* 声明 mall-demo——显式 instances/defaultInstanceId 恒赢(融合规则见 contracts-mall
|
|
20
|
+
* mallControlPlaneOf);值与 .real-env mock 档演示语义一致(星河 Mock 小镇 / mock-demo-app)。
|
|
21
|
+
*
|
|
15
22
|
* 入会体验闭环(C5)追加两件:
|
|
16
|
-
* - scoped mock 换码器(ctx.authExchanges
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
23
|
+
* - scoped mock 换码器(ctx.authExchanges):随机访客身份(guest_<32hex>,统一登录改造
|
|
24
|
+
* T17——固定 demo-user 共享身份退役)、GUEST/MEMBER 双形态对齐真实厂商换码协议
|
|
25
|
+
* (潜客 token=''+openid ↔ 会员 token+memberId)——mock 档冷登走与真实档同一条换码链,
|
|
26
|
+
* H5 侧代码零分叉。会话连续性由 previousIdentity 复用轨(previousToken source=guest
|
|
27
|
+
* 同 sub 续签)保证。
|
|
20
28
|
* - mock 入会落地路由(ctx.routes):POST /demo/member-enroll(容器 mock-enrollment 页
|
|
21
29
|
* 回调 + curl 联调)。
|
|
22
30
|
*/
|
|
31
|
+
import { randomBytes } from 'node:crypto';
|
|
23
32
|
import type { ServerContext, ServerModule } from '@tbox.cn/app-sdk/server';
|
|
24
33
|
import type { ServiceAdapterFactory } from '@tbox.cn/app-sdk/server';
|
|
25
34
|
import type { ExchangeResult } from '@tbox.cn/app-contracts';
|
|
26
35
|
import { readLoginMallId } from '@tbox.cn/app-contracts-mall';
|
|
27
36
|
import {
|
|
28
37
|
MockMemberServiceImpl,
|
|
29
|
-
MOCK_SHELL_USER_ID,
|
|
30
38
|
isMockMemberEnrolled,
|
|
31
39
|
isMockMemberLoggedOut,
|
|
32
40
|
} from './member';
|
|
@@ -49,9 +57,9 @@ export { MockShoppingServiceImpl } from './shopping';
|
|
|
49
57
|
export { MOCK_MALL_INFO_PROVIDER, MOCK_MALL_INFO_IMPL, mockMallInfoFactory } from './mall-info';
|
|
50
58
|
export { createMockEnrollRouter } from './mock-enroll-route';
|
|
51
59
|
|
|
52
|
-
const memberFactory: ServiceAdapterFactory = () => new MockMemberServiceImpl();
|
|
53
|
-
const parkingFactory: ServiceAdapterFactory = (input) => new MockParkingServiceImpl(input.instanceId || 'mall-demo');
|
|
54
|
-
const promotionFactory: ServiceAdapterFactory = () => new MockPromotionServiceImpl();
|
|
60
|
+
const memberFactory: ServiceAdapterFactory = (input) => new MockMemberServiceImpl({}, input.config);
|
|
61
|
+
const parkingFactory: ServiceAdapterFactory = (input) => new MockParkingServiceImpl(input.instanceId || 'mall-demo', input.config);
|
|
62
|
+
const promotionFactory: ServiceAdapterFactory = (input) => new MockPromotionServiceImpl(input.config);
|
|
55
63
|
/** shopping-guide:四槽分支(017 槽位原子化)——MockShoppingServiceImpl 实现全部四 Port,
|
|
56
64
|
* 结构类型满足任一槽产物(catalog 槽 = mock 空商品数据,对齐真实档无商品端点形态)。 */
|
|
57
65
|
const shoppingFactory: ServiceAdapterFactory = (input) => {
|
|
@@ -63,7 +71,7 @@ const shoppingFactory: ServiceAdapterFactory = (input) => {
|
|
|
63
71
|
) {
|
|
64
72
|
throw new Error(`mock guide 工厂不供给槽:${input.service}`);
|
|
65
73
|
}
|
|
66
|
-
return new MockShoppingServiceImpl();
|
|
74
|
+
return new MockShoppingServiceImpl(undefined, input.config);
|
|
67
75
|
};
|
|
68
76
|
/** mall.info:动态商场演示源(任意合法 mallId → 确定性别名;对齐真实厂商 mall-info adapter 通用形态) */
|
|
69
77
|
const mallInfoFactory: ServiceAdapterFactory = (input) => mockMallInfoFactory(input);
|
|
@@ -74,11 +82,20 @@ const mallInfoFactory: ServiceAdapterFactory = (input) => mockMallInfoFactory(in
|
|
|
74
82
|
* 为语义锚;mock 档无独立 auth 槽;无条件兜底位归部署装配的自定义换码器,本候选恒
|
|
75
83
|
* scoped 层 first-match)。authCode 忽略(mock 语义:单 demo 用户/部署,无真实授权码可换)。
|
|
76
84
|
* 统一范式:context 无 mallId(未选择商场)→ 命中本候选,exchangeByCode 显性抛错,
|
|
77
|
-
* 不落内置本地 alipay(缺 env
|
|
85
|
+
* 不落内置本地 alipay(缺 env 报错会误导部署)。
|
|
86
|
+
*
|
|
87
|
+
* 随机访客身份(统一登录改造 T17):mock 档壳内登录恒服务端随机(guest_<32hex>,
|
|
88
|
+
* source 'guest')——固定 demo-user 共享身份退役。会话连续性(enroll 后 MEMBER 形态、
|
|
89
|
+
* 记忆归属)由 previousIdentity 复用轨保证:客户端 previousToken 上送 → previousIdentity
|
|
90
|
+
* source=guest 时同 sub 续签(真实厂商忽略,mock 换码器是唯一复用消费方)。
|
|
78
91
|
*/
|
|
79
92
|
function createMockAlipayLoginExchange(integrations: ServerContext['integrations']) {
|
|
80
93
|
return {
|
|
81
94
|
provider: 'alipay' as const,
|
|
95
|
+
/** 裸/demo 域默认开放 guest 登录(browser 轴 auto 档 → guest 签发) */
|
|
96
|
+
allowsGuestLogin() {
|
|
97
|
+
return true;
|
|
98
|
+
},
|
|
82
99
|
matches(context?: Readonly<Record<string, unknown>>) {
|
|
83
100
|
const mallId = readLoginMallId(context);
|
|
84
101
|
// 未选择商场(context 无 mallId)→ 命中本换码器,由 exchangeByCode 显性抛
|
|
@@ -89,22 +106,23 @@ function createMockAlipayLoginExchange(integrations: ServerContext['integrations
|
|
|
89
106
|
return integrations.hasProviderBinding('member.account', { mallId }, MOCK_PROVIDER, MOCK_MEMBER_IMPL);
|
|
90
107
|
},
|
|
91
108
|
async exchangeByCode(
|
|
92
|
-
|
|
93
|
-
_platform?: string,
|
|
94
|
-
context?: Readonly<Record<string, unknown>>,
|
|
109
|
+
{ context, previousIdentity }: { context?: Readonly<Record<string, unknown>>; previousIdentity?: { userId: string; source: string } },
|
|
95
110
|
): Promise<ExchangeResult> {
|
|
96
111
|
// 未选择商场前置校验(与 matches 语义一致:域缺失显性报错,不产出 demo 身份)
|
|
97
112
|
if (!readLoginMallId(context)) {
|
|
98
113
|
throw new Error('AUTH_NOT_CONFIGURED: 未选择商场(登录 context 无 mallId)');
|
|
99
114
|
}
|
|
100
|
-
|
|
115
|
+
// 随机访客身份(previousToken 复用轨:guest 同 sub 续签)
|
|
116
|
+
const userId = previousIdentity?.source === 'guest'
|
|
117
|
+
? previousIdentity.userId
|
|
118
|
+
: `guest_${randomBytes(16).toString('hex')}`;
|
|
101
119
|
// 会员形态需登录态健康:登出态(loggedOut)降级 GUEST 形态——对齐真实档 silentLogin 信封
|
|
102
120
|
// 非 200 降级(2026-09-02 真机实测):登出后换码 = 潜客同构结果(token=''),H5 侧
|
|
103
121
|
// not_enrolled → 入会引导卡 → 半屏 getLoginState 闭环恢复;enroll 清登出态后冷登回 MEMBER。
|
|
104
122
|
if (isMockMemberEnrolled(userId) && !isMockMemberLoggedOut(userId)) {
|
|
105
123
|
// MEMBER 形态(对齐真实档会员换码输出):token + memberId 随 attributes 流动
|
|
106
124
|
return {
|
|
107
|
-
identity: { userId, source: '
|
|
125
|
+
identity: { userId, source: 'guest' as const },
|
|
108
126
|
credentials: {
|
|
109
127
|
token: `demo:token:${userId}`,
|
|
110
128
|
provider: 'mock',
|
|
@@ -115,7 +133,7 @@ function createMockAlipayLoginExchange(integrations: ServerContext['integrations
|
|
|
115
133
|
// GUEST 形态(对齐真实档潜客分支):token='' + openid 身份——「合法登录未入会」;
|
|
116
134
|
// 登出降级同走此构造(单源)。真实档另携 visitortoken,mock 链路无消费方故极简。
|
|
117
135
|
return {
|
|
118
|
-
identity: { userId, source: '
|
|
136
|
+
identity: { userId, source: 'guest' as const },
|
|
119
137
|
credentials: {
|
|
120
138
|
token: '',
|
|
121
139
|
provider: 'mock',
|
|
@@ -134,6 +152,11 @@ export const serverModule = {
|
|
|
134
152
|
},
|
|
135
153
|
cards,
|
|
136
154
|
register(ctx: ServerContext): void {
|
|
155
|
+
// 隐式默认单实例声明(零拓扑部署兜底——显式 instances/defaultInstanceId 恒赢;
|
|
156
|
+
// 融合规则见 contracts-mall mallControlPlaneOf。?. 兼容旧 SDK:缺 API 时 no-op 降级)
|
|
157
|
+
ctx.integrations?.declareProviderInstances?.('mock', [
|
|
158
|
+
{ id: 'mall-demo', name: '星河 Mock 小镇', attributes: { miniAppId: 'mock-demo-app' } },
|
|
159
|
+
]);
|
|
137
160
|
// adapter 注册(v2 双键:provider 厂商名 + implementation)
|
|
138
161
|
ctx.integrations?.registerAdapter(MOCK_PROVIDER, MOCK_MEMBER_IMPL, memberFactory);
|
|
139
162
|
ctx.integrations?.registerAdapter(MOCK_PROVIDER, MOCK_PARKING_IMPL, parkingFactory);
|
package/src/server/mall-info.ts
CHANGED
|
@@ -9,26 +9,41 @@
|
|
|
9
9
|
* - mallId 形状守卫(/^[\w-]{1,32}$/):畸形 ID 直接返回 undefined(S4 DoS 防线——
|
|
10
10
|
* 记录≠校验教训:请求形状断言在 provider adapter 单测锁死)
|
|
11
11
|
* - fail-soft 契约恒满足:本实现无 IO,不可能失败——契约面与真实档保持一致
|
|
12
|
+
* - config 消费:MALL_INFO_CFG_DEFAULTS 为契约单源(name 空串 = 动态别名回退;
|
|
13
|
+
* 双锁测试 tests/config-schema.test.ts)
|
|
12
14
|
*/
|
|
15
|
+
import { resolveConfig, type CfgDefaults } from './config';
|
|
13
16
|
import type { MallInfo, MallInfoPort } from '@tbox.cn/app-contracts-mall';
|
|
14
17
|
import type { ServiceAdapterFactory } from '@tbox.cn/app-sdk/server';
|
|
15
18
|
|
|
16
19
|
export const MOCK_MALL_INFO_PROVIDER = 'mock';
|
|
17
20
|
export const MOCK_MALL_INFO_IMPL = 'mock-mall-info@1';
|
|
18
21
|
|
|
22
|
+
/** config 契约单源(键集/缺省/整数约束;lat/lon 分式合法——不进 intKeys) */
|
|
23
|
+
export const MALL_INFO_CFG_DEFAULTS = {
|
|
24
|
+
name: '', // '' 哨兵 = 动态别名回退
|
|
25
|
+
address: '示例商场地址(demo)',
|
|
26
|
+
latitude: 30.0,
|
|
27
|
+
longitude: 120.0,
|
|
28
|
+
} as const satisfies CfgDefaults;
|
|
29
|
+
export const MALL_INFO_CFG_INT_KEYS: readonly string[] = [];
|
|
30
|
+
|
|
19
31
|
/** mallId 形状守卫(防注入类字符;畸形 → undefined——与真实厂商 adapter 同规则) */
|
|
20
32
|
const MALL_ID_RE = /^[\w-]{1,32}$/;
|
|
21
33
|
|
|
22
34
|
/** mock mall.info adapter 工厂(对齐真实厂商 adapter 工厂形态) */
|
|
23
|
-
export const mockMallInfoFactory: ServiceAdapterFactory = (): MallInfoPort =>
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
mallId
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
+
export const mockMallInfoFactory: ServiceAdapterFactory = (input): MallInfoPort => {
|
|
36
|
+
const cfg = resolveConfig(input.config, MALL_INFO_CFG_DEFAULTS, MALL_INFO_CFG_INT_KEYS);
|
|
37
|
+
return {
|
|
38
|
+
async getMallInfo(mallId: string): Promise<MallInfo | undefined> {
|
|
39
|
+
if (!MALL_ID_RE.test(mallId)) return undefined;
|
|
40
|
+
return {
|
|
41
|
+
mallId,
|
|
42
|
+
name: cfg.name !== '' ? cfg.name : `示例商场(${mallId})`,
|
|
43
|
+
address: cfg.address,
|
|
44
|
+
latitude: cfg.latitude,
|
|
45
|
+
longitude: cfg.longitude,
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
};
|
package/src/server/member.ts
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
* Mock member 实现(provider-mock 自持——R3-1 裁决:provider 不得依赖业务模块,实现自持
|
|
3
3
|
* 而非包装 module-member InMemory)。演示面最小集:开户/卡面/积分/流水/入会闭环
|
|
4
4
|
* (demo ref 恒 `demo:` 前缀,厂商中立)。
|
|
5
|
+
* config 消费:MEMBER_CFG_DEFAULTS 为契约单源(fail-soft 快照;双锁测试 tests/config-schema.test.ts)。
|
|
5
6
|
*/
|
|
7
|
+
import { resolveConfig, type CfgDefaults } from './config';
|
|
6
8
|
import type {
|
|
7
9
|
MemberAccountPort,
|
|
8
10
|
MemberAccountSnapshot,
|
|
@@ -27,9 +29,16 @@ export type MockMemberService = MemberAccountPort &
|
|
|
27
29
|
MemberBenefitsPort &
|
|
28
30
|
MemberEnrollmentPort;
|
|
29
31
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
/** config 契约单源(键集/缺省/整数约束;tests/config-schema.test.ts 双锁) */
|
|
33
|
+
export const MEMBER_CFG_DEFAULTS = {
|
|
34
|
+
memberName: '示例会员',
|
|
35
|
+
cardName: '示例会员卡',
|
|
36
|
+
levelName: '', // '' 哨兵 = 不展示等级区(MemberCardSnapshot.levelName 可选位)
|
|
37
|
+
initialPoints: 300,
|
|
38
|
+
enrollUrl: 'alipays://platformapi/startapp?appId=demo&page=v/index/index',
|
|
39
|
+
loginUrl: 'alipays://platformapi/startapp?appId=demo&page=v/login/index',
|
|
40
|
+
} as const satisfies CfgDefaults;
|
|
41
|
+
export const MEMBER_CFG_INT_KEYS = ['initialPoints'];
|
|
33
42
|
|
|
34
43
|
/**
|
|
35
44
|
* Mock member 状态单源(模块级共享):factory 每请求新建实例,但状态必须跨实例共享——
|
|
@@ -44,11 +53,11 @@ const mockMemberState = {
|
|
|
44
53
|
/** mock 壳侧登录用户(换码器固定身份;mock 语义 = 单 demo 用户/部署) */
|
|
45
54
|
export const MOCK_SHELL_USER_ID = 'demo-user';
|
|
46
55
|
|
|
47
|
-
/** 入会落地(幂等):enroll 路由/enroll()
|
|
56
|
+
/** 入会落地(幂等):enroll 路由/enroll() 共用;余额不写种子——查询侧按实例配置惰性读
|
|
57
|
+
*(默认 300,见 currentBalanceOf);登录成功即清除登出态 */
|
|
48
58
|
export function enrollMockMember(userId: string): void {
|
|
49
59
|
mockMemberState.enrolled.add(userId);
|
|
50
60
|
mockMemberState.loggedOut.delete(userId);
|
|
51
|
-
if (!mockMemberState.balances.has(userId)) mockMemberState.balances.set(userId, 300);
|
|
52
61
|
}
|
|
53
62
|
|
|
54
63
|
export function isMockMemberEnrolled(userId: string): boolean {
|
|
@@ -84,12 +93,23 @@ export class MockMemberServiceImpl implements MockMemberService {
|
|
|
84
93
|
* 透传素材,mock 出厂面恒配 demo 值)。demo 值厂商中立(appId=demo),点击在壳内
|
|
85
94
|
* navigateTo 失败即无害降级。
|
|
86
95
|
*/
|
|
87
|
-
readonly enrollUrl
|
|
96
|
+
readonly enrollUrl: string;
|
|
88
97
|
/** 登录页深链(同上,可选透传素材;供未登录引导卡跳转)。 */
|
|
89
|
-
readonly loginUrl
|
|
98
|
+
readonly loginUrl: string;
|
|
99
|
+
|
|
100
|
+
/** 配置快照(fail-soft,构造期一次解析;键集 ≡ MEMBER_CFG_DEFAULTS) */
|
|
101
|
+
private readonly cfg: typeof MEMBER_CFG_DEFAULTS;
|
|
102
|
+
/** 积分流水(金额随 initialPoints 派生——与余额同源) */
|
|
103
|
+
private readonly usage: PointUsageRecord[];
|
|
90
104
|
|
|
91
105
|
/** 默认访客(无种子):demo-user 初始 not_enrolled,经入会闭环翻为 active */
|
|
92
|
-
constructor(initial: Record<string, number> = {}) {
|
|
106
|
+
constructor(initial: Record<string, number> = {}, config: unknown = {}) {
|
|
107
|
+
this.cfg = resolveConfig(config, MEMBER_CFG_DEFAULTS, MEMBER_CFG_INT_KEYS);
|
|
108
|
+
this.enrollUrl = this.cfg.enrollUrl;
|
|
109
|
+
this.loginUrl = this.cfg.loginUrl;
|
|
110
|
+
this.usage = [
|
|
111
|
+
{ usageRecordRef: 'demo:usage:1', title: '开卡礼', amount: `+${String(this.cfg.initialPoints)}`, usedAt: new Date().toISOString(), description: 'mock 演示流水' },
|
|
112
|
+
];
|
|
93
113
|
for (const [userId, balance] of Object.entries(initial)) {
|
|
94
114
|
mockMemberState.enrolled.add(userId);
|
|
95
115
|
mockMemberState.balances.set(userId, balance);
|
|
@@ -107,30 +127,31 @@ export class MockMemberServiceImpl implements MockMemberService {
|
|
|
107
127
|
}
|
|
108
128
|
|
|
109
129
|
async getProfile(_userId: string): Promise<MemberProfileSnapshot> {
|
|
110
|
-
return { labels: [{ labelRef: 'demo:label:1', name:
|
|
130
|
+
return { labels: [{ labelRef: 'demo:label:1', name: this.cfg.memberName }], observedAt: new Date().toISOString() };
|
|
111
131
|
}
|
|
112
132
|
|
|
113
133
|
async getCard(userId: string): Promise<MemberCardSnapshot | null> {
|
|
114
134
|
if (!isMockMemberActive(userId)) return null;
|
|
115
135
|
return {
|
|
116
136
|
cardRef: `demo:card:${userId}`,
|
|
117
|
-
cardDisplay:
|
|
137
|
+
cardDisplay: this.cfg.cardName,
|
|
118
138
|
status: 'active',
|
|
139
|
+
...(this.cfg.levelName !== '' ? { levelName: this.cfg.levelName } : {}),
|
|
119
140
|
observedAt: new Date().toISOString(),
|
|
120
141
|
};
|
|
121
142
|
}
|
|
122
143
|
|
|
123
144
|
async queryPoints(userId: string): Promise<Points> {
|
|
124
|
-
return { userId, balance:
|
|
145
|
+
return { userId, balance: this.currentBalanceOf(userId), membershipLabel: this.cfg.cardName };
|
|
125
146
|
}
|
|
126
147
|
|
|
127
|
-
async getBenefits(
|
|
128
|
-
return { availablePoints:
|
|
148
|
+
async getBenefits(userId: string): Promise<MemberBenefitsSnapshot> {
|
|
149
|
+
return { availablePoints: this.currentBalanceOf(userId), levelName: '示例等级', observedAt: new Date().toISOString() };
|
|
129
150
|
}
|
|
130
151
|
|
|
131
152
|
async listPointUsage(_userId: string, page: number, pageSize: number) {
|
|
132
153
|
const start = (page - 1) * pageSize;
|
|
133
|
-
return { items:
|
|
154
|
+
return { items: this.usage.slice(start, start + pageSize), total: this.usage.length };
|
|
134
155
|
}
|
|
135
156
|
|
|
136
157
|
async queryDiscount(): Promise<DiscountRule | undefined> {
|
|
@@ -138,22 +159,29 @@ export class MockMemberServiceImpl implements MockMemberService {
|
|
|
138
159
|
}
|
|
139
160
|
|
|
140
161
|
async deductPoints(userId: string, amount: number, _key: string): Promise<boolean> {
|
|
141
|
-
const balance =
|
|
162
|
+
const balance = this.currentBalanceOf(userId);
|
|
142
163
|
if (balance < amount) return false;
|
|
143
164
|
mockMemberState.balances.set(userId, balance - amount);
|
|
144
165
|
return true;
|
|
145
166
|
}
|
|
146
167
|
|
|
147
168
|
async refundPoints(userId: string, amount: number, _key: string): Promise<boolean> {
|
|
148
|
-
mockMemberState.balances.set(userId,
|
|
169
|
+
mockMemberState.balances.set(userId, this.currentBalanceOf(userId) + amount);
|
|
149
170
|
return true;
|
|
150
171
|
}
|
|
151
172
|
|
|
152
173
|
async awardPoints(userId: string, amount: number): Promise<boolean> {
|
|
153
|
-
mockMemberState.balances.set(userId,
|
|
174
|
+
mockMemberState.balances.set(userId, this.currentBalanceOf(userId) + amount);
|
|
154
175
|
return true;
|
|
155
176
|
}
|
|
156
177
|
|
|
178
|
+
/** 余额单源:显式增减覆盖值 ??(已入会 ? 配置初值 : 0)——入会不写种子(惰性读) */
|
|
179
|
+
private currentBalanceOf(userId: string): number {
|
|
180
|
+
const override = mockMemberState.balances.get(userId);
|
|
181
|
+
if (override !== undefined) return override;
|
|
182
|
+
return isMockMemberEnrolled(userId) ? this.cfg.initialPoints : 0;
|
|
183
|
+
}
|
|
184
|
+
|
|
157
185
|
async enroll(input: MemberEnrollmentInput): Promise<MemberEnrollmentResult> {
|
|
158
186
|
enrollMockMember(input.userId);
|
|
159
187
|
return { status: 'active', memberRef: `demo:member:${input.userId}` };
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Mock 入会落地点路由(入会体验闭环 C5):POST /api/m/provider-mock/demo/member-enroll。
|
|
3
3
|
*
|
|
4
4
|
* 容器 mock-enrollment 页(dev 脚手架)与 curl 联调共用:
|
|
5
|
-
* - body `{userId?}`:缺省
|
|
6
|
-
*
|
|
5
|
+
* - body `{userId?}`:缺省 = 调用方 token 身份(统一登录改造 T11 收口——固定 demo-user
|
|
6
|
+
* 缺省退役,IDOR 写任意用户面收窄为「已鉴权调用方声明 demo 主体」;gate 页经 query
|
|
7
|
+
* 透传 H5 身份,curl 可定向翻指定访客造会员态调试)。
|
|
7
8
|
* - 幂等(Set.add / 余额保守写);NODE_ENV=production → 503(provider-mock 不进生产装配,双保险)。
|
|
8
|
-
* - 经全局 /api 鉴权(AUTH_MODE 缺省 required
|
|
9
|
+
* - 经全局 /api 鉴权(AUTH_MODE 缺省 required)——调用方须携登录令牌;
|
|
9
10
|
* 匿名写显式拒绝(不随 AUTH_MODE 放宽)。
|
|
10
11
|
* - doctor naked-write-route:/demo 前缀在白名单内(webhook/upload/demo/run)。
|
|
11
12
|
*
|
|
@@ -14,17 +15,17 @@
|
|
|
14
15
|
import { Router } from 'express';
|
|
15
16
|
import type { Request, Response } from 'express';
|
|
16
17
|
import { getRequestContext } from '@tbox.cn/app-sdk/server';
|
|
17
|
-
import {
|
|
18
|
+
import { enrollMockMember, logoutMockMember } from './member';
|
|
18
19
|
|
|
19
20
|
export type MockEnrollOutcome =
|
|
20
21
|
| { status: 200; body: { state: 'active'; memberRef: string } }
|
|
21
22
|
| { status: 401; body: { error: string } }
|
|
22
23
|
| { status: 503; body: { error: string } };
|
|
23
24
|
|
|
24
|
-
/** 纯决策:production 拒 503 → 匿名/无身份拒 401 → 翻状态返 200
|
|
25
|
+
/** 纯决策:production 拒 503 → 匿名/无身份拒 401 → 翻状态返 200(幂等;主体缺省 = 调用方) */
|
|
25
26
|
export function resolveMockEnroll(input: {
|
|
26
27
|
body?: unknown;
|
|
27
|
-
identity?: { source: string } | null;
|
|
28
|
+
identity?: { source: string; userId?: string } | null;
|
|
28
29
|
nodeEnv?: string;
|
|
29
30
|
}): MockEnrollOutcome {
|
|
30
31
|
if ((input.nodeEnv ?? process.env.NODE_ENV) === 'production') {
|
|
@@ -36,7 +37,7 @@ export function resolveMockEnroll(input: {
|
|
|
36
37
|
const body = (input.body ?? {}) as { userId?: unknown };
|
|
37
38
|
const userId = typeof body.userId === 'string' && body.userId.trim()
|
|
38
39
|
? body.userId.trim()
|
|
39
|
-
:
|
|
40
|
+
: (input.identity.userId ?? `guest_${Date.now()}`);
|
|
40
41
|
enrollMockMember(userId);
|
|
41
42
|
return { status: 200, body: { state: 'active', memberRef: `demo:member:${userId}` } };
|
|
42
43
|
}
|
|
@@ -46,10 +47,10 @@ export type MockLogoutOutcome =
|
|
|
46
47
|
| { status: 401; body: { error: string } }
|
|
47
48
|
| { status: 503; body: { error: string } };
|
|
48
49
|
|
|
49
|
-
/** 纯决策:production 拒 503 → 匿名/无身份拒 401 → 翻登出态返 200(与 enroll
|
|
50
|
+
/** 纯决策:production 拒 503 → 匿名/无身份拒 401 → 翻登出态返 200(与 enroll 同形;主体缺省 = 调用方) */
|
|
50
51
|
export function resolveMockLogout(input: {
|
|
51
52
|
body?: unknown;
|
|
52
|
-
identity?: { source: string } | null;
|
|
53
|
+
identity?: { source: string; userId?: string } | null;
|
|
53
54
|
nodeEnv?: string;
|
|
54
55
|
}): MockLogoutOutcome {
|
|
55
56
|
if ((input.nodeEnv ?? process.env.NODE_ENV) === 'production') {
|
|
@@ -61,7 +62,7 @@ export function resolveMockLogout(input: {
|
|
|
61
62
|
const body = (input.body ?? {}) as { userId?: unknown };
|
|
62
63
|
const userId = typeof body.userId === 'string' && body.userId.trim()
|
|
63
64
|
? body.userId.trim()
|
|
64
|
-
:
|
|
65
|
+
: (input.identity.userId ?? `guest_${Date.now()}`);
|
|
65
66
|
logoutMockMember(userId);
|
|
66
67
|
return { status: 200, body: { state: 'logged_out' } };
|
|
67
68
|
}
|