@tbox.cn/app-module-parking 0.1.0 → 0.9.3

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 (71) hide show
  1. package/AGENTS.md +16 -0
  2. package/README.md +58 -11
  3. package/dist/chunk-KEUD5YHH.js +1087 -0
  4. package/dist/chunk-QHLX6WXM.js +2667 -0
  5. package/dist/client/index.d.ts +17 -3
  6. package/dist/client/index.js +4 -2
  7. package/dist/index.d.ts +4 -3
  8. package/dist/index.js +14 -4
  9. package/dist/parking-2S2UPCOF.css +1306 -0
  10. package/dist/parking-guide-hero-pea-v2-X2O44LPQ.jpg +0 -0
  11. package/dist/server/index.d.ts +1216 -72
  12. package/dist/server/index.js +11 -3
  13. package/package.json +24 -16
  14. package/skills/parking/SKILL.md +165 -0
  15. package/skills/parking/references/payment-safety.md +25 -0
  16. package/src/client/assets/parking-guide-hero-pea-v2.jpg +0 -0
  17. package/src/client/assets/parking-guide-hero.jpg +0 -0
  18. package/src/client/assets.d.ts +5 -0
  19. package/src/client/cards/index.ts +8 -0
  20. package/src/client/cards/parking-info/index.tsx +41 -0
  21. package/src/client/cards/parking-payment/benefit-selection.ts +79 -0
  22. package/src/client/cards/parking-payment/index.tsx +442 -0
  23. package/src/client/cards/parking-payment-records/index.tsx +259 -0
  24. package/src/client/cards/parking-payment-result/index.tsx +83 -0
  25. package/src/client/cards/parking-vehicle-management/PlateKeyboard.tsx +106 -0
  26. package/src/client/cards/parking-vehicle-management/index.tsx +344 -0
  27. package/src/client/cards/parking-vehicle-management/plate-keyboard.ts +113 -0
  28. package/src/client/cards/view.ts +83 -0
  29. package/src/client/index.ts +19 -4
  30. package/src/client/styles/parking.css +1306 -0
  31. package/src/client/types/css.d.ts +2 -0
  32. package/src/server/actions.ts +975 -0
  33. package/src/server/cards/index.ts +14 -0
  34. package/src/server/cards/parking-info/meta.ts +19 -0
  35. package/src/server/cards/parking-info/samples.ts +50 -0
  36. package/src/server/cards/parking-payment/meta.ts +29 -0
  37. package/src/server/cards/parking-payment/samples.ts +311 -0
  38. package/src/server/cards/parking-payment-records/meta.ts +32 -0
  39. package/src/server/cards/parking-payment-records/samples.ts +86 -0
  40. package/src/server/cards/parking-payment-result/meta.ts +21 -0
  41. package/src/server/cards/parking-payment-result/samples.ts +84 -0
  42. package/src/server/cards/parking-vehicle-management/meta.ts +20 -0
  43. package/src/server/cards/parking-vehicle-management/samples.ts +73 -0
  44. package/src/server/domain.ts +279 -0
  45. package/src/server/handler.ts +47 -16
  46. package/src/server/index.ts +97 -17
  47. package/src/server/intent-context.ts +14 -0
  48. package/src/server/ports.ts +59 -0
  49. package/src/server/service.ts +474 -45
  50. package/src/server/tools.ts +846 -0
  51. package/tbox.module.json +107 -0
  52. package/tests/benefit-selection.test.ts +70 -0
  53. package/tests/cards-render.test.tsx +643 -0
  54. package/tests/dispatcher-flow.test.ts +256 -0
  55. package/tests/payment-flow.test.ts +420 -0
  56. package/tests/plate-keyboard.test.ts +158 -0
  57. package/tests/ports-resolve.test.ts +113 -0
  58. package/tests/pretool-parking-fee.test.ts +104 -0
  59. package/tests/samples.test.ts +44 -0
  60. package/tests/skills.test.ts +37 -0
  61. package/tests/tools-gate.test.ts +237 -0
  62. package/tests/tools-membership.test.ts +91 -0
  63. package/tests/view.test.ts +61 -0
  64. package/tsup.config.ts +9 -1
  65. package/dist/chunk-BYD3C6NE.js +0 -140
  66. package/dist/chunk-QQLBZY6D.js +0 -55
  67. package/src/client/cards/parking-fee/index.tsx +0 -59
  68. package/src/server/cards/parking-fee/meta.ts +0 -26
  69. package/src/server/tool.ts +0 -36
  70. package/tbox.component.json +0 -20
  71. package/tests/service.test.ts +0 -49
