@tbox.cn/app-module-shopping-guide 0.2.1

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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunk-AGBLC6XI.js +1294 -0
  3. package/dist/chunk-U4WDS5PQ.js +173 -0
  4. package/dist/client/index.d.ts +25 -0
  5. package/dist/client/index.js +6 -0
  6. package/dist/index.d.ts +8 -0
  7. package/dist/index.js +22 -0
  8. package/dist/server/index.d.ts +4098 -0
  9. package/dist/server/index.js +18 -0
  10. package/package.json +62 -0
  11. package/skills/shopping-guide/SKILL.md +36 -0
  12. package/skills/shopping-guide/references/comparison-format.md +5 -0
  13. package/skills/shopping-guide/references/faq-answers.md +5 -0
  14. package/skills/shopping-guide/references/floor-directory.md +4 -0
  15. package/skills/shopping-guide/references/intent-patterns.md +5 -0
  16. package/skills/shopping-guide/references/location-format.md +5 -0
  17. package/skills/shopping-guide/references/policy-lookup.md +5 -0
  18. package/skills/shopping-guide/references/product-search-tips.md +6 -0
  19. package/skills/shopping-guide/references/recommendation-style.md +5 -0
  20. package/src/client/cards/index.tsx +267 -0
  21. package/src/client/index.ts +39 -0
  22. package/src/index.ts +6 -0
  23. package/src/server/cards/category-list/meta.ts +19 -0
  24. package/src/server/cards/customer-service-faq/meta.ts +18 -0
  25. package/src/server/cards/human-guide-list/meta.ts +19 -0
  26. package/src/server/cards/index.ts +43 -0
  27. package/src/server/cards/location-handoff/meta.ts +20 -0
  28. package/src/server/cards/mall-directory/meta.ts +27 -0
  29. package/src/server/cards/merchant-detail/meta.ts +27 -0
  30. package/src/server/cards/merchant-list/meta.ts +31 -0
  31. package/src/server/cards/nearby-mall-list/meta.ts +17 -0
  32. package/src/server/cards/product-comparison/meta.ts +29 -0
  33. package/src/server/cards/product-detail/meta.ts +29 -0
  34. package/src/server/cards/product-list/meta.ts +32 -0
  35. package/src/server/domain/value-objects.ts +49 -0
  36. package/src/server/index.ts +180 -0
  37. package/src/server/integrations/joycity/adapter.ts +226 -0
  38. package/src/server/integrations/joycity/auth-strategy.ts +38 -0
  39. package/src/server/integrations/joycity/gateway.ts +128 -0
  40. package/src/server/ports/index.ts +151 -0
  41. package/src/server/ports/local-adapters.ts +90 -0
  42. package/src/server/projections/index.ts +253 -0
  43. package/src/server/tools/index.ts +407 -0
  44. package/tbox.component.json +48 -0
  45. package/tests/shopping-guide.test.ts +290 -0
  46. package/tsconfig.json +8 -0
  47. package/tsup.config.ts +29 -0
