@harrylabsj/kiwi 0.11.0 → 0.12.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.
Files changed (126) hide show
  1. package/README.md +4 -1
  2. package/contracts/kiwi-contracts.lock.json +1 -1
  3. package/contracts/manifest.json +2 -2
  4. package/contracts/runtime-binding/0.1.2/document.schema.json +3 -1
  5. package/dist/a2a/node.d.ts +2 -0
  6. package/dist/a2a/node.js +92 -13
  7. package/dist/a2a/node.js.map +1 -1
  8. package/dist/a2a/server/merchant-handler.js +31 -17
  9. package/dist/a2a/server/merchant-handler.js.map +1 -1
  10. package/dist/a2a/server/pipeline.js +1 -0
  11. package/dist/a2a/server/pipeline.js.map +1 -1
  12. package/dist/a2a/server/types.d.ts +1 -0
  13. package/dist/agent/buyer/buyer-tools.d.ts +2 -2
  14. package/dist/agent/buyer/buyer-tools.js.map +1 -1
  15. package/dist/agent/chat-tools.d.ts +2 -11
  16. package/dist/agent/chat-tools.js.map +1 -1
  17. package/dist/agent/fake-chat-model.d.ts +3 -3
  18. package/dist/agent/fake-chat-model.js +3 -5
  19. package/dist/agent/fake-chat-model.js.map +1 -1
  20. package/dist/agent/kernel-builder.js +4 -4
  21. package/dist/agent/kernel-builder.js.map +1 -1
  22. package/dist/agent/kernel.d.ts +15 -5
  23. package/dist/agent/kernel.js +143 -67
  24. package/dist/agent/kernel.js.map +1 -1
  25. package/dist/agent/kiwi-tool.d.ts +33 -0
  26. package/dist/agent/kiwi-tool.js +17 -0
  27. package/dist/agent/kiwi-tool.js.map +1 -0
  28. package/dist/agent/merchant/merchant-tools.d.ts +2 -17
  29. package/dist/agent/merchant/merchant-tools.js.map +1 -1
  30. package/dist/agent/negotiation-chat.d.ts +3 -2
  31. package/dist/agent/negotiation-chat.js.map +1 -1
  32. package/dist/agent/session.d.ts +15 -3
  33. package/dist/agent/session.js +114 -122
  34. package/dist/agent/session.js.map +1 -1
  35. package/dist/agent/skills/tools.d.ts +2 -2
  36. package/dist/agent/skills/tools.js.map +1 -1
  37. package/dist/cli.d.ts +5 -1
  38. package/dist/cli.js +239 -32
  39. package/dist/cli.js.map +1 -1
  40. package/dist/cloud/binding/enrollment-challenge.d.ts +37 -0
  41. package/dist/cloud/binding/enrollment-challenge.js +153 -0
  42. package/dist/cloud/binding/enrollment-challenge.js.map +1 -0
  43. package/dist/cloud/binding/enrollment-heartbeat.d.ts +26 -0
  44. package/dist/cloud/binding/enrollment-heartbeat.js +146 -0
  45. package/dist/cloud/binding/enrollment-heartbeat.js.map +1 -0
  46. package/dist/cloud/binding/enrollment-key-recovery.d.ts +27 -0
  47. package/dist/cloud/binding/enrollment-key-recovery.js +127 -0
  48. package/dist/cloud/binding/enrollment-key-recovery.js.map +1 -0
  49. package/dist/cloud/binding/runtime-challenge.d.ts +1 -1
  50. package/dist/cloud/binding/runtime-challenge.js +8 -1
  51. package/dist/cloud/binding/runtime-challenge.js.map +1 -1
  52. package/dist/cloud/bootstrap.js +241 -17
  53. package/dist/cloud/bootstrap.js.map +1 -1
  54. package/dist/cloud/catalog-client.d.ts +305 -0
  55. package/dist/cloud/catalog-client.js +962 -0
  56. package/dist/cloud/catalog-client.js.map +1 -0
  57. package/dist/cloud/config.d.ts +12 -0
  58. package/dist/cloud/config.js +45 -0
  59. package/dist/cloud/config.js.map +1 -1
  60. package/dist/cloud/http-router.d.ts +2 -0
  61. package/dist/cloud/http-router.js +8 -0
  62. package/dist/cloud/http-router.js.map +1 -1
  63. package/dist/cloud/listing-publisher.d.ts +45 -0
  64. package/dist/cloud/listing-publisher.js +244 -0
  65. package/dist/cloud/listing-publisher.js.map +1 -0
  66. package/dist/cloud/merchant-connect.d.ts +47 -0
  67. package/dist/cloud/merchant-connect.js +331 -0
  68. package/dist/cloud/merchant-connect.js.map +1 -0
  69. package/dist/cloud/merchant-identity.d.ts +14 -0
  70. package/dist/cloud/merchant-identity.js +76 -0
  71. package/dist/cloud/merchant-identity.js.map +1 -0
  72. package/dist/cloud/onboarding/catalog-pipeline.d.ts +135 -0
  73. package/dist/cloud/onboarding/catalog-pipeline.js +454 -0
  74. package/dist/cloud/onboarding/catalog-pipeline.js.map +1 -0
  75. package/dist/cloud/onboarding/steps.js +2 -2
  76. package/dist/cloud/onboarding/steps.js.map +1 -1
  77. package/dist/cloud/product-import-tabular.d.ts +100 -0
  78. package/dist/cloud/product-import-tabular.js +1073 -0
  79. package/dist/cloud/product-import-tabular.js.map +1 -0
  80. package/dist/cloud/product-source.d.ts +8 -1
  81. package/dist/cloud/product-source.js +63 -13
  82. package/dist/cloud/product-source.js.map +1 -1
  83. package/dist/config/profile.d.ts +4 -0
  84. package/dist/config/profile.js +14 -0
  85. package/dist/config/profile.js.map +1 -1
  86. package/dist/discovery/catalog-source/cloud-card.d.ts +1 -1
  87. package/dist/discovery/catalog-source/cloud-card.js +7 -1
  88. package/dist/discovery/catalog-source/cloud-card.js.map +1 -1
  89. package/dist/http/merchant-management/api.d.ts +17 -0
  90. package/dist/http/merchant-management/api.js +244 -7
  91. package/dist/http/merchant-management/api.js.map +1 -1
  92. package/dist/http/merchant-management/page.js +313 -18
  93. package/dist/http/merchant-management/page.js.map +1 -1
  94. package/dist/mcp/merchant-runtime-assembly.js +4 -1
  95. package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
  96. package/dist/mcp/merchant-server.d.ts +2 -0
  97. package/dist/mcp/merchant-server.js +15 -0
  98. package/dist/mcp/merchant-server.js.map +1 -1
  99. package/dist/merchant/negotiation-observer.d.ts +92 -0
  100. package/dist/merchant/negotiation-observer.js +278 -0
  101. package/dist/merchant/negotiation-observer.js.map +1 -0
  102. package/dist/merchant/operations-report.d.ts +85 -0
  103. package/dist/merchant/operations-report.js +227 -0
  104. package/dist/merchant/operations-report.js.map +1 -0
  105. package/dist/merchant/stats-store.d.ts +5 -0
  106. package/dist/merchant/stats-store.js +18 -0
  107. package/dist/merchant/stats-store.js.map +1 -1
  108. package/dist/merchant-gateway/catalog-publications.d.ts +28 -0
  109. package/dist/merchant-gateway/catalog-publications.js +69 -0
  110. package/dist/merchant-gateway/catalog-publications.js.map +1 -1
  111. package/dist/merchant-gateway/catalog-tools.js +20 -0
  112. package/dist/merchant-gateway/catalog-tools.js.map +1 -1
  113. package/dist/negotiation/lease/store.js +21 -2
  114. package/dist/negotiation/lease/store.js.map +1 -1
  115. package/dist/product-cli.d.ts +2 -2
  116. package/dist/product-cli.js +24 -9
  117. package/dist/product-cli.js.map +1 -1
  118. package/dist/product-init.d.ts +4 -1
  119. package/dist/product-init.js +39 -11
  120. package/dist/product-init.js.map +1 -1
  121. package/dist/product-publish.d.ts +8 -2
  122. package/dist/product-publish.js +222 -142
  123. package/dist/product-publish.js.map +1 -1
  124. package/dist/runtime/fake-model.js +9 -3
  125. package/dist/runtime/fake-model.js.map +1 -1
  126. package/package.json +7 -4