@@ -0,0 +1,975 @@
1
+ /**
2
+ * parking 写动作(10 动作;LLM 直写归零 D5)。
3
+ *
4
+ * 支付三步链(R2):
5
+ * confirm-payment(建单+签名+PAYING 持久化 → payment effect)
6
+ * → [client tradePay(SDK host-effect-runner)]
7
+ * → report-payment-result(uploadResult + reconcile 权威收口 F5 → 结果卡)
8
+ *
9
+ * 全部 singleUse + grant 闭环;cards key = meta.cardType。
10
+ */
11
+ import type { ServerContext } from '@tbox.cn/app-sdk/server';
12
+ import { coerceStringifiedFields } from '@tbox.cn/app-sdk/server';
13
+ import type { CardActionResult, RequestContext } from '@tbox.cn/app-contracts';
14
+ import { PARKING_PLATE_PATTERN, toMallQueryContext } from '@tbox.cn/app-contracts-mall';
15
+ import type { ParkingQueryContext, ParkingQueryPort } from '@tbox.cn/app-contracts-mall';
16
+ import { z } from 'zod';
17
+ import { resolveParkingPaymentPort, resolveParkingQueryPort, resolveParkingVehiclePort } from './ports';
18
+ import { projectMembership, projectSelectableBenefits, durationText } from './tools';
19
+ import {
20
+ assertQuoteRevision,
21
+ cacheQuote,
22
+ createPaymentRef,
23
+ formatCents,
24
+ loadCachedQuote,
25
+ loadOwnedPaymentOperation,
26
+ persistPaymentOperation,
27
+ recordQuotePayment,
28
+ settlePaymentOperation,
29
+ PAYMENT_CHANNEL_ALIPAY,
30
+ } from './domain';
31
+ import type { QuoteSnapshot } from './domain';
32
+
33
+ /** 车牌正则单一真源在 contracts-mall(PARKING_PLATE_PATTERN,双端同源;含新能源格式) */
34
+ const plateSchema = z
35
+ .string()
36
+ .regex(PARKING_PLATE_PATTERN, '请输入正确的车牌号(如 浙A12345 或新能源 浙AD12345)');
37
+
38
+ /**
39
+ * 动作上下文唯一来源 = execute 第二参 reqCtx(分发期注入,实例分裂/并发免疫)。
40
+ * ctx.auth 全局单例已拆除(上下文统一化 0.11.0):动作分发发生在引擎 run 外,
41
+ * 运行上下文不存在全局可读面(曾致全部动作静默失败,见 Agent Note:卡片动作上下文与反馈协议)。
42
+ */
43
+ function toQueryContext(
44
+ reqCtx: RequestContext | undefined,
45
+ ): { q: ParkingQueryContext; reqCtx: RequestContext } | null {
46
+ if (!reqCtx) return null;
47
+ return { q: toMallQueryContext(reqCtx), reqCtx };
48
+ }
49
+
50
+ /**
51
+ * 缴费卡终态数据(原地更新用):报价一经发起支付即终结——
52
+ * selectableBenefits 恒空(权益不可再改),settlement 让 UI 置灰按钮并给出状态。
53
+ */
54
+ function settledPaymentCardData(
55
+ quote: { quoteRef: string; plateNo: string; totalCents: number; discountCents: number; payableCents: number; revision: number; feeItems: readonly { name: string; amountCents: number }[] },
56
+ settlement: { state: 'paying' | 'paid' | 'failed'; text: string },
57
+ ): Record<string, unknown> {
58
+ return {
59
+ quoteRef: quote.quoteRef,
60
+ plateNo: quote.plateNo,
61
+ feeItems: quote.feeItems.map((i) => ({
62
+ name: i.name,
63
+ amountText: formatCents(i.amountCents),
64
+ })),
65
+ totalText: formatCents(quote.totalCents),
66
+ ...(quote.discountCents > 0 ? { discountText: formatCents(quote.discountCents) } : {}),
67
+ payableText: formatCents(quote.payableCents),
68
+ appliedBenefits: [],
69
+ selectableBenefits: [],
70
+ revision: quote.revision,
71
+ caveats: ['费用以出场实际计费为准'],
72
+ settlement,
73
+ };
74
+ }
75
+
76
+ /** 停车时长文案:盘古之白(数字与中文单位间半角空格) */
77
+ function parkedDurationText(entryAt?: string, paidAt?: string): string | undefined {
78
+ if (!entryAt) return undefined;
79
+ const end = paidAt ? new Date(paidAt).getTime() : Date.now();
80
+ const minutes = Math.round((end - new Date(entryAt).getTime()) / 60_000);
81
+ if (!Number.isFinite(minutes) || minutes < 0) return undefined;
82
+ const h = Math.floor(minutes / 60);
83
+ const m = minutes % 60;
84
+ return [h > 0 ? `${h} 小时` : '', m > 0 || h === 0 ? `${m} 分` : ''].filter(Boolean).join(' ');
85
+ }
86
+
87
+ /** 缴费时间文案:当天显示「今天 HH:mm」,跨天显示日期 */
88
+ function paidAtText(iso?: string): string | undefined {
89
+ if (!iso) return undefined;
90
+ const d = new Date(iso);
91
+ if (Number.isNaN(d.getTime())) return undefined;
92
+ const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
93
+ const today = new Date();
94
+ const sameDay =
95
+ d.getFullYear() === today.getFullYear() &&
96
+ d.getMonth() === today.getMonth() &&
97
+ d.getDate() === today.getDate();
98
+ return sameDay ? `今天 ${hm}` : `${d.getMonth() + 1} 月 ${d.getDate()} 日 ${hm}`;
99
+ }
100
+
101
+ /**
102
+ * 回执明细(车牌 / 停车时长 / 缴费时间):只放实际拿得到的字段,缺一项就少一行,不编造。
103
+ * 动作与工具两条出卡路径共用,避免两处漂移。
104
+ */
105
+ export function receiptDetails(op: {
106
+ plateNo: string;
107
+ entryAt?: string;
108
+ paidAt?: string;
109
+ createdAt: string;
110
+ }): { label: string; value: string }[] {
111
+ const duration = parkedDurationText(op.entryAt, op.paidAt ?? op.createdAt);
112
+ const paid = paidAtText(op.paidAt ?? op.createdAt);
113
+ return [
114
+ { label: '车牌', value: op.plateNo },
115
+ ...(duration ? [{ label: '停车时长', value: duration }] : []),
116
+ ...(paid ? [{ label: '缴费时间', value: paid }] : []),
117
+ ];
118
+ }
119
+
120
+ /** parking-payment 结果卡(失败可重开确认卡) */
121
+ function paymentResultCard(data: Record<string, unknown>): {
122
+ cardType: string;
123
+ data: Record<string, unknown>;
124
+ } {
125
+ return { cardType: 'parking-payment-result', data };
126
+ }
127
+
128
+ export function createParkingActions(
129
+ ctx: ServerContext,
130
+ ): Record<string, Parameters<ServerContext['cardActions']['register']>[0]> {
131
+ const state = ctx.state as never as import('./domain').StoreLike;
132
+ /** 动作槽解析器(017 槽位原子化):按动作语义选槽——支付族 → parking.payment、
133
+ * 车辆绑定族 → parking.vehicle、查询族 → parking.query;双槽动作(bind/unbind/
134
+ * apply-invoice)按方法分属各解析一次(部分绑定时语义显式分裂)。 */
135
+ const serviceOf = async <T>(
136
+ reqCtx: RequestContext | undefined,
137
+ resolve: (reqCtx: RequestContext, ctx: ServerContext) => Promise<T>,
138
+ ): Promise<{
139
+ service: T;
140
+ q: ParkingQueryContext;
141
+ } | null> => {
142
+ const c = toQueryContext(reqCtx);
143
+ if (!c) return null;
144
+ const service = await resolve(c.reqCtx, ctx);
145
+ return { service, q: c.q };
146
+ };
147
+
148
+ return {
149
+ /** 1. 确认缴费(三步链 step1:建单 → 签名 → PAYING 持久化 → payment effect) */
150
+ confirmPayment: {
151
+ actionId: 'parking.confirm-payment',
152
+ moduleId: 'parking',
153
+ cardType: 'parking-payment',
154
+ label: '确认支付',
155
+ singleUse: true,
156
+ inputSchema: coerceInput(
157
+ z.object({
158
+ quoteRef: z.string().min(1),
159
+ revision: z
160
+ .union([z.string(), z.number()])
161
+ .transform((v) => String(v))
162
+ .optional()
163
+ .describe('卡上 revision(字符串化的乐观锁版本;兼容 number/string)'),
164
+ benefitRefs: z
165
+ .array(z.string())
166
+ .optional()
167
+ .describe('勾选的权益(与 revision 对应)'),
168
+ }),
169
+ ),
170
+ async execute(input, reqCtx): Promise<CardActionResult> {
171
+ const { quoteRef, revision, benefitRefs } = (input ?? {}) as {
172
+ quoteRef?: string;
173
+ revision?: string;
174
+ benefitRefs?: string[];
175
+ };
176
+ const s = await serviceOf(reqCtx, resolveParkingPaymentPort);
177
+ const owner = s ? paymentOwner(s.q) : null;
178
+ if (!s || !owner || !quoteRef) {
179
+ return { text: '缴费失败:缺少会话上下文或报价引用' };
180
+ }
181
+
182
+ // revision CAS(旧卡重放/缓存过期拒绝——恒实时语义下用户重新查询即得新报价,W4)
183
+ const expectedRevision = revision ? Number(revision) : undefined;
184
+ let quote = expectedRevision
185
+ ? await assertQuoteRevision(state, quoteRef, expectedRevision, owner)
186
+ : null;
187
+ if (!quote) {
188
+ return {
189
+ card: paymentResultCard({
190
+ paymentRef: '',
191
+ plateNo: '',
192
+ status: 'UNKNOWN',
193
+ message: '报价已过期,请重新查询停车费',
194
+ retryable: true,
195
+ }),
196
+ text: '报价已过期(可能已超 5 分钟),请重新查询停车费',
197
+ };
198
+ }
199
+
200
+ // 权益重选(卡上勾选与已生效不一致时,revision 递增后建单)
201
+ if (benefitRefs && benefitRefs.length >= 0) {
202
+ const current = quote.appliedBenefits
203
+ .map((b) => b.benefitRef)
204
+ .sort()
205
+ .join(',');
206
+ const next = [...benefitRefs].sort().join(',');
207
+ if (current !== next) {
208
+ try {
209
+ quote = await s.service.reprice(s.q, quoteRef, benefitRefs, {
210
+ plateNo: quote.plateNo,
211
+ payableCents: quote.payableCents,
212
+ });
213
+ await cacheQuote(state, quote, owner);
214
+ } catch (e) {
215
+ ctx.logger?.warn(
216
+ `重定价失败(confirmPayment 权益重选):err=${(e as Error).message}`,
217
+ );
218
+ return {
219
+ card: paymentResultCard({
220
+ paymentRef: '',
221
+ plateNo: quote.plateNo,
222
+ status: 'CANCELLED',
223
+ message: `权益重选失败:${(e as Error).message}`,
224
+ retryable: true,
225
+ }),
226
+ text: '权益重选失败,请重新查询',
227
+ };
228
+ }
229
+ }
230
+ }
231
+ const effectiveQuoteRef = quote.quoteRef;
232
+ const selectedBenefitRefs = quote.appliedBenefits.map((b) => b.benefitRef);
233
+
234
+ // 零元分支:不拉收银台直接收口
235
+ if (quote.payableCents === 0) {
236
+ const { paymentRef: providerPaymentRef } =
237
+ await s.service.createOrder(s.q, effectiveQuoteRef, {
238
+ plateNo: quote.plateNo,
239
+ payableCents: quote.payableCents,
240
+ benefitRefs: selectedBenefitRefs,
241
+ });
242
+ const paymentRef = createPaymentRef();
243
+ await recordQuotePayment(state, effectiveQuoteRef, paymentRef, owner);
244
+ await persistPaymentOperation(state, {
245
+ paymentRef,
246
+ providerPaymentRef,
247
+ quoteRef: effectiveQuoteRef,
248
+ plateNo: quote.plateNo,
249
+ ...(quote.entryAt ? { entryAt: quote.entryAt } : {}),
250
+ subjectId: owner.subjectId,
251
+ mallId: owner.mallId,
252
+ payableCents: 0,
253
+ status: 'PAYING',
254
+ createdAt: new Date().toISOString(),
255
+ });
256
+ const final = await s.service.reconcile(s.q, providerPaymentRef);
257
+ await settlePaymentOperation(
258
+ state,
259
+ paymentRef,
260
+ final === 'PAID'
261
+ ? 'PAID'
262
+ : final === 'CANCELLED'
263
+ ? 'CANCELLED'
264
+ : 'UNKNOWN',
265
+ );
266
+ return {
267
+ card: paymentResultCard({
268
+ paymentRef,
269
+ plateNo: quote.plateNo,
270
+ status: final === 'PAID' ? 'PAID' : 'UNKNOWN',
271
+ amountText: '0.00 元',
272
+ message:
273
+ final === 'PAID' ? '无需支付,费用已全部抵扣' : '零元单确认中',
274
+ }),
275
+ text: '无需支付:费用已全部抵扣',
276
+ };
277
+ }
278
+
279
+ // step1:建单(quote 明细随行——外部支付服务需真实车牌/金额)
280
+ const { payOrderId, paymentRef: providerPaymentRef } = await s.service
281
+ .createOrder(s.q, effectiveQuoteRef, {
282
+ plateNo: quote.plateNo,
283
+ payableCents: quote.payableCents,
284
+ benefitRefs: selectedBenefitRefs,
285
+ })
286
+ .catch((e: Error) => {
287
+ ctx.logger?.warn(`建单失败:err=${e.message}`);
288
+ throw new Error(`建单失败:${e.message}`);
289
+ });
290
+ const paymentRef = createPaymentRef();
291
+ await recordQuotePayment(state, effectiveQuoteRef, paymentRef, owner);
292
+
293
+ // 无 payOrderId → 直接 reconcile 收口(受理型)
294
+ if (!payOrderId) {
295
+ await persistPaymentOperation(state, {
296
+ paymentRef,
297
+ providerPaymentRef,
298
+ quoteRef: effectiveQuoteRef,
299
+ plateNo: quote.plateNo,
300
+ ...(quote.entryAt ? { entryAt: quote.entryAt } : {}),
301
+ subjectId: owner.subjectId,
302
+ mallId: owner.mallId,
303
+ payableCents: quote.payableCents,
304
+ status: 'PAYING',
305
+ createdAt: new Date().toISOString(),
306
+ });
307
+ const final = await s.service.reconcile(s.q, providerPaymentRef);
308
+ await settlePaymentOperation(
309
+ state,
310
+ paymentRef,
311
+ final === 'PAID'
312
+ ? 'PAID'
313
+ : final === 'CANCELLED'
314
+ ? 'CANCELLED'
315
+ : 'UNKNOWN',
316
+ );
317
+ return {
318
+ card: paymentResultCard({
319
+ paymentRef,
320
+ plateNo: quote.plateNo,
321
+ status: final === 'PAID' ? 'PAID' : 'UNKNOWN',
322
+ amountText: formatCents(quote.payableCents),
323
+ message:
324
+ final === 'PAID'
325
+ ? '支付成功'
326
+ : '支付结果确认中,可稍后查询缴费记录',
327
+ }),
328
+ text: final === 'PAID' ? '支付成功' : '已受理,结果确认中',
329
+ };
330
+ }
331
+
332
+ // 渠道校验(channel 50 = 支付宝)
333
+ const orderInfo = await s.service.getOrderInfo(s.q, providerPaymentRef);
334
+ if (orderInfo.channel !== PAYMENT_CHANNEL_ALIPAY) {
335
+ return {
336
+ card: paymentResultCard({
337
+ paymentRef,
338
+ plateNo: quote.plateNo,
339
+ status: 'CANCELLED',
340
+ message: '当前停车订单暂不支持支付宝支付',
341
+ retryable: false,
342
+ }),
343
+ text: '暂不支持支付宝支付该订单',
344
+ };
345
+ }
346
+ const authoritativeAmount =
347
+ orderInfo.payableFeeCents ?? quote.payableCents;
348
+
349
+ // step2 前置:签名串(空签名防御——POC 7e9a05a 对齐:厂商返回空串将拉起空收银台并制造悬挂 PAYING)
350
+ const { orderInfo: sign, payOrderFlowId } = await s.service.getPaymentSign(
351
+ s.q,
352
+ providerPaymentRef,
353
+ );
354
+ const signStr = typeof sign === 'string' ? sign.trim() : '';
355
+ if (!signStr) {
356
+ return {
357
+ card: paymentResultCard({
358
+ paymentRef,
359
+ plateNo: quote.plateNo,
360
+ status: 'CANCELLED',
361
+ message: '支付签名获取失败,暂无法拉起收银台',
362
+ retryable: true,
363
+ }),
364
+ text: '支付签名获取失败,请稍后重试',
365
+ };
366
+ }
367
+
368
+ // PAYING 持久化(悬挂收口锚点,V2)
369
+ await persistPaymentOperation(state, {
370
+ paymentRef,
371
+ providerPaymentRef,
372
+ quoteRef: effectiveQuoteRef,
373
+ plateNo: quote.plateNo,
374
+ ...(quote.entryAt ? { entryAt: quote.entryAt } : {}),
375
+ subjectId: owner.subjectId,
376
+ mallId: owner.mallId,
377
+ payableCents: authoritativeAmount,
378
+ payOrderNoMasked:
379
+ payOrderId.length > 8
380
+ ? `${payOrderId.slice(0, 4)}****${payOrderId.slice(-4)}`
381
+ : payOrderId,
382
+ ...(payOrderFlowId ? { payOrderFlowId } : {}),
383
+ status: 'PAYING',
384
+ createdAt: new Date().toISOString(),
385
+ });
386
+
387
+ // step2:payment effect(dispatcher 补签 → client tradePay,R1 orderInfo 内联)
388
+ // 同时原地终结缴费卡:token 已 singleUse 消费、revision 已锁定,这张报价单不能再提交。
389
+ // 支付的最终成败经 report-payment-result 落在回执卡上——effect 回传无卡锚点
390
+ // (chat-store sendModuleAction 恒 surfaceId:''),服务端无法二次原地更新本卡。
391
+ return {
392
+ text: `正在拉起支付宝支付(应付 ${formatCents(authoritativeAmount)})…`,
393
+ update: {
394
+ data: settledPaymentCardData(
395
+ { ...quote, payableCents: authoritativeAmount },
396
+ { state: 'paying', text: '支付处理中,结果以回执为准' },
397
+ ),
398
+ },
399
+ effects: [
400
+ {
401
+ type: 'payment',
402
+ paymentRef,
403
+ orderInfo: signStr,
404
+ resultActionId: 'parking.report-payment-result',
405
+ },
406
+ ],
407
+ };
408
+ },
409
+ },
410
+
411
+ /** 2. 支付结果回调(三步链 step3:uploadResult + reconcile 权威收口,F5;补签通道专用不渲染按钮) */
412
+ reportPaymentResult: {
413
+ actionId: 'parking.report-payment-result',
414
+ moduleId: 'parking',
415
+ cardType: 'parking-payment',
416
+ label: '支付结果回调',
417
+ singleUse: true,
418
+ hidden: true,
419
+ inputSchema: coerceInput(
420
+ z.object({
421
+ status: z.enum(['success', 'cancel', 'failure', 'unavailable']),
422
+ paymentRef: z.string().optional(),
423
+ }),
424
+ ),
425
+ async execute(input, reqCtx): Promise<CardActionResult> {
426
+ const { status, paymentRef } = (input ?? {}) as {
427
+ status?: string;
428
+ paymentRef?: string;
429
+ };
430
+ const s = await serviceOf(reqCtx, resolveParkingPaymentPort);
431
+ if (!s || !paymentRef) return { text: '支付结果回传缺少引用' };
432
+ const owner = paymentOwner(s.q);
433
+ const op = owner
434
+ ? await loadOwnedPaymentOperation(state, paymentRef, owner)
435
+ : null;
436
+ if (!op) return { text: '支付记录不可用,请重新查询停车费' };
437
+
438
+ await s.service
439
+ .uploadResult(
440
+ s.q,
441
+ op.providerPaymentRef,
442
+ (status ?? 'failure') as
443
+ | 'success'
444
+ | 'cancel'
445
+ | 'failure'
446
+ | 'unavailable',
447
+ op.payOrderFlowId,
448
+ )
449
+ .catch((e: unknown) => {
450
+ // 资损排查路径:支付结果上报厂商失败必须留痕(error 级)
451
+ ctx.logger?.error(
452
+ `⚠ 支付结果上报失败(资损排查):paymentRef=${paymentRef} err=${(e as Error).message}`,
453
+ );
454
+ return undefined;
455
+ });
456
+ // F5:收口判定恒 reconcile 权威回查(客户端 status 仅上报)
457
+ const final = await s.service.reconcile(s.q, op.providerPaymentRef);
458
+ const settled = await settlePaymentOperation(
459
+ state,
460
+ paymentRef,
461
+ final === 'PAID'
462
+ ? 'PAID'
463
+ : final === 'CANCELLED'
464
+ ? 'CANCELLED'
465
+ : 'UNKNOWN',
466
+ );
467
+ const current = settled ?? op;
468
+
469
+ if (current.status === 'PAID') {
470
+ return {
471
+ card: paymentResultCard({
472
+ paymentRef,
473
+ plateNo: current.plateNo,
474
+ status: 'PAID',
475
+ amountText: formatCents(current.payableCents),
476
+ message: '缴费成功,祝您出场顺利',
477
+ leaveNotice: '请在 15 分钟内离场,超时将重新计费',
478
+ details: receiptDetails(current),
479
+ }),
480
+ text: '停车费支付成功',
481
+ };
482
+ }
483
+ if (current.status === 'CANCELLED') {
484
+ return {
485
+ card: paymentResultCard({
486
+ paymentRef,
487
+ plateNo: current.plateNo,
488
+ status: 'CANCELLED',
489
+ message: '支付已取消,可重新发起缴费',
490
+ // 终态:取消就是取消了,刷新不会变。重新发起要走「查询停车费」拿新报价。
491
+ details: receiptDetails(current),
492
+ }),
493
+ text: '支付已取消',
494
+ };
495
+ }
496
+ // PAYING/UNKNOWN:悬挂(V2:下次交互收口)或用户主动刷新
497
+ return {
498
+ card: paymentResultCard({
499
+ paymentRef,
500
+ plateNo: current.plateNo,
501
+ status: 'UNKNOWN',
502
+ amountText: formatCents(current.payableCents),
503
+ message:
504
+ status === 'unavailable'
505
+ ? '当前环境不支持拉起支付,费用未支付;可在支付宝内重试或前往出口岗亭缴费'
506
+ : '支付结果确认中(对账中);若已扣款请勿重复支付,稍后可在缴费记录中确认',
507
+ retryable: true,
508
+ details: receiptDetails(current),
509
+ }),
510
+ text: '支付结果确认中',
511
+ };
512
+ },
513
+ },
514
+
515
+ /** 3. 权益重选(revision CAS → 新报价卡) */
516
+ reprice: {
517
+ actionId: 'parking.reprice',
518
+ moduleId: 'parking',
519
+ cardType: 'parking-payment',
520
+ label: '重新计算',
521
+ singleUse: true,
522
+ inputSchema: coerceInput(
523
+ z.object({
524
+ quoteRef: z.string().min(1),
525
+ revision: z.union([z.string(), z.number()]).transform((v) => String(v)).optional(),
526
+ benefitRefs: z.array(z.string()).describe('勾选的权益引用列表'),
527
+ }),
528
+ ),
529
+ async execute(input, reqCtx): Promise<CardActionResult> {
530
+ const {
531
+ quoteRef,
532
+ revision,
533
+ benefitRefs = [],
534
+ } = (input ?? {}) as {
535
+ quoteRef?: string;
536
+ revision?: string;
537
+ benefitRefs?: string[];
538
+ };
539
+ const s = await serviceOf(reqCtx, resolveParkingPaymentPort);
540
+ const owner = s ? paymentOwner(s.q) : null;
541
+ if (!s || !owner || !quoteRef)
542
+ return { text: '重算失败:缺少报价引用' };
543
+ const expected = revision ? Number(revision) : undefined;
544
+ let quote: QuoteSnapshot | null = null;
545
+ if (expected) {
546
+ quote = await assertQuoteRevision(
547
+ state,
548
+ quoteRef,
549
+ expected,
550
+ owner,
551
+ );
552
+ if (!quote) return { text: '报价已更新,请以最新缴费卡为准' };
553
+ } else {
554
+ quote = await loadCachedQuote(state, quoteRef, owner);
555
+ if (!quote) return { text: '报价已过期,请重新查询停车费' };
556
+ }
557
+ try {
558
+ const next = await s.service.reprice(s.q, quoteRef, benefitRefs, {
559
+ plateNo: quote.plateNo,
560
+ payableCents: quote.payableCents,
561
+ });
562
+ await cacheQuote(state, next, owner);
563
+ // 权益查询走 query 槽(双槽动作:reprice 写 payment 槽 + 权益查 query 槽)
564
+ const query = await resolveParkingQueryPort(reqCtx as RequestContext, ctx);
565
+ const [benefits, membership] = await Promise.all([
566
+ query
567
+ .queryApplicableBenefits(s.q, next.plateNo)
568
+ .catch((e: unknown) => {
569
+ ctx.logger?.warn(
570
+ `权益查询失败,降级空:err=${(e as Error).message}`,
571
+ );
572
+ return [];
573
+ }),
574
+ projectMembership(ctx, reqCtx, s.q.subjectId),
575
+ ]);
576
+ return {
577
+ // 原地刷新被点击卡(与 card 互斥):勾选触发的 reprice 必须用 update,
578
+ // 否则原卡不刷新、前端 repricing 状态不复位 → 卡在"权益核算中"
579
+ update: {
580
+ data: {
581
+ quoteRef: next.quoteRef,
582
+ plateNo: next.plateNo,
583
+ // 原地刷新必须回填入场/时长,否则卡片刷新后这两项变空(与 queryParkingFee 同源)
584
+ entryAtText: next.entryAt
585
+ ? new Date(next.entryAt).toLocaleString('zh-CN')
586
+ : undefined,
587
+ durationText: durationText(next.entryAt),
588
+ feeItems: next.feeItems.map((i) => ({
589
+ name: i.name,
590
+ amountText: formatCents(i.amountCents),
591
+ })),
592
+ totalText: formatCents(next.totalCents),
593
+ discountText:
594
+ next.discountCents > 0
595
+ ? formatCents(next.discountCents)
596
+ : undefined,
597
+ payableText: formatCents(next.payableCents),
598
+ membership,
599
+ appliedBenefits: next.appliedBenefits.map((b) => ({
600
+ benefitRef: b.benefitRef,
601
+ title: b.title,
602
+ })),
603
+ selectableBenefits: projectSelectableBenefits(next, benefits, membership),
604
+ revision: next.revision,
605
+ caveats: ['权益以商户核验结果为准'],
606
+ },
607
+ },
608
+ text: `已重算:应付 ${formatCents(next.payableCents)}`,
609
+ };
610
+ } catch (e) {
611
+ ctx.logger?.warn(
612
+ `重定价失败(reprice):err=${(e as Error).message}`,
613
+ );
614
+ return { text: `重算失败:${(e as Error).message}` };
615
+ }
616
+ },
617
+ },
618
+
619
+ /** 4-6. 车辆三操作(LLM 直写归零,D5;车牌正则校验) */
620
+ bindVehicle: {
621
+ actionId: 'parking.bind-vehicle',
622
+ moduleId: 'parking',
623
+ cardType: 'parking-vehicle-management',
624
+ label: '绑定车辆',
625
+ singleUse: true,
626
+ inputSchema: coerceInput(z.object({ plateNo: plateSchema })),
627
+ async execute(input, reqCtx): Promise<CardActionResult> {
628
+ const { plateNo } = (input ?? {}) as { plateNo?: string };
629
+ const s = await serviceOf(reqCtx, resolveParkingVehiclePort);
630
+ if (!s || !plateNo) return { text: '绑定失败:缺少车牌' };
631
+ const vehicle = await s.service
632
+ .bindVehicle(s.q, plateNo)
633
+ .catch((e: Error) => {
634
+ ctx.logger?.warn(`绑定失败:err=${e.message}`);
635
+ throw new Error(`绑定失败:${e.message}`);
636
+ });
637
+ // 列表刷新走 query 槽(双槽动作:写 vehicle 槽 + 查 query 槽)
638
+ const query = await resolveParkingQueryPort(reqCtx as RequestContext, ctx);
639
+ const refreshed = await vehiclesCard(query, s.q, `已绑定 ${vehicle.plateNo}`);
640
+ return {
641
+ update: { data: refreshed.data },
642
+ text: `车辆 ${vehicle.plateNo} 绑定成功`,
643
+ };
644
+ },
645
+ },
646
+ unbindVehicle: {
647
+ actionId: 'parking.unbind-vehicle',
648
+ moduleId: 'parking',
649
+ cardType: 'parking-vehicle-management',
650
+ label: '解绑车辆',
651
+ singleUse: true,
652
+ inputSchema: coerceInput(
653
+ z.object({
654
+ plateNo: plateSchema.optional(),
655
+ vehicleRef: z.string().optional(),
656
+ }),
657
+ ),
658
+ async execute(input, reqCtx): Promise<CardActionResult> {
659
+ const { plateNo, vehicleRef } = (input ?? {}) as {
660
+ plateNo?: string;
661
+ vehicleRef?: string;
662
+ };
663
+ const s = await serviceOf(reqCtx, resolveParkingVehiclePort);
664
+ if (!s || !plateNo) return { text: '解绑失败:缺少车牌或车辆引用' };
665
+ // 列表匹配与刷新走 query 槽;解绑写走 vehicle 槽(双槽动作,方法分属)
666
+ const query = await resolveParkingQueryPort(reqCtx as RequestContext, ctx);
667
+ const { bound } = await query.listVehicles(s.q);
668
+ const matched = bound.find((vehicle) =>
669
+ vehicleRef
670
+ ? vehicle.vehicleRef === vehicleRef
671
+ : vehicle.plateNo === plateNo,
672
+ );
673
+ if (!matched) return { text: '车辆引用不可用,未执行解绑' };
674
+ await s.service
675
+ .unbindVehicle(s.q, { vehicleRef: matched.vehicleRef })
676
+ .catch((e: Error) => {
677
+ ctx.logger?.warn(`解绑失败:err=${e.message}`);
678
+ throw new Error(`解绑失败:${e.message}`);
679
+ });
680
+ // 原地更新(surfaceId 锚定):刷新车辆列表 + 重签 token + 复位组件 loading
681
+ const refreshed = await vehiclesCard(query, s.q, `已解绑 ${matched.plateNo}`);
682
+ return {
683
+ update: { data: refreshed.data },
684
+ text: '解绑成功',
685
+ };
686
+ },
687
+ },
688
+ /** 已绑定车辆寻车:vehicleRef 必须先在当前用户车辆列表中解析。 */
689
+ locateVehicle: {
690
+ actionId: 'parking.locate-vehicle',
691
+ moduleId: 'parking',
692
+ cardType: 'parking-vehicle-management',
693
+ label: '一键寻车',
694
+ singleUse: true,
695
+ inputSchema: coerceInput(z.object({ vehicleRef: z.string().min(1) })),
696
+ async execute(input, reqCtx): Promise<CardActionResult> {
697
+ const { vehicleRef } = (input ?? {}) as { vehicleRef?: string };
698
+ const s = await serviceOf(reqCtx, resolveParkingQueryPort);
699
+ if (!s || !vehicleRef) return { text: '寻车失败:缺少车辆引用' };
700
+ const { bound } = await s.service.listVehicles(s.q);
701
+ const vehicle = bound.find((item) => item.vehicleRef === vehicleRef);
702
+ if (!vehicle) return { text: '车辆引用不可用,请刷新车辆列表' };
703
+ const location = await s.service.locateVehicle(s.q, vehicle.plateNo);
704
+ return {
705
+ card: {
706
+ cardType: 'parking-info',
707
+ data: locationCardData(vehicle.plateNo, location),
708
+ },
709
+ text: location
710
+ ? `${vehicle.plateNo} 的停车位置已找到`
711
+ : `暂未找到 ${vehicle.plateNo} 的停车位置`,
712
+ };
713
+ },
714
+ },
715
+
716
+ /** 缴费记录详情:recordRef 的归属由 Port 按当前用户记录列表解析。 */
717
+ openRecordDetail: {
718
+ actionId: 'parking.open-record-detail',
719
+ moduleId: 'parking',
720
+ cardType: 'parking-payment-records',
721
+ label: '查看详情',
722
+ singleUse: true,
723
+ inputSchema: coerceInput(
724
+ z.object({ recordRef: z.coerce.string().min(1).max(128) }),
725
+ ),
726
+ async execute(input, reqCtx): Promise<CardActionResult> {
727
+ const { recordRef } = (input ?? {}) as { recordRef?: string };
728
+ const s = await serviceOf(reqCtx, resolveParkingQueryPort);
729
+ if (!s || !recordRef) return { text: '查询失败:缺少缴费记录引用' };
730
+ const detail = await s.service.getPaymentRecordDetail(s.q, recordRef);
731
+ const settings = await s.service
732
+ .getInvoiceSettings(s.q)
733
+ .catch((error: unknown) => {
734
+ ctx.logger?.warn(
735
+ `停车开票配置查询失败,按不可开票降级:err=${(error as Error).message}`,
736
+ );
737
+ return { parkingInvoiceEnabled: false };
738
+ });
739
+ return {
740
+ card: recordsCard(
741
+ [withInvoiceEligibility(detail, settings.parkingInvoiceEnabled)],
742
+ '已加载订单详情',
743
+ ),
744
+ text: '停车缴费订单详情已加载',
745
+ };
746
+ },
747
+ },
748
+
749
+ /** 申请开票:配置、订单完成态、已开票态均以服务端实时结果为准。 */
750
+ applyInvoice: {
751
+ actionId: 'parking.apply-invoice',
752
+ moduleId: 'parking',
753
+ cardType: 'parking-payment-records',
754
+ label: '申请开票',
755
+ singleUse: true,
756
+ inputSchema: coerceInput(
757
+ z.object({ recordRef: z.coerce.string().min(1).max(128) }),
758
+ ),
759
+ async execute(input, reqCtx): Promise<CardActionResult> {
760
+ const { recordRef } = (input ?? {}) as { recordRef?: string };
761
+ const s = await serviceOf(reqCtx, resolveParkingQueryPort);
762
+ if (!s || !recordRef) return { text: '开票失败:缺少缴费记录引用' };
763
+ const settings = await s.service.getInvoiceSettings(s.q);
764
+ if (!settings.parkingInvoiceEnabled)
765
+ throw new Error('当前停车场暂未开放停车开票');
766
+ const detail = await s.service.getPaymentRecordDetail(s.q, recordRef);
767
+ if (!detail.orderCompleted || detail.invoiceIssued) {
768
+ throw new Error(
769
+ detail.invoiceIssued ? '该停车订单已开票' : '该停车订单暂不可开票',
770
+ );
771
+ }
772
+ // 开票写走 payment 槽(双槽动作:查 query 槽 + 写 payment 槽)
773
+ const payment = await resolveParkingPaymentPort(reqCtx as RequestContext, ctx);
774
+ await payment.applyInvoice(s.q, recordRef);
775
+ return {
776
+ card: recordsCard(
777
+ [{ ...detail, invoiceIssued: true, invoiceEligible: false }],
778
+ '开票申请已提交',
779
+ ),
780
+ text: '开票申请已提交',
781
+ };
782
+ },
783
+ },
784
+
785
+ /** 支付状态刷新(reconcile 轮询兜底;显式交互 R4)——P0 原地更新被点击卡 */
786
+ refreshPayment: {
787
+ actionId: 'parking.refresh-payment',
788
+ moduleId: 'parking',
789
+ cardType: 'parking-payment-result',
790
+ label: '刷新支付状态',
791
+ singleUse: true,
792
+ inputSchema: coerceInput(z.object({ paymentRef: z.string().min(1) })),
793
+ async execute(input, reqCtx): Promise<CardActionResult> {
794
+ const { paymentRef } = (input ?? {}) as { paymentRef?: string };
795
+ const s = await serviceOf(reqCtx, resolveParkingPaymentPort);
796
+ if (!s || !paymentRef) {
797
+ // 防御分支(实际不可达——按钮门控 paymentRef):返回可见失败态而非静默 text
798
+ return {
799
+ update: {
800
+ data: paymentResultCard({
801
+ paymentRef: paymentRef ?? '',
802
+ plateNo: '',
803
+ status: 'UNKNOWN',
804
+ message: '刷新失败,请稍后重试',
805
+ retryable: true,
806
+ }).data,
807
+ },
808
+ };
809
+ }
810
+ const owner = paymentOwner(s.q);
811
+ const op = owner
812
+ ? await loadOwnedPaymentOperation(state, paymentRef, owner)
813
+ : null;
814
+ if (!op) return { text: '支付记录不可用,请重新查询停车费' };
815
+ const final = await s.service.reconcile(s.q, op.providerPaymentRef);
816
+ const settled = await settlePaymentOperation(
817
+ state,
818
+ paymentRef,
819
+ final === 'PAID'
820
+ ? 'PAID'
821
+ : final === 'CANCELLED'
822
+ ? 'CANCELLED'
823
+ : 'UNKNOWN',
824
+ );
825
+ const current = settled ?? op;
826
+ return {
827
+ update: {
828
+ data: paymentResultCard({
829
+ paymentRef,
830
+ plateNo: current.plateNo,
831
+ status:
832
+ current.status === 'PAID'
833
+ ? 'PAID'
834
+ : current.status === 'CANCELLED'
835
+ ? 'CANCELLED'
836
+ : 'UNKNOWN',
837
+ amountText: formatCents(current.payableCents),
838
+ message:
839
+ current.status === 'PAID'
840
+ ? '支付成功'
841
+ : current.status === 'CANCELLED'
842
+ ? '支付已取消,可重新发起'
843
+ : '对账中,请稍后再刷新',
844
+ retryable: current.status !== 'PAID',
845
+ }).data,
846
+ },
847
+ };
848
+ },
849
+ },
850
+ };
851
+ }
852
+
853
+ function paymentOwner(
854
+ q: ParkingQueryContext,
855
+ ): { subjectId: string; mallId: string } | null {
856
+ return q.subjectId && q.scope.mallId
857
+ ? { subjectId: q.subjectId, mallId: q.scope.mallId }
858
+ : null;
859
+ }
860
+
861
+ function locationCardData(
862
+ plateNo: string,
863
+ location: Awaited<ReturnType<ParkingQueryPort['locateVehicle']>>,
864
+ ): Record<string, unknown> {
865
+ return {
866
+ kind: 'vehicleLocation',
867
+ title: '寻车定位',
868
+ entries: location
869
+ ? [
870
+ { label: '车牌', value: plateNo },
871
+ ...(location.floorName
872
+ ? [{ label: '楼层', value: location.floorName }]
873
+ : []),
874
+ ...(location.zoneName
875
+ ? [{ label: '区域', value: location.zoneName }]
876
+ : []),
877
+ ...(location.spaceNo
878
+ ? [{ label: '车位', value: location.spaceNo }]
879
+ : []),
880
+ ...(location.walkingRoute
881
+ ? [{ label: '路线', value: location.walkingRoute }]
882
+ : []),
883
+ ]
884
+ : [{ label: '结果', value: '暂未查询到车辆位置' }],
885
+ };
886
+ }
887
+
888
+ function withInvoiceEligibility(
889
+ record: Awaited<ReturnType<ParkingQueryPort['getPaymentRecordDetail']>>,
890
+ parkingInvoiceEnabled: boolean,
891
+ ) {
892
+ return {
893
+ ...record,
894
+ invoiceEligible:
895
+ parkingInvoiceEnabled &&
896
+ record.orderCompleted === true &&
897
+ record.invoiceIssued !== true,
898
+ };
899
+ }
900
+
901
+ function recordsCard(
902
+ records: readonly Awaited<
903
+ ReturnType<ParkingQueryPort['getPaymentRecordDetail']>
904
+ >[],
905
+ message?: string,
906
+ ): { cardType: string; data: Record<string, unknown> } {
907
+ return {
908
+ cardType: 'parking-payment-records',
909
+ data: {
910
+ items: records.map(recordCardItem),
911
+ total: records.length,
912
+ hasMore: false,
913
+ caveats: [],
914
+ ...(message ? { message } : {}),
915
+ },
916
+ };
917
+ }
918
+
919
+ function recordCardItem(
920
+ record: Awaited<ReturnType<ParkingQueryPort['getPaymentRecordDetail']>>,
921
+ ) {
922
+ return {
923
+ recordRef: record.recordRef,
924
+ plateNo: record.plateNo,
925
+ amountText: formatCents(record.amountCents),
926
+ paidAtText: record.paidAt
927
+ ? new Date(record.paidAt).toLocaleString('zh-CN')
928
+ : '-',
929
+ status: record.status,
930
+ ...(record.parkName ? { parkName: record.parkName } : {}),
931
+ ...(record.plazaName ? { plazaName: record.plazaName } : {}),
932
+ ...(record.entryAt
933
+ ? { entryAtText: new Date(record.entryAt).toLocaleString('zh-CN') }
934
+ : {}),
935
+ ...(record.exitAt
936
+ ? { exitAtText: new Date(record.exitAt).toLocaleString('zh-CN') }
937
+ : {}),
938
+ ...(record.payOrderNoMasked
939
+ ? { payOrderNoMasked: record.payOrderNoMasked }
940
+ : {}),
941
+ ...(record.orderCompleted !== undefined
942
+ ? { orderCompleted: record.orderCompleted }
943
+ : {}),
944
+ ...(record.invoiceEligible !== undefined
945
+ ? { invoiceEligible: record.invoiceEligible }
946
+ : {}),
947
+ ...(record.invoiceIssued !== undefined
948
+ ? { invoiceIssued: record.invoiceIssued }
949
+ : {}),
950
+ };
951
+ }
952
+
953
+ async function vehiclesCard(
954
+ service: Pick<ParkingQueryPort, 'listVehicles'>,
955
+ q: ParkingQueryContext,
956
+ message?: string,
957
+ ): Promise<{ cardType: string; data: Record<string, unknown> }> {
958
+ const { bound } = await service.listVehicles(q);
959
+ return {
960
+ cardType: 'parking-vehicle-management',
961
+ data: {
962
+ // parked 是可选能力:provider 未给则不落字段,UI 据此不显示任何入场状态
963
+ bound: bound.map((v) => ({
964
+ vehicleRef: v.vehicleRef,
965
+ plateNo: v.plateNo,
966
+ ...(v.parked === undefined ? {} : { parked: v.parked }),
967
+ })),
968
+ ...(message ? { message } : {}),
969
+ },
970
+ };
971
+ }
972
+
973
+ function coerceInput<T extends z.ZodTypeAny>(schema: T): T {
974
+ return z.preprocess(coerceStringifiedFields, schema) as unknown as T;
975
+ }