@@ -0,0 +1,31 @@
1
+ import type { CardMeta } from '@tbox.cn/app-contracts';
2
+ import { merchantListCardDataSchema } from '@tbox.cn/app-contracts-mall';
3
+ import { nowIso } from '../../domain/value-objects';
4
+
5
+ const meta: CardMeta<typeof merchantListCardDataSchema> = {
6
+ cardType: 'merchant-list',
7
+ dataSchema: merchantListCardDataSchema,
8
+ allowedTools: ['search-merchants'],
9
+ displayName: '门店列表',
10
+ description: '推荐/搜索门店列表(含位置、营业状态、促销)',
11
+ sampleData: {
12
+ context: 'search',
13
+ items: [
14
+ {
15
+ merchantId: 'm1',
16
+ name: '示例门店',
17
+ businessCategories: ['餐饮'],
18
+ location: { displayText: 'A 栋 3 楼 301' },
19
+ status: { code: 'enabled', label: '营业中', observedAt: nowIso() },
20
+ services: ['堂食'],
21
+ promotionFacts: ['会员 9 折'],
22
+ itemActions: [],
23
+ },
24
+ ],
25
+ refinements: [],
26
+ },
27
+ priority: 90,
28
+ schemaVersion: 1,
29
+ };
30
+
31
+ export default meta;
@@ -0,0 +1,17 @@
1
+ import type { CardMeta } from '@tbox.cn/app-contracts';
2
+ import { nearbyMallListCardDataSchema } from '@tbox.cn/app-contracts-mall';
3
+
4
+ const meta: CardMeta<typeof nearbyMallListCardDataSchema> = {
5
+ cardType: 'nearby-mall-list',
6
+ dataSchema: nearbyMallListCardDataSchema,
7
+ allowedTools: ['list-nearby-malls'],
8
+ displayName: '附近商场',
9
+ description: '附近可切换的大悦城门店列表',
10
+ sampleData: {
11
+ malls: [{ mallId: 'mall-1', name: '示例商场', address: '示例地址', status: { code: 'open', label: '营业中' }, itemActions: [] }],
12
+ },
13
+ priority: 100,
14
+ schemaVersion: 1,
15
+ };
16
+
17
+ export default meta;
@@ -0,0 +1,29 @@
1
+ import type { CardMeta } from '@tbox.cn/app-contracts';
2
+ import { productComparisonCardDataSchema } from '@tbox.cn/app-contracts-mall';
3
+ import { nowIso } from '../../domain/value-objects';
4
+
5
+ const meta: CardMeta<typeof productComparisonCardDataSchema> = {
6
+ cardType: 'product-comparison',
7
+ dataSchema: productComparisonCardDataSchema,
8
+ allowedTools: ['compare-products'],
9
+ displayName: '商品对比',
10
+ description: '2-4 个商品价格/属性/库存并排对比',
11
+ sampleData: {
12
+ products: [
13
+ {
14
+ productId: 'p1',
15
+ name: '商品 A',
16
+ price: {},
17
+ availability: { status: 'unknown', label: '未知', marketable: false, observedAt: nowIso() },
18
+ merchant: { merchantId: 'm1', name: '门店' },
19
+ attributes: [],
20
+ caveats: [],
21
+ },
22
+ ],
23
+ observedAt: nowIso(),
24
+ },
25
+ priority: 120,
26
+ schemaVersion: 1,
27
+ };
28
+
29
+ export default meta;
@@ -0,0 +1,29 @@
1
+ import type { CardMeta } from '@tbox.cn/app-contracts';
2
+ import { productDetailCardDataSchema } from '@tbox.cn/app-contracts-mall';
3
+ import { nowIso } from '../../domain/value-objects';
4
+
5
+ const meta: CardMeta<typeof productDetailCardDataSchema> = {
6
+ cardType: 'product-detail',
7
+ dataSchema: productDetailCardDataSchema,
8
+ allowedTools: ['get-product'],
9
+ displayName: '商品详情',
10
+ description: '单个商品的完整快照(价格/库存/属性/商户)',
11
+ sampleData: {
12
+ productId: 'p1',
13
+ name: '示例跑鞋',
14
+ imageUrls: [],
15
+ categoryPath: ['运动'],
16
+ price: {},
17
+ availability: { status: 'unknown', label: '未知', marketable: false, observedAt: nowIso() },
18
+ merchant: { merchantId: 'm1', name: '示例门店' },
19
+ attributes: [],
20
+ promotionFacts: [],
21
+ evidence: [],
22
+ humanGuideAvailable: false,
23
+ itemActions: [],
24
+ },
25
+ priority: 80,
26
+ schemaVersion: 1,
27
+ };
28
+
29
+ export default meta;
@@ -0,0 +1,32 @@
1
+ import type { CardMeta } from '@tbox.cn/app-contracts';
2
+ import { productListCardDataSchema } from '@tbox.cn/app-contracts-mall';
3
+ import { nowIso } from '../../domain/value-objects';
4
+
5
+ const meta: CardMeta<typeof productListCardDataSchema> = {
6
+ cardType: 'product-list',
7
+ dataSchema: productListCardDataSchema,
8
+ allowedTools: ['recommend', 'search-products', 'list-browsing-history'],
9
+ displayName: '商品列表',
10
+ description: '推荐/搜索/历史商品列表(含价格、库存、门店)',
11
+ sampleData: {
12
+ context: 'search',
13
+ items: [
14
+ {
15
+ productId: 'p1',
16
+ name: '示例跑鞋',
17
+ categoryPath: ['运动', '跑步'],
18
+ price: { sale: { currency: 'CNY', amountMinor: 39900, display: '¥399.00' } },
19
+ availability: { status: 'in_stock', label: '有货', marketable: true, observedAt: nowIso() },
20
+ merchant: { merchantId: 'm1', name: '示例门店' },
21
+ badges: ['热卖'],
22
+ caveats: [],
23
+ itemActions: [],
24
+ },
25
+ ],
26
+ refinements: [],
27
+ },
28
+ priority: 90,
29
+ schemaVersion: 1,
30
+ };
31
+
32
+ export default meta;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * 导购域值对象与运行时上下文(011 S7)。
3
+ * 域模型类型直接复用 contracts-mall Port 的 record 类型(TIER1 单一来源),
4
+ * 模块内不重复声明领域形状。
5
+ *
6
+ * 011 评审 6.1/6.2:scope 解析一律经 TIER1 parseMallScope(不手解 attributes 原始形状);
7
+ * toShoppingQueryContext 显式存在性检查(无 mall scope → 清晰错误,替代 as never 类型逃逸)。
8
+ */
9
+ import type {
10
+ MallRequestContext,
11
+ MallScope,
12
+ ShoppingQueryContext,
13
+ } from '@tbox.cn/app-contracts-mall';
14
+ import { parseMallScope } from '@tbox.cn/app-contracts-mall';
15
+ import type { RequestContext } from '@tbox.cn/app-contracts';
16
+
17
+ /** 从 RequestContext 构造 ShoppingQueryContext(handler/tool 内调用)。
18
+ * 无合法 mall scope → 抛错(mall 域工具只应在 mall 会话内执行)。 */
19
+ export function toShoppingQueryContext(
20
+ requestContext: RequestContext,
21
+ subjectId?: string,
22
+ ): ShoppingQueryContext {
23
+ const scope = parseMallScope(requestContext.attributes);
24
+ if (!scope) {
25
+ throw new Error('缺少 mall scope(工具需在 mall 会话内调用)');
26
+ }
27
+ return {
28
+ scope,
29
+ ...(subjectId ? { subjectId } : {}),
30
+ requestContext: requestContext as unknown as MallRequestContext,
31
+ };
32
+ }
33
+
34
+ /** 工具入参中的 mall scope 兜底解析(D11 字符串化后仍可能缺失) */
35
+ export function scopeFromMallId(
36
+ requestContext: RequestContext,
37
+ overrideMallId?: string,
38
+ ): MallScope {
39
+ const scope = toShoppingQueryContext(requestContext).scope;
40
+ if (overrideMallId && overrideMallId !== scope.mallId) {
41
+ return { ...scope, mallId: overrideMallId };
42
+ }
43
+ return scope;
44
+ }
45
+
46
+ /** ISO 时间戳(卡 schema isoDateTime 形状) */
47
+ export function nowIso(): string {
48
+ return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
49
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * module-shopping-guide 服务端入口(011 K1:自注册闭环)。
3
+ * - 11 卡声明(key = cardType)+ 15 工具 + FAQ silent preTool + intents 意图硬路由;
4
+ * - register 只注册不解析(resolveShoppingGuidePorts 仅 handle/execute 内调用);
5
+ * - 模块级单例:工具实例顶层创建(010 实例一致性),register 幂等。
6
+ */
7
+ import type {
8
+ ServerContext,
9
+ ServerModule,
10
+ TypedBus,
11
+ PreToolDef,
12
+ HandlerDefinition,
13
+ } from '@tbox.cn/app-sdk/server';
14
+ import { definePreTool, loadModuleSkills } from '@tbox.cn/app-sdk/server';
15
+ import type { MallEventMap } from '@tbox.cn/app-contracts-mall';
16
+ import productListMeta from './cards/product-list/meta';
17
+ import productDetailMeta from './cards/product-detail/meta';
18
+ import merchantListMeta from './cards/merchant-list/meta';
19
+ import merchantDetailMeta from './cards/merchant-detail/meta';
20
+ import categoryListMeta from './cards/category-list/meta';
21
+ import productComparisonMeta from './cards/product-comparison/meta';
22
+ import mallDirectoryMeta from './cards/mall-directory/meta';
23
+ import nearbyMallListMeta from './cards/nearby-mall-list/meta';
24
+ import customerServiceFaqMeta from './cards/customer-service-faq/meta';
25
+ import humanGuideListMeta from './cards/human-guide-list/meta';
26
+ import locationHandoffMeta from './cards/location-handoff/meta';
27
+ import { createShoppingGuideTools } from './tools';
28
+ import { resolveShoppingGuidePorts } from './ports';
29
+ import { toShoppingQueryContext } from './domain/value-objects';
30
+ import {
31
+ projectNearbyMalls,
32
+ projectCustomerServiceFaq,
33
+ projectCategoryList,
34
+ } from './projections';
35
+ import { joycityCSignedAuthStrategy } from './integrations/joycity/auth-strategy';
36
+
37
+
38
+ export { shoppingGuideCards } from './cards';
39
+ export { createShoppingGuideTools } from './tools';
40
+ export type { ShoppingGuideTools, ShoppingGuideToolIds } from './tools';
41
+ export { resolveShoppingGuidePorts, SHOPPING_GUIDE_PROVIDER_TEMPLATE_ID } from './ports';
42
+ export { joycityCSignedAuthStrategy, computeJoyCityCSign } from './integrations/joycity/auth-strategy';
43
+
44
+ /** 模块级 ctx 引用(register 期绑定;execute 内读取——平台包实例分裂免疫:不 import SDK 全局单例) */
45
+ let moduleCtx: ServerContext | undefined;
46
+
47
+ /** 工具实例顶层创建(010:pre-tool 声明引用工具实例 = 单一真源) */
48
+ const tools = createShoppingGuideTools({ getCtx: () => moduleCtx! });
49
+
50
+ /**
51
+ * FAQ 静默前置工具(011 D2/D9):客服 FAQ 检索 = silent preTool。
52
+ * - silent:不发前端事件、不落 inputs.preTools,仅本轮 reminder 数据块注入;
53
+ * - routing keywords:宽召回词表(退换货/积分/停车等服务政策类问题);
54
+ * - decide 全权决策:query = 本轮文本,topK=3。
55
+ */
56
+ const faqPreTool = definePreTool(tools.customerServiceFaq, {
57
+ routing: {
58
+ mode: 'keywords',
59
+ terms: ['退换货', '退货', '退款', '积分规则', '停车费', '停车政策', '会员权益', '发票', '售后'],
60
+ },
61
+ decide: ({ text }) =>
62
+ text && text.trim().length > 0
63
+ ? { decision: 'run', args: { query: text, topK: '3' } }
64
+ : { decision: 'skip', reason: '空文本' },
65
+ silent: true,
66
+ });
67
+
68
+ const preTools = {
69
+ 'customer-service-faq': faqPreTool,
70
+ } satisfies Record<string, PreToolDef>;
71
+
72
+ /** 意图硬路由(011 D7/D8:意图与处理器同处定义;命中零 LLM) */
73
+ const shoppingGuideHandler: HandlerDefinition = {
74
+ id: 'shopping-guide',
75
+ intents: [
76
+ {
77
+ // 「附近商场」确定性意图 → 直接出卡(零 LLM)
78
+ patterns: ['附近商场', '附近大悦城', '其他商场', '周边商场'],
79
+ },
80
+ {
81
+ // 「商场有哪些类型的店」确定性意图 → 业态目录(零 LLM)
82
+ patterns: ['有哪些类型的店', '商场有什么店', '有哪些业态', '逛什么'],
83
+ },
84
+ ],
85
+ async handle(action, payload) {
86
+ const ctx = moduleCtx!;
87
+ const ports = await resolveShoppingGuidePorts(ctx);
88
+ // 011 评审 6.2:显式防护——run 上下文缺失时结构化返回(替代 as never 类型逃逸)
89
+ const requestContext = ctx.auth.getContext();
90
+ if (!requestContext) return { text: '运行上下文未绑定,请重试', cards: [] };
91
+ const q = toShoppingQueryContext(requestContext);
92
+
93
+ if (action === 'intent') {
94
+ const text = String(payload ?? '');
95
+ if (/附近|其他|周边/.test(text)) {
96
+ const malls = await ports.navigation.listNearbyMalls(q);
97
+ return {
98
+ text: malls.length > 0 ? '为你找到附近的大悦城门店:' : '暂无附近商场数据。',
99
+ cards: [
100
+ { cardType: 'nearby-mall-list', data: projectNearbyMalls(malls) as unknown as Record<string, unknown> },
101
+ ],
102
+ };
103
+ }
104
+ const categories = await ports.category.listCategories(q);
105
+ return {
106
+ text: categories.length > 0 ? '商场业态分布如下:' : '暂无业态数据。',
107
+ cards: [
108
+ { cardType: 'category-list', data: projectCategoryList(categories) as unknown as Record<string, unknown> },
109
+ ],
110
+ };
111
+ }
112
+ // 兜底:FAQ 查询 handler(非意图路径)
113
+ if (action === 'faq') {
114
+ const faqs = await ports.assistance.searchFaq(q, String(payload ?? ''), 3);
115
+ return {
116
+ text: faqs.length > 0 ? '相关常见问题:' : '未找到相关常见问题。',
117
+ cards: [
118
+ {
119
+ cardType: 'customer-service-faq',
120
+ data: projectCustomerServiceFaq(String(payload ?? ''), faqs) as unknown as Record<string, unknown>,
121
+ },
122
+ ],
123
+ };
124
+ }
125
+ return { text: '', cards: [] };
126
+ },
127
+ };
128
+
129
+ /** 本地 skill(009 文件化:包内 skills/shopping-guide/;map 化回填声明式通道) */
130
+ const skills = Object.fromEntries(
131
+ (await loadModuleSkills('@tbox.cn/app-module-shopping-guide', import.meta.url)).map((s) => [s.name, s]),
132
+ );
133
+
134
+ export const serverModule = {
135
+ declaration: {
136
+ componentId: 'shopping-guide',
137
+ features: [
138
+ 'merchant-discovery',
139
+ 'product-search',
140
+ 'recommendation',
141
+ 'mall-directory',
142
+ 'customer-service',
143
+ 'navigation',
144
+ ],
145
+ },
146
+ cards: {
147
+ 'product-list': productListMeta,
148
+ 'product-detail': productDetailMeta,
149
+ 'merchant-list': merchantListMeta,
150
+ 'merchant-detail': merchantDetailMeta,
151
+ 'category-list': categoryListMeta,
152
+ 'product-comparison': productComparisonMeta,
153
+ 'mall-directory': mallDirectoryMeta,
154
+ 'nearby-mall-list': nearbyMallListMeta,
155
+ 'customer-service-faq': customerServiceFaqMeta,
156
+ 'human-guide-list': humanGuideListMeta,
157
+ 'location-handoff': locationHandoffMeta,
158
+ },
159
+ skills,
160
+ preTools,
161
+ register(ctx: ServerContext): void {
162
+ moduleCtx = ctx;
163
+ // 011 B2:joycity C 端签名策略自注册(Provider 认证注册点;模板 transportFactory 动态可见)
164
+ ctx.authStrategies.register(joycityCSignedAuthStrategy);
165
+ ctx.cards.registerMap(serverModule.cards);
166
+ for (const tool of Object.values(tools)) {
167
+ ctx.tools.register(tool);
168
+ }
169
+ ctx.handlers.register(shoppingGuideHandler);
170
+
171
+ // 类型化事件总线(keyof 约束;跨模块消费 mall 事件)
172
+ const mallBus = ctx.bus as unknown as TypedBus<MallEventMap>;
173
+
174
+ // 会员等级变更 → 导购推荐上下文(演示跨模块订阅;仅读消费不写)
175
+ mallBus.subscribe('member.level.changed', ({ userId }) => {
176
+ void userId;
177
+ // 二期:等级变更后刷新推荐上下文缓存(不做重活)
178
+ });
179
+ },
180
+ } satisfies ServerModule;
@@ -0,0 +1,226 @@
1
+ /**
2
+ * JoyCity adapter:DTO → contracts-mall Port 实现(011 K6)。
3
+ * 实现 CatalogQueryPort / MerchantDirectoryQueryPort / CommercialCategoryQueryPort / MallDirectoryQueryPort 四 Port;
4
+ * Assistance/Navigation 由本地实现(知识库/FAQ/位置)。
5
+ */
6
+ import type {
7
+ CatalogQueryPort,
8
+ CategoryRecord,
9
+ CommercialCategoryQueryPort,
10
+ MallDirectoryQueryPort,
11
+ MallDirectoryRecord,
12
+ MerchantDirectoryQueryPort,
13
+ MerchantRecord,
14
+ MerchantSearchCriteria,
15
+ ProductFacetsRecord,
16
+ ProductRecord,
17
+ ProductSearchCriteria,
18
+ ShoppingPage,
19
+ ShoppingQueryContext,
20
+ } from '@tbox.cn/app-contracts-mall';
21
+ import { nowIso } from '../../domain/value-objects';
22
+ import {
23
+ JoyCityTransportGateway,
24
+ type JoyCityMerchantListItemDto,
25
+ type JoyCityProductDto,
26
+ } from './gateway';
27
+
28
+ export class JoyCityCatalogAdapter implements CatalogQueryPort {
29
+ constructor(private readonly gateway: JoyCityTransportGateway) {}
30
+
31
+ async searchProducts(criteria: ProductSearchCriteria): Promise<ShoppingPage<ProductRecord>> {
32
+ const items = await this.gateway.searchProducts({
33
+ Keyword: criteria.keyword ?? '',
34
+ PageIndex: criteria.page,
35
+ PageSize: criteria.pageSize,
36
+ ...(criteria.categoryCode ? { CommercialTypeID: Number(criteria.categoryCode) } : {}),
37
+ ...(criteria.minPriceMinor !== undefined ? { MinPriceMinor: criteria.minPriceMinor } : {}),
38
+ ...(criteria.maxPriceMinor !== undefined ? { MaxPriceMinor: criteria.maxPriceMinor } : {}),
39
+ });
40
+ const mapped = items.map((dto, order) => mapProductDto(dto, order));
41
+ return {
42
+ items: mapped,
43
+ page: criteria.page,
44
+ pageSize: criteria.pageSize,
45
+ total: mapped.length,
46
+ hasMore: mapped.length === criteria.pageSize,
47
+ };
48
+ }
49
+
50
+ async getProduct(productId: string, _ctx: ShoppingQueryContext): Promise<ProductRecord | null> {
51
+ const dto = await this.gateway.getProduct({ ProductID: Number(productId) });
52
+ if (!dto) return null;
53
+ return mapProductDto(dto, 0);
54
+ }
55
+
56
+ async getFacets(_criteria: ProductSearchCriteria): Promise<ProductFacetsRecord> {
57
+ // JoyCity 目录 API 暂不支持分面
58
+ return { brands: [], categories: [], priceRanges: [], floors: [] };
59
+ }
60
+ }
61
+
62
+ export class JoyCityMerchantAdapter implements MerchantDirectoryQueryPort {
63
+ constructor(private readonly gateway: JoyCityTransportGateway) {}
64
+
65
+ async searchMerchants(criteria: MerchantSearchCriteria): Promise<ShoppingPage<MerchantRecord>> {
66
+ const items = await this.gateway.listMerchants({
67
+ Keyword: criteria.keyword ?? '',
68
+ PageIndex: criteria.page,
69
+ PageSize: criteria.pageSize,
70
+ ...(criteria.businessCategory ? { CommercialTypeID: Number(criteria.businessCategory) } : {}),
71
+ ...(criteria.floorCode ? { FloorCode: criteria.floorCode } : {}),
72
+ ...(criteria.buildingCode ? { BuildingCode: criteria.buildingCode } : {}),
73
+ });
74
+ const mapped = items.map(mapMerchantListItem);
75
+ return {
76
+ items: mapped,
77
+ page: criteria.page,
78
+ pageSize: criteria.pageSize,
79
+ total: mapped.length,
80
+ hasMore: mapped.length === criteria.pageSize,
81
+ };
82
+ }
83
+
84
+ async getMerchant(merchantId: string, _ctx: ShoppingQueryContext): Promise<MerchantRecord | null> {
85
+ const dto = await this.gateway.getMerchant({ MerchantID: Number(merchantId) });
86
+ if (!dto) return null;
87
+ return {
88
+ ...mapMerchantListItem(dto),
89
+ ...(dto.Description ? { description: dto.Description } : {}),
90
+ ...(dto.ContactInfo?.length
91
+ ? {
92
+ contactInfo: dto.ContactInfo.filter((c) => c.Channel && c.Value).map((c) => ({
93
+ channel: String(c.Channel),
94
+ value: String(c.Value),
95
+ })),
96
+ }
97
+ : {}),
98
+ };
99
+ }
100
+ }
101
+
102
+ export class JoyCityCategoryAdapter implements CommercialCategoryQueryPort {
103
+ constructor(private readonly gateway: JoyCityTransportGateway) {}
104
+
105
+ async listCategories(_ctx: ShoppingQueryContext): Promise<readonly CategoryRecord[]> {
106
+ const categories = await this.gateway.listCategories({ Level: 1, PageIndex: 1, PageSize: 100 });
107
+ return categories.map((c) => ({
108
+ code: String(c.CategoryID ?? ''),
109
+ name: c.Name ?? '',
110
+ ...(c.Description ? { description: c.Description } : {}),
111
+ merchantCount: c.MerchantCount ?? 0,
112
+ ...(c.SubCategories?.length
113
+ ? {
114
+ subCategories: c.SubCategories.map((s) => ({
115
+ code: String(s.CategoryID ?? ''),
116
+ name: s.Name ?? '',
117
+ merchantCount: s.MerchantCount ?? 0,
118
+ })),
119
+ }
120
+ : {}),
121
+ }));
122
+ }
123
+ }
124
+
125
+ export class JoyCityMallDirectoryAdapter implements MallDirectoryQueryPort {
126
+ constructor(private readonly gateway: JoyCityTransportGateway) {}
127
+
128
+ async getDirectory(ctx: ShoppingQueryContext): Promise<MallDirectoryRecord | null> {
129
+ const dto = await this.gateway.getMallDirectory({ MallID: ctx.scope.mallId });
130
+ if (!dto) return null;
131
+ return {
132
+ mallId: dto.MallID ?? ctx.scope.mallId,
133
+ mallName: dto.MallName ?? ctx.scope.mallId,
134
+ buildings: (dto.Buildings ?? []).map((b) => ({
135
+ buildingCode: b.BuildingCode ?? '',
136
+ buildingName: b.BuildingName ?? '',
137
+ floors: (b.Floors ?? []).map((f) => ({
138
+ floorCode: f.FloorCode ?? '',
139
+ floorName: f.FloorName ?? '',
140
+ businessCategories: f.BusinessCategories ?? [],
141
+ merchantCount: f.MerchantCount ?? 0,
142
+ })),
143
+ })),
144
+ observedAt: nowIso(),
145
+ };
146
+ }
147
+ }
148
+
149
+ // ===== DTO 映射 =====
150
+
151
+ export function mapProductDto(dto: JoyCityProductDto, _order: number): ProductRecord {
152
+ const observedAt = nowIso();
153
+ return {
154
+ productId: String(dto.ProductID ?? ''),
155
+ name: dto.Name ?? '',
156
+ ...(dto.Description ? { description: dto.Description } : {}),
157
+ ...(dto.ImageUrl ? { imageUrls: [dto.ImageUrl] } : { imageUrls: [] }),
158
+ ...(dto.BrandName ? { brand: dto.BrandName } : {}),
159
+ categoryPath: dto.CategoryPath ?? [],
160
+ price:
161
+ dto.PriceYuan !== undefined
162
+ ? {
163
+ sale: {
164
+ currency: 'CNY' as const,
165
+ amountMinor: Math.round(dto.PriceYuan * 100),
166
+ display: `¥${dto.PriceYuan.toFixed(2)}`,
167
+ },
168
+ ...(dto.OriginalPriceYuan !== undefined && dto.OriginalPriceYuan > dto.PriceYuan
169
+ ? {
170
+ original: {
171
+ currency: 'CNY' as const,
172
+ amountMinor: Math.round(dto.OriginalPriceYuan * 100),
173
+ display: `¥${dto.OriginalPriceYuan.toFixed(2)}`,
174
+ },
175
+ }
176
+ : {}),
177
+ }
178
+ : {},
179
+ availability: {
180
+ status: dto.Marketable === false ? 'out_of_stock' : 'in_stock',
181
+ label: dto.StockLabel ?? '有货',
182
+ marketable: dto.Marketable !== false,
183
+ observedAt,
184
+ },
185
+ merchant: {
186
+ merchantId: String(dto.MerchantID ?? ''),
187
+ name: dto.MerchantName ?? '',
188
+ location: {
189
+ displayText: [dto.BuildingName, dto.FloorName, dto.UnitName].filter(Boolean).join(' ') || '位置待确认',
190
+ ...(dto.BuildingName ? { buildingName: dto.BuildingName } : {}),
191
+ ...(dto.FloorName ? { floorName: dto.FloorName } : {}),
192
+ ...(dto.UnitName ? { unitName: dto.UnitName } : {}),
193
+ },
194
+ },
195
+ labels: dto.Labels ?? [],
196
+ attributes: [],
197
+ promotionFacts: dto.PromotionFacts ?? [],
198
+ observedAt,
199
+ };
200
+ }
201
+
202
+ export function mapMerchantListItem(dto: JoyCityMerchantListItemDto): MerchantRecord {
203
+ const observedAt = nowIso();
204
+ return {
205
+ merchantId: String(dto.MerchantID ?? ''),
206
+ name: dto.Name ?? '',
207
+ ...(dto.LogoUrl ? { logoUrl: dto.LogoUrl } : {}),
208
+ ...(dto.CoverUrl ? { coverUrls: [dto.CoverUrl] } : { coverUrls: [] }),
209
+ ...(dto.BrandName ? { brand: dto.BrandName } : {}),
210
+ businessCategories: [dto.CommercialTypeName].filter((x): x is string => Boolean(x)),
211
+ location: {
212
+ displayText: [dto.BuildingName, dto.FloorName, dto.UnitName].filter(Boolean).join(' ') || '位置待确认',
213
+ ...(dto.BuildingName ? { buildingName: dto.BuildingName } : {}),
214
+ ...(dto.FloorName ? { floorName: dto.FloorName } : {}),
215
+ ...(dto.UnitName ? { unitName: dto.UnitName } : {}),
216
+ },
217
+ status: {
218
+ code: dto.Status === 0 ? 'disabled' : 'enabled',
219
+ label: dto.Status === 0 ? '暂停营业' : '营业中',
220
+ observedAt,
221
+ },
222
+ services: dto.Services ?? [],
223
+ promotionFacts: dto.PromotionFacts ?? [],
224
+ observedAt,
225
+ };
226
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * JoyCity C 端签名认证策略(011 K6:签名算法留模块 + strategy 注册点)。
3
+ * 头格式(全小写,时间戳 epoch ms):
4
+ * sign: <MD5(...)[8..24] 小写>
5
+ * timestamp: <epoch ms>
6
+ * publickey: <publicKey>
7
+ * 签名源:MD5("{publicKey:<pk>,timeStamp:<ts>,data:<bodyJson>,privateKey:<sk>}")[8..24].toLowerCase()
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+ import type { ProviderAuthStrategy, ProviderAuthStrategyInput } from '@tbox.cn/app-sdk/server';
11
+
12
+ export const JOYCITY_C_SIGNED_CREDENTIAL_TYPE = 'joycity-c-signed-v1';
13
+
14
+ export const joycityCSignedAuthStrategy: ProviderAuthStrategy = {
15
+ credentialType: JOYCITY_C_SIGNED_CREDENTIAL_TYPE,
16
+ apply(input: ProviderAuthStrategyInput): Record<string, string> {
17
+ const credential = input.credential.value as { publicKey?: unknown; privateKey?: unknown };
18
+ const publicKey = typeof credential.publicKey === 'string' ? credential.publicKey : '';
19
+ const privateKey = typeof credential.privateKey === 'string' ? credential.privateKey : '';
20
+ const timestamp = String(Date.now());
21
+ const bodyJson = input.body === undefined ? '' : JSON.stringify(input.body);
22
+ return {
23
+ sign: computeJoyCityCSign(publicKey, timestamp, bodyJson, privateKey),
24
+ timestamp,
25
+ publickey: publicKey,
26
+ };
27
+ },
28
+ };
29
+
30
+ export function computeJoyCityCSign(
31
+ publicKey: string,
32
+ timestamp: string,
33
+ bodyJson: string,
34
+ privateKey: string,
35
+ ): string {
36
+ const source = `{publicKey:${publicKey},timeStamp:${timestamp},data:${bodyJson},privateKey:${privateKey}}`;
37
+ return createHash('md5').update(source, 'utf8').digest('hex').substring(8, 24).toLowerCase();
38
+ }