@tbox.cn/app-module-parking 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tbox.cn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @tbox.cn/app-module-parking
2
+
3
+ 商圈停车模块:计费、停车券核销、费用(codegen 源)。
4
+
5
+ ## 安装
6
+
7
+ ```sh
8
+ pnpm add @tbox.cn/app-module-parking
9
+ ```
10
+
11
+ ## 用法
12
+
13
+ 在生成应用中:
14
+
15
+ ```sh
16
+ tbox-app module add @tbox.cn/app-module-parking
17
+ ```
@@ -0,0 +1,140 @@
1
+ // src/server/service.ts
2
+ var InMemoryParkingService = class {
3
+ orders = /* @__PURE__ */ new Map();
4
+ couponsUsed = /* @__PURE__ */ new Set();
5
+ constructor(initial) {
6
+ if (initial) for (const [id, order] of Object.entries(initial)) this.orders.set(id, order);
7
+ }
8
+ /** 发券事件回调(由 serverModule.register 注入,保持 service 与 bus 解耦) */
9
+ onCouponUsed;
10
+ async queryParkingFee(userId, orderId) {
11
+ if (orderId) return this.orders.get(orderId);
12
+ return [...this.orders.values()].find((o) => o.userId === userId && o.status === "PENDING");
13
+ }
14
+ async calcFee(userId, orderId) {
15
+ const existing = this.orders.get(orderId);
16
+ if (existing) return existing;
17
+ const order = {
18
+ orderId,
19
+ userId,
20
+ plate: `\u4EACA\xB7${String(userId).slice(-3) ?? "888"}`,
21
+ fee: 20,
22
+ // PoC 固定 20 元
23
+ status: "PENDING"
24
+ };
25
+ this.orders.set(orderId, order);
26
+ return order;
27
+ }
28
+ async useCoupon(_userId, orderId, couponId) {
29
+ const order = this.orders.get(orderId);
30
+ if (!order) return false;
31
+ if (this.couponsUsed.has(couponId)) return false;
32
+ this.couponsUsed.add(couponId);
33
+ this.onCouponUsed?.({ userId: _userId, couponId, amount: 5 });
34
+ return true;
35
+ }
36
+ async settlePayment(_userId, orderId, amount) {
37
+ const order = this.orders.get(orderId);
38
+ if (!order) return false;
39
+ if (order.status === "PAID") return true;
40
+ if (order.status !== "PENDING") return false;
41
+ order.status = "PAID";
42
+ order.paidAmount = amount;
43
+ return true;
44
+ }
45
+ };
46
+
47
+ // src/server/cards/parking-fee/meta.ts
48
+ import { z } from "zod";
49
+ var dataSchema = z.object({
50
+ orderId: z.string(),
51
+ userId: z.string(),
52
+ plate: z.string(),
53
+ fee: z.number(),
54
+ paidAmount: z.number().optional(),
55
+ pointsUsed: z.number().optional(),
56
+ status: z.enum(["PENDING", "PAID", "CANCELLED"])
57
+ });
58
+ var meta = {
59
+ cardType: "parking-fee",
60
+ dataSchema,
61
+ allowedTools: ["queryParkingFee"],
62
+ displayName: "\u505C\u8F66\u8D39\u5361",
63
+ description: "\u5C55\u793A\u505C\u8F66\u8D39\u5355\u4E0E\u62B5\u6263\u60C5\u51B5",
64
+ sampleData: { orderId: "p_1", userId: "u_1001", plate: "\u4EACA\xB7001", fee: 20, status: "PENDING" },
65
+ schemaVersion: 1
66
+ };
67
+ var meta_default = meta;
68
+
69
+ // src/server/tool.ts
70
+ import { createTool } from "@tbox.cn/app-sdk/server";
71
+ import { z as z2 } from "zod";
72
+ function createQueryParkingFeeTool(getParking) {
73
+ return createTool({
74
+ id: "queryParkingFee",
75
+ description: "\u67E5\u8BE2\u5F53\u524D\u505C\u8F66\u8D39\u5355",
76
+ inputSchema: z2.object({
77
+ userId: z2.string().describe("\u4F1A\u5458 userId"),
78
+ orderId: z2.string().optional()
79
+ }),
80
+ outputSchema: z2.object({
81
+ orderId: z2.string(),
82
+ userId: z2.string(),
83
+ plate: z2.string(),
84
+ fee: z2.number(),
85
+ status: z2.enum(["PENDING", "PAID", "CANCELLED"])
86
+ }),
87
+ execute: async ({ userId, orderId }) => {
88
+ const parking2 = getParking();
89
+ const order = parking2 ? await parking2.queryParkingFee(userId, orderId) : void 0;
90
+ if (!order) {
91
+ return { orderId: orderId ?? "none", userId, plate: "-", fee: 0, status: "PENDING" };
92
+ }
93
+ return { orderId: order.orderId, userId: order.userId, plate: order.plate, fee: order.fee, status: order.status };
94
+ }
95
+ });
96
+ }
97
+
98
+ // src/server/handler.ts
99
+ function createParkingHandler(ctx) {
100
+ return {
101
+ id: "parking",
102
+ handle: async (_action, payload) => {
103
+ const parking2 = ctx.resolveService("parking");
104
+ if (!parking2) return { cards: [], text: "\u505C\u8F66\u670D\u52A1\u4E0D\u53EF\u7528" };
105
+ const { userId, orderId } = payload ?? {};
106
+ if (!userId) return { cards: [], text: "\u7F3A\u5C11 userId" };
107
+ const order = await parking2.queryParkingFee(userId, orderId);
108
+ if (!order) return { cards: [], text: "\u65E0\u5F85\u7ED3\u7B97\u505C\u8F66\u8D39" };
109
+ return {
110
+ cards: [{ cardType: "parking-fee", data: order }],
111
+ text: `\u505C\u8F66\u8D39 ${order.fee} \u5143\uFF08\u8BA2\u5355 ${order.orderId}\uFF09`
112
+ };
113
+ }
114
+ };
115
+ }
116
+
117
+ // src/server/index.ts
118
+ var parking = new InMemoryParkingService();
119
+ var cards = {
120
+ "parking-fee": meta_default
121
+ };
122
+ var serverModule = {
123
+ cards,
124
+ register(ctx) {
125
+ ctx.services.register("parking", parking);
126
+ ctx.tools.register(createQueryParkingFeeTool(() => ctx.resolveService("parking")));
127
+ ctx.cards.registerMap(cards);
128
+ ctx.handlers.register(createParkingHandler(ctx));
129
+ const mallBus = ctx.bus;
130
+ parking.onCouponUsed = (e) => {
131
+ void mallBus.publish("parking.coupon.used", e);
132
+ };
133
+ }
134
+ };
135
+
136
+ export {
137
+ InMemoryParkingService,
138
+ meta_default,
139
+ serverModule
140
+ };
@@ -0,0 +1,55 @@
1
+ // src/client/cards/parking-fee/index.tsx
2
+ import { useState } from "react";
3
+ import { callAction } from "@tbox.cn/app-sdk/client";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ function ParkingFeeCard({
6
+ data,
7
+ isHistory
8
+ }) {
9
+ const [state, setState] = useState({});
10
+ const disabled = isHistory || data.status === "PAID" || state.loading;
11
+ const handleSettle = async () => {
12
+ if (disabled) return;
13
+ setState({ loading: true });
14
+ const res = await callAction("scenario-points-parking.run", {
15
+ userId: data.userId,
16
+ orderId: data.orderId
17
+ });
18
+ const text = res.data?.text;
19
+ setState({
20
+ loading: false,
21
+ ...res.success ? { text: text ?? "\u5DF2\u7ED3\u7B97" } : { error: res.error ?? "\u64CD\u4F5C\u5931\u8D25" }
22
+ });
23
+ };
24
+ return /* @__PURE__ */ jsxs("div", { className: "mall-card mall-card--parking", children: [
25
+ /* @__PURE__ */ jsx("div", { className: "mall-card__title", children: "\u505C\u8F66\u8D39" }),
26
+ /* @__PURE__ */ jsxs("div", { className: "mall-card__fee", children: [
27
+ data.fee,
28
+ " \u5143"
29
+ ] }),
30
+ /* @__PURE__ */ jsxs("div", { className: "mall-card__meta", children: [
31
+ data.plate,
32
+ " \xB7 ",
33
+ data.orderId,
34
+ " \xB7 ",
35
+ data.status
36
+ ] }),
37
+ isHistory ? /* @__PURE__ */ jsx("div", { className: "mall-card__note", children: "\u5386\u53F2\u5361\u7247\uFF0C\u64CD\u4F5C\u5DF2\u7981\u7528" }) : state.error ? /* @__PURE__ */ jsx("div", { className: "mall-card__note mall-card__note--error", children: state.error }) : state.text ? /* @__PURE__ */ jsx("div", { className: "mall-card__note", children: state.text }) : null,
38
+ /* @__PURE__ */ jsx("button", { className: "mall-card__btn", disabled, onClick: handleSettle, children: state.loading ? "\u5904\u7406\u4E2D\u2026" : data.status === "PAID" ? "\u5DF2\u652F\u4ED8" : "\u79EF\u5206\u62B5\u6263\u505C\u8F66\u8D39" })
39
+ ] });
40
+ }
41
+
42
+ // src/client/index.ts
43
+ var cards = {
44
+ "parking-fee": ParkingFeeCard
45
+ };
46
+ var clientModule = {
47
+ cards,
48
+ register(ctx) {
49
+ ctx.cards.registerMap(cards);
50
+ }
51
+ };
52
+
53
+ export {
54
+ clientModule
55
+ };
@@ -0,0 +1,12 @@
1
+ import { CardComponent } from '@tbox.cn/app-contracts';
2
+ import { ClientContext } from '@tbox.cn/app-sdk/client';
3
+
4
+ /** 模块注册入口:自注册闭环(与服务端 serverModule 对称) */
5
+ declare const clientModule: {
6
+ cards: {
7
+ readonly 'parking-fee': CardComponent;
8
+ };
9
+ register(ctx: ClientContext): void;
10
+ };
11
+
12
+ export { clientModule };
@@ -0,0 +1,6 @@
1
+ import {
2
+ clientModule
3
+ } from "../chunk-QQLBZY6D.js";
4
+ export {
5
+ clientModule
6
+ };
@@ -0,0 +1,7 @@
1
+ export { InMemoryParkingService, parkingFeeMeta, serverModule } from './server/index.js';
2
+ export { clientModule } from './client/index.js';
3
+ import '@tbox.cn/app-contracts';
4
+ import 'zod';
5
+ import '@tbox.cn/app-sdk/server';
6
+ import '@tbox.cn/app-contracts-mall';
7
+ import '@tbox.cn/app-sdk/client';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ import {
2
+ InMemoryParkingService,
3
+ meta_default,
4
+ serverModule
5
+ } from "./chunk-BYD3C6NE.js";
6
+ import {
7
+ clientModule
8
+ } from "./chunk-QQLBZY6D.js";
9
+ export {
10
+ InMemoryParkingService,
11
+ clientModule,
12
+ meta_default as parkingFeeMeta,
13
+ serverModule
14
+ };
@@ -0,0 +1,88 @@
1
+ import * as _tbox_cn_app_contracts from '@tbox.cn/app-contracts';
2
+ import { CardMeta } from '@tbox.cn/app-contracts';
3
+ import * as zod from 'zod';
4
+ import { z } from 'zod';
5
+ import { ServerContext } from '@tbox.cn/app-sdk/server';
6
+ import { ParkingQueryPort, ParkingSettlementPort, ParkingFee } from '@tbox.cn/app-contracts-mall';
7
+
8
+ /** ParkingService:停车完整实现(计费 / 券核销 / 结算) */
9
+ interface ParkingService extends ParkingQueryPort, ParkingSettlementPort {
10
+ orders: Map<string, ParkingFee>;
11
+ }
12
+ /** 内存实现(PoC):按 plate 生成固定费率订单 */
13
+ declare class InMemoryParkingService implements ParkingService {
14
+ orders: Map<string, ParkingFee>;
15
+ private couponsUsed;
16
+ constructor(initial?: Record<string, ParkingFee>);
17
+ /** 发券事件回调(由 serverModule.register 注入,保持 service 与 bus 解耦) */
18
+ onCouponUsed?: (e: {
19
+ userId: string;
20
+ couponId: string;
21
+ amount: number;
22
+ }) => void;
23
+ queryParkingFee(userId: string, orderId?: string): Promise<ParkingFee | undefined>;
24
+ calcFee(userId: string, orderId: string): Promise<ParkingFee>;
25
+ useCoupon(_userId: string, orderId: string, couponId: string): Promise<boolean>;
26
+ settlePayment(_userId: string, orderId: string, amount: number): Promise<boolean>;
27
+ }
28
+
29
+ declare const dataSchema: z.ZodObject<{
30
+ orderId: z.ZodString;
31
+ userId: z.ZodString;
32
+ plate: z.ZodString;
33
+ fee: z.ZodNumber;
34
+ paidAmount: z.ZodOptional<z.ZodNumber>;
35
+ pointsUsed: z.ZodOptional<z.ZodNumber>;
36
+ status: z.ZodEnum<["PENDING", "PAID", "CANCELLED"]>;
37
+ }, "strip", z.ZodTypeAny, {
38
+ orderId: string;
39
+ userId: string;
40
+ plate: string;
41
+ fee: number;
42
+ status: "PENDING" | "PAID" | "CANCELLED";
43
+ paidAmount?: number | undefined;
44
+ pointsUsed?: number | undefined;
45
+ }, {
46
+ orderId: string;
47
+ userId: string;
48
+ plate: string;
49
+ fee: number;
50
+ status: "PENDING" | "PAID" | "CANCELLED";
51
+ paidAmount?: number | undefined;
52
+ pointsUsed?: number | undefined;
53
+ }>;
54
+ declare const meta: CardMeta<typeof dataSchema>;
55
+
56
+ /** 模块注册入口:自注册闭环(与客户端 clientModule 对称) */
57
+ declare const serverModule: {
58
+ cards: {
59
+ readonly 'parking-fee': _tbox_cn_app_contracts.CardMeta<zod.ZodObject<{
60
+ orderId: zod.ZodString;
61
+ userId: zod.ZodString;
62
+ plate: zod.ZodString;
63
+ fee: zod.ZodNumber;
64
+ paidAmount: zod.ZodOptional<zod.ZodNumber>;
65
+ pointsUsed: zod.ZodOptional<zod.ZodNumber>;
66
+ status: zod.ZodEnum<["PENDING", "PAID", "CANCELLED"]>;
67
+ }, "strip", zod.ZodTypeAny, {
68
+ orderId: string;
69
+ userId: string;
70
+ plate: string;
71
+ fee: number;
72
+ status: "PENDING" | "PAID" | "CANCELLED";
73
+ paidAmount?: number | undefined;
74
+ pointsUsed?: number | undefined;
75
+ }, {
76
+ orderId: string;
77
+ userId: string;
78
+ plate: string;
79
+ fee: number;
80
+ status: "PENDING" | "PAID" | "CANCELLED";
81
+ paidAmount?: number | undefined;
82
+ pointsUsed?: number | undefined;
83
+ }>>;
84
+ };
85
+ register(ctx: ServerContext): void;
86
+ };
87
+
88
+ export { InMemoryParkingService, meta as parkingFeeMeta, serverModule };
@@ -0,0 +1,10 @@
1
+ import {
2
+ InMemoryParkingService,
3
+ meta_default,
4
+ serverModule
5
+ } from "../chunk-BYD3C6NE.js";
6
+ export {
7
+ InMemoryParkingService,
8
+ meta_default as parkingFeeMeta,
9
+ serverModule
10
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@tbox.cn/app-module-parking",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "商圈停车模块:计费、停车券核销、费用(codegen 源)。",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js"
10
+ },
11
+ "./server": {
12
+ "types": "./dist/server/index.d.ts",
13
+ "import": "./dist/server/index.js"
14
+ },
15
+ "./client": {
16
+ "types": "./dist/client/index.d.ts",
17
+ "import": "./dist/client/index.js"
18
+ }
19
+ },
20
+ "dependencies": {
21
+ "@tbox.cn/app-sdk": "^0.1.0",
22
+ "@tbox.cn/app-contracts": "^0.1.0",
23
+ "@tbox.cn/app-contracts-mall": "^0.1.0"
24
+ },
25
+ "peerDependencies": {
26
+ "zod": "^3.24.0",
27
+ "react": "^18.3.1"
28
+ },
29
+ "devDependencies": {
30
+ "@types/react": "^18.3.12",
31
+ "@types/node": "^24.0.0",
32
+ "typescript": "^5.7.0",
33
+ "tsx": "^4.19.0",
34
+ "vitest": "^4.1.4",
35
+ "zod": "^3.24.0",
36
+ "tsup": "^8.0.0"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "src",
41
+ "tests",
42
+ "tbox.component.json",
43
+ "tsconfig.json",
44
+ "tsup.config.ts",
45
+ "README.md",
46
+ "LICENSE"
47
+ ],
48
+ "engines": {
49
+ "node": ">=20.0.0"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "license": "MIT",
55
+ "scripts": {
56
+ "typecheck": "tsc --noEmit",
57
+ "test": "vitest run",
58
+ "build": "tsup"
59
+ }
60
+ }
@@ -0,0 +1,59 @@
1
+ import { useState } from 'react';
2
+ import { callAction } from '@tbox.cn/app-sdk/client';
3
+ import type { ParkingFeeCardData } from '../../../server/cards/parking-fee/meta';
4
+
5
+ /**
6
+ * 停车费卡(C1 示例:卡片 HTTP 写通道,004 W2)。
7
+ * 按钮 → callAction('scenario-points-parking.run') → POST /api/action → 校验链 → Service → setState。
8
+ * 历史恢复卡(isHistory)与已支付单禁用操作。
9
+ */
10
+ export function ParkingFeeCard({
11
+ data,
12
+ isHistory,
13
+ }: {
14
+ data: ParkingFeeCardData;
15
+ cardId: string;
16
+ isHistory: boolean;
17
+ }) {
18
+ const [state, setState] = useState<{
19
+ loading?: boolean;
20
+ text?: string;
21
+ error?: string;
22
+ }>({});
23
+
24
+ const disabled = isHistory || data.status === 'PAID' || state.loading;
25
+
26
+ const handleSettle = async () => {
27
+ if (disabled) return;
28
+ setState({ loading: true });
29
+ const res = await callAction('scenario-points-parking.run', {
30
+ userId: data.userId,
31
+ orderId: data.orderId,
32
+ });
33
+ const text = (res.data as { text?: string } | undefined)?.text;
34
+ setState({
35
+ loading: false,
36
+ ...(res.success ? { text: text ?? '已结算' } : { error: res.error ?? '操作失败' }),
37
+ });
38
+ };
39
+
40
+ return (
41
+ <div className="mall-card mall-card--parking">
42
+ <div className="mall-card__title">停车费</div>
43
+ <div className="mall-card__fee">{data.fee} 元</div>
44
+ <div className="mall-card__meta">
45
+ {data.plate} · {data.orderId} · {data.status}
46
+ </div>
47
+ {isHistory ? (
48
+ <div className="mall-card__note">历史卡片,操作已禁用</div>
49
+ ) : state.error ? (
50
+ <div className="mall-card__note mall-card__note--error">{state.error}</div>
51
+ ) : state.text ? (
52
+ <div className="mall-card__note">{state.text}</div>
53
+ ) : null}
54
+ <button className="mall-card__btn" disabled={disabled} onClick={handleSettle}>
55
+ {state.loading ? '处理中…' : data.status === 'PAID' ? '已支付' : '积分抵扣停车费'}
56
+ </button>
57
+ </div>
58
+ );
59
+ }
@@ -0,0 +1,16 @@
1
+ import type { CardComponent } from '@tbox.cn/app-contracts';
2
+ import type { ClientContext, ClientModule } from '@tbox.cn/app-sdk/client';
3
+ import { ParkingFeeCard } from './cards/parking-fee';
4
+
5
+ /** 客户端卡片组件 map(key 约定 = cardType;CLI sync 装配读取) */
6
+ const cards = {
7
+ 'parking-fee': ParkingFeeCard as CardComponent,
8
+ } as const;
9
+
10
+ /** 模块注册入口:自注册闭环(与服务端 serverModule 对称) */
11
+ export const clientModule = {
12
+ cards,
13
+ register(ctx: ClientContext): void {
14
+ ctx.cards.registerMap(cards);
15
+ },
16
+ } satisfies ClientModule;
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 模块主入口(package.json exports "." 指向)。
3
+ * 消费方通常走 ./server / ./client 子路径;主入口聚合导出便于直接引用。
4
+ */
5
+ export * from './server';
6
+ export * from './client';
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import type { CardMeta } from '@tbox.cn/app-contracts';
3
+
4
+ export const dataSchema = z.object({
5
+ orderId: z.string(),
6
+ userId: z.string(),
7
+ plate: z.string(),
8
+ fee: z.number(),
9
+ paidAmount: z.number().optional(),
10
+ pointsUsed: z.number().optional(),
11
+ status: z.enum(['PENDING', 'PAID', 'CANCELLED']),
12
+ });
13
+
14
+ export type ParkingFeeCardData = z.infer<typeof dataSchema>;
15
+
16
+ const meta: CardMeta<typeof dataSchema> = {
17
+ cardType: 'parking-fee',
18
+ dataSchema,
19
+ allowedTools: ['queryParkingFee'],
20
+ displayName: '停车费卡',
21
+ description: '展示停车费单与抵扣情况',
22
+ sampleData: { orderId: 'p_1', userId: 'u_1001', plate: '京A·001', fee: 20, status: 'PENDING' },
23
+ schemaVersion: 1,
24
+ };
25
+
26
+ export default meta;
@@ -0,0 +1,22 @@
1
+ import type { HandlerDefinition } from '@tbox.cn/app-sdk/server';
2
+ import type { ParkingQueryPort } from '@tbox.cn/app-contracts-mall';
3
+ import type { ServerContext } from '@tbox.cn/app-sdk/server';
4
+
5
+ /** parking handler:查停车费 → 出 parking-fee 卡 */
6
+ export function createParkingHandler(ctx: ServerContext): HandlerDefinition {
7
+ return {
8
+ id: 'parking',
9
+ handle: async (_action, payload) => {
10
+ const parking = ctx.resolveService<ParkingQueryPort>('parking');
11
+ if (!parking) return { cards: [], text: '停车服务不可用' };
12
+ const { userId, orderId } = (payload ?? {}) as { userId?: string; orderId?: string };
13
+ if (!userId) return { cards: [], text: '缺少 userId' };
14
+ const order = await parking.queryParkingFee(userId, orderId);
15
+ if (!order) return { cards: [], text: '无待结算停车费' };
16
+ return {
17
+ cards: [{ cardType: 'parking-fee', data: order as unknown as Record<string, unknown> }],
18
+ text: `停车费 ${order.fee} 元(订单 ${order.orderId})`,
19
+ };
20
+ },
21
+ };
22
+ }
@@ -0,0 +1,34 @@
1
+ import type { ServerContext, ServerModule, TypedBus } from '@tbox.cn/app-sdk/server';
2
+ import type { MallEventMap } from '@tbox.cn/app-contracts-mall';
3
+ import { InMemoryParkingService } from './service';
4
+ import parkingFeeMeta from './cards/parking-fee/meta';
5
+ import { createQueryParkingFeeTool } from './tool';
6
+ import { createParkingHandler } from './handler';
7
+
8
+ export { InMemoryParkingService } from './service';
9
+ export { default as parkingFeeMeta } from './cards/parking-fee/meta';
10
+
11
+ /** 模块级单例(B14):实例在模块包加载时创建,serverModule.register 幂等 */
12
+ const parking = new InMemoryParkingService();
13
+
14
+ /** 卡片 meta 声明 map(key 约定 = meta.cardType;数据 + 类型源) */
15
+ const cards = {
16
+ 'parking-fee': parkingFeeMeta,
17
+ } as const;
18
+
19
+ /** 模块注册入口:自注册闭环(与客户端 clientModule 对称) */
20
+ export const serverModule = {
21
+ cards,
22
+ register(ctx: ServerContext): void {
23
+ ctx.services.register('parking', parking);
24
+ ctx.tools.register(createQueryParkingFeeTool(() => ctx.resolveService('parking')));
25
+ ctx.cards.registerMap(cards);
26
+ ctx.handlers.register(createParkingHandler(ctx));
27
+
28
+ const mallBus = ctx.bus as unknown as TypedBus<MallEventMap>;
29
+ // 停车券核销 → 发布事件(parking 不依赖 member);publish 为 async(B1,fire-and-forget)
30
+ parking.onCouponUsed = (e) => {
31
+ void mallBus.publish('parking.coupon.used', e);
32
+ };
33
+ },
34
+ } satisfies ServerModule;
@@ -0,0 +1,59 @@
1
+ import type { ParkingFee } from '@tbox.cn/app-contracts-mall';
2
+ import type { ParkingQueryPort, ParkingSettlementPort } from '@tbox.cn/app-contracts-mall';
3
+
4
+ /** ParkingService:停车完整实现(计费 / 券核销 / 结算) */
5
+ export interface ParkingService extends ParkingQueryPort, ParkingSettlementPort {
6
+ orders: Map<string, ParkingFee>;
7
+ }
8
+
9
+ /** 内存实现(PoC):按 plate 生成固定费率订单 */
10
+ export class InMemoryParkingService implements ParkingService {
11
+ orders = new Map<string, ParkingFee>();
12
+ private couponsUsed = new Set<string>();
13
+
14
+ constructor(initial?: Record<string, ParkingFee>) {
15
+ if (initial) for (const [id, order] of Object.entries(initial)) this.orders.set(id, order);
16
+ }
17
+
18
+ /** 发券事件回调(由 serverModule.register 注入,保持 service 与 bus 解耦) */
19
+ onCouponUsed?: (e: { userId: string; couponId: string; amount: number }) => void;
20
+
21
+ async queryParkingFee(userId: string, orderId?: string): Promise<ParkingFee | undefined> {
22
+ if (orderId) return this.orders.get(orderId);
23
+ return [...this.orders.values()].find((o) => o.userId === userId && o.status === 'PENDING');
24
+ }
25
+
26
+ async calcFee(userId: string, orderId: string): Promise<ParkingFee> {
27
+ const existing = this.orders.get(orderId);
28
+ if (existing) return existing;
29
+ const order: ParkingFee = {
30
+ orderId,
31
+ userId,
32
+ plate: `京A·${String(userId).slice(-3) ?? '888'}`,
33
+ fee: 20, // PoC 固定 20 元
34
+ status: 'PENDING',
35
+ };
36
+ this.orders.set(orderId, order);
37
+ return order;
38
+ }
39
+
40
+ async useCoupon(_userId: string, orderId: string, couponId: string): Promise<boolean> {
41
+ const order = this.orders.get(orderId);
42
+ if (!order) return false;
43
+ if (this.couponsUsed.has(couponId)) return false; // 一张券只核销一次
44
+ this.couponsUsed.add(couponId);
45
+ this.onCouponUsed?.({ userId: _userId, couponId, amount: 5 }); // PoC 固定抵扣 5 元
46
+ return true;
47
+ }
48
+
49
+ async settlePayment(_userId: string, orderId: string, amount: number): Promise<boolean> {
50
+ const order = this.orders.get(orderId);
51
+ if (!order) return false;
52
+ // 幂等:已结算订单重复结算视为成功(scenario 重放时避免误判失败触发补偿退款)
53
+ if (order.status === 'PAID') return true;
54
+ if (order.status !== 'PENDING') return false;
55
+ order.status = 'PAID';
56
+ order.paidAmount = amount;
57
+ return true;
58
+ }
59
+ }
@@ -0,0 +1,36 @@
1
+ import { createTool } from '@tbox.cn/app-sdk/server';
2
+ import { z } from 'zod';
3
+ import type { ParkingQueryPort } from '@tbox.cn/app-contracts-mall';
4
+
5
+ /** 停车费查询工具(只读) */
6
+ export function createQueryParkingFeeTool(getParking: () => ParkingQueryPort | undefined) {
7
+ return createTool({
8
+ id: 'queryParkingFee',
9
+ description: '查询当前停车费单',
10
+ inputSchema: z.object({
11
+ userId: z.string().describe('会员 userId'),
12
+ orderId: z.string().optional(),
13
+ }),
14
+ outputSchema: z.object({
15
+ orderId: z.string(),
16
+ userId: z.string(),
17
+ plate: z.string(),
18
+ fee: z.number(),
19
+ status: z.enum(['PENDING', 'PAID', 'CANCELLED']),
20
+ }),
21
+ execute: async ({ userId, orderId }: { userId: string; orderId?: string }): Promise<{
22
+ orderId: string;
23
+ userId: string;
24
+ plate: string;
25
+ fee: number;
26
+ status: 'PENDING' | 'PAID' | 'CANCELLED';
27
+ }> => {
28
+ const parking = getParking();
29
+ const order = parking ? await parking.queryParkingFee(userId, orderId) : undefined;
30
+ if (!order) {
31
+ return { orderId: orderId ?? 'none', userId, plate: '-', fee: 0, status: 'PENDING' };
32
+ }
33
+ return { orderId: order.orderId, userId: order.userId, plate: order.plate, fee: order.fee, status: order.status };
34
+ },
35
+ });
36
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "module-parking",
4
+ "version": "0.1.0",
5
+ "kind": "business",
6
+ "risk": { "level": "medium", "writeBoundary": "source" },
7
+ "distribution": { "defaultMode": "codegen" },
8
+ "contributes": {
9
+ "handlers": ["parking"],
10
+ "tools": ["queryParkingFee"],
11
+ "cards": [{ "cardType": "parking-fee", "schemaVersion": 1 }],
12
+ "routes": [],
13
+ "pages": [],
14
+ "tabs": []
15
+ },
16
+ "dependencies": {
17
+ "modules": [{ "id": "contracts-mall", "required": true }]
18
+ },
19
+ "env": []
20
+ }
@@ -0,0 +1,49 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createServerContext } from '@tbox.cn/app-sdk/server';
3
+ import { serverModule } from '../src/server/index';
4
+
5
+ describe('module-parking 自注册与计费', () => {
6
+ it('serverModule.register 注册 tool/card/service/handler', () => {
7
+ const ctx = createServerContext();
8
+ serverModule.register(ctx);
9
+ expect(ctx.tools.has('queryParkingFee')).toBe(true);
10
+ expect(ctx.cards.has('parking-fee')).toBe(true);
11
+ expect(ctx.handlers.has('parking')).toBe(true);
12
+ });
13
+
14
+ it('calcFee 生成 PENDING 订单', async () => {
15
+ const ctx = createServerContext();
16
+ serverModule.register(ctx);
17
+ const parking = ctx.resolveService<{ calcFee(u: string, o: string): Promise<{ fee: number; status: string }> }>('parking')!;
18
+ const order = await parking.calcFee('u_1', 'p_1');
19
+ expect(order.fee).toBe(20);
20
+ expect(order.status).toBe('PENDING');
21
+ });
22
+
23
+ it('useCoupon 发布 parking.coupon.used 事件(与 member 解耦)', async () => {
24
+ const ctx = createServerContext();
25
+ serverModule.register(ctx);
26
+ let received: unknown;
27
+ ctx.bus.on('parking.coupon.used', (e) => (received = e));
28
+ const parking = ctx.resolveService<{
29
+ calcFee(u: string, o: string): Promise<unknown>;
30
+ useCoupon(u: string, o: string, c: string): Promise<boolean>;
31
+ }>('parking')!;
32
+ await parking.calcFee('u_1', 'p_1');
33
+ await parking.useCoupon('u_1', 'p_1', 'c_1');
34
+ expect(received).toEqual({ userId: 'u_1', couponId: 'c_1', amount: 5 });
35
+ });
36
+
37
+ it('settlePayment 幂等:已结算订单重复结算返回 true(scenario 重放不误退积分)', async () => {
38
+ const ctx = createServerContext();
39
+ serverModule.register(ctx);
40
+ const parking = ctx.resolveService<{
41
+ calcFee(u: string, o: string): Promise<{ fee: number; status: string }>;
42
+ settlePayment(u: string, o: string, a: number): Promise<boolean>;
43
+ }>('parking')!;
44
+ await parking.calcFee('u_1', 'p_1');
45
+ expect(await parking.settlePayment('u_1', 'p_1', 0)).toBe(true);
46
+ // 重复结算:幂等成功,不因 PAID 而返回 false
47
+ expect(await parking.settlePayment('u_1', 'p_1', 0)).toBe(true);
48
+ });
49
+ });
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", "tests"]
8
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,29 @@
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: true,
16
+ external: [
17
+ '@tbox.cn/app-sdk',
18
+ '@tbox.cn/app-contracts',
19
+ '@tbox.cn/app-contracts-mall',
20
+ 'react',
21
+ 'react-dom',
22
+ 'zod',
23
+ '@mastra/core',
24
+ 'express',
25
+ ],
26
+ esbuildOptions(options) {
27
+ options.jsx = 'automatic';
28
+ },
29
+ });