@@ -26,6 +26,8 @@ import { OnboardingStore } from "../../cloud/onboarding/store.js";
26
26
  import type { PlatformEvidenceResult } from "../../cloud/onboarding/types.js";
27
27
  import { type WorkbenchConfirmationStore } from "./webauthn-confirmation.js";
28
28
  import { type A2aNegotiationRow } from "../../merchant/workbench-service.js";
29
+ import { type NegotiationObserver } from "../../merchant/negotiation-observer.js";
30
+ import { type OperationsReportBuilder } from "../../merchant/operations-report.js";
29
31
  import type { ExactMerchantProduct } from "../../agent/merchant/types.js";
30
32
  import { type ExactMoney } from "../../merchant/application/money.js";
31
33
  import type { WorkbenchQuoteResult } from "../../merchant/quote-calculator.js";
@@ -39,6 +41,8 @@ import { type GrantAction, type GrantResourceType, type MerchantGrantStore } fro
39
41
  export interface MerchantManagementApiOptions {
40
42
  /** 本实例商家(服务端绑定;不来自请求)。 */
41
43
  merchantId: string;
44
+ merchantName?: string;
45
+ merchantNameNeedsUpdate?: boolean;
42
46
  /** 当前部署代次(单代次实例恒 1;代次切换后旧代次不得再产生业务写入)。 */
43
47
  generation: () => number;
44
48
  runtimeVersion: string;
@@ -82,6 +86,8 @@ export interface MerchantManagementApiOptions {
82
86
  digest: string;
83
87
  records: CloudProductRecord[];
84
88
  };
89
+ /** Attach local runtime ownership and the Catalog-confirmed merchant id. */
90
+ prepareTable?: (table: CloudProductTable) => CloudProductTable;
85
91
  commit: (table: CloudProductTable) => {
86
92
  digest: string;
87
93
  };
@@ -101,6 +107,7 @@ export interface MerchantManagementApiOptions {
101
107
  ready: boolean;
102
108
  checks: Record<string, {
103
109
  ok: boolean;
110
+ code?: string;
104
111
  }>;
105
112
  }>;
106
113
  /**
@@ -112,6 +119,8 @@ export interface MerchantManagementApiOptions {
112
119
  */
113
120
  onboarding?: {
114
121
  store: OnboardingStore;
122
+ /** 只读安全配对信息的目录;设备码和许可永不经此 API 返回。 */
123
+ enrollmentStateDir?: string;
115
124
  platformEvidence?: (input: {
116
125
  stepId: string;
117
126
  recordId: string;
@@ -132,6 +141,14 @@ export interface MerchantManagementApiOptions {
132
141
  }>;
133
142
  get: (negotiationId: string) => Promise<A2aNegotiationRow>;
134
143
  };
144
+ /**
145
+ * 会话旁观投影(WP11):分页(offset cursor)+ 状态过滤 + 单条时间线。
146
+ * 配置后 `/negotiations` 走本通道(limit-only 查询语义不变);未配置时
147
+ * 维持上面的 legacy 通道(仅 limit)。
148
+ */
149
+ negotiationObserver?: NegotiationObserver;
150
+ /** 运营报告聚合(WP11):stats-store + 磋商账本 → day/week/month 报告。 */
151
+ operationsReports?: OperationsReportBuilder;
135
152
  workbenchReconciliation?: WorkbenchReconciliationStore;
136
153
  exactProducts?: {
137
154
  list: () => Promise<ExactMerchantProduct[]>;
@@ -41,16 +41,20 @@ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
41
41
  import { contentHash } from "../../agent/merchant/action-candidate.js";
42
42
  import { ADMIN_SESSION_COOKIE } from "../../auth/merchant-sessions.js";
43
43
  import { parseProductTable, ProductTableError, productTableDigest, } from "../../cloud/product-source.js";
44
+ import { convertTabularImport, renderImportTemplateCsv, renderImportTemplateXlsx, TABULAR_IMPORT_MAX_BYTES, } from "../../cloud/product-import-tabular.js";
44
45
  import { MerchantImportDraftStore } from "./draft-store.js";
45
46
  import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, } from "../../merchant/application/actor.js";
46
47
  import { MANAGEMENT_API_MAJOR, MANAGEMENT_ERROR_STATUS, ManagementError, MerchantApplicationService, } from "../../merchant/application/service.js";
47
48
  import { managementRequestDigest, MerchantManagementOperationStore } from "./operation-store.js";
48
49
  import { OnboardingStore } from "../../cloud/onboarding/store.js";
50
+ import { readEnrollmentStore } from "../../cloud/binding/enrollment-challenge.js";
49
51
  import { requestsDisabledLocalImplementation } from "../../cloud/onboarding/local-fallback.js";
50
52
  import { checkStepSubmission, planWizard, WIZARD_STEPS } from "../../cloud/onboarding/steps.js";
51
53
  import { createWorkbenchProblem } from "./problem.js";
52
54
  import { WorkbenchConfirmationError, } from "./webauthn-confirmation.js";
53
55
  import { MerchantWorkbenchError, } from "../../merchant/workbench-service.js";
56
+ import { NEGOTIATION_STATUS_FILTERS, } from "../../merchant/negotiation-observer.js";
57
+ import { parseReportPeriod, } from "../../merchant/operations-report.js";
54
58
  import { parseExactMoney, WorkbenchMoneyError, WORKBENCH_CURRENCY_TABLE_VERSION, } from "../../merchant/application/money.js";
55
59
  import { EXACT_PRODUCT_TOOLS } from "../../merchant/exact-product-executors.js";
56
60
  import { SERVICE_CONTROL_TOOLS } from "../../merchant/service-control-executors.js";
@@ -144,7 +148,7 @@ export function createMerchantManagementApiHandler(options) {
144
148
  return;
145
149
  }
146
150
  if (method === "POST") {
147
- await routeWorkbenchV1Post(req, res, rest, requestId);
151
+ await routeWorkbenchV1Post(req, res, rest, requestId, url);
148
152
  return;
149
153
  }
150
154
  {
@@ -244,7 +248,11 @@ export function createMerchantManagementApiHandler(options) {
244
248
  }
245
249
  if (rest === "/runtime/status") {
246
250
  const auth = requireActor(req);
247
- writeJson(res, 200, await readService.getStatus(auth.ctx), { "x-request-id": requestId });
251
+ writeJson(res, 200, {
252
+ ...await readService.getStatus(auth.ctx),
253
+ merchant_name: options.merchantName ?? null,
254
+ merchant_name_needs_update: options.merchantNameNeedsUpdate === true,
255
+ }, { "x-request-id": requestId });
248
256
  return;
249
257
  }
250
258
  if (rest === "/products") {
@@ -268,6 +276,38 @@ export function createMerchantManagementApiHandler(options) {
268
276
  }, { "x-request-id": requestId });
269
277
  return;
270
278
  }
279
+ if (rest === "/products/import-template") {
280
+ const auth = requireActor(req);
281
+ authorizeOrThrow(auth.ctx, "products:read");
282
+ const format = url.searchParams.get("format");
283
+ if (format !== "csv" && format !== "xlsx") {
284
+ throw new ManagementError("invalid_input", "format must be csv or xlsx");
285
+ }
286
+ if (res.headersSent) {
287
+ res.end();
288
+ return;
289
+ }
290
+ if (format === "csv") {
291
+ const body = renderImportTemplateCsv();
292
+ res.writeHead(200, {
293
+ "content-type": "text/csv; charset=utf-8",
294
+ "content-disposition": 'attachment; filename="kiwi-product-import-template.csv"',
295
+ "cache-control": "no-store",
296
+ "x-request-id": requestId,
297
+ });
298
+ res.end(body);
299
+ return;
300
+ }
301
+ const bytes = renderImportTemplateXlsx();
302
+ res.writeHead(200, {
303
+ "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
304
+ "content-disposition": 'attachment; filename="kiwi-product-import-template.xlsx"',
305
+ "cache-control": "no-store",
306
+ "x-request-id": requestId,
307
+ });
308
+ res.end(Buffer.from(bytes));
309
+ return;
310
+ }
271
311
  const productMatch = /^\/products\/([^/]+)$/.exec(rest);
272
312
  if (productMatch !== null) {
273
313
  const auth = requireActor(req);
@@ -289,11 +329,29 @@ export function createMerchantManagementApiHandler(options) {
289
329
  if (rest === "/negotiations") {
290
330
  const auth = requireActor(req);
291
331
  authorizeOrThrow(auth.ctx, "approvals:read");
332
+ const query = pageQuery(url);
333
+ const statusRaw = url.searchParams.get("status");
334
+ if (statusRaw !== null && statusRaw !== "" && !NEGOTIATION_STATUS_FILTERS.includes(statusRaw)) {
335
+ throw new ManagementError("invalid_input", "status must be active, agreement or all");
336
+ }
337
+ const observer = options.negotiationObserver;
338
+ if (observer !== undefined) {
339
+ writeJson(res, 200, observer.list({
340
+ ...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
341
+ ...(query.limit !== undefined ? { limit: query.limit } : {}),
342
+ ...(statusRaw !== null && statusRaw !== ""
343
+ ? { status: statusRaw }
344
+ : {}),
345
+ }), { "x-request-id": requestId });
346
+ return;
347
+ }
348
+ if (statusRaw !== null && statusRaw !== "") {
349
+ throw new ManagementError("unavailable", "status filtering requires the negotiation observer projection");
350
+ }
292
351
  const channel = options.negotiations;
293
352
  if (channel === undefined) {
294
353
  throw new ManagementError("unavailable", "negotiation authority is not configured");
295
354
  }
296
- const query = pageQuery(url);
297
355
  writeJson(res, 200, await channel.list(query.limit), { "x-request-id": requestId });
298
356
  return;
299
357
  }
@@ -301,6 +359,13 @@ export function createMerchantManagementApiHandler(options) {
301
359
  if (negotiationMatch !== null) {
302
360
  const auth = requireActor(req);
303
361
  authorizeOrThrow(auth.ctx, "approvals:read");
362
+ const observer = options.negotiationObserver;
363
+ if (observer !== undefined) {
364
+ writeJson(res, 200, observer.timeline(pathSegment(negotiationMatch[1] ?? "")), {
365
+ "x-request-id": requestId,
366
+ });
367
+ return;
368
+ }
304
369
  const channel = options.negotiations;
305
370
  if (channel === undefined) {
306
371
  throw new ManagementError("unavailable", "negotiation authority is not configured");
@@ -310,6 +375,19 @@ export function createMerchantManagementApiHandler(options) {
310
375
  });
311
376
  return;
312
377
  }
378
+ if (rest === "/reports") {
379
+ const auth = requireActor(req);
380
+ authorizeOrThrow(auth.ctx, "operations:read");
381
+ const builder = options.operationsReports;
382
+ if (builder === undefined) {
383
+ throw new ManagementError("unavailable", "operations report authority is not configured");
384
+ }
385
+ const periodRaw = url.searchParams.get("period");
386
+ writeJson(res, 200, builder.build(parseReportPeriod(periodRaw)), {
387
+ "x-request-id": requestId,
388
+ });
389
+ return;
390
+ }
313
391
  if (rest === "/broadcasts") {
314
392
  const auth = requireActor(req);
315
393
  authorizeOrThrow(auth.ctx, "approvals:read");
@@ -445,7 +523,7 @@ export function createMerchantManagementApiHandler(options) {
445
523
  }
446
524
  writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
447
525
  }
448
- async function routeWorkbenchV1Post(req, res, rest, requestId) {
526
+ async function routeWorkbenchV1Post(req, res, rest, requestId, url) {
449
527
  if (rest === "/runtime/safety-stops") {
450
528
  const auth = requireActor(req);
451
529
  assertWriteGuards(req, auth.sessionId);
@@ -718,10 +796,18 @@ export function createMerchantManagementApiHandler(options) {
718
796
  await postProductsImportCommit(req, res, pathSegment(importCommitMatch[1] ?? ""));
719
797
  return;
720
798
  }
799
+ if (rest === "/products/import-parse") {
800
+ await postProductsImportParse(req, res, url);
801
+ return;
802
+ }
721
803
  if (rest === "/policy/drafts") {
722
804
  await postPolicyDraft(req, res);
723
805
  return;
724
806
  }
807
+ if (rest === "/policy/form-drafts") {
808
+ await postPolicyFormDraft(req, res);
809
+ return;
810
+ }
725
811
  const policyCommitMatch = /^\/policy\/drafts\/([^/]+)\/commit$/.exec(rest);
726
812
  if (policyCommitMatch !== null) {
727
813
  await postPolicyCommit(req, res, pathSegment(policyCommitMatch[1] ?? ""));
@@ -1362,7 +1448,34 @@ export function createMerchantManagementApiHandler(options) {
1362
1448
  authorizeOrThrow(auth.ctx, "onboarding:manage");
1363
1449
  const channel = onboardingChannel();
1364
1450
  const record = channel.store.activeRecord(auth.ctx.merchantId) ?? null;
1365
- writeJson(res, 200, { record, plan: record === null ? null : planWizard(record) });
1451
+ const readiness = await options.readiness();
1452
+ const setupNotices = [
1453
+ ...(readiness.checks.products?.code === "PRODUCTS_NOT_CONFIGURED"
1454
+ ? [{ code: "products_required", message: "请先导入商品;导入后系统会自动继续服务检查,当前不会报价或发布名片。" }]
1455
+ : []),
1456
+ ...(options.merchantNameNeedsUpdate === true
1457
+ ? [{ code: "merchant_name_required", message: "请设置商家显示名后再确认公开资料。" }]
1458
+ : []),
1459
+ ];
1460
+ const enrollment = record === null || channel.enrollmentStateDir === undefined
1461
+ ? undefined
1462
+ : readEnrollmentStore(channel.enrollmentStateDir).sessions
1463
+ .map((session) => session)
1464
+ .find((session) => session.owner_ref === record.recordId);
1465
+ writeJson(res, 200, {
1466
+ record,
1467
+ plan: record === null ? null : planWizard(record),
1468
+ setup_notices: setupNotices,
1469
+ ...(enrollment !== undefined ? {
1470
+ connect: {
1471
+ enrollment_id: enrollment.enrollment_id,
1472
+ status: enrollment.status,
1473
+ user_code: enrollment.user_code,
1474
+ verification_uri: enrollment.verification_uri,
1475
+ expires_at: enrollment.expires_at,
1476
+ },
1477
+ } : {}),
1478
+ });
1366
1479
  return;
1367
1480
  }
1368
1481
  if (rest === "/policy") {
@@ -2058,6 +2171,7 @@ export function createMerchantManagementApiHandler(options) {
2058
2171
  let table;
2059
2172
  try {
2060
2173
  table = parseProductTable(fields["table"], "request body");
2174
+ table = importChannel.prepareTable?.(table) ?? table;
2061
2175
  }
2062
2176
  catch (err) {
2063
2177
  if (err instanceof ProductTableError) {
@@ -2065,8 +2179,8 @@ export function createMerchantManagementApiHandler(options) {
2065
2179
  }
2066
2180
  throw err;
2067
2181
  }
2068
- if (table.merchant_id !== options.merchantId) {
2069
- throw new ManagementError("forbidden", "product table merchant_id does not match this instance");
2182
+ if ((table.runtime_owner_id ?? table.merchant_id) !== options.merchantId) {
2183
+ throw new ManagementError("forbidden", "product table runtime owner does not match this instance");
2070
2184
  }
2071
2185
  let base;
2072
2186
  try {
@@ -2118,6 +2232,43 @@ export function createMerchantManagementApiHandler(options) {
2118
2232
  },
2119
2233
  });
2120
2234
  }
2235
+ /**
2236
+ * POST /products/import-parse?format=csv|xlsx —— 把商家上传的 CSV/xlsx 原文
2237
+ * (WP12)转换为商品表草稿:表头映射报告 + 逐行问题清单。无状态(不落盘),
2238
+ * 商家确认后仍走 import-drafts 严格校验与整表替换预览;服务端解析保证工作
2239
+ * 台、脚本与技能共用同一实现(`product-import-tabular.ts`)。
2240
+ */
2241
+ async function postProductsImportParse(req, res, url) {
2242
+ const auth = requireActor(req);
2243
+ assertWriteGuards(req, auth.sessionId);
2244
+ authorizeOrThrow(auth.ctx, "products:import");
2245
+ const format = url.searchParams.get("format");
2246
+ if (format !== "csv" && format !== "xlsx") {
2247
+ throw new ManagementError("invalid_input", "format must be csv or xlsx");
2248
+ }
2249
+ const chunks = [];
2250
+ let size = 0;
2251
+ for await (const chunk of req) {
2252
+ size += chunk.length;
2253
+ if (size > TABULAR_IMPORT_MAX_BYTES) {
2254
+ throw new ManagementError("invalid_input", `文件超过上限 ${TABULAR_IMPORT_MAX_BYTES} 字节,请分批导入或精简表格`);
2255
+ }
2256
+ chunks.push(chunk);
2257
+ }
2258
+ if (chunks.length === 0) {
2259
+ throw new ManagementError("invalid_input", "request body required");
2260
+ }
2261
+ const buffer = Buffer.concat(chunks);
2262
+ const result = convertTabularImport(format === "csv"
2263
+ ? { kind: "csv", text: buffer.toString("utf8") }
2264
+ : { kind: "xlsx", bytes: new Uint8Array(buffer) }, { merchantId: options.merchantId, now: () => now() });
2265
+ writeJson(res, 200, {
2266
+ ok: result.ok,
2267
+ ...(result.table !== undefined ? { table: result.table } : {}),
2268
+ report: result.report,
2269
+ errors: result.errors,
2270
+ });
2271
+ }
2121
2272
  /** POST /products/import-drafts/{id}/commit —— 原子落盘;结果不可分辨时记 unknown。 */
2122
2273
  async function postProductsImportCommit(req, res, draftId) {
2123
2274
  const auth = requireActor(req);
@@ -2254,6 +2405,75 @@ export function createMerchantManagementApiHandler(options) {
2254
2405
  base_digest: current?.digest ?? null,
2255
2406
  });
2256
2407
  }
2408
+ /**
2409
+ * POST /policy/form-drafts —— 常用规则表单(WP11):表单友好字段 → 服务端映射
2410
+ * 为 policy schema 字段,走与 JSON patch 完全相同的草稿→确认提交流程。
2411
+ * schema 字段名只出现在服务端(页面壳不含策略内部字段名,隐私守卫不变)。
2412
+ */
2413
+ async function postPolicyFormDraft(req, res) {
2414
+ const auth = requireActor(req);
2415
+ assertWriteGuards(req, auth.sessionId);
2416
+ authorizeOrThrow(auth.ctx, "policy:draft");
2417
+ const fields = objectFields(await readJsonBody(req), [
2418
+ "auto",
2419
+ "floor",
2420
+ "discount",
2421
+ "lead_days",
2422
+ "ttl_seconds",
2423
+ "human_review",
2424
+ ]);
2425
+ const patch = {};
2426
+ if (fields["auto"] !== undefined) {
2427
+ if (fields["auto"] !== "on" && fields["auto"] !== "off") {
2428
+ throw new ManagementError("invalid_input", "auto must be on or off");
2429
+ }
2430
+ patch["auto_negotiate"] = fields["auto"] === "on";
2431
+ }
2432
+ if (fields["floor"] !== undefined) {
2433
+ patch["min_unit_price_private"] = requireNonNegativeNumber(fields["floor"], "floor");
2434
+ }
2435
+ if (fields["discount"] !== undefined) {
2436
+ const discount = requireNonNegativeNumber(fields["discount"], "discount");
2437
+ if (discount > 100) {
2438
+ throw new ManagementError("invalid_input", "discount must be between 0 and 100");
2439
+ }
2440
+ patch["max_auto_discount_percent"] = discount;
2441
+ }
2442
+ if (fields["lead_days"] !== undefined) {
2443
+ patch["delivery_lead_days"] = requirePositiveNumber(fields["lead_days"], "lead_days");
2444
+ }
2445
+ if (fields["ttl_seconds"] !== undefined) {
2446
+ patch["quote_ttl_seconds"] = requirePositiveInteger(fields["ttl_seconds"], "ttl_seconds");
2447
+ }
2448
+ if (fields["human_review"] !== undefined) {
2449
+ const triggers = requireStringArray(fields["human_review"], "human_review");
2450
+ for (const trigger of triggers) {
2451
+ if (!HUMAN_REVIEW_TRIGGERS.includes(trigger)) {
2452
+ throw new ManagementError("invalid_input", `human_review trigger must be one of ${HUMAN_REVIEW_TRIGGERS.join(", ")}`);
2453
+ }
2454
+ }
2455
+ patch["human_review_on"] = triggers;
2456
+ }
2457
+ if (Object.keys(patch).length === 0) {
2458
+ throw new ManagementError("invalid_input", "form submitted no changes");
2459
+ }
2460
+ const current = options.policy?.();
2461
+ const digest = managementRequestDigest(patch);
2462
+ const created = options.drafts.create({
2463
+ merchantId: auth.ctx.merchantId,
2464
+ kind: "policy_override",
2465
+ payloadJson: JSON.stringify(patch),
2466
+ payloadDigest: digest,
2467
+ ...(current !== undefined ? { baseDigest: current.digest } : {}),
2468
+ });
2469
+ writeJson(res, 200, {
2470
+ draft_id: created.draftId,
2471
+ digest,
2472
+ reused: created.reused,
2473
+ base_digest: current?.digest ?? null,
2474
+ applied_keys: Object.keys(patch),
2475
+ });
2476
+ }
2257
2477
  /** POST /policy/drafts/{id}/commit —— 应用策略补丁;回执只含版本与摘要(红线 6)。 */
2258
2478
  async function postPolicyCommit(req, res, draftId) {
2259
2479
  const auth = requireActor(req);
@@ -2447,6 +2667,8 @@ function isKnownPath(rest) {
2447
2667
  rest === "/service/pause" ||
2448
2668
  rest === "/service/resume" ||
2449
2669
  rest === "/products/import-drafts" ||
2670
+ rest === "/products/import-parse" ||
2671
+ rest === "/products/import-template" ||
2450
2672
  rest === "/policy/drafts" ||
2451
2673
  rest === "/onboarding") {
2452
2674
  return true;
@@ -2535,6 +2757,21 @@ function requirePositiveInteger(value, field) {
2535
2757
  throw new ManagementError("invalid_input", `${field} must be positive`);
2536
2758
  return integer;
2537
2759
  }
2760
+ /** 表单数值允许小数(元/百分比),但必须有限且非负(或正数,见下)。 */
2761
+ function requireNonNegativeNumber(value, field) {
2762
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
2763
+ throw new ManagementError("invalid_input", `${field} must be a non-negative number`);
2764
+ }
2765
+ return value;
2766
+ }
2767
+ function requirePositiveNumber(value, field) {
2768
+ const number = requireNonNegativeNumber(value, field);
2769
+ if (number === 0)
2770
+ throw new ManagementError("invalid_input", `${field} must be positive`);
2771
+ return number;
2772
+ }
2773
+ /** human_review_on 已知触发词(product-init/supervisor 初始化口径)。 */
2774
+ const HUMAN_REVIEW_TRIGGERS = ["below_floor", "exceptional_warranty", "suspicious_content"];
2538
2775
  function requireDecision(value) {
2539
2776
  if (value !== "approve" && value !== "reject") {
2540
2777
  throw new ManagementError("invalid_input", "decision must be approve or reject");