@tbox.cn/app-module-ai-payment 0.0.0-stage → 0.1.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.
@@ -0,0 +1,50 @@
1
+ /** 支付卡数据与历史支付 Port 兼容类型。当前体验链路经容器点击创单。 */
2
+ import type { MallScope } from '@tbox.cn/app-contracts-mall';
3
+ import type { RequestContext } from '@tbox.cn/app-contracts';
4
+
5
+ /** 支付域 DTO(AI 支付 Demo 语义:tradeStatus 三态移植,保持支付侧权威词汇)。 */
6
+ export type PaymentTradeStatus = 'WAIT_BUYER_PAY' | 'TRADE_SUCCESS' | 'TRADE_CLOSED';
7
+
8
+ export const PAYMENT_SERVICE = 'payment.main';
9
+
10
+ export interface PaymentQueryContext {
11
+ readonly scope: MallScope;
12
+ readonly subjectId?: string;
13
+ readonly requestContext: RequestContext;
14
+ }
15
+
16
+ export interface PaymentPort {
17
+ /**
18
+ * 买家身份取 q.requestContext.identity.userId(可信上下文——身份不经模型传参)。
19
+ * bizContext(可选透传):AI 付场景 my.tradePay 拉起上下文({cashierScene:'agentPay',
20
+ * agentPid, agentId} 的 JSON 字符串,仅 ai 付内使用)——由 provider 依实例 config 组装的
21
+ * 不透明字符串,模块/卡面零解析透传到客户端 tradePay 入参(Code security:拉起上下文
22
+ * 服务端合成物,客户端不在安全决策点消费)。
23
+ */
24
+ createOrder(q: PaymentQueryContext, detail?: { remark?: string }): Promise<{ tradeNo: string; bizContext?: string }>;
25
+ queryOrder(
26
+ q: PaymentQueryContext,
27
+ tradeNo: string,
28
+ ): Promise<{ tradeNo: string; status: PaymentTradeStatus; totalAmountText?: string; subCode?: string; subMsg?: string }>;
29
+ }
30
+
31
+ /** 支付订单卡 schema,支付结果原位更新 payState。 */
32
+ import { z } from 'zod';
33
+
34
+ export const paymentOrderCardDataSchema = z.object({
35
+ tradeNo: z.string().min(1).optional(),
36
+ buyerId: z.string().min(1).optional(),
37
+ subject: z.string().min(1),
38
+ totalAmountText: z.string().min(1),
39
+ payState: z.enum(['created', 'paying', 'paid', 'cancelled', 'failed']),
40
+ /** AI 付 tradePay 拉起上下文(provider 组装的不透明 JSON 字符串;可选——非 AI 付形态缺省) */
41
+ bizContext: z.string().min(1).optional(),
42
+ });
43
+
44
+ /** 支付订单卡 schema map。 */
45
+ export const paymentCardDataSchemas = {
46
+ 'payment-order': paymentOrderCardDataSchema,
47
+ } as const;
48
+
49
+ export type PaymentCardType = keyof typeof paymentCardDataSchemas;
50
+ export type PaymentOrderCardData = z.infer<typeof paymentOrderCardDataSchema>;
@@ -0,0 +1,29 @@
1
+ import { loadModuleSkills } from '@tbox.cn/app-agent-sdk-server';
2
+ import type { ServerContext, ServerModule } from '@tbox.cn/app-agent-sdk-server';
3
+ import paymentOrderMeta from './cards/payment-order/meta';
4
+ import { createAiPaymentTools } from './tools';
5
+ import { createAiPaymentActions } from './actions';
6
+
7
+ export { resolvePaymentPort, PaymentNotConfiguredError } from './ports';
8
+ export { createAiPaymentTools } from './tools';
9
+ export { createAiPaymentActions } from './actions';
10
+ export type { AiPaymentTools } from './tools';
11
+
12
+ const tools = createAiPaymentTools();
13
+
14
+ const cards = { 'payment-order': paymentOrderMeta } as const;
15
+
16
+ export const serverModule = {
17
+ declaration: { moduleId: 'ai-payment' },
18
+ cards,
19
+ skills: Object.fromEntries((await loadModuleSkills('@tbox.cn/app-module-ai-payment', import.meta.url)).map(s => [s.name, s])),
20
+ preTools: {},
21
+ register(ctx: ServerContext): void {
22
+ for (const tool of Object.values(tools)) ctx.tools.register(tool);
23
+ ctx.cards.registerMap(cards);
24
+ const actions = createAiPaymentActions();
25
+ for (const action of Object.values(actions)) ctx.cardActions.register(action as never);
26
+ },
27
+ } satisfies ServerModule;
28
+
29
+ export default serverModule;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * payment.main 槽解析(请求级;register 只注册不解析——铁律)。模块零外呼(铁律):
3
+ * 唯一出口 = integrations registry 槽位解析。支付无 InMemory 降级形态(资损初始化路径),
4
+ * 预期缺席转为 PaymentNotConfiguredError 上抛,由工具层收口为可读文案;其余错误上抛
5
+ * (配置即声明)。
6
+ */
7
+ import { isExpectedProviderAbsence, type RequestContext } from '@tbox.cn/app-contracts';
8
+ import { mallScopeOf } from '@tbox.cn/app-contracts-mall';
9
+ import { PAYMENT_SERVICE, type PaymentPort } from './contracts';
10
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
11
+
12
+ export class PaymentNotConfiguredError extends Error {
13
+ constructor(message: string) {
14
+ super(message);
15
+ this.name = 'PaymentNotConfiguredError';
16
+ }
17
+ }
18
+
19
+ export async function resolvePaymentPort(reqCtx: RequestContext, ctx: ServerContext): Promise<PaymentPort> {
20
+ try {
21
+ const resolved = await ctx.integrations?.resolveService?.({
22
+ service: PAYMENT_SERVICE,
23
+ scope: mallScopeOf(reqCtx),
24
+ request: reqCtx,
25
+ });
26
+ if (!resolved) throw new PaymentNotConfiguredError('payment.main 槽未配置(integrations registry)');
27
+ // Code security: 契约自持 cast——供应商实现无共享类型真源(模块零 provider 依赖铁律),
28
+ // 结构匹配由 provider-mocktest tests/payment.test.ts createOrder/queryOrder 形状断言兜底
29
+ //(create: {tradeNo, bizContext};query: {tradeNo, status: PaymentTradeStatus 三态})。
30
+ return resolved as PaymentPort;
31
+ } catch (e) {
32
+ if (isExpectedProviderAbsence(e)) {
33
+ throw new PaymentNotConfiguredError('支付服务未配置或实例缺失');
34
+ }
35
+ throw e;
36
+ }
37
+ }
@@ -0,0 +1,27 @@
1
+ import { createTool, requireToolRequestContext, withCardEmissionHint } from '@tbox.cn/app-agent-sdk-server';
2
+ import type { ToolExecContextLike } from '@tbox.cn/app-agent-sdk-server';
3
+ import { z } from 'zod';
4
+ import { loadPaymentConfig } from '../config';
5
+
6
+ export function createAiPaymentTools(options: { loadConfig?: typeof loadPaymentConfig } = {}) {
7
+ const tool = createTool({
8
+ id: 'createPaymentOrder',
9
+ description: '展示测试购买商品的待支付卡,固定 0.01 元。用户点击去支付后创单并拉起收银台。',
10
+ inputSchema: z.object({}),
11
+ execute: async (_args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
12
+ const reqCtx = requireToolRequestContext(execCtx, 'createPaymentOrder');
13
+ const config = await (options.loadConfig ?? loadPaymentConfig)();
14
+ const userId = reqCtx.identity?.source !== 'anonymous' ? reqCtx.identity?.userId : undefined;
15
+ // 2088052281674865 为测试账号,仅在已有买家身份缺失或格式无效时兜底。
16
+ const buyerId = userId && /^2088\d+$/.test(userId) ? userId : '2088052281674865';
17
+ const facts = {
18
+ subject: '测试购买商品', totalAmountText: '0.01', payState: 'created',
19
+ ...(buyerId ? { buyerId } : {}),
20
+ ...(config.bizContext ? { bizContext: config.bizContext } : {}),
21
+ };
22
+ return { ...facts, cards: [{ cardType: 'payment-order', data: facts, note: '测试购买商品 0.01 元,等待用户点击支付' }] };
23
+ },
24
+ });
25
+ return { createPaymentOrder: withCardEmissionHint(tool) } as const;
26
+ }
27
+ export type AiPaymentTools = ReturnType<typeof createAiPaymentTools>;
@@ -0,0 +1,48 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "module-ai-payment",
4
+ "name": "AI 支付",
5
+ "description": "0.01 元测试商品,Web 模拟支付与端内云容器创单支付",
6
+ "version": "0.1.0",
7
+ "kind": "business",
8
+ "risk": {
9
+ "level": "medium",
10
+ "writeBoundary": "source"
11
+ },
12
+ "distribution": {
13
+ "defaultMode": "codegen"
14
+ },
15
+ "declare": {
16
+ "handlers": [],
17
+ "tools": [
18
+ "createPaymentOrder"
19
+ ],
20
+ "cards": [
21
+ {
22
+ "cardType": "payment-order",
23
+ "schemaVersion": 1
24
+ }
25
+ ],
26
+ "routes": [],
27
+ "pages": [],
28
+ "tabs": [],
29
+ "actions": [
30
+ "ai-payment.report-payment-result"
31
+ ],
32
+ "consumes": [],
33
+ "owns": [
34
+ {
35
+ "service": "payment.main"
36
+ }
37
+ ]
38
+ },
39
+ "dependencies": {
40
+ "modules": [
41
+ {
42
+ "id": "contracts-mall",
43
+ "required": true
44
+ }
45
+ ]
46
+ },
47
+ "env": []
48
+ }
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createAiPaymentActions } from '../src/server/actions';
3
+
4
+ // 拉起为客户端直调 callJsapi('tradePay')(bizContext 为 JSAPI 同步入参)——服务端仅保留
5
+ // hidden singleUse 回调动作收口卡态;pay 动作已随 client-direct 链退役(manifest 同步收窄)。
6
+ const reqCtx = { identity: { userId: '2088002013890627', source: 'external' } } as never;
7
+ const report = () => createAiPaymentActions()['ai-payment.report-payment-result']!;
8
+
9
+ describe('ai-payment.report-payment-result(hidden singleUse 回调,唯一服务端动作)', () => {
10
+ it('success → paid + 收银台成功文案', async () => {
11
+ const out = await report().execute!({ status: 'success', paymentRef: 't1' }, reqCtx);
12
+ expect((out.update?.data as Record<string, unknown>).payState).toBe('paid');
13
+ expect(out.text).toContain('支付成功');
14
+ expect(out.text).not.toContain('退回');
15
+ });
16
+
17
+ it('cancel → cancelled;failure → failed', async () => {
18
+ expect(((await report().execute!({ status: 'cancel' }, reqCtx)).update?.data as Record<string, unknown>).payState).toBe('cancelled');
19
+ expect(((await report().execute!({ status: 'failure' }, reqCtx)).update?.data as Record<string, unknown>).payState).toBe('failed');
20
+ });
21
+
22
+ it('unavailable → 提示支付宝壳环境', async () => {
23
+ const out = await report().execute!({ status: 'unavailable' }, reqCtx);
24
+ expect(out.text).toContain('支付宝');
25
+ });
26
+
27
+ it('payState 白名单产出(无 payment effect 依赖;paymentRef 透传回卡)', async () => {
28
+ const out = await report().execute!({ status: 'success', paymentRef: '2026091823001490621437665842' }, reqCtx);
29
+ expect((out.update?.data as Record<string, unknown>).tradeNo).toBe('2026091823001490621437665842');
30
+ expect(out.effects).toBeUndefined();
31
+ });
32
+ });
@@ -0,0 +1,48 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createToolExecContext } from '@tbox.cn/app-agent-sdk-server';
3
+ import { createAiPaymentTools } from '../src/server/tools';
4
+ import { loadPaymentConfig, paymentAppRoot } from '../src/server/config';
5
+ import { mkdir, mkdtemp, writeFile, rm } from 'node:fs/promises';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+
9
+ describe('体验商品准备', () => {
10
+ it('mock 工具只准备卡和固定测试买家,不创单不查单', async () => {
11
+ const tools = createAiPaymentTools({ loadConfig: async () => ({ mode: 'mock' }) });
12
+ const out = await tools.createPaymentOrder.execute!({}, createToolExecContext({ identity: { userId: 'anonymous_example', source: 'anonymous' } } as never) as never) as Record<string, unknown>;
13
+ expect(out).toMatchObject({ subject: '测试购买商品', totalAmountText: '0.01', buyerId: '2088052281674865' });
14
+ expect(out.tradeNo).toBeUndefined();
15
+ expect(Object.keys(tools)).toEqual(['createPaymentOrder']);
16
+ });
17
+ it.each(['mock', 'real'])('%s 配置均优先使用有效买家,否则使用固定兜底', async (mode) => {
18
+ const tools = createAiPaymentTools({ loadConfig: async () => ({ mode }) });
19
+ for (const identity of [
20
+ { userId: '2088000000000002', source: 'external' },
21
+ { userId: 'anonymous_example', source: 'anonymous' },
22
+ { userId: 'openid_example', source: 'external' },
23
+ { userId: 'local_2088000000000002', source: 'local' },
24
+ ]) {
25
+ const out = await tools.createPaymentOrder.execute!({}, createToolExecContext({ identity } as never) as never) as Record<string, unknown>;
26
+ expect(out.buyerId).toBe(identity.userId === '2088000000000002' ? identity.userId : '2088052281674865');
27
+ }
28
+ });
29
+ it('真实环境读取 kya.json,商家 PID 与买家独立', async () => {
30
+ const appDir = await mkdtemp(join(tmpdir(), 'payment-config-'));
31
+ try {
32
+ await mkdir(join(appDir, '.tbox'));
33
+ await writeFile(join(appDir, '.tbox/app.json'), '{}');
34
+ await mkdir(join(appDir, 'apps/server'), { recursive: true });
35
+ expect(await paymentAppRoot(join(appDir, 'apps/server'))).toBe(appDir);
36
+ await writeFile(join(appDir, 'kya.json'), JSON.stringify({ kyaid: 'registered-agent' }));
37
+ const out = await loadPaymentConfig({ appDir, env: { NODE_ENV: 'production', AI_PAY_AGENT_PID: 'merchant' } });
38
+ expect(JSON.parse(out.bizContext!)).toEqual({ cashierScene: 'agentPay', agentPid: 'merchant', agentId: 'registered-agent' });
39
+ await writeFile(join(appDir, 'kya.json'), '{}');
40
+ await expect(loadPaymentConfig({ appDir, env: { NODE_ENV: 'production' } })).rejects.toThrow('kyaid');
41
+ } finally { await rm(appDir, { recursive: true }); }
42
+ });
43
+ it('非生产环境使用 mock 固定 ID', async () => {
44
+ expect(JSON.parse((await loadPaymentConfig({ env: { NODE_ENV: 'development', AI_PAY_AGENT_PID: 'merchant' } })).bizContext!).agentId).toBe('2026000116664809');
45
+ expect((await loadPaymentConfig({ env: {} })).mode).toBe('mock');
46
+ expect((await loadPaymentConfig({ env: { NODE_ENV: 'test' } })).mode).toBe('mock');
47
+ });
48
+ });
@@ -0,0 +1,22 @@
1
+ // @vitest-environment happy-dom
2
+ import React, { act } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ vi.mock('@tbox.cn/app-agent-sdk-client', () => ({ callCapability: vi.fn(), callJsapi: vi.fn(), isInAlipayShell: vi.fn(), mapPaymentResultCode: (code: string) => code === '9000' ? 'success' : code === '6001' ? 'cancel' : 'failure', markSelfRendering: (c: unknown) => c, sendCardAction: vi.fn() }));
6
+ import { callCapability, callJsapi, isInAlipayShell, sendCardAction } from '@tbox.cn/app-agent-sdk-client';
7
+ import { PaymentOrderCard } from '../src/client/cards/payment-order';
8
+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
9
+ const data = { subject: '测试购买商品', totalAmountText: '0.01', payState: 'created' as const, buyerId: '2088052281674865', bizContext: '{"cashierScene":"agentPay"}' };
10
+ let root: ReturnType<typeof createRoot>;
11
+ let host: HTMLDivElement;
12
+ afterEach(async () => { if (root) await act(async () => root.unmount()); host?.remove(); vi.resetAllMocks(); });
13
+ async function render(cardData: Omit<typeof data, 'buyerId'> & { buyerId?: string } = data) { host = document.createElement('div'); document.body.append(host); root = createRoot(host); await act(async () => root.render(<PaymentOrderCard data={cardData} cardId="c1" isHistory={false} />)); }
14
+ async function click() { await act(async () => host.querySelector('button')!.click()); }
15
+ describe('支付点击链', () => {
16
+ it('Web 仅模拟成功,零外呼', async () => { vi.mocked(isInAlipayShell).mockReturnValue(false); await render(); await click(); expect(host.querySelector('dialog')?.open).toBe(true); await act(async () => host.querySelector<HTMLButtonElement>('[data-ap-confirm]')!.click()); expect(host.textContent).toContain('模拟支付成功'); expect(callCapability).not.toHaveBeenCalled(); expect(callJsapi).not.toHaveBeenCalled(); });
17
+ it('端内点击才创单,取消后复用订单', async () => { vi.mocked(isInAlipayShell).mockReturnValue(true); vi.mocked(callCapability).mockResolvedValue({ statusCode: 200, data: { tradeNo: 't1' } }); vi.mocked(callJsapi).mockResolvedValue({ resultCode: '6001' }); await render(); expect(callCapability).not.toHaveBeenCalled(); await click(); await click(); expect(callCapability).toHaveBeenCalledTimes(1); expect(callCapability).toHaveBeenCalledWith('app.callContainer', { path: '/api/alipay/aipay/create', method: 'POST', dataType: 'json', header: { 'Content-Type': 'application/json', 'X-API-Token': 'fortest', 'X-Alipay-Service': 'pay-demo' }, data: { buyerId: data.buyerId } }); expect(callJsapi).toHaveBeenCalledWith('tradePay', { tradeNO: 't1', bizContext: data.bizContext }); });
18
+ it('创单失败不拉起收银台', async () => { vi.mocked(isInAlipayShell).mockReturnValue(true); vi.mocked(callCapability).mockRejectedValue(new Error('订单创建失败')); await render(); await click(); expect(callJsapi).not.toHaveBeenCalled(); expect(sendCardAction).toHaveBeenCalledWith('c1', { type: 'toast', content: '订单创建失败', tone: 'error' }); expect(host.textContent).not.toContain('订单创建失败'); });
19
+ it('云容器业务响应无交易号时不拉起支付', async () => { vi.mocked(isInAlipayShell).mockReturnValue(true); vi.mocked(callCapability).mockResolvedValue({ statusCode: 200, data: {} }); await render(); await click(); expect(callJsapi).not.toHaveBeenCalled(); expect(sendCardAction).toHaveBeenCalledWith('c1', { type: 'toast', content: '体验订单创建失败', tone: 'error' }); expect(host.textContent).not.toContain('体验订单创建失败'); });
20
+ it.each([undefined, 'openid_example'])('买家身份 %s 无效时 Toast 提示且不发起创单', async (buyerId) => { vi.mocked(isInAlipayShell).mockReturnValue(true); await render({ ...data, buyerId }); await click(); expect(sendCardAction).toHaveBeenCalledWith('c1', { type: 'toast', content: '缺少有效的买家支付宝身份', tone: 'error' }); expect(callCapability).not.toHaveBeenCalled(); expect(callJsapi).not.toHaveBeenCalled(); expect(host.textContent).not.toContain('缺少有效的买家支付宝身份'); });
21
+ it('支付结果未确认时以 Toast 提示', async () => { vi.mocked(isInAlipayShell).mockReturnValue(true); vi.mocked(callCapability).mockResolvedValue({ statusCode: 200, data: { tradeNo: 't1' } }); vi.mocked(callJsapi).mockResolvedValue({ resultCode: '4000' }); await render(); await click(); expect(sendCardAction).toHaveBeenCalledWith('c1', { type: 'toast', content: '支付结果未确认,请勿重复下单', tone: 'error' }); expect(host.textContent).not.toContain('支付结果未确认'); });
22
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "jsx": "react-jsx",
5
+ "types": ["node"]
6
+ },
7
+ "include": ["src"]
8
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: {
5
+ index: 'src/index.ts',
6
+ 'server/index': 'src/server/index.ts',
7
+ 'client/index': 'src/client/index.ts',
8
+ },
9
+ format: ['esm'],
10
+ target: 'node20',
11
+ platform: 'node',
12
+ outDir: 'dist',
13
+ clean: true,
14
+ sourcemap: false,
15
+ // dts worker 以命令行式传参会撞 TS5074(incremental 需单文件 emit 或 tsBuildInfoFile);
16
+ // 声明产物一次性构建无需增量——仅 dts 关闭,typecheck 的增量缓存不受影响。
17
+ dts: { compilerOptions: { incremental: false } },
18
+ external: [
19
+ '@tbox.cn/app-agent-sdk-client',
20
+ '@tbox.cn/app-agent-sdk-server',
21
+ '@tbox.cn/app-contracts',
22
+ '@tbox.cn/app-contracts-mall',
23
+ 'react',
24
+ 'react-dom',
25
+ 'zod',
26
+ '@mastra/core',
27
+ 'express',
28
+ '@phosphor-icons/react',
29
+ ],
30
+ loader: {
31
+ '.css': 'copy',
32
+ },
33
+ esbuildOptions(options) {
34
+ options.jsx = 'automatic';
35
+ },
36
+ });