Jelajahi Sumber

feat(bos): 授权上界接线与 GET→POST 契约改造,前端首次入库并补齐迁移

- 契约层:`src/bin/klt-bos/openapi.yaml` 与 `src/openapi.yaml` 同步——8 条路由补
  `x-enumeration-kind` 声明(B1),6 条 GET→POST(R-5 裁定=GET 不够用即改 POST),
  `requestBody` 统一 `{data:{}}` 以满足网关注入前提
- 平台接线:`bos-platform/clients/*`(uds/impexp/resource_metadata/iam/activation/
  scheduler)按更正后口径调用;新增 `bos-api/src/grant.rs` 与 `bos-scope/scoped_select.rs`
  改造,承接网关注入的授权上界(B2)
- 可观测:新增 `bos-core/src/trace.rs`、`bos-api/src/trace.rs` 与
  `20261107000004_audit_log_occurred_at.sql`
- 前端:`front-end/` 首次入库(Vite+React,`api/bos.ts`/`types.ts` 与后端 HTTP 方法同步)
- 迁移:新增 `20261107000002`~`20261108000001` 六个(写缺口列、客户历史表、审计时间、
  区域元数据、客户联系方式列、账号状态行版本)
- 仓库:`.gitignore` 排除 `front-end/node_modules`、`front-end/dist` 与运行期
  `src/instance-id.json`
cg 2 minggu lalu
induk
melakukan
f4bf268db7
96 mengubah file dengan 29569 tambahan dan 593 penghapusan
  1. 7 0
      .gitignore
  2. 3 0
      front-end/.env.local
  3. 12 0
      front-end/index.html
  4. 1889 0
      front-end/package-lock.json
  5. 27 0
      front-end/package.json
  6. 72 0
      front-end/src/App.tsx
  7. 671 0
      front-end/src/api/bos.ts
  8. 112 0
      front-end/src/api/http.ts
  9. 107 0
      front-end/src/api/labels.ts
  10. 131 0
      front-end/src/api/platform.ts
  11. 1615 0
      front-end/src/api/types.ts
  12. 96 0
      front-end/src/auth/nav.ts
  13. 114 0
      front-end/src/auth/session.tsx
  14. 491 0
      front-end/src/components/ui.tsx
  15. 132 0
      front-end/src/hooks/useLoad.ts
  16. 96 0
      front-end/src/layout/Shell.tsx
  17. 34 0
      front-end/src/main.tsx
  18. 307 0
      front-end/src/pages/AuditPage.tsx
  19. 913 0
      front-end/src/pages/CustomerDetailPage.tsx
  20. 501 0
      front-end/src/pages/CustomersPage.tsx
  21. 418 0
      front-end/src/pages/EntTeamsPage.tsx
  22. 169 0
      front-end/src/pages/HomePage.tsx
  23. 261 0
      front-end/src/pages/ImportBatchesPage.tsx
  24. 279 0
      front-end/src/pages/LoginPage.tsx
  25. 148 0
      front-end/src/pages/MembersPage.tsx
  26. 433 0
      front-end/src/pages/OperatorsPage.tsx
  27. 652 0
      front-end/src/pages/OpsTeamsPage.tsx
  28. 502 0
      front-end/src/pages/PartnersPage.tsx
  29. 446 0
      front-end/src/pages/RegionsPage.tsx
  30. 296 0
      front-end/src/pages/SubAccountsPage.tsx
  31. 86 0
      front-end/src/styles/app.css
  32. 1118 0
      front-end/src/styles/prototype.css
  33. 20 0
      front-end/tsconfig.json
  34. 65 0
      front-end/vite.config.ts
  35. 14 20
      prototype/app.js
  36. 9 7
      prototype/data.js
  37. 6 1
      src/Cargo.lock
  38. 452 17
      src/bin/klt-bos/openapi.yaml
  39. 47 5
      src/bin/klt-bos/src/config.rs
  40. 160 33
      src/bin/klt-bos/src/main.rs
  41. 7 2
      src/config/default.toml
  42. 2 1
      src/crates/bos-api/Cargo.toml
  43. 57 30
      src/crates/bos-api/src/auth.rs
  44. 48 52
      src/crates/bos-api/src/extract.rs
  45. 224 0
      src/crates/bos-api/src/grant.rs
  46. 4 0
      src/crates/bos-api/src/lib.rs
  47. 10 3
      src/crates/bos-api/src/state.rs
  48. 95 0
      src/crates/bos-api/src/trace.rs
  49. 1 0
      src/crates/bos-core/Cargo.toml
  50. 302 35
      src/crates/bos-core/src/error.rs
  51. 1 0
      src/crates/bos-core/src/lib.rs
  52. 2 2
      src/crates/bos-core/src/response.rs
  53. 74 0
      src/crates/bos-core/src/trace.rs
  54. 145 0
      src/crates/bos-io/src/identity.rs
  55. 2 0
      src/crates/bos-io/src/lib.rs
  56. 15 5
      src/crates/bos-platform/src/clients/activation.rs
  57. 5 3
      src/crates/bos-platform/src/clients/iam.rs
  58. 9 3
      src/crates/bos-platform/src/clients/impexp.rs
  59. 84 6
      src/crates/bos-platform/src/clients/mod.rs
  60. 109 5
      src/crates/bos-platform/src/clients/resource_metadata.rs
  61. 5 5
      src/crates/bos-platform/src/clients/scheduler.rs
  62. 596 0
      src/crates/bos-platform/src/clients/uds.rs
  63. 3 0
      src/crates/bos-scope/Cargo.toml
  64. 76 46
      src/crates/bos-scope/src/scoped_select.rs
  65. 10 10
      src/migrations/dev/20261104000001_bos_core_tables.sql
  66. 110 0
      src/migrations/dev/20261107000002_bos_write_gap_columns.sql
  67. 50 0
      src/migrations/dev/20261107000003_customer_history_tables.sql
  68. 25 0
      src/migrations/dev/20261107000004_audit_log_occurred_at.sql
  69. 48 0
      src/migrations/dev/20261107000005_bos_region_meta.sql
  70. 33 0
      src/migrations/dev/20261107000006_customer_contact_columns.sql
  71. 33 0
      src/migrations/dev/20261108000001_account_status_row_version.sql
  72. 22 0
      src/migrations/dev/20261108000001_ent_team_remark.sql
  73. 1 0
      src/modules/account/Cargo.toml
  74. 513 49
      src/modules/account/src/handlers/account.rs
  75. 83 10
      src/modules/account/src/handlers/activation.rs
  76. 240 0
      src/modules/account/src/handlers/audit.rs
  77. 552 9
      src/modules/account/src/handlers/catalog.rs
  78. 1290 10
      src/modules/account/src/handlers/contract.rs
  79. 953 10
      src/modules/account/src/handlers/cost.rs
  80. 1547 30
      src/modules/account/src/handlers/customer.rs
  81. 1426 15
      src/modules/account/src/handlers/ent_team.rs
  82. 1298 15
      src/modules/account/src/handlers/import_batch.rs
  83. 497 0
      src/modules/account/src/handlers/listq.rs
  84. 2 0
      src/modules/account/src/handlers/mod.rs
  85. 852 18
      src/modules/account/src/handlers/operator.rs
  86. 1555 16
      src/modules/account/src/handlers/ops_team.rs
  87. 1163 15
      src/modules/account/src/handlers/partner.rs
  88. 460 15
      src/modules/account/src/handlers/region.rs
  89. 434 11
      src/modules/account/src/handlers/share_rule.rs
  90. 320 7
      src/modules/account/src/handlers/sub_account.rs
  91. 773 10
      src/modules/account/src/handlers/subscription.rs
  92. 11 7
      src/modules/account/src/router.rs
  93. 1 0
      src/modules/billing/Cargo.toml
  94. 50 48
      src/modules/billing/src/lib.rs
  95. 392 7
      src/openapi.yaml
  96. 38 0
      src/scripts/assert_structure.sh

+ 7 - 0
.gitignore

@@ -13,3 +13,10 @@ src/temp/
 
 # 工具生成的 HTML 分享包,属可再生产物,不入库
 .trae-html-share-packages/
+
+# 前端依赖与构建产物,属可再生产物,不入库
+front-end/node_modules/
+front-end/dist/
+
+# 服务运行期生成的实例标识,不入库
+src/instance-id.json

+ 3 - 0
front-end/.env.local

@@ -0,0 +1,3 @@
+# 本机联调:klt-bos 网关路由未注册(注册中心收紧后需平台签发 cn=klt-bos 证书方可自注册),
+# 业务接口走 /bos 降级直连代理(127.0.0.1:8088)。⛔ 代表上线形态。恢复网关通路时删除本文件。
+VITE_BOS_VIA_GATEWAY=0

+ 12 - 0
front-end/index.html

@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="zh-CN">
+  <head>
+    <meta charset="UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>恪澜通 · 运营支撑</title>
+  </head>
+  <body>
+    <div id="root"></div>
+    <script type="module" src="/src/main.tsx"></script>
+  </body>
+</html>

+ 1889 - 0
front-end/package-lock.json

@@ -0,0 +1,1889 @@
+{
+  "name": "klt-bos-console",
+  "version": "0.1.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "klt-bos-console",
+      "version": "0.1.0",
+      "dependencies": {
+        "@tanstack/react-query": "^5.106.1",
+        "react": "^18.3.1",
+        "react-dom": "^18.3.1",
+        "react-router-dom": "^6.30.6",
+        "zod": "^3.25.76"
+      },
+      "devDependencies": {
+        "@types/node": "^22.10.2",
+        "@types/react": "^18.3.31",
+        "@types/react-dom": "^18.3.7",
+        "@vitejs/plugin-react": "^4.7.0",
+        "typescript": "^5.9.3",
+        "vite": "^5.4.21"
+      }
+    },
+    "node_modules/@babel/code-frame": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/code-frame/-/code-frame-7.29.7.tgz",
+      "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/helper-validator-identifier": "^7.29.7",
+        "js-tokens": "^4.0.0",
+        "picocolors": "^1.1.1"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/compat-data": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/compat-data/-/compat-data-7.29.7.tgz",
+      "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/core": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/core/-/core-7.29.13.tgz",
+      "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/code-frame": "^7.29.7",
+        "@babel/generator": "^7.29.13",
+        "@babel/helper-compilation-targets": "^7.29.13",
+        "@babel/helper-module-transforms": "^7.29.13",
+        "@babel/helpers": "^7.29.13",
+        "@babel/parser": "^7.29.13",
+        "@babel/template": "^7.29.7",
+        "@babel/traverse": "^7.29.13",
+        "@babel/types": "^7.29.11",
+        "@jridgewell/remapping": "^2.3.5",
+        "convert-source-map": "^2.0.0",
+        "debug": "^4.1.0",
+        "gensync": "^1.0.0-beta.2",
+        "json5": "^2.2.3",
+        "semver": "^6.3.1"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/babel"
+      }
+    },
+    "node_modules/@babel/generator": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/generator/-/generator-7.29.13.tgz",
+      "integrity": "sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/parser": "^7.29.13",
+        "@babel/types": "^7.29.11",
+        "@jridgewell/gen-mapping": "^0.3.12",
+        "@jridgewell/trace-mapping": "^0.3.28",
+        "jsesc": "^3.0.2"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-compilation-targets": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz",
+      "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/compat-data": "^7.29.7",
+        "@babel/helper-validator-option": "^7.29.7",
+        "browserslist": "^4.24.0",
+        "lru-cache": "^5.1.1",
+        "semver": "^6.3.1"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-globals": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+      "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-module-imports": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+      "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/traverse": "^7.29.7",
+        "@babel/types": "^7.29.7"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-module-transforms": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-module-transforms/-/helper-module-transforms-7.29.13.tgz",
+      "integrity": "sha512-/U96wOz+SCoZ7Da/8kjDGltcNY280JPQcRNPK0Hk3PTbdpaiBDQImtC6JsbVwb1HGMr3usZQU2WsWVjhYNmRzw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/helper-module-imports": "^7.29.7",
+        "@babel/helper-validator-identifier": "^7.29.7",
+        "@babel/traverse": "^7.29.13"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      },
+      "peerDependencies": {
+        "@babel/core": "^7.0.0"
+      }
+    },
+    "node_modules/@babel/helper-plugin-utils": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
+      "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-string-parser": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz",
+      "integrity": "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-validator-identifier": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helper-validator-option": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+      "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/helpers": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/helpers/-/helpers-7.29.13.tgz",
+      "integrity": "sha512-laoRpD/kO/iA4CDlgJbixHekg7oPvWALK0PQyK3Ob2I2njZRvVAD77RfWCIImtqWCq6KijoBoZK7bp/HlTWASQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/template": "^7.29.7",
+        "@babel/types": "^7.29.11"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/parser": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/parser/-/parser-7.29.13.tgz",
+      "integrity": "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/types": "^7.29.11"
+      },
+      "bin": {
+        "parser": "bin/babel-parser.js"
+      },
+      "engines": {
+        "node": ">=6.0.0"
+      }
+    },
+    "node_modules/@babel/plugin-transform-react-jsx-self": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
+      "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/helper-plugin-utils": "^7.29.7"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      },
+      "peerDependencies": {
+        "@babel/core": "^7.0.0-0"
+      }
+    },
+    "node_modules/@babel/plugin-transform-react-jsx-source": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
+      "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/helper-plugin-utils": "^7.29.7"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      },
+      "peerDependencies": {
+        "@babel/core": "^7.0.0-0"
+      }
+    },
+    "node_modules/@babel/template": {
+      "version": "7.29.7",
+      "resolved": "https://registry.npmmirror.com/@babel/template/-/template-7.29.7.tgz",
+      "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/code-frame": "^7.29.7",
+        "@babel/parser": "^7.29.7",
+        "@babel/types": "^7.29.7"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/traverse": {
+      "version": "7.29.13",
+      "resolved": "https://registry.npmmirror.com/@babel/traverse/-/traverse-7.29.13.tgz",
+      "integrity": "sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/code-frame": "^7.29.7",
+        "@babel/generator": "^7.29.13",
+        "@babel/helper-globals": "^7.29.7",
+        "@babel/parser": "^7.29.13",
+        "@babel/template": "^7.29.7",
+        "@babel/types": "^7.29.11",
+        "debug": "^4.3.1"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@babel/types": {
+      "version": "7.29.11",
+      "resolved": "https://registry.npmmirror.com/@babel/types/-/types-7.29.11.tgz",
+      "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/helper-string-parser": "^7.29.11",
+        "@babel/helper-validator-identifier": "^7.29.7"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@esbuild/aix-ppc64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+      "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/android-arm": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+      "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/android-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+      "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/android-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+      "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/darwin-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+      "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/darwin-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+      "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/freebsd-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+      "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/freebsd-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+      "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-arm": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+      "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+      "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-ia32": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+      "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-loong64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+      "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-mips64el": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+      "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-ppc64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+      "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-riscv64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+      "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-s390x": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+      "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+      "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/netbsd-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+      "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/openbsd-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+      "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/sunos-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+      "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/win32-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+      "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/win32-ia32": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+      "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/win32-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+      "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@jridgewell/gen-mapping": {
+      "version": "0.3.13",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+      "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/sourcemap-codec": "^1.5.0",
+        "@jridgewell/trace-mapping": "^0.3.24"
+      }
+    },
+    "node_modules/@jridgewell/remapping": {
+      "version": "2.3.5",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+      "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/gen-mapping": "^0.3.5",
+        "@jridgewell/trace-mapping": "^0.3.24"
+      }
+    },
+    "node_modules/@jridgewell/resolve-uri": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+      "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.0.0"
+      }
+    },
+    "node_modules/@jridgewell/sourcemap-codec": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+      "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@jridgewell/trace-mapping": {
+      "version": "0.3.31",
+      "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+      "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/resolve-uri": "^3.1.0",
+        "@jridgewell/sourcemap-codec": "^1.4.14"
+      }
+    },
+    "node_modules/@remix-run/router": {
+      "version": "1.23.4",
+      "resolved": "https://registry.npmmirror.com/@remix-run/router/-/router-1.23.4.tgz",
+      "integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@rolldown/pluginutils": {
+      "version": "1.0.0-beta.27",
+      "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
+      "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@rollup/rollup-android-arm-eabi": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.67.5.tgz",
+      "integrity": "sha512-FdWPeulkH+FH+rBzyKBD59tuVN4tRKvmVilSJm0OcnoYsQTpd9UhD78OaPcsYqo2fX6hCwAG0YIjrDLoQ3pR3g==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ]
+    },
+    "node_modules/@rollup/rollup-android-arm64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.67.5.tgz",
+      "integrity": "sha512-bmkDuBGnF+Ji8atWlXcNjxIC52ShCbdXPbW7Nz0lRoCFi1lrvsO0XobJY36kTj7duc1vOmGJeQ9vtVuGjnzihA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ]
+    },
+    "node_modules/@rollup/rollup-android-x64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-x64/-/rollup-android-x64-4.67.5.tgz",
+      "integrity": "sha512-6KvVfnqPTqmbQ5YobMl9HYiSymAsCt8HlNeriDshwJQcveXwT+vIMW6wGL1RcJbXH9+r3BAJvjab5+rIgtSEqA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ]
+    },
+    "node_modules/@rollup/rollup-darwin-arm64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.67.5.tgz",
+      "integrity": "sha512-SNamgdrY69oPdBrQV9fKGo6PSmKcVhyn0D0jnDmcqgRJvrxQGGBhtekOHTUJ7TCgkW0nE8XMH9v2CwXmjNIzVA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ]
+    },
+    "node_modules/@rollup/rollup-darwin-x64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.67.5.tgz",
+      "integrity": "sha512-HNdl34thiJtHDSglogjmAlQ296L8cc8zA7ODH65nnmY7E+jPP55WEbh8J5583rWFLMjxyYywxZuwPOwRvEi5tA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ]
+    },
+    "node_modules/@rollup/rollup-freebsd-arm64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.67.5.tgz",
+      "integrity": "sha512-WvZYtANNswfHzSNHaJAoG6Ipfc4SyZIDYuIjFdHv07xXxhHl+Xx8o+bNDWsxpOADFT2mKXcXVrfOG4OlWTLo8Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ]
+    },
+    "node_modules/@rollup/rollup-freebsd-x64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.67.5.tgz",
+      "integrity": "sha512-EUU+Wgf9NyHekceC+DxAdm42f6bq2ezH/7DEb/JnCb8SAUhG2xph5BiVukxplWal2m5pP8CzJZE+FLwRopywjQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.67.5.tgz",
+      "integrity": "sha512-dgU1CvUuE2IkaJBAeuAbxpDdMHAdZBT5oth5u22DtuoMg4gXXYr2+Sm30RigPJG1F2VEoiGJUziGLuIh9+jPxA==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.67.5.tgz",
+      "integrity": "sha512-rdgJcJig2VngYlcTCRQw2BA8kLWM6QwDFe9uLFo81lya0jPC1r8wZu92sAvTUIv48GWlkRVi6/fpsa5CoFSKoQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm64-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.67.5.tgz",
+      "integrity": "sha512-+jtCiQnrEFHWAUAcUpP7wppb1p6HKOgBP3mXx75cEYpDF2Y5MEqBky2HNz+osFuVx5uX44gnMTmbe5RJauzn6A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm64-musl": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.67.5.tgz",
+      "integrity": "sha512-heflX7ENhL8eHmLcUxDEHCSK8CKLyPprysb2JGoSTh5Ip7nHrzIRc+2USyxul3nxi98H8pGxJIEDEpURlS1X5A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-loong64-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.67.5.tgz",
+      "integrity": "sha512-rRtNU0zBfRHkJ8pscHN9qRtUYLq8Rao4EX7aVWvKcFmJUANkCCXFRU7ovNBEMhpEONyUEB/3DRVDXwDDguSfHA==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-loong64-musl": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.67.5.tgz",
+      "integrity": "sha512-/6auyi9yj8MD/Q+8P+f2ay57jQ7a0j7Yp1JK86pecH6ZnRViQZ5GOjoRSjGArFeTSHFznRbM2QPQcBgDPyNMfQ==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.67.5.tgz",
+      "integrity": "sha512-Hsc0vlt+vPvqzUkHKffWKf3YE/yexrY+yeFf7IsUvDC6PV7YGCsA/gJvPa+WJdgxGJnwuoO1HmLkbahaLKabYQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-ppc64-musl": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.67.5.tgz",
+      "integrity": "sha512-Jx5TMMSPJwHY7F/JwPdS6nuBwny2ECRK+EsAJV5HZrfiddeSS6ZrohkLkFZm3rjqBUuQ4FPX5gGMtakUuQO6fQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.67.5.tgz",
+      "integrity": "sha512-fGWcq2lo/XCqAkBLOokg66D/z+MUouryB8i+QdU9RR6O5knG7rucc0WFPqWYL1Wk/wuiJouDfmyBxmZKRM9bag==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-riscv64-musl": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.67.5.tgz",
+      "integrity": "sha512-JwO/Ys3jybc0UW3V5XO2CMnp0RhvoczDDQTgAEE1IctT+HRY3W5parIIWLUpmAK4gHSeeYJofm2iQPFA62K6ag==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-s390x-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.67.5.tgz",
+      "integrity": "sha512-vVD4iqel6J6A1xAJlb4mxEO9i1wOJ4/SkcKoDKAuK/wqEBPOA7/P5dDyZvNx46ocHwOUwzo3WjhTdKqET9kEAg==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-x64-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.67.5.tgz",
+      "integrity": "sha512-HmEfNh5Cdd/NHxgqwMzKnjlvicQQA+D+w+vQXDJSV0x/aHiQSjVwh1Th5RoA7QsMieIaxibt/5iJq68BraTSUg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "libc": [
+        "glibc"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-x64-musl": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.67.5.tgz",
+      "integrity": "sha512-NfmALpbe009nYzZ2QqlSW6nzbGddXpqk3nwualrIr+4QflQCTGMzt3QKK20yARiAnSV9fJdM5WNwIYUf31x3uA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "libc": [
+        "musl"
+      ],
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-openbsd-x64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.67.5.tgz",
+      "integrity": "sha512-ngcE7Udpy/iJ3lexVhYcbpUV2OJIakRGus3snc6K52BnAAJetDBG1Ku5Eh3CECtnW3mpBYWg5VCD4tTaOXKOVQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ]
+    },
+    "node_modules/@rollup/rollup-openharmony-arm64": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.67.5.tgz",
+      "integrity": "sha512-DZ01A2EdTYX8xVeGoGiWkJBRWDh+/BOflwGPVsBay43PDxcq8ez0xuovZnPnk1xjE3CdI0pdZXxsJp/Xjmf7uQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-arm64-msvc": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.67.5.tgz",
+      "integrity": "sha512-nJKiMKDO140DUCEcQZl+f4HiGPMBxrW2webjuWJ2E3qPeoruHf2zByml4TP52lA1zDi6L4I92D/5stxeA/6pig==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-ia32-msvc": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.67.5.tgz",
+      "integrity": "sha512-ykLkBCf+Kls24QmqM3IRf1T4sGMh0rXPyymtj+hXlWKPJnXbXraHqUUsKtOIxqLasjT1i7DhfQGAaZYeiHbSOw==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-x64-gnu": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.67.5.tgz",
+      "integrity": "sha512-NiFPUFw8cHhkmBlL1k1eaz+5AXXm89rztj+DQdDuQ7VGPM0+ADFhezQ2KcBMF50UEFzGUr0+DVjVND743XwKWQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-x64-msvc": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.67.5.tgz",
+      "integrity": "sha512-Khj/vrKCpdbiAWYbJAeSy4D5iep+qwW/86lNoKvdleJYGxgbRE7h87+5d5T9D7gt8NcqhNFpreRgIg8T4bLzKQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@tanstack/query-core": {
+      "version": "5.106.1",
+      "resolved": "https://registry.npmmirror.com/@tanstack/query-core/-/query-core-5.106.1.tgz",
+      "integrity": "sha512-erYv/UACddcdgjOL2ixmFdK6tO/AVBeUcTCOtX2N51yZpDQ2U7KJ+xgB/bCNfsF3uoCDTqGHEEbDiFsIO9YUmQ==",
+      "license": "MIT",
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/tannerlinsley"
+      }
+    },
+    "node_modules/@tanstack/react-query": {
+      "version": "5.106.1",
+      "resolved": "https://registry.npmmirror.com/@tanstack/react-query/-/react-query-5.106.1.tgz",
+      "integrity": "sha512-ORDvJG/DSfmlFL9lQ8GDkE0VjtQbLeRDY7BL8xjKkQFGLfjFGfNWNuteWgPqA2gPJgLLuWfQ7IX0FlsHCJriyg==",
+      "license": "MIT",
+      "dependencies": {
+        "@tanstack/query-core": "5.106.1"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/tannerlinsley"
+      },
+      "peerDependencies": {
+        "@types/react": "^18 || ^19",
+        "react": "^18 || ^19"
+      },
+      "peerDependenciesMeta": {
+        "@types/react": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@types/babel__core": {
+      "version": "7.20.5",
+      "resolved": "https://registry.npmmirror.com/@types/babel__core/-/babel__core-7.20.5.tgz",
+      "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/parser": "^7.20.7",
+        "@babel/types": "^7.20.7",
+        "@types/babel__generator": "*",
+        "@types/babel__template": "*",
+        "@types/babel__traverse": "*"
+      }
+    },
+    "node_modules/@types/babel__generator": {
+      "version": "7.27.0",
+      "resolved": "https://registry.npmmirror.com/@types/babel__generator/-/babel__generator-7.27.0.tgz",
+      "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/types": "^7.0.0"
+      }
+    },
+    "node_modules/@types/babel__template": {
+      "version": "7.4.4",
+      "resolved": "https://registry.npmmirror.com/@types/babel__template/-/babel__template-7.4.4.tgz",
+      "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/parser": "^7.1.0",
+        "@babel/types": "^7.0.0"
+      }
+    },
+    "node_modules/@types/babel__traverse": {
+      "version": "7.28.0",
+      "resolved": "https://registry.npmmirror.com/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
+      "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/types": "^7.28.2"
+      }
+    },
+    "node_modules/@types/estree": {
+      "version": "1.0.10",
+      "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.10.tgz",
+      "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/node": {
+      "version": "22.20.5",
+      "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.20.5.tgz",
+      "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "undici-types": "~6.21.0"
+      }
+    },
+    "node_modules/@types/prop-types": {
+      "version": "15.7.15",
+      "resolved": "https://registry.npmmirror.com/@types/prop-types/-/prop-types-15.7.15.tgz",
+      "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
+      "devOptional": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/react": {
+      "version": "18.3.31",
+      "resolved": "https://registry.npmmirror.com/@types/react/-/react-18.3.31.tgz",
+      "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
+      "devOptional": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/prop-types": "*",
+        "csstype": "^3.2.2"
+      }
+    },
+    "node_modules/@types/react-dom": {
+      "version": "18.3.7",
+      "resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-18.3.7.tgz",
+      "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
+      "dev": true,
+      "license": "MIT",
+      "peerDependencies": {
+        "@types/react": "^18.0.0"
+      }
+    },
+    "node_modules/@vitejs/plugin-react": {
+      "version": "4.7.0",
+      "resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
+      "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@babel/core": "^7.28.0",
+        "@babel/plugin-transform-react-jsx-self": "^7.27.1",
+        "@babel/plugin-transform-react-jsx-source": "^7.27.1",
+        "@rolldown/pluginutils": "1.0.0-beta.27",
+        "@types/babel__core": "^7.20.5",
+        "react-refresh": "^0.17.0"
+      },
+      "engines": {
+        "node": "^14.18.0 || >=16.0.0"
+      },
+      "peerDependencies": {
+        "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
+      }
+    },
+    "node_modules/baseline-browser-mapping": {
+      "version": "2.11.35",
+      "resolved": "https://registry.npmmirror.com/baseline-browser-mapping/-/baseline-browser-mapping-2.11.35.tgz",
+      "integrity": "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "baseline-browser-mapping": "dist/cli.cjs"
+      },
+      "engines": {
+        "node": ">=6.0.0"
+      }
+    },
+    "node_modules/browserslist": {
+      "version": "4.29.5",
+      "resolved": "https://registry.npmmirror.com/browserslist/-/browserslist-4.29.5.tgz",
+      "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/browserslist"
+        },
+        {
+          "type": "tidelift",
+          "url": "https://tidelift.com/funding/github/npm/browserslist"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "baseline-browser-mapping": "^2.11.33",
+        "caniuse-lite": "^1.0.30001819",
+        "electron-to-chromium": "^1.5.464",
+        "node-releases": "^2.0.60",
+        "update-browserslist-db": "^1.3.4"
+      },
+      "bin": {
+        "browserslist": "cli.js"
+      },
+      "engines": {
+        "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+      }
+    },
+    "node_modules/caniuse-lite": {
+      "version": "1.0.30001822",
+      "resolved": "https://registry.npmmirror.com/caniuse-lite/-/caniuse-lite-1.0.30001822.tgz",
+      "integrity": "sha512-Y3fvWQWzc69dlCyr07tuNrEhotv+db5FpMSPD3slZnkPKwRNOKwFBz2dP966XUmWMXLTOt+YShkFoQoom3U7hg==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/browserslist"
+        },
+        {
+          "type": "tidelift",
+          "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "CC-BY-4.0"
+    },
+    "node_modules/convert-source-map": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmmirror.com/convert-source-map/-/convert-source-map-2.0.0.tgz",
+      "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/csstype": {
+      "version": "3.2.3",
+      "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
+      "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+      "devOptional": true,
+      "license": "MIT"
+    },
+    "node_modules/debug": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz",
+      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/electron-to-chromium": {
+      "version": "1.5.478",
+      "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.478.tgz",
+      "integrity": "sha512-pftG+ma5Lm8O6/p45bhYT6StBN5ziQymaRzmCZwFl8DwWHKPPD93FdOmP1aqftcepolQYvrcyTLa17kE8Yf+jg==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/esbuild": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.21.5.tgz",
+      "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "bin": {
+        "esbuild": "bin/esbuild"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "optionalDependencies": {
+        "@esbuild/aix-ppc64": "0.21.5",
+        "@esbuild/android-arm": "0.21.5",
+        "@esbuild/android-arm64": "0.21.5",
+        "@esbuild/android-x64": "0.21.5",
+        "@esbuild/darwin-arm64": "0.21.5",
+        "@esbuild/darwin-x64": "0.21.5",
+        "@esbuild/freebsd-arm64": "0.21.5",
+        "@esbuild/freebsd-x64": "0.21.5",
+        "@esbuild/linux-arm": "0.21.5",
+        "@esbuild/linux-arm64": "0.21.5",
+        "@esbuild/linux-ia32": "0.21.5",
+        "@esbuild/linux-loong64": "0.21.5",
+        "@esbuild/linux-mips64el": "0.21.5",
+        "@esbuild/linux-ppc64": "0.21.5",
+        "@esbuild/linux-riscv64": "0.21.5",
+        "@esbuild/linux-s390x": "0.21.5",
+        "@esbuild/linux-x64": "0.21.5",
+        "@esbuild/netbsd-x64": "0.21.5",
+        "@esbuild/openbsd-x64": "0.21.5",
+        "@esbuild/sunos-x64": "0.21.5",
+        "@esbuild/win32-arm64": "0.21.5",
+        "@esbuild/win32-ia32": "0.21.5",
+        "@esbuild/win32-x64": "0.21.5"
+      }
+    },
+    "node_modules/escalade": {
+      "version": "3.2.0",
+      "resolved": "https://registry.npmmirror.com/escalade/-/escalade-3.2.0.tgz",
+      "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/fsevents": {
+      "version": "2.3.3",
+      "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz",
+      "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+      }
+    },
+    "node_modules/gensync": {
+      "version": "1.0.0-beta.2",
+      "resolved": "https://registry.npmmirror.com/gensync/-/gensync-1.0.0-beta.2.tgz",
+      "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/js-tokens": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz",
+      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+      "license": "MIT"
+    },
+    "node_modules/jsesc": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmmirror.com/jsesc/-/jsesc-3.1.0.tgz",
+      "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "jsesc": "bin/jsesc"
+      },
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/json5": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmmirror.com/json5/-/json5-2.2.3.tgz",
+      "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "json5": "lib/cli.js"
+      },
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/loose-envify": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmmirror.com/loose-envify/-/loose-envify-1.4.0.tgz",
+      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+      "license": "MIT",
+      "dependencies": {
+        "js-tokens": "^3.0.0 || ^4.0.0"
+      },
+      "bin": {
+        "loose-envify": "cli.js"
+      }
+    },
+    "node_modules/lru-cache": {
+      "version": "5.1.1",
+      "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-5.1.1.tgz",
+      "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "yallist": "^3.0.2"
+      }
+    },
+    "node_modules/ms": {
+      "version": "2.1.3",
+      "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
+      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/nanoid": {
+      "version": "3.3.20",
+      "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.20.tgz",
+      "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "bin": {
+        "nanoid": "bin/nanoid.cjs"
+      },
+      "engines": {
+        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+      }
+    },
+    "node_modules/node-releases": {
+      "version": "2.0.63",
+      "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.63.tgz",
+      "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/picocolors": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
+      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/postcss": {
+      "version": "8.5.32",
+      "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.32.tgz",
+      "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/postcss/"
+        },
+        {
+          "type": "tidelift",
+          "url": "https://tidelift.com/funding/github/npm/postcss"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "nanoid": "^3.3.20",
+        "picocolors": "^1.1.1",
+        "source-map-js": "^1.2.2"
+      },
+      "engines": {
+        "node": "^10 || ^12 || >=14"
+      }
+    },
+    "node_modules/react": {
+      "version": "18.3.1",
+      "resolved": "https://registry.npmmirror.com/react/-/react-18.3.1.tgz",
+      "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+      "license": "MIT",
+      "dependencies": {
+        "loose-envify": "^1.1.0"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/react-dom": {
+      "version": "18.3.1",
+      "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-18.3.1.tgz",
+      "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
+      "license": "MIT",
+      "dependencies": {
+        "loose-envify": "^1.1.0",
+        "scheduler": "^0.23.2"
+      },
+      "peerDependencies": {
+        "react": "^18.3.1"
+      }
+    },
+    "node_modules/react-refresh": {
+      "version": "0.17.0",
+      "resolved": "https://registry.npmmirror.com/react-refresh/-/react-refresh-0.17.0.tgz",
+      "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/react-router": {
+      "version": "6.30.6",
+      "resolved": "https://registry.npmmirror.com/react-router/-/react-router-6.30.6.tgz",
+      "integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==",
+      "license": "MIT",
+      "dependencies": {
+        "@remix-run/router": "1.23.4"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      },
+      "peerDependencies": {
+        "react": ">=16.8"
+      }
+    },
+    "node_modules/react-router-dom": {
+      "version": "6.30.6",
+      "resolved": "https://registry.npmmirror.com/react-router-dom/-/react-router-dom-6.30.6.tgz",
+      "integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@remix-run/router": "1.23.4",
+        "react-router": "6.30.6"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      },
+      "peerDependencies": {
+        "react": ">=16.8",
+        "react-dom": ">=16.8"
+      }
+    },
+    "node_modules/rollup": {
+      "version": "4.67.5",
+      "resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.67.5.tgz",
+      "integrity": "sha512-3Ve5VH1hacCVutdpbmu/htg4kz+JCOIWgy4Q3hjHPYGHeHeIElNHJ0LcJ3rCfIsd5G7qOl5k5mwpzGMj9kdHPA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/estree": "^1.0.10"
+      },
+      "bin": {
+        "rollup": "dist/bin/rollup"
+      },
+      "engines": {
+        "node": ">=18.0.0",
+        "npm": ">=8.0.0"
+      },
+      "optionalDependencies": {
+        "@rollup/rollup-android-arm-eabi": "4.67.5",
+        "@rollup/rollup-android-arm64": "4.67.5",
+        "@rollup/rollup-android-x64": "4.67.5",
+        "@rollup/rollup-darwin-arm64": "4.67.5",
+        "@rollup/rollup-darwin-x64": "4.67.5",
+        "@rollup/rollup-freebsd-arm64": "4.67.5",
+        "@rollup/rollup-freebsd-x64": "4.67.5",
+        "@rollup/rollup-linux-arm-gnueabihf": "4.67.5",
+        "@rollup/rollup-linux-arm-musleabihf": "4.67.5",
+        "@rollup/rollup-linux-arm64-gnu": "4.67.5",
+        "@rollup/rollup-linux-arm64-musl": "4.67.5",
+        "@rollup/rollup-linux-loong64-gnu": "4.67.5",
+        "@rollup/rollup-linux-loong64-musl": "4.67.5",
+        "@rollup/rollup-linux-ppc64-gnu": "4.67.5",
+        "@rollup/rollup-linux-ppc64-musl": "4.67.5",
+        "@rollup/rollup-linux-riscv64-gnu": "4.67.5",
+        "@rollup/rollup-linux-riscv64-musl": "4.67.5",
+        "@rollup/rollup-linux-s390x-gnu": "4.67.5",
+        "@rollup/rollup-linux-x64-gnu": "4.67.5",
+        "@rollup/rollup-linux-x64-musl": "4.67.5",
+        "@rollup/rollup-openbsd-x64": "4.67.5",
+        "@rollup/rollup-openharmony-arm64": "4.67.5",
+        "@rollup/rollup-win32-arm64-msvc": "4.67.5",
+        "@rollup/rollup-win32-ia32-msvc": "4.67.5",
+        "@rollup/rollup-win32-x64-gnu": "4.67.5",
+        "@rollup/rollup-win32-x64-msvc": "4.67.5",
+        "fsevents": "~2.3.2"
+      }
+    },
+    "node_modules/scheduler": {
+      "version": "0.23.2",
+      "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.23.2.tgz",
+      "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
+      "license": "MIT",
+      "dependencies": {
+        "loose-envify": "^1.1.0"
+      }
+    },
+    "node_modules/semver": {
+      "version": "6.3.2",
+      "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.2.tgz",
+      "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==",
+      "dev": true,
+      "license": "ISC",
+      "bin": {
+        "semver": "bin/semver.js"
+      }
+    },
+    "node_modules/source-map-js": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.2.tgz",
+      "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/typescript": {
+      "version": "5.9.3",
+      "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
+      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "tsc": "bin/tsc",
+        "tsserver": "bin/tsserver"
+      },
+      "engines": {
+        "node": ">=14.17"
+      }
+    },
+    "node_modules/undici-types": {
+      "version": "6.21.0",
+      "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
+      "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/update-browserslist-db": {
+      "version": "1.3.4",
+      "resolved": "https://registry.npmmirror.com/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz",
+      "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/browserslist"
+        },
+        {
+          "type": "tidelift",
+          "url": "https://tidelift.com/funding/github/npm/browserslist"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "escalade": "^3.2.0",
+        "picocolors": "^1.1.1"
+      },
+      "bin": {
+        "update-browserslist-db": "cli.js"
+      },
+      "peerDependencies": {
+        "browserslist": ">= 4.21.0"
+      }
+    },
+    "node_modules/vite": {
+      "version": "5.4.21",
+      "resolved": "https://registry.npmmirror.com/vite/-/vite-5.4.21.tgz",
+      "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "esbuild": "^0.21.3",
+        "postcss": "^8.4.43",
+        "rollup": "^4.20.0"
+      },
+      "bin": {
+        "vite": "bin/vite.js"
+      },
+      "engines": {
+        "node": "^18.0.0 || >=20.0.0"
+      },
+      "funding": {
+        "url": "https://github.com/vitejs/vite?sponsor=1"
+      },
+      "optionalDependencies": {
+        "fsevents": "~2.3.3"
+      },
+      "peerDependencies": {
+        "@types/node": "^18.0.0 || >=20.0.0",
+        "less": "*",
+        "lightningcss": "^1.21.0",
+        "sass": "*",
+        "sass-embedded": "*",
+        "stylus": "*",
+        "sugarss": "*",
+        "terser": "^5.4.0"
+      },
+      "peerDependenciesMeta": {
+        "@types/node": {
+          "optional": true
+        },
+        "less": {
+          "optional": true
+        },
+        "lightningcss": {
+          "optional": true
+        },
+        "sass": {
+          "optional": true
+        },
+        "sass-embedded": {
+          "optional": true
+        },
+        "stylus": {
+          "optional": true
+        },
+        "sugarss": {
+          "optional": true
+        },
+        "terser": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/yallist": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmmirror.com/yallist/-/yallist-3.1.1.tgz",
+      "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/zod": {
+      "version": "3.25.76",
+      "resolved": "https://registry.npmmirror.com/zod/-/zod-3.25.76.tgz",
+      "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/colinhacks"
+      }
+    }
+  }
+}

+ 27 - 0
front-end/package.json

@@ -0,0 +1,27 @@
+{
+  "name": "klt-bos-console",
+  "private": true,
+  "version": "0.1.0",
+  "type": "module",
+  "scripts": {
+    "dev": "vite",
+    "build": "tsc --noEmit && vite build",
+    "preview": "vite preview",
+    "typecheck": "tsc --noEmit"
+  },
+  "dependencies": {
+    "@tanstack/react-query": "^5.106.1",
+    "react": "^18.3.1",
+    "react-dom": "^18.3.1",
+    "react-router-dom": "^6.30.6",
+    "zod": "^3.25.76"
+  },
+  "devDependencies": {
+    "@types/node": "^22.10.2",
+    "@types/react": "^18.3.31",
+    "@types/react-dom": "^18.3.7",
+    "@vitejs/plugin-react": "^4.7.0",
+    "typescript": "^5.9.3",
+    "vite": "^5.4.21"
+  }
+}

+ 72 - 0
front-end/src/App.tsx

@@ -0,0 +1,72 @@
+import { Navigate, Route, Routes } from "react-router-dom";
+import { firstRoute } from "./auth/nav";
+import { useSession } from "./auth/session";
+import { getToken } from "./api/http";
+import { Btn } from "./components/ui";
+import { AuditPage } from "./pages/AuditPage";
+import { CustomerDetailPage } from "./pages/CustomerDetailPage";
+import { CustomersPage } from "./pages/CustomersPage";
+import { EntTeamsPage } from "./pages/EntTeamsPage";
+import { HomePage } from "./pages/HomePage";
+import { ImportBatchesPage } from "./pages/ImportBatchesPage";
+import { LoginPage } from "./pages/LoginPage";
+import { MembersPage } from "./pages/MembersPage";
+import { OpsTeamsPage } from "./pages/OpsTeamsPage";
+import { OperatorsPage } from "./pages/OperatorsPage";
+import { PartnersPage } from "./pages/PartnersPage";
+import { RegionsPage } from "./pages/RegionsPage";
+import { SubAccountsPage } from "./pages/SubAccountsPage";
+
+function Guard({ children }: { children: React.ReactNode }) {
+  const { ctx, loading, error, reload } = useSession();
+  // 令牌只存 sessionStorage(⛔ 跨标签共享):新开标签深链进来时本机没有登录态,
+  // 这属「未登录」而非「未绑定角色」,须回登录页,⛔ 用角色缺失的文案误导用户。
+  if (!getToken()) return <Navigate to="/login" replace />;
+  if (loading) return <div className="guard">正在建立业务会话…</div>;
+  if (!ctx)
+    return (
+      <div className="guard">
+        <div className="big">无法获取业务角色上下文</div>
+        <div className="note">{error ?? "该登录身份尚未绑定任何业务角色,请改用已开通的账号,或联系总部管理员开通。"}</div>
+        <div className="row" style={{ justifyContent: "center", marginTop: 14 }}>
+          <Btn onClick={() => void reload()}>重试</Btn>
+          <Btn ghost onClick={() => (location.hash = "#/login")}>
+            返回登录
+          </Btn>
+        </div>
+      </div>
+    );
+  return <>{children}</>;
+}
+
+export default function App() {
+  const { ctx } = useSession();
+  return (
+    <Routes>
+      <Route path="/login" element={<LoginPage />} />
+      <Route
+        path="/*"
+        element={
+          <Guard>
+            <Routes>
+              <Route index element={<Navigate to={firstRoute(ctx?.role_code)} replace />} />
+              <Route path="home" element={<HomePage />} />
+              <Route path="regions" element={<RegionsPage />} />
+              <Route path="operators" element={<OperatorsPage />} />
+              <Route path="partners" element={<PartnersPage />} />
+              <Route path="entteams" element={<EntTeamsPage />} />
+              <Route path="opsteams" element={<OpsTeamsPage />} />
+              <Route path="members" element={<MembersPage />} />
+              <Route path="customers" element={<CustomersPage />} />
+              <Route path="customers/:id" element={<CustomerDetailPage />} />
+              <Route path="imports" element={<ImportBatchesPage />} />
+              <Route path="subaccounts" element={<SubAccountsPage />} />
+              <Route path="audit" element={<AuditPage />} />
+              <Route path="*" element={<Navigate to={firstRoute(ctx?.role_code)} replace />} />
+            </Routes>
+          </Guard>
+        }
+      />
+    </Routes>
+  );
+}

+ 671 - 0
front-end/src/api/bos.ts

@@ -0,0 +1,671 @@
+/**
+ * klt-bos 接口面:**逐字对齐** `src/bin/klt-bos/openapi.yaml` 声明的 93 个接口。
+ *
+ * ⚠️ 网关白名单为「未声明即拒绝」(code=11001),任何路径改名都会被打回,
+ *    因此本文件的 path / method / data 字段名一律照抄 spec,不做 camelCase 转换。
+ *
+ * 分组按 spec `tags`,组内按 spec 声明顺序;函数名 = 路径去 `@v1` 后转 camelCase。
+ * `get:` 型用 get(),`post:` 型用 post(),带分页的 get_list 型用 list()。
+ *
+ * 每个函数的应答标记(详见 ./types.ts 文件头的图例):
+ *   [实] 后端已真实下发 —— 类型形状照 `json_ok(...)` 建模;
+ *   [半] 部分实现 —— 形状照 handler,含占位 null / 恒空数组;
+ *   [位] ⚠️ 后端待实现,契约以此为准。
+ */
+import { get, list, post } from "./http";
+import type {
+  AccountChangePasswordResult,
+  AccountProvisionResult,
+  AccountResetCodeResult,
+  AccountStatusResult,
+  ActivationVerifyResult,
+  AuditItem,
+  AuditListResult,
+  AuthContext,
+  CatalogCreateResult,
+  CatalogGetResult,
+  CatalogListResult,
+  CatalogUpdateResult,
+  CostAmountListResult,
+  CostAmountSaveResult,
+  CostItemListResult,
+  CostItemSaveResult,
+  ContractCreateResult,
+  ContractGetResult,
+  ContractIpEntry,
+  ContractListResult,
+  ContractServiceItem,
+  ContractUpdateResult,
+  CustomerAttributionResult,
+  CustomerCreateResult,
+  CustomerDeletePrecheck,
+  CustomerDeleteResult,
+  CustomerDetail,
+  CustomerHistoryResult,
+  CustomerInfluence,
+  CustomerListResult,
+  CustomerMoveRegionResult,
+  CustomerUpdateResult,
+  EntTeamCreateResult,
+  EntTeamDeleteResult,
+  EntTeamMemberAddResult,
+  EntTeamMemberRemoveResult,
+  EntTeamScope,
+  EntTeamScopeSaveResult,
+  EntTeamTransferPrimaryResult,
+  EntTeamUpdateResult,
+  ExportResult,
+  HealthInfo,
+  ImportBatchDetail,
+  ImportBatchListResult,
+  ImportResumeResult,
+  ImportRow,
+  ImportSubmitResult,
+  ImportTemplateSpec,
+  JobKey,
+  JobRunsResult,
+  JobRunReport,
+  JobToggleResult,
+  JobSpecRow,
+  MountCandidatesResult,
+  OpsMemberAddResult,
+  OpsMemberRemoveResult,
+  OpsMemberScopeSaveResult,
+  OpsMemberUpdateResult,
+  OpsTeamCoverage,
+  OpsTeamCreateResult,
+  OpsTeamDeleteResult,
+  OpsTeamDispatchResult,
+  OpsTeamScopeSaveResult,
+  OpsTeamUpdateResult,
+  OperatorCreateResult,
+  OperatorDeleteResult,
+  OperatorListResult,
+  OperatorUpdateResult,
+  OverviewStat,
+  EntTeamListResult,
+  OpsTeamListResult,
+  PartnerCreateResult,
+  PartnerDeleteResult,
+  PartnerListResult,
+  PartnerScope,
+  PartnerScopeSaveResult,
+  PartnerUpdateResult,
+  PingInfo,
+  ReconAccountCreateResult,
+  ReconAccountGetResult,
+  RegionChangeLogResult,
+  RegionCreateResult,
+  RegionDeleteResult,
+  RegionOrphanResult,
+  RegionRenameResult,
+  RegionSubtreeResult,
+  RegionTreeResult,
+  ShareRuleDeleteResult,
+  ShareRuleDetail,
+  ShareRuleListResult,
+  ShareRuleSaveResult,
+  SubAccountListResult,
+  SubAccountUpdateResult,
+  SubscriptionChangeResult,
+  SubscriptionCreateResult,
+  SubscriptionGetResult,
+  SubscriptionListResult,
+  SubscriptionStackResult,
+} from "./types";
+
+/* ── 系统健康(3) ─────────────────────────────────────────────── */
+
+/** 健康检查 [实] —— 服务存活探测,无需登录。 */
+export const health = () => get<HealthInfo>("/health");
+/** 健康检查(v1) [实] —— 同上,带版本后缀路径。 */
+export const healthV1 = () => get<HealthInfo>("/health@v1");
+/** 存活探测 [实] —— 需登录,返回服务状态与绑定信息。 */
+export const ping = () => get<PingInfo>("/ping@v1");
+
+/* ── 认证与激活(2) ───────────────────────────────────────────── */
+
+/** 当前登录上下文 [半] —— 身份/角色/主体/可见形态;未激活、已过期在此拦截。六项展示字段后端待补。 */
+export const authContext = () => get<AuthContext>("/auth/context@v1");
+/** 激活并设置密码 [位] —— 免登录豁免接口,校验激活码后设密。 */
+export const activationVerify = (d: { code: string; new_password: string }) =>
+  post<ActivationVerifyResult>("/activation/verify@v1", d);
+
+/* ── 区域管理(7) ─────────────────────────────────────────────── */
+
+/** 新建区域节点 [位] —— admin 任意层级;区域运营主/子账号限本范围内已有省份下建市/区县。 */
+export const regionCreate = (d: { node_name: string; parent_node_id?: string; level?: string }) =>
+  post<RegionCreateResult>("/region/create@v1", d);
+/** 重命名区域节点 [位] —— 仅改 node_name,不改层级与父子关系。 */
+export const regionRename = (d: { node_id: string; node_name: string }) =>
+  post<RegionRenameResult>("/region/rename@v1", d);
+/** 删除区域节点 [位] —— 仅 admin,须带逐字一致的 confirm_name 并过三重守卫。 */
+export const regionDelete = (d: { node_id: string; confirm_name: string }) =>
+  post<RegionDeleteResult>("/region/delete@v1", d);
+/** 查询可见区域树 [实] —— handler 只返回收窄后的 `node_ids` 扁平数组。⚠️ 2026-11-08 由 GET 改 POST(R-5)。 */
+export const regionTree = () => post<RegionTreeResult>("/region/tree@v1", {});
+/** 查询区域子树 [实] —— handler 直接复用 tree(),形状同为 `node_ids`。 */
+export const regionSubtree = (d?: { node_id?: string }) => post<RegionSubtreeResult>("/region/subtree@v1", d ?? {});
+/** 区域变更流水 [位] —— 仅 admin 可见。 */
+export const regionChangeLog = () => get<RegionChangeLogResult>("/region/change_log@v1");
+/** 悬空区域节点 [实] —— 下发未清理完成的挂载请求候选(含 total/dangling_count/message)。⚠️ 2026-11-08 由 GET 改 POST(R-5)。 */
+export const regionOrphans = () => post<RegionOrphanResult>("/region/orphans@v1", {});
+
+/* ── 账号管理(5) ─────────────────────────────────────────────── */
+
+/** 开通账号 [位] —— 四入口共用开通管线;唯一性守卫先于平台调用。 */
+export const accountProvision = (d: {
+  username: string;
+  role_code: string;
+  subject_type: string;
+  subject_id: string;
+  mobile?: string;
+}) => post<AccountProvisionResult>("/account/provision@v1", d);
+/** 停用或恢复账号 [位] —— 不可操作当前登录账号。 */
+export const accountUpdateStatus = (d: { user_id: string; status: string }) =>
+  post<AccountStatusResult>("/account/update_status@v1", d);
+/** 重置激活码 [位] —— 仅未激活账号可重置,新码仅当次返回。 */
+export const accountResetCode = (d: { user_id: string }) => post<AccountResetCodeResult>("/account/reset_code@v1", d);
+/** 导出激活码 [位] —— validity=expired/all 为写操作(先作废再换新码)。 */
+export const accountExportCodes = (d: {
+  user_ids: string[];
+  scope_type: string;
+  scope_id: string;
+  validity: string;
+}) => post<ExportResult>("/account/export_codes@v1", d);
+/** 自助修改密码 [位] —— 新旧相同不保存。 */
+export const accountChangePassword = (d: { old_password: string; new_password: string }) =>
+  post<AccountChangePasswordResult>("/account/change_password@v1", d);
+
+/* ── 运营商(6) ───────────────────────────────────────────────── */
+
+/** 新建运营商 [半] —— 所属区域须为省级节点;同省份×品牌唯一。operator_id 当前恒 null。 */
+export const operatorCreate = (d: {
+  name: string;
+  brand: string;
+  region_node_id: string;
+  is_province_node?: boolean;
+  settle_mode?: string;
+  settle_value?: number;
+}) => post<OperatorCreateResult>("/operator/create@v1", d);
+/** 编辑运营商 [位] —— 改品牌/省份不得绕过唯一与省级校验。 */
+export const operatorUpdate = (d: {
+  operator_id: string;
+  name: string;
+  brand: string;
+  region_node_id: string;
+  is_province_node?: boolean;
+  settle_mode?: string;
+  settle_value?: number;
+  row_version?: number;
+}) => post<OperatorUpdateResult>("/operator/update@v1", d);
+/** 删除运营商 [位] —— 删除前六项检查并级联注销对账账号。 */
+export const operatorDelete = (d: { operator_id: string }) => post<OperatorDeleteResult>("/operator/delete@v1", d);
+/** 运营商列表 [实] —— 名称/品牌模糊+建档区域过滤,带名下客户数。 */
+export const operatorGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  region_node_id?: string;
+}) => list<OperatorListResult>("/operator/get_list@v1", d, d);
+/** 创建对账账号 [半] —— 一家运营商至多一个;初始密码仅当次显示。user_id 当前恒 null。 */
+export const operatorReconAccountCreate = (d: { operator_id: string; username: string; mobile?: string }) =>
+  post<ReconAccountCreateResult>("/operator/recon_account/create@v1", d);
+/** 查询对账账号 [位] —— 只回状态提示,不回密码。 */
+export const operatorReconAccountGet = (d: { operator_id: string }) =>
+  post<ReconAccountGetResult>("/operator/recon_account/get@v1", d);
+
+/* ── 合伙人(6) ───────────────────────────────────────────────── */
+
+/** 新建合伙人 [半] —— 建档并同步开通账号;名称全站唯一。partner_id 当前恒 null。 */
+export const partnerCreate = (d: {
+  name: string;
+  region_node_id: string;
+  username: string;
+  duty_desc?: string;
+  mobile?: string;
+  settle_mode?: string;
+  settle_value?: number;
+}) => post<PartnerCreateResult>("/partner/create@v1", d);
+/** 编辑合伙人 [位] —— 登录名不可改。 */
+export const partnerUpdate = (d: {
+  partner_id: string;
+  name: string;
+  duty_desc?: string;
+  region_node_id?: string;
+  mobile?: string;
+  settle_mode?: string;
+  settle_value?: number;
+  row_version?: number;
+}) => post<PartnerUpdateResult>("/partner/update@v1", d);
+/** 删除合伙人 [位] —— 删除档案及相关授权。 */
+export const partnerDelete = (d: { partner_id: string }) => post<PartnerDeleteResult>("/partner/delete@v1", d);
+/** 合伙人列表 [实] —— 名称模糊+区域/状态过滤;手机号已掩码(需求§5.4)。 */
+export const partnerGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  region_node_id?: string;
+  status?: string;
+}) => list<PartnerListResult>("/partner/get_list@v1", d, d);
+/** 读取合伙人负责范围 [位] —— 返回 region/customer 两类 bos_data_scope。 */
+export const partnerScopeGet = () => post<PartnerScope>("/partner/scope/get@v1", {});
+/** 保存合伙人负责范围 [位] —— 允许保存为空,保存即 bump epoch。 */
+export const partnerScopeSave = (d: { partner_id: string; region_node_ids?: string[]; customer_ids?: string[] }) =>
+  post<PartnerScopeSaveResult>("/partner/scope/save@v1", d);
+
+/* ── 运营团队(8) ─────────────────────────────────────────────── */
+
+/** 新建运营团队 [位] —— 仅 admin,负责范围初始为空。 */
+export const entTeamCreate = (d: { team_name: string; primary_username?: string; primary_mobile?: string; remark?: string }) =>
+  post<EntTeamCreateResult>("/ent_team/create@v1", d);
+/** 编辑运营团队 [位] —— 仅 admin。`remark` 三态:⛔ 本键=⛔ 改本列;空白串=清空;带文本=设值。 */
+export const entTeamUpdate = (d: { team_id: string; team_name: string; remark?: string; row_version?: number }) =>
+  post<EntTeamUpdateResult>("/ent_team/update@v1", d);
+/** 删除运营团队 [位] —— 内置「总部·不限区域」团队不可删。 */
+export const entTeamDelete = (d: { team_id: string }) => post<EntTeamDeleteResult>("/ent_team/delete@v1", d);
+/** 添加运营团队成员 [位] —— 每团队有且仅有一个主账号。 */
+export const entTeamMemberAdd = (d: { team_id: string; username: string; mobile?: string; is_primary?: boolean }) =>
+  post<EntTeamMemberAddResult>("/ent_team/member_add@v1", d);
+/** 移除运营团队成员 [位] —— 内置主账号不可删,不可删当前登录账号。 */
+export const entTeamMemberRemove = (d: { team_id: string; user_id: string }) =>
+  post<EntTeamMemberRemoveResult>("/ent_team/member_remove@v1", d);
+/** 转交运营团队主账号 [实] —— 守卫已接线但恒拒绝(transferred:false + reason),宿主域接线后启用。 */
+export const entTeamTransferPrimary = (d: { team_id: string; from_user_id: string; to_user_id: string }) =>
+  post<EntTeamTransferPrimaryResult>("/ent_team/transfer_primary@v1", d);
+/** 读取运营团队负责范围 [位] —— 仅 admin。 */
+export const entTeamScopeGet = () => post<EntTeamScope>("/ent_team/scope/get@v1", {});
+/** 保存运营团队负责范围 [位] —— 仅 admin,写入 bos_data_scope(holder=ent_team)。 */
+export const entTeamScopeSave = (d: { team_id: string; region_node_ids: string[] }) =>
+  post<EntTeamScopeSaveResult>("/ent_team/scope/save@v1", d);
+
+/* ── 运维团队与成员(10) ─────────────────────────────────────── */
+
+/** 新建运维团队 [半] —— 须指定区域、可派工单类型≥1、分派方式与结算口径。team_id 当前恒 null。 */
+export const opsTeamCreate = (d: {
+  team_name: string;
+  region_node_id: string;
+  ticket_types: string[];
+  dispatch_mode: string;
+  settle_mode?: string;
+  settle_value?: number;
+  primary_username?: string;
+  primary_mobile?: string;
+}) => post<OpsTeamCreateResult>("/ops_team/create@v1", d);
+/** 编辑运维团队 [位] —— 2026-11-05 起团队不分类型,无 team_type 键。 */
+export const opsTeamUpdate = (d: {
+  team_id: string;
+  team_name?: string;
+  region_node_id?: string;
+  ticket_types?: string[];
+  settle_mode?: string;
+  settle_value?: number;
+  row_version?: number;
+}) => post<OpsTeamUpdateResult>("/ops_team/update@v1", d);
+/** 删除运维团队 [位] —— 校验引用与未办完工单等守卫。 */
+export const opsTeamDelete = (d: { team_id: string }) => post<OpsTeamDeleteResult>("/ops_team/delete@v1", d);
+/** 保存运维团队负责范围 [位] —— 同事务校验包含关系与未办完工单守卫。 */
+export const opsTeamScopeSave = (d: { team_id: string; region_node_ids?: string[]; customer_ids?: string[] }) =>
+  post<OpsTeamScopeSaveResult>("/ops_team/scope/save@v1", d);
+/** 添加运维成员 [位] —— 建成员档案并开通运维子账号(role_code=ops)。 */
+export const opsTeamMemberAdd = (d: { team_id: string; username: string; ticket_types?: string[]; mobile?: string }) =>
+  post<OpsMemberAddResult>("/ops_team/member_add@v1", d);
+/** 更新运维成员 [位] —— 可改手机号与可处理工单类型,不改 role_code。 */
+export const opsTeamMemberUpdate = (d: { team_id: string; member_id: string; ticket_types?: string[]; mobile?: string }) =>
+  post<OpsMemberUpdateResult>("/ops_team/member_update@v1", d);
+/** 移除运维成员 [位] —— 删除前五项检查并注销账号。 */
+export const opsTeamMemberRemove = (d: { team_id: string; member_id: string }) =>
+  post<OpsMemberRemoveResult>("/ops_team/member_remove@v1", d);
+/** 保存运维成员负责范围 [位] —— scope_mode∈follow_team/region/customer。 */
+export const opsMemberScopeSave = (d: { member_id: string; scope_mode: string; targets?: string[] }) =>
+  post<OpsMemberScopeSaveResult>("/ops_member/scope/save@v1", d);
+/** 更新分派方式 [位] —— 与运营侧改同一字段,后写入者生效。 */
+export const opsTeamDispatchModeUpdate = (d: { team_id: string; dispatch_mode: string }) =>
+  post<OpsTeamDispatchResult>("/ops_team/dispatch_mode/update@v1", d);
+/** 运维团队覆盖客户 [位] —— 团队区域范围(Tree) ∩ 归属(Owner)。 */
+export const opsTeamCoverageGet = () => post<OpsTeamCoverage>("/ops_team/coverage/get@v1", {});
+
+/* ── 客户管理(11) ────────────────────────────────────────────── */
+
+/** 新建客户 [位] —— 须指定归属运营商;可选合伙人、挂载申请、父区域节点。 */
+export const customerCreate = (d: {
+  customer_name: string;
+  subject_type: string;
+  operator_id: string;
+  partner_id?: string;
+  mount_request_id?: string;
+  parent_node_id?: string;
+  id_code?: string;
+  contact_name?: string;
+  contact_mobile?: string;
+  address?: string;
+  ops_team_ids?: string[];
+  primary_username?: string;
+  primary_mobile?: string;
+}) => post<CustomerCreateResult>("/customer/create@v1", d);
+/**
+ * 客户列表 [实] —— 可见范围由后端按角色下发(运维侧全量、团队走 `customer_team_belong`、
+ * 企业/分账号/合伙人走 `visible_customer_ids`),前端⛔ 自行判权限。
+ */
+export const customerGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  operator_id?: string;
+  partner_id?: string;
+  acct_status?: string;
+  subject_type?: string;
+}) => list<CustomerListResult>("/customer/get_list@v1", d, d);
+/** 客户详情 [实] —— 主体+当前承接团队+分账号数+区域挂载(订阅/合同视图⛔ 数源,属第 3 册)。 */
+export const customerGet = (d: { customer_id: string }) => post<CustomerDetail>("/customer/get@v1", d);
+/** 编辑客户 [位] —— 拒收 customer_id/region_node_id/operator_id/partner_id;改识别号须带 change_basis。 */
+export const customerUpdate = (d: {
+  customer_id: string;
+  customer_name?: string;
+  subject_type?: string;
+  id_code?: string;
+  change_basis?: string;
+  contact_name?: string;
+  contact_mobile?: string;
+  address?: string;
+  ops_team_ids?: string[];
+  row_version?: number;
+}) => post<CustomerUpdateResult>("/customer/update@v1", d);
+/** 客户删除前置检查 [位] —— 返回 can_delete 与 blocked 清单+阻塞快照版本。 */
+export const customerDeletePrecheck = (d: { customer_id: string }) =>
+  post<CustomerDeletePrecheck>("/customer/delete_precheck@v1", d);
+/** 删除客户 [位] —— 须携带前置检查时的阻塞快照版本。 */
+export const customerDelete = (d: { customer_id: string; precheck_version?: string }) =>
+  post<CustomerDeleteResult>("/customer/delete@v1", d);
+/** 客户变更历史 [位] —— 档案变更流水(分页)。 */
+export const customerHistory = (d: { customer_id: string; page?: number; page_size?: number; keyword?: string }) =>
+  list<CustomerHistoryResult>("/customer/history@v1", d, d);
+/** 改挂候选客户 [位] —— 操作人可见范围内可作改挂目标的客户。 */
+export const customerMountCandidates = () => post<MountCandidatesResult>("/customer/mount_candidates@v1", {});
+/** 改挂影响面 [位] —— 未办完工单数、当前责任人与团队、当期是否已出账。 */
+export const customerInfluence = (d: { customer_id: string }) => post<CustomerInfluence>("/customer/influence@v1", d);
+/** 客户改挂区域 [位] —— 复合事务;新区域省份须等于归属运营商档案省份。 */
+export const customerMoveRegion = (d: { customer_id: string; new_region_node_id: string; ops_team_ids?: string[] }) =>
+  post<CustomerMoveRegionResult>("/customer/move_region@v1", d);
+/** 更新客户归属 [位] —— 改归属运营商/合伙人。 */
+export const customerAttributionUpdate = (d: { customer_id: string; operator_id?: string; partner_id?: string }) =>
+  post<CustomerAttributionResult>("/customer/attribution/update@v1", d);
+
+/* ── 批量导入(7) ─────────────────────────────────────────────── */
+
+/** 下载导入模板 [实] —— handler 返回 `{ format:"xlsx", columns:14, max_rows:500 }`,columns 为列数。 */
+export const importBatchTemplateDownload = () => get<ImportTemplateSpec>("/import_batch/template_download@v1");
+/** 提交客户批量导入 [半] —— 单批上限 500 行;total 为真实行数,batch_no 当前恒 null。 */
+export const importBatchSubmit = (d: { rows: ImportRow[] }) => post<ImportSubmitResult>("/import_batch/submit@v1", d);
+export const importBatchGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  status?: string;
+}) => list<ImportBatchListResult>("/import_batch/get_list@v1", d, d);
+export const importBatchGet = (d: { batch_no?: string; batch_id?: string; page?: number; page_size?: number }) =>
+  post<ImportBatchDetail>("/import_batch/get@v1", d);
+/** 失败行续传 [位] —— 行号对应原 row_no。 */
+export const importBatchResume = (d: { batch_id: string; rows: ImportRow[] }) =>
+  post<ImportResumeResult>("/import_batch/resume@v1", d);
+/** 按批次导出激活码 [位] —— 语义同账号导出,须传收窄后的 user_ids 与 scope。 */
+export const importBatchExportCodes = (d: {
+  batch_id: string;
+  user_ids: string[];
+  scope_type: string;
+  scope_id: string;
+  validity: string;
+}) => post<ExportResult>("/import_batch/export_codes@v1", d);
+/** 按批次导出客户 [位] —— 15 列结果。 */
+export const importBatchExportCustomers = (d: { batch_id: string }) =>
+  post<ExportResult>("/import_batch/export_customers@v1", d);
+
+/* ── 账号管理 · 分账号(2) ───────────────────────────────────── */
+
+/** 分账号列表 [实] —— 登录名/使用人/用途/网络侧账号名;可见范围后端下发。 */
+export const subAccountGetList = (d: { customer_id: string; page?: number; page_size?: number; keyword?: string }) =>
+  list<SubAccountListResult>("/sub_account/get_list@v1", d, d);
+/** 更新分账号 [位] —— 运营可改 display_name 与 network_account_name;客户主账号只许改 display_name。 */
+export const subAccountUpdate = (d: { sub_account_id: string; display_name?: string; network_account_name?: string }) =>
+  post<SubAccountUpdateResult>("/sub_account/update@v1", d);
+
+/* ── 套餐档位(4) ─────────────────────────────────────────────── */
+
+/** 新建套餐档位 [位] —— 自定义档必填 customer_id;拒收 monthly_settle_cents/sub_mode/first_referred_at。 */
+export const catalogCreate = (d: {
+  plan_kind: string;
+  plan_name: string;
+  use_category: string;
+  annual_price_cents: number;
+  sub_account_quota?: number;
+  bandwidth_committed?: boolean;
+  bandwidth_up_mbps?: number;
+  bandwidth_down_mbps?: number;
+  customer_id?: string;
+}) => post<CatalogCreateResult>("/catalog/create@v1", d);
+/** 编辑套餐档位 [位] —— use_category 建后不可改;被订阅引用冻结后多数字段只读。 */
+export const catalogUpdate = (d: {
+  plan_id: string;
+  plan_name?: string;
+  annual_price_cents?: number;
+  sub_account_quota?: number;
+  bandwidth_committed?: boolean;
+  bandwidth_up_mbps?: number;
+  bandwidth_down_mbps?: number;
+  row_version?: number;
+}) => post<CatalogUpdateResult>("/catalog/update@v1", d);
+/** 套餐档位列表 [位] —— 按 plan_kind 等条件筛选。 */
+export const catalogGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  plan_kind?: string;
+  use_category?: string;
+  customer_id?: string;
+}) => list<CatalogListResult>("/catalog/get_list@v1", d, d);
+/** 套餐档位详情 [位]。 */
+export const catalogGet = (d: { plan_id: string }) => post<CatalogGetResult>("/catalog/get@v1", d);
+
+/* ── 合同(4) ─────────────────────────────────────────────────── */
+
+/** 新建合同 [位] —— 客户段+合同段+服务构成条目+IP 条件一次提交;拒收 source。 */
+export const contractCreate = (d: {
+  pay_cycle: string;
+  start_date: string;
+  end_date: string;
+  customer_id?: string;
+  contract_no?: string;
+  external_no?: string;
+  contract_amount_cents?: number;
+  agent_name?: string;
+  agent_mobile?: string;
+  agent_handover_on?: string;
+  agent_org?: string;
+  attachment_url?: string;
+  service_items?: ContractServiceItem[];
+  ip_entries?: ContractIpEntry[];
+}) => post<ContractCreateResult>("/contract/create@v1", d);
+/** 编辑合同 [位] —— 编号与签约客户不可改;条目按 item_id 三向对比增删改。 */
+export const contractUpdate = (d: {
+  contract_id: string;
+  row_version: number;
+  external_no?: string;
+  contract_amount_cents?: number;
+  pay_cycle?: string;
+  start_date?: string;
+  end_date?: string;
+  agent_name?: string;
+  agent_mobile?: string;
+  agent_handover_on?: string;
+  agent_org?: string;
+  attachment_url?: string;
+  service_items?: ContractServiceItem[];
+  ip_entries?: ContractIpEntry[];
+}) => post<ContractUpdateResult>("/contract/update@v1", d);
+/** 合同列表 [位] —— 按客户/状态等筛选。 */
+export const contractGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  customer_id?: string;
+  status?: string;
+}) => list<ContractListResult>("/contract/get_list@v1", d, d);
+/** 合同详情 [位] —— 含服务条目与 IP 条件。 */
+export const contractGet = (d: { contract_id: string }) => post<ContractGetResult>("/contract/get@v1", d);
+
+/* ── 订阅(5) ─────────────────────────────────────────────────── */
+
+/** 新建订阅 [位] —— 拒收 line_exits/sub_mode/order_no、新建时 end_date、opened_at。 */
+export const subscriptionCreate = (d: {
+  customer_id: string;
+  plan_id: string;
+  contract_id: string;
+  contract_item_id: string;
+  start_date: string;
+  annual_price_cents: number;
+  monthly_settle_cents: number;
+  use_category?: string;
+}) => post<SubscriptionCreateResult>("/subscription/create@v1", d);
+/** 订阅升降配 [位] —— 须填 replaces_subscription_id 且使用新的 contract_id。 */
+export const subscriptionChange = (d: {
+  replaces_subscription_id: string;
+  customer_id: string;
+  plan_id: string;
+  contract_id: string;
+  contract_item_id: string;
+  start_date: string;
+  annual_price_cents: number;
+  monthly_settle_cents: number;
+  use_category?: string;
+}) => post<SubscriptionChangeResult>("/subscription/change@v1", d);
+/** 订阅叠加或白名单更新 [位] —— 仅两金额+end_date 等白名单字段可写。 */
+export const subscriptionStack = (d: {
+  subscription_id?: string;
+  customer_id?: string;
+  plan_id?: string;
+  contract_id?: string;
+  contract_item_id?: string;
+  annual_price_cents?: number;
+  monthly_settle_cents?: number;
+  end_date?: string;
+  start_date?: string;
+}) => post<SubscriptionStackResult>("/subscription/stack@v1", d);
+/** 订阅列表 [位] —— 按客户等维度筛选。 */
+export const subscriptionGetList = (d?: {
+  customer_id?: string;
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  status?: string;
+}) => list<SubscriptionListResult>("/subscription/get_list@v1", d, d);
+/** 订阅详情 [位]。 */
+export const subscriptionGet = (d: { subscription_id: string }) => post<SubscriptionGetResult>("/subscription/get@v1", d);
+
+/* ── 成本与分成(8) ───────────────────────────────────────────── */
+
+/** 保存成本项定义 [位] —— 仅 admin;拒收金额、客户、运营商、省份、cycle、is_system。 */
+export const costItemSave = (d: {
+  category: string;
+  item_name: string;
+  billing_unit: string;
+  is_amortized: boolean;
+  deduct_from_base: boolean;
+  cost_item_id?: string;
+  amortization_months?: number;
+  remark?: string;
+  row_version?: number;
+}) => post<CostItemSaveResult>("/cost_item/save@v1", d);
+/** 成本项列表 [位] —— 全局成本项目录,无客户过滤。 */
+export const costItemGetList = (d?: { page?: number; page_size?: number; keyword?: string; category?: string }) =>
+  list<CostItemListResult>("/cost_item/get_list@v1", d, d);
+/** 保存成本金额 [位] —— 按「省份×运营商×成本项」只写差异金额;留空表示删除该差异。 */
+export const costAmountSave = (d: {
+  province_node_id: string;
+  operator_id: string;
+  items: { cost_item_id: string; amount_cents?: number; row_version?: number }[];
+}) => post<CostAmountSaveResult>("/cost_amount/save@v1", d);
+/** 成本金额一览 [位] —— 透视表;admin 全量,区域运营按可见省/运营商收窄。 */
+export const costAmountGetList = (d?: {
+  province_node_id?: string;
+  operator_id?: string;
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+}) => list<CostAmountListResult>("/cost_amount/get_list@v1", d, d);
+/** 保存分成规则 [位] —— holder_type 仅 operator/ops_team;share_value 填 0/负表示删除该行。 */
+export const shareRuleSave = (d: {
+  holder_type: string;
+  holder_id: string;
+  rules: {
+    rule_id?: string;
+    customer_id?: string;
+    rule_level?: "contract_addon" | "region_regular";
+    share_mode?: "ratio_total" | "per_account" | "fixed_amount";
+    share_value?: number;
+    remark?: string;
+  }[];
+}) => post<ShareRuleSaveResult>("/share_rule/save@v1", d);
+/** 分成规则列表 [位]。 */
+export const shareRuleGetList = (d?: {
+  holder_type?: string;
+  holder_id?: string;
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+}) => list<ShareRuleListResult>("/share_rule/get_list@v1", d, d);
+/** 分成规则详情 [位] —— 按持有方一次返回四卡摘要与规则表。 */
+export const shareRuleGet = (d: { holder_type: string; holder_id: string }) => post<ShareRuleDetail>("/share_rule/get@v1", d);
+/** 删除分成规则 [半] —— handler 恒返回 `{ deleted: true, req }`(未落库);亦可在 save 内以 0/负值删除。 */
+export const shareRuleDelete = (d: { rule_id: string }) => post<ShareRuleDeleteResult>("/share_rule/delete@v1", d);
+
+/* ── 运维视图(1) ─────────────────────────────────────────────── */
+
+/** 运维只读首页 [实] —— U-60 方案 B:当前为诚实空态(tickets/overdue.available=false),前端须兜空态。 */
+export const opsviewHome = () => get<OverviewStat>("/opsview/home@v1");
+
+/* ── 定时作业(4) ─────────────────────────────────────────────── */
+
+/** 定时作业清单 [实] —— 来自 `phase1_job_specs()`,形状 `{ items: JobSpecRow[] }`;spec 为 get 型,不分页。 */
+export const jobsGetList = () => get<{ items: JobSpecRow[] }>("/jobs/get_list@v1");
+/** 启停定时作业 [实] —— 仅 admin;平台 sjc_job_toggle 透传,形状由平台决定。 */
+export const jobsToggle = (d: { key: JobKey; enabled: boolean }) => post<JobToggleResult>("/jobs/toggle@v1", d);
+/** 作业执行记录 [半] —— handler 返回 `{ job_key, runs: [] }`,runs 待接。 */
+export const jobsRuns = (d: { key: JobKey }) => post<JobRunsResult>("/jobs/runs@v1", d);
+/** 补跑作业一次 [实] —— 返回 RunReport `{processed,succeeded,skipped,failed,message}`;prod 仅总运营可补跑。 */
+export const jobsRunOnce = (d: { key: JobKey }) => post<JobRunReport>("/jobs/run_once@v1", d);
+
+/* ── 分页列表补齐(p6b:后端已落真 SQL,路由早已在 openapi.yaml 声明) ── */
+
+/** 运营团队列表 [实] —— 负责人登录名+成员数;成员明细⛔ 只读接口。 */
+export const entTeamGetList = (d?: { page?: number; page_size?: number; keyword?: string }) =>
+  list<EntTeamListResult>("/ent_team/get_list@v1", d, d);
+
+/** 运维团队列表 [实] —— 带可分配工单类型;负载两列暂无数源(后端回 null+load_pending)。 */
+export const opsTeamGetList = (d?: {
+  page?: number;
+  page_size?: number;
+  keyword?: string;
+  region_node_id?: string;
+}) => list<OpsTeamListResult>("/ops_team/get_list@v1", d, d);
+
+/**
+ * 操作日志列表 [实] —— 游标 `(occurred_at)|id`,⛔ total/⛔ OFFSET,靠 `next_cursor` 翻页。
+ * 日志是「兜底对账入口」,只读,⛔ 任何修改入口。
+ *
+ * ⚠️ 入参名以 `handlers/audit.rs::AuditListReq` 为真源:`object_type`/`object_ref{type,id}`/
+ * `actor_user_id`/`occurred_from`/`occurred_to`/`keyword`。曾按 `action`/`actor_username`/
+ * `object_id`/`from`/`to` 送参 ⇒ 后端 `serde` 静默丢弃未知字段,页面「查询」按钮形同刷新(实测:
+ * 动作填乱码仍回 45 条,只有 `object_type` 生效)。后端**没有** `action` 入参 ⇒ 这里也不提供。
+ */
+export const auditGetList = (d?: {
+  cursor?: string;
+  page_size?: number;
+  object_type?: string;
+  object_ref?: { type: string; id: string };
+  actor_user_id?: string;
+  occurred_from?: string;
+  occurred_to?: string;
+  keyword?: string;
+}) => post<AuditListResult>("/audit/get_list@v1", d ?? {});
+
+export type { AuditItem };

+ 112 - 0
front-end/src/api/http.ts

@@ -0,0 +1,112 @@
+/**
+ * klt-bos 业务接口客户端。
+ *
+ * 统一信封(总则§2):请求 { data, cursor?, page_size? },应答 { code, message, data },
+ * code=10000 为成功。失败关闭:非 10000 一律抛 ApiError,由调用方决定提示还是回退。
+ *
+ * 通路:默认经 Vite 代理走平台网关(/gateway → https://localhost:3000 → /api/klt-bos);
+ * 网关路由尚未注册时可置 VITE_BOS_VIA_GATEWAY=0 直连本地进程(/bos → 127.0.0.1:$KLT_BOS_PORT,
+ * 该代理会剥掉 `/bos` 前缀,因为本地进程的路由不带服务名前缀)。
+ */
+
+export const OK = 10000;
+
+export class ApiError extends Error {
+  constructor(
+    public code: number | null,
+    message: string,
+    public status?: number,
+    public detail?: unknown,
+  ) {
+    super(message);
+    this.name = "ApiError";
+  }
+}
+
+const VIA_GATEWAY = (import.meta.env.VITE_BOS_VIA_GATEWAY ?? "1") !== "0";
+const BASE = VIA_GATEWAY ? "/gateway/api/klt-bos" : "/bos";
+
+export type Envelope<T> = { code: number; message: string; data: T };
+
+export type Page<T> = {
+  items: T[];
+  total: number;
+  page: number;
+  page_size: number;
+};
+
+export const TOKEN_KEY = "klt.bos.accessToken";
+
+export function getToken(): string | null {
+  return sessionStorage.getItem(TOKEN_KEY);
+}
+
+export function setToken(t: string | null) {
+  if (t) sessionStorage.setItem(TOKEN_KEY, t);
+  else sessionStorage.removeItem(TOKEN_KEY);
+}
+
+/** 未授权/无权限:跳回登录,前端不做兜底渲染(总则§16.5)。 */
+function onUnauthorized() {
+  setToken(null);
+  if (!location.hash.startsWith("#/login")) location.hash = "#/login";
+}
+
+export async function call<T>(
+  path: string,
+  data?: unknown,
+  opts: { method?: "GET" | "POST"; page?: { page?: number; page_size?: number } } = {},
+): Promise<T> {
+  const method = opts.method ?? (path.includes("/get_list@") || !path.endsWith("/tree@v1") ? "POST" : "POST");
+  const query = new URLSearchParams();
+  if (opts.page?.page) query.set("page", String(opts.page.page));
+  if (opts.page?.page_size) query.set("page_size", String(opts.page.page_size));
+  const qs = query.toString();
+  const url = `${BASE}${path}${qs ? `?${qs}` : ""}`;
+
+  const headers: Record<string, string> = { "Content-Type": "application/json" };
+  const token = getToken();
+  if (token) headers.Authorization = `Bearer ${token}`;
+
+  let r: Response;
+  try {
+    r = await fetch(url, {
+      method,
+      headers,
+      body: method === "GET" ? undefined : JSON.stringify({ data: data ?? {}, ...opts.page }),
+    });
+  } catch (e) {
+    throw new ApiError(null, `网络不可达:${(e as Error).message}`);
+  }
+
+  const raw = await r.text();
+  let body: Envelope<T> | null = null;
+  try {
+    body = JSON.parse(raw) as Envelope<T>;
+  } catch {
+    /* 非 JSON(网关原文/HTML) */
+  }
+
+  if (r.status === 401 || body?.code === 11002) {
+    onUnauthorized();
+    throw new ApiError(body?.code ?? null, body?.message ?? "登录态失效,请重新登录", r.status, raw);
+  }
+  if (!body) {
+    throw new ApiError(null, `应答不是合法信封(HTTP ${r.status}):${raw.slice(0, 200)}`, r.status, raw);
+  }
+  if (body.code !== OK) {
+    throw new ApiError(body.code, body.message || `接口失败(code=${body.code})`, r.status, body.data);
+  }
+  return body.data;
+}
+
+/** GET 型接口(无 data)。 */
+export const get = <T>(path: string) => call<T>(path, undefined, { method: "GET" });
+/** POST 型接口。 */
+export const post = <T>(path: string, data?: unknown) => call<T>(path, data, { method: "POST" });
+/** 分页列表接口:page/page_size 同时放 body 与 query,兼容两种读法。 */
+export const list = <T>(
+  path: string,
+  data?: Record<string, unknown> | null,
+  page?: { page?: number; page_size?: number },
+) => call<T>(path, { ...(data ?? {}), ...(page ?? {}) }, { method: "POST", page });

+ 107 - 0
front-end/src/api/labels.ts

@@ -0,0 +1,107 @@
+/**
+ * 枚举原值 → 中文展示。
+ *
+ * 原值真源:`src/migrations/dev/20261104000001_bos_core_tables.sql` 列注释(dev 库 27 张表)。
+ * 未知原值一律**原样返回**,⛔ 映射成「正常」等默认值冒充。
+ */
+
+export const SUBJECT_TYPE: Record<string, string> = {
+  hq: "总部",
+  region: "区域",
+  ops_team: "运维团队",
+  ent_team: "运营团队",
+  customer: "客户",
+  sub_account: "分账号",
+  partner: "合伙人",
+  operator: "运营商",
+  enterprise: "企业",
+  individual: "个人",
+  sole_proprietor: "个体工商户",
+};
+
+export const ACCT_STATUS: Record<string, string> = {
+  active: "正常",
+  normal: "正常",
+  not_opened: "未开通",
+  in_use: "使用中",
+  stopped: "已停用",
+  disabled: "已停用",
+  expired: "已过期",
+  unactivated: "未激活",
+};
+
+export const PARTNER_STATUS: Record<string, string> = {
+  active: "正常",
+  disabled: "已停用",
+  pending: "待激活",
+};
+
+export const IMPORT_STATUS: Record<string, string> = {
+  running: "处理中",
+  done: "已完成",
+  failed_pending: "部分成功",
+  failed: "失败",
+};
+
+export const VALIDATE_STATUS: Record<string, string> = {
+  pending: "待校验",
+  valid: "校验通过",
+  invalid: "校验失败",
+  imported: "已导入",
+};
+
+export const SETTLE_MODE: Record<string, string> = {
+  ratio: "按比例分成",
+  amount: "固定金额分成",
+  per_account: "按账号数分成",
+};
+
+export const DISPATCH_MODE: Record<string, string> = {
+  manual: "手动分派",
+  auto_avg: "自动均衡分派",
+};
+
+export const SCOPE_MODE: Record<string, string> = {
+  follow_team: "跟随团队",
+  region: "按区域",
+  customer: "按客户",
+};
+
+export const TARGET_TYPE: Record<string, string> = {
+  region: "区域节点",
+  customer: "客户",
+  ops_team: "运维团队",
+  ent_team: "运营团队",
+  account: "成员账号",
+  sub_account: "客户分账号",
+  partner: "合伙人",
+  operator: "运营商",
+  import_batch: "导入批次",
+};
+
+export const ACTION_AUDIT: Record<string, string> = {
+  LOGIN: "登录",
+  LOGOUT: "退出",
+  LOGIN_FAILED: "登录失败",
+  PASSWORD_CHANGE: "修改密码",
+  // 后端写入审计的 `action` 真源(src/modules/*/handlers);未收录的代码原样显示,⛔ 猜标签。
+  "bos.customer.update": "修改客户档案",
+  "bos.customer.attribution_update": "客户改挂区域",
+  "bos.account.provision": "开设成员账号",
+  "bos.account.update_status": "变更账号状态",
+  "bos.account.reset_code": "重置激活码",
+  "bos.sub_account.update": "修改分账号资料",
+  "bos.ent_team.create": "新建运营团队",
+  "bos.ent_team.update": "修改运营团队",
+  "bos.ent_team.delete": "删除运营团队",
+  "bos.ent_team.member_add": "运营团队加成员",
+  "bos.ent_team.member_remove": "运营团队移成员",
+  "bos.ent_team.transfer_primary": "移交团队主账号",
+  "bos.ent_team.scope.manage": "调整团队负责范围",
+};
+
+/** 取标签:命中字典用中文,否则原样;空值由调用方用 `Cell` 兜「—」。 */
+export function label(dict: Record<string, string>, v: string | null | undefined): string {
+  if (!v) return "";
+  return dict[v] ?? v;
+}

+ 131 - 0
front-end/src/api/platform.ts

@@ -0,0 +1,131 @@
+/**
+ * 平台网关调用(总则§16.1:登录页归 SEOH 平台,本系统不自建登录校验)。
+ *
+ * 三步式真实登录:图形验证码 → 凭证校验拿 challenge_token → 密码登录拿 access_token。
+ * 本地 otp-service 开了 OTP_SERVICE_BYPASS_CAPTCHA_VERIFY,故 code 可固定 "0000";
+ * 生产环境必须把图片渲染出来让用户输入(见 LoginPage 的验证码图)。
+ */
+
+const GW = "/gateway/api/system";
+
+/** 由 vite.config.ts `define` 注入的项目空间标识(见该文件 seoCtx 注释)。 */
+declare const __SEO_CTX__:
+  | { tenant_id: string; project_id: string; env: string; stage: string }
+  | undefined;
+
+export const SEO_CTX = __SEO_CTX__ ?? { tenant_id: "", project_id: "", env: "nonprod", stage: "dev" };
+
+/**
+ * 登录档位:
+ * · `end_user`=项目空间账号(本系统全部业务角色账号属此档,业主 2026-11-07 裁定,
+ *   见 18 册 §18.3),必须带 `scope_id/project_id/tenant_id/env/stage`;
+ * · `platform`=平台身份服务账号(本机仅 `root`,用于对照),⛔ 带空间字段。
+ * 两步(`challenge/verify` 与 `auth/password`)必须用**同一份**上下文:`challenge_token`
+ * 一次性且与上下文绑定,第二步换上下文即 12006。
+ */
+export type LoginScope = "end_user" | "platform";
+
+export function loginContext(scope: LoginScope): Record<string, string> {
+  return scope === "end_user"
+    ? {
+        scope_type: "end_user",
+        scope_id: SEO_CTX.project_id,
+        project_id: SEO_CTX.project_id,
+        tenant_id: SEO_CTX.tenant_id,
+        env: SEO_CTX.env,
+        stage: SEO_CTX.stage,
+      }
+    : { scope_type: "platform" };
+}
+
+/** 空间标识缺失时给用户的显式原因(⛔ 让请求带着空 scope_id 发出去)。 */
+export function ctxMissing(scope: LoginScope): boolean {
+  return scope === "end_user" && (!SEO_CTX.project_id || !SEO_CTX.tenant_id);
+}
+
+export class GatewayError extends Error {
+  constructor(
+    public code: number | null,
+    message: string,
+    public status?: number,
+  ) {
+    super(message);
+  }
+}
+
+async function post<T>(path: string, data: unknown, headers?: Record<string, string>): Promise<T> {
+  const r = await fetch(`${GW}${path}`, {
+    method: "POST",
+    headers: { "Content-Type": "application/json", ...headers },
+    body: JSON.stringify({ data }),
+  });
+  const body = await r.json().catch(() => ({}));
+  const code = (body as { code?: number }).code ?? null;
+  if (!r.ok || (code !== null && code !== 10000)) {
+    throw new GatewayError(code, (body as { message?: string }).message ?? `HTTP ${r.status}`, r.status);
+  }
+  return (body as { data: T }).data;
+}
+
+export type Captcha = { captcha_id: string; image_base64?: string; image?: string };
+
+export async function createCaptcha(scene = "playground"): Promise<Captcha> {
+  return post<Captcha>("/seoh-identity-provider/otp/captcha/create@v1", {
+    channel: "captcha",
+    scene,
+  });
+}
+
+export async function verifyChallenge(input: {
+  username: string;
+  captchaId: string;
+  code: string;
+  scene?: string;
+  scope: LoginScope;
+}): Promise<string> {
+  const d = await post<{ challenge_token?: string }>("/seoh-identity-provider/auth/challenge/verify@v1", {
+    username: input.username,
+    channel: "captcha",
+    code: input.code,
+    captcha_id: input.captchaId,
+    scene: input.scene ?? "playground",
+    ...loginContext(input.scope),
+  });
+  if (!d?.challenge_token) throw new GatewayError(null, "凭证校验未返回 challenge_token");
+  return d.challenge_token;
+}
+
+export type LoginResult = {
+  access_token: string;
+  user_id?: string;
+  identity_id?: string;
+  user_type?: string;
+  scope_type?: string;
+  scope_id?: string;
+  expires_in?: number;
+};
+
+export async function loginWithPassword(input: {
+  username: string;
+  password: string;
+  challengeToken: string;
+  scope: LoginScope;
+}): Promise<LoginResult> {
+  return post<LoginResult>(
+    "/seoh-identity-provider/auth/password@v1",
+    { username: input.username, password: input.password, ...loginContext(input.scope) },
+    { "X-Login-Challenge-Token": input.challengeToken },
+  );
+}
+
+export async function logout(accessToken: string): Promise<void> {
+  try {
+    await fetch(`${GW}/seoh-identity-provider/auth/logout@v1`, {
+      method: "POST",
+      headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` },
+      body: JSON.stringify({ data: {} }),
+    });
+  } catch {
+    /* 会话已由前端销毁,登出失败不阻塞 */
+  }
+}

+ 1615 - 0
front-end/src/api/types.ts

@@ -0,0 +1,1615 @@
+/**
+ * klt-bos 前端类型层(应答载荷契约)。
+ *
+ * 权威依据(优先级从高到低):
+ *   1. `src/modules/account/src/handlers/*.rs` 中 `json_ok(...)` 真实写出的 JSON —— 已实现的按此建模;
+ *   2. `src/bin/klt-bos/openapi.yaml` 的 summary/description + `docs/` 设计 +
+ *      `src/migrations/dev/20261104000001_bos_core_tables.sql` 的 27 张表真实列名 —— 占位接口按此定契约。
+ *
+ * 每个应答类型带标记:
+ *   [实] 后端已真实下发,**形状照 handler 逐字建模**(可能较贫瘠,前端页面先照它渲染);
+ *   [半] 部分实现:形状照 handler,但含占位 null / 恒空数组;
+ *   [位] ⚠️ 后端待实现,契约以此为准 —— 注释里给出当前 handler 实际返回,供后端对齐。
+ *
+ * 字段名一律 snake_case;金额列以 `_cents` 结尾存分。
+ * 说明:[位] 类型里的字段类型为**目标可表达类型**(如现在恒为 null 的 id 写成 `string`),
+ *       前端按契约编码,后端接线即可对接。
+ */
+
+/* ══ 会话与权限 ═══════════════════════════════════════════════════ */
+
+export type RoleCode =
+  | "admin"
+  | "opsMain"
+  | "opsSub"
+  | "teamLead"
+  | "ops"
+  | "enterprise"
+  | "sub"
+  | "partner"
+  | "operator";
+
+/** 主体类型(spec subject_type;SQL 注释含 hq/region/ops_team/ent_team/customer/sub_account/partner/operator) */
+export type SubjectType =
+  | "hq"
+  | "region"
+  | "ops_team"
+  | "ent_team"
+  | "customer"
+  | "sub_account"
+  | "partner"
+  | "operator";
+
+/** ⚠️ 后端待实现,契约以此为准:auth/context 目前只下发 `scope_mode: string | null`,未下发本结构。 */
+export type ScopeView = {
+  kind: "all" | "regions" | "teams" | "customers" | "self";
+  region_node_ids: string[];
+  customer_ids: string[];
+  team_ids: string[];
+};
+
+/**
+ * GET /auth/context@v1 —— [半] handler `auth_ctx.rs::context()` 已下发:
+ * `{ user_id, role_code, subject_type, subject_id, entry_only, scope_mode, username }`
+ * (scope_mode 派生:all=admin / regions=opsMain,opsSub / teams=ops / customers=teamLead / self=enterprise,sub / null)。
+ * ⚠️ 后端待实现,契约以此为准:下列 `display_name / subject_name / scope / acct_status / must_change_password /
+ * permissions` 六项 handler **尚未下发**,但 `auth/session.tsx` 与全局 UI 强依赖,后端须补齐。
+ * 未激活、已过期须在此拦截。
+ */
+export type AuthContext = {
+  user_id: string;
+  username: string;
+  role_code: RoleCode;
+  subject_type: SubjectType;
+  subject_id: string | null;
+  /** [实] 平台对账等仅入口账号标记 */
+  entry_only: boolean;
+  /** [实] 可见形态:all/regions/teams/customers/self(与 scope.kind 同源,后端应收敛为 scope) */
+  scope_mode: string | null;
+  display_name: string;
+  /** 主体名称:区域名 / 团队名 / 客户名 / 合伙人名 / 运营商名 */
+  subject_name: string | null;
+  scope: ScopeView;
+  /** 账号状态:normal 正常 / unactivated 未激活 / expired 已过期 / disabled 已停用 */
+  acct_status: "normal" | "unactivated" | "expired" | "disabled";
+  must_change_password: boolean;
+  permissions: string[];
+};
+
+/** GET /health、GET /health@v1 —— [实] handler 返回 `{ status: "ok" }`。 */
+export type HealthInfo = { status: string };
+
+/** GET /ping@v1 —— [实] handler 返回 `{ status, service, user_id, role_code }`。 */
+export type PingInfo = {
+  status: string;
+  service: string;
+  user_id: string;
+  role_code: RoleCode | null;
+};
+
+/**
+ * POST /activation/verify@v1 —— ⚠️ 后端待实现,契约以此为准。
+ * 当前 handler 返回 `{ user_id: null, password_set: true }`(激活码校验未接)。
+ */
+export type ActivationVerifyResult = {
+  user_id: string;
+  password_set: boolean;
+  must_change_password?: boolean;
+};
+
+/* ══ 区域管理 ═════════════════════════════════════════════════════ */
+
+/** POST /region/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ node_id: null, req }`。 */
+export type RegionCreateResult = {
+  node_id: string;
+  node_name?: string;
+  level?: string;
+  level_label?: string;
+};
+
+/** POST /region/rename@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ req }`(仅回显请求体)。 */
+export type RegionRenameResult = { node_id: string; node_name: string };
+
+/** POST /region/delete@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ deleted: false, blocked: [], req }`。 */
+export type RegionDeleteResult = {
+  node_id: string;
+  deleted: boolean;
+  /** 阻塞项枚举:has_children / has_children_customers / has_operator_profiles */
+  blocked: string[];
+};
+
+/**
+ * 区域树节点 [实] —— 结构与承载量三处真源,各自口径⛔ 混为一谈:
+ * * `parent_id`=`dim_node_ancestor` 中 `depth=1` 的祖先(资源树几何的本地只读投影;⛔ 真源,
+ *   取不到=本次可见集合内的根节点);
+ * * `level`/`path_name`=`bos_region_meta`(层级唯一落地位,总则§5.3);
+ * * `counters`=本域各主体表按 `region_node_id` 计数 + `customer_region_mount` 挂载计数。
+ *
+ * ⚠️ `path_name` 当前只到**节点 ID 链**(如 `shp/sh/lg`):平台 RM ⛔ 向 BOS 暴露节点中文名
+ * 读接口(`name_ready: false` 是该边界的机器可读标记),故展示名旁须保留口径说明,
+ * ⛔ 前端造中文名填空。
+ */
+export type RegionNode = {
+  node_id: string;
+  parent_id: string | null;
+  /** 展示名(=path_name,现为节点 ID 链;未建档=null) */
+  name: string | null;
+  path_name: string | null;
+  /** dev 值域:省/市/区县 */
+  level: string | null;
+  level_label: string | null;
+  counters: {
+    operators: number;
+    partners: number;
+    ops_teams: number;
+    /** 直接挂载在本节点的客户数 */
+    customers: number;
+    /** 含下级:本节点子树内的去重客户数 */
+    customers_in_subtree: number;
+    children: number;
+  };
+};
+
+/** POST /region/tree@v1 —— [实] `node_ids` 保留兼容,树形请用 `nodes`(+`parent_id`)。⚠️ 2026-11-08 由 GET 改 POST(R-5)。 */
+export type RegionTreeResult = {
+  node_ids: string[];
+  nodes: RegionNode[];
+  root: string | null;
+  /** false=展示名只到节点 ID 链(平台 RM ⛔ 节点名读接口,18 册在册) */
+  name_ready: boolean;
+  name_source: string;
+  note: string;
+};
+
+/** POST /region/subtree@v1 —— [实] 同 `tree`,`root` 回显收窄依据;不可见 node_id ⇒ 空集合+note。 */
+export type RegionSubtreeResult = RegionTreeResult;
+
+/** GET /region/change_log@v1 应答行 —— 形状取自 2026-11-08 实测报文(`bos_audit_log` 审计行)。 */
+export type RegionChangeLogRow = {
+  action: string;
+  object: { type?: string | null; id?: string | null } | null;
+  before: string | null;
+  after: string | null;
+  actor: { user_id?: string | null; username?: string | null } | null;
+  detail: {
+    object?: string | null;
+    before?: string | null;
+    after?: string | null;
+    actor_name?: string | null;
+  } | null;
+  occurred_at: string | null;
+};
+
+/** GET /region/change_log@v1 —— `message` 说明行集口径(含开发种子、dev 库 occurred_at 可能为 null)。 */
+export type RegionChangeLogResult = {
+  items: RegionChangeLogRow[];
+  total: number;
+  audit_write_ready?: boolean;
+  truncated?: boolean;
+  window_size?: number;
+  message?: string;
+};
+
+/**
+ * POST /region/orphans@v1 应答行 —— 实为「未清理完成的挂载请求候选」,非节点表行。⚠️ 2026-11-08 由 GET 改 POST(R-5)。
+ * 悬空判定须回查平台终态(总则§7.3),后端⛔ 回查,故只作候选(`dangling_count`=本地无客户行的条数)。
+ */
+export type RegionOrphanRow = {
+  mount_request_id: string;
+  customer_id: string;
+  hierarchy_id: string;
+  parent_node_id: string | null;
+  terminal_state: string;
+  local_customer_exists: boolean;
+  created_at: string | null;
+  cleaned_at: string | null;
+};
+
+/** POST /region/orphans@v1 */
+export type RegionOrphanResult = {
+  items: RegionOrphanRow[];
+  total: number;
+  dangling_count: number;
+  window_size?: number;
+  platform_state_verified?: boolean;
+  message?: string;
+};
+
+/* ══ 账号管理 ═════════════════════════════════════════════════════ */
+
+export type AccountBrief = {
+  user_id: string;
+  username: string;
+  mobile: string | null;
+  role_code: RoleCode | null;
+  status: "normal" | "unactivated" | "expired" | "disabled";
+  entry_only: boolean;
+  is_primary: boolean;
+  claim_code: string | null;
+  expire_date: string | null;
+};
+
+/**
+ * POST /account/provision@v1 —— ⚠️ 后端待实现,契约以此为准。
+ * 当前 handler 返回 `{ user_id: null, status: "pending", req }`(平台开通未接)。
+ */
+export type AccountProvisionResult = {
+  user_id: string;
+  status: string;
+  /** 激活码仅开通当次返回 */
+  activation_code?: string | null;
+  expire_date?: string | null;
+};
+
+/** POST /account/update_status@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ req }`。 */
+export type AccountStatusResult = { user_id: string; status: string };
+
+/** POST /account/reset_code@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ req }`。 */
+export type AccountResetCodeResult = {
+  user_id: string;
+  activation_code: string;
+  expire_date: string;
+};
+
+/** 导出类应答 —— ⚠️ 后端待实现,契约以此为准。当前 export_codes 类 handler 统一返回 `{ async: false, req }`。 */
+export type ExportResult = {
+  file_name: string;
+  download_url?: string;
+  content_base64?: string;
+  rows?: Record<string, unknown>[];
+};
+
+/** POST /account/change_password@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ req }`。 */
+export type AccountChangePasswordResult = { changed: boolean };
+
+/* ══ 运营商 ═══════════════════════════════════════════════════════ */
+
+/**
+ * 主体名下账号(列表页内联下发,`bos_user_binding` ⋈ `bos_account_ext`)[实]。
+ *
+ * ⚠️ 同主体绑定多账号时取 `user_id` 最小的一行作代表,`account_count` 给出总数;
+ * ⚠️ `mobile` 已按需求§5.4 掩码,⛔ 再用于拨打/复制。
+ */
+export type SubjectAccount = {
+  user_id: string;
+  username: string;
+  mobile: string | null;
+  status: string;
+  account_count: number;
+};
+
+/**
+ * POST /operator/get_list@v1 应答行 [实] —— 需求§3「运营商管理」逐字列
+ * (名称/品牌/所属区域/对账日/付款周期/分成方式+取值)+名下客户数。
+ * ⚠️ 区域名称⛔ 在本表内(dev 库无 region_node),只下发 `region_node_id`;
+ * ⚠️ 计数与金额由 UDS 以**字符串**下发,前端⛔ 假定 number(否则整表 render 失败)。
+ */
+export type OperatorRow = {
+  operator_id: string;
+  name: string;
+  brand: string | null;
+  region_node_id: string;
+  /** [实] `bos_region_meta.path_name`(现为节点 ID 链;未建档=null) */
+  region_path_name: string | null;
+  /** [实] `bos_region_meta.level`,dev 值域:省/市/区县 */
+  region_level: string | null;
+  /** [实] 名下对账账号;null=未开通(⛔ 用「—」冒充已开通) */
+  account: SubjectAccount | null;
+  recon_day: string;
+  pay_cycle: string;
+  settle_mode: string;
+  settle_value: string | null;
+  customer_count: number;
+};
+
+/** POST /operator/create@v1 —— [实] 真落库;必填缺失回 `20004 KLT-S20004`(⛔ 回显请求体冒充成功)。 */
+export type OperatorCreateResult = {
+  operator_id: string;
+  name: string;
+  brand: string;
+  region_node_id: string;
+};
+
+/** POST /operator/update@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ updated: true, req }`。 */
+export type OperatorUpdateResult = { operator_id: string; updated: boolean };
+
+/** POST /operator/delete@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ deleted: false, blocked: [], req }`。 */
+export type OperatorDeleteResult = {
+  operator_id: string;
+  deleted: boolean;
+  /** 删除前六项检查未通过项 */
+  blocked: string[];
+  /** 级联注销的对账账号 */
+  revoked_user_ids?: string[];
+};
+
+/** POST /operator/get_list@v1 [实] —— 公共分页形制 `{items,total,page,page_size}`(page 0 基)。 */
+export type OperatorListResult = {
+  items: OperatorRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+};
+
+/**
+ * POST /operator/recon_account/create@v1 —— [半] handler 返回
+ * `{ user_id: null, status_hint: "pending: 未发送,线下告知本人", req }`。
+ * ⚠️ 后端待实现,契约以此为准。
+ */
+export type ReconAccountCreateResult = {
+  operator_id: string;
+  user_id: string;
+  username: string;
+  mobile: string | null;
+  status: string;
+  /** 状态提示,如「未发送,线下告知本人」 */
+  status_hint: string | null;
+  /** 仅创建当次返回,查询接口不下发 */
+  initial_password?: string | null;
+};
+
+/** POST /operator/recon_account/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ found: false, req }`。 */
+export type ReconAccountGetResult = {
+  found: boolean;
+  operator_id: string;
+  user_id: string | null;
+  username: string | null;
+  mobile: string | null;
+  status: string | null;
+  status_hint: string | null;
+};
+
+export type ReconAccount = {
+  operator_id: string;
+  user_id: string;
+  username: string;
+  mobile: string | null;
+  status: string;
+  status_hint: string | null;
+};
+
+/* ══ 写侧通用回执形制([实] 五域真落库后的共同口径)═══════════════ */
+
+/** 阻塞项 [实] —— delete/member_remove 的 `blockers[]`;`count: null`=⛔ 可判定(⛔ 折算成 0 当作放行)。 */
+export type BlockerItem = {
+  key: string;
+  count: number | null;
+  message: string;
+  /** 设计口径编号(部分域下发) */
+  design_code?: string;
+};
+
+/** ⛔ 可判定项 [实] —— `unverifiable_checks[]`,命中即整单拒绝(⛔ 当作通过)。 */
+export type UnverifiableCheck = { key: string; reason: string };
+
+/**
+ * opsMain 区域上界核对 [实] —— 有网关注入的区域授权实例=`{applied:true, evidence}`;
+ * 无=`{applied:false, reason}`(⛔ 当作通过,登 18 册待平台补注入)。
+ */
+export type ScopeCheck = { applied: boolean; evidence?: string; reason?: string };
+
+/** 审计/时间在册缺口 [实] —— 写侧出参统一摊平:`audit_written` 恒 false(审计中间件→uds.dml 真写通路未通)。 */
+export type AuditOut = {
+  audit_written: boolean;
+  audit_note: string;
+  time_note?: string;
+  audit_key?: string;
+};
+
+/** 平台建号回执 [实] —— `initial_password` 仅本次回显(⛔ 二次可查);⛔ 建号分支只有 `created`+`reason`。 */
+export type AccountOut = {
+  created: boolean;
+  reason?: string;
+  user_id?: string;
+  username?: string | null;
+  role_code?: string | null;
+  /** 业务角色只落本地 `bos_user_binding.role_code`,平台侧⛔ 角色授予入参 */
+  platform_role_note?: string;
+  must_change_password?: boolean;
+  initial_password?: string | null;
+  credential_note?: string;
+  credential_viewable?: boolean;
+};
+
+/* ══ 合伙人 ═══════════════════════════════════════════════════════ */
+
+/**
+ * POST /partner/get_list@v1 应答行 [实] —— 需求§3「合伙人管理」逐字列+名下客户数。
+ * ⚠️ `mobile` 已由后端按需求§5.4 掩码(列表页⛔ 明文手机号),前端⛔ 再脱敏也⛔ 当明文用于拨打。
+ */
+export type PartnerRow = {
+  partner_id: string;
+  name: string;
+  duty_desc: string | null;
+  region_node_id: string;
+  /** [实] `bos_region_meta.path_name`(节点 ID 链;未建档=null) */
+  region_path_name: string | null;
+  /** [实] `bos_region_meta.level`(合伙人限省级) */
+  region_level: string | null;
+  mobile: string | null;
+  status: string;
+  settle_mode: string | null;
+  settle_value: string | null;
+  customer_count: number;
+  created_at: string | null;
+  /** [实] 名下合伙人账号;null=未开通 */
+  account: SubjectAccount | null;
+  /**
+   * [实] 「配置范围」弹窗回显 —— 随列表一并下发,⛔ 另开「按 id 查他人范围」的接口
+   * (`partner/scope/get@v1` 设计上只允许本人查自己,admin 越权读他人范围在本域被禁止)。
+   */
+  scope: {
+    regions: string[];
+    customers: string[];
+    /** 范围(含下级)内去重在册客户数;null=范围未配置(⛔ 折算 0) */
+    coverage_customers: number | null;
+  };
+};
+
+/**
+ * POST /partner/create@v1 —— [实] `partner.rs::do_create()` 建档+建 `partner` 账号,
+ * 出参全部为**落库后回读真值**(⛔ 回显请求体;查不到即显式失败)。
+ */
+export type PartnerCreateResult = {
+  partner_id: string;
+  name: string;
+  duty_desc: string | null;
+  region_node_id: string;
+  /** [实] `bos_region_meta` 回读(合伙人限省级) */
+  region_level: string;
+  region_path_name: string;
+  ops_main_scope_check: ScopeCheck;
+  /** [实] 已按需求§5.4 掩码 */
+  mobile: string | null;
+  status: string;
+  settle_mode: string | null;
+  /** ⚠️ dev UDS 对 numeric 写入有静默落 NULL 缺陷 ⇒ 与 `settle_requested` 不一致即未落库 */
+  settle_value: string | null;
+  settle_value_note: string;
+  /** 本次请求的分成入参(原样回显,供与 `settle_value` 比对) */
+  settle_requested: { settle_mode: string | null; settle_value: string | number | null };
+  account: AccountOut;
+} & AuditOut;
+
+/** POST /partner/update@v1 —— [实] 整档整体保存后回读;`duty_desc`/`mobile` 空值⇒落 NULL。 */
+export type PartnerUpdateResult = {
+  partner_id: string;
+  name: string;
+  duty_desc: string | null;
+  region_node_id: string;
+  region_level: string;
+  region_path_name: string;
+  ops_main_scope_check: ScopeCheck;
+  mobile: string | null;
+  status: string;
+  settle_mode: string | null;
+  settle_value: string | null;
+  settle_requested: { settle_mode: string | null; settle_value: string | number | null };
+  /** ⛔ 随本接口同步平台账号,此处=本地绑定行真值 */
+  username: string | null;
+  form_semantics: string;
+  platform_sync_note: string;
+  row_version_note: string;
+} & AuditOut;
+
+/** POST /partner/delete@v1 —— [实] 恒 `deleted: false` + blockers/⛔ 可判定项(本接口⛔ 执行删除)。 */
+export type PartnerDeleteResult = {
+  partner_id: string;
+  name: string;
+  deleted: false;
+  blockers: BlockerItem[];
+  unverifiable_checks: UnverifiableCheck[];
+  note: string;
+};
+
+/** POST /partner/get_list@v1 [实] —— 公共分页形制;`mobile` 已按需求§5.4 掩码。 */
+export type PartnerListResult = {
+  items: PartnerRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+};
+
+/**
+ * POST /partner/scope/get@v1 [实] —— 读 `bos_data_scope`;持有者由 `auth.subject` 推导
+ * (⚠️ 2026-11-08 由 GET 改 POST,R-5),非合伙人主体调用回 `20004 KLT-S20004`——本接口只查**当前登录主体自己**的负责范围。
+ */
+export type PartnerScope = {
+  grants: ScopeGrant[];
+  total: number;
+};
+
+/** bos_data_scope 行(holder×target 模型;partner / ops_team / ops_member 共用)。 */
+/** `bos_data_scope` 一行(holder×target 模型;partner/ent_team 共用)。后端只下发 target 两列。 */
+export type ScopeGrant = {
+  target_type: "region" | "customer" | string;
+  target_id: string;
+  grant_id?: string | null;
+  holder_type?: string;
+  holder_id?: string;
+  updated_at?: string | null;
+};
+
+/**
+ * POST /partner/scope/save@v1 —— [实] 授权行整体替换后**回读**(⛔ `saved` 布尔);
+ * 与请求完全一致时走 `noop: true` 分支(⛔ 下发 `consistent`/`diff_with_requested`)。
+ */
+export type PartnerScopeSaveResult = {
+  partner_id: string;
+  grants: ScopeGrant[];
+  region_count: number;
+  customer_count: number;
+  total: number;
+  inserted: number;
+  deleted: number;
+  unchanged: number;
+  /** [实] 仅「本次无需改动」分支下发 */
+  noop?: boolean;
+  /** [实] 回读与请求是否一致(⛔ 假定 true);noop 分支⛔ 下发 */
+  consistent?: boolean;
+  diff_with_requested?: { expected: string[]; actual: string[] } | null;
+  scope_note: string;
+} & AuditOut;
+
+/* ══ 运营团队 ═════════════════════════════════════════════════════ */
+
+/**
+ * POST /ent_team/get_list@v1 应答行 [实] —— 一条团队带负责人登录名与成员数。
+ * ⚠️ 成员**明细**⛔ 只读接口(`/ent_team/*` ⛔ 声明成员清单路由),故列表只到成员数。
+ */
+export type EntTeamRow = {
+  team_id: string;
+  team_name: string;
+  /**
+   * [实] 备注=`ent_team.remark VARCHAR(200) NULL`(2026-11-08 业主定案补列,总则§18.3 `PG-7`)。
+   * ⛔ 参与唯一键、⛔ 参与算账与判权;未配置=null(⛔ 折算成空串冒充"已配置且无内容")。
+   */
+  remark: string | null;
+  is_builtin: boolean;
+  owner_username: string | null;
+  member_count: number;
+  /**
+   * [实] 「所属区域」列=`bos_data_scope` 里的授权节点(`ent_team` ⛔ region 列,区域归属
+   * 按第 1 册§2 只落 scope 表)。空数组:内置团队=「不限」,非内置=「未配置」,
+   * ⛔ 显示成某个真实区域。
+   */
+  scope_regions: string[];
+  /** [实] 范围内直接多选的客户 */
+  scope_customers: string[];
+  /** [实] 覆盖客户数;内置空范围=全量在册;非内置空范围=null(未配置,⛔ 折算 0) */
+  coverage_customers: number | null;
+  created_at: string | null;
+};
+
+/** 成员行 [实] —— `ent_team.rs::member_views()`(`mobile` 已掩码;账号状态⛔ 在此下发)。 */
+export type EntTeamMember = {
+  user_id: string;
+  username: string | null;
+  mobile: string | null;
+  role_code: string | null;
+  is_primary: boolean;
+};
+
+/** POST /ent_team/create@v1 —— [实] 建团(可选建主账号)后回读整团真值。 */
+export type EntTeamCreateResult = {
+  team_id: string;
+  team_name: string;
+  /** [实] 备注回读(未带=null) */
+  remark: string | null;
+  is_builtin: boolean;
+  owner_user_id: string | null;
+  member_count: number;
+  members: EntTeamMember[];
+  /** [实] ⛔ 带 `primary_username` ⇒ `{created:false, reason}`(⛔ 建号=⛔ 成员,故恒带) */
+  account: AccountOut;
+  scope_note: string;
+  builtin_note: string;
+} & AuditOut;
+
+/** POST /ent_team/update@v1 —— [实] 仅改名(团队名可改,区域⛔ 本接口口径),回读真值。 */
+export type EntTeamUpdateResult = {
+  team_id: string;
+  team_name: string;
+  /** [实] 备注回读(写后真值) */
+  remark: string | null;
+  /** [实] 本次是否改了备注(`true`=请求带 `remark` 键,含清空) */
+  remark_touched: boolean;
+  is_builtin: boolean;
+  owner_user_id: string | null;
+  members: EntTeamMember[];
+  /** [实] 内置团队改名说明(非内置=null) */
+  builtin_renamed_note: string | null;
+  platform_sync_note: string;
+  /** 未传 `row_version` ⇒ `未传 row_version`(dev `ent_team` ⛔ 版本列 ⇒ 乐观锁未启用) */
+  row_version_note: string;
+} & AuditOut;
+
+/** POST /ent_team/delete@v1 —— [实] 恒 `deleted: false` + blockers/⛔ 可判定项(本接口⛔ 执行任何写库)。 */
+export type EntTeamDeleteResult = {
+  team_id: string;
+  team_name: string;
+  deleted: false;
+  blockers: BlockerItem[];
+  unverifiable_checks: UnverifiableCheck[];
+  audit_key?: string;
+  note: string;
+};
+
+/** POST /ent_team/member_add@v1 —— [实] 入团(可建号);⛔ `member_id`(`ent_team_member` 以 user_id 为键)。 */
+export type EntTeamMemberAddResult = {
+  team_id: string;
+  team_name: string;
+  added: true;
+  user_id: string;
+  /** `opsMain`(主账号)/`opsSub`(子账号) */
+  role_code: string;
+  is_primary: boolean;
+  /** [实] 团队原⛔ 成员且⛔ 指定 ⇒ 自动置主账号 */
+  primary_forced: boolean;
+  primary_forced_note: string;
+  account: AccountOut;
+  members: EntTeamMember[];
+  member_count: number;
+  /** 同 user_id 已在团 ⇒ 显式报错(本字段为「⛔ 重复」说明) */
+  duplicate_member_note: string;
+  scope_note: string;
+} & AuditOut;
+
+/** POST /ent_team/member_remove@v1 —— [实] 恒 `removed: false`(注销义务⛔ 履行,逐条 blockers 消解后重试)。 */
+export type EntTeamMemberRemoveResult = {
+  team_id: string;
+  team_name: string;
+  user_id: string;
+  username: string | null;
+  role_code: string | null;
+  is_primary: boolean;
+  team_primary_user_id: string | null;
+  member_count: number;
+  removed: false;
+  blockers: BlockerItem[];
+  members: EntTeamMember[];
+  note: string;
+} & AuditOut;
+
+/** POST /ent_team/transfer_primary@v1 —— [实] 转连 `role_code` 一起换(OR-11),逐语句留痕+回读成员清单。 */
+export type EntTeamTransferPrimaryResult = {
+  team_id: string;
+  team_name: string;
+  transferred: true;
+  from_user_id: string;
+  from_username: string | null;
+  to_user_id: string;
+  to_username: string | null;
+  owner_user_id: string;
+  /** [实] 逐语句标签,顺序=执行顺序 */
+  statement_order: string[];
+  role_switch_note: string;
+  unchanged_note: string;
+  members: EntTeamMember[];
+  audit_before_after: {
+    before: { primary_user_id: string | null; owner_user_id: string | null };
+    after: { primary_user_id: string | null; owner_user_id: string | null };
+  };
+} & AuditOut;
+
+/** POST /ent_team/scope/get@v1 [实] —— 读 `bos_data_scope`,持有者由 `auth.subject` 推导。⚠️ 2026-11-08 由 GET 改 POST(R-5)。 */
+export type EntTeamScope = {
+  grants: ScopeGrant[];
+  total: number;
+};
+
+/** POST /ent_team/scope/save@v1 —— [实] 授权行整体替换后回读;⛔ 改动走 `noop: true`(⛔ `team_name`/`consistent`)。 */
+export type EntTeamScopeSaveResult = {
+  team_id: string;
+  /** [实] 仅「确有改动」分支下发 */
+  team_name?: string;
+  /** [实] 回读 `bos_data_scope` 的 target_id 集 */
+  region_node_ids: string[];
+  total: number;
+  inserted: number;
+  deleted: number;
+  unchanged: number;
+  /** 授权清零(全部子账号失去可见性)说明 */
+  empty_allowed: boolean;
+  noop?: boolean;
+  consistent?: boolean;
+  diff_with_requested?: { expected: string[]; actual: string[] } | null;
+  shrink_note: string;
+} & AuditOut;
+
+/* ══ 运维团队与成员 ═══════════════════════════════════════════════ */
+
+/**
+ * POST /ops_team/get_list@v1 应答行 [实] —— 需求§3 逐字:每团队带**可分配工单类型**
+ * 与两列负载(未完成工单/超期未完成)。
+ * ⚠️ 负载两列⛔ 数源(工单表属第 2 册,dev 库 27 张表未含)⇒ 后端回 `null` +顶层
+ * `load_pending` 说明;前端须渲染「无数源」,⛔ 用 0 冒充「没有未完成工单」(已登总则§18.3)。
+ */
+export type OpsTeamRow = {
+  team_id: string;
+  team_name: string;
+  region_node_id: string;
+  /** [实] `bos_region_meta.path_name`(节点 ID 链;未建档=null) */
+  region_path_name: string | null;
+  /** [实] `bos_region_meta.level`(运维团队⛔ 限省级,可下沉市/区县) */
+  region_level: string | null;
+  dispatch_mode: string;
+  settle_mode: string | null;
+  settle_value: string | null;
+  primary_username: string | null;
+  member_count: number;
+  ticket_types: string[];
+  /** [实] 「负责范围」列:授权区域节点+直接多选客户 */
+  scope_regions: string[];
+  scope_customers: string[];
+  /** [实] 「覆盖客户」列:范围(含下级)内去重在册客户数;未配置=null */
+  coverage_customers: number | null;
+  open_tickets: number | null;
+  overdue_open_tickets: number | null;
+};
+
+/** POST /ops_team/get_list@v1 [实]。 */
+export type OpsTeamListResult = {
+  items: OpsTeamRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+  /** 后端在有条目时下发:负载列降级说明 */
+  load_pending?: string;
+};
+
+export type OpsMemberRow = {
+  member_id: string;
+  team_id?: string;
+  user_id: string;
+  username: string;
+  mobile: string | null;
+  ticket_types: string[];
+  scope_mode: string;
+  is_primary: boolean;
+  status: "normal" | "unactivated" | "expired" | "disabled";
+  activation_code?: string | null;
+  expire_date?: string | null;
+};
+
+/**
+ * POST /ops_team/create@v1 —— [实] `ops_team.rs::do_create()` 建档+建团队负责人账号,
+ * 出参全部为**落库后回读真值**(⛔ 回显请求体)。
+ */
+export type OpsTeamCreateResult = {
+  team_id: string;
+  team_name: string;
+  region_node_id: string;
+  /** [实] `bos_region_meta.level`(运维团队⛔ 限省级,可下沉市/区县) */
+  region_level: string;
+  region_path_name: string;
+  dispatch_mode: string;
+  settle_mode: string | null;
+  settle_value: string | null;
+  /** [实] 回读 `ops_team_ticket_type` */
+  ticket_types: string[];
+  /** 本次请求提交的类型(与 `ticket_types` 不一致即未落库) */
+  requested_ticket_types: string[];
+  member_count: number;
+  primary_member_id: string;
+  primary_account: AccountOut;
+  ops_main_scope_check: ScopeCheck;
+} & AuditOut;
+
+/** POST /ops_team/update@v1 —— [实] 整体保存后回读;成员级类型裁剪如实降级。 */
+export type OpsTeamUpdateResult = {
+  team_id: string;
+  team_name: string;
+  region_node_id: string;
+  dispatch_mode: string;
+  settle_mode: string | null;
+  settle_value: string | null;
+  ticket_types: string[];
+  /** [实] 本次被收窄掉的团队类型(⛔ 收窄=空数组) */
+  dropped_team_types: string[];
+  /** [实] 成员级类型载体表 `ops_member_ticket_type` ⛔ 建表 ⇒ 有收窄即 `applied: false` */
+  member_type_trim:
+    | { applied: true; trimmed: string[]; note: string }
+    | { applied: false; dropped_team_types: string[]; reason: string };
+  ops_main_scope_check: ScopeCheck;
+} & AuditOut;
+
+/** POST /ops_team/delete@v1 —— [实] 恒 `deleted: false` + blockers/⛔ 可判定项(本接口⛔ 执行删除)。 */
+export type OpsTeamDeleteResult = {
+  team_id: string;
+  team_name: string;
+  deleted: false;
+  blockers: BlockerItem[];
+  unverifiable_checks: UnverifiableCheck[];
+  ops_main_scope_check: ScopeCheck;
+  note: string;
+};
+
+/** POST /ops_team/scope/save@v1 —— [实] 团队区域范围整体替换后回读(⛔ `saved` 布尔)。 */
+export type OpsTeamScopeSaveResult = {
+  team_id: string;
+  region_node_ids: string[];
+  customer_ids: string[];
+  region_count: number;
+  customer_count: number;
+  coverage_before: number;
+  coverage_after: number;
+  coverage_basis_before: string;
+  coverage_basis_after: string;
+  coverage_basis_saved: string;
+  allow_empty: true;
+} & AuditOut;
+
+/**
+ * 成员级「可分配工单类型」结论 [实] —— 载体表 `ops_member_ticket_type` ⛔ 建表,
+ * 组织§5.5「无静默丢弃路径」⇒ 选了类型即显式报错,成功态只可能是「⛔ 类型=不接单」。
+ */
+export type OpsMemberTypeNote = { stored: boolean; ticket_types: string[]; note: string };
+
+/** POST /ops_team/member_add@v1 —— [实] 入团+建 `ops` 账号;成员行回读真值。 */
+export type OpsMemberAddResult = {
+  member_id: string;
+  team_id: string;
+  user_id: string;
+  is_primary: boolean;
+  scope_mode: string;
+  username: string | null;
+  mobile: string | null;
+  member_count: number;
+  ticket_types: OpsMemberTypeNote;
+  /** [实] ⛔ 重复 `user_id`/`username`(在顶层) */
+  account: AccountOut;
+} & AuditOut;
+
+/** POST /ops_team/member_update@v1 —— [实] 改手机号/成员类型;`mobile_updated` 如实反映是否写入。 */
+export type OpsMemberUpdateResult = {
+  member_id: string;
+  team_id: string;
+  user_id: string;
+  is_primary: boolean;
+  scope_mode: string;
+  mobile: string | null;
+  mobile_updated: boolean;
+  ticket_types: OpsMemberTypeNote;
+} & AuditOut;
+
+/** POST /ops_team/member_remove@v1 —— [实] 恒 `removed: false`(注销义务⛔ 履行)。 */
+export type OpsMemberRemoveResult = {
+  member_id: string;
+  team_id: string;
+  user_id: string;
+  removed: false;
+  blockers: BlockerItem[];
+  account_deactivation: { applied: boolean; reason: string };
+  note: string;
+};
+
+/** POST /ops_member/scope/save@v1 —— [实] 成员范围整体替换;`scope_rows`=`target_type/target_id` 串。 */
+export type OpsMemberScopeSaveResult = {
+  member_id: string;
+  team_id: string;
+  scope_mode: string;
+  scope_mode_before: string | null;
+  is_primary: boolean;
+  scope_rows: string[];
+  scope_row_count: number;
+  team_coverage_count: number;
+  team_coverage_basis: string;
+} & AuditOut;
+
+/** POST /ops_team/dispatch_mode/update@v1 —— [实] 模式未变走 noop 分支(该分支⛔ 下发 `audit_*`)。 */
+export type OpsTeamDispatchResult = {
+  team_id: string;
+  dispatch_mode: string;
+  /** [实] 仅「确有变更」分支下发 */
+  dispatch_mode_before?: string;
+  changed: boolean;
+  written: boolean;
+  /** ⚠️ 当前恒空数组(逐成员结果未接线) */
+  dispatched: unknown[];
+  skipped: unknown[];
+  note: string;
+  ops_main_scope_check: ScopeCheck;
+  audit_written?: boolean;
+  audit_note?: string;
+  time_note?: string;
+};
+
+/**
+ * POST /ops_team/coverage/get@v1 应答 [实] —— `customer_team_belong` 当前归属真源;
+ * 团队由 `auth.subject` 推导(⚠️ 2026-11-08 由 GET 改 POST,R-5),非运维团队主体调用显式失败。
+ */
+export type OpsTeamCoverage = {
+  customers: { customer_id: string; customer_name: string; valid_from: string | null }[];
+  total: number;
+};
+
+/* ══ 客户管理 ═════════════════════════════════════════════════════ */
+
+export type CustomerRow = {
+  customer_id: string;
+  customer_name: string;
+  subject_type: string;
+  masked_id_no: string | null;
+  region_node_id: string;
+  region_path: string;
+  operator_id: string | null;
+  operator_name: string | null;
+  partner_id: string | null;
+  partner_name: string | null;
+  ops_team_ids: string[];
+  ops_team_names: string[];
+  acct_status: string;
+  quota_slots: number;
+  sub_count: number;
+  sub_account_count: number;
+  contact_name: string | null;
+  contact_mobile: string | null;
+  address: string | null;
+  created_at: string;
+  updated_at: string;
+  row_version: string;
+};
+
+/** POST /customer/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ customer_id: null, req }`。 */
+export type CustomerCreateResult = {
+  customer_id: string;
+  user_id?: string | null;
+  activation_code?: string | null;
+};
+
+/**
+ * POST /customer/get_list@v1 应答行 —— [实] handler 只下发 `{ customer_id }`,
+ * 值来自真实权限查询:`bos_data_scope` 按 (partner|ops_team|ops_member) ∩ `bos_customer_region` 收窄,
+ * admin/teamLead/enterprise/sub 走 `visible_customer_ids`(当前返回空集)。
+ * ⚠️ 后端待补全:items 应升级为 CustomerRow 全列,并补 page/page_size。
+ */
+export type CustomerListRow = {
+  customer_id: string;
+  customer_name: string;
+  subject_type: string;
+  operator_id: string | null;
+  operator_name: string | null;
+  partner_id: string | null;
+  partner_name: string | null;
+  acct_status: string;
+  quota_cents: string;
+  team_ids: string[];
+  sub_account_count: number;
+  created_at: string | null;
+};
+
+/** POST /customer/get_list@v1 —— [实] `{ items: [{customer_id}], total }`(total 为真实条数)。 */
+export type CustomerListResult = {
+  items: CustomerListRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** POST /customer/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 仅返回 `{ req }`(回显 customer_id)。 */
+export type CustomerDetail = {
+  customer: {
+    customer_id: string;
+    customer_name: string;
+    subject_type: string;
+    operator_id: string | null;
+    operator_name: string | null;
+    partner_id: string | null;
+    partner_name: string | null;
+    acct_status: string;
+    quota_cents: string;
+    created_at: string | null;
+  };
+  team_ids: string[];
+  sub_account_count: number;
+  region_mounts: { parent_node_id: string; hierarchy_id: string; terminal_state: string }[];
+};
+
+/** POST /customer/update@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ updated: true, req }`。 */
+export type CustomerUpdateResult = { customer_id: string; updated: boolean };
+
+/**
+ * POST /customer/delete_precheck@v1 —— ⚠️ 后端待实现,契约以此为准。
+ * 当前 handler 返回 `{ can_delete: false, blocked: [], req }`:阻塞项键名为 **blocked**(后端补齐时沿用),
+ * 另需补 `precheck_version` 供 delete 携带。
+ */
+export type CustomerDeletePrecheck = {
+  can_delete: boolean;
+  blocked: string[];
+  precheck_version: string;
+};
+
+/** POST /customer/delete@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ deleted: false, blocked: [], req }`。 */
+export type CustomerDeleteResult = { customer_id: string; deleted: boolean; blocked: string[] };
+
+/** POST /customer/history@v1 应答行 —— 2026-11-08 实测:一次改动按字段拆成多行,
+ *  字段名是 `field_key/old_value/new_value/operator/changed_at`,⛔ 有
+ *  `log_id/action/changed_fields/actor_name/created_at`(照设想写的旧契约,页面据此取值会整表空白)。 */
+export type CustomerHistoryRow = {
+  field_key: string;
+  old_value: string | null;
+  new_value: string | null;
+  operator: string | null;
+  changed_at: string | null;
+  change_basis: string | null;
+  source: string;
+};
+
+/** POST /customer/history@v1 —— 分页信封(`total` 与 `items.length` 可不等,页面按 total 展示条数)。 */
+export type CustomerHistoryResult = {
+  items: CustomerHistoryRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+  message?: string;
+};
+
+/** POST /customer/mount_candidates@v1 应答行 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。⚠️ 2026-11-08 由 GET 改 POST(R-5)。 */
+export type MountCandidateRow = {
+  customer_id: string;
+  customer_name: string;
+  region_node_id: string;
+  region_path: string;
+  operator_id: string | null;
+};
+
+/** POST /customer/mount_candidates@v1 —— ⚠️ 后端待实现,契约以此为准(当前 `{ items: [] }`,无 total)。⚠️ 2026-11-08 由 GET 改 POST(R-5)。 */
+export type MountCandidatesResult = { items: MountCandidateRow[]; total?: number };
+
+/** POST /customer/influence@v1 —— 2026-11-08 实测报文(旧设想契约
+ *  (`open_ticket_count/responsible_team_names/current_period_billed` 等)在本机应答里不存在,
+ *  照旧取值会在「计算影响面」后读到 `undefined.length` 直接把整页 React 树打空)。 */
+export type InfluenceItem = { key: string; label: string; count: number; note: string | null };
+export type InfluenceUnverifiable = { key: string; label: string; why: string };
+export type CustomerInfluence = {
+  customer_id: string;
+  attribution: {
+    operator_id: string | null;
+    operator_name: string | null;
+    partner_id: string | null;
+    partner_name: string | null;
+    acct_status: string | null;
+  } | null;
+  current_teams: { team_id: string; team_name: string | null }[];
+  influence_items: InfluenceItem[];
+  unverifiable_checks: InfluenceUnverifiable[];
+  billing: {
+    period_queried: string | null;
+    latest_period: string | null;
+    snapshots_this_period: number | null;
+    snapshots_total: number | null;
+    note: string | null;
+  } | null;
+  /** 传了 target_operator_id 时后端才回;本机未传 ⇒ 恒为 null,形状未取证,原样透出。 */
+  target_operator_check?: unknown;
+  message: string | null;
+};
+
+/** POST /customer/move_region@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ moved: false, blocked: [], req }`。 */
+export type CustomerMoveRegionResult = {
+  customer_id: string;
+  moved: boolean;
+  blocked: string[];
+  new_region_node_id?: string;
+};
+
+/** POST /customer/attribution/update@v1 —— ⚠️ 后端待实现,契约以此为准。当前返回 `{ updated: false, blocked: [], req }`。 */
+export type CustomerAttributionResult = {
+  customer_id: string;
+  updated: boolean;
+  blocked: string[];
+  operator_id?: string | null;
+  partner_id?: string | null;
+};
+
+/* ══ 批量导入 ═════════════════════════════════════════════════════ */
+
+/** 导入行(spec:14 列);请求 rows 与应答 raw_json 同源。 */
+export type ImportRow = {
+  row_no?: number;
+  customer_name?: string;
+  id_code?: string;
+  subject_type?: string;
+  contact_name?: string;
+  contact_mobile?: string;
+  address?: string;
+  region_name?: string;
+  operator_name?: string;
+  partner_name?: string;
+  ops_team_names?: string[];
+  primary_username?: string;
+  primary_mobile?: string;
+};
+
+/**
+ * GET /import_batch/template_download@v1 —— [实] handler 返回
+ * `{ format: "xlsx", columns: 14, max_rows: 500 }`:**columns 是列数(number),不是列名数组**。
+ */
+export type ImportTemplateSpec = {
+  format: string;
+  columns: number;
+  max_rows: number;
+  /** ⚠️ 后端待实现:14 列列名清单(当前不下发) */
+  column_names?: string[];
+};
+
+/**
+ * POST /import_batch/submit@v1 —— [实] 上传即建档(`status: "running"`)并逐行校验后回读。
+ * ⚠️ 本接口计数是**数字**(本次校验结果);列表/详情里的计数是**字符串**(UDS 下发)。
+ * §4.3:上传阶段只校验、尚未建档 ⇒ `success_rows` 恒 0、`fail_rows` =非法行数。
+ */
+export type ImportSubmitResult = {
+  batch_id: string;
+  batch_no: string;
+  status: string;
+  total_rows: number;
+  success_rows: number;
+  fail_rows: number;
+  valid_rows: number;
+  invalid_rows: number;
+  rows_written: number;
+  rows: { row_no: number; validate_status: string; error_list: string[] }[];
+  /** 上传阶段⛔ 执行的校验项(区域/运营商/合伙人名册匹配等) */
+  checks_pending: string[];
+  region_match_note: string;
+};
+
+/** POST /import_batch/resume@v1 应答行 [实] —— 已导入行只回显,其余 overwrite/insert。 */
+export type ImportResumeRow = {
+  row_no: number;
+  outcome: "already_imported" | "overwritten" | "inserted";
+  customer_id?: string | null;
+  note?: string;
+  validate_status?: string;
+  error_list?: string[];
+};
+
+/** POST /import_batch/resume@v1 —— [实] 续跑:逐行结果+库内汇总(`summary` 计数=字符串)。 */
+export type ImportResumeResult = {
+  batch_id: string;
+  batch_no: string;
+  status_before: string;
+  status_after: string;
+  updated_rows: number;
+  inserted_rows: number;
+  affected_rows: number;
+  already_imported_rows: number;
+  summary: { status: string; total_rows: string; success_rows: string; fail_rows: string };
+  rows: ImportResumeRow[];
+  checks_pending: string[];
+};
+
+export type ImportBatchRowT = {
+  batch_id: string;
+  batch_no: string;
+  batch_type: string;
+  status: string;
+  total_rows: string;
+  success_rows: string;
+  fail_rows: string;
+  operator_username: string | null;
+  created_at: string | null;
+};
+
+/** POST /import_batch/get_list@v1 —— [实] 真查 `import_batch`(计数为字符串)+`total/page/page_size`(page 0 基)。 */
+export type ImportBatchListResult = {
+  items: ImportBatchRowT[];
+  total: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** 导入行明细 [实] —— ⛔ 回传原始 14 列(含证件号/手机号),只给校验态与错误清单。 */
+export type ImportRowDetail = {
+  row_no: string;
+  validate_status: string;
+  business_id: string | null;
+  errors: unknown;
+};
+
+/**
+ * POST /import_batch/get@v1 —— [实] `batch` 逐字段同列表行(计数为字符串),
+ * 另发 `status_counts`(校验态分布,`count` 字符串)与分页行明细。
+ */
+export type ImportBatchDetail = {
+  batch: ImportBatchRowT;
+  status_counts: { validate_status: string; count: string }[];
+  rows: ImportRowDetail[];
+  page?: number;
+  page_size?: number;
+};
+
+/* ══ 分账号 ═══════════════════════════════════════════════════════ */
+
+/** 分账号行 [实](`sub_account` LEFT JOIN `bos_user_binding`)。 */
+export type SubAccountRow = {
+  sub_account_id: string;
+  customer_id: string;
+  username: string | null;
+  display_name: string | null;
+  purpose: string | null;
+  net_account: string | null;
+  status: string;
+  created_at: string | null;
+};
+
+/** GET(列表)/sub_account/get_list@v1 —— [实] 真查 `sub_account` LEFT JOIN `bos_user_binding`。 */
+export type SubAccountListResult = {
+  items: SubAccountRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+};
+
+/**
+ * POST /sub_account/update@v1 —— [实] 真落库(`UPDATE sub_account SET display_name/net_account`)+改后回读。
+ * ⚠️ **两口径并存**:列表行叫 `net_account`,本回执叫 `network_account_name`(同源同值,⛔ 混用)。
+ * ⚠️ `purpose` ⛔ 本接口可改字段(带了即 `20004 KLT-S20004`),此处只是原值回显;`platform_sync.applied` 恒 false。
+ */
+export type SubAccountUpdateResult = {
+  sub_account_id: string;
+  customer_id: string;
+  display_name: string | null;
+  /** =库内 `sub_account.net_account`(与列表行同值,仅键名不同) */
+  network_account_name: string | null;
+  /** ⛔ 可改,恒为改前原值 */
+  purpose: string | null;
+  status: string;
+  /** 本次实际写入的列名:`display_name`/`net_account` */
+  updated_fields: string[];
+  written_cols: string[];
+  audit_key: string;
+  audit_before_after: {
+    before: { display_name: string | null; net_account: string | null };
+    after: { display_name: string | null; net_account: string | null };
+  };
+  audit_written: boolean;
+  audit_note: string;
+  purpose_note: string;
+  platform_sync: { applied: boolean; reason: string };
+  time_note: string;
+};
+
+/* ══ 套餐档位 ═════════════════════════════════════════════════════ */
+
+export type CatalogPlanRow = {
+  plan_id: string;
+  plan_name: string;
+  plan_kind: string;
+  use_category: string | null;
+  annual_price_cents: number;
+  sub_account_quota: number | null;
+  bandwidth_committed: boolean | null;
+  bandwidth_up_mbps: number | null;
+  bandwidth_down_mbps: number | null;
+  customer_id: string | null;
+  customer_name?: string | null;
+  status: string;
+  created_at: string;
+  row_version: string;
+};
+
+/** POST /catalog/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ plan_id: null, req }`。 */
+export type CatalogCreateResult = { plan_id: string };
+
+/** POST /catalog/update@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形(`{ plan_id: null, req }`)。 */
+export type CatalogUpdateResult = { plan_id: string; updated: boolean };
+
+/** POST /catalog/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`(无 total)。 */
+export type CatalogListResult = {
+  items: CatalogPlanRow[];
+  total?: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** POST /catalog/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ plan: <请求体回显> }`。 */
+export type CatalogGetResult = CatalogPlanRow;
+
+/* ══ 合同 ═════════════════════════════════════════════════════════ */
+
+/** 合同服务构成条目(请求与应答同源)。 */
+export type ContractServiceItem = {
+  item_id?: string;
+  item_kind?: string;
+  plan_id?: string | null;
+  quantity?: number;
+  account_count?: number;
+  bandwidth_up_mbps?: number;
+  bandwidth_down_mbps?: number;
+  line_exits?: string[];
+};
+
+/** 合同 IP 条件条目(spec 未定义内部字段,前端按自由对象处理)。 */
+export type ContractIpEntry = Record<string, unknown>;
+
+export type ContractRow = {
+  contract_id: string;
+  customer_id: string;
+  customer_name?: string;
+  contract_no: string;
+  external_no: string | null;
+  status: string;
+  contract_amount_cents: number;
+  amount_cents?: number;
+  pay_cycle: string | null;
+  start_date: string | null;
+  end_date: string | null;
+  agent_name: string | null;
+  agent_mobile: string | null;
+  agent_handover_on: string | null;
+  agent_org: string | null;
+  attachment_url: string | null;
+  service_items?: ContractServiceItem[];
+  ip_entries?: ContractIpEntry[];
+  created_at: string;
+  row_version: string;
+};
+
+/** POST /contract/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ contract_id: null, req }`。 */
+export type ContractCreateResult = { contract_id: string; contract_no?: string };
+
+/** POST /contract/update@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形。 */
+export type ContractUpdateResult = { contract_id: string; updated: boolean };
+
+/** POST /contract/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。 */
+export type ContractListResult = {
+  items: ContractRow[];
+  total?: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** POST /contract/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ contract: <请求体回显> }`。 */
+export type ContractGetResult = ContractRow;
+
+/* ══ 订阅 ═════════════════════════════════════════════════════════ */
+
+export type SubscriptionRow = {
+  subscription_id: string;
+  customer_id: string;
+  customer_name?: string;
+  contract_id: string | null;
+  contract_item_id: string | null;
+  plan_id: string | null;
+  plan_name: string | null;
+  use_category: string | null;
+  status: string;
+  start_date: string | null;
+  end_date: string | null;
+  effective_date: string | null;
+  expire_date: string | null;
+  annual_price_cents: number | null;
+  monthly_settle_cents: number | null;
+  quota_slots: number;
+  replaces_subscription_id: string | null;
+  created_at: string;
+  row_version: string;
+};
+
+/** POST /subscription/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ subscription_id: null, req }`。 */
+export type SubscriptionCreateResult = { subscription_id: string; status?: string };
+
+/** POST /subscription/change@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形。 */
+export type SubscriptionChangeResult = { subscription_id: string; replaces_subscription_id?: string };
+
+/** POST /subscription/stack@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形。 */
+export type SubscriptionStackResult = { subscription_id: string; updated_fields?: string[] };
+
+/** POST /subscription/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。 */
+export type SubscriptionListResult = {
+  items: SubscriptionRow[];
+  total?: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** POST /subscription/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ subscription: <请求体回显> }`。 */
+export type SubscriptionGetResult = SubscriptionRow;
+
+/* ══ 成本与分成 ═══════════════════════════════════════════════════ */
+
+export type CostItemRow = {
+  cost_item_id: string;
+  item_id?: string;
+  category: string;
+  item_name: string;
+  billing_unit: string;
+  is_amortized: boolean;
+  amortization_months: number | null;
+  deduct_from_base: boolean;
+  remark: string | null;
+  status: string;
+  row_version: string;
+};
+
+/** POST /cost_item/save@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ saved: true, req }`。 */
+export type CostItemSaveResult = { cost_item_id: string; saved: boolean };
+
+/** POST /cost_item/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。 */
+export type CostItemListResult = {
+  items: CostItemRow[];
+  total?: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** 成本金额差异行(省份×运营商×成本项)。 */
+export type CostAmountRow = {
+  province_node_id: string;
+  operator_id: string;
+  cost_item_id: string;
+  item_name?: string;
+  category?: string;
+  amount_cents: number;
+  row_version: string;
+};
+
+/** POST /cost_amount/save@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ saved: true, req }`。 */
+export type CostAmountSaveResult = {
+  province_node_id: string;
+  operator_id: string;
+  saved: boolean;
+  /** 留空被删除的差异行数 */
+  deleted_count?: number;
+};
+
+/** POST /cost_amount/get_list@v1 透视行 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。 */
+export type CostAmountPivotRow = {
+  province_node_id: string;
+  province_name: string;
+  operator_id: string;
+  operator_name: string;
+  items: CostAmountRow[];
+};
+
+/** POST /cost_amount/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。 */
+export type CostAmountListResult = {
+  items: CostAmountPivotRow[];
+  total?: number;
+  page?: number;
+  page_size?: number;
+};
+
+export type ShareRuleRow = {
+  rule_id: string;
+  holder_type: string;
+  holder_id: string;
+  customer_id: string | null;
+  customer_name?: string | null;
+  rule_level: string;
+  share_mode: string;
+  share_value: number;
+  remark: string | null;
+  status: string;
+};
+
+/** POST /share_rule/save@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ saved: true, req }`。 */
+export type ShareRuleSaveResult = {
+  holder_type: string;
+  holder_id: string;
+  saved: boolean;
+  saved_count?: number;
+};
+
+/** POST /share_rule/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。 */
+export type ShareRuleListResult = {
+  items: ShareRuleRow[];
+  total?: number;
+  page?: number;
+  page_size?: number;
+};
+
+/** POST /share_rule/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ rule: <请求体回显> }`。 */
+export type ShareRuleDetail = {
+  holder_type: string;
+  holder_id: string;
+  holder_name: string;
+  cards: Record<string, number>;
+  rules: ShareRuleRow[];
+};
+
+/** POST /share_rule/delete@v1 —— [半] handler 返回 `{ deleted: true, req }`(恒 true,未落库)。 */
+export type ShareRuleDeleteResult = { rule_id: string; deleted: boolean };
+
+/* ══ 运维视图 ═════════════════════════════════════════════════════ */
+
+/**
+ * GET /opsview/home@v1 —— [实] handler `opsview.rs::home()` 返回(U-60 方案 B,诚实空态):
+ * `{ role, tickets: { pending: null, processing: null, available: false },
+ *    overdue: { count: null, available: false }, message }`。
+ * 工单宿主域第 2 期接线后 pending/processing/count 才给数值,前端须按 available 兜空态。
+ */
+export type OverviewStat = {
+  role: RoleCode | string;
+  tickets: { pending: number | null; processing: number | null; available: boolean };
+  overdue: { count: number | null; available: boolean };
+  message: string;
+};
+
+/* ══ 定时作业 ═════════════════════════════════════════════════════ */
+
+/** 作业 key(`bos_jobs::registry::JobKey` 的 serde 序列化名)。 */
+export type JobKey =
+  | "SUB-EFF"
+  | "STOP-GEN"
+  | "OVERDUE"
+  | "OPEN-GEN"
+  | "SVC-GEN"
+  | "RECON"
+  | "DELEGATION-SYNC";
+
+/**
+ * GET /jobs/get_list@v1 应答行 —— [实] 来自 `phase1_job_specs()`:
+ * `{ key, name, cron_hint, wired_in_phase1 }`。⚠️ 后端待补 enabled / last_run_at / last_status。
+ */
+export type JobSpecRow = {
+  key: JobKey;
+  name: string;
+  cron_hint: string;
+  wired_in_phase1: boolean;
+  /** ⚠️ 后端待实现(handler 未下发) */
+  enabled?: boolean;
+  last_run_at?: string | null;
+  last_status?: string | null;
+};
+
+/** POST /jobs/toggle@v1 —— [实] 平台 `sjc_job_toggle` 透传,形状由平台决定。 */
+export type JobToggleResult = Record<string, unknown>;
+
+/** POST /jobs/runs@v1 应答行 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ job_key, runs: [] }`。 */
+export type JobRunRow = {
+  run_id: string;
+  job_key: JobKey;
+  started_at: string;
+  finished_at: string | null;
+  status: string;
+  processed: number;
+  succeeded: number;
+  skipped: number;
+  failed: number;
+  message: string | null;
+};
+
+/** POST /jobs/runs@v1 —— [半] handler 返回 `{ job_key: <请求 key>, runs: [] }`。 */
+export type JobRunsResult = { job_key: JobKey; runs: JobRunRow[] };
+
+/** POST /jobs/run_once@v1 —— [实] `bos_jobs::report::RunReport`:`{ processed, succeeded, skipped, failed, message }`。 */
+export type JobRunReport = {
+  processed: number;
+  succeeded: number;
+  skipped: number;
+  failed: number;
+  message: string;
+};
+
+/* ══ 操作日志(游标翻页:⛔ total、⛔ OFFSET) ══════════════════════ */
+
+/**
+ * POST /audit/get_list@v1 [实] —— 游标=`created_at|id`。
+ * 后端⛔ 下发 `total`(靠 `next_cursor` 翻页,`null` 即到底),前端⛔ 显示「共 N 条」。
+ */
+export type AuditItem = {
+  occurred_at: string | null;
+  actor: { user_id: string; username: string | null };
+  action: string;
+  object: { type: string; id: string };
+  before: unknown;
+  after: unknown;
+  cursor: string;
+};
+
+export type AuditListResult = {
+  items: AuditItem[];
+  page_size: number;
+  next_cursor: string | null;
+};
+
+/** POST /ent_team/get_list@v1 [实]。 */
+export type EntTeamListResult = {
+  items: EntTeamRow[];
+  total: number;
+  page?: number;
+  page_size?: number;
+};

+ 96 - 0
front-end/src/auth/nav.ts

@@ -0,0 +1,96 @@
+import type { RoleCode } from "../api/types";
+
+export type Leaf = { route: string; label: string };
+export type Group = { key: string; label: string; children: Leaf[] };
+export type NavItem = Group | Leaf;
+
+const isGroup = (n: NavItem): n is Group => "children" in n;
+export { isGroup };
+
+/**
+ * 角色 → 菜单树(册1+册2 范围)。
+ * 菜单只负责隐藏入口;每个页面仍会被后端鉴权二次裁决。
+ */
+const ALL: Record<string, NavItem> = {
+  gOrg: {
+    key: "org",
+    label: "组织与区域",
+    children: [
+      { route: "regions", label: "区域管理" },
+      { route: "operators", label: "运营商" },
+      { route: "partners", label: "合伙人" },
+      { route: "entteams", label: "运营团队" },
+      { route: "opsteams", label: "运维团队" },
+      { route: "members", label: "成员账号" },
+    ],
+  },
+  gCust: {
+    key: "cust",
+    label: "客户与订阅",
+    children: [
+      { route: "customers", label: "客户管理" },
+      { route: "imports", label: "批量导入" },
+      { route: "subaccounts", label: "分账号" },
+    ],
+  },
+  gSys: {
+    key: "sys",
+    label: "系统",
+    children: [{ route: "audit", label: "审计日志" }],
+  },
+};
+
+const leaf = (route: string, label: string): Leaf => ({ route, label });
+
+const NAV: Record<RoleCode, NavItem[]> = {
+  admin: [leaf("home", "概览"), ALL.gOrg, ALL.gCust, leaf("audit", "审计日志")],
+  opsMain: [leaf("home", "概览"), ALL.gOrg, ALL.gCust, leaf("audit", "审计日志")],
+  opsSub: [leaf("home", "概览"), ALL.gOrg, ALL.gCust],
+  teamLead: [
+    leaf("home", "概览"),
+    { key: "t", label: "我的团队", children: [{ route: "members", label: "成员账号" }] },
+    ALL.gCust,
+  ],
+  ops: [leaf("home", "概览"), ALL.gCust],
+  partner: [leaf("home", "概览"), ALL.gCust],
+  operator: [
+    leaf("home", "概览"),
+    { key: "ro", label: "客户(只读)", children: [{ route: "customers", label: "客户清单" }] },
+  ],
+  enterprise: [
+    leaf("home", "概览"),
+    { key: "me", label: "我的账号", children: [{ route: "subaccounts", label: "分账号" }] },
+  ],
+  sub: [
+    leaf("home", "概览"),
+    { key: "me", label: "我的账号", children: [{ route: "subaccounts", label: "分账号" }] },
+  ],
+};
+
+export function navFor(role: RoleCode | undefined): NavItem[] {
+  if (!role) return [];
+  // 运营商是只读主体:去掉可写分组已在 NAV 中静态表达,这里再兜一层。
+  return NAV[role] ?? [];
+}
+
+export function firstRoute(role: RoleCode | undefined): string {
+  const items = navFor(role);
+  for (const n of items) {
+    if (isGroup(n)) return n.children[0]!.route;
+    return n.route;
+  }
+  return "home";
+}
+
+/** 详情页等非菜单路由的高亮归并。 */
+const ALIAS: Record<string, string> = {
+  customer: "customers",
+  entteamscope: "entteams",
+  opsteamscope: "opsteams",
+  partnerscope: "partners",
+  importbatch: "imports",
+};
+
+export function activeRoute(route: string): string {
+  return ALIAS[route] ?? route;
+}

+ 114 - 0
front-end/src/auth/session.tsx

@@ -0,0 +1,114 @@
+import {
+  createContext,
+  useCallback,
+  useContext,
+  useEffect,
+  useMemo,
+  useRef,
+  useState,
+  type ReactNode,
+} from "react";
+import { authContext } from "../api/bos";
+import { ApiError, getToken, setToken } from "../api/http";
+import type { AuthContext, RoleCode } from "../api/types";
+
+export const ROLE_LABEL: Record<RoleCode, string> = {
+  admin: "总部管理员",
+  opsMain: "区域管理员(省级)",
+  opsSub: "区域管理员(市级)",
+  teamLead: "运营团队负责人",
+  ops: "运维班组成员",
+  enterprise: "客户主管账号",
+  sub: "客户子账号",
+  partner: "合伙人账号",
+  operator: "运营商账号",
+};
+
+type SessionValue = {
+  ctx: AuthContext | null;
+  loading: boolean;
+  error: string | null;
+  ready: boolean;
+  reload: () => Promise<void>;
+  signOut: () => void;
+};
+
+const Ctx = createContext<SessionValue>(null as unknown as SessionValue);
+
+export function SessionProvider({ children }: { children: ReactNode }) {
+  const [ctx, setCtx] = useState<AuthContext | null>(null);
+  const [loading, setLoading] = useState<boolean>(() => !!getToken());
+  const [error, setError] = useState<string | null>(null);
+
+  /**
+   * 同一枚票的并发「业务上下文」请求合并为一次真请求。
+   *
+   * 2026-11-08 手测取证:一次页面加载里 `GET /bos/auth/context@v1` 被打了 2 次,
+   * 两条资源条目 `startTime` 只差 0.1~0.2 ms(同一 tick 背靠背、都回 200),
+   * 成因是 dev 下 `StrictMode` 把挂载 effect 跑两遍——调用点只有本文件这一处。
+   * 合并键=票据本身:登录换票后 key 变化,⛔ 复用上一身份的结果。
+   */
+  const inflight = useRef<{ token: string; p: Promise<void> } | null>(null);
+
+  const load = useCallback(async () => {
+    const token = getToken();
+    if (!token) {
+      inflight.current = null;
+      setCtx(null);
+      setLoading(false);
+      return;
+    }
+    const fly = inflight.current;
+    if (fly && fly.token === token) return fly.p;
+
+    const entry: { token: string; p: Promise<void> } = { token, p: Promise.resolve() };
+    entry.p = (async () => {
+      setLoading(true);
+      try {
+        const c = await authContext();
+        setCtx(c);
+        setError(null);
+      } catch (e) {
+        const err = e as ApiError;
+        setError(err.message ?? "无法获取业务角色上下文");
+        setCtx(null);
+      } finally {
+        setLoading(false);
+        if (inflight.current === entry) inflight.current = null;
+      }
+    })();
+    inflight.current = entry;
+    return entry.p;
+  }, []);
+
+  useEffect(() => {
+    void load();
+  }, [load]);
+
+  const signOut = useCallback(() => {
+    setToken(null);
+    setCtx(null);
+    // 退出后⛔ 再留着上一身份的上下文错误,否则登录页会挂着一条与当前操作无关的报错。
+    setError(null);
+    location.hash = "#/login";
+  }, []);
+
+  const value = useMemo<SessionValue>(
+    () => ({ ctx, loading, error, ready: !!ctx && !loading, reload: load, signOut }),
+    [ctx, loading, error, load, signOut],
+  );
+  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
+}
+
+export function useSession() {
+  return useContext(Ctx);
+}
+
+/** 权限判定只用于「隐藏入口」;真正的裁决在后端(总则§16.5)。 */
+export function useCan() {
+  const { ctx } = useSession();
+  return useCallback(
+    (key: string) => !!ctx?.permissions?.includes(key) || !!ctx?.permissions?.includes("*"),
+    [ctx],
+  );
+}

+ 491 - 0
front-end/src/components/ui.tsx

@@ -0,0 +1,491 @@
+import {
+  createContext,
+  useCallback,
+  useContext,
+  useEffect,
+  Fragment,
+  isValidElement,
+  useMemo,
+  useRef,
+  useState,
+  type ReactNode,
+} from "react";
+import { ApiError } from "../api/http";
+
+/* ── 基础控件 ─────────────────────────────────────────────────── */
+
+export function Btn({
+  children,
+  onClick,
+  ghost,
+  warn,
+  danger,
+  disabled,
+  type = "button",
+  title,
+}: {
+  children: ReactNode;
+  onClick?: () => void;
+  ghost?: boolean;
+  warn?: boolean;
+  danger?: boolean;
+  disabled?: boolean;
+  type?: "button" | "submit";
+  title?: string;
+}) {
+  return (
+    <button
+      type={type}
+      className={`btn${ghost ? " ghost" : ""}${warn ? " warn" : ""}${danger ? " danger" : ""}`}
+      onClick={onClick}
+      disabled={disabled}
+      title={title}
+    >
+      {children}
+    </button>
+  );
+}
+
+/** 标题右侧「?」说明(原型 .q-tip):口径、前置条件这类长解释⛔ 塞进标题。 */
+export function QTip({ children, popRight }: { children: ReactNode; popRight?: boolean }) {
+  return (
+    <span className={`q-tip${popRight ? " pop-right" : ""}`} tabIndex={0}>
+      ?<span className="q-tip-pop">{children}</span>
+    </span>
+  );
+}
+
+/**
+ * 面板标题(原型 `.panel h2`):原型没有 `.panel-head` 这一层,标题直接是 `.panel` 的子元素,
+ * 计数写进标题文本或 `<span className="cnt">`,⛔ 再套一层 div 把间距改掉。
+ * 只有确实需要右侧操作时才把 h2 自身拉成两端对齐(原型的批量操作一律放在 `.filters` 里)。
+ */
+export function PanelHead({ title, right }: { title: ReactNode; right?: ReactNode }) {
+  if (!right) return <h2>{title}</h2>;
+  // 原型带操作的面板头:`div.row[space-between] > h2[margin:0] + span(或 span.row) > button`
+  return (
+    <div className="row" style={{ justifyContent: "space-between" }}>
+      <h2 style={{ margin: 0 }}>{title}</h2>
+      <span className={actionCount(right) > 1 ? "row" : undefined}>{right}</span>
+    </div>
+  );
+}
+
+/** 原型面板头右侧容器:一枚按钮用裸 `<span>`(按钮保持 `inline-block`),两枚及以上才 `span.row`。 */
+function actionCount(node: ReactNode): number {
+  if (node === null || node === undefined || node === false || node === true || node === "") return 0;
+  if (Array.isArray(node)) return node.reduce((n, x) => n + actionCount(x), 0);
+  if (isValidElement(node) && node.type === Fragment)
+    return actionCount((node.props as { children?: ReactNode }).children);
+  return 1;
+}
+
+const PILL_TONE: Record<string, string> = {
+  正常: "ok",
+  在用: "ok",
+  使用中: "ok",
+  启用: "ok",
+  已开通: "ok",
+  已激活: "ok",
+  未开通: "wait",
+  未出账: "wait",
+  待派单: "wait",
+  已生效: "ok",
+  生效中: "ok",
+  成功: "ok",
+  已完成: "ok",
+  未激活: "wait",
+  待激活: "wait",
+  待生效: "wait",
+  部分成功: "wait",
+  处理中: "run",
+  已停用: "bad",
+  已过期: "bad",
+  失败: "bad",
+  停用: "bad",
+};
+
+export function Pill({ text }: { text: string | null | undefined }) {
+  if (!text) return <>—</>;
+  return <span className={`pill ${PILL_TONE[text] ?? ""}`.trim()}>{text}</span>;
+}
+
+/** 账号状态码 → 全站统一措辞(`bos_account_ext.status` 值域)。 */
+const ACCT_STATUS: Record<string, string> = {
+  active: "已开通",
+  disabled: "已停用",
+  none: "未开通",
+};
+
+/**
+ * 原型 `acctCell(acc)`:状态徽标+登录名+手机号三行。
+ *
+ * `acc` 为 `null`=该主体未开通账号(⛔ 用「—」冒充已开通,也⛔ 显示成空字符串);
+ * `mobile` 由后端掩码下发,⛔ 在此再加工或还原。同主体多账号时给出总数。
+ */
+export function AcctCell({
+  acc,
+}: {
+  acc: { username: string; mobile: string | null; status: string; account_count: number } | null | undefined;
+}) {
+  const word = !acc ? "未开通" : ACCT_STATUS[acc.status] ?? acc.status;
+  return (
+    <>
+      <Pill text={word} />
+      <br />
+      <span className="note">{acc ? acc.username : "尚未开通"}</span>
+      <br />
+      <span className="note">
+        {acc ? (acc.mobile ? `手机 ${acc.mobile}` : "未绑手机号") : "—"}
+        {acc && acc.account_count > 1 ? ` · 名下共 ${acc.account_count} 个账号` : ""}
+      </span>
+    </>
+  );
+}
+
+/**
+ * 原型 `scopeSummary(db, scope)`:负责范围列文案(授权区域 + 直接多选客户,取并集)。
+ *
+ * 区域本期只有节点 ID —— 中文名称待平台侧区域读接口(18 册在册)。
+ * 两维度都为空=范围未配置,显式说明而⛔ 留空(留空会被读成「范围为空」)。
+ */
+export function ScopeText({ regions, customers }: { regions: string[]; customers: string[] }) {
+  if (!regions.length && !customers.length) return <span className="note">范围未配置</span>;
+  const parts: string[] = [];
+  if (regions.length) parts.push(`区域 ${regions.join("、")}`);
+  if (customers.length) parts.push(`客户 ${customers.join("、")}`);
+  return <>{parts.join(" + ")}</>;
+}
+
+export function Panel({
+  title,
+  extra,
+  note,
+  noteTitle,
+  children,
+}: {
+  title: ReactNode;
+  extra?: ReactNode;
+  note?: ReactNode;
+  /** 折叠说明的摘要文字(原型 `details.note-details > summary`):写清这块在解释什么。 */
+  noteTitle?: string;
+  children: ReactNode;
+}) {
+  return (
+    <div className="panel">
+      <PanelHead title={title} right={extra} />
+      {children}
+      {note ?
+        noteTitle ?
+          (<details className="note-details">
+            <summary>{noteTitle}</summary>
+            <div className="note">{note}</div>
+          </details>) :
+
+          <p className="note">{note}</p>
+      : null}
+    </div>
+  );
+}
+
+/** 面板底部的口径/统计范围说明(原型每页都有一段 `.note`)。 */
+export function Note({ children }: { children: ReactNode }) {
+  return <p className="note">{children}</p>;
+}
+
+/** 概览 KPI 卡(原型 `.cards.kpi .card`):数值+可选拆分,下方灰字口径说明。 */
+export function KpiCard({
+  label,
+  value,
+  split,
+  sub,
+  alarm,
+  onClick,
+}: {
+  label: string;
+  value: ReactNode;
+  split?: ReactNode;
+  sub?: ReactNode;
+  alarm?: boolean;
+  onClick?: () => void;
+}) {
+  return (
+    <div className={`card${alarm ? " alarm" : ""}`} onClick={onClick}>
+      <span>{label}</span>
+      <div className="num-row">
+        <b>{value}</b>
+        {split ? <span className="num-split">{split}</span> : null}
+      </div>
+      {sub ? <span className="card-sub">{sub}</span> : null}
+    </div>
+  );
+}
+
+/** 表格「序号」列的全局序号(跨页连续,与原型 `seq()` 一致)。 */
+export function seq(page: number, page_size: number, i: number): number {
+  return (page - 1) * page_size + i + 1;
+}
+
+export function Card({
+  label,
+  value,
+  sub,
+  alarm,
+  onClick,
+}: {
+  label: string;
+  value: ReactNode;
+  sub?: ReactNode;
+  alarm?: boolean;
+  onClick?: () => void;
+}) {
+  return (
+    <div className={`card${alarm ? " alarm" : ""}`} onClick={onClick}>
+      <span>{label}</span>
+      <b>{value}</b>
+      {sub ? <span className="card-sub">{sub}</span> : null}
+    </div>
+  );
+}
+
+export function Tabs({
+  items,
+  value,
+  onChange,
+}: {
+  items: { key: string; label: string }[];
+  value: string;
+  onChange: (k: string) => void;
+}) {
+  return (
+    <div className="tabs">
+      {items.map((t) => (
+        <button key={t.key} className={`tab${value === t.key ? " active" : ""}`} onClick={() => onChange(t.key)}>
+          {t.label}
+        </button>
+      ))}
+    </div>
+  );
+}
+
+export function Modal({
+  title,
+  onClose,
+  children,
+  wide,
+}: {
+  title: string;
+  onClose: () => void;
+  children: ReactNode;
+  wide?: boolean;
+}) {
+  useEffect(() => {
+    const h = (e: KeyboardEvent) => e.key === "Escape" && onClose();
+    window.addEventListener("keydown", h);
+    return () => window.removeEventListener("keydown", h);
+  }, [onClose]);
+  return (
+    <div className="modal-overlay" onClick={onClose}>
+      <div className={`modal${wide ? " wide" : ""}`} onClick={(e) => e.stopPropagation()}>
+        {/* 原型 `modalOverlay()`:弹窗内首元素就是 `h3`,⛔ 标题栏与 × 关闭钮——
+            关闭只走遮罩点击、Esc 与页脚 `data-modal-close`(取消/关闭)三个出口 */}
+        <h3>{title}</h3>
+        {children}
+      </div>
+    </div>
+  );
+}
+
+export function Drawer({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
+  return (
+    <div className="drawer-overlay" onClick={onClose}>
+      <div className="drawer" onClick={(e) => e.stopPropagation()}>
+        {/* 原型抽屉头:`div.drawer-head > h2 + button.btn.ghost`(关闭),⛔ 自造 `.modal-head` 与 × 钮 */}
+        <div className="drawer-head">
+          <h2>{title}</h2>
+          <Btn ghost onClick={onClose}>
+            关闭
+          </Btn>
+        </div>
+        {children}
+      </div>
+    </div>
+  );
+}
+
+/** 表单字段:label + 控件 + 行内错误(总则§16.5:写操作失败要回滚到原值并给行内错误)。 */
+export function Field({
+  label,
+  required,
+  error,
+  hint,
+  children,
+}: {
+  label: string;
+  required?: boolean;
+  error?: string;
+  hint?: string;
+  children: ReactNode;
+}) {
+  return (
+    <div className={`f-item${error ? " f-bad" : ""}`}>
+      <label>
+        {label}
+        {required ? <i className="req">*</i> : null}
+      </label>
+      {children}
+      {error ? <em className="f-err">{error}</em> : hint ? <div className="note">{hint}</div> : null}
+    </div>
+  );
+}
+
+/** 分页条(原型 `.pager`):左侧「第 a–b 条 / 共 N 条」,右侧页码按钮组。 */
+export function Pager({
+  page,
+  page_size,
+  total,
+  onChange,
+}: {
+  page: number;
+  page_size: number;
+  total: number;
+  onChange: (p: number) => void;
+}) {
+  const pages = Math.max(1, Math.ceil(total / page_size));
+  const from = (page - 1) * page_size;
+  const summary = `第 ${total === 0 ? 0 : from + 1}–${Math.min(from + page_size, total)} 条 / 共 ${total} 条 · 第 ${page} / ${pages} 页,每页 ${page_size} 条`;
+  const nums: (number | "…")[] = [];
+  for (let p = 1; p <= pages; p++) {
+    if (p === 1 || p === pages || Math.abs(p - page) <= 1) nums.push(p);
+    else if (nums[nums.length - 1] !== "…") nums.push("…");
+  }
+  const pg = (text: ReactNode, to: number, enabled: boolean, cur = false, key?: string | number) => (
+    <button
+      key={key ?? String(text)}
+      className={`pg${cur ? " cur" : ""}`}
+      disabled={!enabled}
+      onClick={() => enabled && onChange(to)}
+    >
+      {text}
+    </button>
+  );
+  return (
+    <div className="pager">
+      <span className="note">{summary}</span>
+      <span className="pgs">
+        {pg("上一页", page - 1, page > 1, false, "prev")}
+        {nums.map((p, i) =>
+          p === "…" ? (
+            <span key={`g${i}`} className="pg gap">
+              …
+            </span>
+          ) : (
+            pg(p, p, true, p === page, p)
+          ),
+        )}
+        {pg("下一页", page + 1, page < pages, false, "next")}
+      </span>
+    </div>
+  );
+}
+
+export function Empty({ text = "暂无数据", cols }: { text?: string; cols?: number }) {
+  /* 原型空表不另起容器,直接在 tbody 里铺一行通栏说明。 */
+  if (cols) return <tr><td colSpan={cols}>{text}</td></tr>;
+  return <p className="note">{text}</p>;
+}
+
+export function Loading() {
+  return <p className="note">加载中…</p>;
+}
+
+export function ErrorBox({ error }: { error: unknown }) {
+  if (!error) return null;
+  const e = error as ApiError;
+  return (
+    <div className="alert">
+      <b>请求失败</b>
+      <span>
+        {e.code != null ? `code ${e.code} · ` : ""}
+        {e.message ?? String(error)}
+      </span>
+    </div>
+  );
+}
+
+/** 表格单元格统一空值口径(总则§16.5:未设值显示「未设置」,无权限字段显示「—」)。 */
+export function Cell({ v, dash = "—" }: { v: unknown; dash?: string }) {
+  if (v === null || v === undefined || v === "") return <>{dash}</>;
+  if (Array.isArray(v)) return v.length ? <>{v.join("、")}</> : <>{dash}</>;
+  return <>{String(v)}</>;
+}
+
+/** 诚实降级说明:后端明确「无数源/一期未实现」时用它,⛔ 用 0 或「—」冒充真实数值。 */
+export function Notice({ tone = "info", children }: { tone?: "info" | "warn"; children: ReactNode }) {
+  return <div className={tone === "warn" ? "alert" : "phase-note"}>{children}</div>;
+}
+
+/* ── 轻提示 ───────────────────────────────────────────────────── */
+
+type ToastFn = (msg: string, tone?: "ok" | "bad") => void;
+const ToastCtx = createContext<ToastFn>(() => {});
+export const useToast = () => useContext(ToastCtx);
+
+export function ToastProvider({ children }: { children: ReactNode }) {
+  const [items, setItems] = useState<{ id: number; msg: string; tone: string }[]>([]);
+  const seq = useRef(0);
+  const push = useCallback<ToastFn>((msg, tone = "ok") => {
+    const id = ++seq.current;
+    setItems((s) => [...s, { id, msg, tone }]);
+    setTimeout(() => setItems((s) => s.filter((x) => x.id !== id)), 2800);
+  }, []);
+  const value = useMemo(() => push, [push]);
+  return (
+    <ToastCtx.Provider value={value}>
+      {children}
+      <div className="toast-stack">
+        {items.map((t) => (
+          <div key={t.id} className={`toast ${t.tone}`}>
+            {t.msg}
+          </div>
+        ))}
+      </div>
+    </ToastCtx.Provider>
+  );
+}
+
+/* ── 数据加载骨架 ─────────────────────────────────────────────── */
+
+export function Async({
+  error,
+  loading,
+  isEmpty,
+  children,
+  emptyText,
+}: {
+  error: unknown;
+  loading?: boolean;
+  isEmpty?: boolean;
+  children: ReactNode;
+  emptyText?: string;
+}) {
+  if (error) return <ErrorBox error={error} />;
+  if (loading) return <Loading />;
+  if (isEmpty) return <Empty text={emptyText} />;
+  return <>{children}</>;
+}
+
+export function money(cents: number | null | undefined): string {
+  if (cents === null || cents === undefined) return "—";
+  return `¥${(cents / 100).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+}
+
+export function day(v: string | null | undefined): string {
+  if (!v) return "—";
+  return v.slice(0, 10);
+}
+
+export function datetime(v: string | null | undefined): string {
+  if (!v) return "—";
+  return v.replace("T", " ").slice(0, 19);
+}

+ 132 - 0
front-end/src/hooks/useLoad.ts

@@ -0,0 +1,132 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { ApiError } from "../api/http";
+
+/**
+ * 只读加载骨架。
+ *
+ * 失败关闭(总则§16.5):请求失败一律回 `error`,由页面渲染 `ErrorBox`,
+ * ⛔ 回退成空集或 0 冒充「没有数据」——「查不到」与「查不了」必须能区分。
+ */
+export type Load<T> = {
+  data: T | null;
+  loading: boolean;
+  error: ApiError | null;
+  reload: () => void;
+};
+
+export function useLoad<T>(fn: () => Promise<T>, deps: readonly unknown[]): Load<T> {
+  const [data, setData] = useState<T | null>(null);
+  const [loading, setLoading] = useState<boolean>(true);
+  const [error, setError] = useState<ApiError | null>(null);
+  const [tick, setTick] = useState(0);
+  // eslint-disable-next-line react-hooks/exhaustive-deps
+  const run = useCallback(fn, deps);
+
+  /**
+   * 同一 `run`(依赖未变)在飞行中时复用同一次请求,⛔ 重复打接口。
+   *
+   * 2026-11-08 手测取证:dev 下 `StrictMode` 把挂载 effect 跑两遍,同一 tick 内
+   * 背靠背发出两条同名请求(`auth/context@v1` 实测 2 次、间隔 0.1~0.2 ms)。
+   * 只在「仍在飞行中」时复用:一旦落定即清空,`reload()` 仍会真重取。
+   */
+  const fly = useRef<{ run: () => Promise<T>; p: Promise<T> } | null>(null);
+
+  useEffect(() => {
+    let alive = true;
+    setLoading(true);
+    setError(null);
+    const prev = fly.current;
+    const p = prev && prev.run === run ? prev.p : run();
+    fly.current = { run, p };
+    p.then(
+      (d) => {
+        if (fly.current?.p === p) fly.current = null;
+        if (!alive) return;
+        setData(d);
+        setLoading(false);
+      },
+      (e) => {
+        if (fly.current?.p === p) fly.current = null;
+        if (!alive) return;
+        setError(e as ApiError);
+        setLoading(false);
+      },
+    );
+    return () => {
+      alive = false;
+    };
+  }, [run, tick]);
+
+  return { data, loading, error, reload: () => setTick((t) => t + 1) };
+}
+
+/**
+ * 写操作骨架:成功回 true(调用方决定是否刷新),失败把 `ApiError` 交给页面行内呈现。
+ *
+ * 后端回 `20007 内部错误`/`20008 功能未实现` 时是真失效,这里⛔ 吞掉、⛔ 转成成功。
+ */
+export type Submit = {
+  busy: boolean;
+  error: ApiError | null;
+  run: (fn: () => Promise<unknown>) => Promise<boolean>;
+  clear: () => void;
+};
+
+export function useSubmit(): Submit {
+  const [busy, setBusy] = useState(false);
+  const [error, setError] = useState<ApiError | null>(null);
+  const alive = useRef(true);
+  useEffect(() => {
+    // StrictMode(dev)会「挂载→卸载→再挂载」同一 fiber,ref 不重建:
+    // 若不在 mount 时复位,`alive` 将永远停在 false,导致 busy/error 一律不落状态,
+    // 界面卡在「提交中…」且看不到错误(2026-11-08 实测:region/create 回 60006 后按钮永久禁用)。
+    alive.current = true;
+    return () => {
+      alive.current = false;
+    };
+  }, []);
+
+  const run = useCallback(async (fn: () => Promise<unknown>) => {
+    setBusy(true);
+    setError(null);
+    try {
+      await fn();
+      if (alive.current) setBusy(false);
+      return true;
+    } catch (e) {
+      if (alive.current) {
+        setError(e as ApiError);
+        setBusy(false);
+      }
+      return false;
+    }
+  }, []);
+
+  return { busy, error, run, clear: () => setError(null) };
+}
+
+/**
+ * 表单状态:写操作失败后调用方 `reset()` 回原值(总则§16.5 回滚口径)。
+ */
+export type Form = {
+  vals: Record<string, string>;
+  bind: (k: string) => { value: string; onChange: (e: { target: { value: string } }) => void };
+  set: (k: string, v: string) => void;
+  get: (k: string) => string;
+  reset: (v?: Record<string, string>) => void;
+};
+
+export function useForm(init: Record<string, string> = {}): Form {
+  const [vals, setVals] = useState<Record<string, string>>(init);
+  const bind = useCallback(
+    (k: string) => ({
+      value: vals[k] ?? "",
+      onChange: (e: { target: { value: string } }) => setVals((s) => ({ ...s, [k]: e.target.value })),
+    }),
+    [vals],
+  );
+  const set = useCallback((k: string, v: string) => setVals((s) => ({ ...s, [k]: v })), []);
+  const get = useCallback((k: string) => (vals[k] ?? "").trim(), [vals]);
+  const reset = useCallback((v: Record<string, string> = {}) => setVals(v), []);
+  return { vals, bind, set, get, reset };
+}

+ 96 - 0
front-end/src/layout/Shell.tsx

@@ -0,0 +1,96 @@
+import { Fragment, useState, type ReactNode } from "react";
+import { useNavigate } from "react-router-dom";
+import { activeRoute, isGroup, navFor } from "../auth/nav";
+import { ROLE_LABEL, useSession } from "../auth/session";
+import { QTip } from "../components/ui";
+
+export function Shell({
+  route,
+  title,
+  hint,
+  actions,
+  mainClass,
+  qtip,
+  children,
+}: {
+  route: string;
+  title: string;
+  hint?: string;
+  actions?: ReactNode;
+  mainClass?: string;
+  qtip?: ReactNode;
+  children: ReactNode;
+}) {
+  const { ctx, signOut } = useSession();
+  const nav = useNavigate();
+  const [open, setOpen] = useState<Record<string, boolean>>({});
+  const items = navFor(ctx?.role_code);
+  const active = activeRoute(route);
+
+  return (
+    <div className="shell">
+      <aside className="nav">
+        <div className="brand">运营支撑系统</div>
+        <div className="nav-menu">
+          {items.map((n) =>
+            isGroup(n) ? (
+              <Fragment key={n.key}>
+                <button
+                  className={`nav-group${open[n.key] === false ? "" : " open"}`}
+                  onClick={() => setOpen((s) => ({ ...s, [n.key]: !(s[n.key] ?? true) }))}
+                >
+                  {n.label}
+                  <span className="caret">▾</span>
+                </button>
+                <div className={`nav-sub${open[n.key] === false ? " closed" : ""}`}>
+                  {n.children.map((c) => (
+                    <button
+                      key={c.route}
+                      className={`nav-leaf${active === c.route ? " active" : ""}`}
+                      onClick={() => nav(`/${c.route}`)}
+                    >
+                      {c.label}
+                    </button>
+                  ))}
+                </div>
+              </Fragment>
+            ) : (
+              <button
+                key={n.route}
+                className={`nav-leaf${active === n.route ? " active" : ""}`}
+                onClick={() => nav(`/${n.route}`)}
+              >
+                {n.label}
+              </button>
+            ),
+          )}
+        </div>
+        <div className="who">
+          {ctx?.display_name || ctx?.username || "未加载"}
+          <br />
+          {ctx ? ROLE_LABEL[ctx.role_code] : ""}
+          {ctx?.subject_name ? (
+            <>
+              <br />
+              {ctx.subject_name}
+            </>
+          ) : null}
+          <button onClick={signOut}>退出登录</button>
+        </div>
+      </aside>
+      <section className={`main${mainClass ? ` ${mainClass}` : ""}`}>
+        <div className="top">
+          <div>
+            <h1>
+              {title}
+              {qtip ? <QTip>{qtip}</QTip> : null}
+            </h1>
+            {hint ? <p>{hint}</p> : null}
+          </div>
+          {actions ? <div className="row">{actions}</div> : null}
+        </div>
+        {children}
+      </section>
+    </div>
+  );
+}

+ 34 - 0
front-end/src/main.tsx

@@ -0,0 +1,34 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { HashRouter } from "react-router-dom";
+import App from "./App";
+import { ToastProvider } from "./components/ui";
+import { SessionProvider } from "./auth/session";
+import "./styles/prototype.css";
+import "./styles/app.css";
+
+/**
+ * 会话态一律不做跨页缓存(总则§16.5:切换角色/退出后不得残留上一身份的数据),
+ * 因此关闭 staleTime 复用之外的一切持久化,窗口失焦也不自动重取。
+ */
+const queryClient = new QueryClient({
+  defaultOptions: {
+    queries: { staleTime: 30_000, refetchOnWindowFocus: false, retry: 0 },
+    mutations: { retry: 0 },
+  },
+});
+
+createRoot(document.getElementById("root") as HTMLElement).render(
+  <StrictMode>
+    <QueryClientProvider client={queryClient}>
+      <ToastProvider>
+        <SessionProvider>
+          <HashRouter>
+            <App />
+          </HashRouter>
+        </SessionProvider>
+      </ToastProvider>
+    </QueryClientProvider>
+  </StrictMode>,
+);

+ 307 - 0
front-end/src/pages/AuditPage.tsx

@@ -0,0 +1,307 @@
+import { useCallback, useEffect, useState } from "react";
+import { ACTION_AUDIT, TARGET_TYPE, label } from "../api/labels";
+import { auditGetList } from "../api/bos";
+import type { AuditItem } from "../api/types";
+import { ApiError } from "../api/http";
+import { Btn, Cell, ErrorBox, Field, Loading, Panel, datetime } from "../components/ui";
+import { Shell } from "../layout/Shell";
+
+/** 原型 `AUDIT_PAGE_ROWS` 的单批口径,正式系统沿用后端 `page_size`(演示口径是 10 条,不新增配置项)。 */
+const PAGE_SIZE = 50;
+
+/** 原型 `auditFilter` 的六个条件:对象类型/主体定位/操作人/时间区间(起)/(止)/关键字。 */
+const EMPTY_FILTER = {
+  object_type: "",
+  object_ref: "",
+  actor_user_id: "",
+  occurred_from: "",
+  occurred_to: "",
+  keyword: "",
+};
+
+/**
+ * `datetime-local` 回的是「本地挂钟时间」且⛔ 秒与时区(`2026-01-01T00:00`),后端按
+ * `::timestamptz` 解析 ⇒ UDS 报 `Arrow error: Parser error: Error parsing timestamp from
+ * '2026-01-01T00:00'`(实测 code 60006)。这里补秒并把本地 UTC 偏移写进串里,⛔ 靠"当 UTC 处理"蒙。
+ */
+const toTs = (v: string) => {
+  if (!v) return "";
+  const d = new Date(v);
+  if (Number.isNaN(d.getTime())) return v;
+  const off = -d.getTimezoneOffset();
+  const abs = Math.abs(off);
+  const pad = (n: number) => String(n).padStart(2, "0");
+  return `${v.length === 16 ? `${v}:00` : v}${off >= 0 ? "+" : "-"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
+};
+
+/** 主体定位的下拉值:后端入参是 `{type,id}`,下拉只能带一个字符串,故用 JSON 串承载一对值。 */
+const refValue = (type: string, id: string) => JSON.stringify([type, id]);
+const parseRef = (v: string): { type: string; id: string } | undefined => {
+  if (!v) return undefined;
+  try {
+    const [type, id] = JSON.parse(v) as [string, string];
+    return type && id ? { type, id } : undefined;
+  } catch {
+    return undefined;
+  }
+};
+
+/** 下拉项累加表:只由**已载入的可见行**去重得到(⛔ 全库去重,接口不提供枚举能力)。 */
+type Seen = { types: string[]; refs: { type: string; id: string }[]; actors: { id: string; name: string }[] };
+const EMPTY_SEEN: Seen = { types: [], refs: [], actors: [] };
+
+/**
+ * 审计日志(册2§审计/原型 `pageAudit`)。
+ *
+ * ⚠️ 后端是**游标翻页**(游标=`occurred_at|id`,`next_cursor` 为 null 即到底):这里累加已取条目,
+ * ⛔ 页码控件、⛔「共 N 条」——后端不下发 total,故沿用原型的「加载更多」游标分页条,
+ * 不套共享 `Pager`(那需要 total/页码,会造出假总数)。日志只读,⛔ 任何修改入口。
+ */
+export function AuditPage() {
+  const [draft, setDraft] = useState(EMPTY_FILTER);
+  const [applied, setApplied] = useState(EMPTY_FILTER);
+  const [items, setItems] = useState<AuditItem[]>([]);
+  const [seen, setSeen] = useState<Seen>(EMPTY_SEEN);
+  const [cursor, setCursor] = useState<string | null>(null);
+  const [loading, setLoading] = useState(true);
+  const [error, setError] = useState<ApiError | null>(null);
+
+  const query = useCallback(
+    (cur: string | null) =>
+      auditGetList({
+        page_size: PAGE_SIZE,
+        cursor: cur ?? undefined,
+        object_type: applied.object_type || undefined,
+        object_ref: parseRef(applied.object_ref),
+        actor_user_id: applied.actor_user_id || undefined,
+        // 原型是自然日选择:起取当日 00:00、止取当日 23:59,再交给 toTs 补秒与时区
+        occurred_from: applied.occurred_from ? toTs(`${applied.occurred_from}T00:00`) : undefined,
+        occurred_to: applied.occurred_to ? toTs(`${applied.occurred_to}T23:59`) : undefined,
+        keyword: applied.keyword || undefined,
+      }),
+    [applied],
+  );
+
+  const absorb = useCallback((rows: AuditItem[]) => {
+    setSeen((s) => {
+      const types = new Set(s.types);
+      const refs = new Map(s.refs.map((r) => [refValue(r.type, r.id), r]));
+      const actors = new Map(s.actors.map((a) => [a.id, a]));
+      rows.forEach((r) => {
+        if (r.object?.type) types.add(r.object.type);
+        if (r.object?.type && r.object?.id) refs.set(refValue(r.object.type, r.object.id), { type: r.object.type, id: r.object.id });
+        if (r.actor?.user_id) actors.set(r.actor.user_id, { id: r.actor.user_id, name: r.actor.username || r.actor.user_id });
+      });
+      return {
+        types: [...types].sort(),
+        refs: [...refs.values()].sort((a, b) => (a.type === b.type ? a.id.localeCompare(b.id) : a.type.localeCompare(b.type))),
+        actors: [...actors.values()].sort((a, b) => a.name.localeCompare(b.name)),
+      };
+    });
+  }, []);
+
+  useEffect(() => {
+    let alive = true;
+    setLoading(true);
+    setError(null);
+    query(null).then(
+      (r) => {
+        if (!alive) return;
+        setItems(r.items);
+        setCursor(r.next_cursor);
+        absorb(r.items);
+        setLoading(false);
+      },
+      (e) => {
+        if (!alive) return;
+        setItems([]);
+        setCursor(null);
+        setError(e as ApiError);
+        setLoading(false);
+      },
+    );
+    return () => {
+      alive = false;
+    };
+  }, [query, absorb]);
+
+  const loadMore = async () => {
+    if (!cursor) return;
+    setLoading(true);
+    setError(null);
+    try {
+      const r = await query(cursor);
+      setItems((s) => [...s, ...r.items]);
+      setCursor(r.next_cursor);
+      absorb(r.items);
+    } catch (e) {
+      setError(e as ApiError);
+    } finally {
+      setLoading(false);
+    }
+  };
+
+  const bind = (k: keyof typeof EMPTY_FILTER) => ({
+    value: draft[k],
+    onChange: (e: { target: { value: string } }) => setDraft((s) => ({ ...s, [k]: e.target.value })),
+  });
+
+  const clearAll = () => {
+    setDraft(EMPTY_FILTER);
+    setApplied(EMPTY_FILTER);
+  };
+
+  return (
+    <Shell
+      route="audit"
+      title="审计日志"
+      hint="只追加,不允许修改或删除。区域树维护记录仅总运营可见;其他角色只看本公司挂载与自身范围变更。可按对象类型/主体/操作人/时间区间与关键字检索,检索只在本人可见范围内收窄结果,不改写可见范围。"
+    >
+      <Panel
+        title={<>记录(可见范围 — 条,当前条件命中 — 条,已显示 {items.length} 条)</>}
+        note={
+          <>
+            记录只追加,本页没有新增/编辑/删除入口,也没有补录与改判入口。记录按时间倒序以游标分页逐批载入,只有「加载更多」,没有页码条与「跳至第 N
+            页」,也不显示总页数;检索在本人可见范围内收窄结果,条件之间取交集:主体定位只列本人可见范围内出现过的对象(原型以对象标识定位,正式系统按
+            {'{type,id}'}
+            定位,名称不参与范围判定);关键字只比对对象名称、操作人姓名与变更前后值,不比对操作类型;时间区间只填一端即只限制那一端。导出仅运营侧提供(运维团队、合伙人、运营商、客户四侧不提供导出入口),导出复用本人可见范围与当前检索条件,并把本次导出写入审计留痕——留痕只记筛选条件、导出行数与文件名,不写被导出行的内容。
+            <br />
+            本期取数口径:①面板头的「可见范围 N 条」「当前条件命中 M 条」——`audit/get_list@v1`⛔
+            下发可见范围总数与命中总数(只回 `items`+`next_cursor`),故显「—」,⛔ 以本页条数冒充;分页条同理只报「已显示
+            K 条」,不给「K / M」比值。②后端确实是游标分页,与原型同口径,故本页不套页码分页条。③<b>对象类型/主体定位/操作人</b>三个下拉项取自<b>当前可见行</b>(含本页已「加载更多」累加进来的行)去重,未做全库去重:库里存在但本批未出现的取值不会出现在下拉里,需要时先加载更多或清空条件。④操作人下拉按后端真有的
+            `actor_user_id` 取值(原型按姓名),后端⛔ 按姓名匹配;主体定位按 `{'{type,id}'}`
+            传参。⑤关键字后端命中口径为<b>操作人登录名或对象 ID</b>,与原型示意的「对象名称、操作人姓名与变更前后值」不完全一致。⑥时间区间沿用原型的自然日选择:起取所选当日
+            00:00、止取当日 23:59(送后端时精确到秒并带本地时区)。⑦<b>「导出当前结果」本期未开放</b>:`api/bos.ts` 没有审计导出接口,页面不放空壳按钮;原型是条件一改就即时过滤,本页条件要送后端才生效,故筛选条末格(原型摆导出按钮的那格)放「查询」。⑧后端⛔
+            开放「动作」维度筛选(无 `action` 入参),故不提供操作类型筛选;原型按身份追加的范围时间性说明句后端也未下发,未呈现。
+          </>
+        }
+      >
+        <div className="filters">
+          <Field label="对象类型">
+            <select {...bind("object_type")}>
+              <option value="">全部</option>
+              {seen.types.map((t) => (
+                <option key={t} value={t}>
+                  {t}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="主体定位">
+            <select {...bind("object_ref")}>
+              <option value="">全部对象</option>
+              {seen.refs.map((r) => (
+                <option key={refValue(r.type, r.id)} value={refValue(r.type, r.id)}>
+                  {r.id}({r.type})
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="操作人">
+            <select {...bind("actor_user_id")}>
+              <option value="">全部</option>
+              {seen.actors.map((a) => (
+                <option key={a.id} value={a.id}>
+                  {a.name}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="时间区间(起)">
+            <input type="date" {...bind("occurred_from")} />
+          </Field>
+          <Field label="时间区间(止)">
+            <input type="date" {...bind("occurred_to")} />
+          </Field>
+          <Field label="关键字">
+            <input type="text" {...bind("keyword")} placeholder="只比对对象名称、操作人姓名与变更前后值" />
+          </Field>
+          <Field label={"\u00A0"}>
+            <Btn ghost onClick={clearAll}>
+              清除条件
+            </Btn>
+          </Field>
+          {/* 原型这一格是主按钮「导出当前结果」(本期无接口),条件要送后端才生效,故把「查询」放同一位置 */}
+          <Field label={"\u00A0"}>
+            <Btn onClick={() => setApplied({ ...draft })}>查询</Btn>
+          </Field>
+        </div>
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && items.length === 0 ? <Loading /> : null}
+        {items.length > 0 || (!loading && !error) ? (
+          <table>
+            <thead>
+              <tr>
+                <th>时间</th>
+                <th>操作人</th>
+                <th>操作类型</th>
+                <th>对象</th>
+                <th>变更前</th>
+                <th>变更后</th>
+              </tr>
+            </thead>
+            <tbody>
+              {items.map((r) => {
+                const ts = r.occurred_at ? datetime(r.occurred_at) : "";
+                return (
+                  <tr key={r.cursor}>
+                    <td>
+                      {ts ? ts.slice(0, 10) : "—"}
+                      <br />
+                      <span className="note">{ts ? ts.slice(11) || "—" : "—"}</span>
+                    </td>
+                    <td>
+                      <Cell v={r.actor?.username} />
+                      <br />
+                      <span className="note">{r.actor?.user_id || "—"}</span>
+                    </td>
+                    <td>
+                      <Cell v={label(ACTION_AUDIT, r.action)} />
+                    </td>
+                    <td>
+                      <Cell v={r.object?.id} />
+                      <br />
+                      <span className="note">{label(TARGET_TYPE, r.object?.type) || "—"}</span>
+                    </td>
+                    <td className="wrap">
+                      <Snapshot v={r.before} />
+                    </td>
+                    <td className="wrap">
+                      <Snapshot v={r.after} />
+                    </td>
+                  </tr>
+                );
+              })}
+              {!items.length ? (
+                <tr>
+                  <td colSpan={6}>可见范围内暂无记录</td>
+                </tr>
+              ) : null}
+            </tbody>
+          </table>
+        ) : null}
+        {cursor ? (
+          <div className="pager">
+            <span className="note">游标分页:已显示 {items.length} 条,⛔ 不提供「跳至第 N 页」</span>
+            <span className="pgs">
+              <button className="pg" disabled={loading} onClick={() => void loadMore()}>
+                {loading ? "加载中…" : "加载更多"}
+              </button>
+            </span>
+          </div>
+        ) : items.length > 0 ? (
+          <p className="note">游标分页:已显示全部 {items.length} 条</p>
+        ) : null}
+      </Panel>
+    </Shell>
+  );
+}
+
+/**
+ * 变更前后快照:原型 `td.wrap` 就是一段行内文本(`${esc(l.before) || "—"}`),⛔ 摘要成「有变更」
+ * 之类的猜测文案,也⛔ 另起 details/pre 容器(`.wrap` 本身已 `white-space:normal` 负责折行)。
+ */
+function Snapshot({ v }: { v: unknown }) {
+  if (v === null || v === undefined || v === "") return <>—</>;
+  return <>{typeof v === "string" ? v : JSON.stringify(v)}</>;
+}

+ 913 - 0
front-end/src/pages/CustomerDetailPage.tsx

@@ -0,0 +1,913 @@
+import { useState, type ReactNode } from "react";
+import { useNavigate, useParams } from "react-router-dom";
+import { useSession } from "../auth/session";
+import { ACCT_STATUS, SUBJECT_TYPE, label } from "../api/labels";
+import {
+  customerAttributionUpdate,
+  customerDelete,
+  customerDeletePrecheck,
+  customerGet,
+  customerHistory,
+  customerInfluence,
+  customerMoveRegion,
+  customerUpdate,
+  operatorGetList,
+  opsTeamGetList,
+  partnerGetList,
+  regionTree,
+  subAccountGetList,
+  subAccountUpdate,
+  subscriptionGetList,
+} from "../api/bos";
+import type { SubAccountRow } from "../api/types";
+import {
+  Btn,
+  Cell,
+  Drawer,
+  ErrorBox,
+  Field,
+  Loading,
+  Modal,
+  Note,
+  Notice,
+  Panel,
+  Pill,
+  QTip,
+  datetime,
+  money,
+  seq,
+  useToast,
+} from "../components/ui";
+import { useLoad, useForm, useSubmit } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+/** 档案页下方三张子表一次取一页(原型这些表格不分页)。 */
+const SUB_PAGE_SIZE = 50;
+
+/* ── 以下说明逐字照抄 prototype/app.js:IDNO_TIP/SUB_STATUS_TIP/idNoLabel/materialsText/
+   masterPanel 的 note/下属分账号的 note/归属与挂载的两条 note/STOP_TYPE/CLAIM_DAYS_DEFAULT ── */
+
+const IDNO_TIP = (
+  <>
+    客户建档、查重与跨系统匹配的唯一依据:企业取统一社会信用代码,个人与个体工商户取身份证号。
+    <br />
+    列表默认掩码展示(企业留前后各 4 位,个人留前 6 位与末 4 位),完整值只在客户详情、编辑弹窗与导出文件里出现。
+    <br />
+    <b>客户名称允许重名</b>
+    ,不作唯一键与匹配条件;按名称查到的同名客户请以识别号区分。
+  </>
+);
+
+const SUB_STATUS_TIP = (
+  <>
+    <b>待生效</b>:订阅已建立,未到合同生效日。
+    <br />
+    <b>生效中</b>:已到合同生效日,且未到订阅结束日。
+    <br />
+    <b>已到期</b>:已过订阅结束日,应收停算。
+    <br />
+    本列只由合同生效日与结束日推导,不表示网络侧已开通:网络侧是否开通看「实际开通日」与客户服务开通状态,尚未开通的日子不计应收。
+  </>
+);
+
+/** 原型 idNoLabel(subject):企业取统一社会信用代码,其余取身份证号。 */
+const idNoLabel = (subjectCn: string) => (subjectCn ? (subjectCn === "企业" ? "统一社会信用代码" : "身份证号") : "—");
+/** 原型 materialsText(subject):主体类型对应的应备材料清单。 */
+const materialsText = (subjectCn: string) =>
+  subjectCn === "企业"
+    ? "营业执照、客户名称、统一社会信用代码、经办联系人、地址、合同、电话"
+    : "身份证、姓名、身份证号、手机号、地址";
+
+const STOP_TYPE = "服务停用";
+const CLAIM_DAYS_DEFAULT = 7;
+
+type Sheet = "influence" | null;
+type ModalKind = "update" | "move" | "attribution" | "subedit" | "delete" | null;
+
+export function CustomerDetailPage() {
+  const { id = "" } = useParams();
+  const nav = useNavigate();
+  const toast = useToast();
+  const { ctx } = useSession();
+  /* 原型 isAdmin/isAdminLike:客户档案的归属与挂载、主账号、分账号编辑只对运营侧开放 */
+  const isAdmin = ctx?.role_code === "admin";
+  const adminLike = isAdmin || ctx?.role_code === "opsMain" || ctx?.role_code === "opsSub";
+
+  const [sheet, setSheet] = useState<Sheet>(null);
+  const [modal, setModal] = useState<ModalKind>(null);
+  const [teamsSel, setTeamsSel] = useState<string[]>([]);
+  const [subRow, setSubRow] = useState<SubAccountRow | null>(null);
+  const sub = useSubmit();
+  const form = useForm();
+
+  const detail = useLoad(() => customerGet({ customer_id: id }), [id]);
+  const accts = useLoad(
+    () => subAccountGetList({ customer_id: id, page: 0, page_size: SUB_PAGE_SIZE }),
+    [id],
+  );
+  const subs = useLoad(
+    () => subscriptionGetList({ customer_id: id, page: 0, page_size: SUB_PAGE_SIZE }),
+    [id],
+  );
+  const hist = useLoad(
+    () => customerHistory({ customer_id: id, page: 0, page_size: SUB_PAGE_SIZE }),
+    [id],
+  );
+  const ops = useLoad(() => operatorGetList({ page: 0, page_size: 200 }), []);
+  const pts = useLoad(() => partnerGetList({ page: 0, page_size: 200 }), []);
+  const teams = useLoad(() => opsTeamGetList({ page: 0, page_size: 200 }), []);
+  const tree = useLoad(() => regionTree(), []);
+
+  const close = () => {
+    setModal(null);
+    setSubRow(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const submit = async () => {
+    if (!modal) return;
+    const ok = await sub.run(() => {
+      if (modal === "update")
+        return customerUpdate({
+          customer_id: id,
+          customer_name: form.get("customer_name") || undefined,
+          id_code: form.get("id_code") || undefined,
+          change_basis: form.get("change_basis") || undefined,
+          contact_name: form.get("contact_name") || undefined,
+          contact_mobile: form.get("contact_mobile") || undefined,
+          address: form.get("address") || undefined,
+        });
+      if (modal === "move")
+        return customerMoveRegion({
+          customer_id: id,
+          new_region_node_id: form.get("new_region_node_id"),
+          ops_team_ids: teamsSel,
+        });
+      if (modal === "attribution")
+        return customerAttributionUpdate({
+          customer_id: id,
+          operator_id: form.get("operator_id") || undefined,
+          partner_id: form.get("partner_id") || undefined,
+        });
+      if (modal === "subedit" && subRow)
+        return subAccountUpdate({
+          sub_account_id: subRow.sub_account_id,
+          display_name: form.get("display_name") || undefined,
+          network_account_name: form.get("net_account") || undefined,
+        });
+      return customerDelete({ customer_id: id, precheck_version: form.get("precheck_version") || undefined });
+    });
+    if (!ok) return;
+    toast("已提交");
+    close();
+    detail.reload();
+    accts.reload();
+  };
+
+  const askDelete = async () => {
+    form.reset();
+    setModal("delete");
+    await sub.run(async () => {
+      const pre = await customerDeletePrecheck({ customer_id: id });
+      form.set("precheck_version", pre.precheck_version);
+      if (!pre.can_delete)
+        throw Object.assign(new Error(`不可删除:${pre.blocked.join(";") || "见阻塞清单"}`), { code: null });
+    });
+  };
+
+  const c = detail.data?.customer;
+  const subjectCn = c ? label(SUBJECT_TYPE, c.subject_type) : "";
+  const mounts = detail.data?.region_mounts ?? [];
+  const teamIds = detail.data?.team_ids ?? [];
+  const teamName: Record<string, string> = {};
+  (teams.data?.items ?? []).forEach((t) => {
+    teamName[t.team_id] = t.team_name;
+  });
+  const acctItems = accts.data?.items ?? [];
+  const acctUsed = detail.data?.sub_account_count ?? accts.data?.total ?? 0;
+  const acctInUse = acctItems.filter((a) => label(ACCT_STATUS, a.status) === "使用中").length;
+  const quotaText = c?.quota_cents ? money(Number(c.quota_cents)) : "";
+  const subRows = acctItems;
+  const subList = subs.data?.items ?? [];
+
+  return (
+    <Shell
+      route="customers"
+      title={c?.customer_name ?? "客户档案"}
+      hint={`${c?.customer_id ?? id} · ${subjectCn || "—"} · 电话 — · 材料只接受运营商提供`}
+      actions={
+        <>
+          <Btn ghost onClick={detail.reload}>
+            刷新
+          </Btn>
+          <Btn ghost onClick={() => nav("/customers")}>
+            返回列表
+          </Btn>
+          <Btn ghost onClick={() => setSheet("influence")}>
+            改挂影响面
+          </Btn>
+          <Btn
+            onClick={() => {
+              form.reset({
+                customer_name: c?.customer_name ?? "",
+                id_code: "",
+                change_basis: "",
+                contact_name: "",
+                contact_mobile: "",
+                address: "",
+              });
+              setModal("update");
+            }}
+          >
+            编辑
+          </Btn>
+        </>
+      }
+    >
+      {detail.error ? <ErrorBox error={detail.error} /> : null}
+      {detail.loading ? <Loading /> : null}
+      {detail.data && !c ? (
+        <Notice tone="warn">
+          后端 <code>customer/get</code> 本期只回显 <code>customer_id</code>(待实现),主体卡片与归属块按原型保留列位显示
+          「—」,⛔ 猜测填充;下方分账号、订阅、变更历史各自走自己的接口,仍显示真实数据。
+        </Notice>
+      ) : null}
+
+      {/* ── 概览卡片(原型 pageEnterprise 的 .cards,七块同序)────────────────── */}
+      <div className="cards">
+        <div className="card">
+          <span>状态</span>
+          <b>
+            <Cell v={c ? label(ACCT_STATUS, c.acct_status) : null} />
+          </b>
+        </div>
+        <div className="card">
+          <span>
+            客户识别号({idNoLabel(subjectCn)})
+            <QTip>{IDNO_TIP}</QTip>
+          </span>
+          <b style={{ fontSize: 15 }}>
+            <Cell v={null} />
+          </b>
+        </div>
+        <div className="card">
+          <span>所属区域</span>
+          <b style={{ fontSize: 15 }}>
+            {mounts.length ? mounts.map((m) => m.parent_node_id).join("、") : <Cell v={null} />}
+          </b>
+        </div>
+        <div className="card">
+          <span>运营商 / 合伙人</span>
+          <b style={{ fontSize: 15 }}>
+            <Cell v={c?.operator_name} /> / <Cell v={c?.partner_name} />
+          </b>
+        </div>
+        <div className="card">
+          <span>分账号</span>
+          <b>
+            {acctUsed} / 额度 <Cell v={quotaText} /> · 在用 {acctInUse}
+          </b>
+        </div>
+        <div className="card">
+          <span>经办联系人 / 联系电话</span>
+          <b style={{ fontSize: 15 }}>
+            <Cell v={null} /> / <Cell v={null} />
+          </b>
+        </div>
+        <div className="card" style={{ gridColumn: "1 / -1" }}>
+          <span>地址(运营商可核查,用于资源核查与现场施工定位)</span>
+          <b style={{ fontSize: 15 }}>
+            <Cell v={null} />
+          </b>
+        </div>
+      </div>
+      <Note>
+        卡片取数口径:<code>customer/get</code> 本期只下发 customer_name/subject_type/acct_status/quota_cents/
+        operator/partner/created_at。「客户识别号」「经办联系人 / 联系电话」「地址」⛔ 数据源,按原型保留卡片显示「—」;
+        「所属区域」只有 <code>region_mounts[].parent_node_id</code>——资源树接口本期只下发可见节点 ID,
+        节点名称与层级⛔ 由本系统维护;「额度」取 <code>quota_cents</code>(单位为分,页面按金额展示,
+        与原型「分账号额度数」口径不同,如实标注)。
+      </Note>
+
+      {/* ── 归属与挂载(原型 adminAttrs)────────────────────────────────────── */}
+      {adminLike ? (
+        <Panel
+          title={`归属与挂载${isAdmin ? "(总运营)" : "(负责范围内)"}`}
+          note={
+            <>
+              区域与承接团队走 <code>customer/move_region</code>(复合事务,新区域省份须等于归属运营商档案省份);
+              运营商与合伙人走 <code>customer/attribution/update</code>,留空的字段表示不改。
+              区域下拉只能列出 <code>region/tree</code> 的可见 <code>node_ids</code>(节点名称与层级⛔ 由本系统维护),
+              团队名称现取 <code>ops_team/get_list</code>,取不到时按 <code>team_id</code> 原值显示。
+            </>
+          }
+        >
+          <Note>
+            变更保留历史与审计日志;已生成的账单明细仍指向变更前对象,下一个自然月的对账才用新对象。
+            分成随团队变化,不随工单责任人变化。
+          </Note>
+          {!isAdmin ? (
+            <Note>
+              运营商、合伙人和运维团队的下拉只列出您负责范围内的对象;客户原本挂着的合伙人建档在范围外时,
+              下拉里保留这一项并标注「建档区域在负责范围外」,只能原样保留或改成范围内的对象,不能另选其他范围外对象。
+            </Note>
+          ) : null}
+          <div className="form-grid">
+            <div>
+              <label>所属区域</label>
+              <div style={{ padding: "6px 0" }}>
+                {mounts.length ? (
+                  mounts.map((m) => (
+                    <span key={m.hierarchy_id} className="code-chip" style={{ marginRight: 6 }}>
+                      {m.parent_node_id}
+                    </span>
+                  ))
+                ) : (
+                  <Cell v={null} />
+                )}
+                <div className="note">挂载记录 {mounts.length} 条 · 终态 {mounts.map((m) => m.terminal_state).join("、") || "—"}</div>
+              </div>
+            </div>
+            <div>
+              <label>运营商(唯一)</label>
+              <div style={{ padding: "6px 0" }}>
+                <Cell v={c?.operator_name} />
+                <div className="note">
+                  <span className="code-chip">{c?.operator_id ?? "—"}</span>
+                </div>
+              </div>
+            </div>
+            <div>
+              <label>合伙人(可空)</label>
+              <div style={{ padding: "6px 0" }}>
+                <Cell v={c?.partner_name} />
+                <div className="note">
+                  <span className="code-chip">{c?.partner_id ?? "—"}</span>
+                </div>
+              </div>
+            </div>
+            <div style={{ gridColumn: "1 / -1" }}>
+              <label>
+                运维团队<span className="req">*</span>(可多支,勾选)
+              </label>
+              <div className="row" style={{ flexWrap: "wrap", padding: "6px 0" }}>
+                {teamIds.length ? (
+                  teamIds.map((t) => (
+                    <span key={t} className="code-chip" style={{ marginRight: 6 }}>
+                      {teamName[t] ?? t}
+                    </span>
+                  ))
+                ) : (
+                  <Cell v={null} />
+                )}
+              </div>
+              <Note>
+                工单按「哪支团队声明承接该工单类型」落团队;多支团队都承接同一类型时,由承接类型更少(更专精)的那支优先,
+                例如开户会先落到只接开户的那支团队。客户名下某类型工单若没有挂接团队承接,工单仍会建出并留在第一支团队待派单。
+              </Note>
+            </div>
+          </div>
+          <div className="form-actions">
+            <div className="row">
+              <Btn
+                onClick={() => {
+                  form.reset({ operator_id: "", partner_id: "" });
+                  setModal("attribution");
+                }}
+              >
+                保存归属变更(运营商 / 合伙人)
+              </Btn>
+              <Btn
+                ghost
+                onClick={() => {
+                  form.reset({ new_region_node_id: mounts[0]?.parent_node_id ?? "" });
+                  setTeamsSel(teamIds);
+                  setModal("move");
+                }}
+              >
+                改挂区域 / 承接团队
+              </Btn>
+              <Btn danger onClick={() => void askDelete()}>
+                删除客户
+              </Btn>
+            </div>
+          </div>
+        </Panel>
+      ) : null}
+
+      {/* ── 客户主账号(原型 masterPanel)────────�──────────────────────────── */}
+      {adminLike ? (
+        <Panel title="客户主账号(客户自己的登录账号 · 一个客户最多一个)">
+          <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
+            <div>
+              主账号登录名:
+              <Cell v={null} />
+              <br />
+              <span className="note">激活状态:</span>
+              <Cell v={null} />
+            </div>
+            <div className="row">
+              <Btn ghost disabled title="重置激活码走 account/reset_code,需 user_id;customer/get 本期不下发主账号 user_id">
+                重置激活码
+              </Btn>
+              <Btn ghost disabled title="模拟客户激活属客户侧免登录激活页行为,⛔ 本系统实现">
+                模拟客户激活
+              </Btn>
+              <Btn ghost disabled title="账号开通管线 account/provision 需 username+role_code+subject 等参数,本页面无数源,请到「账号管理」办理">
+                开通账号
+              </Btn>
+            </div>
+          </div>
+          <Notice tone="warn">
+            主账号登录名、激活状态与激活码发出时间⛔ 接口数源(<code>customer/get</code> 只回档案字段,
+            账号侧字段属第 1 册账号接口),按原型保留本块显示「—」,⛔ 用「未激活」等默认值冒充。
+          </Notice>
+          <Note>
+            只用于管理本主体的订阅(含历史订阅)、下属分账号与账单,网络权益不在本账号上使用,也不占套餐的分账号额度。
+            人工页面建档可录初始密码(选填):录了即当场开通可登录主账号,密码只在当次操作结果里显示一次、由操作人线下告知本人,
+            下次登录须改密;留空则建档时生成一次性激活码(10 位),有效期自发放当天起算,采用平台引导凭证 TTL(activate 默认{" "}
+            {CLAIM_DAYS_DEFAULT} 天)。系统自动建档(运营商接口同步开户、批量导入、存量补号)⛔ 不接受初始密码、一律发激活码。
+            激活码不经短信、邮件或站内消息投递,由运营在客户管理页导出后线下交给客户,导出不重新起算有效期。
+            客户在免登录的激活页凭码自设密码后才能登录;未设密不放行。凭证过期后在客户管理页再次导出时系统会自动换新码,
+            新 TTL 自换码日起算。重置激活码会让原码立即作废并重发新码,TTL 自重置当日重算,已激活的账号重置后需重新走一遍激活。
+            绑定手机号后可用手机号代替登录名登录。客户改名不改登录名,也不重发激活码。
+          </Note>
+        </Panel>
+      ) : null}
+
+      {/* ── 全部订阅(原型订阅 panel)───────────────────────────────────────── */}
+      <Panel
+        title={
+          adminLike
+            ? "全部订阅(后台保留升降配/叠加全部记录)"
+            : "当前生效套餐(客户侧「我的套餐」另列待生效与往期套餐)"
+        }
+        extra={
+          <>
+            <Btn warn disabled title="发起服务停用要建工单,工单接口属第 2 册,本期未接入">
+              发起服务停用
+            </Btn>
+            <Btn disabled title="订阅的新增/升降配/叠加走 subscription/create 等接口,本期后端未实现">
+              套餐订阅管理
+            </Btn>
+          </>
+        }
+        note={
+          <>
+            订阅取 <code>subscription/get_list</code>(按 customer_id 过滤,{SUB_PAGE_SIZE} 条一页)。「线路出口」{" "}
+            <code>subscription/exit/list</code> 本期未接入、「方式」需升降配来源与叠加标记(接口只回{" "}
+            <code>replaces_subscription_id</code>,⛔ 据此推断新购/升降配)、「实际开通日」是网络侧开通日,
+            接口的 <code>effective_date</code>/<code>expire_date</code> 是合同推导日期、口径不同,三列均显示「—」。
+            「订阅状态」显示 <code>status</code> 经 <code>labels.ts</code> 后的原值。
+          </>
+        }
+      >
+        {subs.error ? <ErrorBox error={subs.error} /> : null}
+        {subs.loading ? <Loading /> : null}
+        <table>
+          <thead>
+            <tr>
+              <th>序号</th>
+              <th>套餐 / 合同</th>
+              <th>线路出口</th>
+              <th>方式</th>
+              <th>
+                订阅状态
+                <QTip>{SUB_STATUS_TIP}</QTip>
+              </th>
+              <th>合同期间</th>
+              <th>实际开通日</th>
+              <th>月结算标准</th>
+            </tr>
+          </thead>
+          <tbody>
+            {subList.length ? (
+              subList.map((s, i) => (
+                <tr key={s.subscription_id}>
+                  <td>{seq(1, SUB_PAGE_SIZE, i)}</td>
+                  <td>
+                    <Cell v={s.plan_name} />
+                    <br />
+                    <span className="note">
+                      合同 <Cell v={s.contract_id} />
+                    </span>
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>
+                    <Pill text={s.status || "—"} />
+                  </td>
+                  <td>
+                    {s.start_date || s.end_date ? `${s.start_date ?? "—"} 至 ${s.end_date ?? "—"}` : <Cell v={null} />}
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>{money(s.monthly_settle_cents)}</td>
+                </tr>
+              ))
+            ) : (
+              <tr>
+                <td colSpan={8}>{subs.loading ? "加载中…" : "该客户还没有订阅记录"}</td>
+              </tr>
+            )}
+          </tbody>
+        </table>
+      </Panel>
+
+      {/* ── 下属分账号(原型同名 panel)────────────────────────────────────── */}
+      <Panel title="下属分账号(分账号数量与套餐额度自动对齐 · 账号名 = 客户主账号 - 序号)">
+        {accts.error ? <ErrorBox error={accts.error} /> : null}
+        {accts.loading ? <Loading /> : null}
+        <table>
+          <thead>
+            <tr>
+              <th>序号</th>
+              <th>账号名</th>
+              <th>姓名</th>
+              <th>网络侧账号名(零信任客户端)</th>
+              <th>状态</th>
+              <th>开通日</th>
+              <th>计费</th>
+              {adminLike ? <th>操作</th> : null}
+            </tr>
+          </thead>
+          <tbody>
+            {subRows.length ? (
+              subRows.map((a, i) => (
+                <tr key={a.sub_account_id}>
+                  <td>{seq(1, SUB_PAGE_SIZE, i)}</td>
+                  <td>
+                    <Cell v={a.username} />
+                  </td>
+                  <td>
+                    <Cell v={a.display_name} />
+                  </td>
+                  <td>{a.net_account ? a.net_account : <span className="note">未绑定</span>}</td>
+                  <td>
+                    <Pill text={label(ACCT_STATUS, a.status)} />
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>
+                    {label(ACCT_STATUS, a.status) === "已停用"
+                      ? "停用后不计(到期停机或服务停用回填后)"
+                      : "应收随订阅出账,不单独计费"}
+                  </td>
+                  {adminLike ? (
+                    <td>
+                      <Btn
+                        ghost
+                        onClick={() => {
+                          setSubRow(a);
+                          form.reset({ display_name: a.display_name ?? "", net_account: a.net_account ?? "" });
+                          setModal("subedit");
+                        }}
+                      >
+                        编辑
+                      </Btn>
+                    </td>
+                  ) : null}
+                </tr>
+              ))
+            ) : (
+              <tr>
+                <td colSpan={adminLike ? 8 : 7}>{accts.loading ? "加载中…" : "该客户还没有下属分账号"}</td>
+              </tr>
+            )}
+          </tbody>
+        </table>
+        <Note>
+          分账号 {acctUsed} / 额度 <Cell v={quotaText} />。数量由套餐额度决定:订阅建立、升降配或叠加后,
+          系统按未到期订阅的额度之和自动补建,不部分开通,也不提供手工新增;账号名取「客户主账号登录名 - 序号」,序号从 1 起,
+          同一客户共用一个序号池。开户和订阅仍是两步:开户时可以一个分账号都不开通,额度回落时不删号,
+          超出额度的在用分账号随到期停机一并改为停用。姓名建号时留空为「席位 n」
+          {adminLike ? ",点行尾「编辑」改写" : ""};客户主账号只能在自己的「下属分账号」页改下属号姓名,
+          客户侧不提供账号停用入口(2026-11-02 定案),要停号由运营发起{STOP_TYPE}工单;网络侧账号名即零信任客户端的账号名,
+          选填、可改、不做唯一性校验,用于开停机回填时与网络侧账号一一对应。
+          <br />
+          本表取数口径:「账号名」取 <code>sub_account/get_list</code> 的 <code>username</code>,「姓名」取{" "}
+          <code>display_name</code>,「网络侧账号名」取 <code>net_account</code>;「开通日」⛔ 数据源(接口只下发{" "}
+          <code>created_at</code> 建档时间,不等同于网络侧开通日),显示「—」;行尾「编辑」写 <code>display_name</code> 与{" "}
+          <code>network_account_name</code>,⛔ 改登录名。
+        </Note>
+      </Panel>
+
+      {/* ── 登记材料与合同(原型 filesPanel)──────────────────────────────── */}
+      <Panel title="登记材料与合同(对象存储只存键,浏览器直传)">
+        <Note>
+          应备材料:{materialsText(subjectCn)}。材料只接受运营商提供。清单只显示文档名,对象存储全键留在后台,鼠标悬停可查。
+        </Note>
+        <Notice tone="warn">
+          材料清单与合同文件本期⛔ 接口数源(对象存储文件接口未实现,<code>customer/get</code> 不下发 files/materials),
+          本块不列清单,也⛔ 用「尚未上传登记材料」「该客户还没有合同文件」冒充已查过的结论;
+          合同文件按原型挂在订阅上,合同编号见上方「套餐 / 合同」列。
+        </Notice>
+      </Panel>
+
+      {/* ── 归属与状态变更历史(原型同名 panel)────────────────────────────── */}
+      <Panel
+        title="归属与状态变更历史"
+        note={
+          <>
+            取 <code>customer/history</code>(分页,本页取 {SUB_PAGE_SIZE} 条)。后端一次改动按字段拆成多行下发
+            (changed_at/field_key/old_value/new_value/operator),故「字段」列下方附{" "}
+            <code>change_basis</code>(变更依据)与 <code>source</code>(来源)原值,⛔ 与原型表头另起新列。
+          </>
+        }
+      >
+        {hist.error ? <ErrorBox error={hist.error} /> : null}
+        {hist.loading ? <Loading /> : null}
+        <table>
+          <thead>
+            <tr>
+              <th>时间</th>
+              <th>字段</th>
+              <th>变更前</th>
+              <th>变更后</th>
+              <th>操作人</th>
+            </tr>
+          </thead>
+          <tbody>
+            {hist.data?.items.length ? (
+              hist.data.items.map((r, i) => (
+                <tr key={`${r.changed_at ?? ""}#${r.field_key ?? ""}#${i}`}>
+                  <td>{datetime(r.changed_at)}</td>
+                  <td>
+                    {r.field_key}
+                    <br />
+                    <span className="note">
+                      依据 <Cell v={r.change_basis} /> · 来源 <Cell v={r.source} />
+                    </span>
+                  </td>
+                  <td className="wrap">
+                    <Cell v={r.old_value} />
+                  </td>
+                  <td className="wrap">
+                    <Cell v={r.new_value} />
+                  </td>
+                  <td>
+                    <Cell v={r.operator} />
+                  </td>
+                </tr>
+              ))
+            ) : (
+              <tr>
+                <td colSpan={5}>{hist.loading ? "加载中…" : "暂无"}</td>
+              </tr>
+            )}
+          </tbody>
+        </table>
+      </Panel>
+
+      {modal === "update" ? (
+        <WriteModal title="编辑客户" sub={sub} onClose={close} onSubmit={() => void submit()}>
+          <Field label="客户名称">
+            <input {...form.bind("customer_name")} />
+          </Field>
+          <Field label="统一识别号" hint="改动须同时填变更依据">
+            <input {...form.bind("id_code")} />
+          </Field>
+          <Field label="变更依据">
+            <input {...form.bind("change_basis")} />
+          </Field>
+          <Field label="联系人">
+            <input {...form.bind("contact_name")} />
+          </Field>
+          <Field label="联系电话">
+            <input {...form.bind("contact_mobile")} />
+          </Field>
+          <Field label="地址">
+            <input {...form.bind("address")} />
+          </Field>
+        </WriteModal>
+      ) : null}
+
+      {modal === "attribution" ? (
+        <WriteModal title="保存归属变更(运营商 / 合伙人)" sub={sub} onClose={close} onSubmit={() => void submit()}>
+          <Notice tone="warn">
+            写侧走 <code>customer/attribution/update</code>;下拉取 <code>operator/get_list</code>/{" "}
+            <code>partner/get_list</code> 的真实名称(各取 200 条),留空表示该字段不改。后端拒绝时如实显示{" "}
+            <code>code</code>+<code>error_code</code>。
+          </Notice>
+          <Field label="运营商(唯一)" hint="留空表示不改">
+            <select {...form.bind("operator_id")}>
+              <option value="">不改</option>
+              {(ops.data?.items ?? []).map((o) => (
+                <option key={o.operator_id} value={o.operator_id}>
+                  {o.name}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="合伙人(可空)" hint="留空表示不改">
+            <select {...form.bind("partner_id")}>
+              <option value="">不改</option>
+              {(pts.data?.items ?? []).map((p) => (
+                <option key={p.partner_id} value={p.partner_id}>
+                  {p.name}
+                </option>
+              ))}
+            </select>
+          </Field>
+        </WriteModal>
+      ) : null}
+
+      {modal === "move" ? (
+        <WriteModal title="改挂区域 / 承接团队" sub={sub} onClose={close} onSubmit={() => void submit()}>
+          <Notice tone="warn">
+            改挂区域走平台资源树、改承接链走本地写侧(复合事务,新区域省份须等于归属运营商档案省份);
+            后端拒绝时如实显示 <code>code</code>+<code>error_code</code>。
+          </Notice>
+          <Field label="新区域节点" hint="region/tree 本期只下发可见 node_id,节点名称与层级⛔ 由本系统维护">
+            <select {...form.bind("new_region_node_id")}>
+              <option value="">请选择</option>
+              {(tree.data?.node_ids ?? []).map((n) => (
+                <option key={n} value={n}>
+                  {n}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="运维团队(可多支,勾选)">
+            <div className="row" style={{ flexWrap: "wrap" }}>
+              {(teams.data?.items ?? []).map((t) => (
+                <label key={t.team_id} style={{ display: "flex", gap: 4, alignItems: "center" }}>
+                  <input
+                    type="checkbox"
+                    checked={teamsSel.includes(t.team_id)}
+                    onChange={(e) =>
+                      setTeamsSel((s) => (e.target.checked ? [...s, t.team_id] : s.filter((x) => x !== t.team_id)))
+                    }
+                  />
+                  {t.team_name}
+                  <span className="code-chip">{t.team_id}</span>
+                </label>
+              ))}
+              {!teams.data?.items.length ? <span className="note">ops_team/get_list 未返回可选团队</span> : null}
+            </div>
+          </Field>
+        </WriteModal>
+      ) : null}
+
+      {modal === "subedit" ? (
+        <WriteModal title={`编辑分账号 · ${subRow?.username ?? subRow?.sub_account_id ?? ""}`} sub={sub} onClose={close} onSubmit={() => void submit()}>
+          <Notice tone="warn">
+            写侧走 <code>sub_account/update</code>:运营可改「姓名」与「网络侧账号名」,登录名不可改。
+          </Notice>
+          <Field label="姓名">
+            <input {...form.bind("display_name")} />
+          </Field>
+          <Field label="网络侧账号名(零信任客户端)" hint="选填、可改、不做唯一性校验">
+            <input {...form.bind("net_account")} />
+          </Field>
+        </WriteModal>
+      ) : null}
+
+      {modal === "delete" ? (
+        <WriteModal title="删除客户" sub={sub} onClose={close} onSubmit={() => void submit()}>
+          <Notice tone="warn">
+            删除前置检查与删除动作均由后端执行(可判定项逐条实查,缺数源项⛔ 当作「没有依赖」)。
+            下方阻塞快照版本由后端返回后自动带入,⛔ 自行伪造。
+          </Notice>
+          <Field label="阻塞快照版本">
+            <input {...form.bind("precheck_version")} readOnly />
+          </Field>
+        </WriteModal>
+      ) : null}
+
+      {sheet === "influence" ? (
+        <Drawer title="改挂影响面" onClose={() => setSheet(null)}>
+          <InfluenceBody customerId={id} />
+        </Drawer>
+      ) : null}
+    </Shell>
+  );
+}
+
+function WriteModal({
+  title,
+  sub,
+  onClose,
+  onSubmit,
+  children,
+}: {
+  title: string;
+  sub: ReturnType<typeof useSubmit>;
+  onClose: () => void;
+  onSubmit: () => void;
+  children: ReactNode;
+}) {
+  return (
+    <Modal title={title} onClose={onClose}>
+      <div className="form-grid">
+        {children}
+        <div className="form-actions">
+          {sub.error ? <ErrorBox error={sub.error} /> : null}
+          <div className="row">
+            <Btn onClick={onSubmit} disabled={sub.busy}>
+              {sub.busy ? "提交中…" : "提交"}
+            </Btn>
+            <Btn ghost onClick={onClose}>
+              取消
+            </Btn>
+          </div>
+        </div>
+      </div>
+    </Modal>
+  );
+}
+
+function InfluenceBody({ customerId }: { customerId: string }) {
+  const inf = useSubmit();
+  const [data, setData] = useState<Awaited<ReturnType<typeof customerInfluence>> | null>(null);
+  return (
+    <>
+      <div className="row">
+        <Btn
+          disabled={inf.busy}
+          onClick={() => void inf.run(async () => setData(await customerInfluence({ customer_id: customerId })))}
+        >
+          {inf.busy ? "计算中…" : "计算影响面"}
+        </Btn>
+      </div>
+      {inf.error ? <ErrorBox error={inf.error} /> : null}
+      {data ? (
+        <>
+          <div className="kv" style={{ marginTop: 12 }}>
+            <div>
+              <span className="k">当前归属运营商</span>
+              <Cell v={data.attribution?.operator_name ?? data.attribution?.operator_id ?? null} />
+            </div>
+            <div>
+              <span className="k">拓展合伙人</span>
+              <Cell v={data.attribution?.partner_name ?? data.attribution?.partner_id ?? null} />
+            </div>
+            <div>
+              <span className="k">账号开通状态</span>
+              <Cell v={data.attribution?.acct_status ?? null} />
+            </div>
+            <div>
+              <span className="k">承接团队</span>
+              <Cell
+                v={data.current_teams.length ? data.current_teams.map((t) => t.team_name ?? t.team_id) : null}
+              />
+            </div>
+            <div>
+              <span className="k">查询账期</span>
+              <Cell v={data.billing?.period_queried ?? null} />
+            </div>
+            <div>
+              <span className="k">本期出账快照/累计快照</span>
+              <span>
+                {data.billing?.snapshots_this_period ?? "—"} / {data.billing?.snapshots_total ?? "—"}
+              </span>
+            </div>
+          </div>
+          {data.influence_items.length ? (
+            <table style={{ marginTop: 12 }}>
+              <thead>
+                <tr>
+                  <th>影响项</th>
+                  <th className="num">数量</th>
+                  <th>说明</th>
+                </tr>
+              </thead>
+              <tbody>
+                {data.influence_items.map((r) => (
+                  <tr key={r.key}>
+                    <td>{r.label}</td>
+                    <td className="num">{r.count}</td>
+                    <td className="wrap">
+                      <Cell v={r.note} />
+                    </td>
+                  </tr>
+                ))}
+              </tbody>
+            </table>
+          ) : null}
+          {data.unverifiable_checks.length ? (
+            <Notice tone="warn">
+              <div>以下影响面本机数据源缺失,后端如实标为「不可判定」,⛔ 当成「无影响」:</div>
+              <ul style={{ margin: "6px 0 0", paddingLeft: 18 }}>
+                {data.unverifiable_checks.map((r) => (
+                  <li key={r.key}>
+                    <b>{r.label}</b>:{r.why}
+                  </li>
+                ))}
+              </ul>
+            </Notice>
+          ) : null}
+          {data.billing?.note ? <Notice tone="warn">{data.billing.note}</Notice> : null}
+          {data.message ? <div className="note">{data.message}</div> : null}
+        </>
+      ) : null}
+    </>
+  );
+}

+ 501 - 0
front-end/src/pages/CustomersPage.tsx

@@ -0,0 +1,501 @@
+import { useCallback, useMemo, useState } from "react";
+import { useNavigate } from "react-router-dom";
+import { ACCT_STATUS, SUBJECT_TYPE, label } from "../api/labels";
+import {
+  customerCreate,
+  customerDelete,
+  customerDeletePrecheck,
+  customerGetList,
+  customerUpdate,
+  operatorGetList,
+  opsTeamGetList,
+  partnerGetList,
+  regionTree,
+} from "../api/bos";
+import type { CustomerListRow } from "../api/types";
+import { useSession } from "../auth/session";
+import { Btn, Cell, Empty, ErrorBox, Field, Loading, Modal, Pager, Pill, QTip, seq } from "../components/ui";
+import { useForm, useLoad, useSubmit } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+const PAGE_SIZE = 20;
+
+/** 原型 `IDNO_TIP`(客户列表「主体/识别号」列头说明)。 */
+const IDNO_TIP =
+  "客户建档、查重与跨系统匹配的唯一依据:企业取统一社会信用代码,个人与个体工商户取身份证号。列表默认掩码展示(企业留前后各 4 位,个人留前 6 位与末 4 位),完整值只在客户详情、编辑弹窗与导出文件里出现。客户名称允许重名,不作唯一键与匹配条件;按名称查到的同名客户请以识别号区分。";
+
+/** 原型 `ENT_STATUS_TIP`(客户列表「状态」列头说明,原型该枚说明气泡朝左弹出)。 */
+const ENT_STATUS_TIP =
+  "未开通:客户档案与主账号已建立,网络侧尚未完成开通,订阅应收不计(开通后起算)。在用:已在网络侧开通,订阅应收从实际开通日起计费。停用:订阅已到期且到期停机已完成,或服务停用已回填成功,订阅应收停计。账号仍保留,仍可登录查看订阅、应收等历史记录,但不能继续使用订阅的权益;不是中途停户。";
+
+/** 原型 `ENT_SUBJECTS`(企业/个人/个体工商户)对应的后端 `subject_type` 码值。 */
+const SUBJECT_OPTS = [
+  ["enterprise", "企业"],
+  ["individual", "个人"],
+  ["sole_proprietor", "个体工商户"],
+] as const;
+
+/** 原型 `ENT_STATUSES`(未开通/在用/停用)对应的后端 `acct_status` 码值,选项文案取后端口径。 */
+const STATUS_OPTS = ["not_opened", "in_use", "stopped"] as const;
+
+/** 原型 `entFilter` 里后端真能承接的条件(区域与识别号两个条件见面板末「本页口径」)。 */
+const EMPTY_FILTER = { operator: "", partner: "", subject: "", status: "", name: "", no: "" };
+
+/**
+ * 客户管理(原型 `pageEnterprises`):面板内只有 `.filters` + `table.ent-list`+分页条,原型没有面板标题行、
+ * 没有 KPI 卡区,四个动作按钮全部走 `.filters` 里的按钮型 `.f-item`(`label` 为 `&nbsp;`)。
+ */
+export function CustomersPage() {
+  const nav = useNavigate();
+  const { ctx } = useSession();
+  // 原型 `isAdminLike(user())`:总运营/区域运营才有新增、编辑、删除与批量导入
+  const adminLike = ctx?.role_code === "admin" || ctx?.role_code === "opsMain" || ctx?.role_code === "opsSub";
+  const readOnlyViewer = ctx?.role_code === "partner" || ctx?.role_code === "operator";
+
+  const [draft, setDraft] = useState(EMPTY_FILTER);
+  const [applied, setApplied] = useState(EMPTY_FILTER);
+  const [page, setPage] = useState(1);
+
+  const params = useCallback(
+    () => ({
+      page: page - 1,
+      page_size: PAGE_SIZE,
+      keyword: applied.name || undefined,
+      subject_type: applied.subject || undefined,
+      acct_status: applied.status || undefined,
+      operator_id: applied.operator || undefined,
+      partner_id: applied.partner || undefined,
+    }),
+    [applied, page],
+  );
+
+  const { data, loading, error, reload } = useLoad(() => customerGetList(params()), [params]);
+  const { data: operatorsData } = useLoad(() => operatorGetList({ page: 0, page_size: 200 }), []);
+  const { data: partnersData } = useLoad(() => partnerGetList({ page: 0, page_size: 200 }), []);
+  const { data: teamsData } = useLoad(() => opsTeamGetList({ page: 0, page_size: 200 }), []);
+  // `region/tree@v1` 实测只回 node_id 扁平数组(⛔ 名称与层级),建档要挂父区域节点时只能按 id 选
+  const { data: regionData } = useLoad(() => regionTree(), []);
+
+  const operators = operatorsData?.items ?? [];
+  const partners = partnersData?.items ?? [];
+  const nodeIds = regionData?.node_ids ?? [];
+  const items = data?.items ?? [];
+  const total = data?.total ?? 0;
+
+  const teamNameById = useMemo(
+    () => Object.fromEntries((teamsData?.items ?? []).map((t) => [t.team_id, t.team_name])),
+    [teamsData],
+  );
+
+  // 原型的「按主体号(精确匹配)」在全量列表上比对;后端无主体号入参,只能在当前页对真有的
+  // customer_id 比对,跨页命中口径本期未接通(见面板末「本页口径」③)。
+  const shown = applied.no ? items.filter((r) => r.customer_id === applied.no) : items;
+
+  const [modal, setModal] = useState<{ kind: "create" | "edit" | "delete"; row?: CustomerListRow; blocked?: string[]; version?: string } | null>(null);
+  const form = useForm();
+  const sub = useSubmit();
+
+  const apply = () => {
+    setApplied({ ...draft, name: draft.name.trim(), no: draft.no.trim() });
+    setPage(1);
+  };
+  const clear = () => {
+    setDraft(EMPTY_FILTER);
+    setApplied(EMPTY_FILTER);
+    setPage(1);
+  };
+
+  const openCreate = () => {
+    form.reset({
+      name: "",
+      subject: "enterprise",
+      operator: "",
+      partner: "",
+      region: "",
+      id_code: "",
+      contact_name: "",
+      contact_mobile: "",
+      address: "",
+    });
+    sub.clear();
+    setModal({ kind: "create" });
+  };
+  const openEdit = (r: CustomerListRow) => {
+    // customer/get@v1 后端待实现,列表也只回名称与主体类型:其余字段⛔ 用空串冒充「原值」,
+    // 留空即「本次不改」(`customer/update@v1` 对缺省字段按不改处理)。
+    form.reset({
+      name: r.customer_name,
+      subject: r.subject_type,
+      id_code: "",
+      change_basis: "",
+      contact_name: "",
+      contact_mobile: "",
+      address: "",
+    });
+    sub.clear();
+    setModal({ kind: "edit", row: r });
+  };
+  const openDelete = async (r: CustomerListRow) => {
+    try {
+      const pc = await customerDeletePrecheck({ customer_id: r.customer_id });
+      setModal({ kind: "delete", row: r, blocked: pc.blocked ?? [], version: pc.precheck_version });
+    } catch (e) {
+      setModal({ kind: "delete", row: r, blocked: [`删除前置检查未完成:${(e as Error)?.message ?? String(e)}`] });
+    }
+  };
+  const close = () => {
+    setModal(null);
+    sub.clear();
+  };
+
+  const submit = async () => {
+    if (!modal) return;
+    const ok = await sub.run(() => {
+      if (modal.kind === "create")
+        return customerCreate({
+          customer_name: form.get("name"),
+          subject_type: form.get("subject"),
+          operator_id: form.get("operator"),
+          partner_id: form.get("partner") || undefined,
+          parent_node_id: form.get("region") || undefined,
+          id_code: form.get("id_code") || undefined,
+          contact_name: form.get("contact_name") || undefined,
+          contact_mobile: form.get("contact_mobile") || undefined,
+          address: form.get("address") || undefined,
+        });
+      if (modal.kind === "edit" && modal.row)
+        return customerUpdate({
+          customer_id: modal.row.customer_id,
+          customer_name: form.get("name") || undefined,
+          subject_type: form.get("subject") || undefined,
+          // 改识别号须带改动依据(后端拒收无依据的 id_code),⛔ 由前端猜一个理由
+          id_code: form.get("id_code") || undefined,
+          change_basis: form.get("id_code") ? form.get("change_basis") || undefined : undefined,
+          contact_name: form.get("contact_name") || undefined,
+          contact_mobile: form.get("contact_mobile") || undefined,
+          address: form.get("address") || undefined,
+        });
+      if (modal.kind === "delete" && modal.row)
+        return customerDelete({ customer_id: modal.row.customer_id, precheck_version: modal.version });
+      return Promise.resolve(null);
+    });
+    if (!ok) return;
+    close();
+    reload();
+  };
+
+  return (
+    <Shell
+      route="customers"
+      title={readOnlyViewer ? "客户清单" : "客户管理"}
+      hint={
+        readOnlyViewer
+          ? "当前身份是只读查看账号:只列出档案上归属本方的客户,不能新增、编辑、删除客户,也不提供套餐订阅与激活码办理。点一行看客户档案。"
+          : "客户必须挂在区域树的一个节点下;唯一运营商、至多一个合伙人、每种类型至多一个运维团队。新增、编辑、删除与套餐订阅配置都在本页办理。"
+      }
+    >
+      <div className="panel">
+        <div className="filters">
+          <Field label="按运营商">
+            <select value={draft.operator} onChange={(e) => setDraft((s) => ({ ...s, operator: e.target.value }))}>
+              <option value="">全部运营商</option>
+              {operators.map((o) => (
+                <option key={o.operator_id} value={o.operator_id}>
+                  {o.name}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="按合伙人">
+            <select value={draft.partner} onChange={(e) => setDraft((s) => ({ ...s, partner: e.target.value }))}>
+              <option value="">全部合伙人</option>
+              {partners.map((p) => (
+                <option key={p.partner_id} value={p.partner_id}>
+                  {p.name}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="按主体类型">
+            <select value={draft.subject} onChange={(e) => setDraft((s) => ({ ...s, subject: e.target.value }))}>
+              <option value="">全部主体类型</option>
+              {SUBJECT_OPTS.map(([v, t]) => (
+                <option key={v} value={v}>
+                  {t}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="按状态">
+            <select value={draft.status} onChange={(e) => setDraft((s) => ({ ...s, status: e.target.value }))}>
+              <option value="">全部状态</option>
+              {STATUS_OPTS.map((v) => (
+                <option key={v} value={v}>
+                  {label(ACCT_STATUS, v)}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="按客户名称(模糊)">
+            <input
+              value={draft.name}
+              placeholder="输入名称中的部分文字"
+              onChange={(e) => setDraft((s) => ({ ...s, name: e.target.value }))}
+              onKeyDown={(e) => e.key === "Enter" && apply()}
+            />
+          </Field>
+          <Field label="按主体号(精确匹配)">
+            <input
+              value={draft.no}
+              placeholder="完整客户主体号,不做模糊匹配"
+              onChange={(e) => setDraft((s) => ({ ...s, no: e.target.value }))}
+              onKeyDown={(e) => e.key === "Enter" && apply()}
+            />
+          </Field>
+          <Field label={" "}>
+            <Btn ghost onClick={clear}>
+              清除筛选
+            </Btn>
+          </Field>
+          {/* 原型条件即时生效;本页五个条件要送后端才生效,故补一枚「查询」(见面板末「本页口径」⑤) */}
+          <Field label={" "}>
+            <Btn onClick={apply}>查询</Btn>
+          </Field>
+          {adminLike ? (
+            <Field label={" "}>
+              <Btn onClick={openCreate}>+ 新增客户</Btn>
+            </Field>
+          ) : null}
+          {adminLike ? (
+            <Field label={" "}>
+              <Btn ghost disabled title="本期未开放:客户建档模板上传与 import_batch/create 文件解析未接通,页面不放空壳入口">
+                批量导入
+              </Btn>
+            </Field>
+          ) : null}
+          {adminLike ? (
+            <Field label={" "}>
+              <Btn ghost disabled title="本期未开放:activation_code/export 接口未接通,页面不放空壳入口">
+                导出激活码
+              </Btn>
+            </Field>
+          ) : null}
+        </div>
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && !data ? <Loading /> : null}
+        {data ? (
+          <table className="ent-list">
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th className="c-ent">客户编号 / 名称</th>
+                <th className="c-subject">
+                  主体 / 识别号<QTip>{IDNO_TIP}</QTip>
+                </th>
+                <th className="c-region">所属区域</th>
+                <th className="c-op">运营商</th>
+                <th className="c-partner">合伙人</th>
+                <th className="c-teams">运维团队</th>
+                <th className="c-status">
+                  状态<QTip popRight>{ENT_STATUS_TIP}</QTip>
+                </th>
+                {adminLike ? <th className="c-ops">操作</th> : null}
+              </tr>
+            </thead>
+            <tbody>
+              {shown.map((r, i) => (
+                <tr
+                  key={r.customer_id}
+                  className="clickable"
+                  role="button"
+                  tabIndex={0}
+                  onClick={() => nav(`/customers/${r.customer_id}`)}
+                  onKeyDown={(e) => e.key === "Enter" && nav(`/customers/${r.customer_id}`)}
+                >
+                  <td>{seq(page, PAGE_SIZE, i)}</td>
+                  <td className="c-ent">
+                    {r.customer_id}
+                    <br />
+                    <span className="note">{r.customer_name}</span>
+                  </td>
+                  <td className="c-subject">
+                    {label(SUBJECT_TYPE, r.subject_type) || "—"}
+                    <span className="note">
+                      <br />
+                      <Cell v={null} />
+                    </span>
+                  </td>
+                  <td className="c-region">
+                    <Cell v={null} />
+                  </td>
+                  <td className="c-op">
+                    <Cell v={r.operator_name} />
+                  </td>
+                  <td className="c-partner">
+                    <Cell v={r.partner_name} />
+                  </td>
+                  {/* 原型 `td.c-teams`:多个运维团队逐行换行(`join("<br>")`),⛔ 顿号串成一行 */}
+                  <td className="c-teams">
+                    {r.team_ids?.length
+                      ? r.team_ids.flatMap((id, k) =>
+                          k
+                            ? [<br key={`br-${k}`} />, teamNameById[id] ?? id]
+                            : [teamNameById[id] ?? id],
+                        )
+                      : "—"}
+                  </td>
+                  <td className="c-status">
+                    <Pill text={label(ACCT_STATUS, r.acct_status)} />
+                  </td>
+                  {adminLike ? (
+                    <td className="c-ops">
+                      <span className="row" onClick={(e) => e.stopPropagation()}>
+                        <Btn ghost onClick={() => openEdit(r)}>
+                          编辑
+                        </Btn>
+                        <Btn ghost onClick={() => void openDelete(r)}>
+                          删除
+                        </Btn>
+                      </span>
+                    </td>
+                  ) : null}
+                </tr>
+              ))}
+              {!shown.length && !loading ? <Empty text="范围内没有客户" cols={adminLike ? 9 : 8} /> : null}
+            </tbody>
+          </table>
+        ) : null}
+        {total > PAGE_SIZE ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+
+        <details className="note-details">
+          <summary>本页口径(区域与识别号筛选、列取值与批量导入)</summary>
+          <div className="note">
+            ①原型筛选条第 1 格「按区域(含下级)」与第 8 格「按客户识别号(精确匹配)」本期<b>不提供输入框</b>:
+            `region/tree@v1` 实测只回 <b>node_id 扁平数组</b>(⛔ 名称、⛔ 层级),`customer/get_list@v1` 的入参与
+            应答行里都<b>没有区域字段与识别号字段</b>,前端既拿不到可显示的区域名、也无从比对识别号,摆一个填了
+            永远不出结果的条件比缺一格更误导。②「所属区域」「识别号」两列按原型保留并显「—」,<b>⛔
+            以运营商名、建档时间或本页条数冒充</b>;「运维团队」按 `team_ids` 映射团队名(本批 200
+            条内映射不到的原样显示团队号,⛔ 谎称「已删除团队」)。③「按主体号(精确匹配)」在本页对真有的
+            `customer_id` 比对,原型是在全量列表上比对,<b>⛔ 跨页承诺命中</b>;「按客户名称(模糊)」送后端
+            keyword(后端命中客户名称或登录名)。④原型行尾三枚按钮里的「套餐订阅」跳套餐订阅页,正式系统的套餐订阅页
+            本期未开放(`subscription/get_list@v1` 契约位待后端补齐),故该入口不提供,办理请进客户档案页。⑤原型
+            条件一改即时过滤,本页「运营商/合伙人/主体类型/状态/客户名称」五个条件要送后端才生效,故筛选条补一枚
+            <b>「查询」</b>。⑥原型列出全量客户、⛔ 分页条;正式系统是服务端分页,故按后端真有的 `total`
+            出分页条。⑦「批量导入」「导出激活码」两枚按钮原型可用,本期后端文件解析与
+            `activation_code/export` 未接通,按钮置灰并在悬停提示里写明原因,<b>⛔ 用空批次冒充提交成功</b>。⑧两个弹窗的字段各自
+            照接口摆:<b>新增</b>收 `customer/create@v1` 的入参(客户名称、主体类型、归属运营商<b>必填</b>、合伙人、父区域节点、识别号、联系人与联系方式、地址),其中
+            <b>父区域节点只能按 node_id 选</b>(`region/tree@v1`⛔ 回区域名称与层级,见①);<b>编辑</b>只收
+            `customer/update@v1` 的入参(客户名称、主体类型、识别号+改动依据、联系人与联系方式、地址),该接口<b>⛔
+            改归属运营商与合伙人</b>,故编辑弹窗不出这两个下拉,<b>⛔ 摆一个改了送不出去的控件</b>;`customer/get@v1`
+            后端待实现,编辑框拿不到原值,<b>留空=本次不改这一项</b>,⛔ 用空串冒充「原值」显示。
+          </div>
+        </details>
+      </div>
+
+      {modal?.kind === "delete" ? (
+        <Modal title={`删除客户 ${modal.row?.customer_name ?? ""}`} onClose={close}>
+          <div className="form-grid">
+            <div className="notice bad">
+              {modal.blocked?.length
+                ? `以下事项未完成,后端不会放行删除:${modal.blocked.join(";")}`
+                : "删除只删客户档案与账号:已生效订阅、历史应收与已分账流水⛔ 随之删除,请先核对。"}
+            </div>
+          </div>
+          <div className="form-actions">
+            {sub.error ? <ErrorBox error={sub.error} /> : null}
+            <Btn onClick={() => void submit()} disabled={sub.busy || !!modal.blocked?.length}>
+              {sub.busy ? "提交中…" : "确认删除"}
+            </Btn>
+            <Btn ghost onClick={close}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+
+      {modal && modal.kind !== "delete" ? (
+        <Modal title={modal.kind === "create" ? "新增客户" : `编辑客户 ${modal.row?.customer_id ?? ""}`} onClose={close}>
+          <div className="form-grid">
+            <Field label="客户名称" required error={sub.error && !form.get("name") ? "必填" : undefined}>
+              <input {...form.bind("name")} placeholder="客户名称允许重名,不作唯一键" />
+            </Field>
+            <Field label="主体类型" required>
+              <select {...form.bind("subject")}>
+                {SUBJECT_OPTS.map(([v, t]) => (
+                  <option key={v} value={v}>
+                    {t}
+                  </option>
+                ))}
+              </select>
+            </Field>
+            {modal.kind === "create" ? (
+              <>
+                <Field label="归属运营商" required error={sub.error && !form.get("operator") ? "必选:客户必须唯一归属一个运营商" : undefined}>
+                  <select {...form.bind("operator")}>
+                    <option value="">请选择运营商</option>
+                    {operators.map((o) => (
+                      <option key={o.operator_id} value={o.operator_id}>
+                        {o.name}
+                      </option>
+                    ))}
+                  </select>
+                </Field>
+                <Field label="合伙人">
+                  <select {...form.bind("partner")}>
+                    <option value="">不挂合伙人</option>
+                    {partners.map((p) => (
+                      <option key={p.partner_id} value={p.partner_id}>
+                        {p.name}
+                      </option>
+                    ))}
+                  </select>
+                </Field>
+                <Field label="父区域节点">
+                  <select {...form.bind("region")}>
+                    <option value="">不指定</option>
+                    {nodeIds.map((id) => (
+                      <option key={id} value={id}>
+                        {id}
+                      </option>
+                    ))}
+                  </select>
+                </Field>
+              </>
+            ) : null}
+            <Field label="客户识别号">
+              <input {...form.bind("id_code")} placeholder={modal.kind === "create" ? "企业取统一社会信用代码,个人取身份证号" : "留空=不改识别号"} />
+            </Field>
+            {modal.kind === "edit" ? (
+              <Field label="识别号改动依据">
+                <input {...form.bind("change_basis")} placeholder="改了识别号必填,例:三证合一换证" />
+              </Field>
+            ) : null}
+            <Field label="联系人">
+              <input {...form.bind("contact_name")} placeholder={modal.kind === "edit" ? "留空=不改" : "选填"} />
+            </Field>
+            <Field label="联系手机">
+              <input {...form.bind("contact_mobile")} placeholder={modal.kind === "edit" ? "留空=不改" : "选填"} />
+            </Field>
+            <Field label="联系地址">
+              <input {...form.bind("address")} placeholder={modal.kind === "edit" ? "留空=不改" : "选填"} />
+            </Field>
+            <div className="note">
+              {modal.kind === "edit"
+                ? "`customer/get@v1` 后端待实现,编辑框拿不到原值:留空=本次不改这一项(`customer/update@v1` 对缺省字段按不改处理)。该接口⛔ 改归属运营商与合伙人,故此处没有这两个下拉;客户主体号由后端生成,⛔ 在此改。"
+                : "客户主体号与主账号登录名由后端在建档时生成;主账号一次性激活码在建档结果里回显一次,⛔ 二次查看。「父区域节点」下拉只能列区域节点号——`region/tree@v1` 只回 node_id、⛔ 区域名称。"}
+            </div>
+          </div>
+          <div className="form-actions">
+            {sub.error ? <ErrorBox error={sub.error} /> : null}
+            <Btn onClick={() => void submit()} disabled={sub.busy}>
+              {sub.busy ? "提交中…" : "提交"}
+            </Btn>
+            <Btn ghost onClick={close}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}

+ 418 - 0
front-end/src/pages/EntTeamsPage.tsx

@@ -0,0 +1,418 @@
+import { useState } from "react";
+import { TARGET_TYPE, label } from "../api/labels";
+import {
+  entTeamCreate,
+  entTeamDelete,
+  entTeamGetList,
+  entTeamMemberAdd,
+  entTeamScopeGet,
+  entTeamScopeSave,
+  entTeamUpdate,
+} from "../api/bos";
+import type { EntTeamRow } from "../api/types";
+import {
+  Btn,
+  Cell,
+  Empty,
+  ErrorBox,
+  Field,
+  Loading,
+  Modal,
+  Notice,
+  Note,
+  Pager,
+  Panel,
+  Pill,
+  ScopeText,
+  seq,
+  useToast,
+} from "../components/ui";
+import { useLoad, useForm, useSubmit } from "../hooks/useLoad";
+import { useSession } from "../auth/session";
+import { Shell } from "../layout/Shell";
+
+const PAGE_SIZE = 20;
+
+type ModalKind =
+  | { kind: "create" }
+  | { kind: "update"; row: EntTeamRow }
+  | { kind: "delete"; row: EntTeamRow }
+  | { kind: "member"; row: EntTeamRow }
+  | { kind: "scope"; row: EntTeamRow }
+  | null;
+
+export function EntTeamsPage() {
+  const toast = useToast();
+  const { ctx } = useSession();
+  const canAdmin = ctx?.role_code === "admin";
+  const [keyword, setKeyword] = useState("");
+  const [page, setPage] = useState(1);
+  const [modal, setModal] = useState<ModalKind>(null);
+  const sub = useSubmit();
+  const form = useForm();
+
+  const { data, loading, error, reload } = useLoad(
+    () => entTeamGetList({ page: page - 1, page_size: PAGE_SIZE, keyword: keyword || undefined }),
+    [page, keyword],
+  );
+
+  const rows = data?.items ?? [];
+  const total = data?.total ?? 0;
+  /* 原型脚注里点名的内置团队名(后端下发),⛔ 当列表里没有时不编名字 */
+  const hqName = rows.find((r) => r.is_builtin)?.team_name;
+
+  const close = () => {
+    setModal(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const reset = () => {
+    setKeyword("");
+    setPage(1);
+  };
+
+  const submit = async () => {
+    if (!modal) return;
+    const ok = await sub.run(() => {
+      switch (modal.kind) {
+        case "create":
+          return entTeamCreate({
+            team_name: form.get("team_name"),
+            primary_username: form.get("primary_username") || undefined,
+            primary_mobile: form.get("primary_mobile") || undefined,
+            remark: form.get("remark") || undefined,
+          });
+        case "update":
+          // `remark` 恒带(弹窗预填当前备注):清空输入框=清空该列(后端三态:空白串=NULL)。
+          return entTeamUpdate({
+            team_id: modal.row.team_id,
+            team_name: form.get("team_name"),
+            remark: form.get("remark") ?? "",
+          });
+        case "delete":
+          return entTeamDelete({ team_id: modal.row.team_id });
+        case "member":
+          return entTeamMemberAdd({
+            team_id: modal.row.team_id,
+            username: form.get("username"),
+            mobile: form.get("mobile") || undefined,
+            is_primary: form.get("is_primary") === "1",
+          });
+        case "scope":
+          return entTeamScopeSave({
+            team_id: modal.row.team_id,
+            region_node_ids: form
+              .get("region_node_ids")
+              .split(/[\s,,]+/)
+              .filter(Boolean),
+          });
+      }
+    });
+    if (!ok) return;
+    toast("已提交");
+    close();
+    reload();
+  };
+
+  return (
+    <Shell
+      route="entteams"
+      title="运营团队管理"
+      hint="运营团队由总运营开通,按所属区域建档;团队内账号功能等同总运营,但只能在负责范围内操作。每个团队有且只有一个主账号,可再增加子账号。成员账号可绑定手机号(选填、全站唯一),绑定后可用手机号代替登录名登录。新增、编辑、删除与账号变更均写审计日志,删除团队前须先清理团队内全部账号。"
+    >
+      {!canAdmin ? (
+        <Notice tone="warn">
+          当前为运营团队账号,只显示您所在的团队「{ctx?.subject_name || "—"}
+          」,其他运营团队及其成员账号不可见。
+        </Notice>
+      ) : null}
+
+      <Panel
+        title={`运营团队(共 ${total} 个,当前页显示 ${rows.length} 个)`}
+        extra={
+          canAdmin ? (
+            <Btn
+              onClick={() => {
+                form.reset();
+                setModal({ kind: "create" });
+              }}
+            >
+              + 新建运营团队
+            </Btn>
+          ) : (
+            <span className="note">档案只读,不能新建团队;本团队成员账号可管理</span>
+          )
+        }
+        noteTitle="本页取数口径:与上段原型不一致的六处(区域名称、区域筛选、成员账号、配置范围、总部标记、分页)"
+        note={
+          <>
+            ① 「所属区域」=bos_data_scope 授权节点(ent_team ⛔ region 列,区域归属按第 1 册§2 只落 scope 表),
+            本期只有节点 ID —— 中文名称待平台侧区域读接口(18 册在册);「覆盖客户」为范围内去重在册客户数(内置团队空范围=全量在册)。
+            「分成方式」「分成比例/金额」两列已删(✅ 2026-11-08 业主定案,总则§18.3 `PG-7` 路线 A=原型回改)——
+            分成方是封闭的三类(运营商/合伙人/运维团队,第 4 册§5.1/§5.2),运营团队⛔ 分成方,故 ent_team ⛔ 这两列,原型也⛔ 这两列。
+            「团队名称」下方的备注=在册列 ent_team.remark VARCHAR(200) NULL(同一定案补列),未配置则不渲染该行。
+            ② 「按区域(含下级)」筛选本期未开放(列表接口⛔ 该入参,团队也⛔ 建档区域列,只有 scope 授权节点),故不渲染该下拉;
+            「按名称 / 备注」以 keyword 传给后端,后端按 team_name OR remark 模糊匹配(第 1 册 05 册§5.4 OR-09)。
+            ③ 「成员账号」列只到后端下发的成员<b>数量</b>(含主账号):成员明细⛔ 只读接口
+            (`/ent_team` 未声明成员清单路由),⛔ 编造成员行,原型「成员账号」页本期无法列出行。
+            ④ 「配置范围」的保存走 `ent_team/scope/save`,读取接口只回<b>当前登录主体自己</b>的授权 ⇒ 弹窗回显取自<b>本行内联下发</b>的
+            scope_regions(⛔ 调按他人读取的路由);下方仍如实列出当前登录主体自己的授权记录(后端只给 target_type/target_id,⛔ 节点名称)。
+            ⑤ 「总部」标记=后端 `is_builtin`(内置「总部·不限区域」团队),可编辑与配置范围但⛔ 删除;
+            原型「成员账号」入口本期⛔ 数源,改为「添加成员」直连 `ent_team/member/add`。
+            ⑥ 列表为服务端分页:面板头「共」为后端总条数、「当前页显示」为当页条数,未透传后端的条件只在当页内生效。
+          </>
+        }
+      >
+        <div className="filters">
+          <Field label="按名称 / 备注">
+            <input
+              value={keyword}
+              onChange={(e) => {
+                setKeyword(e.target.value);
+                setPage(1);
+              }}
+              placeholder="输入关键字,例如 华东"
+            />
+          </Field>
+          <Field label={" "}>
+            <Btn ghost onClick={reset}>
+              重置筛选
+            </Btn>
+          </Field>
+        </div>
+
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && !data ? (
+          <Loading />
+        ) : (
+          <table>
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th>团队名称(含备注)</th>
+                <th>所属区域</th>
+                <th>覆盖客户</th>
+                <th>成员账号</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.length ? (
+                rows.map((r, i) => (
+                  <tr key={r.team_id}>
+                    <td>{seq(page, PAGE_SIZE, i)}</td>
+                    <td>
+                      {r.team_name}
+                      {r.is_builtin ? (
+                        <>
+                          {" "}
+                          <Pill text="总部" />
+                        </>
+                      ) : null}
+                      {/* 备注(在册列 ent_team.remark):未配置=⛔ 渲染假文字,也不渲染空行 */}
+                      {r.remark ? (
+                        <>
+                          <br />
+                          <span className="note">{r.remark}</span>
+                        </>
+                      ) : null}
+                    </td>
+                    <td className="wrap">
+                      {r.is_builtin && !r.scope_regions.length && !r.scope_customers.length ? (
+                        <span className="note">不限区域(内置团队)</span>
+                      ) : (
+                        <ScopeText regions={r.scope_regions} customers={r.scope_customers} />
+                      )}
+                    </td>
+                    <td>
+                      {r.coverage_customers === null ? <Cell v={null} /> : r.coverage_customers}
+                    </td>
+                    <td>
+                      {r.member_count ? <b>{r.member_count} 个</b> : <Pill text="未开通" />}
+                    </td>
+                    <td>
+                      {canAdmin ? (
+                        <>
+                          <Btn
+                            ghost
+                            onClick={() => {
+                              form.reset({ region_node_ids: r.scope_regions.join("、") });
+                              setModal({ kind: "scope", row: r });
+                            }}
+                          >
+                            配置范围
+                          </Btn>
+                          <Btn
+                            ghost
+                            onClick={() => {
+                              form.reset();
+                              setModal({ kind: "member", row: r });
+                            }}
+                          >
+                            添加成员
+                          </Btn>
+                          <Btn
+                            ghost
+                            onClick={() => {
+                              form.reset({ team_name: r.team_name, remark: r.remark ?? "" });
+                              setModal({ kind: "update", row: r });
+                            }}
+                          >
+                            编辑
+                          </Btn>
+                          {/* 原型:内置「总部」团队不给删除入口(可编辑与配置范围) */}
+                          {r.is_builtin ? null : (
+                            <Btn
+                              ghost
+                              danger
+                              onClick={() => {
+                                form.reset();
+                                setModal({ kind: "delete", row: r });
+                              }}
+                            >
+                              删除
+                            </Btn>
+                          )}
+                        </>
+                      ) : (
+                        <span className="note">档案只读</span>
+                      )}
+                    </td>
+                  </tr>
+                ))
+              ) : (
+                <Empty
+                  cols={6}
+                  text={
+                    keyword.trim()
+                      ? `共 ${total} 个运营团队,可调整查询条件`
+                      : "还没有运营团队,先新建一个「总运营团队」"
+                  }
+                />
+              )}
+            </tbody>
+          </table>
+        )}
+
+        <Note>
+          {canAdmin && hqName ?
+            `「${hqName}」为系统内置的总部平台级团队,不限所属区域、覆盖全国,可编辑与配置范围但不能删除;团队的内置主账号即总运营账号,该账号不能删除、主账号也不可转交。按区域筛选时不显示不限区域的团队。`
+          : ""}
+          所属区域为团队建档区域,显示全路径;按区域筛选时含该区域下级建档的团队。覆盖客户按负责范围实时计算。成员账号点击进入该团队账号管理。
+        </Note>
+
+        {data ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+      </Panel>
+
+      {modal ? (
+        <Modal
+          title={
+            modal.kind === "create"
+              ? "新建运营团队"
+              : modal.kind === "update"
+                ? `编辑运营团队 · ${modal.row.team_name}`
+                : modal.kind === "member"
+                  ? `添加成员 · ${modal.row.team_name}`
+                  : modal.kind === "scope"
+                    ? `负责范围 · ${modal.row.team_name}`
+                    : `删除运营团队 · ${modal.row.team_name}`
+          }
+          onClose={close}
+        >
+          <div className="form-grid">
+            {modal.kind === "create" || modal.kind === "update" ? (
+              <>
+                <Field label="团队名称" required>
+                  <input {...form.bind("team_name")} />
+                </Field>
+                <Field label="备注" hint="选填,≤200 字;随档案一并保存,变更写审计前后值">
+                  <input {...form.bind("remark")} maxLength={200} placeholder="例如 覆盖上海市与江苏省全部下挂客户" />
+                </Field>
+                {modal.kind === "create" ? (
+                  <>
+                    <Field label="主账号登录名" hint="每团队有且仅有一个主账号">
+                      <input {...form.bind("primary_username")} />
+                    </Field>
+                    <Field label="主账号手机号">
+                      <input {...form.bind("primary_mobile")} />
+                    </Field>
+                  </>
+                ) : null}
+              </>
+            ) : null}
+            {modal.kind === "member" ? (
+              <>
+                <Field label="成员登录名" required>
+                  <input {...form.bind("username")} />
+                </Field>
+                <Field label="手机号">
+                  <input {...form.bind("mobile")} />
+                </Field>
+                <Field label="设为主账号">
+                  <select {...form.bind("is_primary")}>
+                    <option value="0">否</option>
+                    <option value="1">是</option>
+                  </select>
+                </Field>
+              </>
+            ) : null}
+            {modal.kind === "scope" ? (
+              <>
+                <Field label="区域节点 ID" hint="多个以逗号或空格分隔;留空=不限区域;资源树接口本期只下发可见节点 ID(⛔ 名称与层级)">
+                  <input {...form.bind("region_node_ids")} placeholder="RN_01, RN_02" />
+                </Field>
+                <div style={{ gridColumn: "1 / -1" }}>
+                  <ScopeBody />
+                </div>
+              </>
+            ) : null}
+            {modal.kind === "delete" ? (
+              <Notice tone="warn">
+                删除守卫由后端实查:系统内置团队、名下成员、名下客户;命中即拒绝并回传阻塞项与 `KLT-*`。
+              </Notice>
+            ) : null}
+            <div className="form-actions">
+              {sub.error ? <ErrorBox error={sub.error} /> : null}
+              <Btn onClick={() => void submit()} disabled={sub.busy}>
+                {sub.busy ? "提交中…" : "提交"}
+              </Btn>
+              <Btn ghost onClick={close}>
+                取消
+              </Btn>
+            </div>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}
+
+/** 负责范围现状:后端只回 target_type/target_id,⛔ 编造节点名称。 */
+function ScopeBody() {
+  const scope = useLoad(() => entTeamScopeGet(), []);
+  if (scope.error) return <ErrorBox error={scope.error} />;
+  if (scope.loading) return <Loading />;
+  if (!scope.data?.grants.length) return <Empty text="当前登录主体名下没有范围授权记录" />;
+  return (
+    <>
+      <Note>当前登录主体的范围授权(共 {scope.data.total} 条):</Note>
+      <table>
+        <thead>
+          <tr>
+            <th>类型</th>
+            <th>目标 ID</th>
+          </tr>
+        </thead>
+        <tbody>
+          {scope.data.grants.map((g) => (
+            <tr key={`${g.target_type}:${g.target_id}`}>
+              <td>{label(TARGET_TYPE, g.target_type)}</td>
+              <td>{g.target_id}</td>
+            </tr>
+          ))}
+        </tbody>
+      </table>
+    </>
+  );
+}

+ 169 - 0
front-end/src/pages/HomePage.tsx

@@ -0,0 +1,169 @@
+import { useNavigate } from "react-router-dom";
+import {
+  customerGetList,
+  entTeamGetList,
+  importBatchGetList,
+  operatorGetList,
+  opsTeamGetList,
+  opsviewHome,
+  partnerGetList,
+  regionOrphans,
+  regionTree,
+} from "../api/bos";
+import { ROLE_LABEL, useSession } from "../auth/session";
+import { Btn, KpiCard, Panel } from "../components/ui";
+import { useLoad } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+/** 计数探针:只要 `total`,故 `page_size=1`(真实接口分页计数,⛔ 前端自行数页内行数)。 */
+const COUNT = { page: 0, page_size: 1 } as const;
+
+export function HomePage() {
+  const { ctx } = useSession();
+  const nav = useNavigate();
+
+  const custAll = useLoad(() => customerGetList({ ...COUNT }), []);
+  const custInUse = useLoad(() => customerGetList({ ...COUNT, acct_status: "in_use" }), []);
+  const custNotOpened = useLoad(() => customerGetList({ ...COUNT, acct_status: "not_opened" }), []);
+  const operators = useLoad(() => operatorGetList({ ...COUNT }), []);
+  const partners = useLoad(() => partnerGetList({ ...COUNT }), []);
+  const entTeams = useLoad(() => entTeamGetList({ ...COUNT }), []);
+  const opsTeams = useLoad(() => opsTeamGetList({ ...COUNT }), []);
+  const tree = useLoad(() => regionTree(), []);
+  const orphans = useLoad(() => regionOrphans(), []);
+  const importPending = useLoad(() => importBatchGetList({ ...COUNT, status: "failed_pending" }), []);
+  const ov = useLoad(() => opsviewHome(), []);
+
+  // 「查不到」与「查不了」必须能区分:接口失败就是 null(界面显「—」),⛔ 塌成 0。
+  const n = (l: { data: { total?: number } | null }) => (l.data?.total == null ? null : l.data.total);
+  const num = (v: number | null) => (v == null ? "—" : v);
+  const sum = (a: number | null, b: number | null) => (a == null && b == null ? null : (a ?? 0) + (b ?? 0));
+  const busy =
+    custAll.loading || custInUse.loading || custNotOpened.loading || operators.loading || partners.loading;
+
+  const scope = "当前登录身份可见范围(后端下发)";
+  const todos = [
+    {
+      name: "客户账号未开通",
+      basis: "建档后主账号仍未开通/未激活,客户无法登录自助门户",
+      count: n(custNotOpened),
+      go: () => nav("/customers"),
+      goText: "去处理",
+    },
+    {
+      name: "批量导入部分成功,存在失败明细",
+      basis: "导入批次内有校验失败行,需修正后续传或重新导入",
+      count: n(importPending),
+      go: () => nav("/imports"),
+      goText: "去补跑",
+    },
+    {
+      name: "区域挂载申请待认领",
+      basis: "悬空挂载申请(主体已建、区域尚未确认),需区域管理员指定承接",
+      count: orphans.data?.dangling_count ?? null,
+      go: () => nav("/regions"),
+      goText: "去区域",
+    },
+    {
+      name: "新装/维修工单待分派",
+      basis: "状态为「待分派」的工单:已建单、尚无责任人。工单生命周期在运维工单系统内,本系统一期未提供只读汇总接口",
+      count: ov.data?.tickets.available ? ov.data.tickets.pending : null,
+      go: null,
+      goText: "",
+    },
+    {
+      name: "超 7 日未完成",
+      basis: "自开停记录进入待执行之日(服务开通工单自创建之日)起算,满 7 个自然日仍未完成;口径需工单系统提供后才可统计",
+      count: ov.data?.overdue.available ? ov.data.overdue.count : null,
+      go: null,
+      goText: "",
+    },
+  ];
+
+  return (
+    <Shell
+      route="home"
+      title="概览"
+      hint={`今天 ${new Date().toLocaleDateString("zh-CN")} · 数据范围:${scope} · 当前角色:${
+        ctx ? ROLE_LABEL[ctx.role_code] : "—"
+      }`}
+    >
+      {/* 原型 `.cards.kpi > .card > span + .num-row>b + span.card-sub`:
+          卡内只有这三层,原型另有 `svg.spark` 迷你曲线=演示设施、后端无数源 ⇒ ⛔ 伪造,口径写进 .card-sub。 */}
+      <div className="cards kpi">
+        <KpiCard
+          label="在册客户"
+          value={busy && custAll.data == null ? "…" : num(n(custAll))}
+          sub={
+            custAll.error
+              ? `客户计数失败:${custAll.error.message ?? "接口异常"}`
+              : `使用中 ${num(n(custInUse))} · 未开通 ${num(n(custNotOpened))}(在管客户主体数,不含账号数)`
+          }
+        />
+        <KpiCard
+          label="服务商"
+          value={num(sum(n(operators), n(partners)))}
+          sub={
+            operators.error || partners.error
+              ? "服务商计数失败:见控制台错误"
+              : `运营商 ${num(n(operators))} · 合伙人 ${num(n(partners))}(运营商只读自平台;合伙人停用后⛔ 新增客户与团队)`
+          }
+        />
+        <KpiCard
+          label="团队"
+          value={num(sum(n(entTeams), n(opsTeams)))}
+          sub={
+            entTeams.error || opsTeams.error
+              ? "团队计数失败:见控制台错误"
+              : `运营团队 ${num(n(entTeams))} · 运维团队 ${num(n(opsTeams))}(运营团队按区域建档)`
+          }
+        />
+        <KpiCard
+          label="可见区域节点"
+          value={tree.data == null ? "—" : tree.data.node_ids.length}
+          sub={
+            tree.error
+              ? "区域树接口失败"
+              : tree.data?.note || "接口仅下发可见节点编号(不含名称与父子关系),名称需到区域管理页按节点查询"
+          }
+        />
+        <KpiCard
+          label="待分派工单"
+          alarm={!!ov.data?.tickets.available && (ov.data.tickets.pending ?? 0) > 0}
+          value={ov.data?.tickets.available ? num(ov.data.tickets.pending) : "—"}
+          sub={
+            ov.data?.tickets.available
+              ? "状态=待分派且未超时,按优先级排序;近期走势无数据源,不提供曲线"
+              : ov.data?.message || "工单数据源未接入"
+          }
+        />
+      </div>
+
+      <Panel
+        title="待处理事项"
+        note="概览只列需要人工干预的异常计数,条目数不随客户量增长;明细一律到各专页带筛选查看。客户/导入/区域三类取真实接口计数,可直接下钻;同一张工单按不同处理口径可能出现在多行,本页任何位置都不出现各行之和。工单类指标的数据源在运维工单系统,本系统一期未提供只读汇总接口,故显示「—」而⛔ 估算,行末也⛔ 挂无跳转的假入口。"
+      >
+        <table>
+          <thead>
+            <tr>
+              <th>事项</th>
+              <th>口径</th>
+              <th>数量</th>
+              <th>处理</th>
+            </tr>
+          </thead>
+          <tbody>
+            {todos.map((t) => (
+              <tr key={t.name}>
+                <td>{t.name}</td>
+                <td className="wrap">{t.basis}</td>
+                <td>{t.count == null ? <span className="note">—</span> : t.count === 0 ? <span className="note">0</span> : <b>{t.count}</b>}</td>
+                <td>{t.go && t.count ? <Btn ghost onClick={t.go}>{t.goText}</Btn> : <span className="note">—</span>}</td>
+              </tr>
+            ))}
+          </tbody>
+        </table>
+      </Panel>
+    </Shell>
+  );
+}

+ 261 - 0
front-end/src/pages/ImportBatchesPage.tsx

@@ -0,0 +1,261 @@
+import { useState } from "react";
+import { IMPORT_STATUS, VALIDATE_STATUS, label } from "../api/labels";
+import { importBatchGet, importBatchGetList, importBatchTemplateDownload } from "../api/bos";
+import type { ImportBatchRowT } from "../api/types";
+import { Btn, Cell, Drawer, ErrorBox, Field, Loading, Modal, Notice, Pager, Panel, Pill, datetime } from "../components/ui";
+import { useLoad } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+const PAGE_SIZE = 20;
+
+export function ImportBatchesPage() {
+  const [keyword, setKeyword] = useState("");
+  const [page, setPage] = useState(1);
+  const [detail, setDetail] = useState<ImportBatchRowT | null>(null);
+  const [specOpen, setSpecOpen] = useState(false);
+
+  const { data, loading, error, reload } = useLoad(
+    () => importBatchGetList({ page: page - 1, page_size: PAGE_SIZE, keyword: keyword || undefined }),
+    [page, keyword],
+  );
+
+  const items = data?.items ?? [];
+  const total = data?.total ?? 0;
+  const q = keyword.trim();
+
+  const reset = () => {
+    setKeyword("");
+    setPage(1);
+  };
+
+  return (
+    <Shell
+      route="imports"
+      title="批量导入"
+      hint="批量导入按模板逐行建档:主体号自动生成,主账号同步开通并发放一次性激活码;导入只建客户档案,套餐到该客户的「套餐订阅」里新增订阅。批次号贯穿行级结果、续传与按批次导出。"
+    >
+      <Panel
+        title={
+          <>
+            批次列表({q ? `查出 ${total} 个 / 可见范围内共 — 个批次` : `共 ${total} 个批次`},当前页显示 {items.length} 个)
+          </>
+        }
+        extra={
+          <>
+            <Btn ghost onClick={() => setSpecOpen(true)}>
+              导入模板规格
+            </Btn>
+            <Btn ghost onClick={reload}>
+              刷新
+            </Btn>
+          </>
+        }
+        note={
+          <>
+            「详情」里查看行级结果与失败原因,并办理续传、导出本批次客户信息、下载本批次激活码清单。状态为「有失败待续传」的批次请按原行编号修正后重新上传,已成功的行不会重复建档。导入、续传与两类导出都写操作日志,日志不记激活码。
+            <br />
+            本期取数与入口口径:①「文件名」列——`/import_batch/get_list@v1`⛔ 下发文件名(只回批次号、类型、状态、行数计数、导入人与导入时间),该列按原型保留并显「—」,⛔
+            以批次类型或批次号冒充。②原型的「+ 批量导入客户」上传入口、<b>失败行续传</b>、<b>按批次导出客户</b>与<b>激活码清单</b>本期未开放(后端文件解析与
+            `import_batch/resume`、`export_customers`、`export_codes` 未接通),页面不放空壳按钮,也不得用空批次冒充提交成功;原型「下载导入模板」接口只回模板<b>规格</b>(格式/列数/单批上限),不下发模板文件,故面板头只提供「导入模板规格」查看与「刷新」。③原型筛选只有「关键字 + 重置筛选」两格;后端虽另有
+            status 入参,原型未提供该筛选维度,本页⛔ 凭空多一个下拉。关键字先传后端;原型的关键字还比对批次内的客户名称与主体号,后端 `keyword` 未覆盖客户维度时只在本页比对,跨页客户命中口径本期未接通。④列表为服务端分页,原型全量列出不分页,分页条按后端真有的 `total` 呈现。⑤原型面板头的「可见范围内共 N 个批次」需要未过滤总数,接口未下发,显「—」。
+          </>
+        }
+      >
+        <div className="filters">
+          <Field label="按批次号 / 文件名 / 导入人 / 客户">
+            <input
+              value={keyword}
+              placeholder="输入批次号、文件名、导入人,或批次里的客户名称、主体号"
+              onChange={(e) => {
+                setKeyword(e.target.value);
+                setPage(1);
+              }}
+            />
+          </Field>
+          <Field label={"\u00A0"}>
+            <Btn ghost onClick={reset}>
+              重置筛选
+            </Btn>
+          </Field>
+        </div>
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && !data ? <Loading /> : null}
+        {data ? (
+          <table>
+            <thead>
+              <tr>
+                <th>批次号</th>
+                <th>文件名</th>
+                <th>导入人</th>
+                <th>导入时间</th>
+                <th>总行数</th>
+                <th>成功</th>
+                <th>失败</th>
+                <th>状态</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {items.map((r) => (
+                <tr key={r.batch_id}>
+                  <td>
+                    <strong>{r.batch_no}</strong>
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>
+                    <Cell v={r.operator_username} />
+                  </td>
+                  <td>{r.created_at ? datetime(r.created_at) : "—"}</td>
+                  <td>
+                    <Cell v={r.total_rows} />
+                  </td>
+                  <td>
+                    <Cell v={r.success_rows} />
+                  </td>
+                  <td>
+                    <Cell v={r.fail_rows} />
+                  </td>
+                  <td>
+                    <Pill text={label(IMPORT_STATUS, r.status)} />
+                  </td>
+                  <td>
+                    <Btn ghost onClick={() => setDetail(r)}>
+                      详情
+                    </Btn>
+                  </td>
+                </tr>
+              ))}
+              {!items.length ? (
+                <tr>
+                  <td colSpan={9} className="note">
+                    {q ? `没有匹配「${q}」的批次,可换个关键字或点「重置筛选」` : "还没有导入批次"}
+                  </td>
+                </tr>
+              ) : null}
+            </tbody>
+          </table>
+        ) : null}
+        {total > 0 ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+      </Panel>
+
+      {detail ? (
+        <Drawer title={`批次明细 · ${detail.batch_no}`} onClose={() => setDetail(null)}>
+          <DetailBody batch={detail} />
+        </Drawer>
+      ) : null}
+
+      {specOpen ? <TemplateSpec onClose={() => setSpecOpen(false)} /> : null}
+    </Shell>
+  );
+}
+
+/** 只在抽屉打开时挂载,避免关着抽屉也发请求。 */
+function DetailBody({ batch }: { batch: ImportBatchRowT }) {
+  const { data, loading, error } = useLoad(
+    () => importBatchGet({ batch_id: batch.batch_id, page: 0, page_size: 100 }),
+    [batch.batch_id],
+  );
+
+  if (loading && !data) return <Loading />;
+
+  return (
+    <>
+      {error ? <ErrorBox error={error} /> : null}
+      <p className="note">
+        批次号 {data?.batch?.batch_no ?? batch.batch_no}
+        <br />
+        状态 <Pill text={label(IMPORT_STATUS, data?.batch?.status ?? batch.status)} />
+        <br />
+        总行数 <Cell v={data?.batch?.total_rows ?? batch.total_rows} /> / 成功 <Cell v={data?.batch?.success_rows ?? batch.success_rows} /> / 失败{" "}
+        <Cell v={data?.batch?.fail_rows ?? batch.fail_rows} />
+      </p>
+      {(data?.status_counts?.length ?? 0) > 0 ? (
+        <>
+          <h3 style={{ marginTop: 16 }}>校验态分布</h3>
+          <table className="dense">
+            <thead>
+              <tr>
+                <th>校验态</th>
+                <th>行数</th>
+              </tr>
+            </thead>
+            <tbody>
+              {data?.status_counts.map((c) => (
+                <tr key={c.validate_status}>
+                  <td>{label(VALIDATE_STATUS, c.validate_status)}</td>
+                  <td>
+                    <Cell v={c.count} />
+                  </td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+        </>
+      ) : (
+        <Notice>后端未下发校验态分布(`status_counts`),此处不做推算。</Notice>
+      )}
+      <h3 style={{ marginTop: 16 }}>行明细(最多 100 行)</h3>
+      {(data?.rows?.length ?? 0) === 0 ? <p className="note">后端未下发行明细,或该批次无行</p> : null}
+      {(data?.rows?.length ?? 0) > 0 ? (
+        <table className="dense">
+          <thead>
+            <tr>
+              <th>行号</th>
+              <th>校验态</th>
+              <th>业务主键</th>
+              <th>错误</th>
+            </tr>
+          </thead>
+          <tbody>
+            {data?.rows.map((r) => (
+              <tr key={String(r.row_no)}>
+                <td>
+                  <Cell v={r.row_no} />
+                </td>
+                <td>{label(VALIDATE_STATUS, r.validate_status)}</td>
+                <td>
+                  <Cell v={r.business_id} />
+                </td>
+                <td className="wrap">
+                  <Cell v={r.errors instanceof Array ? r.errors.map((x) => String(x)) : r.errors} />
+                </td>
+              </tr>
+            ))}
+          </tbody>
+        </table>
+      ) : null}
+      <Notice>为遵守需求§5.4,行明细⛔ 回传原始 14 列(证件号/手机号等),只给校验态与错误清单。</Notice>
+    </>
+  );
+}
+
+/** 模板规格:后端只下发 format/列数/上限,未下发列名与文件内容 ⇒ 如实呈现,⛔ 自行拼一份「模板」。 */
+function TemplateSpec({ onClose }: { onClose: () => void }) {
+  const { data, loading, error } = useLoad(() => importBatchTemplateDownload(), []);
+  return (
+    <Modal title="导入模板规格" onClose={onClose}>
+      {loading && !data ? <Loading /> : null}
+      {error ? <ErrorBox error={error} /> : null}
+      {data ? (
+        <p className="note">
+          格式 <Cell v={data.format} />
+          <br />
+          列数 <Cell v={data.columns} />
+          <br />
+          单批上限 <Cell v={data.max_rows} />
+        </p>
+      ) : null}
+      <Notice>
+        接口只下发<b>规格</b>(格式/列数/行数上限),未下发列名清单与模板文件内容,页面无法提供真实下载;
+        列名以《批量导入模板》附件为准。
+      </Notice>
+      <div className="form-actions">
+        <Btn ghost onClick={onClose}>
+          关闭
+        </Btn>
+      </div>
+    </Modal>
+  );
+}

+ 279 - 0
front-end/src/pages/LoginPage.tsx

@@ -0,0 +1,279 @@
+import { useCallback, useEffect, useState } from "react";
+import { useNavigate } from "react-router-dom";
+import { post, setToken } from "../api/http";
+import {
+  ctxMissing,
+  createCaptcha,
+  loginWithPassword,
+  verifyChallenge,
+  type Captcha,
+  type LoginScope,
+} from "../api/platform";
+import { firstRoute } from "../auth/nav";
+import { useSession } from "../auth/session";
+import { Btn, Field } from "../components/ui";
+
+/** 本机演示账号:`end_user` 档=IAM 项目空间业务账号(temp/uds_p5_probe.py 建号,
+ *  口令见该台账);`platform` 档=平台身份服务账号,本机仅 root。
+ *  ⚠️ 两档账号不互通:拿 `end_user` 账号走 `platform` 档登录会 12002。 */
+const DEMO: Record<LoginScope, { user: string; label: string }[]> = {
+  end_user: [
+    { user: "klt_bos_admin", label: "总运营" },
+    { user: "klt_bos_ops_main", label: "运维团队主账号" },
+    { user: "klt_bos_ops_sub", label: "运维子账号" },
+    { user: "klt_bos_team_lead", label: "运营团队主账号" },
+    { user: "klt_bos_ops", label: "运营子账号" },
+    { user: "klt_bos_ent", label: "客户主账号" },
+    { user: "klt_bos_sub", label: "客户下属分账号" },
+    { user: "klt_bos_partner", label: "合伙人" },
+    { user: "klt_bos_operator", label: "运营商(只读)" },
+  ],
+  platform: [{ user: "root", label: "平台账号(对照用)" }],
+};
+
+const SCOPE_TABS: { key: LoginScope; label: string }[] = [
+  { key: "end_user", label: "项目空间账号" },
+  { key: "platform", label: "平台账号" },
+];
+
+export function LoginPage() {
+  const nav = useNavigate();
+  const { ctx, reload, error: ctxError, signOut } = useSession();
+
+  const [username, setUsername] = useState("");
+  const [password, setPassword] = useState("");
+  const [code, setCode] = useState("");
+  const [captcha, setCaptcha] = useState<Captcha | null>(null);
+  const [busy, setBusy] = useState(false);
+  const [err, setErr] = useState<string | null>(null);
+
+  const [step, setStep] = useState<"login" | "pwd">("login");
+  const [scope, setScope] = useState<LoginScope>("end_user");
+  const [np1, setNp1] = useState("");
+  const [np2, setNp2] = useState("");
+
+  const refreshCaptcha = useCallback(async () => {
+    try {
+      setCaptcha(await createCaptcha());
+      setCode("");
+    } catch (e) {
+      setErr(`验证码获取失败:${(e as Error).message}`);
+      setCaptcha(null);
+    }
+  }, []);
+
+  useEffect(() => {
+    void refreshCaptcha();
+  }, [refreshCaptcha]);
+
+  /** 拿到业务上下文后分流:强制改密优先于进入工作台(总则§16.5:未改密不得用其它功能)。 */
+  useEffect(() => {
+    if (!ctx) return;
+    if (ctx.must_change_password) setStep("pwd");
+    else nav(`/${firstRoute(ctx.role_code)}`, { replace: true });
+  }, [ctx, nav]);
+
+  async function onSubmit(e: React.FormEvent) {
+    e.preventDefault();
+    if (!captcha) {
+      setErr("验证码尚未就绪,请重试");
+      return;
+    }
+    if (ctxMissing(scope)) {
+      setErr("缺少项目空间标识(tenant_id/project_id):本机联调需 temp/seoh_provision.json 在位,或用 VITE_SEOH_* 指定");
+      return;
+    }
+    setBusy(true);
+    setErr(null);
+    try {
+      const challengeToken = await verifyChallenge({
+        username,
+        captchaId: captcha.captcha_id,
+        code,
+        scope,
+      });
+      const r = await loginWithPassword({ username, password, challengeToken, scope });
+      setToken(r.access_token);
+      await reload();
+    } catch (e2) {
+      setErr((e2 as Error).message || "登录失败");
+      void refreshCaptcha();
+      setBusy(false);
+      return;
+    }
+    setBusy(false);
+  }
+
+  async function onChangePassword(e: React.FormEvent) {
+    e.preventDefault();
+    if (np1 !== np2) {
+      setErr("两次输入的新密码不一致");
+      return;
+    }
+    setBusy(true);
+    setErr(null);
+    try {
+      await post("/account/change_password@v1", { old_password: password, new_password: np1 });
+      await reload();
+      if (step === "pwd") nav(`/${firstRoute(ctx?.role_code)}`, { replace: true });
+    } catch (e2) {
+      setErr((e2 as Error).message || "修改密码失败");
+    }
+    setBusy(false);
+  }
+
+  const img = captcha?.image_base64 ?? captcha?.image ?? "";
+
+  return (
+    <div className="login">
+      <aside className="login-side">
+        <h1>运营支撑系统</h1>
+        <p>
+          恪澜通宽带业务的运营支撑后台:组织与区域、运营商/合伙人、运营与运维团队、客户与分账号、批量导入与审计追溯。
+        </p>
+        <p className="note">
+          登录经 SEOH 平台统一身份服务下发令牌,本系统再据令牌换取业务角色上下文;身份、角色与可见范围全部由后端裁决,
+          前端⛔ 自行判权,界面上能看到⛔ 等于能操作。
+        </p>
+      </aside>
+      <div className="login-main">
+        <div className="login-form">
+          <section className="panel">
+            {step === "login" ? (
+              <form onSubmit={onSubmit}>
+                <h2>账号登录</h2>
+                <div className="tabs" role="tablist" aria-label="登录档位">
+                  {SCOPE_TABS.map((t) => (
+                    <button
+                      key={t.key}
+                      type="button"
+                      role="tab"
+                      aria-selected={scope === t.key}
+                      className={`tab${scope === t.key ? " active" : ""}`}
+                      onClick={() => {
+                        setScope(t.key);
+                        setUsername("");
+                        setErr(null);
+                      }}
+                    >
+                      {t.label}
+                    </button>
+                  ))}
+                </div>
+                <Field label="登录名" required>
+                  <input
+                    value={username}
+                    onChange={(e) => setUsername(e.target.value)}
+                    autoComplete="username"
+                    placeholder={scope === "end_user" ? "项目空间账号登录名" : "平台登录名"}
+                  />
+                </Field>
+                <Field label="密码" required>
+                  <input
+                    type="password"
+                    value={password}
+                    onChange={(e) => setPassword(e.target.value)}
+                    autoComplete="current-password"
+                  />
+                </Field>
+                <Field label="图形验证码" required hint="点击图片可换一张;连错 5 次锁定 1 小时">
+                  <div className="captcha-row">
+                    <input
+                      value={code}
+                      onChange={(e) => setCode(e.target.value)}
+                      placeholder="图中字符"
+                      autoComplete="off"
+                    />
+                    {img ? (
+                      <img
+                        src={img.startsWith("data:") ? img : `data:image/png;base64,${img}`}
+                        alt="验证码"
+                        title="点击刷新"
+                        onClick={() => void refreshCaptcha()}
+                      />
+                    ) : (
+                      <Btn ghost onClick={() => void refreshCaptcha()}>
+                        获取
+                      </Btn>
+                    )}
+                  </div>
+                </Field>
+                {err ? <div className="alert">{err}</div> : null}
+                {/* 票据已拿到但业务上下文取不到:必须显式呈现,⛔ 停在登录页静默失败
+                    (2026-11-08 手测「点登录没反应」=上下文失败被吞掉,页面既不进系统也不报错)。 */}
+                {!err && ctxError ? (
+                  <div className="alert">
+                    登录已通过,但业务上下文获取失败:{ctxError}
+                    <br />
+                    <span className="note">令牌已保存在本会话,可「重新获取」再试;仍失败请清除登录态后换账号。</span>
+                    <div className="form-actions">
+                      <Btn ghost onClick={() => void reload()}>
+                        重新获取
+                      </Btn>
+                      <Btn ghost onClick={signOut}>
+                        清除登录态
+                      </Btn>
+                    </div>
+                  </div>
+                ) : null}
+                <div className="form-actions">
+                  <Btn type="submit" disabled={busy || !username || !password || !code}>
+                    {busy ? "登录中…" : "登录"}
+                  </Btn>
+                  <Btn ghost onClick={() => void refreshCaptcha()}>
+                    换一张验证码
+                  </Btn>
+                </div>
+              </form>
+            ) : (
+              <form onSubmit={onChangePassword}>
+                <h2>设置新密码</h2>
+                <p className="note">首次登录或密码被重置,须先设置新密码才能继续使用其它功能。</p>
+                <div className="form-grid">
+                  <Field label="新密码" required>
+                    <input type="password" value={np1} onChange={(e) => setNp1(e.target.value)} autoComplete="new-password" />
+                  </Field>
+                  <Field label="确认新密码" required error={np2 && np1 !== np2 ? "两次输入不一致" : undefined}>
+                    <input type="password" value={np2} onChange={(e) => setNp2(e.target.value)} autoComplete="new-password" />
+                  </Field>
+                </div>
+                {err ? <div className="alert">{err}</div> : null}
+                <div className="form-actions">
+                  <Btn type="submit" disabled={busy || !np1 || !np2}>
+                    {busy ? "提交中…" : "保存并进入"}
+                  </Btn>
+                </div>
+              </form>
+            )}
+          </section>
+
+          {step === "login" ? (
+            <section className="panel">
+              <h2>本机演示账号</h2>
+              <p className="note">
+                点击卡片仅填入登录名,密码需手输(口令见 <code>temp/uds_p5_probe.py</code> 建号台账)。两档账号不互通:
+                项目空间账号走平台档登录会报 12002。
+              </p>
+              <div className="cards">
+                {DEMO[scope].map((d) => (
+                  <button
+                    key={d.user}
+                    type="button"
+                    className="persona"
+                    onClick={() => {
+                      setUsername(d.user);
+                      setErr(null);
+                    }}
+                  >
+                    <strong>{d.label}</strong>
+                    <span>{d.user}</span>
+                  </button>
+                ))}
+              </div>
+            </section>
+          ) : null}
+        </div>
+      </div>
+    </div>
+  );
+}

+ 148 - 0
front-end/src/pages/MembersPage.tsx

@@ -0,0 +1,148 @@
+import { useMemo, useState } from "react";
+import { entTeamGetList, opsTeamGetList } from "../api/bos";
+import { ROLE_LABEL, useSession } from "../auth/session";
+import { Btn, Empty, ErrorBox, Loading, Note, useToast } from "../components/ui";
+import { useLoad } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+/** 原型 `/members`=「成员与负责范围」:一个 `.panel`,工具条只有关键字输入与重置筛选。 */
+const HINT = "本方团队成员名单、可处理工单类型与负责范围;账号与密码由平台统一维护,本系统只读展示。";
+
+type Kind = "ops" | "ent";
+
+export function MembersPage() {
+  const toast = useToast();
+  const { ctx } = useSession();
+  const [kw, setKw] = useState("");
+  const isOps = ctx?.subject_type === "ops_team";
+  const isEnt = ctx?.subject_type === "ent_team";
+  /** 原型该页的团队来自登录上下文(`user().team`);本系统 `/members` 不带团队参数 ⇒ 用筛选器选定团队。 */
+  const [teamId, setTeamId] = useState("");
+
+  const ops = useLoad(() => opsTeamGetList({ page: 0, page_size: 200 }), []);
+  const ent = useLoad(() => entTeamGetList({ page: 0, page_size: 200 }), []);
+  const selfTeamId = isOps || isEnt ? ctx?.subject_id ?? "" : "";
+
+  const opsTeams = useMemo(
+    () => (ops.data?.items ?? []).filter((t) => !isOps || !selfTeamId || t.team_id === selfTeamId),
+    [ops.data, isOps, selfTeamId],
+  );
+  const entTeams = useMemo(
+    () => (ent.data?.items ?? []).filter((t) => !isEnt || !selfTeamId || t.team_id === selfTeamId),
+    [ent.data, isEnt, selfTeamId],
+  );
+
+  const opts = useMemo(
+    () => [
+      ...opsTeams.map((t) => ({ id: t.team_id, name: `运维 · ${t.team_name}`, kind: "ops" as Kind })),
+      ...entTeams.map((t) => ({ id: t.team_id, name: `运营 · ${t.team_name}`, kind: "ent" as Kind })),
+    ],
+    [opsTeams, entTeams],
+  );
+  const canSwitch = !isOps && !isEnt;
+  const curTeam = teamId || selfTeamId || opts[0]?.id || "";
+  const kind: Kind = opts.find((o) => o.id === curTeam)?.kind ?? (isEnt ? "ent" : "ops");
+  const opsRow = opsTeams.find((t) => t.team_id === curTeam) ?? null;
+  const entRow = entTeams.find((t) => t.team_id === curTeam) ?? null;
+
+  /** 后端只给到团队级真值:在册人数、团队可处理工单类型、团队未完成/超时工单、建档区域节点。 */
+  const memberCount = kind === "ent" ? (entRow?.member_count ?? null) : (opsRow?.member_count ?? null);
+  const ticketTypes = opsRow?.ticket_types ?? [];
+  const openTickets = opsRow?.open_tickets ?? null;
+  const regionNode = kind === "ent" ? null : opsRow?.region_node_id || null;
+  const loading = kind === "ent" ? ent.loading : ops.loading;
+  const error = kind === "ent" ? ent.error : ops.error;
+
+  const resetFilter = () => {
+    setKw("");
+    toast("已清空关键字筛选");
+  };
+
+  return (
+    <Shell route="members" title="成员与负责范围" hint={HINT}>
+      <div className="panel">
+        <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end" }}>
+          <div className="filters" style={{ flex: 1, margin: 0 }}>
+            {canSwitch ? (
+              <div className="f-item">
+                <label>选择团队</label>
+                <select value={curTeam} onChange={(e) => setTeamId(e.target.value)}>
+                  {opts.length === 0 ? <option value="">暂无团队</option> : null}
+                  {opts.map((t) => (
+                    <option key={`${t.kind}-${t.id}`} value={t.id}>
+                      {t.name}
+                    </option>
+                  ))}
+                </select>
+              </div>
+            ) : null}
+            <div className="f-item">
+              <label>按成员 / 可处理类型 / 登录账号 / 负责范围</label>
+              <input value={kw} onChange={(e) => setKw(e.target.value)} placeholder="输入关键字,例如 张三、138、OPS-01" />
+            </div>
+            <div className="f-item">
+              <label>&nbsp;</label>
+              <Btn ghost onClick={resetFilter}>
+                重置筛选
+              </Btn>
+            </div>
+          </div>
+        </div>
+
+        {error ? <ErrorBox error={error} /> : null}
+
+        <Note>
+          当前团队在册 <b>{memberCount == null ? "—" : memberCount}</b> 名成员(后端 <code>member_count</code> 真值)
+          {ticketTypes.length ? <>;团队可处理工单类型 <b>{ticketTypes.join("、")}</b></> : null}
+          {openTickets != null ? <>;团队未完成工单 <b>{openTickets}</b> 单</> : null}
+          {regionNode ? <>;建档区域节点 <code>{regionNode}</code></> : null}。
+          原型的成员行有「可处理工单类型」「负责范围」「未完成工单」三列<b>落到成员个人</b>,本期后端只有<b>团队级</b>口径,
+          成员级⛔ 折算或估算;「负责范围」原型为网格/街道+客户清单,本系统运维团队的负责范围是<b>平台资源树节点集合</b>、
+          运营团队<b>无区域维度</b>,口径不同。
+          <b>成员明细本期读不到</b>:后端只提供成员写接口(<code>ops_team/member_add</code>/<code>member_update</code>/
+          <code>member_remove</code>)与 <code>member_count</code>,<b>没有成员列表读接口</b>,故下方表格按空态呈现、
+          关键字筛选无行可筛;新增/编辑成员请走「运维团队」/「运营团队」页。
+        </Note>
+
+        <table>
+          <thead>
+            <tr>
+              <th>序号</th>
+              <th>成员</th>
+              <th>可处理工单类型</th>
+              <th>负责范围</th>
+              <th>未完成工单</th>
+              <th>登录账号</th>
+              <th>操作</th>
+            </tr>
+          </thead>
+          <tbody>
+            {loading ? (
+              <tr>
+                <td colSpan={7}>
+                  <Loading />
+                </td>
+              </tr>
+            ) : !curTeam ? (
+              <tr>
+                <td colSpan={7}>
+                  <Empty
+                    text={`当前身份没有所属团队(角色:${ctx ? ROLE_LABEL[ctx.role_code] : "—"}),成员名单请到「运维团队」/「运营团队」页查看`}
+                  />
+                </td>
+              </tr>
+            ) : (
+              <tr>
+                <td colSpan={7}>
+                  <Empty
+                    text={`后端未下发成员明细(在册 ${memberCount ?? "—"} 人:账号、可处理工单类型、成员级负责范围与未完成工单均⛔ 编造)${kw ? ";关键字筛选无行可筛" : ""}`}
+                  />
+                </td>
+              </tr>
+            )}
+          </tbody>
+        </table>
+      </div>
+    </Shell>
+  );
+}

+ 433 - 0
front-end/src/pages/OperatorsPage.tsx

@@ -0,0 +1,433 @@
+import { useState } from "react";
+import { SETTLE_MODE, label } from "../api/labels";
+import {
+  operatorCreate,
+  operatorDelete,
+  operatorGetList,
+  operatorReconAccountCreate,
+  operatorReconAccountGet,
+  operatorUpdate,
+  regionTree,
+} from "../api/bos";
+import type { OperatorRow } from "../api/types";
+import {
+  Btn,
+  Cell,
+  ErrorBox,
+  Field,
+  AcctCell,
+  Loading,
+  Modal,
+  Note,
+  Notice,
+  Pager,
+  Panel,
+  seq,
+  useToast,
+} from "../components/ui";
+import { useLoad, useForm, useSubmit } from "../hooks/useLoad";
+import { useSession } from "../auth/session";
+import { Shell } from "../layout/Shell";
+
+const PAGE_SIZE = 20;
+
+/**
+ * 区域选择:`region/tree@v1` 本期只下发 `node_ids`(⛔ 名称、⛔ 层级、⛔ 父子),
+ * 故下拉直接列出可见节点 ID;取不到节点时才退回手工输入兜底。
+ */
+function RegionPicker({
+  value,
+  onChange,
+  nodes,
+  placeholder,
+}: {
+  value: string;
+  onChange: (v: string) => void;
+  nodes: string[];
+  placeholder: string;
+}) {
+  if (!nodes.length) {
+    return (
+      <input
+        value={value}
+        onChange={(e) => onChange(e.target.value)}
+        placeholder="区域节点 ID,例如 RN_310000(资源树不可用时手工输入)"
+      />
+    );
+  }
+  const opts = value && !nodes.includes(value) ? [value, ...nodes] : nodes;
+  return (
+    <select value={value} onChange={(e) => onChange(e.target.value)}>
+      <option value="">{placeholder}</option>
+      {opts.map((id) => (
+        <option key={id} value={id}>
+          {id}
+        </option>
+      ))}
+    </select>
+  );
+}
+
+type ModalKind =
+  | { kind: "create" }
+  | { kind: "update"; row: OperatorRow }
+  | { kind: "delete"; row: OperatorRow }
+  | { kind: "recon"; row: OperatorRow }
+  | null;
+
+export function OperatorsPage() {
+  const toast = useToast();
+  const { ctx } = useSession();
+  const canAdmin = ctx?.role_code === "admin";
+  const [keyword, setKeyword] = useState("");
+  const [region, setRegion] = useState("");
+  const [cycle, setCycle] = useState("");
+  const [page, setPage] = useState(1);
+  const [modal, setModal] = useState<ModalKind>(null);
+  const sub = useSubmit();
+  const form = useForm();
+
+  const { data, loading, error, reload } = useLoad(
+    () =>
+      operatorGetList({
+        page: page - 1,
+        page_size: PAGE_SIZE,
+        keyword: keyword || undefined,
+        region_node_id: region || undefined,
+      }),
+    [page, keyword, region],
+  );
+
+  const tree = useLoad(() => regionTree(), []);
+  const nodes = tree.data?.node_ids ?? [];
+
+  const items = data?.items ?? [];
+  /* 后端无 pay_cycle 入参 ⇒ 付款周期只在本页当页内过滤(选项取自当页出现过的取值,⛔ 造枚举) */
+  const cycles = Array.from(new Set(items.map((r) => r.pay_cycle).filter(Boolean)));
+  const rows = cycle ? items.filter((r) => r.pay_cycle === cycle) : items;
+  const total = data?.total ?? 0;
+
+  const close = () => {
+    setModal(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const reset = () => {
+    setKeyword("");
+    setRegion("");
+    setCycle("");
+    setPage(1);
+  };
+
+  const settle = () => {
+    const m = form.get("settle_mode");
+    const v = form.get("settle_value");
+    return { settle_mode: m || undefined, settle_value: v ? Number(v) : undefined };
+  };
+
+  const submit = async () => {
+    if (!modal) return;
+    const ok = await sub.run(() => {
+      if (modal.kind === "create")
+        return operatorCreate({
+          name: form.get("name"),
+          brand: form.get("brand"),
+          region_node_id: form.get("region_node_id"),
+          is_province_node: form.get("province") === "1",
+          ...settle(),
+        });
+      if (modal.kind === "update")
+        return operatorUpdate({
+          operator_id: modal.row.operator_id,
+          name: form.get("name"),
+          brand: form.get("brand"),
+          region_node_id: form.get("region_node_id"),
+          is_province_node: form.get("province") === "1",
+          ...settle(),
+        });
+      if (modal.kind === "delete") return operatorDelete({ operator_id: modal.row.operator_id });
+      return operatorReconAccountCreate({
+        operator_id: modal.row.operator_id,
+        username: form.get("username"),
+        mobile: form.get("mobile") || undefined,
+      });
+    });
+    if (!ok) return;
+    toast("已提交");
+    close();
+    reload();
+  };
+
+  const openCreate = () => {
+    form.reset({ region_node_id: nodes[0] ?? "", province: "1" });
+    setModal({ kind: "create" });
+  };
+
+  const openUpdate = (row: OperatorRow) => {
+    form.reset({
+      name: row.name,
+      brand: row.brand ?? "",
+      region_node_id: row.region_node_id,
+      // 存量运营商建档时已过 I6(非省级建不了档),编辑默认沿用「省级」确认。
+      province: "1",
+      settle_mode: row.settle_mode ?? "",
+      settle_value: row.settle_value ?? "",
+    });
+    setModal({ kind: "update", row });
+  };
+
+  const lookRecon = async (row: OperatorRow) => {
+    const ok = await sub.run(() => operatorReconAccountGet({ operator_id: row.operator_id }));
+    if (ok) toast("该运营商对账账号查询已提交(详情见后端应答)");
+  };
+
+  return (
+    <Shell
+      route="operators"
+      title="运营商管理"
+      hint="运营商按所属区域建档,是对账对手方(分成方)。每家运营商可开通一个对账查看账号(只读):登录后只能查看本方对账日与本方的对账清单、账单明细,不能修改任何数据。账号可绑定手机号(选填、全站唯一),绑定后可用手机号代替登录名登录,号码可随时更换或解绑。一家客户只归属一个运营商;对账日未单独设置时跟随系统默认对账日。新增、编辑、删除与账号变更均写审计日志,删除前须先移走下挂客户并清理对账清单。"
+    >
+      <Panel
+        title={`运营商(共 ${total} 家,当前页显示 ${rows.length} 家)`}
+        extra={<Btn onClick={openCreate}>+ 新增运营商</Btn>}
+        noteTitle="本页取数口径:与上段说明不一致的几处(区域名称、对账日、筛选与分页)"
+        note={
+          <>
+            ① 「所属区域」列显示 <code>bos_region_meta.path_name</code>(层级的唯一落地位)。⚠️ 平台的资源元数据只开了
+            新建/重命名/删除,⛔「按节点 ID 批量取中文名」的读接口(18 册在册,已提请平台侧提供),故路径目前是
+            节点 ID 链(鼠标悬停可看节点与层级);是否含下级由后端按所选节点判定,前端⛔ 展开下级。
+            ② 「登录账号」列由列表接口随行走内联下发(登录名、掩码手机号与状态),未建档主体显「尚未开通」;
+            开通与停用仍在「账号」弹窗内完成,⛔ 在前端凭猜测补全账号。
+            ③ 「对账日」列显示后端下发的 recon_day 原文,「跟随系统默认对账日」的系统参数本期未接入本页。
+            ④ 筛选:「按名称 / 通知地址」与「按区域」以 keyword/region_node_id 传给后端(后端只按名称/品牌与建档区域匹配,
+            通知地址本期⛔ 下发);「按付款周期」后端无该入参,只在本页当页内过滤,选项取自当页出现过的取值。
+            ⑤ 列表为服务端分页,面板头计数为「共 后端总条数 / 当前页显示 当页条数」;
+            写入口(新增/编辑/删除/账号)本期由后端做权限裁决,前端按身份隐藏按钮的逻辑尚未接入。
+          </>
+        }
+      >
+        <div className="filters">
+          <Field label="按区域(含下级)">
+            <RegionPicker
+              value={region}
+              onChange={(v) => {
+                setRegion(v);
+                setPage(1);
+              }}
+              nodes={nodes}
+              placeholder="全部区域"
+            />
+          </Field>
+          <Field label="按名称 / 通知地址">
+            <input
+              value={keyword}
+              onChange={(e) => {
+                setKeyword(e.target.value);
+                setPage(1);
+              }}
+              placeholder="输入关键字,例如 电信"
+            />
+          </Field>
+          <Field label="按付款周期">
+            <select value={cycle} onChange={(e) => setCycle(e.target.value)}>
+              <option value="">全部付款周期</option>
+              {cycles.map((c) => (
+                <option key={c} value={c}>
+                  {c}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label={" "}>
+            <Btn ghost onClick={reset}>
+              重置筛选
+            </Btn>
+          </Field>
+        </div>
+
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && !data ? <Loading /> : (
+          <table>
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th>运营商</th>
+                <th>所属区域</th>
+                <th>对账日</th>
+                <th>付款周期</th>
+                <th>分成方式</th>
+                <th>分成比例/金额</th>
+                <th>下挂客户</th>
+                <th>登录账号</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.length ? (
+                rows.map((r, i) => (
+                  <tr key={r.operator_id}>
+                    <td>{seq(page, PAGE_SIZE, i)}</td>
+                    <td>{r.name}</td>
+                    <td title={`节点 ${r.region_node_id};层级 ${r.region_level ?? "未建档"}`}>
+                      {r.region_path_name ?? r.region_node_id}
+                    </td>
+                    <td>
+                      <Cell v={r.recon_day} />
+                    </td>
+                    <td>
+                      <Cell v={r.pay_cycle} />
+                    </td>
+                    <td>{label(SETTLE_MODE, r.settle_mode) || <Cell v={null} />}</td>
+                    <td>
+                      <Cell v={r.settle_value} />
+                    </td>
+                    <td>{r.customer_count}</td>
+                    <td>
+                      <AcctCell acc={r.account} />
+                    </td>
+                    <td>
+                      <Btn ghost onClick={() => openUpdate(r)}>
+                        编辑
+                      </Btn>
+                      <Btn
+                        ghost
+                        danger
+                        onClick={() => {
+                          form.reset();
+                          setModal({ kind: "delete", row: r });
+                        }}
+                      >
+                        删除
+                      </Btn>
+                      <Btn
+                        ghost
+                        onClick={() => {
+                          form.reset();
+                          setModal({ kind: "recon", row: r });
+                        }}
+                      >
+                        账号
+                      </Btn>
+                    </td>
+                  </tr>
+                ))
+              ) : (
+                <tr>
+                  <td colSpan={10}>
+                    {canAdmin ? "没有符合筛选条件的运营商" : "您的负责范围内没有运营商,可调整筛选条件"}
+                  </td>
+                </tr>
+              )}
+            </tbody>
+          </table>
+        )}
+
+        <Note>
+          所属区域列显示建档区域全路径;按区域筛选时含该区域下级建档的运营商。下挂客户为该运营商名下的客户数量(不限区域)。
+          登录账号与运营商档案一比一,未开通时可点「账号」开通;停用的账号不出现在「换身份」列表,删除运营商时账号同步注销。
+          运营主账号只列出建档区域或下挂客户落在自己负责范围内的运营商,并只能在该范围内新增、编辑与删除运营商、管理这些运营商的对账账号;
+          建档区域超出负责范围时拦下保存。运营子账号只读。
+        </Note>
+
+        {data ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+      </Panel>
+
+      {modal ? (
+        <Modal
+          title={
+            modal.kind === "create"
+              ? "新建运营商"
+              : modal.kind === "update"
+                ? `编辑运营商 · ${modal.row.name}`
+                : modal.kind === "delete"
+                  ? `删除运营商 · ${modal.row.name}`
+                  : `开通对账账号 · ${modal.row.name}`
+          }
+          onClose={close}
+        >
+          <div className="form-grid">
+            {modal.kind === "create" || modal.kind === "update" ? (
+              <>
+                <Field label="名称" required>
+                  <input {...form.bind("name")} />
+                </Field>
+                <Field label="品牌" required hint="同省份×品牌唯一">
+                  <input {...form.bind("brand")} />
+                </Field>
+                <Field
+                  label="建档区域节点"
+                  required
+                  hint="须为省级节点;资源树接口本期只下发可见节点 ID(⛔ 名称与层级),默认从可见节点下拉选择"
+                >
+                  <RegionPicker
+                    value={form.vals.region_node_id ?? ""}
+                    onChange={(v) => form.set("region_node_id", v)}
+                    nodes={nodes}
+                    placeholder="请选择区域节点"
+                  />
+                </Field>
+                <Field
+                  label="节点层级确认"
+                  required
+                  hint="平台资源树只回 node_id、不回层级,后端 I6 只能按本确认校验:不勾选=直接拒绝建档"
+                >
+                  <label className="check">
+                    <input
+                      type="checkbox"
+                      checked={form.vals.province === "1"}
+                      onChange={(e) => form.set("province", e.target.checked ? "1" : "")}
+                    />
+                    该节点是省级区域节点
+                  </label>
+                </Field>
+                <Field label="分成方式" hint="留空=未配置">
+                  <select {...form.bind("settle_mode")}>
+                    <option value="">未设置</option>
+                    <option value="ratio">按比例分成</option>
+                    <option value="amount">固定金额分成</option>
+                    <option value="per_account">按账号数分成</option>
+                  </select>
+                </Field>
+                <Field label="分成取值" hint="单位由分成方式决定">
+                  <input {...form.bind("settle_value")} />
+                </Field>
+              </>
+            ) : null}
+            {modal.kind === "recon" ? (
+              <>
+                <Field label="登录名" required>
+                  <input {...form.bind("username")} />
+                </Field>
+                <Field label="手机号">
+                  <input {...form.bind("mobile")} />
+                </Field>
+              </>
+            ) : null}
+            {modal.kind === "delete" ? (
+              <Notice tone="warn">
+                删除的前置检查由后端逐条实查:名下未删除客户、已配分成规则、当前登录身份。三项均为 0 时,
+                后端仍<b>显式拒绝</b>删除——未对账账单、进行中工单、分成明细、开通/开停记录四类阻塞项的
+                源表在 dev 骨架尚未建立,⛔ 把「查不出依赖」当「没有依赖」。
+              </Notice>
+            ) : null}
+            <div className="form-actions">
+              {sub.error ? <ErrorBox error={sub.error} /> : null}
+              {modal.kind === "recon" ?
+                <Btn ghost onClick={() => void lookRecon(modal.row)}>
+                  查询现有账号
+                </Btn>
+              : null}
+              <Btn onClick={() => void submit()} disabled={sub.busy}>
+                {sub.busy ? "提交中…" : "提交"}
+              </Btn>
+              <Btn ghost onClick={close}>
+                取消
+              </Btn>
+            </div>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}

+ 652 - 0
front-end/src/pages/OpsTeamsPage.tsx

@@ -0,0 +1,652 @@
+import { useState } from "react";
+import { DISPATCH_MODE, SETTLE_MODE, label } from "../api/labels";
+import {
+  opsTeamCoverageGet,
+  opsTeamCreate,
+  opsTeamDelete,
+  opsTeamDispatchModeUpdate,
+  opsTeamGetList,
+  opsTeamMemberAdd,
+  opsTeamScopeSave,
+  opsTeamUpdate,
+  regionTree,
+} from "../api/bos";
+import type { OpsTeamRow } from "../api/types";
+import {
+  Btn,
+  Cell,
+  Drawer,
+  Empty,
+  ErrorBox,
+  Field,
+  Loading,
+  Modal,
+  Notice,
+  Note,
+  Pager,
+  Panel,
+  Pill,
+  ScopeText,
+  seq,
+  useToast,
+} from "../components/ui";
+import { useLoad, useForm, useSubmit } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+
+const PAGE_SIZE = 20;
+
+/**
+ * 区域选择:`region/tree@v1` 本期只下发 `node_ids`(⛔ 名称、⛔ 层级、⛔ 父子),
+ * 故下拉直接列出可见节点 ID;取不到节点时才退回手工输入兜底。
+ */
+function RegionPicker({
+  value,
+  onChange,
+  nodes,
+  placeholder,
+}: {
+  value: string;
+  onChange: (v: string) => void;
+  nodes: string[];
+  placeholder: string;
+}) {
+  if (!nodes.length) {
+    return (
+      <input
+        value={value}
+        onChange={(e) => onChange(e.target.value)}
+        placeholder="区域节点 ID,例如 RN_310000(资源树不可用时手工输入)"
+      />
+    );
+  }
+  const opts = value && !nodes.includes(value) ? [value, ...nodes] : nodes;
+  return (
+    <select value={value} onChange={(e) => onChange(e.target.value)}>
+      <option value="">{placeholder}</option>
+      {opts.map((id) => (
+        <option key={id} value={id}>
+          {id}
+        </option>
+      ))}
+    </select>
+  );
+}
+
+type ModalKind =
+  | { kind: "create" }
+  | { kind: "update"; row: OpsTeamRow }
+  | { kind: "delete"; row: OpsTeamRow }
+  | { kind: "member"; row: OpsTeamRow }
+  | { kind: "scope"; row: OpsTeamRow }
+  | null;
+
+export function OpsTeamsPage() {
+  const toast = useToast();
+  const { ctx } = useSession();
+  const canAdmin = ctx?.role_code === "admin";
+  const canWrite = canAdmin || ctx?.role_code === "opsMain";
+  const [keyword, setKeyword] = useState("");
+  const [region, setRegion] = useState("");
+  const [mode, setMode] = useState("");
+  const [page, setPage] = useState(1);
+  const [modal, setModal] = useState<ModalKind>(null);
+  const [coverageOpen, setCoverageOpen] = useState(false);
+  const sub = useSubmit();
+  const form = useForm();
+
+  const { data, loading, error, reload } = useLoad(
+    () =>
+      opsTeamGetList({
+        page: page - 1,
+        page_size: PAGE_SIZE,
+        keyword: keyword || undefined,
+        region_node_id: region || undefined,
+      }),
+    [page, keyword, region],
+  );
+
+  const tree = useLoad(() => regionTree(), []);
+  const nodes = tree.data?.node_ids ?? [];
+
+  const items = data?.items ?? [];
+  /* 后端无 dispatch_mode 入参 ⇒ 分派方式只在本页当页内过滤 */
+  const rows = mode ? items.filter((r) => r.dispatch_mode === mode) : items;
+  const total = data?.total ?? 0;
+  const filtered = !!(region || mode || keyword.trim());
+  const loadDown = data?.load_pending ?? null;
+
+  const close = () => {
+    setModal(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const reset = () => {
+    setKeyword("");
+    setRegion("");
+    setMode("");
+    setPage(1);
+  };
+
+  const openCreate = () => {
+    form.reset({ region_node_id: nodes[0] ?? "", dispatch_mode: "manual" });
+    setModal({ kind: "create" });
+  };
+
+  const split = (s: string) => s.split(/[\s,,]+/).filter(Boolean);
+
+  const submit = async () => {
+    if (!modal) return;
+    const sv = form.get("settle_value");
+    const ok = await sub.run(() => {
+      switch (modal.kind) {
+        case "create":
+          return opsTeamCreate({
+            team_name: form.get("team_name"),
+            region_node_id: form.get("region_node_id"),
+            ticket_types: split(form.get("ticket_types")),
+            dispatch_mode: form.get("dispatch_mode") || "manual",
+            settle_mode: form.get("settle_mode") || undefined,
+            settle_value: sv ? Number(sv) : undefined,
+            primary_username: form.get("primary_username") || undefined,
+            primary_mobile: form.get("primary_mobile") || undefined,
+          });
+        case "update": {
+          /* 原型把「分派方式」放在团队编辑表单里;`ops_team/update` ⛔ 该入参 ⇒ 有变化时追加一次专用调用
+             (两次写入不同事务,前者成功后者失败时如实报错,⛔ 假装一次保存完成) */
+          const nextMode = form.get("dispatch_mode") || modal.row.dispatch_mode;
+          const teamId = modal.row.team_id;
+          return (async () => {
+            const res = await opsTeamUpdate({
+              team_id: teamId,
+              team_name: form.get("team_name") || undefined,
+              region_node_id: form.get("region_node_id") || undefined,
+              ticket_types: form.get("ticket_types") ? split(form.get("ticket_types")) : undefined,
+              settle_mode: form.get("settle_mode") || undefined,
+              settle_value: sv ? Number(sv) : undefined,
+            });
+            if (nextMode !== modal.row.dispatch_mode) {
+              await opsTeamDispatchModeUpdate({ team_id: teamId, dispatch_mode: nextMode });
+            }
+            return res;
+          })();
+        }
+        case "delete":
+          return opsTeamDelete({ team_id: modal.row.team_id });
+        case "member":
+          return opsTeamMemberAdd({
+            team_id: modal.row.team_id,
+            username: form.get("username"),
+            mobile: form.get("mobile") || undefined,
+            ticket_types: form.get("ticket_types") ? split(form.get("ticket_types")) : undefined,
+          });
+        case "scope":
+          return opsTeamScopeSave({
+            team_id: modal.row.team_id,
+            region_node_ids: form.get("region_node_ids") ? split(form.get("region_node_ids")) : undefined,
+            customer_ids: form.get("customer_ids") ? split(form.get("customer_ids")) : undefined,
+          });
+      }
+    });
+    if (!ok) return;
+    toast("已提交");
+    close();
+    reload();
+  };
+
+  /* 原型 layout() 第二参数:身份不同追加不同口径句,逐字沿用 */
+  const hintBase =
+    "运维团队不再分「常规团队 / 施工团队」两种类型:团队上只记一件事——「可分配工单类型」,勾了哪几类就接哪几类工单。团队固定两层——团队主账号 / 运维子账号;成员也不分身份,能接什么工单由成员档案上的「可处理工单类型」决定(只能是团队可分配类型的子集)。开通运维团队时录入的账号即该团队的主账号;主账号在「成员与负责范围」中新增、编辑、删除成员,并给成员配可处理的工单类型与负责范围;每个成员各对应一个登录账号,可在「账号」中开通、重置密码或停用。";
+  const hint = canAdmin
+    ? hintBase
+    : canWrite
+      ? `${hintBase}运营主账号只列出负责范围内(覆盖客户与自己范围有交集)的运维团队,并只能在该范围内开通、编辑与删除团队、配置团队负责范围与增删团队成员;团队所属区域超出负责范围时拦下保存。`
+      : `${hintBase}区域运营只列出负责范围内(覆盖客户与自己范围有交集)的运维团队,档案只读。`;
+
+  /* 原型:只读身份下这一行是空的(⛔ 另加提示文字),开通口径已写进页头 hint */
+  const openBtn = canWrite ? <Btn onClick={openCreate}>+ 开通运维团队</Btn> : null;
+
+  /* 一个团队都没有才用空状态页;有团队但查不到时仍保留查询条件(原型口径) */
+  if (!loading && !error && total === 0) {
+    return (
+      <Shell route="opsteams" title="运维团队" hint={hint}>
+        <div className="row team-tabs">{openBtn}</div>
+        <div className="panel team-empty">
+          <p className="team-empty-title">运维团队还没有开通</p>
+          <p className="note">
+            {canAdmin
+              ? "开通时同步录入该团队的主账号,再配置团队负责范围与可分配工单类型;客户建档时勾选挂接的一支或多支团队。"
+              : canWrite
+                ? "您的负责范围内还没有运维团队,可在本范围内点「开通运维团队」新建;如需扩大范围请联系总运营调整负责范围。"
+                : "您的负责范围内还没有运维团队,如需查看请联系总运营调整负责范围。"}
+          </p>
+          {canWrite ? <Btn onClick={openCreate}>开通运维团队</Btn> : null}
+        </div>
+        {modal ? <TeamModal modal={modal} form={form} sub={sub} nodes={nodes} close={close} submit={submit} /> : null}
+      </Shell>
+    );
+  }
+
+  return (
+    <Shell
+      route="opsteams"
+      title="运维团队"
+      hint={hint}
+    >
+      <div className="row team-tabs">{openBtn}</div>
+
+      <Panel
+        title={`运维团队(共 ${total} 个${filtered ? `,当前页显示 ${rows.length} 个` : ""})`}
+        noteTitle="本页取数口径:与上两段原型不一致的六处(区域中文名、负责范围与覆盖客户、负载两列、成员账号、筛选与分页、配置范围与分派方式)"
+        note={
+          <>
+            ① 「所属区域」列显示本域 bos_region_meta.path_name 的<b>节点 ID 全路径</b>(悬停看建档节点):
+            平台资源元数据只开了新建/重命名/删除,⛔「按节点 ID 批量取中文名」的读接口(18 册在册,已提请平台侧提供),
+            故⛔ 显示成「上海市 / 青浦区」这类中文名;「按所属区域(含下级)」下拉同样列出可见节点 ID,是否含下级由后端判定。
+            ② 「负责范围」「覆盖客户」两列由列表接口随行内联下发(scope_regions/scope_customers/
+            coverage_customers):负责范围保存接口无对应的按团队读取路由,承接客户接口(`ops_team/coverage/get`)
+            又只回<b>当前登录主体自己</b>的团队,故⛔ 另开越权路由。「覆盖客户」为范围(含下级)内去重在册客户数,
+            范围未配置时下发 null ⇒ 显「—」而⛔ 折算 0;本团队的承接客户仍可在筛选条「我的承接客户」抽屉查看(运维团队身份才出现该按钮,原型⛔ 该入口)。
+            ③ 「未完成工单」「超期未完成」两列后端无数源时下发 null 并以顶层 load_pending 说明降级原因,页面显「—」而⛔ 填 0
+            (超期列后端⛔ 返回「正常/超期」判定,故无数据时⛔ 冒充「正常」)。
+            {loadDown ? (
+              <>
+                {" "}
+                后端本次降级说明:{loadDown}
+              </>
+            ) : null}
+            ④ 「成员账号」列为后端下发的成员数量,原型该列是「主账号+运维子账号」合计,成员明细⛔ 只读清单接口 ⇒ ⛔ 逐个列名;
+            原型的「成员账号」入口页本期也无法列出行,写入口改为「添加成员」直连 `ops_team/member/add`。
+            ⑤ 筛选:关键字与区域以 keyword/region_node_id 传后端(后端只在团队名称上匹配关键字,⛔ 匹配区域路径、负责范围与成员姓名);
+            「按分派方式」后端无该入参 ⇒ 只在本页当页内过滤。列表为服务端分页,面板头「共」为后端总条数、
+            「当前页显示」为当页条数。
+            ⑥ 原型的「配置范围」保存走 `ops_team/scope/save`,读取路由⛔ 按团队查询 ⇒ 弹窗回显取自<b>本行内联下发</b>的既有范围
+            (⛔ 调按他人读取的路由),保存整体替换后由后端回读;
+            原型把「分派方式」放在开通/编辑团队表单里,本期「编辑」弹窗同样带该字段,但它与 `ops_team/update` ⛔ 同接口:
+            分派方式有变化时在前一次保存成功后追加调用 `ops_team/dispatch_mode/update`(两次写入⛔ 同一事务,
+            后一步失败时如实报错并保留已保存的档案改动);该字段与团队侧改的是同一个值,后写入者生效。
+          </>
+        }
+      >
+        <div className="filters">
+          <Field label="按团队 / 区域 / 负责范围 / 成员">
+            <input
+              value={keyword}
+              onChange={(e) => {
+                setKeyword(e.target.value);
+                setPage(1);
+              }}
+              placeholder="输入关键字,例如 华东 或 周宁"
+            />
+          </Field>
+          <Field label="按所属区域(含下级)">
+            <RegionPicker
+              value={region}
+              onChange={(v) => {
+                setRegion(v);
+                setPage(1);
+              }}
+              nodes={nodes}
+              placeholder="全部区域"
+            />
+          </Field>
+          <Field label="按分派方式">
+            <select value={mode} onChange={(e) => setMode(e.target.value)}>
+              <option value="">全部分派方式</option>
+              {Object.entries(DISPATCH_MODE).map(([k, v]) => (
+                <option key={k} value={k}>
+                  {v}
+                </option>
+              ))}
+            </select>
+          </Field>
+          {ctx?.subject_type === "ops_team" ?
+            <Field label="我的承接客户">
+              <Btn ghost onClick={() => setCoverageOpen(true)}>
+                查看承接客户
+              </Btn>
+            </Field>
+          : null}
+          <Field label={" "}>
+            <Btn ghost onClick={reset}>
+              重置筛选
+            </Btn>
+          </Field>
+        </div>
+
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && !data ? (
+          <Loading />
+        ) : (
+          <table>
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th>团队名称</th>
+                <th>所属区域</th>
+                <th>可分配工单类型</th>
+                <th>分成方式</th>
+                <th>分成比例/金额</th>
+                <th>负责范围</th>
+                <th>覆盖客户</th>
+                <th>未完成工单</th>
+                <th>超期未完成</th>
+                <th>成员账号</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.length ? (
+                rows.map((r, i) => (
+                  <tr key={r.team_id}>
+                    <td>{seq(page, PAGE_SIZE, i)}</td>
+                    <td>
+                      {r.team_name}
+                      <br />
+                      <span className="note">{label(DISPATCH_MODE, r.dispatch_mode)}</span>
+                    </td>
+                    <td title={`建档区域节点:${r.region_node_id}`}>
+                      {r.region_path_name ?? r.region_node_id}
+                      {r.region_level ? (
+                        <>
+                          <br />
+                          <span className="note">{r.region_level}</span>
+                        </>
+                      ) : null}
+                    </td>
+                    <td className="wrap">
+                      <span className="note">
+                        <Cell v={r.ticket_types} />
+                      </span>
+                    </td>
+                    <td>{label(SETTLE_MODE, r.settle_mode) || <Cell v={null} />}</td>
+                    <td>
+                      <Cell v={r.settle_value} />
+                    </td>
+                    <td className="wrap">
+                      <ScopeText regions={r.scope_regions} customers={r.scope_customers} />
+                    </td>
+                    <td>
+                      {r.coverage_customers === null ? <Cell v={null} /> : r.coverage_customers}
+                    </td>
+                    <td>
+                      {r.open_tickets === null ? (
+                        <Cell v={null} />
+                      ) : r.open_tickets ? (
+                        <b>{r.open_tickets}</b>
+                      ) : (
+                        <span className="note">0</span>
+                      )}
+                    </td>
+                    <td>
+                      {r.overdue_open_tickets === null ? (
+                        <Cell v={null} />
+                      ) : r.overdue_open_tickets ? (
+                        <span className="pill bad">超期 {r.overdue_open_tickets}</span>
+                      ) : (
+                        <Pill text="正常" />
+                      )}
+                    </td>
+                    <td>{r.member_count ? `${r.member_count} 个` : <Pill text="未开通" />}</td>
+                    <td>
+                      {canWrite ? (
+                        <>
+                          <Btn
+                            ghost
+                            onClick={() => {
+                              form.reset({
+                                region_node_ids: r.scope_regions.join("、"),
+                                customer_ids: r.scope_customers.join("、"),
+                              });
+                              setModal({ kind: "scope", row: r });
+                            }}
+                          >
+                            配置范围
+                          </Btn>
+                          <Btn
+                            ghost
+                            onClick={() => {
+                              form.reset();
+                              setModal({ kind: "member", row: r });
+                            }}
+                          >
+                            添加成员
+                          </Btn>
+                          <Btn
+                            ghost
+                            onClick={() => {
+                              form.reset({
+                                team_name: r.team_name,
+                                region_node_id: r.region_node_id,
+                                ticket_types: r.ticket_types.join(","),
+                                dispatch_mode: r.dispatch_mode,
+                                settle_mode: r.settle_mode ?? "",
+                                settle_value: r.settle_value ?? "",
+                              });
+                              setModal({ kind: "update", row: r });
+                            }}
+                          >
+                            编辑
+                          </Btn>
+                          <Btn
+                            ghost
+                            danger
+                            onClick={() => {
+                              form.reset();
+                              setModal({ kind: "delete", row: r });
+                            }}
+                          >
+                            删除
+                          </Btn>
+                        </>
+                      ) : (
+                        /* 原型此处是「成员账号」入口,成员明细⛔ 只读接口 ⇒ 只读身份只剩「档案只读」 */
+                        <span className="note">档案只读</span>
+                      )}
+                    </td>
+                  </tr>
+                ))
+              ) : (
+                <Empty
+                  cols={12}
+                  text={
+                    filtered
+                      ? `共 ${total} 个运维团队,没有符合查询条件的团队,可点「重置筛选」看全部`
+                      : "没有可见的运维团队"
+                  }
+                />
+              )}
+            </tbody>
+          </table>
+        )}
+
+        <Note>
+          所属区域为团队建档区域,显示全路径;可分配工单类型在开通与编辑团队时指定,客户工单只落在声明承接该类型的团队上(多支都承接时承接类型更少者优先);
+          覆盖客户为负责范围内且挂接了该团队的客户数;未完成工单为归属该团队的在办工单数(待派单、待处理与处理中),待派单即含尚未分派到人的单;
+          超期未完成按 7 日超期口径计数(开户与停机类看开停记录进入待执行之日、服务开通看建单之日,满 7 个自然日仍未完成即计入,期限日当天即算;
+          有批准延期的按延期后的新期限),无超期为正常;成员账号为该团队主账号与运维子账号合计,点击进入该团队账号管理。团队名称下方为团队内的工单分派方式。
+        </Note>
+        <Note>
+          查询只在可见团队内进行,三项条件叠加生效:关键字同时在团队名称、所属区域全路径、负责范围(区域名与直接多选的客户端口名)
+          以及本团队主账号与运维子账号姓名上匹配,例如输入客户所在区域名或某位运维成员的名字即可定位到团队;
+          所属区域按建档区域含下级匹配;「重置筛选」回到全部可见团队。{canAdmin ? "" : "区域运营的查询结果仍受负责范围限制,查不到不等于团队不存在。"}
+        </Note>
+
+        {data ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+      </Panel>
+
+      {modal ? <TeamModal modal={modal} form={form} sub={sub} nodes={nodes} close={close} submit={submit} /> : null}
+
+      {coverageOpen ? (
+        <Drawer title="本团队承接客户" onClose={() => setCoverageOpen(false)}>
+          <CoverageBody />
+        </Drawer>
+      ) : null}
+    </Shell>
+  );
+}
+
+/** 弹窗保持原有五类写操作不变,只是从主渲染里拆出来,空状态页与列表页共用。 */
+function TeamModal({
+  modal,
+  form,
+  sub,
+  nodes,
+  close,
+  submit,
+}: {
+  modal: Exclude<ModalKind, null>;
+  form: ReturnType<typeof useForm>;
+  sub: ReturnType<typeof useSubmit>;
+  nodes: string[];
+  close: () => void;
+  submit: () => Promise<void>;
+}) {
+  return (
+    <Modal
+      title={
+        modal.kind === "create"
+          ? "开通运维团队"
+          : modal.kind === "update"
+            ? `编辑运维团队 · ${modal.row.team_name}`
+            : modal.kind === "member"
+              ? `新增成员 · ${modal.row.team_name}`
+              : modal.kind === "scope"
+                ? `配置范围 · ${modal.row.team_name}`
+                : `删除运维团队 · ${modal.row.team_name}`
+      }
+      onClose={close}
+    >
+      <div className="form-grid">
+        {modal.kind === "create" || modal.kind === "update" ? (
+          <>
+            <Field label="团队名称" required={modal.kind === "create"}>
+              <input {...form.bind("team_name")} />
+            </Field>
+            <Field
+              label="区域节点"
+              required={modal.kind === "create"}
+              hint="运维团队必须挂在一个区域节点下;资源树接口本期只下发可见节点 ID(⛔ 名称与层级),默认从可见节点下拉选择"
+            >
+              <RegionPicker
+                value={form.vals.region_node_id ?? ""}
+                onChange={(v) => form.set("region_node_id", v)}
+                nodes={nodes}
+                placeholder={modal.kind === "create" ? "请选择区域节点" : "不修改"}
+              />
+            </Field>
+            <Field label="可分配工单类型" hint="逗号分隔,至少 1 项">
+              <input {...form.bind("ticket_types")} placeholder="RECHARGE, RECON" />
+            </Field>
+            <Field
+              label="分派方式"
+              required={modal.kind === "create"}
+              hint={
+                modal.kind === "create" ?
+                  "手工由主账号逐单指定,自动平均取未完成最少且可接单的成员"
+                : "该字段单独走 `ops_team/dispatch_mode/update`:有变化时在前一次档案保存成功后提交,与团队侧改同一个值,后写入者生效"
+              }
+            >
+              <select {...form.bind("dispatch_mode")}>
+                <option value="manual">手动分派</option>
+                <option value="auto_avg">自动均衡分派</option>
+              </select>
+            </Field>
+            <Field label="分成方式">
+              <select {...form.bind("settle_mode")}>
+                <option value="">未设置</option>
+                <option value="ratio">按比例分成</option>
+                <option value="amount">固定金额分成</option>
+                <option value="per_account">按账号数分成</option>
+              </select>
+            </Field>
+            <Field label="分成取值">
+              <input {...form.bind("settle_value")} />
+            </Field>
+            {modal.kind === "create" ? (
+              <>
+                <Field label="主账号登录名" hint="开通时录入的账号即该团队的主账号">
+                  <input {...form.bind("primary_username")} />
+                </Field>
+                <Field label="主账号手机号">
+                  <input {...form.bind("primary_mobile")} />
+                </Field>
+              </>
+            ) : null}
+          </>
+        ) : null}
+        {modal.kind === "member" ? (
+          <>
+            <Field label="成员登录名" required>
+              <input {...form.bind("username")} />
+            </Field>
+            <Field label="手机号">
+              <input {...form.bind("mobile")} />
+            </Field>
+            <Field label="可处理工单类型" hint="逗号分隔,留空=跟随团队">
+              <input {...form.bind("ticket_types")} />
+            </Field>
+          </>
+        ) : null}
+        {modal.kind === "scope" ? (
+          <>
+            <Field label="区域节点 ID" hint="逗号分隔;资源树本期只下发可见节点 ID,⛔ 回显该团队既有范围">
+              <input {...form.bind("region_node_ids")} />
+            </Field>
+            <Field label="客户 ID" hint="逗号分隔;须落在区域范围内">
+              <input {...form.bind("customer_ids")} />
+            </Field>
+          </>
+        ) : null}
+        {modal.kind === "delete" ? (
+          <Notice tone="warn">
+            删除前置检查由后端逐条实查(成员、主账号、客户当期归属、账号绑定、当前登录团队);分成行/账单明细/对账清单三项
+            dev 缺表 ⇒ 后端按「查不出依赖⛔ 放行删除」纪律显式拒绝。
+          </Notice>
+        ) : null}
+        <div className="form-actions">
+          {sub.error ? <ErrorBox error={sub.error} /> : null}
+          <Btn onClick={() => void submit()} disabled={sub.busy}>
+            {sub.busy ? "提交中…" : "提交"}
+          </Btn>
+          <Btn ghost onClick={close}>
+            取消
+          </Btn>
+        </div>
+      </div>
+    </Modal>
+  );
+}
+
+function CoverageBody() {
+  const cov = useLoad(() => opsTeamCoverageGet(), []);
+  if (cov.error) return <ErrorBox error={cov.error} />;
+  if (cov.loading) return <Loading />;
+  if (!cov.data?.customers.length) return <Empty text="当前暂无承接客户" />;
+  return (
+    <>
+      <table>
+        <thead>
+          <tr>
+            <th>客户名称</th>
+            <th>客户 ID</th>
+            <th>生效起</th>
+          </tr>
+        </thead>
+        <tbody>
+          {cov.data.customers.map((c) => (
+            <tr key={c.customer_id}>
+              <td>{c.customer_name}</td>
+              <td>{c.customer_id}</td>
+              <td>
+                <Cell v={c.valid_from} />
+              </td>
+            </tr>
+          ))}
+        </tbody>
+      </table>
+      <Note>共 {cov.data.total} 家客户(团队区域范围 ∩ 客户归属)。</Note>
+    </>
+  );
+}

+ 502 - 0
front-end/src/pages/PartnersPage.tsx

@@ -0,0 +1,502 @@
+import { useState } from "react";
+import { SETTLE_MODE, TARGET_TYPE, label } from "../api/labels";
+import {
+  partnerCreate,
+  partnerDelete,
+  partnerGetList,
+  partnerScopeGet,
+  partnerScopeSave,
+  partnerUpdate,
+  regionTree,
+} from "../api/bos";
+import type { PartnerRow } from "../api/types";
+import {
+  AcctCell,
+  Btn,
+  Cell,
+  Drawer,
+  Empty,
+  ErrorBox,
+  Field,
+  Loading,
+  Modal,
+  Note,
+  Notice,
+  Pager,
+  Panel,
+  ScopeText,
+  seq,
+  useToast,
+} from "../components/ui";
+import { useLoad, useForm, useSubmit } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+
+const PAGE_SIZE = 20;
+
+/**
+ * 区域选择:`region/tree@v1` 本期只下发 `node_ids`(⛔ 名称、⛔ 层级、⛔ 父子),
+ * 故下拉直接列出可见节点 ID;取不到节点时才退回手工输入兜底。
+ */
+function RegionPicker({
+  value,
+  onChange,
+  nodes,
+  placeholder,
+}: {
+  value: string;
+  onChange: (v: string) => void;
+  nodes: string[];
+  placeholder: string;
+}) {
+  if (!nodes.length) {
+    return (
+      <input
+        value={value}
+        onChange={(e) => onChange(e.target.value)}
+        placeholder="区域节点 ID,例如 RN_310000(资源树不可用时手工输入)"
+      />
+    );
+  }
+  const opts = value && !nodes.includes(value) ? [value, ...nodes] : nodes;
+  return (
+    <select value={value} onChange={(e) => onChange(e.target.value)}>
+      <option value="">{placeholder}</option>
+      {opts.map((id) => (
+        <option key={id} value={id}>
+          {id}
+        </option>
+      ))}
+    </select>
+  );
+}
+
+type ModalKind =
+  | { kind: "create" }
+  | { kind: "update"; row: PartnerRow }
+  | { kind: "scope"; row: PartnerRow }
+  | { kind: "delete"; row: PartnerRow }
+  | null;
+
+export function PartnersPage() {
+  const toast = useToast();
+  const { ctx } = useSession();
+  const canAdmin = ctx?.role_code === "admin";
+  const [keyword, setKeyword] = useState("");
+  const [region, setRegion] = useState("");
+  const [page, setPage] = useState(1);
+  const [modal, setModal] = useState<ModalKind>(null);
+  const [scopeOpen, setScopeOpen] = useState(false);
+  const sub = useSubmit();
+  const form = useForm();
+
+  const { data, loading, error, reload } = useLoad(
+    () =>
+      partnerGetList({
+        page: page - 1,
+        page_size: PAGE_SIZE,
+        keyword: keyword || undefined,
+        region_node_id: region || undefined,
+      }),
+    [page, keyword, region],
+  );
+
+  const tree = useLoad(() => regionTree(), []);
+  const nodes = tree.data?.node_ids ?? [];
+
+  const rows = data?.items ?? [];
+  const total = data?.total ?? 0;
+
+  const close = () => {
+    setModal(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const reset = () => {
+    setKeyword("");
+    setRegion("");
+    setPage(1);
+  };
+
+  const openCreate = () => {
+    form.reset({ region_node_id: nodes[0] ?? "" });
+    setModal({ kind: "create" });
+  };
+
+  const split = (s: string) => s.split(/[\s,,、]+/).filter(Boolean);
+
+  const submit = async () => {
+    if (!modal) return;
+    const sv = form.get("settle_value");
+    const ok = await sub.run(() => {
+      switch (modal.kind) {
+        case "create":
+          return partnerCreate({
+            name: form.get("name"),
+            region_node_id: form.get("region_node_id"),
+            username: form.get("username"),
+            duty_desc: form.get("duty_desc") || undefined,
+            mobile: form.get("mobile") || undefined,
+            settle_mode: form.get("settle_mode") || undefined,
+            settle_value: sv ? Number(sv) : undefined,
+          });
+        case "update":
+          return partnerUpdate({
+            partner_id: modal.row.partner_id,
+            name: form.get("name"),
+            duty_desc: form.get("duty_desc") || undefined,
+            region_node_id: form.get("region_node_id") || undefined,
+            mobile: form.get("mobile") || undefined,
+            settle_mode: form.get("settle_mode") || undefined,
+            settle_value: sv ? Number(sv) : undefined,
+          });
+        case "scope":
+          /* 保存后端回读;⛔ 本次不提交=清空该维度(后端按整体替换处理) */
+          return partnerScopeSave({
+            partner_id: modal.row.partner_id,
+            region_node_ids: split(form.get("region_node_ids")),
+            customer_ids: split(form.get("customer_ids")),
+          });
+        case "delete":
+          return partnerDelete({ partner_id: modal.row.partner_id });
+      }
+    });
+    if (!ok) return;
+    toast("已提交");
+    close();
+    reload();
+  };
+
+  return (
+    <Shell
+      route="partners"
+      title="合伙人管理"
+      hint="即原代理合作商。合伙人按所属区域建档,本人就是一个登录账号(不是团队,没有成员账号),不处理工单、不执行开停。账号管理在「账号」中完成:开通、重置密码、停用与重新启用。负责范围可多选区域或直接多选客户,取并集;未绑定合伙人的客户不进入其负责范围,也不产生本方分成与账单明细。新增、编辑、删除与账号变更均写审计日志,删除档案时登录账号同步注销。"
+    >
+      <Panel
+        title={`合伙人(共 ${total} 个,当前页显示 ${rows.length} 个)`}
+        extra={<Btn onClick={openCreate}>+ 新建合伙人</Btn>}
+        noteTitle="本页取数口径:与上段说明不一致的四处(区域中文名、负责范围、登录账号、操作列)"
+        note={
+          <>
+            ① 「所属区域」列显示本域 bos_region_meta.path_name 的<b>节点 ID 全路径</b>(鼠标悬停看建档节点):
+            平台资源元数据只开了新建/重命名/删除,⛔「按节点 ID 批量取中文名」的读接口(18 册在册,已提请平台侧提供),
+            故⛔ 显示成「上海市 / 青浦区」这类中文名;「按区域(含下级)」下拉同样列出可见节点 ID,是否含下级由后端判定。
+            ② 「负责范围」「覆盖客户」两列由列表接口随行内联下发(scope):负责范围读取路由只回<b>当前登录主体自己</b>的授权
+            (合伙人身份见筛选条「我的负责范围」抽屉),⛔ 按他人查询,故⛔ 另开越权路由。「覆盖客户」为范围(含下级)内去重在册客户数,
+            括号内为已绑定到该合伙人名下的客户数;范围未配置时显「范围未配置」而⛔ 折算 0。
+            ③ 「登录账号」列三行分别为账号状态、登录名、手机号——由后端随行内联下发(bos_account_ext ⋈ bos_user_binding),
+            未开通的下发 null ⇒ 显「尚未开通」而⛔ 补一个占位账号;手机号已按需求§5.4 掩码下发,前端⛔ 还原明文。
+            同主体绑定多账号时取代表账号并在末行标注名下总数。
+            ④ 筛选:「按区域(含下级)」以 region_node_id 传后端,「按名称 / 渠道说明 / 通知地址」以 keyword 传后端
+            (后端只按名称匹配,渠道说明与通知地址本期⛔ 下发);后端另有 status 入参,原型筛选条没有该项,本期按原型口径不渲染。
+            列表为服务端分页,面板头计数为「共 后端总条数 / 当前页显示 当页条数」。
+            ⑤ 原型操作列的「配置范围」本期开放:弹窗回显取自列表内联的 scope(⛔ 调「按他人读取范围」的路由),保存直连
+            partner/scope/save@v1。「账号」按钮本期仍不渲染——合伙人账号的开通/重置/停用路由在本域⛔ 实现(18 册在册),
+            ⛔ 借总运营账号接口越权代办。写入口(新建/编辑/删除/配置范围)的权限由后端裁决,后端拒绝时如实显示 code+error_code,
+            ⛔ 假装成功或本地改一行。
+          </>
+        }
+      >
+        <div className="filters">
+          <Field label="按区域(含下级)">
+            <RegionPicker
+              value={region}
+              onChange={(v) => {
+                setRegion(v);
+                setPage(1);
+              }}
+              nodes={nodes}
+              placeholder="全部区域"
+            />
+          </Field>
+          <Field label="按名称 / 渠道说明 / 通知地址">
+            <input
+              value={keyword}
+              onChange={(e) => {
+                setKeyword(e.target.value);
+                setPage(1);
+              }}
+              placeholder="输入关键字,例如 华东"
+            />
+          </Field>
+          {ctx?.subject_type === "partner" ?
+            <Field label="我的负责范围">
+              <Btn ghost onClick={() => setScopeOpen(true)}>
+                查看授权客户
+              </Btn>
+            </Field>
+          : null}
+          <Field label={" "}>
+            <Btn ghost onClick={reset}>
+              重置筛选
+            </Btn>
+          </Field>
+        </div>
+
+        {error ? <ErrorBox error={error} /> : null}
+        {loading && !data ? <Loading /> : (
+          <table>
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th>合伙人</th>
+                <th>所属区域</th>
+                <th>登录账号</th>
+                <th>分成方式</th>
+                <th>分成比例/金额</th>
+                <th>负责范围</th>
+                <th>覆盖客户</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.length ? (
+                rows.map((r, i) => (
+                  <tr key={r.partner_id}>
+                    <td>{seq(page, PAGE_SIZE, i)}</td>
+                    <td>
+                      {r.name}
+                      {r.duty_desc ? (
+                        <>
+                          <br />
+                          <span className="note">{r.duty_desc}</span>
+                        </>
+                      ) : null}
+                    </td>
+                    <td title={`建档区域节点:${r.region_node_id}`}>
+                      {r.region_path_name ?? r.region_node_id}
+                      {r.region_level ? (
+                        <>
+                          <br />
+                          <span className="note">{r.region_level}</span>
+                        </>
+                      ) : null}
+                    </td>
+                    <td>
+                      <AcctCell acc={r.account} />
+                    </td>
+                    <td>{label(SETTLE_MODE, r.settle_mode) || <Cell v={null} />}</td>
+                    <td>
+                      <Cell v={r.settle_value} />
+                    </td>
+                    <td className="wrap">
+                      <ScopeText regions={r.scope.regions} customers={r.scope.customers} />
+                    </td>
+                    <td>
+                      {r.scope.coverage_customers === null ? (
+                        <span className="note">范围未配置</span>
+                      ) : (
+                        <>
+                          {r.scope.coverage_customers}(名下 {r.customer_count})
+                        </>
+                      )}
+                    </td>
+                    <td>
+                      <Btn
+                        ghost
+                        title="回显取自本行内联的负责范围(列表接口下发),⛔ 调按他人读取范围的路由"
+                        onClick={() => {
+                          form.reset({
+                            region_node_ids: r.scope.regions.join("、"),
+                            customer_ids: r.scope.customers.join("、"),
+                          });
+                          setModal({ kind: "scope", row: r });
+                        }}
+                      >
+                        配置范围
+                      </Btn>
+                      <Btn
+                        ghost
+                        onClick={() => {
+                          form.reset({
+                            name: r.name,
+                            duty_desc: r.duty_desc ?? "",
+                            region_node_id: r.region_node_id,
+                            mobile: "",
+                            settle_mode: r.settle_mode ?? "",
+                            settle_value: r.settle_value ?? "",
+                          });
+                          setModal({ kind: "update", row: r });
+                        }}
+                      >
+                        编辑
+                      </Btn>
+                      <Btn
+                        ghost
+                        danger
+                        onClick={() => {
+                          form.reset();
+                          setModal({ kind: "delete", row: r });
+                        }}
+                      >
+                        删除
+                      </Btn>
+                    </td>
+                  </tr>
+                ))
+              ) : (
+                <Empty
+                  cols={9}
+                  text={canAdmin ? "没有符合筛选条件的合伙人" : "您的负责范围内没有合伙人,可调整筛选条件"}
+                />
+              )}
+            </tbody>
+          </table>
+        )}
+
+        <Note>
+          所属区域为建档区域,显示全路径;按区域筛选时含该区域下级建档的合伙人。覆盖客户按负责范围实时计算,括号内为已绑定到该合伙人名下的客户数。
+          登录账号与档案一比一:未开通的可点「账号」开通,停用的账号不出现在「换身份」列表中,删除档案时账号同步注销。
+          账号可绑定手机号(选填、全站唯一),绑定后可用手机号代替登录名登录。运营主账号只列出建档区域落在自己负责范围(含下级区域)内的合伙人,
+          建档在范围外的合伙人整体不可见,并只能在该范围内新增、编辑、删除与配置负责范围;「分成方式」与「分成比例/金额」仍只由总运营维护,
+          运营侧一律只读。运营子账号档案只读。
+        </Note>
+
+        {data ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+      </Panel>
+
+      {modal ? (
+        <Modal
+          title={
+            modal.kind === "create"
+              ? "新建合伙人"
+              : modal.kind === "update"
+                ? `编辑合伙人 · ${modal.row.name}`
+                : modal.kind === "scope"
+                  ? `配置范围 · ${modal.row.name}`
+                  : `删除合伙人 · ${modal.row.name}`
+          }
+          onClose={close}
+        >
+          <div className="form-grid">
+            {modal.kind === "create" || modal.kind === "update" ? (
+              <>
+                <Field label="名称" required hint="全站唯一">
+                  <input {...form.bind("name")} />
+                </Field>
+                {modal.kind === "create" ? (
+                  <>
+                    <Field label="登录名" required hint="登录名创建后不可修改">
+                      <input {...form.bind("username")} />
+                    </Field>
+                    <Field
+                      label="区域节点"
+                      required
+                      hint="资源树接口本期只下发可见节点 ID(⛔ 名称与层级),默认从可见节点下拉选择"
+                    >
+                      <RegionPicker
+                        value={form.vals.region_node_id ?? ""}
+                        onChange={(v) => form.set("region_node_id", v)}
+                        nodes={nodes}
+                        placeholder="请选择区域节点"
+                      />
+                    </Field>
+                  </>
+                ) : (
+                  <Field label="区域节点" hint="留空=不修改">
+                    <RegionPicker
+                      value={form.vals.region_node_id ?? ""}
+                      onChange={(v) => form.set("region_node_id", v)}
+                      nodes={nodes}
+                      placeholder="不修改"
+                    />
+                  </Field>
+                )}
+                <Field label="职责说明">
+                  <input {...form.bind("duty_desc")} />
+                </Field>
+                <Field label="手机号" hint={modal.kind === "update" ? "编辑时列表回显为掩码,留空=不修改" : undefined}>
+                  <input {...form.bind("mobile")} />
+                </Field>
+                <Field label="分成方式">
+                  <select {...form.bind("settle_mode")}>
+                    <option value="">未设置</option>
+                    <option value="ratio">按比例分成</option>
+                    <option value="amount">固定金额分成</option>
+                    <option value="per_account">按账号数分成</option>
+                  </select>
+                </Field>
+                <Field label="分成取值">
+                  <input {...form.bind("settle_value")} />
+                </Field>
+              </>
+            ) : modal.kind === "scope" ? (
+              <>
+                <Field
+                  label="区域节点"
+                  hint="多个以空格/逗号分隔;清空后提交=清空该维度全部授权(整体替换,⛔ 增量追加)"
+                >
+                  <input {...form.bind("region_node_ids")} placeholder="RN_01, RN_02" />
+                </Field>
+                <Field label="客户 ID" hint="可直接指定客户,与区域取并集;区域只有节点 ID,中文名称待平台侧读接口">
+                  <input {...form.bind("customer_ids")} placeholder="CUST_001, CUST_002" />
+                </Field>
+                <Notice tone="warn">
+                  回显取自列表内联的 scope(负责范围读取路由只回<b>当前登录主体自己</b>的授权,⛔ 按他人查询);
+                  保存走 partner/scope/save@v1 整体替换后由后端回读,权限与守卫由后端裁决,
+                  拒绝时如实显示 code+error_code,⛔ 假装已保存。
+                </Notice>
+              </>
+            ) : (
+              <Notice tone="warn">
+                删除会一并清理该合伙人的客户授权;守卫与清理由后端执行,拒绝时如实显示 `code`+`error_code`。
+              </Notice>
+            )}
+            <div className="form-actions">
+              {sub.error ? <ErrorBox error={sub.error} /> : null}
+              <Btn onClick={() => void submit()} disabled={sub.busy}>
+                {sub.busy ? "提交中…" : "提交"}
+              </Btn>
+              <Btn ghost onClick={close}>
+                取消
+              </Btn>
+            </div>
+          </div>
+        </Modal>
+      ) : null}
+
+      {scopeOpen ? (
+        <Drawer title="我的负责范围(合伙人 → 客户)" onClose={() => setScopeOpen(false)}>
+          <ScopeBody />
+        </Drawer>
+      ) : null}
+    </Shell>
+  );
+}
+
+/** 抽屉内容单独成组件:只在打开时才发请求,未打开时⛔ 用假数据占位。 */
+function ScopeBody() {
+  const scope = useLoad(() => partnerScopeGet(), []);
+  if (scope.error) return <ErrorBox error={scope.error} />;
+  if (scope.loading) return <Loading />;
+  if (!scope.data?.grants.length) return <Empty text="负责范围内暂无客户" />;
+  return (
+    <>
+      <table>
+        <thead>
+          <tr>
+            <th>授权类型</th>
+            <th>目标 ID</th>
+            <th>更新时间</th>
+          </tr>
+        </thead>
+        <tbody>
+          {scope.data.grants.map((g) => (
+            <tr key={`${g.target_type}:${g.target_id}`}>
+              <td>{label(TARGET_TYPE, g.target_type)}</td>
+              <td>{g.target_id}</td>
+              <td>
+                <Cell v={g.updated_at} />
+              </td>
+            </tr>
+          ))}
+        </tbody>
+      </table>
+      <Note>
+        后端仅下发 target_type / target_id(共 {scope.data.total} 条),⛔ 客户名称数源,故此处只列 ID。
+      </Note>
+    </>
+  );
+}

+ 446 - 0
front-end/src/pages/RegionsPage.tsx

@@ -0,0 +1,446 @@
+import { useState } from "react";
+import { useNavigate } from "react-router-dom";
+import {
+  regionCreate,
+  regionDelete,
+  regionRename,
+  regionTree,
+} from "../api/bos";
+import type { RegionNode } from "../api/types";
+import { useSession } from "../auth/session";
+import { Btn, ErrorBox, Field, Loading, Modal, useToast } from "../components/ui";
+import { useForm, useLoad, useSubmit } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+/** 原型 `pageRegions` 的 hint(去掉强调标记后的纯文本口径)。 */
+const HINT =
+  "三级:省 / 市 / 区县。客户必须挂一个节点。右侧为区域概况卡片,点击卡片进入对应列表并进行增删改查;" +
+  "切换区域树节点会回到概况。";
+
+/** 原型 `ovCard()`:`button.card.ov-card > span.ov-title + b + span.ov-sub.note + span.ov-go`。 */
+function OvCard({
+  title,
+  value,
+  sub,
+  go,
+}: {
+  title: string;
+  value: string;
+  sub: string;
+  go?: () => void;
+}) {
+  return (
+    <button className="card ov-card" onClick={go} disabled={!go}>
+      <span className="ov-title">{title}</span>
+      <b>{value}</b>
+      <span className="ov-sub note">{sub}</span>
+      {go ? <span className="ov-go">查看列表 →</span> : null}
+    </button>
+  );
+}
+
+type ModalKind =
+  | { kind: "create"; parent_node_id?: string }
+  | { kind: "rename"; node_id: string }
+  | { kind: "delete"; node_id: string }
+  | null;
+
+export function RegionsPage() {
+  const toast = useToast();
+  const { ctx } = useSession();
+  const nav = useNavigate();
+  const canAdmin = ctx?.role_code === "admin";
+  const [modal, setModal] = useState<ModalKind>(null);
+  const [selId, setSelId] = useState("");
+  const [menu, setMenu] = useState("");
+  const [drill, setDrill] = useState("");
+
+  const tree = useLoad(() => regionTree(), []);
+  const sub = useSubmit();
+  const form = useForm();
+
+  const treeNodes = tree.data?.nodes ?? [];
+  /** 平台资源树的「全部」虚根:⛔ 区域节点(`bos_region_meta` ⛔ 该行),只作父子链中转。 */
+  const V_ROOT = "V-ALL";
+  const byParent = new Map<string | null, RegionNode[]>();
+  for (const n of treeNodes) {
+    if (n.node_id === V_ROOT) continue;
+    const p = !n.parent_id || n.parent_id === V_ROOT || n.parent_id === n.node_id ? null : n.parent_id;
+    const arr = byParent.get(p) ?? [];
+    arr.push(n);
+    byParent.set(p, arr);
+  }
+  byParent.forEach((v) => v.sort((a, b) => a.node_id.localeCompare(b.node_id)));
+  const kids = (p: string | null) => byParent.get(p) ?? [];
+  const nodeById = new Map(treeNodes.map((n) => [n.node_id, n]));
+  const nodes = treeNodes.filter((n) => n.node_id !== V_ROOT).map((n) => n.node_id);
+  const sel = selId && nodes.includes(selId) ? selId : nodes[0] ?? "";
+  const selNode = nodeById.get(sel);
+
+  /**
+   * 选中节点的承载量:直接取 `region/tree@v1` 已下发的 `counters`。
+   *
+   * 树接口的 `counters.operators/partners/ops_teams` 与三枚列表的 `total` 同源
+   * (都是本域主体表按 `region_node_id` 直接计数,见 handlers/region.rs 的 `count_by`),
+   * 故⛔ 再按节点并发三枚 `get_list@v1` 只取 `total`——2026-11-08 手测即因此
+   * 每点一次树节点重复打三次接口。点击树节点由此变为纯本地切换,⛔ 发请求。
+   */
+  const counters = selNode?.counters ?? null;
+  const countersReady = !tree.loading && !tree.error && !!counters;
+
+  /** 原型概况头部的「被引用 · 不可删」:只按运营商/合伙人/运维团队三项真计数判定;树未就绪时为 null(⛔ 当成「未被引用」)。 */
+  const referenced = !countersReady
+    ? null
+    : [counters.operators, counters.partners, counters.ops_teams].some((v) => v > 0);
+
+  const close = () => {
+    setModal(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const submit = async () => {
+    if (!modal) return;
+    const ok = await sub.run(() =>
+      modal.kind === "create"
+        ? regionCreate({
+            node_name: form.get("node_name"),
+            parent_node_id: modal.parent_node_id || form.get("parent_node_id") || undefined,
+          })
+        : modal.kind === "rename"
+          ? regionRename({ node_id: modal.node_id, node_name: form.get("node_name") })
+          : regionDelete({ node_id: modal.node_id, confirm_name: form.get("confirm_name") }),
+    );
+    if (!ok) return;
+    toast(modal.kind === "create" ? "节点已创建" : modal.kind === "rename" ? "节点已重命名" : "节点已删除");
+    close();
+    tree.reload();
+  };
+
+  const openCreate = (parent_node_id?: string) => {
+    form.reset(parent_node_id ? { parent_node_id } : {});
+    setMenu("");
+    setModal({ kind: "create", parent_node_id });
+  };
+
+  /** 原型 `treeHtml(parentId, depth)`:递归嵌套 `ul.tree`,一行=节点名+层级+承载量+菜单。 */
+  const treeNodeRow = (n: RegionNode): JSX.Element => (
+    <li key={n.node_id}>
+      <div className={`tree-node${sel === n.node_id ? " on" : ""}`}>
+        <button
+          className="tree-select"
+          title={n.name ? `节点 ID:${n.node_id}` : "平台未下发节点名,只能显示节点 ID"}
+          onClick={() => {
+            setSelId(n.node_id);
+            setMenu("");
+            setDrill("");
+          }}
+        >
+          {n.name ?? n.node_id}
+        </button>
+        {/* 层级=`bos_region_meta.level`(层级唯一落地位,总则§5.3);承载量=本域真查询计数。 */}
+        <span className="lv">{n.level_label ?? "—"}</span>
+        <span className="cnt">
+          直属 {n.counters.customers} · 含下级 {n.counters.customers_in_subtree}
+        </span>
+        {canAdmin ? (
+          <button
+            className="node-menu-btn"
+            title="操作菜单"
+            onClick={() => setMenu(menu === n.node_id ? "" : n.node_id)}
+          >
+            ⋯
+          </button>
+        ) : null}
+        {menu === n.node_id ? (
+          <div className="node-menu">
+            <button onClick={() => openCreate(n.node_id)}>新建下级节点</button>
+            <button
+              onClick={() => {
+                form.reset();
+                setMenu("");
+                setModal({ kind: "rename", node_id: n.node_id });
+              }}
+            >
+              重命名
+            </button>
+            <button
+              className="danger"
+              onClick={() => {
+                form.reset({ confirm_name: n.node_id });
+                setMenu("");
+                setModal({ kind: "delete", node_id: n.node_id });
+              }}
+            >
+              删除节点
+            </button>
+          </div>
+        ) : null}
+      </div>
+      {kids(n.node_id).length ? <ul className="tree">{kids(n.node_id).map((c) => treeNodeRow(c))}</ul> : null}
+    </li>
+  );
+
+  return (
+    <Shell route="regions" title="区域管理" hint={HINT} mainClass="stretch">
+      <div className="split region-split" style={{ gridTemplateColumns: "0.72fr 1.28fr" }}>
+        {/* ── 左:区域树(原型 .panel.uncut > .tree-head + ul.tree) ───────── */}
+        <div className="panel uncut">
+          <div className="tree-head">
+            <h2>区域树</h2>
+            {canAdmin ? <Btn ghost onClick={() => openCreate()}>+ 新建省份</Btn> : <span className="note">仅本团队负责范围</span>}
+          </div>
+          {tree.error ? <ErrorBox error={tree.error} /> : null}
+          {tree.loading ? <Loading /> : null}
+          {!tree.loading && !tree.error && nodes.length === 0 ? (
+            <p className="note">当前身份在资源树内没有可见节点</p>
+          ) : null}
+          {nodes.length ? (
+            <>
+              <ul className="tree">{kids(null).map((n) => treeNodeRow(n))}</ul>
+              <details className="note-details">
+                <summary>建节点规则与「为什么只能按节点 ID 平铺」</summary>
+                <div className="note">
+                  新建省份只有总部管理员可以——按需求确认(2026-11-03),省份由总部管理员在区域树手工「+ 新建省份」建,
+                  系统不会因新建运营商或客户自动建省份;新建后其下市/区县由该省的省级管理员自行新增,新建市须选省、
+                  新建区县须选市;客户档案里可选到的区域节点=该客户所属运营商的可见区域节点。
+                  删除或改挂区域前先提示受影响数量(含该节点及其下所有子节点);节点下已有客户时不可直接删除。
+                  <br />
+                  <b>本期取数口径</b>:树的结构、层级与承载量已是真数据——父子关系取 <code>dim_node_ancestor</code>
+                  (<code>depth=1</code> 即直接父,⛔ 由深度反推层级),层级取 <code>bos_region_meta.level</code>
+                  (层级的唯一落地位),承载量为本域真查询计数。<br />
+                  仍未解决的只有<b>节点中文名</b>:平台的资源元数据只开了新建/重命名/删除,⛔「按节点 ID 批量取中文名」
+                  的读接口(18 册在册,已提请平台侧提供),故节点名只能显示 <code>path_name</code> 的节点 ID 链
+                  ({tree.data?.note ?? "加载中…"}),⛔ 自行编造「XX省」这类名称。
+                </div>
+              </details>
+            </>
+          ) : null}
+        </div>
+
+        {/* ── 右:区域概况 / 区域信息下钻(原型 .region-over) ──────────── */}
+        <div className="region-over">
+          {drill === "" ? (
+            <>
+              <div className="panel ov-head">
+                <div className="row" style={{ justifyContent: "space-between", alignItems: "center" }}>
+                  <h2 style={{ margin: 0 }}>区域概况</h2>
+                  <span className="note">
+                    {sel ? (
+                      <>
+                        当前节点 <code>{sel}</code>
+                      </>
+                    ) : (
+                      "未选中节点"
+                    )}{" "}
+                    {referenced ? (
+                      <span className="ref-tag" title="被引用:运营商/合伙人/运维团队的负责范围引用本节点,不能删除">
+                        被引用 · 不可删
+                      </span>
+                    ) : referenced === false && canAdmin ? (
+                      <button
+                        className="icon-btn danger"
+                        title="删除本节点(需输入名称确认)"
+                        onClick={() => {
+                          form.reset({ confirm_name: sel });
+                          setModal({ kind: "delete", node_id: sel });
+                        }}
+                      >
+                        &#128465;
+                      </button>
+                    ) : null}
+                  </span>
+                </div>
+                <p className="note">
+                  点击下方卡片进入对应列表并进行增删改查。运营商/合伙人/运维团队与下挂客户四张卡片,全部取自{" "}
+                  <code>region/tree@v1</code> 一次下发的 <code>counters</code>(本域主体表按{" "}
+                  <code>region_node_id</code> 直接计数 + 挂载表去重计数),故切换树节点是纯本地切换、⛔ 再发请求;
+                  显「—」的卡片后端没有按节点统计的能力,⛔ 用 0 或估算值冒充。「区域信息」卡片只在选中节点时可点。
+                </p>
+              </div>
+              <div className="ov-grid">
+                <OvCard
+                  title="区域信息"
+                  value={sel ? "查看" : "—"}
+                  sub="结构与层级已下发;节点中文名待平台读接口"
+                  go={sel ? () => setDrill("info") : undefined}
+                />
+                <OvCard
+                  title="运营商"
+                  value={counters ? String(counters.operators) : "—"}
+                  sub="按建档区域节点统计,含下级由资源树裁决"
+                  go={() => nav("/operators")}
+                />
+                <OvCard
+                  title="合伙人"
+                  value={counters ? String(counters.partners) : "—"}
+                  sub="按建档区域节点统计"
+                  go={() => nav("/partners")}
+                />
+                <OvCard
+                  title="运营团队"
+                  value="—"
+                  sub="运营团队列表接口无区域入参,本期无法按节点统计"
+                  go={() => nav("/entteams")}
+                />
+                <OvCard
+                  title="运维团队"
+                  value={counters ? String(counters.ops_teams) : "—"}
+                  sub="按团队绑定区域节点统计"
+                  go={() => nav("/opsteams")}
+                />
+                <OvCard
+                  title="下挂客户"
+                  value={selNode ? String(selNode.counters.customers) : "—"}
+                  sub={
+                    selNode
+                      ? `直接挂载的去重在册客户;含下级 ${selNode.counters.customers_in_subtree} 家`
+                      : "选中节点后按挂载表统计"
+                  }
+                  go={() => nav("/customers")}
+                />
+              </div>
+            </>
+          ) : (
+            <div className="panel">
+              <div className="row" style={{ justifyContent: "space-between", alignItems: "center" }}>
+                <h2 style={{ margin: 0 }}>
+                  区域信息 <span className="note">节点 <code>{sel}</code></span>
+                </h2>
+                <span>
+                  <Btn ghost onClick={() => setDrill("")}>
+                    ← 返回概况
+                  </Btn>
+                </span>
+              </div>
+              <div className="cards">
+                <div className="card">
+                  <span>层级</span>
+                  <b>{selNode?.level_label ?? "—"}</b>
+                </div>
+                <div className="card">
+                  <span>直属客户</span>
+                  <b>{selNode ? selNode.counters.customers : "—"}</b>
+                </div>
+                <div className="card">
+                  <span>含下级客户</span>
+                  <b>{selNode ? selNode.counters.customers_in_subtree : "—"}</b>
+                </div>
+                <div className="card">
+                  <span>下级节点</span>
+                  <b>{selNode ? selNode.counters.children : "—"}</b>
+                </div>
+              </div>
+              <p className="note">
+                节点 <code>{sel}</code>
+                {selNode?.path_name ? ` · 路径 ${selNode.path_name}` : ""}
+                {selNode?.parent_id ? ` · 上级 ${selNode.parent_id}` : " · 上级 —(未在册或为顶层)"}
+                ;节点中文名待平台读接口(18 册在册),其余数值均为本域真查询:层级取{" "}
+                <code>bos_region_meta</code>,客户承载量取挂载表去重,子节点数取资源树深度关系。
+              </p>
+              {referenced ? (
+                <div className="alert">
+                  本节点被负责范围引用,不能删除:运营商/合伙人/运维团队的团队范围按 <code>region_node_id</code>=本节点有建档。
+                </div>
+              ) : null}
+              <p className="note">
+                原型这一屏的四个数值(层级/直属客户/含下级客户/下级节点)全部取自身已维护的区域树;
+                本期后端 <code>region/tree@v1</code> 只回可见节点 ID 集合,客户列表又不带区域字段 ⇒
+                四格统一显「—」,⛔ 编造;原型的「下级节点」表格同样因没有父子关系无法成行,本期不提供。
+                可执行的只有下面的节点维护动作。
+              </p>
+              <div className="form-actions">
+                {canAdmin ? (
+                  <>
+                    <Btn onClick={() => openCreate(sel)}>+ 新建下级节点</Btn>
+                    <Btn
+                      ghost
+                      onClick={() => {
+                        form.reset();
+                        setModal({ kind: "rename", node_id: sel });
+                      }}
+                    >
+                      重命名本节点
+                    </Btn>
+                    <Btn
+                      warn
+                      onClick={() => {
+                        form.reset({ confirm_name: sel });
+                        setModal({ kind: "delete", node_id: sel });
+                      }}
+                    >
+                      删除本节点
+                    </Btn>
+                  </>
+                ) : (
+                  <span className="note">当前身份没有区域维护权限(只有总部管理员可新增/重命名/删除节点)。</span>
+                )}
+              </div>
+            </div>
+          )}
+        </div>
+      </div>
+
+      {modal ? (
+        <Modal
+          title={
+            modal.kind === "create"
+              ? modal.parent_node_id
+                ? "新建下级节点"
+                : "新建省份"
+              : modal.kind === "rename"
+                ? "重命名节点"
+                : "删除节点"
+          }
+          onClose={close}
+        >
+          <div className="form-grid">
+            {modal.kind !== "create" ? (
+              <Field label="节点 ID">
+                <input readOnly value={modal.node_id} />
+              </Field>
+            ) : null}
+            {modal.kind === "create" ? (
+              <>
+                <Field
+                  label="上级节点 ID"
+                  hint="留空=挂在根下(建省份);填节点 ID=在其下建市/区县。层级由平台资源树裁决,本系统不校验。"
+                >
+                  <input {...form.bind("parent_node_id")} placeholder="RN_xxx" />
+                </Field>
+                <Field label="节点名称" required>
+                  <input {...form.bind("node_name")} placeholder="如 华东区" />
+                </Field>
+              </>
+            ) : null}
+            {modal.kind === "rename" ? (
+              <Field label="新名称" required hint="名称写入平台资源树;本系统不回读,故列表仍按节点 ID 展示。">
+                <input {...form.bind("node_name")} />
+              </Field>
+            ) : null}
+            {modal.kind === "delete" ? (
+              <>
+                <Field label="输入节点 ID 以确认" required hint="删除前平台会检查名下子节点与客户">
+                  <input {...form.bind("confirm_name")} />
+                </Field>
+                <p className="note">
+                  原型删除前有「受影响数量」清单(含下级节点与名下客户),该数据需资源树层级+客户按节点统计,
+                  本期两者均无数源 ⇒ 此处无法预先展示,改由平台侧守卫兜底(名下有子节点或客户时删除会被拒绝)。
+                </p>
+              </>
+            ) : null}
+            <div className="form-actions">
+              {sub.error ? <ErrorBox error={sub.error} /> : null}
+              <Btn onClick={() => void submit()} disabled={sub.busy}>
+                {sub.busy ? "提交中…" : "提交"}
+              </Btn>
+              <Btn ghost onClick={close}>
+                取消
+              </Btn>
+            </div>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}

+ 296 - 0
front-end/src/pages/SubAccountsPage.tsx

@@ -0,0 +1,296 @@
+import { useState } from "react";
+import { ACCT_STATUS, label } from "../api/labels";
+import { customerGetList, subAccountGetList, subAccountUpdate } from "../api/bos";
+import type { SubAccountRow } from "../api/types";
+import { useSession } from "../auth/session";
+import { Btn, Cell, ErrorBox, Field, Loading, Modal, Pager, Panel, PanelHead, Pill } from "../components/ui";
+import { useLoad, useForm, useSubmit } from "../hooks/useLoad";
+import { Shell } from "../layout/Shell";
+
+const PAGE_SIZE = 20;
+
+/**
+ * 原型 `pageAccounts` 页头副题(`.top > div > h1 + p`)逐字沿用;额度(分账号数量上限)接口未下发
+ * ⇒ 显「—」,⛔ 以金额或分账号数冒充额度。
+ */
+const HINT =
+  "额度 —,以套餐订阅时的合同额度为准,分账号数量由系统按额度自动补齐;账号名为客户主账号加序号,网络侧账号名(零信任客户端)由运营在客户管理页填写。姓名由客户主账号在本页维护。本页不提供账号停用入口:2026-11-02 定案客户侧⛔ 无自助停用,需要停号请联系运营,由运营发起「服务停用」工单在网络侧办理。";
+
+/** 原型 A28 的「在用」口径:只有该状态的行给「改姓名」入口。 */
+const IN_USE = ["in_use", "active", "normal"];
+
+/**
+ * 下属分账号(原型 `pageAccounts`)。
+ *
+ * ⚠️ `/sub_account/get_list@v1` 必须带 `customer_id`:
+ * 企业主账号(subject_type=customer)与分账号(sub_account)直接取会话主体 ID;
+ * 运营/管理员须先选客户。
+ */
+export function SubAccountsPage() {
+  const { ctx } = useSession();
+  const ownId =
+    ctx?.subject_type === "customer" || ctx?.subject_type === "sub_account" ? (ctx?.subject_id ?? "") : "";
+  const isMain = ctx?.subject_type === "customer";
+  const [customerId, setCustomerId] = useState(ownId);
+
+  return (
+    <Shell route="subaccounts" title="下属分账号" hint={HINT}>
+      {customerId ? (
+        <SubAccountTable customerId={customerId} isMain={isMain} onSwitch={ownId ? undefined : () => setCustomerId("")} />
+      ) : (
+        <CustomerPick onPick={setCustomerId} />
+      )}
+    </Shell>
+  );
+}
+
+/** 运营侧入口:先选客户(可见范围由后端按角色下发)。 */
+function CustomerPick({ onPick }: { onPick: (id: string) => void }) {
+  const [keyword, setKeyword] = useState("");
+  const [page, setPage] = useState(1);
+  const { data, loading, error, reload } = useLoad(
+    () => customerGetList({ page: page - 1, page_size: PAGE_SIZE, keyword: keyword || undefined }),
+    [page, keyword],
+  );
+  const items = data?.items ?? [];
+
+  return (
+    <Panel
+      title={<>选择客户(共 {data?.total ?? 0} 家,当前页显示 {items.length} 家)</>}
+      extra={
+        <Btn ghost onClick={reload}>
+          刷新
+        </Btn>
+      }
+      note="分账号列表接口须指定客户,这里先按本人可见范围选人;客户列表只回「分账号数」,⛔ 回分账号额度(数量上限),故进入后提示句里的额度显「—」。"
+    >
+      <div className="filters">
+        <Field label="客户名称/识别号">
+          <input
+            value={keyword}
+            onChange={(e) => {
+              setKeyword(e.target.value);
+              setPage(1);
+            }}
+          />
+        </Field>
+        <Field label={"\u00A0"}>
+          <Btn
+            ghost
+            onClick={() => {
+              setKeyword("");
+              setPage(1);
+            }}
+          >
+            重置筛选
+          </Btn>
+        </Field>
+      </div>
+      {error ? <ErrorBox error={error} /> : null}
+      {loading && !data ? <Loading /> : null}
+      {data ? (
+        <>
+          <table>
+            <thead>
+              <tr>
+                <th>客户名称</th>
+                <th>客户 ID</th>
+                <th>分账号数</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {items.map((r) => (
+                <tr key={r.customer_id}>
+                  <td>{r.customer_name}</td>
+                  <td>{r.customer_id}</td>
+                  <td>
+                    <Cell v={r.sub_account_count} />
+                  </td>
+                  <td>
+                    <Btn ghost onClick={() => onPick(r.customer_id)}>
+                      查看分账号
+                    </Btn>
+                  </td>
+                </tr>
+              ))}
+              {!items.length ? (
+                <tr>
+                  <td colSpan={4} className="note">
+                    {keyword.trim() ? `没有匹配「${keyword.trim()}」的客户,可换个关键字或点「重置筛选」` : "可见范围内没有客户"}
+                  </td>
+                </tr>
+              ) : null}
+            </tbody>
+          </table>
+          {(data?.total ?? 0) > 0 ? <Pager page={page} page_size={PAGE_SIZE} total={data?.total ?? 0} onChange={setPage} /> : null}
+        </>
+      ) : null}
+    </Panel>
+  );
+}
+
+function SubAccountTable({
+  customerId,
+  isMain,
+  onSwitch,
+}: {
+  customerId: string;
+  isMain: boolean;
+  onSwitch?: () => void;
+}) {
+  const [page, setPage] = useState(1);
+  const [editing, setEditing] = useState<SubAccountRow | null>(null);
+  const form = useForm();
+  const sub = useSubmit();
+
+  // 原型本页(pageAccounts / pageEntSubs)⛔ 筛选条:面板里就是一张表,故不给关键字下拉
+  const { data, loading, error, reload } = useLoad(
+    () => subAccountGetList({ customer_id: customerId, page: page - 1, page_size: PAGE_SIZE }),
+    [customerId, page],
+  );
+
+  const items = data?.items ?? [];
+  const total = data?.total ?? 0;
+
+  const close = () => {
+    setEditing(null);
+    sub.clear();
+    form.reset();
+  };
+
+  const submit = async () => {
+    if (!editing) return;
+    const ok = await sub.run(() =>
+      subAccountUpdate({
+        sub_account_id: editing.sub_account_id,
+        display_name: form.get("display_name") || undefined,
+        // 客户主账号只许改 display_name(后端拒收 network_account_name),故该身份不送该字段
+        network_account_name: isMain ? undefined : form.get("net_account") || undefined,
+      }),
+    );
+    if (!ok) return;
+    close();
+    reload();
+  };
+
+  return (
+    <div className="panel">
+      {/* 原型 `pageAccounts` 的面板内只有 `table`(口径句在页头副题):⛔ 面板头与面板底 note。
+          运营侧要多一个「换个客户」入口(原型无运营侧页面),只在该入口真需要时才摆面板头。 */}
+      {onSwitch ? (
+        <PanelHead
+          title={<>分账号清单(共 {total} 条,当前页显示 {items.length} 条)</>}
+          right={
+            <>
+              <Btn ghost onClick={onSwitch}>
+                换个客户
+              </Btn>
+              <Btn ghost onClick={reload}>
+                刷新
+              </Btn>
+            </>
+          }
+        />
+      ) : null}
+      {error ? <ErrorBox error={error} /> : null}
+      {loading && !data ? <Loading /> : null}
+      {data ? (
+        <>
+          <table>
+            <thead>
+              <tr>
+                <th>姓名</th>
+                <th>网络侧账号名</th>
+                <th>状态</th>
+                <th>开通时间</th>
+                <th>停用时间</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {items.map((r) => (
+                <tr key={r.sub_account_id}>
+                  <td>
+                    <Cell v={r.display_name} />
+                  </td>
+                  <td>
+                    <Cell v={r.net_account} dash="待开通" />
+                  </td>
+                  <td>
+                    <Pill text={label(ACCT_STATUS, r.status)} />
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>
+                    <Cell v={null} />
+                  </td>
+                  <td>
+                    {!isMain || IN_USE.includes(r.status) ? (
+                      <Btn
+                        ghost
+                        onClick={() => {
+                          form.reset({ display_name: r.display_name ?? "", net_account: r.net_account ?? "" });
+                          setEditing(r);
+                        }}
+                      >
+                        {isMain ? "改姓名" : "编辑"}
+                      </Btn>
+                    ) : null}
+                  </td>
+                </tr>
+              ))}
+              {!items.length ? (
+                <tr>
+                  <td colSpan={6} className="note">
+                    该客户还没有下属分账号(额度内应已自动补齐,稍后刷新或联系运营)
+                  </td>
+                </tr>
+              ) : null}
+            </tbody>
+          </table>
+          {total > 0 ? <Pager page={page} page_size={PAGE_SIZE} total={total} onChange={setPage} /> : null}
+        </>
+      ) : null}
+
+      {editing ? (
+        <Modal title={`${isMain ? "改姓名" : "编辑分账号"} · ${editing.username ?? editing.sub_account_id}`} onClose={close}>
+          <div className="form-grid">
+            <Field label="姓名">
+              <input {...form.bind("display_name")} />
+            </Field>
+            {!isMain ? (
+              <Field label="网络侧账号名" hint="仅运营可改">
+                <input {...form.bind("net_account")} />
+              </Field>
+            ) : null}
+            <div className="form-actions">
+              {sub.error ? <ErrorBox error={sub.error} /> : null}
+              <Btn onClick={() => void submit()} disabled={sub.busy}>
+                {sub.busy ? "提交中…" : "提交"}
+              </Btn>
+              <Btn ghost onClick={close}>
+                取消
+              </Btn>
+            </div>
+          </div>
+        </Modal>
+      ) : null}
+
+      <details className="note-details">
+        <summary>本页口径(额度、开通时间与可改字段)</summary>
+        <div className="note">
+          ①「开通时间」「停用时间」两列——`/sub_account/get_list@v1`⛔
+          下发(只回 `created_at` 建档时间与 `status`),两列按原型保留并显「—」,⛔
+          以建档时间冒充开通时间。②页头副题里的「额度」同上,接口未下发,显「—」,⛔ 以套餐金额或分账号数量冒充额度。③原型按
+          <b>禁用=不渲染</b>(A28):客户主账号身份下只有「在用」行给「改姓名」,其余状态行该格出空单元格;运营侧还需填写网络侧账号名,故运营身份全行给「编辑」。④编辑只改姓名与网络侧账号名,走写侧真落库,后端拒绝时如实显示
+          <b> code+error_code</b>;客户主账号只许改姓名,故该身份的弹窗不出网络侧账号名字段。⑤原型面板内就是一张全量列表(⛔ 面板头、⛔
+          筛选条、⛔ 分页条),本页据此在客户身份下只出表;正式系统是服务端分页,故底部按后端真有的 `total` 出分页条,运营身份另在面板头给「换个客户」与「刷新」(原型无运营侧页面,该入口为正式系统补齐)。⑥接口另下发「登录名」(`username`)与「用途」(`purpose`),原型本页是五列只读、没有这两列,故未在表内呈现(登录名只在弹窗标题里用到),`sub_account/update@v1`⛔
+          改「用途」。⑦「+ 新增分账号」「立即停用」原型本页没有,且 `sub_account/create`/`disable` 写侧未接通,故⛔
+          放空壳按钮,需要请到客户档案页办理。
+        </div>
+      </details>
+    </div>
+  );
+}

+ 86 - 0
front-end/src/styles/app.css

@@ -0,0 +1,86 @@
+/* 本文件只补 prototype.css 没有的少量结构类,配色与字体全部沿用 :root 变量;
+   原型已有的类(.panel/.filters/.pager/.card/.tree-node/.kv…)⛔ 在这里重复定义,避免覆盖原型观感。 */
+
+.toast-stack {
+  position: fixed;
+  right: 20px;
+  bottom: 20px;
+  z-index: 120;
+  display: flex;
+  flex-direction: column;
+  gap: 8px;
+}
+.toast-stack .toast {
+  position: static;
+  animation: fadeInUp 220ms ease both;
+}
+.toast-stack .toast.bad {
+  border-color: var(--red);
+  color: var(--red);
+}
+
+table th.num,
+table td.num {
+  text-align: right;
+  font-variant-numeric: tabular-nums;
+}
+
+.kv {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+  gap: 8px 18px;
+  font-size: 13px;
+}
+.kv div {
+  display: flex;
+  gap: 8px;
+}
+.kv dt,
+.kv .k {
+  color: var(--muted);
+  min-width: 92px;
+}
+
+.code-chip {
+  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+  background: rgba(14, 110, 104, 0.08);
+  border: 1px solid rgba(14, 110, 104, 0.25);
+  color: var(--teal-ink);
+  padding: 2px 6px;
+  border-radius: 4px;
+  letter-spacing: 0.04em;
+}
+
+/* 登录页:外壳沿用原型 .login / .login-side / .login-main,这里只补窄栏与验证码行 */
+.login-form {
+  max-width: 620px;
+}
+.login-side .note {
+  color: #9dbdb7;
+}
+.captcha-row {
+  display: flex;
+  gap: 10px;
+  align-items: flex-end;
+}
+.captcha-row input {
+  flex: 1;
+}
+.captcha-row img {
+  height: 38px;
+  border: 1px solid var(--line);
+  border-radius: 6px;
+  background: #fff;
+  cursor: pointer;
+}
+
+.guard {
+  padding: 60px 24px;
+  text-align: center;
+  color: var(--muted);
+}
+.guard .big {
+  font-size: 18px;
+  color: var(--ink);
+  margin-bottom: 8px;
+}

+ 1118 - 0
front-end/src/styles/prototype.css

@@ -0,0 +1,1118 @@
+:root {
+  --ink: #1b2430;
+  --muted: #5c6b7a;
+  --line: #e2d9cc;
+  --paper: #f6f1e8;
+  --card: #fffdf8;
+  --teal: #0e6e68;
+  --teal-ink: #084843;
+  --amber: #9a5b12;
+  --red: #8f2d2d;
+  --green: #1d6b45;
+  --shadow: 0 10px 30px rgba(40, 32, 20, 0.06);
+  font-family: "PingFang SC", "Noto Sans SC", "Source Han Sans SC", sans-serif;
+}
+
+* { box-sizing: border-box; }
+body { margin: 0; color: var(--ink); background: var(--paper); }
+button, input, select, textarea { font: inherit; color: inherit; }
+button { cursor: pointer; }
+h1, h2, h3, p { margin: 0; }
+
+.login {
+  min-height: 100vh;
+  display: grid;
+  grid-template-columns: 320px 1fr;
+}
+.login-side {
+  background: var(--teal-ink);
+  color: #f3efe6;
+  padding: 48px 36px;
+}
+.login-side h1 { font-size: 28px; font-weight: 650; letter-spacing: 0.04em; }
+.login-side p { margin-top: 16px; line-height: 1.7; color: #d5ebe8; }
+.login-main { padding: 40px 48px 64px; }
+/* 身份选择:组织机构图,按层次排布,同层节点在同一水平线 */
+.org-chart { margin-top: 20px; overflow-x: auto; padding-bottom: 10px; }
+.org-chart ul { display: flex; justify-content: center; list-style: none; margin: 0; padding: 22px 0 0; position: relative; }
+.org-chart > ul { padding-top: 0; }
+.org-chart li { display: flex; flex-direction: column; align-items: center; position: relative; padding: 22px 4px 0; }
+/* 子节点上方的连接线:左右两段横线拼成本节点的横向挂线 */
+.org-chart li::before, .org-chart li::after {
+  content: "";
+  position: absolute;
+  top: 0;
+  right: 50%;
+  width: 50%;
+  height: 22px;
+  border-top: 1px dashed #c8bca8;
+}
+.org-chart li::after { right: auto; left: 50%; border-left: 1px dashed #c8bca8; }
+/* 独子不需要横挂线,直接从父节点垂直落下 */
+.org-chart li:only-child { padding-top: 0; }
+.org-chart li:only-child::before, .org-chart li:only-child::after { display: none; }
+/* 行首行尾只保留朝向内侧的横线和落到本节点的竖线 */
+.org-chart li:first-child::before, .org-chart li:last-child::after { border: 0 none; }
+.org-chart li:last-child::before { border-right: 1px dashed #c8bca8; }
+.org-chart li:first-child::after, .org-chart li:last-child::before { border-radius: 4px 0 0 0; }
+/* 父卡片底部到横挂线之间的竖线 */
+.org-chart ul ul::before {
+  content: "";
+  position: absolute;
+  top: 0;
+  left: 50%;
+  width: 0;
+  height: 22px;
+  border-left: 1px dashed #c8bca8;
+}
+/* 顶层(总运营)不挂线 */
+.org-chart > ul > li { padding-top: 0; }
+.org-chart > ul > li::before, .org-chart > ul > li::after { display: none; }
+.persona {
+  text-align: left;
+  background: var(--card);
+  border: 1px solid var(--line);
+  border-radius: 12px;
+  padding: 14px 16px;
+  box-shadow: var(--shadow);
+}
+/* 横向挂载组:团队子账号排在主账号右侧,短横虚线相连(宽度与 app.js 常量一致) */
+.org-side { display: flex; align-items: center; }
+.org-side-link { flex: none; width: 28px; border-top: 1px dashed #c8bca8; }
+/* 组织图内卡片紧凑档:收窄到 170px,配合整体缩放保证一屏看全 */
+.org-chart .persona { display: block; width: 170px; flex: none; padding: 10px 12px; }
+.org-chart .persona strong { font-size: 14px; }
+.org-chart .persona span { font-size: 12px; }
+.org-chart .persona .note, .org-chart .persona .brief { word-break: break-all; }
+.persona strong { display: block; font-size: 16px; }
+.persona span { display: block; margin-top: 6px; color: var(--muted); font-size: 13px; line-height: 1.5; }
+.persona .brief { margin-top: 8px; padding-top: 8px; border-top: 1px dashed var(--line); color: #46586a; }
+.persona:hover { border-color: var(--teal); }
+
+/* 左右两栏各自占满视口、各自滚动:侧栏自身不滚动,滚动只发生在菜单区,底部账号信息固定 */
+.shell { height: 100vh; display: grid; grid-template-columns: 220px 1fr; }
+.nav {
+  background: #172028;
+  color: #e7e1d6;
+  padding: 22px 14px;
+  display: flex;
+  flex-direction: column;
+  gap: 4px;
+  height: 100vh;
+  overflow: hidden;
+}
+/* 侧栏定高后直接子项一律不参与 flex 收缩:.nav-sub 为折叠动画带 overflow:hidden,
+   自动最小尺寸为 0,被压缩时会裁掉组内末尾的菜单项(如「全部订阅」) */
+.nav > * { flex: none; }
+/* 菜单区独占剩余高度并独立滚动;菜单高于视口时给出可发现的细滚动条,避免被当成菜单缺失 */
+.nav-menu {
+  flex: 1 1 auto;
+  min-height: 0;
+  overflow-y: auto;
+  overscroll-behavior: contain;
+  display: flex;
+  flex-direction: column;
+  gap: 4px;
+  scrollbar-width: thin;
+  scrollbar-color: rgba(255, 255, 255, 0.22) transparent;
+  /* 关掉滚动锚定:重绘后脚本还原的 scrollTop 才不会被浏览器再挪一次 */
+  overflow-anchor: none;
+}
+.nav-menu > * { flex: none; }
+.nav-menu::-webkit-scrollbar { width: 8px; }
+.nav-menu::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.18); border-radius: 4px; }
+.brand { padding: 0 8px 16px; font-weight: 650; letter-spacing: 0.06em; }
+.nav button {
+  background: transparent;
+  border: 0;
+  color: inherit;
+  text-align: left;
+  border-radius: 8px;
+  padding: 9px 10px;
+  width: 100%;
+  font-size: 14px;
+  cursor: pointer;
+}
+.nav button.active, .nav button:hover { background: rgba(255, 255, 255, 0.08); }
+.nav .nav-group {
+  font-size: 12px;
+  letter-spacing: 0.08em;
+  text-transform: uppercase;
+  color: #8ea0a0;
+  padding: 14px 10px 6px;
+  cursor: pointer;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  user-select: none;
+}
+.nav .nav-group:hover { background: transparent; color: #c2d3d1; }
+.nav .nav-group .caret { font-size: 11px; transition: transform 0.18s ease; }
+.nav .nav-group.open .caret { transform: rotate(0deg); }
+.nav .nav-sub { padding-left: 12px; display: flex; flex-direction: column; gap: 2px; }
+.nav .nav-sub.closed { display: none; }
+.nav .nav-sub .nav-leaf { font-size: 13.5px; color: #d1c8ba; padding: 7px 10px; }
+.nav .nav-sub .nav-leaf.active {
+  background: linear-gradient(90deg, rgba(255,255,255,0.14), rgba(255,255,255,0.04));
+  color: #fff;
+}
+/* 身份面板与菜单列底色区分:独立卡片底 + 描边,避免和菜单混成一块 */
+.nav .who {
+  margin-top: auto;
+  padding: 12px;
+  font-size: 13px;
+  color: #cdd9d7;
+  line-height: 1.5;
+  background: linear-gradient(180deg, rgba(255,255,255,0.09), rgba(255,255,255,0.04));
+  border: 1px solid rgba(255,255,255,0.12);
+  border-radius: 12px;
+}
+.nav .who button { margin-top: 8px; border: 1px solid rgba(255,255,255,0.22); background: rgba(23,32,40,0.55); width: 100%; }
+.nav .who button:hover { background: rgba(23,32,40,0.8); }
+
+.main { padding: 22px 28px 48px; min-width: 0; height: 100vh; overflow-y: auto; overscroll-behavior: contain; }
+.top { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; margin-bottom: 18px; }
+.top h1 { font-size: 22px; font-weight: 650; }
+.top p { color: var(--muted); margin-top: 4px; font-size: 13px; }
+.row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 16px; }
+/* 工单页顶部告警卡:同排最多两张,不拉伸整行;卡内第二行 span 是说明文案 */
+.cards.narrow { grid-template-columns: repeat(auto-fit, minmax(210px, 320px)); }
+.card .hint { display: block; margin-top: 6px; font-size: 12px; line-height: 1.5; opacity: .82; }
+/* 统计卡的口径副标题:必须**常驻印在卡上**,⛔ 不是「?」悬浮气泡(第 6 册 14:24/:30)。
+   它存在的理由就是「卡片 12 万、列表加起来 15 万」不需要人解释 */
+.card .card-sub { display: block; margin-top: 6px; font-size: 12px; line-height: 1.5; color: var(--muted); opacity: .95; }
+/* 账单明细客户列的「归属已变更」标记:客户已改挂到别的分成方,历史明细照常显示但要标出来 */
+.tag-changed { display: inline-block; margin-left: 4px; padding: 1px 6px; border-radius: 999px; font-size: 12px; line-height: 1.5; color: var(--amber); border: 1px solid currentColor; vertical-align: 1px; }
+/* 回填弹窗「执行结论」联动提示:失败红字、部分成功黄字 */
+.bf-hint { grid-column: 1 / -1; font-size: 13px; line-height: 1.6; margin: 2px 0 4px; }
+.bf-hint.bad { color: var(--red); }
+.bf-hint.warn { color: var(--amber); }
+/* 报文摘要与脱敏原文展开(明文出口=零) */
+.fb-brief b { font-weight: 600; }
+.fb-brief .note { margin-top: 2px; }
+.fb-raw { margin-top: 4px; }
+.fb-raw summary { cursor: pointer; font-size: 12px; color: var(--muted); }
+.fb-raw summary:hover { color: var(--teal); }
+.card, .panel {
+  background: var(--card);
+  border: 1px solid var(--line);
+  border-radius: 14px;
+  box-shadow: var(--shadow);
+}
+.card { padding: 14px 16px; }
+.card b { display: block; font-size: 22px; margin-top: 4px; word-break: break-word; }
+.card span { color: var(--muted); font-size: 13px; }
+/* 未完成工单卡:数字用告警红,整卡可点开明细列表 */
+.card.alarm { cursor: pointer; }
+.card.alarm b { color: var(--red); }
+.card.alarm:hover { border-color: var(--red); box-shadow: 0 2px 10px rgba(143, 45, 45, 0.14); }
+/* 概览 KPI 卡:数值下方放历史曲线,曲线一律贴卡片底边对齐 */
+.cards.kpi { grid-auto-rows: 1fr; }
+.cards.kpi .card { display: flex; flex-direction: column; }
+.cards.kpi .num-row { margin-bottom: 10px; }
+.cards.kpi .num-row b { flex: none; font-size: 27px; }
+.cards.kpi .spark { display: block; flex: none; width: 100%; height: 34px; margin: auto 0 0; overflow: visible; }
+.spark-line { fill: none; stroke: var(--teal); stroke-width: 1.8; stroke-linecap: round; vector-effect: non-scaling-stroke; }
+.spark-area { fill: var(--teal); opacity: 0.09; stroke: none; }
+.card.alarm .spark-line { stroke: var(--red); }
+.card.alarm .spark-area { fill: var(--red); }
+/* 数值行:未完成工单卡在总数右侧显示待处理 / 处理中拆分数 */
+.num-row { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
+/* 选择器带上 .cards.kpi 前缀,避免被上面的 .card span 规则把字号改回 13px */
+.cards.kpi .num-split { font-size: 12px; line-height: 1.15; text-align: right; }
+.cards.kpi .num-split i { font-style: normal; opacity: 0.72; margin-right: 4px; }
+.panel { padding: 16px 18px; margin-bottom: 14px; overflow-x: auto; min-width: 0; }
+.panel h2 { font-size: 16px; margin-bottom: 10px; }
+.panel > .note { margin-top: 8px; }
+
+table { width: 100%; border-collapse: collapse; font-size: 14px; }
+th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--line); vertical-align: middle; white-space: nowrap; }
+td.wrap { white-space: normal; min-width: 240px; }
+/* 定时任务页:任务编码与执行编号是系统标识符,等宽显示便于逐位比对与检索 */
+code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 13px; }
+/* 分成管理列表:分成方列放宽,分成方式与分成比例/金额列收紧(多个取值逐行列出),避免表格横向溢出后点不到操作列 */
+td .party-name { max-width: 200px; white-space: normal; line-height: 1.4; }
+td .tight { max-width: 104px; white-space: normal; line-height: 1.4; }
+/* 合同管理列表:列多且值长(编号、外部单号、期间、出口),字号与行内边距收紧 + 长文本列换行,避免面板出现横向滚动 */
+table.dense { font-size: 13px; }
+table.dense th, table.dense td { padding: 7px 7px; }
+/* 表头允许换行:窗口变窄时表头折行,整表最小宽度随之下降,不致于撑出横向滚动 */
+table.dense th { white-space: normal; }
+table.dense .note { font-size: 12px; line-height: 1.5; }
+/* 行内操作按钮收紧且不换行,否则两个按钮竖排会把整行撑到三层高 */
+table.dense .row { flex-wrap: nowrap; gap: 6px; }
+table.dense .btn { padding: 4px 8px; font-size: 12px; }
+/* 定时任务清单:10 列监控指标(编码、名称、调度、上次执行、耗时、结果、计数、下轮、状态、操作)。
+   任务名称与调度说明折行、时间戳拆两行,把横向空间让给计数列与操作列,避免面板出现横向滚动。
+   min-width 不能省:只有 max-width 时自动布局会把折行列压到单字宽(任务名称曾塌成 27px)。 */
+table.job-list td.c-name { min-width: 92px; max-width: 126px; white-space: normal; line-height: 1.4; }
+table.job-list td.c-sched { min-width: 100px; max-width: 132px; white-space: normal; line-height: 1.4; }
+/* 客户管理列表:列多且值长(编号、掩码识别号、区域全路径、团队名),
+   长文本列折行、行尾操作列不折行——按钮一旦竖排会把整行撑到三层高。 */
+table.ent-list { font-size: 13px; }
+table.ent-list th, table.ent-list td { padding: 7px 8px; }
+table.ent-list th { white-space: normal; }
+table.ent-list .note { font-size: 12px; line-height: 1.45; }
+/* 折行列限定宽度,把横向空间让给操作列;折行只发生在编号下方、区域路径与团队清单上 */
+table.ent-list td.c-ent, table.ent-list td.c-subject,
+table.ent-list td.c-region, table.ent-list td.c-teams { white-space: normal; }
+table.ent-list td.c-ent { width: 108px; }
+/* 掩码识别号是一个不断行的整串(18 位),这列的最小宽就是它撑出来的宽度 */
+table.ent-list td.c-subject { width: 122px; }
+table.ent-list td.c-region { width: 128px; }
+table.ent-list td.c-teams { width: 110px; }
+/* 短列显式收窄,避免自动布局把剩余宽度按比例摊到它们身上、反过来挤压长文本列 */
+table.ent-list th:first-child, table.ent-list td:first-child { width: 36px; }
+table.ent-list td.c-op, table.ent-list td.c-partner { width: 62px; }
+table.ent-list td.c-status { width: 66px; }
+/* 操作列按三枚按钮的最小宽度取宽,不参与压缩;按钮字号与内边距同步收紧 */
+table.ent-list th.c-ops, table.ent-list td.c-ops { width: 1%; }
+table.ent-list td.c-ops .row { flex-wrap: nowrap; gap: 6px; }
+table.ent-list td.c-ops .btn { padding: 4px 8px; font-size: 12px; }
+th { color: var(--muted); font-weight: 550; font-size: 12px; }
+tr.clickable { cursor: pointer; }
+tr.clickable:hover { background: #f3efe6; }
+
+.pill {
+  display: inline-block;
+  border-radius: 999px;
+  padding: 2px 8px;
+  font-size: 12px;
+  background: #efe7da;
+  white-space: nowrap;
+}
+.pill.ok { background: #e5f4ea; color: var(--green); }
+.pill.wait { background: #fff1d6; color: var(--amber); }
+.pill.bad { background: #fde8e4; color: var(--red); }
+.pill.run { background: #e5f3f2; color: var(--teal-ink); }
+/* 表内的对账单号:行整体可点(进明细),单号本身再点一下进批次详情。
+   视觉上只做下划线提示,不做成按钮,避免每行塞一颗按钮 */
+.bno {
+  color: var(--teal-ink);
+  font-variant-numeric: tabular-nums;
+  text-decoration: underline;
+  text-underline-offset: 2px;
+  cursor: pointer;
+  white-space: nowrap;
+}
+.bno:hover { color: var(--teal); }
+
+/* 线路出口已选标签:下拉选一个即落一枚,可逐枚移除;与配置面板的可选项清单共用 */
+.exit-chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 6px; min-height: 26px; }
+.exit-chips:empty::after { content: "尚未选择线路出口"; color: var(--muted); font-size: 12px; }
+.exit-chip {
+  display: inline-flex; align-items: center; gap: 6px;
+  border-radius: 999px; padding: 3px 6px 3px 11px; font-size: 12px;
+  background: #e5f3f2; color: var(--teal-ink); border: 1px solid #bfe0dd;
+}
+.exit-chip button {
+  border: 0; background: transparent; color: var(--teal-ink);
+  font-size: 13px; line-height: 1; padding: 0 2px; cursor: pointer;
+}
+.exit-chip button:hover { color: var(--red); }
+.exit-opts { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 8px; }
+.exit-opts .exit-chip { background: #efe7da; color: var(--ink); border-color: var(--line); }
+
+.btn, .btn.ghost {
+  border-radius: 8px;
+  padding: 7px 12px;
+  border: 1px solid var(--teal);
+  background: var(--teal);
+  color: white;
+  white-space: nowrap;
+}
+.btn.ghost { background: transparent; color: var(--teal-ink); }
+.btn.warn { background: var(--red); border-color: var(--red); }
+.btn:disabled { opacity: 0.45; cursor: not-allowed; }
+
+label { display: block; font-size: 13px; color: var(--muted); margin: 10px 0 4px; }
+input, select, textarea {
+  width: 100%;
+  max-width: 420px;
+  border: 1px solid var(--line);
+  background: white;
+  border-radius: 8px;
+  padding: 8px 10px;
+}
+input[type="checkbox"], input[type="radio"] { width: auto; max-width: none; margin: 0; }
+td select, .row select { width: auto; min-width: 96px; max-width: 200px; }
+.row input { width: auto; }
+textarea { min-height: 88px; max-width: 560px; }
+.form-actions { margin-top: 14px; display: flex; gap: 8px; flex-wrap: wrap; }
+
+/* 多列表单 */
+.form-grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+  gap: 0 18px;
+}
+.form-grid label { margin-top: 8px; }
+/* 必填项标记:字段名后的红色星号 */
+.req { color: #c0392b; margin-left: 2px; font-weight: 700; }
+/* 校验未通过:已填内容整体保留、弹窗不重置,只红显有问题的编辑项并在字段下写原因 */
+.f-bad > label { color: var(--red); }
+.f-bad input, .f-bad select { border-color: var(--red); box-shadow: 0 0 0 2px rgba(143, 45, 45, 0.12); }
+.f-err { display: block; margin-top: 3px; font-size: 12px; color: var(--red); }
+.form-grid .form-actions { grid-column: 1 / -1; }
+
+/* 套餐档弹窗的成本项:名称下拉取自「成本管理」的全局成本项定义,档位上不录金额,可加多条、逐条删除 */
+.form-grid .pkg-costs { grid-column: 1 / -1; margin-top: 10px; }
+.pkg-costs-head {
+  display: flex; align-items: center; justify-content: space-between;
+  gap: 10px; flex-wrap: wrap;
+}
+.pkg-costs-head .btn { padding: 5px 12px; font-size: 13px; }
+.pkg-cost-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 6px; }
+.pkg-cost-row select { flex: 1 1 auto; min-width: 0; }
+.pkg-cost-row input { flex: 0 0 auto; width: 120px; max-width: 120px; }
+.pkg-cost-row .pkg-cost-qty { width: 62px; max-width: 62px; }
+.pkg-cost-row .pkg-cost-times { flex: 0 0 auto; }
+.pkg-cost-row .pkg-cost-qty-unit, .pkg-cost-row .pkg-cost-money-unit { flex: 0 0 auto; white-space: nowrap; }
+.pkg-cost-row .pkg-cost-amt-note { flex: 0 1 auto; white-space: nowrap; }
+
+/* 成本管理 ② 成本金额定义录入:一个「省份 × 运营商」组合下逐条成本项填具体金额 */
+td input.cost-amt { width: 130px; max-width: 130px; }
+
+/* 开关(二态表单):checkbox 隐藏,用 .track 画滑块 */
+label.switch {
+  display: inline-flex;
+  align-items: center;
+  gap: 8px;
+  cursor: pointer;
+  margin: 8px 0 4px;
+  min-height: 38px;
+  font-size: 13px;
+  color: var(--muted);
+}
+label.switch input { position: absolute; opacity: 0; width: 0; height: 0; }
+label.switch .track {
+  flex: none;
+  width: 40px;
+  height: 22px;
+  border-radius: 999px;
+  background: #cfc8ba;
+  position: relative;
+  transition: background 180ms ease;
+}
+label.switch .track::after {
+  content: "";
+  position: absolute;
+  top: 3px;
+  left: 3px;
+  width: 16px;
+  height: 16px;
+  border-radius: 50%;
+  background: #fff;
+  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
+  transition: transform 180ms ease;
+}
+label.switch input:checked + .track { background: var(--teal-ink); }
+label.switch input:checked + .track::after { transform: translateX(18px); }
+label.switch input:disabled + .track { opacity: 0.45; cursor: not-allowed; }
+
+/* 对象存储键列表 / 材料列表 */
+ul.files {
+  margin: 8px 0 0;
+  padding: 0;
+  list-style: none;
+}
+ul.files li {
+  padding: 6px 10px;
+  background: #f7f2e8;
+  border: 1px solid var(--line);
+  border-radius: 8px;
+  margin-bottom: 6px;
+  font-size: 13px;
+  word-break: break-all;
+}
+
+/* 建档弹窗的材料上传:左侧「登记材料」与右侧「合同文档」并排,两类都可选上传 */
+.doc-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
+@media (max-width: 760px) { .doc-row { grid-template-columns: 1fr; } }
+/* 文件控件 + 已选清单(文档名在左,移除在右) */
+.doc-pick { margin-top: 8px; min-width: 0; }
+.doc-pick input[type="file"] { width: 100%; margin-top: 4px; }
+.doc-pick .files { margin-top: 6px; }
+ul.files.doc-list li {
+  padding: 4px 9px;
+  margin-bottom: 4px;
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 8px;
+}
+ul.files.doc-list .doc-name { min-width: 0; overflow-wrap: anywhere; }
+ul.files.doc-list .btn { padding: 2px 8px; font-size: 11px; }
+
+/* 复选列表(成员范围、客户直选) */
+.checklist {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
+  gap: 2px 18px;
+  margin-top: 6px;
+}
+label.ck {
+  display: flex;
+  align-items: center;
+  gap: 7px;
+  font-size: 14px;
+  font-weight: normal;
+  color: var(--ink);
+  margin: 4px 0;
+  line-height: 1.5;
+}
+label.ck .note { font-weight: normal; }
+
+/* 区域树 */
+ul.tree {
+  list-style: none;
+  margin: 0;
+  padding: 0;
+}
+ul.tree ul.tree { padding-left: 24px; }
+.tree-node {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  padding: 2px 0;
+}
+.tree-select {
+  background: transparent;
+  border: 1px solid transparent;
+  border-radius: 8px;
+  padding: 5px 10px;
+  color: var(--ink);
+}
+.tree-select:hover { background: #f3efe6; }
+.tree-node.on .tree-select {
+  background: var(--teal);
+  border-color: var(--teal);
+  color: #fff;
+}
+.lv {
+  font-size: 12px;
+  color: var(--teal-ink);
+  background: #e5f3f2;
+  border-radius: 6px;
+  padding: 1px 7px;
+  white-space: nowrap;
+}
+.cnt { font-size: 12px; color: var(--muted); white-space: nowrap; }
+
+/* 范围配置里的勾选树 */
+ul.tree.check label.ck { margin: 5px 0; }
+ul.tree.check ul.tree { margin: 2px 0; }
+
+.note { color: var(--muted); font-size: 13px; line-height: 1.6; }
+.alert {
+  background: #fff4ec;
+  border: 1px solid #f0d2bc;
+  color: #7a3e12;
+  border-radius: 12px;
+  padding: 10px 12px;
+  margin-bottom: 12px;
+  font-size: 14px;
+  line-height: 1.6;
+}
+/* 期次标注横幅:原型把「第 3 期接线后的形态」与第 1/2 期的接线现状同页展示(对账演示数据留着,
+   RECON 注册位仍是未接线),这类说明是口径消歧、不是待办,故用中性青色与 .alert 区分,
+   避免演示口径与真实待办混成同一级视觉提示 */
+.phase-note {
+  background: #eef4f3;
+  border: 1px solid #cfe0dd;
+  color: var(--teal-ink);
+  border-radius: 12px;
+  padding: 9px 12px;
+  margin-bottom: 12px;
+  font-size: 13px;
+  line-height: 1.6;
+}
+.toast {
+  position: fixed;
+  /* 提示浮在抽屉(45)与弹窗(50)之上,否则「已按某任务过滤」这类提示会被遮在浮层底下 */
+  z-index: 60;
+  right: 20px;
+  bottom: 20px;
+  background: var(--ink);
+  color: white;
+  padding: 12px 14px;
+  border-radius: 10px;
+  max-width: 320px;
+  box-shadow: var(--shadow);
+  font-size: 14px;
+  line-height: 1.5;
+}
+.split { display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 14px; align-items: start; }
+.log { margin: 0; padding-left: 18px; color: var(--muted); }
+.log li { margin: 4px 0; line-height: 1.6; }
+@media (max-width: 900px) {
+  .login, .shell, .split { grid-template-columns: 1fr; }
+  .login-side { padding: 28px 22px; }
+  /* 窄屏单列:回到整页滚动,不锁两栏各自的高度与滚动条 */
+  .shell { height: auto; }
+  .nav, .nav-menu, .main { height: auto; overflow: visible; overscroll-behavior: auto; }
+}
+
+/* ================= 交互与视觉增强 ================= */
+
+/* 全局过渡基类,给常见可交互元素 */
+button, .card, .panel, tr.clickable, .tree-select, label.ck {
+  transition: background 180ms ease, border-color 180ms ease, color 180ms ease, transform 120ms ease, box-shadow 180ms ease;
+}
+input, select, textarea { transition: border-color 180ms ease, box-shadow 180ms ease; }
+
+/* 侧栏:折叠子菜单过渡(用 max-height 替代 display:none) */
+.nav .nav-sub { overflow: hidden; transition: max-height 220ms ease, opacity 220ms ease; max-height: 600px; opacity: 1; }
+.nav .nav-sub.closed { max-height: 0; opacity: 0; }
+
+/* 侧栏叶子按钮活跃态:左侧竖条 + 更强对比 */
+.nav .nav-sub .nav-leaf.active {
+  position: relative;
+  background: rgba(14, 110, 104, 0.22);
+  color: #fff;
+  padding-left: 14px;
+}
+.nav .nav-sub .nav-leaf.active::before {
+  content: "";
+  position: absolute; left: -12px; top: 4px; bottom: 4px; width: 3px;
+  background: #19d0c0; border-radius: 2px;
+}
+.nav .nav-sub .nav-leaf:hover { color: #fff; background: rgba(255,255,255,0.06); }
+
+/* 顶层叶子按钮(如"概览""审计日志")活跃态 */
+.nav > button.nav-leaf.active {
+  background: rgba(14, 110, 104, 0.22);
+  color: #fff;
+}
+
+/* 折叠 caret 旋转 */
+.nav .nav-group .caret { transform: rotate(-90deg); }
+.nav .nav-group.open .caret { transform: rotate(0deg); }
+
+/* 按钮:focus-visible + 按下态 */
+.btn:focus-visible, button:focus-visible,
+.persona:focus-visible, .tree-select:focus-visible {
+  outline: 2px solid var(--teal);
+  outline-offset: 2px;
+}
+.btn:active { transform: translateY(1px); }
+
+/* 表格:thead 底线 + hover 高亮 + 斑马纹 */
+table { border-radius: 10px; overflow: hidden; }
+thead th {
+  background: #faf4e8;
+  border-bottom: 2px solid var(--line);
+  padding: 10px 10px;
+  position: sticky; top: 0; z-index: 1;
+}
+tbody tr:nth-child(even) td { background: #fbf7ee; }
+tbody tr.clickable:hover td, tbody tr:hover td {
+  background: #f0e8d6 !important;
+}
+
+/* 套餐目录:用途分类分组小标题行 */
+tbody tr.grp td {
+  background: #f2ece0 !important;
+  border-bottom: 1px solid var(--line);
+  padding: 7px 10px;
+  font-weight: 640;
+  color: var(--teal-ink);
+  white-space: nowrap;
+}
+tbody tr.grp td span {
+  margin-left: 10px;
+  font-weight: 400;
+  font-size: 12px;
+  color: var(--muted);
+}
+
+/* 表单 focus glow */
+input:focus, select:focus, textarea:focus {
+  border-color: var(--teal);
+  box-shadow: 0 0 0 3px rgba(14, 110, 104, 0.14);
+  outline: none;
+}
+
+/* panel / card 入场动画 */
+@keyframes fadeInUp {
+  from { opacity: 0; transform: translateY(6px); }
+  to   { opacity: 1; transform: none; }
+}
+.panel, .card, .alert, .persona { animation: fadeInUp 300ms ease both; }
+.panel:nth-child(2)  { animation-delay: 40ms; }
+.panel:nth-child(3)  { animation-delay: 80ms; }
+.panel:nth-child(4)  { animation-delay: 120ms; }
+
+/* toast 滑入 */
+.toast {
+  animation: slideInRight 280ms ease both;
+}
+@keyframes slideInRight {
+  from { opacity: 0; transform: translateX(24px); }
+  to   { opacity: 1; transform: none; }
+}
+
+/* 登录 persona 悬停抬升 */
+.persona { transition: transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease; }
+.persona:hover {
+  transform: translateY(-2px);
+  box-shadow: 0 14px 32px rgba(40, 32, 20, 0.12);
+  border-color: var(--teal);
+}
+
+/* webkit 滚动条 */
+::-webkit-scrollbar { width: 10px; height: 10px; }
+::-webkit-scrollbar-track { background: transparent; }
+::-webkit-scrollbar-thumb { background: #d7ccba; border-radius: 5px; }
+::-webkit-scrollbar-thumb:hover { background: #b9ac95; }
+.panel::-webkit-scrollbar-thumb { background: #d7ccba; }
+
+/* pill hover 微动(可交互的情况下) */
+.pill { cursor: default; }
+
+/* 区域树选中节点加 glow */
+.tree-node.on .tree-select {
+  box-shadow: 0 0 0 2px rgba(14,110,104,0.2);
+}
+
+/* 区域树操作菜单 */
+.tree-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; position: relative; }
+.tree-head h2 { margin: 0; }
+.tree-node { position: relative; }
+.node-menu-btn {
+  background: transparent; border: 1px solid transparent; border-radius: 6px;
+  color: var(--muted); font-weight: 700; font-size: 15px; line-height: 1;
+  padding: 3px 7px; margin-left: 2px;
+}
+.node-menu-btn:hover { background: #efe7da; color: var(--ink); }
+.tree-node.on .node-menu-btn { color: #fff; }
+.tree-node.on .node-menu-btn:hover { background: rgba(255, 255, 255, 0.18); color: #fff; }
+.node-menu {
+  position: absolute; top: 100%; left: 0; z-index: 30;
+  background: var(--card); border: 1px solid var(--line); border-radius: 10px;
+  box-shadow: 0 12px 32px rgba(40, 32, 20, 0.16);
+  padding: 4px; min-width: 176px;
+  display: flex; flex-direction: column; gap: 2px;
+}
+.node-menu button {
+  text-align: left; background: transparent; border: 0; border-radius: 7px;
+  padding: 7px 10px; font-size: 13.5px;
+}
+.node-menu button:hover { background: #f3efe6; }
+.node-menu button.danger { color: var(--red); }
+.node-menu button.danger:hover { background: #fde8e4; }
+/* 区域树面板:不裁剪溢出内容,保证节点下拉菜单完整显示 */
+.panel.uncut { overflow: visible; }
+/* 区域管理页:主区纵向铺满视口,左右两栏拉伸到底,区域树底部与窗口底部对齐 */
+.main.stretch { display: flex; flex-direction: column; padding-bottom: 22px; }
+.main.stretch .top { flex: none; }
+.main.stretch .region-split { flex: 1 1 auto; align-items: stretch; }
+.main.stretch .region-split > .panel.uncut { display: flex; flex-direction: column; }
+.main.stretch .region-split > .panel.uncut > ul.tree { flex: 1 1 auto; }
+.icon-btn {
+  background: transparent; border: 1px solid var(--line); border-radius: 7px;
+  color: var(--muted); font-size: 14px; line-height: 1;
+  padding: 5px 8px; margin-left: 6px;
+}
+.icon-btn:hover { background: #efe7da; color: var(--ink); }
+.icon-btn.danger:hover { background: #fde8e4; color: var(--red); }
+/* 套餐目录操作列:编辑与删除用图标按钮,同一行水平排列不折行;引用提示另起一行 */
+.pkg-ops { display: flex; flex-wrap: nowrap; gap: 6px; align-items: center; }
+.pkg-ops .icon-btn { margin-left: 0; }
+/* 区域详情卡片标题旁的"被引用"小标签:随标题行内显示,不占独立高度 */
+.ref-tag {
+  display: inline-block; vertical-align: 2px; margin-left: 8px;
+  font-size: 12px; font-weight: 500; color: var(--red);
+  background: #fde8e4; border-radius: 6px; padding: 2px 7px; cursor: help;
+}
+
+/* 弹窗 */
+.modal-overlay {
+  position: fixed; inset: 0; z-index: 50;
+  background: rgba(23, 32, 40, 0.45);
+  display: flex; align-items: center; justify-content: center;
+  padding: 20px;
+  animation: fadeIn 160ms ease both;
+}
+@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
+/* 弹窗已开着时的重绘(如切换套餐档位、条目增删、校验反馈):不再重播入场动画,消除闪动 */
+.modal-overlay.no-anim { animation: none; }
+.modal-overlay.no-anim .panel, .modal-overlay.no-anim .card, .modal-overlay.no-anim .alert { animation: none; }
+/* 同一次重绘里底层整页也会重建,隔着半透明遮罩可见其卡片上浮动画重播——一并禁用 */
+#app.no-page-anim .panel, #app.no-page-anim .card, #app.no-page-anim .alert,
+#app.no-page-anim .persona, #app.no-page-anim .ov-card { animation: none; }
+.modal {
+  background: var(--card); border: 1px solid var(--line); border-radius: 14px;
+  padding: 20px 22px; width: 100%; max-width: 480px;
+  max-height: calc(100vh - 40px); overflow-y: auto;
+  box-shadow: 0 20px 60px rgba(20, 16, 10, 0.28);
+}
+.modal h3 { font-size: 17px; margin-bottom: 10px; }
+.modal label { margin-top: 2px; }
+/* 弹窗内的编辑项跟随弹窗宽度,不再受全局 420/560 上限约束(多行文本框同样撑满所在列) */
+.modal input, .modal select, .modal textarea { max-width: 100%; }
+/* 字段较多的新增/编辑表单(客户档案、订阅)用宽弹窗 */
+.modal.wide { max-width: 760px; }
+/* 新增客户字段最多(含客户主账号),再加宽一档 */
+.modal.wider { max-width: 980px; }
+/* 加宽后表单最小列宽同步提高,保证每行最多三列(窄屏仍自动降为两列/单列) */
+.modal.wider .form-grid { grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); }
+/* 报文兜底与超期工单明细:列数多,用最宽一档,让整表在常见宽屏上不必横向滚动 */
+.modal.widest { max-width: min(1320px, 100%); }
+/* 兜底表的处理列改上下排布,下拉显式限宽(否则固有宽度随最长选项,整表被撑到 1300+) */
+.fb-act { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; }
+.fb-act select { width: 230px; max-width: 100%; }
+/* 该档弹窗内的说明列允许压得更窄,把宽度让给处理列 */
+.modal.widest td.wrap { min-width: 180px; }
+.modal .form-grid { gap: 0 16px; }
+
+/* 右侧抽屉:定时任务页的「执行记录」。整高贴右滑入,遮罩比弹窗低一层——
+   抽屉里再点「详情」开的弹窗浮在抽屉之上,关弹窗后抽屉还在原位 */
+.drawer-overlay {
+  position: fixed; inset: 0; z-index: 45;
+  background: rgba(23, 32, 40, 0.35);
+  display: flex; justify-content: flex-end;
+  animation: fadeIn 160ms ease both;
+}
+@keyframes drawerIn { from { transform: translateX(28px); opacity: 0.3; } to { transform: none; opacity: 1; } }
+.drawer {
+  width: min(1180px, 100%); height: 100%;
+  background: var(--card); border-left: 1px solid var(--line);
+  box-shadow: -18px 0 54px rgba(20, 16, 10, 0.22);
+  padding: 20px 24px 34px; overflow-y: auto; overscroll-behavior: contain;
+  animation: drawerIn 200ms ease both;
+}
+/* 抽屉开着时的重绘(改筛选、启停任务):不再重播入场动画,消除闪动 */
+.drawer-overlay.no-anim { animation: none; }
+.drawer-overlay.no-anim .drawer { animation: none; }
+.drawer-head {
+  display: flex; align-items: flex-start; justify-content: space-between; gap: 16px;
+  margin-bottom: 12px;
+}
+.drawer-head h2 { font-size: 17px; }
+/* 列数多的流水表在抽屉里横向滚动,不把整只抽屉撑宽 */
+.drawer-scroll-x { overflow-x: auto; }
+/* 窄抽屉:成员负责范围只装一棵区域树,不必像执行记录那样占满整屏 */
+.drawer.narrow { width: min(620px, 100%); }
+/* 客户名称联想下拉:输入部分关键字后在输入框下方弹出已有客户列表 */
+.ac-box { position: relative; }
+.ac-list {
+  position: absolute; z-index: 30; top: calc(100% + 2px); left: 0; right: 0;
+  max-height: 220px; overflow-y: auto;
+  background: var(--card); border: 1px solid var(--line); border-radius: 10px;
+  box-shadow: 0 12px 28px rgba(20, 16, 10, 0.18);
+}
+.ac-item {
+  display: block; width: 100%; text-align: left; padding: 7px 12px;
+  background: none; border: 0; border-bottom: 1px solid rgba(226, 217, 204, 0.5);
+  font: inherit; color: var(--ink); cursor: pointer;
+}
+.ac-item:last-child { border-bottom: 0; }
+.ac-item:hover { background: #f3eee4; }
+.ac-item small { display: block; opacity: 0.65; font-size: 12px; }
+
+/* 标题右侧问号提示:悬停或聚焦时弹出说明文字 */
+.q-tip {
+  position: relative;
+  display: inline-flex;
+  align-items: center;
+  justify-content: center;
+  width: 18px;
+  height: 18px;
+  margin-left: 8px;
+  border-radius: 50%;
+  border: 1px solid var(--line);
+  background: #f3eee4;
+  color: var(--muted);
+  font-size: 12px;
+  font-weight: 600;
+  cursor: help;
+  vertical-align: 2px;
+}
+.q-tip .q-tip-pop {
+  display: none;
+  position: absolute;
+  top: 24px;
+  left: -10px;
+  width: 320px;
+  padding: 10px 12px;
+  background: #2f2a22;
+  color: #fff;
+  font-size: 12px;
+  font-weight: 400;
+  line-height: 1.6;
+  text-align: left;
+  border-radius: 8px;
+  z-index: 30;
+  box-shadow: 0 8px 24px rgba(20, 16, 10, 0.25);
+}
+.q-tip:hover .q-tip-pop, .q-tip:focus .q-tip-pop, .q-tip.open .q-tip-pop { display: block; }
+/* 表头里的问号:单元格是 nowrap,弹层要单独允许换行;靠右的列让弹层向左展开,
+   否则会被 .panel 的横向滚动裁掉(overflow-x:auto 同时会裁掉纵向溢出) */
+th .q-tip-pop { white-space: normal; }
+.q-tip.pop-right .q-tip-pop { left: auto; right: -6px; }
+
+/* 初始密码:输入框与「自动生成」按钮同行,等宽字体便于分辨易混字符 */
+.pwd-row { display: flex; align-items: center; gap: 8px; }
+.pwd-row input {
+  flex: 1; min-width: 0; max-width: none;
+  font-family: ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .5px;
+}
+.pwd-row input.flash { animation: pwdFlash 520ms ease both; }
+@keyframes pwdFlash { from { background: #dff3ef; border-color: var(--teal); } to { background: white; border-color: var(--line); } }
+
+/* 新增档案时一并开通登录账号:可选区块,左侧色条把「登录名—初始密码—手机号」归为一组,
+   浅底与卡片底色区分,表明这几项不是档案必填内容(都留空即只建档案) */
+.acct-new {
+  margin-top: 8px;
+  padding: 8px 12px 6px;
+  border: 1px solid var(--line);
+  border-left: 3px solid var(--teal);
+  border-radius: 10px;
+  background: #fbf7ef;
+}
+.acct-new .note { margin-top: 4px; }
+/* 登录名与手机号并排显示 */
+.acct-grid {
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  gap: 0 12px;
+}
+@media (max-width: 580px) { .acct-grid { grid-template-columns: 1fr; } }
+/* 弹窗内可折叠说明,默认收起 */
+details.note-details { margin-top: 4px; }
+details.note-details summary {
+  cursor: pointer; font-size: 12px; color: var(--muted);
+  list-style: none; display: inline-flex; align-items: center; gap: 4px;
+}
+details.note-details summary::before { content: '?'; display: inline-flex; align-items: center; justify-content: center; width: 14px; height: 14px; border-radius: 50%; border: 1px solid var(--line); background: #f3eee4; font-size: 10px; font-weight: 600; flex: none; }
+details.note-details[open] summary::before { content: '\2212'; }
+details.note-details .note { margin-top: 4px; }
+
+/* 成员负责范围:下拉多选树。收起时是一行选择框,展开后浮层内是区域—客户勾选树,区域可整块勾选 */
+.scope-pick { position: relative; margin-top: 6px; }
+.scope-pick-btn {
+  width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 10px;
+  padding: 8px 11px; border: 1px solid var(--line); border-radius: 10px;
+  background: var(--card); font-size: 14px; text-align: left;
+  transition: border-color 160ms ease;
+}
+.scope-pick-btn:hover, .scope-pick.open .scope-pick-btn { border-color: var(--teal); }
+.scope-pick-text {
+  flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+  color: var(--muted);
+}
+.scope-pick-caret { color: var(--muted); font-size: 12px; transition: transform 160ms ease; }
+.scope-pick.open .scope-pick-caret { transform: rotate(180deg); }
+.scope-pick-pop {
+  display: none; position: absolute; z-index: 6; left: 0; right: 0; margin-top: 6px;
+  padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--card);
+  box-shadow: 0 14px 34px rgba(40, 32, 20, 0.16);
+}
+.scope-pick.open .scope-pick-pop { display: block; animation: fadeIn 140ms ease both; }
+.scope-pick-bar { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
+.scope-pick-bar .note { margin-left: auto; }
+.scope-pick-scroll { max-height: 250px; overflow: auto; }
+ul.tree .sp-region { font-weight: 600; }
+ul.tree .sp-region, ul.tree .sp-ent { margin: 3px 0; }
+/* 负责范围抽屉里的区域树:直接摊开在抽屉里(不走下拉浮层),限高让底部保存按钮始终够得着 */
+.scope-tree {
+  max-height: 52vh; overflow: auto; margin-top: 4px;
+  padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: #fbf7ef;
+}
+
+/* 导出激活码弹窗:区域范围勾选树在弹窗内直接展开(勾选父节点即整块勾选其下级) */
+.ex-tree {
+  max-height: 262px; overflow: auto; margin: 0 0 12px;
+  padding: 8px 12px; border: 1px solid var(--line); border-radius: 12px; background: #fbf7ef;
+}
+.ex-tree ul.tree { margin: 2px 0; }
+.ex-tree label.ck { font-weight: normal; }
+
+/* 工单流程:状态筛选 tabs */
+.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
+.tab {
+  display: inline-flex; align-items: center; gap: 6px;
+  border: 1px solid var(--line); background: var(--card); border-radius: 999px;
+  padding: 6px 14px; font-size: 13px; color: var(--muted);
+  transition: border-color 160ms ease, background 160ms ease, color 160ms ease, transform 160ms ease;
+}
+.tab b { font-size: 12px; color: inherit; opacity: 0.75; }
+.tab:hover { border-color: var(--teal); color: var(--teal-ink); transform: translateY(-1px); }
+.tab.active { background: var(--teal-ink); border-color: var(--teal-ink); color: #f3efe6; }
+.tab.active b { opacity: 0.9; }
+
+/* 运维团队:tab 与「开通运维团队」按钮同行,tab 在左按钮在右 */
+.team-tabs { justify-content: space-between; margin-bottom: 14px; }
+.panel-sub { margin: 16px 0 0; font-size: 14px; font-weight: 600; color: var(--muted); }
+/* 某类型尚未开通团队时的空白 tab 页:虚线空态 + 居中开通入口 */
+.team-empty {
+  display: flex; flex-direction: column; align-items: center; gap: 4px;
+  padding: 46px 18px; border: 1px dashed #d3c6b3; background: transparent;
+}
+.team-empty-title { font-size: 15px; color: var(--ink); }
+.team-empty .note { max-width: 540px; margin-bottom: 10px; }
+
+/* 工单流程:状态流转指示 */
+.flow { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 12px; }
+.fstep {
+  display: inline-flex; align-items: center;
+  border: 1px solid var(--line); border-radius: 999px;
+  padding: 3px 12px; font-size: 12px; color: var(--muted); background: var(--card);
+}
+.fstep.done { border-color: #bcd9c8; color: var(--green); background: #e5f4ea; }
+.fstep.now { border-color: var(--teal); color: var(--teal-ink); background: #e5f3f2; font-weight: 600; }
+.fstep.bad { border-color: #eac4bc; color: var(--red); background: #fde8e4; }
+.farrow { color: var(--muted); font-size: 12px; }
+.fstep.clickable {
+  cursor: pointer; border-style: dashed; border-color: var(--teal); color: var(--teal-ink);
+  transition: transform 160ms ease, box-shadow 160ms ease, background 160ms ease;
+}
+.fstep.clickable:hover {
+  transform: translateY(-1px);
+  background: #eef7f5;
+  box-shadow: 0 0 0 2px rgba(14, 110, 104, 0.15);
+}
+
+/* ===== 区域管理:概况卡片 + 钻取列表 ===== */
+/* 右栏允许收缩到 fr 份额以内,宽表格在 panel 内部横向滚动,避免挤压左侧区域树 */
+.region-over { min-height: 0; min-width: 0; }
+.ov-grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(215px, 1fr));
+  gap: 14px;
+  align-content: start;
+}
+button.ov-card {
+  text-align: left;
+  width: 100%;
+  display: flex;
+  flex-direction: column;
+  gap: 6px;
+  cursor: pointer;
+  border: 1px solid var(--line);
+}
+button.ov-card:hover {
+  border-color: var(--teal);
+  transform: translateY(-2px);
+  box-shadow: 0 14px 32px rgba(40, 32, 20, 0.12);
+}
+.ov-card .ov-title { color: var(--muted); font-size: 13.5px; }
+.ov-card b { font-size: 30px; margin: 2px 0; line-height: 1.1; word-break: break-word; }
+.ov-card .ov-sub { color: var(--muted); font-size: 12.5px; line-height: 1.55; min-height: 36px; }
+.ov-card .ov-go { color: var(--teal-ink); font-size: 12.5px; margin-top: 2px; }
+.ov-head .row { margin-bottom: 2px; }
+
+/* 危险色 ghost 按钮 */
+.btn.danger { background: transparent; color: var(--red); border-color: var(--red); }
+.btn.danger:hover { background: #fde8e4; }
+
+/* 概况卡片与右侧钻取视图入场动画(保持既有动效) */
+.ov-card { animation: fadeInUp 300ms ease both; }
+
+/* 列表筛选条:区域/付款周期下拉框与名称文本框排在表头上方,底部对齐 */
+.filters {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 10px 16px;
+  align-items: flex-end;
+  margin: 6px 0 12px;
+}
+.filters .f-item label { margin: 0 0 4px; }
+.filters .f-item select,
+.filters .f-item input { width: auto; min-width: 200px; max-width: 320px; }
+/* 多选筛选下拉:工单类型 / 状态 / 回填来源三组各占一个控件的宽度,与其他下拉同行排布,
+   纵向省掉三整行标签。选项面板绝对定位浮在表格上方,展开态由 JS 状态维持,勾完一项仍保持展开 */
+.filters .f-item .msel { position: relative; }
+.filters .f-item .msel-btn {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  width: auto;
+  min-width: 200px;
+  max-width: 320px;
+  border: 1px solid var(--line);
+  background: white;
+  border-radius: 8px;
+  padding: 8px 10px;
+  text-align: left;
+  transition: border-color 180ms ease, box-shadow 180ms ease;
+}
+.filters .f-item .msel-btn:hover { border-color: var(--teal); }
+.filters .f-item .msel.open .msel-btn { border-color: var(--teal); box-shadow: 0 0 0 3px rgba(14, 110, 104, 0.12); }
+.filters .f-item .msel-text {
+  flex: 1 1 auto;
+  min-width: 0;
+  overflow: hidden;
+  white-space: nowrap;
+  text-overflow: ellipsis;
+  color: var(--muted);
+}
+.filters .f-item .msel-btn.has .msel-text { color: var(--ink); font-weight: 600; }
+.filters .f-item .msel-n {
+  flex: none;
+  min-width: 18px;
+  padding: 0 5px;
+  border-radius: 999px;
+  background: var(--teal);
+  color: #fff;
+  font-size: 11.5px;
+  line-height: 17px;
+  text-align: center;
+}
+.filters .f-item .msel-caret { flex: none; color: var(--muted); transition: transform 150ms ease; }
+.filters .f-item .msel.open .msel-caret { transform: rotate(180deg); }
+.filters .f-item .msel-panel {
+  position: absolute;
+  z-index: 30;
+  top: calc(100% + 4px);
+  left: 0;
+  min-width: 100%;
+  max-height: 264px;
+  overflow-y: auto;
+  display: flex;
+  flex-direction: column;
+  gap: 2px;
+  padding: 6px;
+  background: var(--card);
+  border: 1px solid var(--line);
+  border-radius: 10px;
+  box-shadow: var(--shadow);
+}
+.filters .f-item .msel-opt {
+  display: flex;
+  align-items: center;
+  gap: 7px;
+  white-space: nowrap;
+  border: 0;
+  background: transparent;
+  border-radius: 7px;
+  padding: 6px 9px;
+  font-size: 13.5px;
+  text-align: left;
+}
+.filters .f-item .msel-opt:hover { background: #f0e8d6; }
+.filters .f-item .msel-opt.on { color: var(--teal-ink); font-weight: 600; }
+
+/* ② 成本金额定义 · 一览表:未配置的格子按 0 计但置灰区分,当前录入中的组合整行高亮。
+   放在文件末尾以胜过上面 tbody tr:nth-child(even) td 的斑马纹背景 */
+td.amt-none { color: var(--muted); }
+tbody tr.combo-cur td { background: #f1e7d3; }
+tbody tr.combo-cur td:first-child { font-weight: 600; }
+.filters .f-item .msel-tick { flex: none; width: 12px; color: var(--teal); font-weight: 700; }
+
+/* 工单管理分页条:左边说明当前区间与总条数,右边页码;当前页实心,到头的一侧置灰不可点 */
+.pager { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 12px; }
+.pager .note { margin: 0 auto 0 0; }
+.pager .pgs { display: flex; align-items: center; gap: 6px; }
+.pager .pg {
+  min-width: 34px; padding: 5px 10px; border: 1px solid var(--line); border-radius: 8px;
+  background: var(--card); font-size: 13px; color: var(--ink);
+  transition: border-color 160ms ease, background 160ms ease, color 160ms ease;
+}
+.pager .pg:hover:not(:disabled) { border-color: var(--teal); }
+.pager .pg.cur { background: var(--teal); border-color: var(--teal); color: #fff; font-weight: 600; }
+.pager .pg:disabled { color: var(--muted); opacity: 0.5; cursor: not-allowed; }
+.pager .pg.gap { border: 0; background: transparent; color: var(--muted); }

+ 20 - 0
front-end/tsconfig.json

@@ -0,0 +1,20 @@
+{
+  "compilerOptions": {
+    "target": "ES2022",
+    "lib": ["ES2022", "DOM", "DOM.Iterable"],
+    "module": "ESNext",
+    "moduleResolution": "bundler",
+    "jsx": "react-jsx",
+    "strict": true,
+    "noUnusedLocals": true,
+    "noUnusedParameters": true,
+    "noFallthroughCasesInSwitch": true,
+    "skipLibCheck": true,
+    "isolatedModules": true,
+    "resolveJsonModule": true,
+    "allowImportingTsExtensions": true,
+    "noEmit": true,
+    "types": ["vite/client", "node"]
+  },
+  "include": ["src", "vite.config.ts"]
+}

+ 65 - 0
front-end/vite.config.ts

@@ -0,0 +1,65 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { defineConfig } from "vite";
+import react from "@vitejs/plugin-react";
+
+/**
+ * 联调代理(总则§16.1:接口一律经平台网关,前端不拼 IP:端口)
+ *
+ * /gateway → SEOH API 网关(本地 docker,自签证书 HTTPS,故 secure:false)
+ *            网关只声明了 GET/POST 且未放行 Authorization 头,浏览器直连必然预检失败,
+ *            所以必须走本代理。
+ * /bos     → klt-bos 本地进程直连(网关路由未注册时的降级通路,仅本地开发用;
+ *            ⚠️ 必须剥掉 `/bos` 前缀:服务按 OpenAPI 声明挂载**无服务名前缀**的路由,
+ *            带 `/api/klt-bos` 前缀会被判 11001「接口未在 OpenAPI 声明,拒绝访问」
+ *            ——该错误同样以 HTTP 200 返回,⛔ 用状态码判断路由是否命中)
+ *            VITE_BOS_VIA_GATEWAY=0 时启用。
+ */
+const GATEWAY = process.env.VITE_GATEWAY_BASE ?? "https://localhost:3000";
+const BOS_PORT = process.env.KLT_BOS_PORT ?? "8088";
+
+/**
+ * 项目空间(`end_user` 档)登录上下文:`auth/password@v1` 除 `scope_type/scope_id` 外
+ * 还须带 `project_id/tenant_id/env/stage`,缺一即 11103;且 `challenge/verify@v1` 必须带
+ * **同一份**上下文,否则 12006「challenge_token 与登录上下文不匹配」。
+ *
+ * 标识取自建号台账 temp/seoh_provision.json(单一真源,⛔ 在前端另抄一份 ID)。
+ * ⚠️ 该台账同时含 `auth_key`/`auth_code` 两枚凭证,这里按字段白名单只读 tenant_id/
+ * project_id,⛔ 整体读入或内联进产物。可用 VITE_SEOH_* 覆盖。
+ */
+function seoCtx() {
+  let j: { tenant_id?: string; project_id?: string } = {};
+  try {
+    j = JSON.parse(readFileSync(fileURLToPath(new URL("../temp/seoh_provision.json", import.meta.url)), "utf-8"));
+  } catch {
+    /* 台账缺失时留空,由登录页给出显式提示(⛔ 静默用错误的空间号登录) */
+  }
+  return {
+    tenant_id: process.env.VITE_SEOH_TENANT_ID ?? String(j.tenant_id ?? ""),
+    project_id: process.env.VITE_SEOH_PROJECT_ID ?? String(j.project_id ?? ""),
+    env: process.env.VITE_SEOH_ENV ?? "nonprod",
+    stage: process.env.VITE_SEOH_STAGE ?? "dev",
+  };
+}
+
+export default defineConfig({
+  plugins: [react()],
+  define: { __SEO_CTX__: JSON.stringify(seoCtx()) },
+  server: {
+    port: 5173,
+    proxy: {
+      "/gateway": {
+        target: GATEWAY,
+        changeOrigin: true,
+        secure: false,
+        rewrite: (p) => p.replace(/^\/gateway/, ""),
+      },
+      "/bos": {
+        target: `http://127.0.0.1:${BOS_PORT}`,
+        changeOrigin: true,
+        rewrite: (p) => p.replace(/^\/bos/, ""),
+      },
+    },
+  },
+  build: { outDir: "dist", sourcemap: true },
+});

+ 14 - 20
prototype/app.js

@@ -5651,7 +5651,6 @@ function regionDrill(ctx) {
       const scopeBtn = `<button class="btn ghost" data-go="roscope" data-id="${ri}" data-scope-from="regops">配置范围</button>`;
       const editBtns = canAdmin ? `<button class="btn ghost" data-regops-rename="${ri}">编辑</button> <button class="btn ghost danger" data-regops-delete="${ri}">删除</button>` : "";
       return `<tr><td>${esc(rt.name)}<br><span class="note">${esc(rt.desc || "")}</span></td>
-        <td>${shareModeText(rt)}</td><td>${shareValueText(rt)}</td>
         <td class="wrap">${esc(scopeSummary(db, rt.scope) || "—")}</td>
         <td>${covered.length}</td>
         <td>${scopeBtn} ${editBtns}</td></tr>`;
@@ -5661,9 +5660,9 @@ function regionDrill(ctx) {
         <h2 style="margin:0">运营团队 ${pathNote}</h2>
         <span>${backBtn} ${canAdmin ? `<button class="btn" data-regops-add>+ 新建运营团队</button>` : ""}</span>
       </div>
-      <p class="note">运营团队由总运营开通,覆盖若干区域。团队内账号功能等同总运营但只限范围内。${isOpsAcct(u) ? "仅显示您所在团队。" : "仅显示与本节点直接关联的团队。"}</p>
-      <table><thead><tr><th>团队名称</th><th>分成方式</th><th>分成比例/金额</th><th>负责范围</th><th>覆盖客户</th><th>操作</th></tr></thead>
-        <tbody>${rows || `<tr><td colspan="6">本节点暂无直接关联运营团队${isOpsAcct(u) ? "(您的团队可能未覆盖此节点)" : ""}</td></tr>`}</tbody></table>
+      <p class="note">运营团队由总运营开通,覆盖若干区域。团队内账号功能等同总运营但只限范围内。${isOpsAcct(u) ? "仅显示您所在团队。" : "仅显示与本节点直接关联的团队。"}运营团队⛔ 分成方(分成方=运营商/合伙人/运维团队三类,见第 4 册§5.1/§5.2),本表⛔「分成方式/分成比例/金额」两列。</p>
+      <table><thead><tr><th>团队名称</th><th>负责范围</th><th>覆盖客户</th><th>操作</th></tr></thead>
+        <tbody>${rows || `<tr><td colspan="4">本节点暂无直接关联运营团队${isOpsAcct(u) ? "(您的团队可能未覆盖此节点)" : ""}</td></tr>`}</tbody></table>
     </div>`;
   }
 
@@ -5814,8 +5813,8 @@ function modalHtml() {
       : `<label>所属区域<span class="req">*</span></label><select id="roRegion"><option value="">请选择所属区域</option>${regionSelectOptions(defRegion, null)}</select>`;
     body = `<label>运营团队名称<span class="req">*</span></label><input id="modalName" placeholder="例如 华东运营" value="${t ? esc(t.name) : ""}">
       ${regionField}
-      <label>备注</label><input id="modalDesc" placeholder="例如 覆盖上海市与江苏省全部下挂客户" value="${t ? esc(t.desc || "") : ""}">
-      ${shareFields(t)}`;
+      <label>备注</label><input id="modalDesc" maxlength="200" placeholder="例如 覆盖上海市与江苏省全部下挂客户" value="${t ? esc(t.desc || "") : ""}">
+      <p class="note">运营团队⛔ 分成方(分成方=运营商/合伙人/运维团队三类,见第 4 册§5.1/§5.2),本弹窗⛔ 分成设置区。</p>`;
     footer += `<button class="btn" data-modal-save>${m.kind === "roNew" ? "新建团队" : "保存"}</button>`;
   } else if (m.kind === "roDelete") {
     const cur = db.regOpsTeams[m.index];
@@ -7208,24 +7207,21 @@ function saveModal() {
     const region = regionSel ? regionSel.value : editing.region;
     if (!region && !(editing && editing.hq)) { say("请选择所属区域"); return; }
     const desc = val("modalDesc");
-    const share = readShareFields();
-    if (share.err) { say(share.err); return; }
+    if (desc.length > 200) { say("备注最长 200 字"); return; }
     if (m.kind === "roNew") {
       if (db.regOpsTeams.some((t) => t.name === name)) { say("运营团队已存在"); return; }
       const scope = route === "regions" && regionTab === "regops" ? { regions: [selRegion], enterprises: [] } : { regions: [], enterprises: [] };
-      db.regOpsTeams.push({ name, region, desc, scope, ...share });
-      addAudit("运营团队首次创建", name, "(空)", `所属区域 ${regionPath(db, region)};${desc || "新建"};分成 ${shareTextOf(share)};负责范围待配置`);
+      db.regOpsTeams.push({ name, region, desc, scope });
+      addAudit("运营团队首次创建", name, "(空)", `所属区域 ${regionPath(db, region)};备注 ${desc || "新建"};负责范围待配置`);
       modal = null;
       say("运营团队已新建,下一步可配置负责范围与成员账号");
     } else {
       const cur = editing;
-      const before = `${cur.name};所属区域 ${regOpsRegionText(cur)};${cur.desc || "无备注"};分成 ${shareTextOf(cur)}`;
+      const before = `${cur.name};所属区域 ${regOpsRegionText(cur)};备注 ${cur.desc || "无备注"}`;
       cur.name = name;
       cur.region = region;
       cur.desc = desc;
-      cur.shareMode = share.shareMode;
-      cur.shareValue = share.shareValue;
-      addAudit("运营团队信息变更", name, before, `${name};所属区域 ${regOpsRegionText(cur)};${desc || "无备注"};分成 ${shareTextOf(share)}`);
+      addAudit("运营团队信息变更", name, before, `${name};所属区域 ${regOpsRegionText(cur)};备注 ${desc || "无备注"}`);
       modal = null;
       say("运营团队信息已保存");
     }
@@ -7768,10 +7764,10 @@ function saveModal() {
       m.reason = "";
       return;
     }
-    const t = db.tickets[m.index];
+    /* 提示语⛔ 在此二次 say:withdrawTicket() 内部已 say「工单已撤回关闭」,
+       再覆盖一次会让界面只显长串,与第 10/14/15 册三处断言对不上(同一动作两份文案) */
     withdrawTicket(m.index, reason);
     modal = null;
-    say(`工单已撤回并终止,撤回原因与操作人已写入处理记录`);
   } else if (m.kind === "selfPwd") {
     /* 自助改密:原密码校验+8–32 位+两次一致+新旧不同(KLT-T223),失败只追加提示、弹窗不关、内容不丢 */
     const acc = selfAcctOf();
@@ -8813,8 +8809,6 @@ function pageRegOpsTeams() {
       <td>${seq(i)}</td>
       <td>${esc(t.name)}${t.hq ? ` ${pill("总部")}` : ""}<br><span class="note">${esc(t.desc || "")}</span></td>
       <td>${esc(regOpsRegionText(t))}</td>
-      <td>${shareModeText(t)}</td>
-      <td>${shareValueText(t)}</td>
       <td>${covered}</td>
       <td>${members ? `${members} 个` : pill("未开通")}</td>
       <td>${canAdmin ? `<button class="btn ghost" data-go="roscope" data-id="${i}" data-scope-from="ropsteams" data-scope-route="ropsteams">配置范围</button> ${ops}` : `<span class="note">档案只读</span> ${ops}`}</td>
@@ -8834,8 +8828,8 @@ function pageRegOpsTeams() {
         <div class="f-item"><label>按名称 / 备注</label><input data-ro-filter="q" value="${esc(roFilter.q)}" placeholder="输入关键字,例如 华东"></div>
         <div class="f-item"><label>&nbsp;</label><button class="btn ghost" data-ro-filter-reset>重置筛选</button></div>
       </div>
-      <table><thead><tr><th>序号</th><th>团队名称</th><th>所属区域</th><th>分成方式</th><th>分成比例/金额</th><th>覆盖客户</th><th>成员账号</th><th>操作</th></tr></thead>
-        <tbody>${rows || `<tr><td colspan="8">没有符合筛选条件的运营团队</td></tr>`}</tbody></table>
+      <table><thead><tr><th>序号</th><th>团队名称(含备注)</th><th>所属区域</th><th>覆盖客户</th><th>成员账号</th><th>操作</th></tr></thead>
+        <tbody>${rows || `<tr><td colspan="6">没有符合筛选条件的运营团队</td></tr>`}</tbody></table>
       <p class="note">${canAdmin ? `「${esc(hqName)}」为系统内置的总部平台级团队,不限所属区域、覆盖全国,可编辑与配置范围但不能删除;团队的内置主账号即总运营账号,该账号不能删除、主账号也不可转交。按区域筛选时不显示不限区域的团队。` : ""}所属区域为团队建档区域,显示全路径;按区域筛选时含该区域下级建档的团队。覆盖客户按负责范围实时计算。成员账号点击进入该团队账号管理。</p>
     </div>`);
 }

+ 9 - 7
prototype/data.js

@@ -46,18 +46,20 @@ const SEED = {
       运维团队不再按「常规 / 施工」分类,团队上只有一个「可分配工单类型」集合;
      mode 为团队内工单分派方式,ticketTypes 为该团队可承接的工单类型(开通与编辑团队时指定,
      路由工单时只在声明了该类型的团队里落单),
-     shareMode 与 shareValue 为档案级分成配置,口径与运营商、合伙人、运营团队一致。 */
+     shareMode 与 shareValue 为档案级分成配置,口径与运营商、合伙人一致(分成方=运营商/合伙人/运维团队三类)。 */
   teams: [
     { name: "华东运维", region: "shp", mode: "手工", ticketTypes: ["开户", "服务开通", "到期停机", "服务停用", "故障", "售后"], scope: { regions: ["sh", "su"], enterprises: [] }, shareMode: "按金额", shareValue: 50 },
     { name: "沪东开户组", region: "sh", mode: "自动平均", ticketTypes: ["开户"], scope: { regions: ["pd"], enterprises: [1] }, shareMode: "按每账号", shareValue: 4 },
   ],
   /* hq: true 为系统内置的总运营团队:不限所属区域(region 为空),负责范围覆盖全国,列表置顶且不可删除。
-     该团队的默认主账号即总运营账号(见 users 中 builtin: true 的一条),不再另设运营团队账号。 */
+     该团队的默认主账号即总运营账号(见 users 中 builtin: true 的一条),不再另设运营团队账号。
+     desc 为「备注」(在册列 ent_team.remark VARCHAR(200) NULL,选填,参与「按名称 / 备注」关键字筛选与审计前后值)。
+     ⚠️ 运营团队⛔ 分成方,故本表⛔ shareMode / shareValue 两字段(2026-11-08 定案:分成方=运营商/合伙人/运维团队三类,见第 4 册§5.1/§5.2)。 */
   regOpsTeams: [
-    { name: "总运营团队", region: "", hq: true, scope: { regions: ["shp", "jsp", "gdp"], enterprises: [] }, desc: "总部平台级团队,不限所属区域,覆盖全国全部客户", shareMode: "按比例", shareValue: 0.1 },
-    { name: "华东运营", region: "shp", scope: { regions: ["shp", "jsp"], enterprises: [] }, desc: "覆盖上海市与江苏省全部下挂客户", shareMode: "按比例", shareValue: 0.08 },
-    { name: "华南运营", region: "gdp", scope: { regions: ["gdp"], enterprises: [] }, desc: "覆盖广东省全部下挂客户", shareMode: "按金额", shareValue: 30 },
-    { name: "上海运营", region: "sh", scope: { regions: ["sh"], enterprises: [] }, desc: "覆盖上海市及其下级区域", shareMode: "按每账号", shareValue: 2.5 },
+    { name: "总运营团队", region: "", hq: true, scope: { regions: ["shp", "jsp", "gdp"], enterprises: [] }, desc: "总部平台级团队,不限所属区域,覆盖全国全部客户" },
+    { name: "华东运营", region: "shp", scope: { regions: ["shp", "jsp"], enterprises: [] }, desc: "覆盖上海市与江苏省全部下挂客户" },
+    { name: "华南运营", region: "gdp", scope: { regions: ["gdp"], enterprises: [] }, desc: "覆盖广东省全部下挂客户" },
+    { name: "上海运营", region: "sh", scope: { regions: ["sh"], enterprises: [] }, desc: "覆盖上海市及其下级区域" },
   ],
   /* 成员不再分「常规 / 施工」两种身份:每名成员配三件事——
      ① types=本人可处理的工单类型(必须是所在团队 ticketTypes 的子集);
@@ -614,7 +616,7 @@ const SEED = {
         evidences: ["oss://回填凭证/T-20260318-03/零信任放行截图.png"], photos: [],
       } },
   ],
-  /* 分成取值只有一处真源:四类分成方(运营商、合伙人、运维团队)各自档案上的 shareMode / shareValue 两列,
+  /* 分成取值只有一处真源:三类分成方(运营商、合伙人、运维团队)各自档案上的 shareMode / shareValue 两列(运营团队⛔ 分成方),
      2026-11-04 业主定案取消逐客户分成规则(原 rules 数组与「区域常规 / 合同增补」层级一并删除),
      该方名下客户统一按这两个取值计算分成;名下没有客户的该方不产生分成行。 */
   /* 应扣除成本项是两块功能(见需求规格说明 6.1):① 定义全局一套、不涉及金额;② 金额按「省份 × 运营商」组合各配一套。

+ 6 - 1
src/Cargo.lock

@@ -17,6 +17,7 @@ dependencies = [
  "bos-platform",
  "bos-scope",
  "chrono",
+ "rand 0.8.8",
  "serde",
  "serde_json",
  "sqlx",
@@ -258,6 +259,7 @@ version = "0.1.0"
 dependencies = [
  "async-trait",
  "bos-core",
+ "bos-platform",
  "chrono",
  "serde",
  "serde_json",
@@ -315,16 +317,17 @@ version = "0.1.0"
 dependencies = [
  "async-trait",
  "axum",
- "base64 0.22.1",
  "bos-core",
  "bos-platform",
  "bos-scope",
  "chrono",
+ "seoh-service-sdk",
  "serde",
  "serde_json",
  "sqlx",
  "tower 0.4.13",
  "tracing",
+ "uuid",
 ]
 
 [[package]]
@@ -337,6 +340,7 @@ dependencies = [
  "serde_json",
  "sqlx",
  "thiserror 1.0.69",
+ "tokio",
  "tracing",
  "uuid",
 ]
@@ -417,6 +421,7 @@ dependencies = [
  "bos-core",
  "bos-platform",
  "chrono",
+ "seoh-service-sdk",
  "serde",
  "serde_json",
  "sqlx",

File diff ditekan karena terlalu besar
+ 452 - 17
src/bin/klt-bos/openapi.yaml


+ 47 - 5
src/bin/klt-bos/src/config.rs

@@ -3,7 +3,7 @@ use serde::Deserialize;
 #[derive(Debug, Clone, Deserialize)]
 pub struct AppConfig {
     pub server: ServerConfig,
-    pub database: DatabaseConfig,
+    pub uds: UdsSection,
     pub gateway: GatewayConfig,
     pub registry: RegistryConfig,
     #[serde(default = "default_bos_env")]
@@ -32,8 +32,30 @@ fn default_port() -> u16 {
 }
 
 #[derive(Debug, Clone, Deserialize)]
-pub struct DatabaseConfig {
-    pub url: String,
+pub struct UdsSection {
+    /// UDS 网关基址(本机联调 `https://127.0.0.1:3022`,集群内 `https://seoh-uds-gateway:3022`)。
+    #[serde(default = "default_uds_base")]
+    pub base_url: String,
+    pub tenant_id: String,
+    pub project_id: String,
+    /// SEOH 逻辑环境 ∈ `dev|test|prod`(进 `X-Seoh-Env` 头)。
+    #[serde(default = "default_seoh_env")]
+    pub seoh_env: String,
+    /// 数据面环境 ∈ `nonprod|prod`(进 body)。
+    #[serde(default = "default_data_env")]
+    pub data_env: String,
+    #[serde(default)]
+    pub danger_accept_invalid_certs: bool,
+}
+
+fn default_uds_base() -> String {
+    "https://127.0.0.1:3022".into()
+}
+fn default_seoh_env() -> String {
+    std::env::var("BOS_ENV").unwrap_or_else(|_| "dev".into())
+}
+fn default_data_env() -> String {
+    "nonprod".into()
 }
 
 #[derive(Debug, Clone, Deserialize)]
@@ -68,14 +90,34 @@ fn default_ver() -> String {
     "0.1.0".into()
 }
 
+fn env_flag(key: &str) -> bool {
+    std::env::var(key)
+        .ok()
+        .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
+        .unwrap_or(false)
+}
+
 pub async fn load() -> Result<AppConfig, Box<dyn std::error::Error>> {
     let mut builder = config::Config::builder()
         .add_source(config::File::with_name("config/default").required(false))
         .add_source(config::File::with_name("config/development").required(false))
         .add_source(config::Environment::default().separator("__"));
 
-    if let Ok(url) = std::env::var("KLT_BOS_DATABASE_URL") {
-        builder = builder.set_override("database.url", url)?;
+    // 数据通道:⛔ 数据库凭据,只需网关地址与归属 ID
+    for (key, path) in [
+        ("KLT_BOS_UDS_BASE_URL", "uds.base_url"),
+        ("KLT_BOS_UDS_TENANT_ID", "uds.tenant_id"),
+        ("KLT_BOS_UDS_PROJECT_ID", "uds.project_id"),
+        ("KLT_BOS_SEOH_ENV", "uds.seoh_env"),
+    ] {
+        if let Ok(v) = std::env::var(key) {
+            if !v.trim().is_empty() {
+                builder = builder.set_override(path, v)?;
+            }
+        }
+    }
+    if env_flag("KLT_BOS_TLS_DANGER_ACCEPT_INVALID_CERTS") {
+        builder = builder.set_override("uds.danger_accept_invalid_certs", true)?;
     }
     if let Ok(port) = std::env::var("KLT_BOS_PORT") {
         builder = builder.set_override("server.port", port)?;

+ 160 - 33
src/bin/klt-bos/src/main.rs

@@ -6,7 +6,10 @@ use std::sync::Arc;
 use account::account_router;
 use axum::Router;
 use bos_api::AppState;
-use bos_platform::clients::PlatformClient;
+use bos_platform::clients::{
+    uds::{UdsClient, UdsConfig},
+    PlatformClient,
+};
 use bos_scope::DbScopedSelect;
 use seoh_service_sdk::{
     build_openapi_ac_route_table, unified_ac_middleware, RuntimeTokenManager,
@@ -26,25 +29,39 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         )
         .init();
 
-    let internal_token = match std::env::var("KLT_BOS_SERVICE_TOKEN")
-        .ok()
-        .filter(|t| !t.trim().is_empty())
-    {
-        Some(t) => t.trim().to_string(),
+    // 两类凭证职责不同,⛔ 混用(AC 对 `X-Internal-Token` 只接受 token-issuer 签发的
+    // **服务身份** JWT,用户/账号 JWT 会被判 11001「服务间认证失败」):
+    // · 服务间内部票 `KLT_BOS_INTERNAL_TOKEN`(`X-Internal-Token`):调用 AC 判权、
+    //   服务注册中心与网关管理接口。线上由 `BOOTSTRAP_TOKEN` 换票得到;本机联调由
+    //   temp/bos_run.sh 只签一张一次性 bootstrap 票,这里交给 SDK 的
+    //   `obtain_runtime_token_from_env` 用 mTLS 换票并把 service_refresh 落盘续期
+    //   (token-issuer 开了 mtls_required,缺客户端证书即 401)。
+    // · 运行期账号票 `KLT_BOS_SERVICE_TOKEN`(`Authorization: Bearer`):本项目下发的
+    //   项目空间账号 JWT,是 UDS 与平台业务接口的数据面凭证(业主 2026-11-07 裁定,
+    //   见 docs/详细设计说明书/00-总则与全局约定/18-未决事项与口径差异登记.md §18.3)。
+    let internal_token = match env_token("KLT_BOS_INTERNAL_TOKEN") {
+        Some(t) => t,
         None => match seoh_service_sdk::obtain_runtime_token_from_env().await {
             Ok(rt) => {
-                info!("已用 Bootstrap Token 换取运行期 JWT");
+                info!("已用 Bootstrap Token 换取运行期服务 JWT");
                 rt
             }
             Err(e) => {
                 tracing::warn!(
-                    "未配置服务 Token 且 Bootstrap 换取失败: {};将以空 Token 继续(本地/降级)",
+                    "未配置 KLT_BOS_INTERNAL_TOKEN 且 Bootstrap 换票失败: {};\
+                     AC 判权将按「缺少内部调用令牌」失败关闭",
                     e
                 );
                 String::new()
             }
         },
     };
+    let account_token = env_token("KLT_BOS_SERVICE_TOKEN").unwrap_or_default();
+    if account_token.is_empty() {
+        tracing::warn!(
+            "未配置 KLT_BOS_SERVICE_TOKEN(项目空间账号 JWT);UDS 数据面调用会失败"
+        );
+    }
     std::env::set_var("CONFIG_CENTER_TOKEN", &internal_token);
     let runtime_token_manager =
         Arc::new(RuntimeTokenManager::new(internal_token.clone(), 300));
@@ -56,31 +73,47 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         cfg.server.port, cfg.bos_env
     );
 
-    if cfg.database.url.trim().is_empty() {
-        return Err("必须配置 database.url(配置中心或 KLT_BOS_DATABASE_URL)".into());
+    if cfg.uds.tenant_id.trim().is_empty() || cfg.uds.project_id.trim().is_empty() {
+        return Err(
+            "必须配置 uds.tenant_id 与 uds.project_id(KLT_BOS_UDS_TENANT_ID/KLT_BOS_UDS_PROJECT_ID)"
+                .into(),
+        );
     }
-    let pool = sqlx::postgres::PgPoolOptions::new()
-        .max_connections(10)
-        .connect(&cfg.database.url)
-        .await?;
-    sqlx::migrate!("../../migrations/dev").run(&pool).await?;
-    info!("数据库连接与迁移完成");
+    // 数据一律经 UDS:⛔ 自持库凭据直连库,也⛔ 由本服务跑 DDL 迁移
+    // (建表/种子由 DM 交付件经 UDS `exec_ddl@v1` 执行,见 temp/uds_apply.py)。
+    let token_for_uds = account_token.clone();
+    let db = Arc::new(UdsClient::new(
+        UdsConfig {
+            base_url: cfg.uds.base_url.clone(),
+            tenant_id: cfg.uds.tenant_id.clone(),
+            project_id: cfg.uds.project_id.clone(),
+            seoh_env: cfg.uds.seoh_env.clone(),
+            data_env: cfg.uds.data_env.clone(),
+            danger_accept_invalid_certs: cfg.uds.danger_accept_invalid_certs,
+        },
+        Arc::new(move || token_for_uds.clone()),
+    ));
+    info!(
+        "UDS 数据通道就绪 base={} tenant={} project={} seoh_env={} data_env={}",
+        cfg.uds.base_url, cfg.uds.tenant_id, cfg.uds.project_id, cfg.uds.seoh_env, cfg.uds.data_env
+    );
 
-    let token_for_platform = runtime_token_manager.clone();
+    let token_for_platform = account_token;
     let platform = Arc::new(PlatformClient::new(
         cfg.gateway.url.clone(),
-        Arc::new(move || token_for_platform.current_token()),
+        Arc::new(move || token_for_platform.clone()),
     ));
-    let scope = Arc::new(DbScopedSelect {
-        pool: pool.clone(),
-    });
+    let scope = Arc::new(DbScopedSelect { db: db.clone() });
 
     let state = AppState {
-        pool,
+        db,
         platform,
         scope,
         bos_env: cfg.bos_env.clone(),
         service_name: cfg.registry.service_name.clone(),
+        project_id: cfg.uds.project_id.clone(),
+        data_env: cfg.uds.data_env.clone(),
+        seoh_env: cfg.uds.seoh_env.clone(),
     };
 
     let registry_url_for_ac = if !cfg.registry.url.trim().is_empty() {
@@ -102,6 +135,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
     let app = Router::new()
         .merge(account_router())
+        // 最内层:读网关注入到**请求体根级**的授权上界(工单回件 §5.2 B2)。必须在 AC 两层内侧
+        // ——`unified_ac_middleware` 会把体缓冲后重发,本层在其之后才读得到体;解析结果进请求扩展,
+        // 由 `RequireAuth` 交给 `load_binding`(⛔ 在此判角色/拼 SQL,也⛔ 改 handler 签名)。
+        .layer(axum::middleware::from_fn(bos_api::grant_inject_middleware))
+        // 紧接路由、在 AC 内侧:给 `ac_ms` 打点(=进服务到判权结束),三段耗时的分界点。
+        .layer(axum::middleware::from_fn(bos_api::ac_done_middleware))
         .layer(axum::middleware::from_fn_with_state(
             ac_cfg,
             unified_ac_middleware,
@@ -112,6 +151,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
                 .allow_methods([axum::http::Method::GET, axum::http::Method::POST])
                 .allow_headers(Any),
         )
+        // 最外层:`X-Request-Id` 贯穿+`request.id`/`ac_ms`/`uds_ms`/`self_ms` 请求日志
+        // (《外部项目服务接入约束》§10 可观测最低要求、讨论稿 K12 ②④)。
+        .layer(axum::middleware::from_fn(bos_api::request_trace_middleware))
         .with_state(state);
 
     let addr: SocketAddr = format!("{}:{}", cfg.server.host, cfg.server.port).parse()?;
@@ -121,11 +163,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
             register_service_with_delayed_registration, GatewayConfig as SdkGatewayConfig,
             ServerConfig as SdkServerConfig, ServiceRegistrationConfig,
         };
-        let health_host = if cfg.server.host == "0.0.0.0" {
-            "localhost".to_string()
-        } else {
-            cfg.server.host.clone()
-        };
+        let health_host = advertised_listener(&cfg.server.host, cfg.server.port).0;
         let reg_config = ServiceRegistrationConfig {
             gateway: SdkGatewayConfig {
                 enabled: cfg.gateway.enabled,
@@ -133,8 +171,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
                 service_name: cfg.gateway.service_name.clone(),
                 service_version: cfg.gateway.service_version.clone(),
                 api_key: None,
-                danger_accept_invalid_certs: Some(false),
-                ca_cert_path: None,
+                // 集群内核心服务均为自签名证书:加载 Root CA 完成链路校验,
+                // 仅在显式开关打开时才放宽(本机联调)。
+                danger_accept_invalid_certs: Some(env_flag(
+                    "KLT_BOS_TLS_DANGER_ACCEPT_INVALID_CERTS",
+                )),
+                ca_cert_path: std::env::var("CONFIG_CENTER_CA_CERT_PATH")
+                    .ok()
+                    .map(|v| v.trim().to_string())
+                    .filter(|v| !v.is_empty()),
                 client_cert_path: None,
                 client_key_path: None,
             },
@@ -167,13 +212,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         } else {
             Some(internal_token)
         };
+        let (reg_host, reg_port) = advertised_listener(&cfg.server.host, cfg.server.port);
         let reg_config = seoh_service_sdk::build_registry_registration_config_from_env(
             &cfg.registry.url,
             &cfg.registry.service_name,
             &cfg.registry.service_version,
             "klt-bos",
-            &cfg.server.host,
-            cfg.server.port,
+            &reg_host,
+            reg_port,
             cfg.server.tls_enabled,
             cfg.registry.signature_secret.as_deref(),
             "/var/lib/seoh/klt-bos-instance-id.json",
@@ -191,12 +237,93 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
         tracing::warn!("phase1 jobs register skipped: {e}");
     }
 
-    info!("klt-bos listening on {addr}");
+    info!(
+        "klt-bos listening on {addr}(注册中心心跳=SDK 默认开启、60s 一次,可用 \
+         REGISTRY_HEARTBEAT_INTERVAL_SECS 调整;`heartbeat_required` 暂不声明,等平台判活扫描上线)"
+    );
     let listener = tokio::net::TcpListener::bind(addr).await?;
-    axum::serve(listener, app).await?;
+    // 优雅停机(讨论稿 K3.2 ①、接入约束 §7.5):收到 SIGTERM/SIGINT ⇒ 停止接受新请求 ⇒
+    // 排空在途请求 ⇒ 退出。⛔ 在此调网关的 `deregister()`(K3:会删掉平台侧手配路由);
+    // 实例注销应调注册中心 `service/deregister@v1`,SDK 尚无该客户端实现 ⇒ 见 18 册登记。
+    axum::serve(listener, app)
+        .with_graceful_shutdown(wait_shutdown_signal())
+        .await?;
+    info!("已停止接受新请求并排空在途请求,klt-bos 退出");
     Ok(())
 }
 
+/// 停机信号:容器编排发 SIGTERM,本机前台运行发 SIGINT。
+async fn wait_shutdown_signal() {
+    #[cfg(unix)]
+    {
+        use tokio::signal::unix::{signal, SignalKind};
+        match signal(SignalKind::terminate()) {
+            Ok(mut term) => {
+                tokio::select! {
+                    _ = tokio::signal::ctrl_c() => info!("收到 SIGINT,开始优雅停机"),
+                    _ = term.recv() => info!("收到 SIGTERM,开始优雅停机"),
+                }
+            }
+            Err(e) => {
+                tracing::warn!("注册 SIGTERM 处理器失败,仅监听 SIGINT: {e}");
+                let _ = tokio::signal::ctrl_c().await;
+            }
+        }
+    }
+    #[cfg(not(unix))]
+    {
+        let _ = tokio::signal::ctrl_c().await;
+        info!("收到 SIGINT,开始优雅停机");
+    }
+}
+
+/// 对外(网关容器)可达的监听地址:网关跑在 Docker 里,容器内的 localhost 不是本机,
+/// 因此注册到注册中心/网关的地址需显式指定(macOS Docker Desktop 内置 host.docker.internal)。
+fn advertised_listener(bind_host: &str, bind_port: u16) -> (String, u16) {
+    let host = ["SEOH_REGISTRY_ADVERTISE_HOST", "REGISTRY_ADVERTISE_HOST"]
+        .iter()
+        .filter_map(|k| std::env::var(k).ok())
+        .map(|v| v.trim().to_string())
+        .find(|v| !v.is_empty())
+        .unwrap_or_else(|| {
+            if bind_host == "0.0.0.0" || bind_host.is_empty() {
+                "localhost".to_string()
+            } else {
+                bind_host.to_string()
+            }
+        });
+    let port = ["SEOH_REGISTRY_ADVERTISE_PORT", "REGISTRY_ADVERTISE_PORT"]
+        .iter()
+        .filter_map(|k| std::env::var(k).ok())
+        .filter_map(|v| v.trim().parse::<u16>().ok())
+        .next()
+        .unwrap_or(bind_port);
+    // 讨论稿 K4/§7.1:注册实例地址只收 IPv4/IPv6 字面量,⛔ 域名,且回环地址会被地址策略拒绝。
+    // 本机联调用 `host.docker.internal` 是 Docker Desktop 的临时形态,正式部署必须显式给容器 IPv4。
+    if host.parse::<std::net::IpAddr>().is_err() {
+        tracing::warn!(
+            "登记到注册中心/网关的地址 `{host}` 不是 IP 字面量(K4 要求 IPv4/IPv6):\
+             正式部署请设 SEOH_REGISTRY_ADVERTISE_HOST=<本实例 IPv4>"
+        );
+    }
+    (host, port)
+}
+
+/// 读取令牌类环境变量(trim 后空串视为未设置)。
+fn env_token(key: &str) -> Option<String> {
+    std::env::var(key)
+        .ok()
+        .map(|v| v.trim().to_string())
+        .filter(|v| !v.is_empty())
+}
+
+fn env_flag(key: &str) -> bool {
+    std::env::var(key)
+        .ok()
+        .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
+        .unwrap_or(false)
+}
+
 fn openapi_spec(version: &str) -> serde_json::Value {
     let mut v: serde_json::Value =
         serde_yaml::from_str(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/openapi.yaml")))

+ 7 - 2
src/config/default.toml

@@ -5,8 +5,13 @@ host = "0.0.0.0"
 port = 8088
 tls_enabled = false
 
-[database]
-url = ""
+[uds]
+base_url = "https://127.0.0.1:3022"
+tenant_id = "376985083560624128"
+project_id = "376985101906509824"
+seoh_env = "dev"
+data_env = "nonprod"
+danger_accept_invalid_certs = true
 
 [gateway]
 enabled = true

+ 2 - 1
src/crates/bos-api/Cargo.toml

@@ -15,4 +15,5 @@ sqlx = { workspace = true }
 tracing = { workspace = true }
 async-trait = { workspace = true }
 chrono = { workspace = true }
-base64 = { workspace = true }
+uuid = { workspace = true }
+seoh-service-sdk = { workspace = true }

+ 57 - 30
src/crates/bos-api/src/auth.rs

@@ -1,53 +1,79 @@
 use bos_core::{BosError, RoleCode};
+use bos_platform::clients::uds::{de, UdsClient};
 use bos_scope::{AuthContext, ScopeMode, SubjectRef};
-use sqlx::PgPool;
+use serde::Deserialize;
+use serde_json::json;
 use std::collections::HashSet;
 
-#[derive(Debug, sqlx::FromRow)]
+#[derive(Debug, Deserialize)]
 struct BindingRow {
-    user_id: i64,
+    #[serde(deserialize_with = "de::as_string")]
+    user_id: String,
     role_code: String,
     subject_type: String,
     subject_id: String,
     entry_only: bool,
+    #[serde(default, deserialize_with = "de::as_opt_string")]
     username: Option<String>,
 }
 
-pub async fn load_binding(pool: &PgPool, user_id: &str) -> Result<AuthContext, BosError> {
-    let uid: i64 = user_id
-        .parse()
+/// 读业务身份绑定(`bos_user_binding`)。
+///
+/// p4 起该绑定关系仍在我方业务库,IAM 只负责「谁登录」;值一律走 `params`,
+/// `$1::bigint` 是联邦引擎已实测可渲染的写法。
+///
+/// `grant`=本次请求携带的**通道②授权上界**(工单回件 §5.2 B2,2026-11-08 起不再恒置空):
+/// `None`=未注入(路由未声明 `x-enumeration-kind`/绕网关直连/注入键形状不认识),
+/// `Some(..)`=确已下发。两者都会落到 `AuthContext::granted_resource_instances` 的**空集**
+/// (上界为零/不限同样给空集),既有消费方「空集=拒绝/回落本地 `bos_data_scope`」的
+/// 失败关闭语义不变;口径差异只经 `AuthContext::grant_bound` 表达。
+/// 解析一律走平台 SDK `resolve_upper_bound`(见 [`crate::grant`]),⛔ 在此自行解释三形态。
+pub async fn load_binding(
+    db: &UdsClient,
+    user_id: &str,
+    grant: Option<&seoh_service_sdk::InstanceUpperBound>,
+) -> Result<AuthContext, BosError> {
+    user_id
+        .parse::<i64>()
         .map_err(|_| BosError::bad_params("invalid user_id"))?;
-    let row = sqlx::query_as::<_, BindingRow>(
-        r#"
-        SELECT user_id, role_code, subject_type, subject_id, entry_only, username
-        FROM bos_user_binding WHERE user_id = $1
-        "#,
-    )
-    .bind(uid)
-    .fetch_optional(pool)
-    .await
-    .map_err(|e| BosError::internal(e.to_string()))?
-    .ok_or_else(|| BosError::biz(bos_core::ErrorCode::Forbidden, "账号未绑定业务角色"))?;
+    let row = db
+        .query_one::<BindingRow>(
+            "SELECT user_id, role_code, subject_type, subject_id, entry_only, username \
+             FROM bos_user_binding WHERE user_id = $1::bigint",
+            &[json!(user_id)],
+        )
+        .await?
+        .ok_or_else(|| BosError::biz(bos_core::ErrorCode::Forbidden, "账号未绑定业务角色"))?;
 
-    let role = RoleCode::parse(&row.role_code).ok_or_else(|| {
-        BosError::internal(format!("unknown role_code {}", row.role_code))
-    })?;
+    let role = RoleCode::parse(&row.role_code)
+        .ok_or_else(|| BosError::internal(format!("unknown role_code {}", row.role_code)))?;
 
     let scope_mode = if matches!(role, RoleCode::Ops) {
-        let mode: Option<(String,)> = sqlx::query_as(
-            "SELECT scope_mode FROM ops_member WHERE user_id = $1 LIMIT 1",
-        )
-        .bind(uid)
-        .fetch_optional(pool)
-        .await
-        .map_err(|e| BosError::internal(e.to_string()))?;
-        mode.and_then(|(m,)| ScopeMode::parse(&m))
+        let mode = db
+            .query_one::<serde_json::Value>(
+                "SELECT scope_mode FROM ops_member WHERE user_id = $1::bigint LIMIT 1",
+                &[json!(user_id)],
+            )
+            .await?;
+        mode.and_then(|m| {
+            m.get("scope_mode")
+                .and_then(|v| v.as_str())
+                .and_then(ScopeMode::parse)
+        })
     } else {
         None
     };
 
+    // 通道②:把上界投影成「可直接按精确 id 判定」的集合(口径见 AuthContext 字段注释)。
+    // 未注入 ⇒ 空集+grant_bound=None,与 2026-11-08 之前的行为逐字节一致(失败关闭)。
+    let grant_bound = grant.cloned();
+    let granted_resource_instances = match &grant_bound {
+        Some(b) => crate::grant::usable_instance_ids(b),
+        None => HashSet::new(),
+    };
+
     Ok(AuthContext {
-        user_id: row.user_id.to_string(),
+        user_id: row.user_id,
         role,
         subject: SubjectRef {
             subject_type: row.subject_type,
@@ -55,7 +81,8 @@ pub async fn load_binding(pool: &PgPool, user_id: &str) -> Result<AuthContext, B
         },
         entry_only: row.entry_only,
         scope_mode,
-        granted_resource_instances: HashSet::new(),
+        granted_resource_instances,
+        grant_bound,
         username: row.username,
     })
 }

+ 48 - 52
src/crates/bos-api/src/extract.rs

@@ -6,6 +6,7 @@ use axum::{
 };
 use bos_core::{ApiResponse, BosError};
 use bos_scope::AuthContext;
+use seoh_service_sdk::{GrantedUpperBound, UnifiedAcContext};
 use serde::de::DeserializeOwned;
 
 use crate::state::AppState;
@@ -13,6 +14,24 @@ use crate::state::AppState;
 pub struct RequireAuth(pub AuthContext);
 pub struct OptionalAuth(pub Option<AuthContext>);
 
+/// 「当前是哪个业务账号」的**唯一**可信来源=SDK 统一判权中间件写入请求扩展的
+/// [`UnifiedAcContext`](其 `identity_id` 由 `access/check@v1` 回显,等于人类 JWT 的 `sub`
+/// =IAM `user/create` 的 `id`,见 18 册 §18.3 第六轮)。
+///
+/// ⛔ 三类旧写法(平台《外部项目服务接入约束》§8.3 红线 6「信任客户端自行带来的身份」):
+/// * `X-Seoh-User-Id`:任何直连 `:8088` 的调用方都能伪造成任意账号;
+/// * `X-Granted-Resource-Instances`:授权范围由调用方自报=行级可见范围可被放大;
+/// * 自行 base64 解 `Authorization` 里的 JWT `sub`(不验签):伪造一个 JWT 形状的字符串即可冒充。
+///   需要自行解析人类 JWT 时必须**验签**,本项目改走 AC 上下文,不再自解。
+fn ac_identity(parts: &Parts) -> Option<String> {
+    parts
+        .extensions
+        .get::<UnifiedAcContext>()
+        .and_then(|ctx| ctx.identity_id.clone())
+        .map(|v| v.trim().to_string())
+        .filter(|v| !v.is_empty())
+}
+
 #[async_trait]
 impl FromRequestParts<AppState> for RequireAuth {
     type Rejection = axum::response::Response;
@@ -24,40 +43,42 @@ impl FromRequestParts<AppState> for RequireAuth {
         if let Some(auth) = parts.extensions.get::<AuthContext>() {
             return Ok(RequireAuth(auth.clone()));
         }
-        // 尝试从 Authorization 头解析(本地/网关后)
-        let auth_header = parts
-            .headers
-            .get(axum::http::header::AUTHORIZATION)
-            .and_then(|v| v.to_str().ok())
-            .unwrap_or("");
-        let user_id = parts
-            .headers
-            .get("X-Seoh-User-Id")
-            .and_then(|v| v.to_str().ok())
-            .map(|s| s.to_string())
-            .or_else(|| extract_sub_from_bearer(auth_header));
-
-        let Some(user_id) = user_id else {
+        let Some(user_id) = ac_identity(parts) else {
+            // 判权中间件没给出身份=该请求没经过 AC(多为绕网关直连或路由未登记),
+            // 一律失败关闭,⛔ 退回到「读头自认身份」。
+            tracing::warn!(
+                "缺少 AC 判权上下文(UnifiedAcContext.identity_id),拒绝按未认证请求处理 route={}",
+                parts.uri.path()
+            );
             return Err(json_err(BosError::biz(
                 bos_core::ErrorCode::Unauthorized,
-                "未登录",
+                "未登录(缺少 AC 判权上下文)",
             )));
         };
 
-        // 注入的 granted 实例
-        let mut auth = crate::load_binding(&state.pool, &user_id)
+        // 通道②授权上界(工单回件 §5.2 B2):两条下发路径同由 SDK `resolve_upper_bound` 解析,
+        // 谁在取谁——
+        // 1. [`crate::grant::grant_inject_middleware`]:网关写进请求体根级的注入(我方当前唯一可用来源);
+        // 2. [`seoh_service_sdk::GrantedUpperBound`]:SDK 从 AC 响应写入的扩展(我方路由当前取不到:
+        //    SDK 路由表把 `x-scope` 原样发给 AC、⛔ 折叠 `x-enumeration-kind`,而手写
+        //    `x-scope.source_enumeration` 会被注册中心拒,详见 grant.rs 头注)。
+        // 两者都取不到 ⇒ `None`=**未注入**,消费方保持现状的失败关闭(⛔ 当「不限」放行)。
+        let grant = parts
+            .extensions
+            .get::<crate::grant::GrantInjection>()
+            .map(|g| g.0.clone())
+            .or_else(|| {
+                parts
+                    .extensions
+                    .get::<GrantedUpperBound>()
+                    .map(|g| g.0.clone())
+            });
+        let auth = crate::load_binding(&state.db, &user_id, grant.as_ref())
             .await
             .map_err(json_err)?;
-        if let Some(raw) = parts
-            .headers
-            .get("X-Granted-Resource-Instances")
-            .and_then(|v| v.to_str().ok())
-        {
-            if let Ok(ids) = serde_json::from_str::<Vec<String>>(raw) {
-                auth.granted_resource_instances.extend(ids);
-            }
-        }
-        // 环境一致性
+
+        // `X-Seoh-Env` 只用于「请求打到了错误环境的实例」这类快速失败,⛔ 当身份或判权依据
+        // (接入约束 §6/讨论稿 K8:该头由网关剥离重注,客户端传了也没用)。
         if let Some(env) = parts.headers.get("X-Seoh-Env").and_then(|v| v.to_str().ok()) {
             if env != state.bos_env {
                 return Err(json_err(BosError::bad_params(format!(
@@ -86,31 +107,6 @@ impl FromRequestParts<AppState> for OptionalAuth {
     }
 }
 
-fn extract_sub_from_bearer(header: &str) -> Option<String> {
-    let token = header.strip_prefix("Bearer ")?.trim();
-    // 非验证解析 JWT payload 仅用于本地 stub;生产由 SDK middleware 注入 user id。
-    let parts: Vec<&str> = token.split('.').collect();
-    if parts.len() < 2 {
-        return None;
-    }
-    let payload = parts[1];
-    let padded = match payload.len() % 4 {
-        2 => format!("{payload}=="),
-        3 => format!("{payload}="),
-        _ => payload.to_string(),
-    };
-    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
-    let bytes = URL_SAFE_NO_PAD
-        .decode(padded.trim_end_matches('='))
-        .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(&padded))
-        .ok()?;
-    let v: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
-    v.get("sub")
-        .or_else(|| v.get("user_id"))
-        .and_then(|x| x.as_str())
-        .map(|s| s.to_string())
-}
-
 pub struct DataBody<T>(pub T);
 
 #[async_trait]

+ 224 - 0
src/crates/bos-api/src/grant.rs

@@ -0,0 +1,224 @@
+//! 通道②(平台授权上界)的消费入口 —— 工单回件 §5.2 B2(业主认领 2026-11-08)。
+//!
+//! 平台侧机制(2026-11-08 在平台仓实读,⛔ 凭记忆):
+//! * 作者侧唯一的真源列举标记=operation 级 `x-enumeration-kind: tree|list`,注册中心把它折叠为
+//!   `scope_config.<METHOD>.source_enumeration`(`seoh-service-registry/src/services/registry.rs:486-528`);
+//!   手写 `x-scope.source_enumeration` 会被注册中心判非法 ⇒ 路由 abnormal/callable=false;
+//! * AC 仅在 `scope_config.source_enumeration.kind ∈ {tree,list}` 时回传上界
+//!   (`seoh-access-control/src/handlers/access.rs:983-988`);
+//! * 网关拿到上界后,**先删除客户端自带的同名键**,再写入转发体的**根级**(与 `data` 平级,
+//!   ⛔ 在 `data` 内):`seoh-api-gateway/src/proxy.rs:1665-1698`;
+//! * 唯一解析口径=SDK `resolve_upper_bound`(`all`/`ids`/`rules`+`deny_*`),
+//!   本项目经 workspace 依赖直接复用该 crate(`src/Cargo.toml:31`),⛔ 在此平行实现。
+//!
+//! 为什么要在这里缓冲请求体:注入键位于**请求体根级**,而 [`crate::extract::RequireAuth`] 是
+//! `FromRequestParts`,按 axum 契约拿不到体。SDK 自己在 AC 响应通道写入的 `GrantedUpperBound`
+//! 扩展在我方路由上取不到上界——SDK 的 `OpenApiAcRouteTable` 把 `x-scope` 原样发给 AC、
+//! ⛔ 折叠 `x-enumeration-kind`(`seoh-service-sdk/rust/src/unified_ac_middleware.rs:926-970`),
+//! 而手写 `x-scope.source_enumeration` 又会被注册中心拒 ⇒ 我方无任何合法途径让 AC 响应通道带上
+//! 上界,只能消费网关注入。本层只解一次体,结果放请求扩展,由 [`crate::extract`] 交给
+//! [`crate::auth::load_binding`],⛔ 改任何 handler 签名。
+//!
+//! 失败关闭:非 JSON/根级键形状不认识 ⇒ 要么不写扩展(=未注入,消费方按现状拒绝),要么写
+//! `Empty`(=确已注入但上界不可用);⛔ 在此放宽成「拿不到就全放行」。
+
+use axum::{
+    body::{to_bytes, Body},
+    extract::Request,
+    http::{HeaderMap, Method},
+    middleware::Next,
+    response::Response,
+};
+use seoh_service_sdk::{resolve_upper_bound, GrantedResourceGrant, InstanceUpperBound};
+use serde_json::Value;
+use std::collections::HashSet;
+
+/// 网关注入键(体根级,与 `data` 平级)。客户端自带值在网关转发前已被 `remove`,
+/// 故本服务读到这两个键即可判定它来自网关(`proxy.rs:1672-1676`)。
+pub const GRANTED_RESOURCE_INSTANCES_KEY: &str = "__granted_resource_instances";
+pub const GRANTED_RESOURCE_GRANT_KEY: &str = "__granted_resource_grant";
+
+/// 请求扩展:本次请求携带的授权上界(由 SDK `resolve_upper_bound` 解析)。
+///
+/// 扩展**缺省**=本次请求无上界可依据(`AuthContext::grant_bound`=`None`),
+/// 与 `Some(Empty)`(下发了上界且上界为零)是两种口径,⛔ 混为一谈。
+#[derive(Debug, Clone)]
+pub struct GrantInjection(pub InstanceUpperBound);
+
+/// 与 SDK 判权中间件同一取法(`unified_ac_middleware.rs:496` 亦为 `usize::MAX`):
+/// 本层只在其之后多一次内存拷贝,不引入新的上限口径。
+const MAX_BODY: usize = usize::MAX;
+
+/// 从请求体根级读出网关注入的授权上界,写入请求扩展后原样转发(⛔ 改写请求体)。
+///
+/// 挂载位置:`main.rs` 里 AC 两层的**内侧**、紧接路由——`unified_ac_middleware` 会把请求体
+/// 缓冲重发,本层必须在其之后才能读到体。
+pub async fn grant_inject_middleware(req: Request, next: Next) -> Response {
+    // 只有带体的方法才可能有注入(网关侧同样只认 application/json 请求体,见影响清单 G-1)。
+    if !matches!(*req.method(), Method::POST | Method::PUT | Method::PATCH)
+        || !is_json(req.headers())
+    {
+        return next.run(req).await;
+    }
+    let (mut parts, body) = req.into_parts();
+    let bytes = match to_bytes(body, MAX_BODY).await {
+        Ok(b) => b,
+        // 读体失败 ⇒ 不写扩展(=未注入),错误留给下游 `DataBody` 如实报 400。
+        Err(_) => return next.run(Request::from_parts(parts, Body::empty())).await,
+    };
+    match parse_injection(&bytes) {
+        Some(bound) => {
+            parts.extensions.insert(GrantInjection(bound));
+        }
+        None if bytes_contains_injection_key(&bytes) => {
+            // 注入了但形状不认识 ⇒ 失败关闭成「上界为零」,并留 warn 便于区分口径。
+            tracing::warn!(
+                "通道②:网关注入的授权上界形状不认识(键={GRANTED_RESOURCE_GRANT_KEY}/{GRANTED_RESOURCE_INSTANCES_KEY}),按 Empty 失败关闭"
+            );
+            parts
+                .extensions
+                .insert(GrantInjection(InstanceUpperBound::Empty));
+        }
+        // 根级无注入键 ⇒ 不写扩展(`grant_bound`=None=未注入)。
+        None => {}
+    }
+    next.run(Request::from_parts(parts, Body::from(bytes)))
+        .await
+}
+
+fn is_json(headers: &HeaderMap) -> bool {
+    headers
+        .get(axum::http::header::CONTENT_TYPE)
+        .and_then(|v| v.to_str().ok())
+        .is_some_and(|v| v.contains("application/json"))
+}
+
+/// 注入键探针(避免对每个正常列表请求做完整 JSON 解析)。
+fn bytes_contains_injection_key(bytes: &[u8]) -> bool {
+    let s = match std::str::from_utf8(bytes) {
+        Ok(s) => s,
+        Err(_) => return false,
+    };
+    s.contains(GRANTED_RESOURCE_GRANT_KEY) || s.contains(GRANTED_RESOURCE_INSTANCES_KEY)
+}
+
+/// 根级两键任一存在即走 SDK `resolve_upper_bound`(同一份口径:结构化 grant 优先,
+/// 扁平数组=旧版 AC 形态,`["*"]`=不限)。返回 `None`=根级确无注入键;
+/// 形状不认识(scope 非 all/ids/rules、扁平位不是字符串数组)⇒ 解析失败,由调用方失败关闭。
+fn parse_injection(bytes: &[u8]) -> Option<InstanceUpperBound> {
+    let root: Value = serde_json::from_slice(bytes).ok()?;
+    let obj = root.as_object()?;
+    let flat = obj.get(GRANTED_RESOURCE_INSTANCES_KEY);
+    let grant = obj.get(GRANTED_RESOURCE_GRANT_KEY);
+    if flat.is_none() && grant.is_none() {
+        return None;
+    }
+    let flat: Option<Vec<String>> = match flat {
+        Some(v) => Some(serde_json::from_value(v.clone()).ok()?),
+        None => None,
+    };
+    let grant: Option<GrantedResourceGrant> = match grant {
+        Some(v) => Some(serde_json::from_value(v.clone()).ok()?),
+        None => None,
+    };
+    Some(resolve_upper_bound(flat.as_deref(), grant.as_ref()))
+}
+
+/// [`InstanceUpperBound`] → 消费方可直接按精确 id 判定的集合(口径见
+/// `bos_scope::AuthContext::granted_resource_instances` 字段注释)。
+///
+/// **只有 `Exact` 才投影成非空集合**,其余三形态一律空集(=消费方维持 2026-11-08 之前的行为,
+/// 失败关闭/回落本地 `bos_data_scope`),逐条理由:
+/// * `Unrestricted` ⇒ ⛔ 把 `*` 之类哨兵塞进 id 集合(消费方会把它当一枚真实实例 id 拼进
+///   `= ANY(...)`/祖先链比对),「不限」这一口径只经 `grant_bound` 表达;
+/// * `Empty` ⇒ 确已下发且上界为零,空集=拒绝(与「未注入」的区分同样只看 `grant_bound`);
+/// * `Rules` ⇒ 上界是**锚点**,语义=「锚点子树减去 deny」,需消费方沿 RM 父链自行展开
+///   (SDK 注释同口径)。把锚点当精确实例塞进来会两头错配:
+///   `visible_region_node_ids`(region.rs:181)会把它当节点 id 直接过滤 ⇒ 已授权的子孙**反而少**
+///   (比现状回落本地 `bos_data_scope` 更差),而 `ops_main_bound`(partner.rs:172)按祖先链比对
+///   又正好需要锚点 ⇒ 同一份集合无法同时正确服务两者。⇒ 本轮⛔ 投影,`Rules` 完整留在
+///   `grant_bound` 里,待业主确认「按 RM 祖先链展开」口径后由各消费方按自身语义接入(影响清单 L-3)。
+pub fn usable_instance_ids(bound: &InstanceUpperBound) -> HashSet<String> {
+    match bound {
+        InstanceUpperBound::Exact(ids) => ids.iter().cloned().collect(),
+        InstanceUpperBound::Unrestricted
+        | InstanceUpperBound::Empty
+        | InstanceUpperBound::Rules(_) => HashSet::new(),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn inject(json: &str) -> Option<InstanceUpperBound> {
+        parse_injection(json.as_bytes())
+    }
+
+    #[test]
+    fn no_injection_key_means_not_injected() {
+        assert!(inject(r#"{"data":{"page":1}}"#).is_none());
+        // 空体/非 JSON(GET、表单)⇒ 同样「未注入」,失败关闭交给消费方
+        assert!(inject("").is_none());
+        assert!(inject("not json").is_none());
+    }
+
+    #[test]
+    fn grant_all_is_unrestricted_but_yields_no_exact_ids() {
+        let b = inject(r#"{"data":{},"__granted_resource_grant":{"scope":"all"}}"#).unwrap();
+        assert_eq!(b, InstanceUpperBound::Unrestricted);
+        assert!(usable_instance_ids(&b).is_empty());
+    }
+
+    #[test]
+    fn ids_scope_and_flat_array_share_the_exact_set() {
+        let b = inject(r#"{"__granted_resource_grant":{"scope":"ids","ids":["320000","320100"]}}"#)
+            .unwrap();
+        let ids: HashSet<String> = ["320000".to_string(), "320100".to_string()]
+            .into_iter()
+            .collect();
+        assert_eq!(usable_instance_ids(&b), ids);
+        // 只有扁平位在场(旧版 AC 形态)时同由 resolve_upper_bound 解析;`*`=不限
+        let f = inject(r#"{"__granted_resource_instances":["320000","320100"]}"#).unwrap();
+        assert_eq!(usable_instance_ids(&f), ids);
+        assert_eq!(
+            inject(r#"{"__granted_resource_instances":["*"]}"#).unwrap(),
+            InstanceUpperBound::Unrestricted
+        );
+    }
+
+    #[test]
+    fn rules_shape_is_kept_in_bound_but_not_projected_to_exact_ids() {
+        let b = inject(
+            r#"{"__granted_resource_grant":{"scope":"rules",
+                "ids":["320100"],"ancestor_ids":["320000","330000"],
+                "deny_ids":["320105"],"deny_ancestor_ids":["330100"]}}"#,
+        )
+        .unwrap();
+        // 锚点语义需沿 RM 父链展开 ⇒ 本轮⛔ 投影为精确实例集(消费方回落本地口径/拒绝=失败关闭),
+        // 但完整上界留在 grant_bound 里,页面可如实区分口径。
+        assert!(usable_instance_ids(&b).is_empty());
+        match b {
+            InstanceUpperBound::Rules(r) => {
+                assert_eq!(
+                    r.allow_anchors,
+                    vec!["320000".to_string(), "330000".to_string()]
+                );
+                assert_eq!(r.deny_anchors, vec!["330100".to_string()]);
+            }
+            other => panic!("rules 形态应原样保留,实际={other:?}"),
+        }
+    }
+
+    #[test]
+    fn unknown_shape_fails_closed_and_stays_distinguishable() {
+        // scope 非 all/ids/rules ⇒ SDK 反序列化失败 ⇒ None(探针会把它记成 Empty)
+        assert!(inject(r#"{"__granted_resource_grant":{"scope":"everything"}}"#).is_none());
+        assert!(bytes_contains_injection_key(
+            br#"{"__granted_resource_grant":{"scope":"everything"}}"#
+        ));
+        // 空数组=确已注入且上界为零(与「未注入」不同口径)
+        let b = inject(r#"{"__granted_resource_grant":{"scope":"ids","ids":[]}}"#).unwrap();
+        assert_eq!(b, InstanceUpperBound::Empty);
+    }
+}

+ 4 - 0
src/crates/bos-api/src/lib.rs

@@ -2,9 +2,13 @@
 
 pub mod auth;
 pub mod extract;
+pub mod grant;
 pub mod middleware;
 pub mod state;
+pub mod trace;
 
 pub use auth::load_binding;
 pub use extract::{DataBody, OptionalAuth, RequireAuth};
+pub use grant::{grant_inject_middleware, GrantInjection};
 pub use state::AppState;
+pub use trace::{ac_done_middleware, request_trace_middleware};

+ 10 - 3
src/crates/bos-api/src/state.rs

@@ -1,13 +1,20 @@
-use bos_platform::clients::PlatformClient;
+use bos_platform::clients::{uds::UdsClient, PlatformClient};
 use bos_scope::DbScopedSelect;
-use sqlx::PgPool;
 use std::sync::Arc;
 
 #[derive(Clone)]
 pub struct AppState {
-    pub pool: PgPool,
+    /// 数据出入口:一律经 SEOH UDS,⛔ 自持数据库凭据直连。
+    pub db: Arc<UdsClient>,
     pub platform: Arc<PlatformClient>,
     pub scope: Arc<DbScopedSelect>,
     pub bos_env: String,
     pub service_name: String,
+    /// 本项目的项目空间 ID = 平台 `scope_type='end_user'` 的 `scope_id`。
+    /// 建号类接口(`iam-user/user/create@v1`)必须自带作用域三元组,平台侧
+    /// `ensure_end_user_env_stage` 缺一即 `11103` ⇒ BOS 无从由 JWT 之外的途径取得。
+    pub project_id: String,
+    /// 数据面环境二元组(`nonprod|prod` + `dev|test|prod`),与 UDS 取数同一口径。
+    pub data_env: String,
+    pub seoh_env: String,
 }

+ 95 - 0
src/crates/bos-api/src/trace.rs

@@ -0,0 +1,95 @@
+//! 请求链路中间件:`X-Request-Id` 贯穿+三段耗时+请求日志。
+//!
+//! 平台《外部项目服务接入约束》§10「可观测最低要求」=日志含 `request.id`/路由/状态码/耗时,
+//! 且 `ac_ms`/`uds_ms`/`self_ms` 分开记录;讨论稿 **K12** ② 明确「本项目全程携带
+//! `X-Request-Id`」,§8.3 红线把「自己生成 `X-Request-Id`」列为线上事故成因,故:
+//!
+//! * 入口**优先复用**上游带来的 `X-Request-Id`,只有确实没有(本机直连、脚本探针)才新建;
+//! * 新建时不覆盖上游值,⛔ 一次请求出现两个 id;
+//! * 同一个 id 由 [`bos_core::trace`] 的 task-local 带到 UDS/平台网关的出站请求上;
+//! * 响应头回写 `X-Request-Id`,便于前端/网关对账。
+
+use axum::{
+    extract::Request,
+    http::{HeaderMap, HeaderValue, Method},
+    middleware::Next,
+    response::Response,
+};
+use bos_core::trace::{RequestTrace, REQUEST_ID_HEADER};
+use std::sync::atomic::Ordering;
+use std::sync::Arc;
+
+/// 上游 id 长度上限:异常长的头不进日志,也⛔ 原样回写/转发。
+const MAX_ID_LEN: usize = 128;
+
+/// 最外层中间件:建立链路上下文、记请求日志、回写响应头。
+pub async fn request_trace_middleware(req: Request, next: Next) -> Response {
+    let inbound = req
+        .headers()
+        .get(REQUEST_ID_HEADER)
+        .and_then(|v| v.to_str().ok())
+        .map(|s| s.trim().to_string())
+        .filter(|s| !s.is_empty() && s.len() <= MAX_ID_LEN);
+    let (request_id, inherited) = match inbound {
+        Some(id) => (id, true),
+        None => (uuid::Uuid::new_v4().simple().to_string(), false),
+    };
+    let trace = Arc::new(RequestTrace::new(request_id));
+    let method = req.method().clone();
+    let route = req.uri().path().to_string();
+
+    let mut res = bos_core::trace::trace_scope(trace.clone(), async move { next.run(req).await }).await;
+
+    let total_ms = trace.started_at.elapsed().as_millis() as u64;
+    let ac_ms = trace.ac_ms.load(Ordering::Relaxed);
+    let ac_measured = trace.ac_measured.load(Ordering::Relaxed);
+    let uds_ms = trace.uds_ms.load(Ordering::Relaxed);
+    let uds_calls = trace.uds_calls.load(Ordering::Relaxed);
+    let self_ms = total_ms.saturating_sub(ac_ms).saturating_sub(uds_ms);
+    if method != Method::OPTIONS {
+        // `request.id` 是平台侧日志检索字段名(K12),⛔ 改名。
+        tracing::info!(
+            request.id = %trace.request_id,
+            request.inherited = inherited,
+            route = %route,
+            method = %method,
+            status = res.status().as_u16(),
+            total_ms,
+            ac_ms,
+            ac_measured,
+            uds_ms,
+            uds_calls,
+            self_ms,
+            "请求完成"
+        );
+        if uds_calls > 3 {
+            tracing::warn!(
+                request.id = %trace.request_id,
+                route = %route,
+                uds_calls,
+                "单请求 UDS 往返超过 3 次(讨论稿 §8.2 性能红线),需改批量或下推聚合"
+            );
+        }
+    }
+    push_request_id(res.headers_mut(), &trace.request_id);
+    res
+}
+
+/// AC 之后的内层中间件:给 `ac_ms` 打点(=进入本服务到 AC 判权结束的耗时)。
+///
+/// 必须挂在 `unified_ac_middleware` **内侧**、紧接路由,否则测不到 AC 往返。
+pub async fn ac_done_middleware(req: Request, next: Next) -> Response {
+    if let Some(trace) = bos_core::trace::current_trace() {
+        trace
+            .ac_ms
+            .store(trace.started_at.elapsed().as_millis() as u64, Ordering::Relaxed);
+        trace.ac_measured.store(true, Ordering::Relaxed);
+    }
+    next.run(req).await
+}
+
+fn push_request_id(headers: &mut HeaderMap, id: &str) {
+    if let Ok(v) = HeaderValue::from_str(id) {
+        headers.insert(REQUEST_ID_HEADER, v);
+    }
+}

+ 1 - 0
src/crates/bos-core/Cargo.toml

@@ -11,4 +11,5 @@ chrono = { workspace = true }
 chrono-tz = { workspace = true }
 uuid = { workspace = true }
 sqlx = { workspace = true }
+tokio = { workspace = true }
 tracing = { workspace = true }

+ 302 - 35
src/crates/bos-core/src/error.rs

@@ -4,38 +4,78 @@ use thiserror::Error;
 /// 平台通用成功码。
 pub const CODE_OK: i64 = 10000;
 
-/// BOS 业务数字码段 20000–20999;对外稳定契约仍用 `KLT-*`。
+/// 成功码沿用平台统一值,⛔ 不属本服务业务码段(总则§9.2「10000 成功」)。
+///
+/// ⚠️ 本服务**产出**的业务数字码必须全部落在被分配段 `60000`–`60999` 内
+/// (平台侧口径=开发指南 §7.2:`info.x-error-code-range` 必填且值域须为被分配段位)。
+/// ⚠️ **段位第二次平移(业主 2026-11-07 转述平台新口径)**:`60000` 以前平台已保留,
+/// 本服务被分配段由 `20000`–`20999` 改为 `60000`–`60999`,段内**整体 +40000**、
+/// 块结构与段内顺位⛔ 变;⚠️ 这是继 2026-10-30 `14xxx → 20xxx` 之后**第二次对外契约破坏性平移**。
+/// ⚠️ **`KLT-*` 字符串⛔ 随段位改名**(它是对外稳定契约,见总则§9.1)⇒ 自本次起**字符串内嵌的数字
+/// 与实际 `code` 脱钩**(如 `KLT-S20004` 的 `code` 是 `60004`),⛔ 再按字符串内数字反推码值。
+/// ✅ **唯一在册例外=鉴权失败类**(`Unauthorized`/`Forbidden`):业主 2026-11-07 裁定
+/// **⛔ 收段、原样透传平台原码 `11000`/`11001`**(含平台 SDK 鉴权闸门在本进程内产出的响应),
+/// 业务侧⛔ 改写 ⇒ 这两枚码**故意**落在被分配段之外,登记见总则§9.2/§18.3。
+/// 其余平台通用码(`11100`/`11103`/`11104`/`10110`)仍收进本服务段,平台原码在
+/// `message` 原文里逐字保留。
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub enum ErrorCode {
     Ok,
     /// 通用冲突(条件更新零行 / 唯一索引)
     ConflictS407,
+    /// 未认证:缺 AC 判权上下文/令牌无效
     Unauthorized,
+    /// 无权限:身份类别或授权层拦下(⛔ 与角色层 `KLT-P301` 混用)
     Forbidden,
     ForbiddenRole,
     BadParams,
     NotFound,
+    /// 下游平台依赖失败(平台原码进 `message`)
     Downstream,
     Internal,
+    /// 功能未实现(桩面,⛔ 与「内部错误」合并)
+    NotImplemented,
     /// 业务码(按册块预留;具体文案由 KltCode)
     Business(i64),
 }
 
 impl ErrorCode {
+    /// 本服务产出的数字码:除成功码 `10000` 外落在 `60000`–`60999`,
+    /// ⚠️ 唯一例外=鉴权失败类透传 `11000`/`11001`(见本文件头与 [`鉴权失败类透传平台原码`])。
     pub fn as_i64(self) -> i64 {
         match self {
             Self::Ok => CODE_OK,
-            Self::ConflictS407 => 20001,
+            Self::ConflictS407 => 60001,
+            // ⚠️ 业主 2026-11-07 裁定=**鉴权失败类⛔ 收段,原样透传平台原码** `11000`/`11001`
+            // (与平台 SDK 鉴权闸门在本进程内产出的响应同构),业务侧⛔ 改写。
+            // 本服务被分配段以外的这两枚码是**在册例外**,登记见总则§9.2/§18.3。
             Self::Unauthorized => 11000,
             Self::Forbidden => 11001,
-            Self::ForbiddenRole => 20010, // KLT-P301
-            Self::BadParams => 11103,
-            Self::NotFound => 11104,
-            Self::Downstream => 10110,
-            Self::Internal => 11100,
+            Self::ForbiddenRole => 60058, // KLT-P301
+            Self::BadParams => 60004,
+            Self::NotFound => 60005,
+            Self::Downstream => 60006,
+            Self::Internal => 60007,
+            Self::NotImplemented => 60008,
             Self::Business(n) => n,
         }
     }
+
+    /// 通用码的对外稳定字符串;`Business(n)` 的 `KLT-*` 由 [`KltCode`] 自带,故此处不给出。
+    pub fn klt(self) -> Option<&'static str> {
+        match self {
+            Self::Ok | Self::Business(_) => None,
+            Self::ConflictS407 => Some("KLT-S407"),
+            Self::Unauthorized => Some("KLT-S20002"),
+            Self::Forbidden => Some("KLT-S20003"),
+            Self::ForbiddenRole => Some("KLT-P301"),
+            Self::BadParams => Some("KLT-S20004"),
+            Self::NotFound => Some("KLT-S20005"),
+            Self::Downstream => Some("KLT-S20006"),
+            Self::Internal => Some("KLT-S20007"),
+            Self::NotImplemented => Some("KLT-S20008"),
+        }
+    }
 }
 
 /// 对外稳定错误码字符串。
@@ -44,6 +84,20 @@ impl ErrorCode {
 pub enum KltCode {
     #[serde(rename = "KLT-S407")]
     S407,
+    #[serde(rename = "KLT-S20002")]
+    S20002,
+    #[serde(rename = "KLT-S20003")]
+    S20003,
+    #[serde(rename = "KLT-S20004")]
+    S20004,
+    #[serde(rename = "KLT-S20005")]
+    S20005,
+    #[serde(rename = "KLT-S20006")]
+    S20006,
+    #[serde(rename = "KLT-S20007")]
+    S20007,
+    #[serde(rename = "KLT-S20008")]
+    S20008,
     #[serde(rename = "KLT-P301")]
     P301,
     #[serde(rename = "KLT-B001")]
@@ -52,6 +106,12 @@ pub enum KltCode {
     B002,
     #[serde(rename = "KLT-B003")]
     B003,
+    /// 账号未设密(组织§4.1 首次业务请求拦截,响应带 `redirect=激活页`)
+    #[serde(rename = "KLT-A001")]
+    A001,
+    /// 激活凭证已过期(未设密且 `expire_date` < today)
+    #[serde(rename = "KLT-A002")]
+    A002,
     #[serde(rename = "KLT-A003")]
     A003,
     #[serde(rename = "KLT-R101")]
@@ -66,6 +126,15 @@ pub enum KltCode {
     R105,
     #[serde(rename = "KLT-T201")]
     T201,
+    /// 激活码不正确或已被使用(组织§4.3 逐位比对/一码一用)
+    #[serde(rename = "KLT-T221")]
+    T221,
+    /// 操作过于频繁(激活与登录限流,⛔ 不锁定账号)
+    #[serde(rename = "KLT-T222")]
+    T222,
+    /// 新密码不能与原密码相同(AC-05)
+    #[serde(rename = "KLT-T223")]
+    T223,
     #[serde(rename = "KLT-T224")]
     T224,
     #[serde(rename = "KLT-T225")]
@@ -88,51 +157,93 @@ pub enum KltCode {
     S403,
     #[serde(rename = "KLT-S404")]
     S404,
+    #[serde(rename = "KLT-D002")]
+    D002,
+    #[serde(rename = "KLT-D003")]
+    D003,
+    #[serde(rename = "KLT-D004")]
+    D004,
+    #[serde(rename = "KLT-D005")]
+    D005,
 }
 
 impl KltCode {
+    /// ⚠️ 数字码唯一真源=总则§9.5.1(旧段对照)+各册§7.1 明细+总则§9.5「新发号」行;
+    /// 三位序号(`S407`/`R101`…)**不等于**数字码尾三位,⛔ 按尾三位反推。
     pub fn numeric(self) -> i64 {
         match self {
-            Self::S407 => 20001,
-            Self::P301 => 20010,
-            Self::B001 => 20020,
-            Self::B002 => 20021,
-            Self::B003 => 20022,
-            Self::A003 => 20030,
-            Self::R101 => 20040,
-            Self::R102 => 20041,
-            Self::R103 => 20042,
-            Self::R104 => 20043,
-            Self::R105 => 20044,
-            Self::T201 => 20050,
-            Self::T224 => 20051,
-            Self::T225 => 20052,
-            Self::C001 => 20060,
-            Self::C008 => 20061,
-            Self::I101 => 20078,
-            Self::I102 => 20079,
-            Self::I105 => 20082,
-            Self::S401 => 20101,
-            Self::S402 => 20102,
-            Self::S403 => 20103,
-            Self::S404 => 20104,
+            Self::S407 => 60001,
+            Self::S20002 => 11000,
+            Self::S20003 => 11001,
+            Self::S20004 => 60004,
+            Self::S20005 => 60005,
+            Self::S20006 => 60006,
+            Self::S20007 => 60007,
+            Self::S20008 => 60008,
+            Self::P301 => 60058,
+            Self::B001 => 60053,
+            Self::B002 => 60054,
+            Self::B003 => 60055,
+            Self::A001 => 60051,
+            Self::A002 => 60052,
+            Self::A003 => 60088,
+            Self::R101 => 60059,
+            Self::R102 => 60060,
+            Self::R103 => 60061,
+            Self::R104 => 60062,
+            Self::R105 => 60063,
+            Self::S401 => 60064,
+            Self::S402 => 60065,
+            Self::S403 => 60066,
+            Self::S404 => 60067,
+            Self::T201 => 60068,
+            Self::T221 => 60075,
+            Self::T222 => 60076,
+            Self::T223 => 60077,
+            Self::T224 => 60089,
+            Self::T225 => 60090,
+            Self::C001 => 60056,
+            Self::C008 => 60117,
+            Self::I101 => 60078,
+            Self::I102 => 60079,
+            Self::I105 => 60082,
+            Self::D002 => 60111,
+            Self::D003 => 60112,
+            Self::D004 => 60113,
+            Self::D005 => 60114,
         }
     }
 
     pub fn as_str(self) -> &'static str {
         match self {
             Self::S407 => "KLT-S407",
+            Self::S20002 => "KLT-S20002",
+            Self::S20003 => "KLT-S20003",
+            Self::S20004 => "KLT-S20004",
+            Self::S20005 => "KLT-S20005",
+            Self::S20006 => "KLT-S20006",
+            Self::S20007 => "KLT-S20007",
+            Self::S20008 => "KLT-S20008",
             Self::P301 => "KLT-P301",
             Self::B001 => "KLT-B001",
             Self::B002 => "KLT-B002",
             Self::B003 => "KLT-B003",
+            Self::A001 => "KLT-A001",
+            Self::A002 => "KLT-A002",
             Self::A003 => "KLT-A003",
             Self::R101 => "KLT-R101",
             Self::R102 => "KLT-R102",
             Self::R103 => "KLT-R103",
             Self::R104 => "KLT-R104",
             Self::R105 => "KLT-R105",
+            Self::S401 => "KLT-S401",
+            Self::S402 => "KLT-S402",
+            Self::S403 => "KLT-S403",
+            Self::S404 => "KLT-S404",
             Self::T201 => "KLT-T201",
+            Self::T221 => "KLT-T221",
+            Self::T222 => "KLT-T222",
+            Self::T223 => "KLT-T223",
             Self::T224 => "KLT-T224",
             Self::T225 => "KLT-T225",
             Self::C001 => "KLT-C001",
@@ -140,10 +251,10 @@ impl KltCode {
             Self::I101 => "KLT-I101",
             Self::I102 => "KLT-I102",
             Self::I105 => "KLT-I105",
-            Self::S401 => "KLT-S401",
-            Self::S402 => "KLT-S402",
-            Self::S403 => "KLT-S403",
-            Self::S404 => "KLT-S404",
+            Self::D002 => "KLT-D002",
+            Self::D003 => "KLT-D003",
+            Self::D004 => "KLT-D004",
+            Self::D005 => "KLT-D005",
         }
     }
 }
@@ -164,7 +275,7 @@ impl BosError {
     pub fn biz(code: ErrorCode, message: impl Into<String>) -> Self {
         Self::Biz {
             code: code.as_i64(),
-            error_code: None,
+            error_code: code.klt(),
             message: message.into(),
         }
     }
@@ -192,4 +303,160 @@ impl BosError {
     pub fn internal(message: impl Into<String>) -> Self {
         Self::biz(ErrorCode::Internal, message)
     }
+
+    /// 「功能未实现/不支持」——⛔ 与 [`BosError::internal`] 混用(两者出路相反:
+    /// 一个是系统故障需排障,一个是功能尚未交付/按设计不支持)。
+    pub fn not_implemented(message: impl Into<String>) -> Self {
+        Self::biz(ErrorCode::NotImplemented, message)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// 本服务被平台分配的段位(开发指南 §7.2:`info.x-error-code-range`)。
+    /// ⚠️ 2026-11-07 平台新口径=`60000` 以前平台已保留 ⇒ 本段由 `20000`–`20999`
+    /// 整体 +40000 平移而来(块结构与段内顺位⛔ 变)。
+    const RANGE: (i64, i64) = (60_000, 60_999);
+
+    /// ✅ **鉴权失败类透传例外**(业主 2026-11-07 裁定):`KLT-S20002`/`KLT-S20003`
+    /// ⛔ 收段,恒等透传平台原码 `11000`/`11001`(含平台 SDK 鉴权闸门在本进程内
+    /// 产出的响应),业务侧⛔ 改写 ⇒ 这两枚**故意**落在被分配段之外,
+    /// ⛔ 参与"必须落段"与"⛔ 占整十位码位"两条守卫,由 [`鉴权失败类透传平台原码`] 单独守卫。
+    const AUTH_PASSTHROUGH: &[KltCode] = &[KltCode::S20002, KltCode::S20003];
+
+    /// `AUTH_PASSTHROUGH` 在 `ErrorCode` 侧的对应变体(同一对外语义)。
+    const AUTH_PASSTHROUGH_ERRORS: &[ErrorCode] = &[ErrorCode::Unauthorized, ErrorCode::Forbidden];
+
+    const ALL_KLT: &[KltCode] = &[
+        KltCode::S407, KltCode::S20002, KltCode::S20003, KltCode::S20004, KltCode::S20005,
+        KltCode::S20006, KltCode::S20007, KltCode::S20008, KltCode::P301, KltCode::B001,
+        KltCode::B002, KltCode::B003, KltCode::A001, KltCode::A002, KltCode::A003, KltCode::R101,
+        KltCode::R102, KltCode::R103, KltCode::R104, KltCode::R105, KltCode::T201, KltCode::T221,
+        KltCode::T222, KltCode::T223, KltCode::T224, KltCode::T225, KltCode::C001, KltCode::C008,
+        KltCode::I101, KltCode::I102, KltCode::I105, KltCode::D002, KltCode::D003, KltCode::D004,
+        KltCode::D005,
+    ];
+
+    const ALL_GENERIC: &[ErrorCode] = &[
+        ErrorCode::ConflictS407,
+        ErrorCode::Unauthorized,
+        ErrorCode::Forbidden,
+        ErrorCode::ForbiddenRole,
+        ErrorCode::BadParams,
+        ErrorCode::NotFound,
+        ErrorCode::Downstream,
+        ErrorCode::Internal,
+        ErrorCode::NotImplemented,
+    ];
+
+    /// 守卫:本服务产出的数字码⛔ 越段(越段=平台注册侧判契约不合规)。
+    #[test]
+    fn 产出的数字码必须落在被分配段() {
+        for c in ALL_KLT {
+            if AUTH_PASSTHROUGH.contains(c) {
+                continue; // ✅ 鉴权类透传平台原码,⛔ 落段(业主 2026-11-07 裁定)
+            }
+            let n = c.numeric();
+            assert!(
+                (RANGE.0..=RANGE.1).contains(&n),
+                "{:?} 的数字码 {} 越出 {}-{}",
+                c.as_str(),
+                n,
+                RANGE.0,
+                RANGE.1
+            );
+        }
+        for c in ALL_GENERIC {
+            if AUTH_PASSTHROUGH_ERRORS.contains(c) {
+                continue; // ✅ 同上
+            }
+            let n = c.as_i64();
+            assert!(
+                (RANGE.0..=RANGE.1).contains(&n),
+                "{:?} 的数字码 {} 越出 {}-{}",
+                c,
+                n,
+                RANGE.0,
+                RANGE.1
+            );
+        }
+        assert_eq!(ErrorCode::Ok.as_i64(), CODE_OK);
+    }
+
+    /// 守卫:`x00` 整十位不入编号空间(总则§2.2 错误码段位行)。
+    #[test]
+    fn 不得占用整十位码位() {
+        for c in ALL_KLT {
+            if AUTH_PASSTHROUGH.contains(c) {
+                continue; // ⚠️ 透传的 `11000` 本身是整十位,属平台码、⛔ 受本纪律约束
+            }
+            assert_ne!(c.numeric() % 100, 0, "{} 取了 x00 码位", c.as_str());
+        }
+        for c in ALL_GENERIC {
+            if AUTH_PASSTHROUGH_ERRORS.contains(c) {
+                continue;
+            }
+            assert_ne!(c.as_i64() % 100, 0, "{:?} 取了 x00 码位", c);
+        }
+    }
+
+    /// 守卫:**鉴权失败类恒等透传平台原码**(业主 2026-11-07 裁定=业务侧⛔ 改写,
+    /// 含平台 SDK 鉴权闸门在本进程内产出的响应)。⚠️ 改动这两枚=违约。
+    #[test]
+    fn 鉴权失败类透传平台原码() {
+        assert_eq!(ErrorCode::Unauthorized.as_i64(), 11000);
+        assert_eq!(ErrorCode::Forbidden.as_i64(), 11001);
+        assert_eq!(KltCode::S20002.numeric(), 11000);
+        assert_eq!(KltCode::S20003.numeric(), 11001);
+        // ⚠️ `KLT-*` 字符串⛔ 随段位改名(对外稳定契约),故字符串内嵌数字与实际 code 脱钩。
+        assert_eq!(KltCode::S20002.as_str(), "KLT-S20002");
+        assert_eq!(KltCode::S20003.as_str(), "KLT-S20003");
+    }
+
+    /// 守卫:一枚数字码只指一个 `KLT-*`(总则§2.2「一条编号只对应一个对象」)。
+    #[test]
+    fn 数字码不得一号两义() {
+        let mut seen = std::collections::BTreeMap::new();
+        for c in ALL_KLT {
+            if let Some(prev) = seen.insert(c.numeric(), c.as_str()) {
+                panic!("{} 与 {} 共用数字码 {}", prev, c.as_str(), c.numeric());
+            }
+        }
+        // 通用码与业务码同属一张表,⛔ 撞号。
+        for c in ALL_GENERIC {
+            let n = c.as_i64();
+            match c.klt() {
+                Some(s) if ALL_KLT.iter().any(|k| k.as_str() == s) => {
+                    assert!(
+                        ALL_KLT.iter().all(|k| k.as_str() != s || k.numeric() == n),
+                        "{} 的通用号 {} 与业务号不一致",
+                        s,
+                        n
+                    );
+                }
+                _ => assert!(!seen.contains_key(&n), "通用码 {:?} 的 {} 与业务码撞号", c, n),
+            }
+        }
+    }
+
+    /// 守卫:`as_str()` 与 `serde` 序列化出的 `error_code` 必须逐字相同。
+    #[test]
+    fn 序列化字符串与as_str一致() {
+        for c in ALL_KLT {
+            let s = serde_json::to_string(&c).unwrap();
+            assert_eq!(s, format!("\"{}\"", c.as_str()));
+        }
+    }
+
+    /// 守卫:通用码必须带得出 `error_code` 字符串(对外只暴露 `KLT-*`)。
+    #[test]
+    fn 通用码必须带稳定字符串() {
+        for c in ALL_GENERIC {
+            assert!(c.klt().is_some(), "{:?} 缺 error_code 字符串", c);
+        }
+        assert!(ErrorCode::Ok.klt().is_none());
+        assert!(ErrorCode::Business(60051).klt().is_none());
+    }
 }

+ 1 - 0
src/crates/bos-core/src/lib.rs

@@ -6,6 +6,7 @@ pub mod page;
 pub mod response;
 pub mod roles;
 pub mod time;
+pub mod trace;
 
 pub use error::{BosError, ErrorCode, KltCode};
 pub use money::Cents;

+ 2 - 2
src/crates/bos-core/src/response.rs

@@ -44,9 +44,9 @@ impl<T: Serialize> ApiResponse<T> {
                 data: None,
             },
             BosError::Other(e) => ApiResponse {
-                code: 11100,
+                code: crate::error::ErrorCode::Internal.as_i64(),
                 message: e.to_string(),
-                error_code: None,
+                error_code: crate::error::ErrorCode::Internal.klt(),
                 data: None,
             },
         }

+ 74 - 0
src/crates/bos-core/src/trace.rs

@@ -0,0 +1,74 @@
+//! 请求级链路上下文:`X-Request-Id` 贯穿+`ac_ms`/`uds_ms`/`self_ms` 埋点。
+//!
+//! 依据平台《外部项目服务接入约束》§8.3 红线与 §10「可观测最低要求」,及讨论稿 **K12**
+//! ②(本项目全程携带 `X-Request-Id`)+④(三段耗时分开记录)。
+//!
+//! 载体用 `tokio::task_local!`(⛔ `thread_local!`:一个请求的 future 会跨线程续跑,
+//! 线程本地会串号)。中间件在入口 `scope` 一次,本服务内任何出站调用(UDS/平台网关)
+//! 都取到同一个 `request_id`。
+
+use std::future::Future;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::Instant;
+
+/// 平台贯穿用的请求关联头(讨论稿 §7.4:网关注入,全链路同名)。
+pub const REQUEST_ID_HEADER: &str = "X-Request-Id";
+
+/// 单个请求的链路状态。
+#[derive(Debug)]
+pub struct RequestTrace {
+    pub request_id: String,
+    /// 进入本服务的时刻,`ac_ms` 以此为起点。
+    pub started_at: Instant,
+    /// AC 判权及其前置耗时(由 AC 之后的内层中间件打点)。
+    pub ac_ms: AtomicU64,
+    /// `ac_ms` 是否真取到样本:AC **判权拒绝**时响应由 AC 层直接返回,内层中间件不会执行,
+    /// 此时 `ac_ms` 恒 0 且 AC 往返会落进 `self_ms` ⇒ 用本标记区分「真的 0 ms」与「没测到」,
+    /// ⛔ 把判权拒绝的请求误判成业务代码慢。
+    pub ac_measured: AtomicBool,
+    /// UDS 出站累计耗时(一次请求可能多次往返)。
+    pub uds_ms: AtomicU64,
+    /// UDS 往返次数(讨论稿 §8.2:单请求超过 3 次往返要告警)。
+    pub uds_calls: AtomicU64,
+}
+
+impl RequestTrace {
+    pub fn new(request_id: impl Into<String>) -> Self {
+        Self {
+            request_id: request_id.into(),
+            started_at: Instant::now(),
+            ac_ms: AtomicU64::new(0),
+            ac_measured: AtomicBool::new(false),
+            uds_ms: AtomicU64::new(0),
+            uds_calls: AtomicU64::new(0),
+        }
+    }
+}
+
+tokio::task_local! {
+    static CURRENT_TRACE: Arc<RequestTrace>;
+}
+
+/// 把 `trace` 绑定到该 future 的执行范围(请求入口中间件用)。
+pub fn trace_scope<F: Future>(trace: Arc<RequestTrace>, fut: F) -> impl Future<Output = F::Output> {
+    CURRENT_TRACE.scope(trace, fut)
+}
+
+/// 当前请求的链路上下文;不在请求作用域内(启动期、后台作业)返回 `None`。
+pub fn current_trace() -> Option<Arc<RequestTrace>> {
+    CURRENT_TRACE.try_with(|t| t.clone()).ok()
+}
+
+/// 当前请求的 `X-Request-Id`(出站调用携带)。
+pub fn current_request_id() -> Option<String> {
+    current_trace().map(|t| t.request_id.clone())
+}
+
+/// 记一次 UDS 往返耗时(累计,⛔ 覆盖)。
+pub fn add_uds_ms(ms: u64) {
+    if let Some(t) = current_trace() {
+        t.uds_ms.fetch_add(ms, Ordering::Relaxed);
+        t.uds_calls.fetch_add(1, Ordering::Relaxed);
+    }
+}

+ 145 - 0
src/crates/bos-io/src/identity.rs

@@ -0,0 +1,145 @@
+//! 客户识别号归一化与格式校验(第 2 册 客户§3.4)。
+//!
+//! 第 2 册§3.4 三条纪律之第三条:**四处共用同一个函数**(手工建档、代录、导入逐行校验、
+//! 联通同步匹配),「任何一处自己写一份归一化,查重就会分叉」。因此本函数只此一份,
+//! 落在 `bos-io`(导入/导出公共层)供各域复用,⛔ 在 handler 内另写一份。
+//!
+//! ⚠️ 归一化之后的 `identity_no_hash = HMAC-SHA256(keybox 索引密钥, normalized)` 依赖平台
+//! 密钥通路,全仓尚无该通路(见 18 册),故本模块只交付「归一化 + 格式校验」两步,
+//! ⛔ 不自行发明哈希算法(自己算出的哈希与库内既有哈希必然分叉)。
+
+/// 归一化:去全部空白 → 全角转半角 → 字母统一大写(第 2 册§3.4 前三步)。
+pub fn norm_identity_no(raw: &str) -> String {
+    raw.chars()
+        .filter(|c| !c.is_whitespace())
+        .map(fullwidth_to_halfwidth)
+        .flat_map(|c| c.to_uppercase())
+        .collect()
+}
+
+/// 单个全角字符转半角(`U+FF01..=U+FF5E` → 码位减 `0xFEE0`);其余原样返回。
+fn fullwidth_to_halfwidth(c: char) -> char {
+    let cp = c as u32;
+    if (0xFF01..=0xFF5E).contains(&cp) {
+        char::from_u32(cp - 0xFEE0).unwrap_or(c)
+    } else {
+        c
+    }
+}
+
+/// 格式校验(归一化之后调用):企业=18 位且 GB32100 校验位重算通过;
+/// 个人/个体工商户=18 位且末位 ∈ `0-9X` 且出生日期段(第 7–14 位)为合法日期。
+///
+/// 返回 `false` 时调用方按§3.3 报错文本呈现(企业/个人均=「证件号格式不正确」)。
+pub fn is_valid_identity_no(normalized: &str, subject_type: &str) -> bool {
+    match subject_type {
+        "enterprise" => is_uscc(normalized),
+        "individual" | "sole_proprietor" => is_id_card(normalized),
+        _ => false,
+    }
+}
+
+/// GB32100 统一社会信用代码字符集(不含 I/O/S/Z/V,共 31 字符)。
+const USCC_CHARS: &[u8] = b"0123456789ABCDEFGHJKLMNPQRTUWXY";
+/// GB32100 前 17 位加权因子。
+const USCC_WEIGHTS: [u32; 17] = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
+
+fn is_uscc(s: &str) -> bool {
+    let b = s.as_bytes();
+    if b.len() != 18 {
+        return false;
+    }
+    let mut sum = 0u32;
+    for i in 0..17 {
+        let v = match USCC_CHARS.iter().position(|c| *c == b[i]) {
+            Some(v) => v as u32,
+            None => return false,
+        };
+        sum += v * USCC_WEIGHTS[i];
+    }
+    let check = (31 - sum % 31) % 31;
+    USCC_CHARS[check as usize] == b[17]
+}
+
+fn is_id_card(s: &str) -> bool {
+    let b = s.as_bytes();
+    if b.len() != 18 || !b[..17].iter().all(u8::is_ascii_digit) || !(b[17].is_ascii_digit() || b[17] == b'X')
+    {
+        return false;
+    }
+    let num = |a: usize, n: usize| s[a..a + n].parse::<i32>().ok();
+    let (Some(y), Some(m), Some(d)) = (num(6, 4), num(10, 2), num(12, 2)) else {
+        return false;
+    };
+    if !(1900..=2100).contains(&y) || !(1..=12).contains(&m) {
+        return false;
+    }
+    d >= 1 && d <= days_in_month(y, m)
+}
+
+fn days_in_month(y: i32, m: i32) -> i32 {
+    match m {
+        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
+        4 | 6 | 9 | 11 => 30,
+        2 => {
+            if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
+                29
+            } else {
+                28
+            }
+        }
+        _ => 0,
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn norm_strips_space_fullwidth_and_uppercases() {
+        assert_eq!(norm_identity_no(" 91310000MA1FL1AB7X "), "91310000MA1FL1AB7X");
+        // 全角数字/字母转半角并大写
+        assert_eq!(norm_identity_no("91310000MA1fl1ab7x"), "91310000MA1FL1AB7X");
+        assert_eq!(norm_identity_no("9131 0000"), "91310000");
+    }
+
+    #[test]
+    fn uscc_check_digit() {
+        // 构造一个校验位正确的码:先按前 17 位算出期望末位再断言通过
+        let head = "91310000MA1FL1AB7";
+        let mut sum = 0u32;
+        for i in 0..17 {
+            let v = USCC_CHARS.iter().position(|c| *c == head.as_bytes()[i]).unwrap() as u32;
+            sum += v * USCC_WEIGHTS[i];
+        }
+        let check = USCC_CHARS[((31 - sum % 31) % 31) as usize];
+        let code = format!("{head}{}", check as char);
+        assert!(is_uscc(&code), "自算校验位应通过:{code}");
+        let mut bad = code.clone();
+        bad.pop();
+        bad.push(if check == b'0' { '1' } else { '0' });
+        assert!(!is_uscc(&bad), "校验位改掉应不通过:{bad}");
+        assert!(!is_uscc("91310000MA1FL1AB7")); // 17 位
+        assert!(!is_uscc("91310000MA1FL1AB7XI")); // 19 位
+        assert!(!is_uscc("91310000MA1FL1AB7SI")); // 含禁用字符 S
+    }
+
+    #[test]
+    fn id_card_birth_segment() {
+        assert!(is_id_card("31010119900307432X"));
+        assert!(!is_id_card("31010119901307432X")); // 月份 13
+        assert!(!is_id_card("31010119900230432X")); // 2 月 30 日
+        assert!(is_id_card("31010120000229432X")); // 2000 闰年 2 月 29 日
+        assert!(!is_id_card("31010119990229432X")); // 1999 非闰年
+        assert!(!is_id_card("31010119900307432Y")); // 末位非 0-9X
+        assert!(!is_id_card("3101011990A307432X")); // 前 17 位含字母
+    }
+
+    #[test]
+    fn subject_type_out_of_range_fails() {
+        assert!(!is_valid_identity_no("31010119900307432X", "company"));
+        assert!(is_valid_identity_no("31010119900307432X", "individual"));
+        assert!(is_valid_identity_no("31010119900307432X", "sole_proprietor"));
+    }
+}

+ 2 - 0
src/crates/bos-io/src/lib.rs

@@ -1,7 +1,9 @@
 //! M2:导入流水线 + 谓词收窄导出。
 
 pub mod export;
+pub mod identity;
 pub mod import;
 
 pub use export::{ExportDataSource, ExportRequest};
+pub use identity::{is_valid_identity_no, norm_identity_no};
 pub use import::{assert_row_limit, ImportBatchStatus, ImportPipelineStage};

+ 15 - 5
src/crates/bos-platform/src/clients/activation.rs

@@ -3,13 +3,23 @@ use super::PlatformClient;
 use bos_core::BosError;
 
 impl PlatformClient {
-    pub async fn bootstrap_credential_create_batch(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/identity-provider/bootstrap_credential/create_batch@v1", json!({ "data": data })).await
+    /// 批量发放引导凭证:`issue_batch@v1`。
+    ///
+    /// ⚠️ 路由名真源=总则§8.3 `iam-user` 行的六条(`issue`/`issue_batch`/`get`/`get_list`/`revoke`/`export`),⛔ 无 `create_batch`。
+    /// ⚠️ `U-94` ①:本组路由=「双调用方」路由(除 `issue@v1` 外 `x-internal-callers` 为 `[]`)⇒ 只允许**经网关带 Bearer 用户令牌**调用,
+    /// ⛔ 不得用 `X-Internal-Token`/服务身份直连(一律 `11001`),故走 [`post_json_as_user`](super::PlatformClient::post_json_as_user)。
+    /// `user_token` =当前操作人的用户令牌。
+    pub async fn bootstrap_credential_issue_batch(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
+        self.post_json_as_user("/api/system/seoh-identity-provider/bootstrap_credential/issue_batch@v1", json!({ "data": data }), user_token)
+            .await
     }
-    pub async fn bootstrap_credential_export(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/identity-provider/bootstrap_credential/export@v1", json!({ "data": data })).await
+    /// 导出引导凭证明文:`export@v1`(鉴权身份=**Bearer 用户令牌+权限键**,⛔ 不是内部服务令牌,总则§8.3)。
+    /// ⚠️ 该权限键在我方**无合法持有主体**=`U-98`;未定前两个导出入口按「能力待定」降级呈现,⛔ 不得改用内部令牌。
+    pub async fn bootstrap_credential_export(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
+        self.post_json_as_user("/api/system/seoh-identity-provider/bootstrap_credential/export@v1", json!({ "data": data }), user_token)
+            .await
     }
     pub async fn user_set_password(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/iam-user/user/set_password@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-iam-user/user/set_password@v1", json!({ "data": data })).await
     }
 }

+ 5 - 3
src/crates/bos-platform/src/clients/iam.rs

@@ -4,12 +4,14 @@ use bos_core::BosError;
 
 impl PlatformClient {
     pub async fn user_create(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/iam-user/user/create@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-iam-user/user/create@v1", json!({ "data": data })).await
     }
     pub async fn user_get(&self, user_id: &str) -> Result<Value, BosError> {
-        self.post_json("/api/system/iam-user/user/get@v1", json!({ "data": { "user_id": user_id } })).await
+        self.post_json("/api/system/seoh-iam-user/user/get@v1", json!({ "data": { "user_id": user_id } })).await
     }
+    /// 身份↔角色绑定:真实路由=`seoh-iam-role/identity_role/bind@v1`
+    ///(真源=seoh-iam-role 服务路由表;⚠️ `iam-user-group/user_group_role/bind` 系虚构路径,平台无此接口)。
     pub async fn group_role_bind(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/iam-user-group/user_group_role/bind@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-iam-role/identity_role/bind@v1", json!({ "data": data })).await
     }
 }

+ 9 - 3
src/crates/bos-platform/src/clients/impexp.rs

@@ -3,10 +3,16 @@ use super::PlatformClient;
 use bos_core::BosError;
 
 impl PlatformClient {
-    pub async fn import_export_submit(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/import-export/task/submit@v1", json!({ "data": data })).await
+    /// 建导入/导出任务(通道侧真端点=`task/create@v1`)。
+    ///
+    /// ⚠️ 2026-11-08 网关日志实读更正:该服务只注册 `task/create`/`get`/`get_list`/
+    /// `pickup`/`report`/`cancel`/`purge_expired`/`upload_ticket`,**⛔ `task/submit@v1`**
+    /// ——旧写法每打一次必吃 `50000 未找到匹配路由`。
+    /// 出参 `source_file_name`(≤255,平台 D6 已交付)由调用方原样放进 `data`,通道只回显不解释。
+    pub async fn import_export_create(&self, data: Value) -> Result<Value, BosError> {
+        self.post_json("/api/system/seoh-import-export/task/create@v1", json!({ "data": data })).await
     }
     pub async fn import_export_get(&self, task_id: &str) -> Result<Value, BosError> {
-        self.post_json("/api/system/import-export/task/get@v1", json!({ "data": { "task_id": task_id } })).await
+        self.post_json("/api/system/seoh-import-export/task/get@v1", json!({ "data": { "task_id": task_id } })).await
     }
 }

+ 84 - 6
src/crates/bos-platform/src/clients/mod.rs

@@ -3,10 +3,38 @@ pub mod iam;
 pub mod impexp;
 pub mod resource_metadata;
 pub mod scheduler;
+pub mod uds;
 
-use reqwest::Client;
+use reqwest::{Certificate, Client};
 use std::sync::Arc;
 
+/// 信任根:与 SDK 注册链路同口径读 `CONFIG_CENTER_CA_CERT_PATH`(集群 Root CA+本机开发 CA
+/// 的 bundle,逐张拆出)。⛔ 加载 ⇒ rustls 只认内置根,经本机 TLS sidecar(SAN=localhost、
+/// 由开发 CA 签发)调平台时握手即 `UnknownIssuer`,报错被 reqwest 包成
+/// `platform call failed: error sending request for url (…)`,看着像"通路不通",
+/// 实为证书链问题(实测 2026-11-07:`user/create@v1` 建号 100% 失败于握手)。
+fn ca_roots() -> Vec<Vec<u8>> {
+    let Ok(path) = std::env::var("CONFIG_CENTER_CA_CERT_PATH") else {
+        return Vec::new();
+    };
+    let path = path.trim();
+    if path.is_empty() {
+        return Vec::new();
+    }
+    let Ok(pem) = std::fs::read_to_string(path) else {
+        tracing::warn!("平台信任根读取失败:{path}");
+        return Vec::new();
+    };
+    // bundle(多张证书)⇒ 逐张 `add_root_certificate`(reqwest 的 `from_pem` ⛔ 吃整包)。
+    pem.split("-----END CERTIFICATE-----")
+        .filter_map(|seg| {
+            let i = seg.find("-----BEGIN CERTIFICATE-----")?;
+            Some(seg[i..].to_string() + "-----END CERTIFICATE-----\n")
+        })
+        .map(|s| s.into_bytes())
+        .collect()
+}
+
 #[derive(Clone)]
 pub struct PlatformClient {
     pub http: Client,
@@ -17,10 +45,16 @@ pub struct PlatformClient {
 impl PlatformClient {
     pub fn new(gateway_base: impl Into<String>, token: Arc<dyn Fn() -> String + Send + Sync>) -> Self {
         Self {
-            http: Client::builder()
-                .danger_accept_invalid_certs(false)
-                .build()
-                .expect("reqwest client"),
+            http: {
+                let mut b = Client::builder().danger_accept_invalid_certs(false);
+                for pem in ca_roots() {
+                    match Certificate::from_pem(&pem) {
+                        Ok(c) => b = b.add_root_certificate(c),
+                        Err(e) => tracing::warn!("平台信任根单张解析失败:{e}"),
+                    }
+                }
+                b.build().expect("reqwest client")
+            },
             gateway_base: gateway_base.into().trim_end_matches('/').to_string(),
             token,
         }
@@ -34,9 +68,53 @@ impl PlatformClient {
         let url = format!("{}{}", self.gateway_base, path);
         let token = (self.token)();
         let mut req = self.http.post(&url).json(&body);
+        // ⛔ 把账号 JWT 塞进 `X-Internal-Token`:那是内部服务令牌位(应放 Bootstrap 换来的
+        // 服务身份票),拿账号票去占用它=踩《外部项目服务接入约束》§8.3 红线与业主
+        // 2026-11-07「`klt-bos` ⛔ 走内部令牌通道」裁定。这些平台业务接口按「用户 JWT」口径
+        // 只发 `Authorization: Bearer <本项目下发账号的 JWT>`,权限=该账号在 IAM 的权限。
         if !token.is_empty() {
             req = req.header("Authorization", format!("Bearer {token}"));
-            req = req.header("X-Internal-Token", &token);
+        }
+        if let Some(rid) = bos_core::trace::current_request_id() {
+            req = req.header(bos_core::trace::REQUEST_ID_HEADER, rid);
+        }
+        let resp = req
+            .send()
+            .await
+            .map_err(|e| bos_core::BosError::internal(format!("platform call failed: {e}")))?;
+        let status = resp.status();
+        let v: serde_json::Value = resp
+            .json()
+            .await
+            .map_err(|e| bos_core::BosError::internal(format!("platform decode: {e}")))?;
+        if !status.is_success() {
+            return Err(bos_core::BosError::biz(
+                bos_core::ErrorCode::Downstream,
+                format!("platform HTTP {status}: {v}"),
+            ));
+        }
+        Ok(v)
+    }
+
+    /// 只带 **Bearer 用户令牌**、⛔ 不带 `X-Internal-Token` 的调用通道。
+    ///
+    /// ⚠️ 适用对象=平台标记为「双调用方」的路由(`U-94` 平台书面答复,真源 总则§8.3 `iam-user` 行 ①):
+    /// 这类路由的 `x-internal-callers` 名单不含我方服务身份,用内部令牌直连**一律 `11001`**;
+    /// 我方⛔ 不得自建"可调用的服务名单"(平台的允许集是唯一真源)。
+    pub async fn post_json_as_user(
+        &self,
+        path: &str,
+        body: serde_json::Value,
+        user_token: &str,
+    ) -> Result<serde_json::Value, bos_core::BosError> {
+        let url = format!("{}{}", self.gateway_base, path);
+        let mut req = self
+            .http
+            .post(&url)
+            .json(&body)
+            .header("Authorization", format!("Bearer {user_token}"));
+        if let Some(rid) = bos_core::trace::current_request_id() {
+            req = req.header(bos_core::trace::REQUEST_ID_HEADER, rid);
         }
         let resp = req
             .send()

+ 109 - 5
src/crates/bos-platform/src/clients/resource_metadata.rs

@@ -4,18 +4,122 @@ use bos_core::BosError;
 
 impl PlatformClient {
     pub async fn node_create(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/resource-metadata/node/create@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-resource-metadata/node/create@v1", json!({ "data": data })).await
     }
     pub async fn node_rename(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/resource-metadata/node/update@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-resource-metadata/node/update@v1", json!({ "data": data })).await
     }
     pub async fn node_delete(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/resource-metadata/node/delete@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-resource-metadata/node/delete@v1", json!({ "data": data })).await
     }
     pub async fn registered_resource_create(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/resource-metadata/registered_resource/create@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-resource-metadata/registered_resource/create@v1", json!({ "data": data })).await
     }
     pub async fn registered_resource_move(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/resource-metadata/registered_resource/move@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-resource-metadata/registered_resource/move@v1", json!({ "data": data })).await
+    }
+
+    /// 注册实例清单枚举的**唯一通道**(总则§8.3;CI 结构断言 `A74`,来源=平台侧技术债审计 `P-16`)。
+    ///
+    /// ⚠️ 本口 `page_size` 缺省 200、合法区间 `1..=5000`、越界由平台**显式报错**(无静默截断);
+    /// RM 的旧通用清单口缺省 20 且**无上界校验** ⇒ ⛔ 消费(`A74` ①),需要枚举注册实例只走本函数。
+    /// ⚠️ 取数完成条件=`next_cursor` 为空串/`Null`(同 `U-05` 纪律);⛔ 以「本页条数 < page_size」判完成(`A74` ②)。
+    pub async fn registered_resource_list_all(
+        &self,
+        resource_type: &str,
+        page_size: i64,
+    ) -> Result<Vec<Value>, BosError> {
+        let size = page_size.clamp(1, 5_000);
+        let mut cursor = String::new();
+        let mut all: Vec<Value> = Vec::new();
+        loop {
+            let resp = self
+                .post_json(
+                    "/api/system/seoh-resource-metadata/registered_resource/get_list_by_type@v1",
+                    json!({ "data": { "resource_type": resource_type }, "cursor": cursor, "page_size": size }),
+                )
+                .await?;
+            if resp.get("code").and_then(Value::as_i64) != Some(bos_core::error::CODE_OK) {
+                return Err(BosError::biz(
+                    bos_core::ErrorCode::Downstream,
+                    format!("RM 清单口返回非成功码: {resp}"),
+                ));
+            }
+            let (items, next) = parse_list_page(&resp)?;
+            all.extend(items);
+            if next.is_empty() {
+                return Ok(all);
+            }
+            if next == cursor {
+                return Err(BosError::internal("RM 清单口游标未推进,已失败关闭(⛔ 不得当作取数完成)"));
+            }
+            cursor = next;
+        }
+    }
+}
+
+/// 解析清单口的一页应答:返回(本页 `items`,下一页游标)。
+/// 游标为空串或 `Null` =**取数完成**(`A74` ②;同 `U-05` 纪律);游标字段类型异常一律失败关闭。
+/// 兼容两种载荷位置:`data.{items,next_cursor}` 与顶层 `{items,pagination.next_cursor}`。
+fn parse_list_page(resp: &Value) -> Result<(Vec<Value>, String), BosError> {
+    let payload = resp.get("data").cloned().unwrap_or_else(|| resp.clone());
+    let items = payload
+        .get("items")
+        .and_then(Value::as_array)
+        .map(|a| a.clone())
+        .unwrap_or_default();
+    let raw = payload
+        .get("next_cursor")
+        .or_else(|| payload.get("pagination").and_then(|p| p.get("next_cursor")))
+        .cloned()
+        .unwrap_or(Value::Null);
+    let next = match raw {
+        Value::Null => String::new(),
+        Value::String(s) => s,
+        other => return Err(BosError::internal(format!("RM 清单口 next_cursor 类型异常: {other}"))),
+    };
+    Ok((items, next))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn empty_cursor_means_done() {
+        let resp = json!({ "code": 10000, "data": { "items": [{ "id": 1 }], "next_cursor": "" } });
+        let (items, next) = parse_list_page(&resp).unwrap();
+        assert_eq!(items.len(), 1);
+        assert!(next.is_empty(), "空串游标=取数完成");
+    }
+
+    #[test]
+    fn null_cursor_means_done() {
+        let resp = json!({ "code": 10000, "data": { "items": [], "next_cursor": null } });
+        let (_, next) = parse_list_page(&resp).unwrap();
+        assert!(next.is_empty());
+    }
+
+    #[test]
+    fn non_empty_cursor_continues_pagination() {
+        let resp = json!({ "code": 10000, "items": [{ "id": 1 }], "pagination": { "next_cursor": "c2" } });
+        let (items, next) = parse_list_page(&resp).unwrap();
+        assert_eq!(items.len(), 1);
+        assert_eq!(next, "c2");
+    }
+
+    /// `A74` ② 的反面:⛔ 以「本页条数 < page_size」判完成——应答不满页但游标非空时必须继续翻页。
+    #[test]
+    fn short_page_with_cursor_must_not_be_treated_as_done() {
+        let resp = json!({ "code": 10000, "data": { "items": [{ "id": 1 }], "next_cursor": "c2" } });
+        let (items, next) = parse_list_page(&resp).unwrap();
+        assert!(items.len() < 200, "本页不满页");
+        assert!(!next.is_empty(), "不满页⛔ 不等于取数完成");
+    }
+
+    #[test]
+    fn malformed_cursor_fails_closed() {
+        let resp = json!({ "code": 10000, "data": { "items": [], "next_cursor": 3 } });
+        assert!(parse_list_page(&resp).is_err());
     }
 }

+ 5 - 5
src/crates/bos-platform/src/clients/scheduler.rs

@@ -4,18 +4,18 @@ use bos_core::BosError;
 
 impl PlatformClient {
     pub async fn sjc_job_register(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/scheduled-job-center/job/register@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-scheduled-job-center/job/register@v1", json!({ "data": data })).await
     }
     pub async fn sjc_job_toggle(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/scheduled-job-center/job/toggle@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-scheduled-job-center/job/toggle@v1", json!({ "data": data })).await
     }
     pub async fn sjc_job_list(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/scheduled-job-center/job/list@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-scheduled-job-center/job/list@v1", json!({ "data": data })).await
     }
     pub async fn ets_subscribe(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/event-task-scheduler/subscription/create@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-event-task-scheduler/subscription/create@v1", json!({ "data": data })).await
     }
     pub async fn ets_run_once(&self, data: Value) -> Result<Value, BosError> {
-        self.post_json("/api/system/event-task-scheduler/task/run_once@v1", json!({ "data": data })).await
+        self.post_json("/api/system/seoh-event-task-scheduler/task/run_once@v1", json!({ "data": data })).await
     }
 }

+ 596 - 0
src/crates/bos-platform/src/clients/uds.rs

@@ -0,0 +1,596 @@
+//! SEOH `seoh-uds-gateway` 数据通道客户端——本服务**唯一**的数据出入口。
+//!
+//! 口径真源:总则§5.2 与 `docs/详细设计说明书/00-总则与全局约定/18-未决事项与口径差异登记.md`
+//! §18.3「UDS-1~UDS-5」「DM-1~DM-9」两行。硬约束在代码里的落点:
+//!
+//! * ⛔ 后端自持数据库凭据直连 `project_{id}_{env}`:平台不签发/轮换库凭据,本客户端是唯一通道;
+//! * `tenant_id`/`project_id` **只走 body**(`X-Tenant-Id`/`X-Project-Id` 实测不被网关读取);
+//! * `seoh_env` ∈ `dev|test|prod` **只走 `X-Seoh-Env` 头**(头优先,body 仅校验一致性,
+//!   非法值在落库前 `11103`);数据面 `env` ∈ `nonprod|prod`,与 `seoh_env` 是两套值域;
+//! * 一切值一律走 `params`(注入防线+绕开 `sql_guard` 对 SQL 原文的字面量子串误杀=`UDS-6`);
+//! * 表名一律改写为三段式 `uds.public.<table>`(⛔ 加双引号,实测 `13001`);
+//! * 读走联邦引擎(DataFusion 方言,⛔ `setval`/`nextval`),DML 走原生 Postgres;
+//! * `UPDATE/DELETE … RETURNING` 会让平台写侧上限**静默失效** ⇒ 本客户端⛔ 拼 `RETURNING`,
+//!   影响行数一律由 `/dml/batch@v1` 的 `affected_rows` 取回;
+//! * 退避重试集合=`11100`(内部)+`11000`+`13002`(数据源不可用)+`13019`(并发闸);
+//!   `11001`(归属配置错)/`13001`(SQL 失败)/`11103`(参数非法)**⛔ 重试**。
+
+use crate::audit::AuditEvent;
+use bos_core::{BosError, ErrorCode};
+use reqwest::Client;
+use serde::de::DeserializeOwned;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// 我方业务表所在 schema 前缀(平台侧固定 `uds.<schema>.`)。
+pub const SCHEMA_PREFIX: &str = "uds.public.";
+
+/// 可退避重试的平台错误码。`13019` ⛔ 当「空结果」或「查询失败」处理。
+const RETRYABLE_CODES: [i64; 4] = [11100, 11000, 13002, 13019];
+const MAX_ATTEMPTS: usize = 3;
+const BACKOFF_MS: [u64; 3] = [200, 600, 1500];
+
+#[derive(Debug, Clone)]
+pub struct UdsConfig {
+    /// UDS 网关基址(运行期直连 `https://seoh-uds-gateway:3022`,本机联调 `https://127.0.0.1:3022`)。
+    pub base_url: String,
+    pub tenant_id: String,
+    pub project_id: String,
+    /// SEOH 逻辑环境 ∈ `dev|test|prod`,进 `X-Seoh-Env` 头。
+    pub seoh_env: String,
+    /// 数据面环境 ∈ `nonprod|prod`,进 body。
+    pub data_env: String,
+    /// 集群内自签证书:本机联调需关闭校验(运行期改为挂载平台 Root CA)。
+    pub danger_accept_invalid_certs: bool,
+}
+
+/// 短批内的一条语句。
+#[derive(Debug, Clone, Serialize)]
+pub struct DmlStatement {
+    pub sql: String,
+    pub params: Vec<Value>,
+}
+
+impl DmlStatement {
+    pub fn new(sql: impl Into<String>, params: Vec<Value>) -> Self {
+        Self { sql: sql.into(), params }
+    }
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct QueryData {
+    #[serde(default)]
+    pub columns: Vec<String>,
+    #[serde(default)]
+    pub rows: Vec<Value>,
+    #[serde(default)]
+    pub row_count: usize,
+    /// 空串=没有下一页;非空⇒ 结果被分页截断,须续拉或改窄条件。
+    #[serde(default)]
+    pub next_cursor: String,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct DmlStatementResult {
+    #[serde(default)]
+    pub index: usize,
+    #[serde(default)]
+    pub affected_rows: Option<u64>,
+    #[serde(default)]
+    pub row_count: usize,
+}
+
+#[derive(Clone)]
+pub struct UdsClient {
+    http: Client,
+    cfg: UdsConfig,
+    token: Arc<dyn Fn() -> String + Send + Sync>,
+}
+
+impl UdsClient {
+    pub fn new(cfg: UdsConfig, token: Arc<dyn Fn() -> String + Send + Sync>) -> Self {
+        Self {
+            http: Client::builder()
+                .danger_accept_invalid_certs(cfg.danger_accept_invalid_certs)
+                .timeout(Duration::from_secs(60))
+                .build()
+                .expect("uds reqwest client"),
+            cfg: UdsConfig {
+                base_url: cfg.base_url.trim_end_matches('/').to_string(),
+                ..cfg
+            },
+            token,
+        }
+    }
+
+    pub fn config(&self) -> &UdsConfig {
+        &self.cfg
+    }
+
+    // ---------------- 读 ----------------
+
+    pub async fn query(&self, sql: &str, params: &[Value]) -> Result<QueryData, BosError> {
+        self.query_page(sql, params, None, None).await
+    }
+
+    pub async fn query_page(
+        &self,
+        sql: &str,
+        params: &[Value],
+        cursor: Option<&str>,
+        page_size: Option<i64>,
+    ) -> Result<QueryData, BosError> {
+        let mut body = self.scope_body(sql, params);
+        body["env"] = json!(self.cfg.data_env);
+        if let Some(c) = cursor.filter(|c| !c.is_empty()) {
+            body["cursor"] = json!(c);
+        }
+        if let Some(n) = page_size {
+            body["page_size"] = json!(n);
+        }
+        let data = self.post("/query/execute@v1", body).await?;
+        serde_json::from_value(data).map_err(|e| BosError::internal(format!("UDS 读响应解析失败: {e}")))
+    }
+
+    pub async fn query_all<T: DeserializeOwned>(
+        &self,
+        sql: &str,
+        params: &[Value],
+    ) -> Result<Vec<T>, BosError> {
+        let data = self.query(sql, params).await?;
+        self.assert_single_page(&data, sql)?;
+        from_rows(data.rows)
+    }
+
+    pub async fn query_one<T: DeserializeOwned>(
+        &self,
+        sql: &str,
+        params: &[Value],
+    ) -> Result<Option<T>, BosError> {
+        let mut rows = self.query_all::<T>(sql, params).await?;
+        Ok(rows.pop())
+    }
+
+    /// 联邦读默认单页 500 行:调用方用 `query_all` 却还有下一页=静默丢数,必须显式失败。
+    fn assert_single_page(&self, data: &QueryData, sql: &str) -> Result<(), BosError> {
+        if data.next_cursor.is_empty() {
+            return Ok(());
+        }
+        Err(BosError::internal(format!(
+            "UDS 结果被分页截断(row_count={},next_cursor={}),该 SQL 须改用 query_page 或聚合下推:{}",
+            data.row_count,
+            data.next_cursor,
+            &sql.chars().take(120).collect::<String>()
+        )))
+    }
+
+    // ---------------- 写 ----------------
+
+    /// 单语句写入:走 `/dml/batch@v1` 取回 `affected_rows`(`/query/execute@v1` 的 DML 不回影响行数,
+    /// 而我方「影响行数自检」⛔ 依赖它)。
+    pub async fn dml(&self, sql: &str, params: &[Value]) -> Result<u64, BosError> {
+        let results = self.dml_batch(&[DmlStatement::new(sql, params.to_vec())]).await?;
+        Ok(results
+            .first()
+            .and_then(|r| r.affected_rows)
+            .unwrap_or(0))
+    }
+
+    /// 同请求短批=**原子提交**(`UDS-2` ①=是),但⛔ 批内条件中止(②=否):
+    /// 需要「中途不满足就整体不写」时,把条件写进谓词或安排一条注定失败的守卫语句。
+    pub async fn dml_batch(
+        &self,
+        statements: &[DmlStatement],
+    ) -> Result<Vec<DmlStatementResult>, BosError> {
+        if statements.is_empty() {
+            return Err(BosError::internal("dml_batch: statements 为空"));
+        }
+        let mut body = self.scope_body("", &[]);
+        body["env"] = json!(self.cfg.data_env);
+        body["statements"] = Value::Array(
+            statements
+                .iter()
+                .map(|s| json!({ "sql": qualify(&s.sql), "params": s.params }))
+                .collect(),
+        );
+        let data = self.post("/dml/batch@v1", body).await?;
+        let committed = data.get("committed").and_then(Value::as_bool).unwrap_or(false);
+        let results: Vec<DmlStatementResult> = serde_json::from_value(
+            data.get("results").cloned().unwrap_or(Value::Array(vec![])),
+        )
+        .map_err(|e| BosError::internal(format!("UDS 写响应解析失败: {e}")))?;
+        if !committed {
+            return Err(BosError::biz(
+                ErrorCode::Downstream,
+                "UDS 短批未提交(committed=false)",
+            ));
+        }
+        Ok(results)
+    }
+
+    /// 写一条业务审计到 `bos_audit_log`(合规留痕唯一写入口)。
+    ///
+    /// ⚠️ 时间列走 SQL 文本 `now()`:UDS 对 `timestamptz` **参数**会静默落 NULL(UDS 已知坑),
+    /// `created_at`/`occurred_at` 一律⛔ 走 params;`DEFAULT NOW()` 又会被 `exec_ddl` 丢弃 ⇒
+    /// 必须显式写 `now()`。
+    ///
+    /// 断言 `affected_rows == 1`:⛔ 把 `10000` 当成功、⛔ 回显请求体当落库。
+    pub async fn write_audit(&self, event: &AuditEvent) -> Result<(), BosError> {
+        let params: Vec<Value> = vec![
+            Value::String(event.actor_user_id.clone()),
+            Value::String(event.action.clone()),
+            Value::String(event.resource_type.clone()),
+            Value::String(event.resource_id.clone()),
+            event.before.clone().unwrap_or(Value::Null),
+            event.after.clone().unwrap_or(Value::Null),
+            event.detail.clone().unwrap_or(Value::Null),
+        ];
+        let sql = "INSERT INTO bos_audit_log \
+                   (actor_user_id, action, resource_type, resource_id, before_json, after_json, \
+                    detail_json, occurred_at, created_at) \
+                   VALUES ($1::bigint, $2::text, $3::text, $4::text, $5::jsonb, $6::jsonb, \
+                    $7::jsonb, now(), now())";
+        let results = self.dml_batch(&[DmlStatement::new(sql, params)]).await?;
+        let affected = results.first().and_then(|r| r.affected_rows);
+        if affected != Some(1) {
+            return Err(BosError::internal(format!(
+                "审计日志未落库(affected_rows={affected:?} ⛔ 1)⇒ ⛔ 把 `10000` 当成功"
+            )));
+        }
+        Ok(())
+    }
+
+    // ---------------- 传输 ----------------
+
+    fn scope_body(&self, sql: &str, params: &[Value]) -> Value {
+        json!({
+            "tenant_id": self.cfg.tenant_id,
+            "project_id": self.cfg.project_id,
+            "seoh_env": self.cfg.seoh_env,
+            "sql": qualify(sql),
+            "params": params,
+        })
+    }
+
+    async fn post(&self, path: &str, body: Value) -> Result<Value, BosError> {
+        let url = format!("{}{}", self.cfg.base_url, path);
+        let mut last = String::new();
+        for attempt in 0..MAX_ATTEMPTS {
+            if attempt > 0 {
+                tokio::time::sleep(Duration::from_millis(BACKOFF_MS[
+                    (attempt - 1).min(BACKOFF_MS.len() - 1)
+                ]))
+                .await;
+            }
+            let token = (self.token)();
+            // UDS 与其它 SEOH 服务一样用统一信封:业务字段必须包在 `data` 内,
+            // 平铺发送会被判 11103「请求体无效: Failed to deserialize the JSON body」。
+            let envelope = json!({ "data": body });
+            let mut req = self.http.post(&url).json(&envelope).header("X-Seoh-Env", &self.cfg.seoh_env);
+            // `X-Request-Id` 一律**沿用**入口带来的值(讨论稿 K12 ②:本项目全程携带),
+            // ⛔ 在此另生成一个——那是接入约束 §8.3 点名的「链路断开」成因。
+            if let Some(rid) = bos_core::trace::current_request_id() {
+                req = req.header(bos_core::trace::REQUEST_ID_HEADER, rid);
+            }
+            // 运行期形态=**外部调用**(业主 2026-11-07 裁定:`klt-bos` ⛔ 走内部令牌通道)=
+            // 只发 `Authorization: Bearer <本项目下发账号的 JWT>`,⛔ 发 `X-Internal-Token`
+            // (内部令牌路径实测可绕过读写双键判权、且可改写 `dev` 写侧护栏,属平台侧缺陷面)。
+            // 代价=该账号须显式并持 `uds.query.execute@v1`+`uds.dml.execute@v1`(后者⛔ 进 AC
+            // 字典,须 `role_permission/bind@v1` 直绑),行级权限仍由本服务业务侧实现。
+            if !token.is_empty() {
+                req = req.header("Authorization", format!("Bearer {token}"));
+            }
+            let t0 = std::time::Instant::now();
+            let resp = match req.send().await {
+                Ok(r) => r,
+                Err(e) => {
+                    last = format!("传输失败: {e}");
+                    continue;
+                }
+            };
+            let status = resp.status();
+            let payload: Value = match resp.json().await {
+                Ok(v) => v,
+                Err(e) => {
+                    last = format!("响应非 JSON(HTTP {status}): {e}");
+                    continue;
+                }
+            };
+            // 累计进 `uds_ms`(接入约束 §10:`ac_ms`/`uds_ms`/`self_ms` 分开记录)。
+            bos_core::trace::add_uds_ms(t0.elapsed().as_millis() as u64);
+            let code = payload.get("code").and_then(Value::as_i64).unwrap_or(-1);
+            if code == 10000 {
+                return Ok(payload.get("data").cloned().unwrap_or(Value::Null));
+            }
+            let message = payload
+                .get("message")
+                .and_then(Value::as_str)
+                .unwrap_or("<无 message>")
+                .to_string();
+            last = format!("UDS {code}: {message}");
+            if !RETRYABLE_CODES.contains(&code) {
+                return Err(BosError::biz(ErrorCode::Downstream, last));
+            }
+        }
+        tracing::warn!(path, error = %last, "UDS 调用在重试上限内仍失败");
+        Err(BosError::biz(ErrorCode::Downstream, format!("{last}(已退避重试)")))
+    }
+}
+
+fn from_rows<T: DeserializeOwned>(rows: Vec<Value>) -> Result<Vec<T>, BosError> {
+    rows.into_iter()
+        .map(|r| {
+            serde_json::from_value(r).map_err(|e| {
+                BosError::internal(format!("UDS 行反序列化失败: {e}"))
+            })
+        })
+        .collect()
+}
+
+/// 把裸表名改写为 `uds.public.<table>`;已三段式的、`WITH` 里声明的 CTE 名⛔ 再改写。
+///
+/// 只在**字符串字面量之外**匹配,避免误伤值内容(`UDS-6` 的字面量误杀已由「值一律走 `params`」规避,
+/// 这里⛔ 需要处理引号内的表名)。
+pub fn qualify(sql: &str) -> String {
+    let cte = cte_names(sql);
+    let b = sql.as_bytes();
+    let mut out = String::with_capacity(sql.len() + 16);
+    let mut i = 0usize; // 扫描位
+    let mut seg = 0usize; // 尚未原样复制的起点
+    while i < b.len() {
+        if b[i] == b'\'' {
+            // 整个字面量原样复制(`''` 是转义),⛔ 在其中改写
+            let mut j = i + 1;
+            while j < b.len() {
+                if b[j] != b'\'' {
+                    j += 1;
+                    continue;
+                }
+                if b.get(j + 1) == Some(&b'\'') {
+                    j += 2;
+                    continue;
+                }
+                j += 1;
+                break;
+            }
+            out.push_str(&sql[seg..j]);
+            i = j;
+            seg = j;
+            continue;
+        }
+        if let Some(kw) = KEYWORDS.iter().find(|k| word_at(b, i, k)) {
+            let ws_end = skip_ws(b, i + kw.len());
+            let end = ident_end(b, ws_end);
+            out.push_str(&sql[seg..ws_end]);
+            let ident = &sql[ws_end..end];
+            // ⚠️ `ON CONFLICT DO UPDATE SET …` 中 `UPDATE` 紧跟 `SET`(非表名),
+            // 若把 `SET` 当表名加前缀会变成 `uds.public.SET` ⇒ SQL 解析失败。
+            // 同理 `JOIN ... ON`/`FROM (SELECT` 的子查询等也可能紧跟关键字。
+            let is_sql_keyword = SKIP_IDENTS
+                .iter()
+                .any(|k| k.eq_ignore_ascii_case(ident));
+            if !ident.is_empty() {
+                let already_qualified = b.get(end).copied() == Some(b'.');
+                if is_sql_keyword || already_qualified
+                    || cte.iter().any(|c| c.eq_ignore_ascii_case(ident))
+                {
+                    out.push_str(ident);
+                } else {
+                    out.push_str(SCHEMA_PREFIX);
+                    out.push_str(ident);
+                }
+            }
+            i = end;
+            seg = end;
+            continue;
+        }
+        i += 1;
+    }
+    out.push_str(&sql[seg..]);
+    out
+}
+
+fn is_ident_byte(b: u8) -> bool {
+    b.is_ascii_alphanumeric() || b == b'_'
+}
+
+const KEYWORDS: [&str; 4] = ["from", "into", "update", "join"];
+
+/// 紧跟 `from|into|update|join` 之后、但**不是**表名的 SQL 关键字(⛔ 加前缀)。
+/// 典型:`ON CONFLICT DO UPDATE SET …`、`JOIN … ON …`、`FROM (SELECT …)`。
+const SKIP_IDENTS: [&str; 8] = [
+    "set", "on", "select", "where", "values", "default", "only", "lateral",
+];
+
+fn word_at(b: &[u8], i: usize, w: &str) -> bool {
+    if i > 0 && is_ident_byte(b[i - 1]) {
+        return false;
+    }
+    let e = i + w.len();
+    e <= b.len()
+        && b[i..e].eq_ignore_ascii_case(w.as_bytes())
+        && !b.get(e).is_some_and(|c| is_ident_byte(*c))
+}
+
+fn skip_ws(b: &[u8], mut i: usize) -> usize {
+    while matches!(b.get(i), Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r')) {
+        i += 1;
+    }
+    i
+}
+
+fn ident_end(b: &[u8], mut i: usize) -> usize {
+    while i < b.len() && is_ident_byte(b[i]) {
+        i += 1;
+    }
+    i
+}
+
+/// `WITH a AS (...), b AS (...)` 里的 CTE 名。
+fn cte_names(sql: &str) -> Vec<String> {
+    let mut out = Vec::new();
+    let lower = sql.to_ascii_lowercase();
+    let b = lower.as_bytes();
+    let mut i = 0usize;
+    while let Some(pos) = find_word(&lower, "with", i) {
+        let mut j = skip_ws(b, pos + 4);
+        while j < b.len() {
+            let e = ident_end(b, j);
+            if e == j {
+                break;
+            }
+            out.push(lower[j..e].to_string());
+            j = skip_ws(b, e);
+            if word_at(b, j, "as") {
+                j = skip_ws(b, j + 2);
+            }
+            if b.get(j) != Some(&b'(') {
+                break;
+            }
+            j = skip_ws(b, skip_parens(b, j));
+            if b.get(j) != Some(&b',') {
+                break;
+            }
+            j = skip_ws(b, j + 1);
+        }
+        i = pos + 4;
+    }
+    out
+}
+
+/// 返回与 `i` 处左括号配对的右括号之后的位置。
+fn skip_parens(b: &[u8], mut i: usize) -> usize {
+    let mut depth = 0usize;
+    while i < b.len() {
+        match b[i] {
+            b'(' => depth += 1,
+            b')' => {
+                depth -= 1;
+                if depth == 0 {
+                    return i + 1;
+                }
+            }
+            _ => {}
+        }
+        i += 1;
+    }
+    i
+}
+
+fn find_word(hay: &str, needle: &str, from: usize) -> Option<usize> {
+    let hb = hay.as_bytes();
+    let mut i = from;
+    while let Some(rel) = hay[i..].find(needle) {
+        let p = i + rel;
+        let before_ok = p == 0 || !is_ident_byte(hb[p - 1]);
+        let after = p + needle.len();
+        let after_ok = !hb.get(after).is_some_and(|c| is_ident_byte(*c));
+        if before_ok && after_ok {
+            return Some(p);
+        }
+        i = p + needle.len();
+    }
+    None
+}
+
+/// 宽松取字符串:平台可能把 `bigint`/`bool` 序列化成数字或字符串,取值处⛔ 假定单一形态。
+pub mod de {
+    use serde::de::{Deserialize, Deserializer};
+    use serde_json::Value;
+
+    pub fn as_string<'de, D>(d: D) -> Result<String, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let v = Value::deserialize(d)?;
+        Ok(match v {
+            Value::String(s) => s,
+            Value::Number(n) => n.to_string(),
+            Value::Bool(b) => b.to_string(),
+            Value::Null => String::new(),
+            other => other.to_string(),
+        })
+    }
+
+    pub fn as_opt_string<'de, D>(d: D) -> Result<Option<String>, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        let v = Option::<Value>::deserialize(d)?;
+        Ok(match v {
+            None | Some(Value::Null) => None,
+            Some(Value::String(s)) => Some(s),
+            Some(Value::Number(n)) => Some(n.to_string()),
+            Some(other) => Some(other.to_string()),
+        })
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::qualify;
+
+    #[test]
+    fn qualifies_bare_table_names() {
+        assert_eq!(
+            qualify("SELECT id FROM customer WHERE id = $1"),
+            "SELECT id FROM uds.public.customer WHERE id = $1"
+        );
+        assert_eq!(
+            qualify("INSERT INTO billing_snapshot_customer (period) VALUES ($1)"),
+            "INSERT INTO uds.public.billing_snapshot_customer (period) VALUES ($1)"
+        );
+        assert_eq!(
+            qualify("UPDATE bos_data_scope s JOIN ent_team t ON t.id = s.holder_id SET x = 1"),
+            "UPDATE uds.public.bos_data_scope s JOIN uds.public.ent_team t ON t.id = s.holder_id SET x = 1"
+        );
+        assert_eq!(
+            qualify("DELETE FROM bos_data_scope WHERE holder_id = $1"),
+            "DELETE FROM uds.public.bos_data_scope WHERE holder_id = $1"
+        );
+    }
+
+    #[test]
+    fn keeps_qualified_names_and_skips_cte() {
+        assert_eq!(
+            qualify("SELECT c.id FROM uds.public.customer c"),
+            "SELECT c.id FROM uds.public.customer c"
+        );
+        let sql = "WITH picked AS (SELECT id FROM customer), t2 AS (SELECT id FROM picked) \
+                   SELECT p.id FROM picked p JOIN t2 ON p.id = t2.id";
+        assert_eq!(
+            qualify(sql),
+            "WITH picked AS (SELECT id FROM uds.public.customer), t2 AS (SELECT id FROM picked) \
+             SELECT p.id FROM picked p JOIN t2 ON p.id = t2.id"
+        );
+    }
+
+    #[test]
+    fn does_not_touch_string_literals_or_subqueries() {
+        assert_eq!(
+            qualify("SELECT 'FROM customer' AS s FROM partner WHERE name = $1"),
+            "SELECT 'FROM customer' AS s FROM uds.public.partner WHERE name = $1"
+        );
+        assert_eq!(
+            qualify("SELECT * FROM (SELECT id FROM customer) x"),
+            "SELECT * FROM (SELECT id FROM uds.public.customer) x"
+        );
+    }
+
+    #[test]
+    fn on_conflict_do_update_set_not_qualified() {
+        // `ON CONFLICT DO UPDATE SET …` 中 `UPDATE` 紧跟 `SET`(非表名),
+        // 若把 `SET` 当表名加前缀会变成 `uds.public.SET` ⇒ SQL 解析失败。
+        let sql = "INSERT INTO rate_limit_bucket (bucket_key, count) VALUES ($1, 1) \
+                   ON CONFLICT (bucket_key) DO UPDATE SET count = rate_limit_bucket.count + 1 \
+                   WHERE rate_limit_bucket.count < $2";
+        assert_eq!(
+            qualify(sql),
+            "INSERT INTO uds.public.rate_limit_bucket (bucket_key, count) VALUES ($1, 1) \
+             ON CONFLICT (bucket_key) DO UPDATE SET count = rate_limit_bucket.count + 1 \
+             WHERE rate_limit_bucket.count < $2"
+        );
+    }
+}

+ 3 - 0
src/crates/bos-scope/Cargo.toml

@@ -6,6 +6,9 @@ edition = { workspace = true }
 [dependencies]
 bos-core = { workspace = true }
 bos-platform = { workspace = true }
+# 工单回件 §5.2 B2:通道②授权上界的解析口径=平台 SDK `resolve_upper_bound`(all/ids/rules+deny_*)。
+# 直接依赖该 crate 复用其类型与解析,⛔ 在本仓库重写一份平行实现。
+seoh-service-sdk = { workspace = true }
 serde = { workspace = true }
 serde_json = { workspace = true }
 sqlx = { workspace = true }

+ 76 - 46
src/crates/bos-scope/src/scoped_select.rs

@@ -1,6 +1,9 @@
 use bos_core::{BosError, RoleCode};
+use bos_platform::clients::uds::{de, UdsClient};
+use seoh_service_sdk::InstanceUpperBound;
 use serde::{Deserialize, Serialize};
 use std::collections::HashSet;
+use std::sync::Arc;
 
 use crate::grant::ScopeMode;
 use crate::roles_policy::{visible_customer_strategy, VisibilitySource};
@@ -18,8 +21,32 @@ pub struct AuthContext {
     pub subject: SubjectRef,
     pub entry_only: bool,
     pub scope_mode: Option<ScopeMode>,
-    /// 通道②:网关注入的已授权实例(真源 HTTP 列举)
+    /// 通道②:平台侧下发的已授权实例(真源 HTTP 列举)。
+    ///
+    /// 2026-11-08 起不再恒为空集(工单回件 §4 N-5/§5.2 B2):由 `bos_api::load_binding` 从
+    /// **网关注入到请求体根级**的 `__granted_resource_grant`/`__granted_resource_instances`
+    /// 解析而来(注入键⛔ 信任客户端自报:网关转发前先 `remove` 同名键,
+    /// `seoh-api-gateway/src/proxy.rs:1665-1698`);仍⛔ 从请求头自报授权范围
+    /// (《外部项目服务接入约束》§8.3 红线 6)。
+    ///
+    /// 口径(⛔ 当「空集=全放行」用,既有消费方的失败关闭语义不变):
+    /// * 非空=平台**逐个点名**下发了授权实例(上界=`Exact`,线格式 `{"scope":"ids"}`/扁平数组),
+    ///   集合即这批实例 id;
+    /// * 空集=**本次没有可逐点点名的实例集合**,含四种情形:未注入(`grant_bound`=`None`)、
+    ///   上界为零(`Some(Empty)`)、上界不限(`Some(Unrestricted)`)、上界是**锚点**
+    ///   (`Some(Rules)`——语义=锚点子树减 deny,须沿 RM 父链展开,⛔ 当精确实例用,
+    ///   投影理由见 `bos_api::grant::usable_instance_ids`)。四者一律按现状处理:
+    ///   「无授权⇒拒绝/判空,或回落本地 `bos_data_scope`」,⛔ 借「不限」放大可见范围。
     pub granted_resource_instances: HashSet<String>,
+    /// 通道②的**结构化**授权上界(=平台 SDK `resolve_upper_bound` 的产物,复用它、⛔ 平行实现)。
+    ///
+    /// 与 `granted_resource_instances` 的分工:本字段表达**口径**,前者表达**可直接判定的 id 集合**。
+    /// * `None`=本次请求**没有**上界可依据(路由未声明 `x-enumeration-kind`/AC 未下发/
+    ///   绕网关直连/注入键形状不认识);
+    /// * `Some(Empty)`=确已下发上界且上界为零。
+    /// 两者语义不同 ⇒ 页面须分开说明(⛔ 把「未注入」写成「您无权查看任何数据」,
+    /// 工单回件 §5.2 B2「可区分未注入与注入后为空」)。
+    pub grant_bound: Option<InstanceUpperBound>,
     pub username: Option<String>,
 }
 
@@ -47,9 +74,15 @@ pub trait ScopedSelect: Send + Sync {
     async fn visible_region_node_ids(&self, auth: &AuthContext) -> Result<Vec<String>, BosError>;
 }
 
+#[derive(Debug, Deserialize)]
+struct IdRow {
+    #[serde(deserialize_with = "de::as_string")]
+    id: String,
+}
+
 /// 进程内默认实现:Owner/Bind 走业务库;Tree 依赖 dim_node_ancestor / 注入 granted。
 pub struct DbScopedSelect {
-    pub pool: sqlx::PgPool,
+    pub db: Arc<UdsClient>,
 }
 
 #[async_trait::async_trait]
@@ -62,65 +95,62 @@ impl ScopedSelect for DbScopedSelect {
                     RoleCode::Operator => "operator_id",
                     _ => unreachable!(),
                 };
-                let q = format!(
-                    "SELECT customer_id::text FROM customer WHERE {} = $1 AND deleted_at IS NULL",
-                    col
-                );
-                let rows: Vec<(String,)> = sqlx::query_as(&q)
-                    .bind(&auth.subject.subject_id)
-                    .fetch_all(&self.pool)
-                    .await
-                    .map_err(|e| BosError::internal(e.to_string()))?;
-                Ok(rows.into_iter().map(|r| r.0).collect())
-            }
-            VisibilitySource::Bind => {
-                Ok(vec![auth.subject.subject_id.clone()])
+                let rows = self
+                    .db
+                    .query_all::<IdRow>(
+                        &format!(
+                            "SELECT customer_id AS id FROM customer \
+                             WHERE {col} = $1::text AND deleted_at IS NULL"
+                        ),
+                        &[serde_json::json!(&auth.subject.subject_id)],
+                    )
+                    .await?;
+                Ok(rows.into_iter().map(|r| r.id).collect())
             }
+            VisibilitySource::Bind => Ok(vec![auth.subject.subject_id.clone()]),
             VisibilitySource::TreeUnionPicked => {
-                // 优先消费通道②注入;否则走 scope_grant 点选 / follow_team。
+                // 优先消费通道②注入;否则走 bos_data_scope 点选 / follow_team。
                 if !auth.granted_resource_instances.is_empty() {
                     return Ok(auth.granted_resource_instances.iter().cloned().collect());
                 }
-                let rows: Vec<(String,)> = sqlx::query_as(
-                    r#"
-                    SELECT target_id FROM scope_grant
-                    WHERE holder_type = 'user' AND holder_id = $1 AND target_type = 'customer'
-                    "#,
-                )
-                .bind(&auth.user_id)
-                .fetch_all(&self.pool)
-                .await
-                .map_err(|e| BosError::internal(e.to_string()))?;
-                Ok(rows.into_iter().map(|r| r.0).collect())
+                let rows = self
+                    .db
+                    .query_all::<IdRow>(
+                        "SELECT target_id AS id FROM bos_data_scope \
+                         WHERE holder_type = 'user' AND holder_id = $1::text \
+                         AND target_type = 'customer'",
+                        &[serde_json::json!(&auth.user_id)],
+                    )
+                    .await?;
+                Ok(rows.into_iter().map(|r| r.id).collect())
             }
         }
     }
 
     async fn visible_region_node_ids(&self, auth: &AuthContext) -> Result<Vec<String>, BosError> {
         if auth.role == RoleCode::Admin {
-            let rows: Vec<(String,)> = sqlx::query_as(
-                "SELECT node_id FROM dim_node_ancestor WHERE ancestor_id = node_id",
-            )
-            .fetch_all(&self.pool)
-            .await
-            .map_err(|e| BosError::internal(e.to_string()))?;
-            return Ok(rows.into_iter().map(|r| r.0).collect());
+            let rows = self
+                .db
+                .query_all::<IdRow>(
+                    "SELECT node_id AS id FROM dim_node_ancestor WHERE ancestor_id = node_id",
+                    &[],
+                )
+                .await?;
+            return Ok(rows.into_iter().map(|r| r.id).collect());
         }
         if !auth.granted_resource_instances.is_empty() {
             return Ok(auth.granted_resource_instances.iter().cloned().collect());
         }
-        let rows: Vec<(String,)> = sqlx::query_as(
-            r#"
-            SELECT target_id FROM scope_grant
-            WHERE holder_type IN ('user','ent_team','ops_team','partner')
-              AND holder_id = $1 AND target_type = 'region'
-            "#,
-        )
-        .bind(&auth.subject.subject_id)
-        .fetch_all(&self.pool)
-        .await
-        .map_err(|e| BosError::internal(e.to_string()))?;
-        Ok(rows.into_iter().map(|r| r.0).collect())
+        let rows = self
+            .db
+            .query_all::<IdRow>(
+                "SELECT target_id AS id FROM bos_data_scope \
+                 WHERE holder_type IN ('user','ent_team','ops_team','partner') \
+                 AND holder_id = $1::text AND target_type = 'region'",
+                &[serde_json::json!(&auth.subject.subject_id)],
+            )
+            .await?;
+        Ok(rows.into_iter().map(|r| r.id).collect())
     }
 }
 

+ 10 - 10
src/migrations/dev/20261104000001_bos_core_tables.sql

@@ -65,7 +65,7 @@ COMMENT ON COLUMN bos_seq_year.year IS '发号年份';
 COMMENT ON COLUMN bos_seq_year.kind IS '发号种类(如 customer、import_batch)';
 COMMENT ON COLUMN bos_seq_year.last_value IS '当年该种类已用最大流水值';
 
-CREATE TABLE IF NOT EXISTS scope_grant (
+CREATE TABLE IF NOT EXISTS bos_data_scope (
     id BIGSERIAL PRIMARY KEY,
     holder_type VARCHAR(32) NOT NULL,
     holder_id VARCHAR(64) NOT NULL,
@@ -73,15 +73,15 @@ CREATE TABLE IF NOT EXISTS scope_grant (
     target_id VARCHAR(64) NOT NULL,
     created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
 );
-CREATE INDEX IF NOT EXISTS idx_scope_grant_holder ON scope_grant (holder_type, holder_id);
-CREATE INDEX IF NOT EXISTS idx_scope_grant_target ON scope_grant (target_type, target_id);
-COMMENT ON TABLE scope_grant IS '负责范围授权:持有者对区域/客户等目标的授权行';
-COMMENT ON COLUMN scope_grant.id IS '主键';
-COMMENT ON COLUMN scope_grant.holder_type IS '持有者类型(如 user/ent_team/ops_team/partner)';
-COMMENT ON COLUMN scope_grant.holder_id IS '持有者 ID';
-COMMENT ON COLUMN scope_grant.target_type IS '目标类型(如 region/customer)';
-COMMENT ON COLUMN scope_grant.target_id IS '目标 ID';
-COMMENT ON COLUMN scope_grant.created_at IS '创建时间';
+CREATE INDEX IF NOT EXISTS idx_bos_data_scope_holder ON bos_data_scope (holder_type, holder_id);
+CREATE INDEX IF NOT EXISTS idx_bos_data_scope_target ON bos_data_scope (target_type, target_id);
+COMMENT ON TABLE bos_data_scope IS '负责范围授权:持有者对区域/客户等目标的授权行';
+COMMENT ON COLUMN bos_data_scope.id IS '主键';
+COMMENT ON COLUMN bos_data_scope.holder_type IS '持有者类型(如 user/ent_team/ops_team/partner)';
+COMMENT ON COLUMN bos_data_scope.holder_id IS '持有者 ID';
+COMMENT ON COLUMN bos_data_scope.target_type IS '目标类型(如 region/customer)';
+COMMENT ON COLUMN bos_data_scope.target_id IS '目标 ID';
+COMMENT ON COLUMN bos_data_scope.created_at IS '创建时间';
 
 CREATE TABLE IF NOT EXISTS dim_node_ancestor (
     node_id VARCHAR(64) NOT NULL,

+ 110 - 0
src/migrations/dev/20261107000002_bos_write_gap_columns.sql

@@ -0,0 +1,110 @@
+-- 2026-11-07 写侧落库补列(业主当日裁定=方案 A:dev 骨架补列,⛔ 维持"缺列即只能拒写/丢字段")
+--
+-- 范围纪律(⛔ 顺手补齐全设计册列集):本文件只补两类列
+--   ① `src/openapi.yaml` 写侧请求体里**已出现**的字段(前端表单已在提交、服务端无处落库);
+--   ② 只读侧 handler 里 `COLUMNS_PENDING` 点名回 `null` 的字段(=前端类型已声明的列)。
+-- 设计册(第 3 册 §2.3/第 4 册)里更深的形态(订阅快照列 `plan_kind`/`plan_owner_customer_id`/
+-- `plan_name`/`sub_mode`/`line_exits`+`line_exit_key`/`term`/`trial_months`、生成列与 I6/I12 落库兜底、
+-- `contract_service_item.derived_from_contract_item_id` 派生档链等)**本文件不补**,
+-- 差额已登 总则§18.3;补它们=实施期的表结构重建,不属于"补写侧缺口"。
+--
+-- 类型口径:业务 ID 列沿用 dev 骨架的 `VARCHAR(64)`(⛔ 跟设计册 `BIGINT` 混用,历轮已定);
+-- ⚠️ 一处被迫偏离=`line_exits` 设计是 `TEXT[]`+`GIN`,dev 用 `JSONB` 承载(UDS 参数绑定按
+-- JSON 值发送,数组→`text[]` 的隐式转换不可靠),读出后按字符串数组原样回给前端,差异已登 18 册。
+--
+-- 幂等:全部 `IF NOT EXISTS`,可重复执行(`temp/uds_apply.py --ddl`)。
+-- 已有种子行不受影响:新增列一律可空或带默认值。
+
+-- ── 套餐档位(catalog_plan)────────────────────────────────────────
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS use_category        VARCHAR(32)  NULL;
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS sub_account_quota   INT          NULL;
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS bandwidth_committed BOOLEAN      NOT NULL DEFAULT TRUE;
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS bandwidth_up_mbps   INT          NULL;
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS bandwidth_down_mbps INT          NULL;
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS customer_id         VARCHAR(64)  NULL;
+ALTER TABLE catalog_plan ADD COLUMN IF NOT EXISTS row_version         INT          NOT NULL DEFAULT 1;
+COMMENT ON COLUMN catalog_plan.use_category IS '用途分类:office/live/ai/value_add/customized;建后不可改';
+COMMENT ON COLUMN catalog_plan.bandwidth_committed IS '是否承诺带宽;false=不承诺,上下行两列一律为空';
+COMMENT ON COLUMN catalog_plan.customer_id IS '自定义档(plan_kind=custom)归属客户;固定档为空。专属套餐据此收窄可见性';
+
+-- ── 合同主档(contract)───────────────────────────────────────────
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS external_no       VARCHAR(64)  NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS pay_cycle         VARCHAR(16)  NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS start_date        DATE         NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS end_date          DATE         NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS agent_name        VARCHAR(128) NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS agent_mobile      VARCHAR(64)  NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS agent_handover_on DATE         NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS agent_org         VARCHAR(128) NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS attachment_url    TEXT         NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS updated_at        TIMESTAMPTZ  NOT NULL DEFAULT NOW();
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS row_version       INT          NOT NULL DEFAULT 1;
+COMMENT ON COLUMN contract.pay_cycle IS '付款周期:yearly/quarterly/monthly';
+
+-- 服务构成条目(设计册 §2.2 `contract_service_item`,此前整表未建 ⇒ 读侧只能回 null)
+CREATE TABLE IF NOT EXISTS contract_service_item (
+    item_id            VARCHAR(64) PRIMARY KEY,
+    contract_id        VARCHAR(64) NOT NULL REFERENCES contract (contract_id),
+    item_kind          VARCHAR(16) NOT NULL,
+    plan_id            VARCHAR(64) NULL,
+    quantity           INT NULL,
+    account_count      INT NULL,
+    bandwidth_up_mbps  INT NULL,
+    bandwidth_down_mbps INT NULL,
+    line_exits         JSONB NULL,
+    use_category       VARCHAR(32) NULL,
+    annual_price_cents BIGINT NULL,
+    created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_contract_service_item_contract ON contract_service_item (contract_id);
+COMMENT ON TABLE contract_service_item IS '合同服务构成条目(线路出口只挂本表,账号级⛔ 不建出口字段)';
+COMMENT ON COLUMN contract_service_item.item_kind IS '条目类型:plan_based(套餐式)/custom_spec(自定义式)';
+COMMENT ON COLUMN contract_service_item.line_exits IS '线路出口字符串数组;设计形态=TEXT[]+GIN,dev 用 JSONB 承载(差异登 18 册)';
+
+-- 固定 IP 条目(设计册 §2.2 `contract_ip_entry`,此前整表未建)
+CREATE TABLE IF NOT EXISTS contract_ip_entry (
+    entry_id            VARCHAR(64) PRIMARY KEY,
+    contract_id         VARCHAR(64) NOT NULL REFERENCES contract (contract_id),
+    line_exit           VARCHAR(64) NULL,
+    bandwidth_tier_mbps INT NULL,
+    ip_count            INT NULL,
+    created_at          TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_contract_ip_entry_contract ON contract_ip_entry (contract_id);
+COMMENT ON TABLE contract_ip_entry IS '合同固定 IP 条目(条件必填三元组:出口×带宽档位×数量)';
+COMMENT ON COLUMN contract_ip_entry.bandwidth_tier_mbps IS '带宽档位三值枚举 5/10/30,⛔ 不放开连续值(服务端校验,dev 不加 CHECK 以便存量与脏数据可读)';
+
+-- ── 订阅主档(subscription)───────────────────────────────────────
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS contract_item_id         VARCHAR(64) NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS use_category             VARCHAR(32) NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS start_date               DATE        NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS end_date                 DATE        NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS annual_price_cents       BIGINT      NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS monthly_settle_cents     BIGINT      NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS replaces_subscription_id VARCHAR(64) NULL;
+ALTER TABLE subscription ADD COLUMN IF NOT EXISTS row_version              INT         NOT NULL DEFAULT 1;
+-- ⚠️ 遗留重复:`effective_date`/`expire_date` 是一期骨架的早期列,与补入的设计列
+-- `start_date`/`end_date` 语义重叠。写侧只写设计列(=唯一真源),骨架两列⛔ 不再写入、
+-- 读侧继续原样呈现(存量种子只有这两列有值),合并成一个口径已登 18 册待裁定。
+COMMENT ON COLUMN subscription.effective_date IS '⚠️ 一期骨架遗留列(写侧已停用):与 start_date 语义重叠,去留待裁定';
+COMMENT ON COLUMN subscription.expire_date IS '⚠️ 一期骨架遗留列(写侧已停用):与 end_date 语义重叠,去留待裁定';
+COMMENT ON COLUMN subscription.replaces_subscription_id IS '升降配时被替换的原订阅 ID(唯一,⛔ 同一原订阅配两次升降配)';
+
+-- ── 成本项(cost_item)────────────────────────────────────────────
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS category            VARCHAR(32)  NULL;
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS billing_unit        VARCHAR(32)  NULL;
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS is_amortized        BOOLEAN      NULL;
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS amortization_months INT          NULL;
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS deduct_from_base    BOOLEAN      NULL;
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS remark              VARCHAR(512) NULL;
+ALTER TABLE cost_item ADD COLUMN IF NOT EXISTS row_version         INT          NOT NULL DEFAULT 1;
+COMMENT ON COLUMN cost_item.category IS '类别:intl_resource/device_purchase/project_fee';
+COMMENT ON COLUMN cost_item.billing_unit IS '计费单位:per_customer/per_account/per_copy';
+
+-- ── 成本金额(cost_amount):补透视表的两根轴 ──────────────────────
+ALTER TABLE cost_amount ADD COLUMN IF NOT EXISTS province_node_id VARCHAR(64) NULL;
+ALTER TABLE cost_amount ADD COLUMN IF NOT EXISTS operator_id      VARCHAR(64) NULL;
+ALTER TABLE cost_amount ADD COLUMN IF NOT EXISTS row_version      INT         NOT NULL DEFAULT 1;
+CREATE INDEX IF NOT EXISTS idx_cost_amount_axes ON cost_amount (province_node_id, operator_id);
+COMMENT ON COLUMN cost_amount.province_node_id IS '省份节点 ID(透视表横轴);正式形态下与 operator_id 共同构成差异行唯一键';
+COMMENT ON COLUMN cost_amount.operator_id IS '运营商 ID(透视表纵轴)';

+ 50 - 0
src/migrations/dev/20261107000003_customer_history_tables.sql

@@ -0,0 +1,50 @@
+-- 2026-11-07 第 2 册「变更历史」两张表补建(真源=客户§2 数据模型 B-6、客户§9 索引、客户§4.1 逐字段历史)
+--
+-- 为什么单独建:`bos.customer/history@v1`(openapi:2143)与写侧 `update@v1` 的逐字段留痕
+-- 都**只有这两张表是真源**,而 20261104 的 dev 骨架只落了第 1/3/4 册+第 2 册主档,
+-- 把 B-6 清单里的这三张从属表漏掉了 ⇒ 只读侧无处可查、写侧无处可写。
+-- ⛔ 改 20261104 那份历史迁移(业主历轮口径=只追加新文件、⛔ 重灌数据)。
+--
+-- 范围纪律:本次只建 `history@v1`/`update@v1` 直接依赖的两张表。
+-- B-6 清单里的 `customer_external_ref` 当前无任何 handler 引用,⛔ 顺手建(等它的接口落地时再补)。
+--
+-- ⚠️ 与设计册的两处已知偏离(已登 总则§18.3):
+--   ① 主键用 `BIGSERIAL`(客户§2 写 `id` PK,未定类型)=与 dev 骨架同类从属表(`customer_region_mount`
+--      /`bos_audit_log`)一致;⛔ 在这里换成业务 ID 列口径,那属于全库 ID 策略议题。
+--   ② `old_cipher`/`new_cipher` 以 `TEXT` 承载**平台侧密文原文**,一期 BOS ⛔ 加解密能力
+--      (客户§3.4 完整值解密在渲染层、依赖平台密钥服务),故本表**只写不读值**:
+--      `history@v1` 只回 `change_basis`+时间+操作人,密文列⛔ 出现在任何出参里。
+--
+-- 幂等:全部 `IF NOT EXISTS`,可重复执行(`temp/uds_apply.py --ddl`)。
+
+CREATE TABLE IF NOT EXISTS customer_field_history (
+    id               BIGSERIAL   PRIMARY KEY,
+    customer_id      VARCHAR(64) NOT NULL,
+    field_key        VARCHAR(64) NOT NULL,
+    old_display      TEXT        NULL,
+    new_display      TEXT        NULL,
+    operator_user_id VARCHAR(64) NULL,
+    changed_at       TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+COMMENT ON COLUMN customer_field_history.old_display IS '变更前**展示值**(区域写全路径、团队写团队名、归属写名称,⛔ 内部 ID);客户§2.2';
+COMMENT ON COLUMN customer_field_history.new_display IS '变更后展示值,口径同上;掩码在渲染层按角色施加,⛔ 存掩码值';
+
+CREATE TABLE IF NOT EXISTS customer_identity_history (
+    id               BIGSERIAL   PRIMARY KEY,
+    customer_id      VARCHAR(64) NOT NULL,
+    old_cipher       TEXT        NULL,
+    old_hash         VARCHAR(64) NULL,
+    new_cipher       TEXT        NULL,
+    new_hash         VARCHAR(64) NULL,
+    change_basis     TEXT        NOT NULL,
+    operator_user_id VARCHAR(64) NULL,
+    changed_at       TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+COMMENT ON COLUMN customer_identity_history.change_basis IS '变更依据(企业改制换税号/个人换证等);缺依据不保存 ⇒ KLT-C006';
+COMMENT ON COLUMN customer_identity_history.new_cipher IS '新识别号密文原文;⛔ 明文,⛔ 出现在任何出参(需要完整值时由渲染层按角色解密)';
+
+-- 客户§9:详情页「变更历史」倒序分页
+CREATE INDEX IF NOT EXISTS ix_cust_field_hist_customer_changed
+    ON customer_field_history (customer_id, changed_at DESC);
+CREATE INDEX IF NOT EXISTS ix_cust_identity_hist_customer_changed
+    ON customer_identity_history (customer_id, changed_at DESC);

+ 25 - 0
src/migrations/dev/20261107000004_audit_log_occurred_at.sql

@@ -0,0 +1,25 @@
+-- 2026-11-07 修 dev 实表与迁移文件的漂移:`bos_audit_log.occurred_at` 缺列
+--
+-- 现象(本轮实测,⛔ 静态推断):`bos_audit_log` 的**实表列**为
+--   id / actor_user_id / action / resource_type / resource_id / before_json / after_json
+--   / detail_json / created_at
+-- —— 没有 `occurred_at`,而 20261104 那份迁移文件里 `occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()`
+-- 一直在册。实表早于该列建立,`CREATE TABLE IF NOT EXISTS` 对已存在的表**只跳过、不改列**
+-- ⇒ 迁移文件与实表就此分叉,且**无人报错**(直到有人真读这一列)。
+--
+-- 后果(本轮踩到):凡 SELECT `occurred_at` 的读侧全部 `10110 / UDS 13001 Schema error`:
+--   ① `/audit/list@v1`([audit.rs](../../../src/modules/account/src/handlers/audit.rs) 选择列表第 2 列,**本轮之前就在坏**)
+--   ② `/region/change_log@v1`(本轮新落库,撞在同一列上)
+-- ⇒ 这不是查询写错,是 dev 库缺列;⛔ 通过改代码绕开(那等于把迁移文件当摆设)。
+--
+-- 处置口径(沿用业主历轮裁定):⛔ 改 20261104 那份历史迁移、⛔ 重灌数据,
+-- 只**追加**本文件的 `ALTER TABLE … ADD COLUMN IF NOT EXISTS`,实表补齐后代码与文件重新一致。
+--
+-- 既有行数实测=0(`uds_apply.py --ddl` 的回读),故⛔ 写回填分支:
+-- `DEFAULT now()` 加列即满足 NOT NULL,没有历史行需要折算。
+-- ⚠️ 若 prod 侧也存在同一漂移,须按业主「prod ⛔ DDL」裁定走**上线申请**,本文件只管 dev。
+
+ALTER TABLE bos_audit_log
+    ADD COLUMN IF NOT EXISTS occurred_at TIMESTAMPTZ NOT NULL DEFAULT now();
+
+COMMENT ON COLUMN bos_audit_log.occurred_at IS '动作发生时刻(读侧统一按这一列排序/展示);`created_at` 是落库时刻的 BIGINT 秒,二者口径不同、⛔ 混用';

+ 48 - 0
src/migrations/dev/20261107000005_bos_region_meta.sql

@@ -0,0 +1,48 @@
+-- 层级真源表 bos_region_meta(✅ 2026-11-01 业主定案 U-02=**必建**,原「退化才建」作废)
+-- 设计口径真源:总则§5.3 / 05-数据建模总则与跨域表.md:44 / 第 1 册§5.1(`KLT-T225` 服务端硬校验)
+--   bos_region_meta(node_id, level, path_name, synced_at)
+--   =区域节点**自身业务属性(层级类型)的唯一落地位**;⛔ 区域归属副本、⛔ 层次结构副本
+-- ⚠️ 本表⛔ `depth`、⛔ `parent_id`:父子几何唯一真源=平台资源树,层级**⛔ 由 `depth` 推导**
+--    (业主 U-02 明令,18 册§18.1)⇒ 运行时判级只允许读本表 `level`。
+-- ⚠️ 平台 `/admin/exec_ddl@v1` 会静默丢弃 `NOT NULL` 与 `DEFAULT`(18 册第十四轮在册)
+--    ⇒ 下列约束表达的是**设计口径**,实际生效性以应用后回读为准。
+-- ⛔ 历史迁移不可改,本表以**追加新迁移**方式补建(18 册第十六轮业主定案)。
+
+CREATE TABLE IF NOT EXISTS bos_region_meta (
+    node_id VARCHAR(64) PRIMARY KEY,
+    level VARCHAR(8) NOT NULL,
+    path_name VARCHAR(512) NULL,
+    synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+    CONSTRAINT ck_bos_region_meta_level CHECK (level IN ('省', '市', '区县'))
+);
+CREATE INDEX IF NOT EXISTS idx_bos_region_meta_level ON bos_region_meta (level);
+
+COMMENT ON TABLE bos_region_meta IS '区域节点层级真源(业务侧自持,⛔ 区域归属副本、⛔ 由平台 depth 推导)';
+COMMENT ON COLUMN bos_region_meta.node_id IS '平台资源树节点 ID(与 dim_node_ancestor.node_id 同源)';
+COMMENT ON COLUMN bos_region_meta.level IS '层级类型:省/市/区县(值域见 ck_bos_region_meta_level)';
+COMMENT ON COLUMN bos_region_meta.path_name IS '路径展示名(业务侧自持;空=待建档补录)';
+COMMENT ON COLUMN bos_region_meta.synced_at IS '本行层级信息的维护时间';
+
+-- ---------------------------------------------------------------------------
+-- 层级初值(**人工录入的业务事实**,⛔ 运行时按 depth 自动推导)
+--
+-- ⚠️ 诚实性声明:以下 11 行的 `level` 由本轮按**节点编码语义**(`*p`=省级节点、
+--    `sh`/`su`/`gz`=市、`lg`/`mh`/`pd`/`ks`/`th`=区县)人工判读录入,**待业务方在
+--    OR-01 区域建档页复核改判**;`path_name` 暂以节点 ID 链填充(区域树零业务字段、
+--    平台未向 BOS 暴露节点中文名,BOS 侧无从取真中文名 ⇒ ⛔ 编中文名)。
+-- ⚠️ `V-ALL`(全网虚拟根)**不落本表**:`省/市/区县` 值域容不下它,且它不经 OR-01 建档
+--    ⇒ 层级检查(`KLT-R106` 父节点未定级⇒新建子节点被拒)对虚拟根豁免,本轮在册待裁。
+-- ---------------------------------------------------------------------------
+INSERT INTO bos_region_meta (node_id, level, path_name, synced_at) VALUES
+    ('shp', '省', 'shp', NOW()),
+    ('jsp', '省', 'jsp', NOW()),
+    ('gdp', '省', 'gdp', NOW()),
+    ('sh', '市', 'shp/sh', NOW()),
+    ('su', '市', 'jsp/su', NOW()),
+    ('gz', '市', 'gdp/gz', NOW()),
+    ('lg', '区县', 'shp/sh/lg', NOW()),
+    ('mh', '区县', 'shp/sh/mh', NOW()),
+    ('pd', '区县', 'shp/sh/pd', NOW()),
+    ('ks', '区县', 'jsp/su/ks', NOW()),
+    ('th', '区县', 'gdp/gz/th', NOW())
+ON CONFLICT (node_id) DO NOTHING;

+ 33 - 0
src/migrations/dev/20261107000006_customer_contact_columns.sql

@@ -0,0 +1,33 @@
+-- ============================================================
+-- KLT 运营支撑系统 · dev 骨架第 6 件补列(客户写侧缺列,业主裁定 A 案的续件)
+-- 目的:客户建档/资料修改的契约字段在 dev 骨架无落点 ⇒ 补列,⛔ "丢字段落库"
+-- 依据:
+--   · 业主裁定(方案 A)="缺列即补列"(⛔ 拒写/⛔ 丢字段),口径见
+--     docs/详细设计说明书/00-总则与全局约定/18-未决事项与口径差异登记.md §18.3 第十五轮;
+--   · 范围纪律=只补 ① openapi **写请求体已出现**的字段 ② 设计里有但契约没提的一律⛔ 补
+--     (同 20261107000002_bos_write_gap_columns.sql:16-19)。
+-- 本件补的列(四条全部命中 ①):
+--   customer.contact_name   ← openapi `customer/create@v1`/`customer/update@v1` `contact_name`
+--   customer.contact_mobile ← 同上 `contact_mobile`
+--   customer.address        ← 同上 `address`
+--   customer.row_version    ← openapi `customer/update@v1` `row_version`(乐观锁版本(若启用))
+-- 有意**未**补(随本轮登记,⛔ 用补列绕过业务未定的口径):
+--   · `identity_no_cipher`/`identity_no_hash` 两列**已存在**(第 1 件:226-227),缺的是
+--     加密与 HMAC 通路——全仓⛔ 任何加解密/HMAC 实现 ⇒ ⛔ 在这里造一个"看着像密文"的列,
+--     也⛔ 把明文识别号写进这两列;
+--   · `ops_team_ids` 落 `customer_team_belong`(表已具备),但 `ops_team` **无团队类型列**
+--     ⇒ 不变式 I3(常规归属恰 1 条/施工至多 1 条)在 dev 不可判定,类型口径待业主定;
+--   · `parent_node_id`/`mount_request_id` 落 `customer_region_mount`(表已具备),⛔ 重复建列。
+-- ⚠️ 只增列、⛔ 破坏性操作;⛔ 改历史迁移,本件为新追加。
+-- 上线前须人工执行(dev 经 UDS path 型 DDL:temp/uds_apply.py)。
+-- ============================================================
+
+ALTER TABLE customer ADD COLUMN IF NOT EXISTS contact_name   VARCHAR(128) NULL;
+ALTER TABLE customer ADD COLUMN IF NOT EXISTS contact_mobile VARCHAR(32)  NULL;
+ALTER TABLE customer ADD COLUMN IF NOT EXISTS address        VARCHAR(512) NULL;
+ALTER TABLE customer ADD COLUMN IF NOT EXISTS row_version    INT NOT NULL DEFAULT 1;
+
+COMMENT ON COLUMN customer.contact_name   IS '联系人姓名(openapi customer/create/update 同名入参,可空)';
+COMMENT ON COLUMN customer.contact_mobile IS '联系电话(openapi 同名入参,可空;⛔ 回显给无凭证查看权的角色)';
+COMMENT ON COLUMN customer.address        IS '注册地址(openapi 同名入参,可空)';
+COMMENT ON COLUMN customer.row_version    IS '乐观锁版本(openapi customer/update `row_version`=「若启用」⇒ 调用方带则必比、不带则跳过并在出参标注;每次改写 +1)';

+ 33 - 0
src/migrations/dev/20261108000001_account_status_row_version.sql

@@ -0,0 +1,33 @@
+-- 2026-11-08 账号域写侧补列+硬约束(组织§4 账号管理/OR-06)
+--
+-- 背景:`bos_user_binding` dev 骨架只有 `role_code/subject_type/subject_id` 等绑定列,
+-- ⛔ 账号启停状态列、⛔ 乐观锁列 ⇒ 「运营侧停用成员账号」无处落库、并发改无兜底。
+-- 本轮补:① `status`(成员账号启停)② `row_version`(乐观锁)③ 运营商对账账号部分唯一索引。
+--
+-- ⚠️ exec_ddl 已知坑:会静默丢弃 `NOT NULL`/`DEFAULT`/`CHECK` ⇒ 以下列即使写了
+-- `NOT NULL DEFAULT`,实际表结构里仍可能是可空、无默认。代码侧**必须显式写入**
+-- `status='active'` 与 `row_version=1`,⛔ 依赖数据库默认值。
+--
+-- 幂等:全部 `IF NOT EXISTS`,可重复执行(`temp/uds_apply.py --ddl`)。
+-- ⚠️ 应用后须 `docker restart seoh-uds-gateway`(ALTER 后 plan 缓存污染)。
+
+-- ── bos_user_binding:启停状态 + 乐观锁 ────────────────────────────
+ALTER TABLE bos_user_binding ADD COLUMN IF NOT EXISTS status      VARCHAR(16) NOT NULL DEFAULT 'active';
+ALTER TABLE bos_user_binding ADD COLUMN IF NOT EXISTS row_version INTEGER     NOT NULL DEFAULT 1;
+COMMENT ON COLUMN bos_user_binding.status IS '成员账号启停状态:active(在用)/disabled(已停用);客户主账号的激活态在 bos_account_ext.status(issued/issuing/activated),与本列正交';
+COMMENT ON COLUMN bos_user_binding.row_version IS '乐观锁版本号,UPDATE 时 WHERE row_version=:old 并 +1,命中 0 行 ⇒ KLT-S407 并发冲突';
+
+-- ── OR-06:一家运营商至多一个对账账号(subject_type='operator')────────
+CREATE UNIQUE INDEX IF NOT EXISTS uq_bos_user_binding_one_recon_per_operator
+    ON bos_user_binding (subject_id)
+    WHERE subject_type = 'operator';
+COMMENT ON INDEX uq_bos_user_binding_one_recon_per_operator IS 'OR-06 硬兜底:同一运营商至多一对账账号;前置 COUNT 守卫仍保留(返回可读文案,不把唯一冲突当 500)';
+
+-- ── 激活码/登录限流桶(组织§4.3 限流行:按来源 IP+码的固定窗口,⛔ 失败计数、⛔ 锁死)──
+CREATE TABLE IF NOT EXISTS rate_limit_bucket (
+    bucket_key   VARCHAR(128) PRIMARY KEY,
+    window_start TIMESTAMPTZ  NOT NULL,
+    count        BIGINT       NOT NULL DEFAULT 0
+);
+COMMENT ON TABLE rate_limit_bucket IS '激活码与登录限流计数(固定窗口);bucket_key=`ip|code` 或 `ip|login`,窗口长度在代码侧按 action 决定';
+COMMENT ON COLUMN rate_limit_bucket.window_start IS '窗口起点;代码侧取 `now() - window_size` 之前的桶视为过期、整桶重置';

+ 22 - 0
src/migrations/dev/20261108000001_ent_team_remark.sql

@@ -0,0 +1,22 @@
+-- 2026-11-08 运营团队(ent_team)补「备注」列(业主当日裁定)
+--
+-- 起因(`PG-7`,见 docs/SEOH平台交互/提请平台交付与支持-页面取数缺口十项(2026-11-08).md):
+-- 原型运营团队页面三处消费「备注」(弹窗输入框、列表「按名称 / 备注」关键字筛选、审计前后值),
+-- 而第 1 册 02 册的 `ent_team` 列集里⛔ 这一列 ⇒ 属**在册缺列**,按建议口径补:
+--   `remark VARCHAR(200) NULL`——同域先例=`partner.duty_desc`(档案说明列)。
+-- 列定义真源=第 1 册 02 册 §2.3 `ent_team` 行;筛选谓词与审计口径=第 1 册 05 册 §5.4 OR-09。
+--
+-- ⛔ 本文件同时**明确不给** `ent_team` 加 `settle_mode`/`settle_value`(业主同日裁定=路线 A):
+-- 分成方是封闭的三类(运营商/合伙人/运维团队,第 4 册 §5.1 FN-03「三类档案」、§5.2 归属快照只有
+-- `operator_id`/`partner_id`/`billing_snapshot_customer_team` 三分支、§5.5 计 0 判据只覆盖三张表),
+-- 运营团队⛔ 分成方 ⇒ 给一个⛔ 进算账链路的主体配分成参数=造「可填但⛔ 消费方」的假配置项。
+-- 该两列的消亡走**原型回改**(列表两列、弹窗分成设置区、区域详情「运营团队」标签页两列、审计「分成 …」段),
+-- ⛔ 在此加列占位、⛔ 以"先加列、算账下期补"的过渡态存在。
+--
+-- 幂等:`IF NOT EXISTS`,可重复执行(`temp/uds_apply.py --ddl`)。存量种子行不受影响(新列可空)。
+
+ALTER TABLE ent_team ADD COLUMN IF NOT EXISTS remark VARCHAR(200) NULL;
+
+COMMENT ON COLUMN ent_team.remark IS '备注(选填,≤200 字):随档案新建/编辑读写,变更写审计前后值(记文字);'
+    '列表「按名称 / 备注」关键字筛选=team_name ILIKE %q% OR remark ILIKE %q%;'
+    '⛔ 参与唯一键、⛔ 参与任何算账与判权谓词;写权限随档案写入口(限总运营)';

+ 1 - 0
src/modules/account/Cargo.toml

@@ -20,3 +20,4 @@ async-trait = { workspace = true }
 thiserror = { workspace = true }
 tracing = { workspace = true }
 chrono = { workspace = true }
+rand = { workspace = true }

+ 513 - 49
src/modules/account/src/handlers/account.rs

@@ -3,9 +3,130 @@ use axum::response::Response;
 use bos_activation::{assert_export_scope, assert_reset_allowed, ActivationStatus, ExportCodesRequest};
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
 use bos_api::AppState;
-use bos_core::RoleCode;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, KltCode, RoleCode};
+use bos_platform::audit::AuditEvent;
+use bos_platform::clients::uds::{de, DmlStatement};
 use serde::Deserialize;
-use serde_json::json;
+use serde_json::{json, Value};
+
+use super::listq::{mask_mobile, total, Params};
+
+/// 成员账号列表(`bos.account.list@v1`)。
+///
+/// 列口径(`用例说明/04_组织与区域.md:666`):姓名/登录名/手机号/主-子账号标记/状态。
+/// ⚠️ `bos_user_binding` ⛔ 姓名列(只有 `username`/`mobile`),"姓名"暂回 `null`,
+/// 已登总则§18.3;手机号⛔ 明文(需求§5.4 列表页掩码)。
+#[derive(Deserialize)]
+pub struct AccountListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub role_code: Option<String>,
+    pub subject_type: Option<String>,
+    pub status: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct AccountRow {
+    #[serde(deserialize_with = "de::as_string")]
+    user_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    username: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    mobile: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    role_code: String,
+    #[serde(deserialize_with = "de::as_string")]
+    subject_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    subject_id: String,
+    entry_only: Option<bool>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    status: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    created_at: Option<String>,
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<AccountListReq>,
+) -> Response {
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+
+    // 可见范围:运维侧看全量;团队侧只看本团队成员;其余⛔ 该页。
+    match auth.role {
+        RoleCode::Admin | RoleCode::OpsMain | RoleCode::OpsSub => {}
+        RoleCode::TeamLead | RoleCode::Ops => {
+            if auth.subject.subject_type != "ent_team" && auth.subject.subject_type != "ops_team" {
+                return json_ok(json!({ "items": [], "total": 0, "page": body.pg.page, "page_size": body.pg.page_size }));
+            }
+            let team = p.push(Value::String(auth.subject.subject_id.clone()));
+            preds.push(format!(
+                "b.user_id IN (SELECT user_id FROM ent_team_member WHERE team_id = {team}::text \
+                 UNION SELECT user_id FROM ops_member WHERE team_id = {team}::text)"
+            ));
+        }
+        _ => return json_err(bos_core::BosError::forbidden_role("无权查看成员账号列表")),
+    }
+
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        preds.push(format!("(b.username_norm LIKE {k} OR b.mobile LIKE {k})"));
+    }
+    if let Some(r) = p.push_eq(body.role_code.as_deref()) {
+        preds.push(format!("b.role_code = {r}::text"));
+    }
+    if let Some(s) = p.push_eq(body.subject_type.as_deref()) {
+        preds.push(format!("b.subject_type = {s}::text"));
+    }
+    if let Some(s) = p.push_eq(body.status.as_deref()) {
+        preds.push(format!("e.status = {s}::text"));
+    }
+
+    let from_where = format!(
+        "FROM bos_user_binding b LEFT JOIN bos_account_ext e ON e.user_id = b.user_id {}",
+        p.where_clause(&preds)
+    );
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT b.user_id, b.username, b.mobile, b.role_code, b.subject_type, b.subject_id, \
+         b.entry_only, e.status, b.created_at {from_where} \
+         ORDER BY b.created_at DESC, b.user_id DESC LIMIT {lim} OFFSET {off}"
+    );
+    let rows = match state.db.query_all::<AccountRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            json!({
+                "user_id": r.user_id,
+                "display_name": Value::Null,
+                "username": r.username,
+                "mobile": mask_mobile(r.mobile.as_deref()),
+                "role_code": r.role_code,
+                "subject_type": r.subject_type,
+                "subject_id": r.subject_id,
+                "account_kind": if r.entry_only.unwrap_or(false) { "entry" } else if r.role_code == "sub" { "sub" } else { "primary" },
+                "status": r.status.unwrap_or_else(|| "active".to_string()),
+                "created_at": r.created_at,
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
+}
 
 #[derive(Deserialize)]
 pub struct ProvisionReq {
@@ -16,57 +137,238 @@ pub struct ProvisionReq {
     pub mobile: Option<String>,
 }
 
+/// I5:角色↔主体一致性(组织§4.2 管线第 3 步)。
+/// 返回该角色允许绑定的 `subject_type` 集合;请求入参不在其内 ⇒ `KLT-I105`。
+fn allowed_subject_types(role: RoleCode) -> &'static [&'static str] {
+    match role {
+        RoleCode::Admin => &["platform"],
+        RoleCode::OpsMain | RoleCode::OpsSub => &["ops_team"],
+        RoleCode::TeamLead | RoleCode::Ops => &["ops_team", "ent_team"],
+        RoleCode::Enterprise => &["ent_team", "customer"],
+        RoleCode::Partner => &["partner"],
+        RoleCode::Operator => &["operator"],
+        RoleCode::Sub => &["sub_account"],
+    }
+}
+
+/// I5:绑定的主体行必须存在(团队/合作伙伴/运营商/客户)。
+/// `platform`(admin)无业务主体行 ⇒ 跳过。
+async fn assert_subject_exists(
+    state: &AppState,
+    subject_type: &str,
+    subject_id: &str,
+) -> Result<(), BosError> {
+    let (table, id_col) = match subject_type {
+        "ops_team" => ("ops_team", "team_id"),
+        "ent_team" => ("ent_team", "team_id"),
+        "partner" => ("partner", "partner_id"),
+        "operator" => ("operator", "operator_id"),
+        "customer" => ("customer", "customer_id"),
+        "sub_account" => ("sub_account", "sub_account_id"),
+        "platform" => return Ok(()),
+        other => {
+            return Err(BosError::bad_params(format!(
+                "未知 subject_type={other}(I5 一致性校验)"
+            )))
+        }
+    };
+    let sql = format!("SELECT 1 FROM {table} WHERE {id_col} = $1::text LIMIT 1");
+    let exists = state
+        .db
+        .query_one::<Value>(&sql, &[Value::String(subject_id.to_string())])
+        .await?
+        .is_some();
+    if !exists {
+        return Err(BosError::klt(
+            KltCode::I105,
+            format!("绑定主体不存在:{subject_type}/{subject_id}"),
+        ));
+    }
+    Ok(())
+}
+
+/// 唯一性守卫用点查:查不到=不存在,查失败⛔ 当不存在(否则会写出重复账号)。
+async fn find_one(
+    state: &AppState,
+    sql: &str,
+    params: [serde_json::Value; 1],
+) -> Result<Option<serde_json::Value>, BosError> {
+    state.db.query_one::<serde_json::Value>(sql, &params).await
+}
+
 pub async fn provision(
     State(state): State<AppState>,
     RequireAuth(auth): RequireAuth,
     DataBody(body): DataBody<ProvisionReq>,
 ) -> Response {
     if let Err(e) = auth.require_roles(&[
-        RoleCode::Admin, RoleCode::OpsMain, RoleCode::TeamLead, RoleCode::Ops,
+        RoleCode::Admin,
+        RoleCode::OpsMain,
+        RoleCode::TeamLead,
+        RoleCode::Ops,
     ]) {
         return json_err(e);
     }
-    let username_norm = body.username.trim().to_lowercase();
+    match do_provision(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_provision(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    body: ProvisionReq,
+) -> Result<Value, BosError> {
+    let username = body.username.trim().to_string();
+    let username_norm = username.to_lowercase();
     if username_norm.is_empty() {
-        return json_err(bos_core::BosError::klt(bos_core::KltCode::B001, "登录名不能为空"));
+        return Err(BosError::klt(KltCode::B001, "登录名不能为空"));
+    }
+    let mobile = body
+        .mobile
+        .map(|m| m.trim().to_string())
+        .filter(|m| !m.is_empty());
+    if let Some(m) = &mobile {
+        if m.len() != 11 || !m.chars().all(|c| c.is_ascii_digit()) {
+            return Err(BosError::bad_params(format!("手机号须为 11 位数字,收到「{m}」")));
+        }
     }
-    // 唯一性守卫先于平台调用
-    let exists: Option<(i64,)> = sqlx::query_as(
-        "SELECT user_id FROM bos_user_binding WHERE username_norm = $1",
+    let role = RoleCode::parse(&body.role_code).ok_or_else(|| {
+        BosError::bad_params(format!("未知 role_code={}", body.role_code))
+    })?;
+    // I5 角色↔主体一致性
+    if !allowed_subject_types(role).contains(&body.subject_type.as_str()) {
+        return Err(BosError::klt(
+            KltCode::I105,
+            format!(
+                "角色 {} 不允许绑定到主体类型 {}",
+                body.role_code, body.subject_type
+            ),
+        ));
+    }
+    assert_subject_exists(state, &body.subject_type, &body.subject_id).await?;
+
+    // 唯一性守卫先于平台调用(组织§2.1;DB 唯一索引兜底)
+    if find_one(
+        state,
+        "SELECT user_id FROM bos_user_binding WHERE username_norm = $1::text",
+        [json!(&username_norm)],
     )
-    .bind(&username_norm)
-    .fetch_optional(&state.pool)
-    .await
-    .ok()
-    .flatten();
-    if exists.is_some() {
-        return json_err(bos_core::BosError::klt(bos_core::KltCode::B001, "登录名已存在"));
-    }
-    if let Some(m) = &body.mobile {
-        let exists_m: Option<(i64,)> = sqlx::query_as(
-            "SELECT user_id FROM bos_user_binding WHERE mobile = $1",
+    .await?
+    .is_some()
+    {
+        return Err(BosError::klt(KltCode::B001, "登录名已存在"));
+    }
+    if let Some(m) = &mobile {
+        if find_one(
+            state,
+            "SELECT user_id FROM bos_user_binding WHERE mobile = $1::text",
+            [json!(m)],
         )
-        .bind(m)
-        .fetch_optional(&state.pool)
-        .await
-        .ok()
-        .flatten();
-        if exists_m.is_some() {
-            return json_err(bos_core::BosError::klt(bos_core::KltCode::B002, "手机号已存在"));
+        .await?
+        .is_some()
+        {
+            return Err(BosError::klt(KltCode::B002, "手机号已存在"));
         }
     }
-    match state
+
+    // 系统自动建档通道⛔ 初始密码 ⇒ 建无密码用户、status=issued、平台发激活码。
+    // ⚠️ BOS 从不持有激活码明文(U-05);code_hmac/code_cipher 由平台侧凭证链路产生,
+    // 本期本地只落 status/expire_date 占位,明文核销归平台 `bootstrap_credential/verify@v1`。
+    let created = state
         .platform
         .user_create(json!({
-            "username": body.username,
-            "mobile": body.mobile,
-            "role_hint": body.role_code,
+            "scope_type": "end_user",
+            "scope_id": state.project_id.clone(),
+            "project_id": state.project_id.clone(),
+            "user_type": "end_user",
+            "env": state.data_env.clone(),
+            "stage": state.seoh_env.clone(),
+            "username": username.clone(),
+            "phone": mobile.clone().unwrap_or_default(),
         }))
         .await
-    {
-        Ok(v) => json_ok(v),
-        Err(e) => json_err(e),
+        .map_err(|e| BosError::internal(format!("平台建号未成功,本地⛔ 写任何数据:{e}")))?;
+    let user_id = created
+        .pointer("/data/id")
+        .and_then(Value::as_str)
+        .unwrap_or_default()
+        .to_string();
+    if user_id.is_empty() {
+        return Err(BosError::internal(format!(
+            "平台建号应答未回 user_id,本地⛔ 写:{created}"
+        )));
+    }
+
+    // 同一次 dml_batch 写 binding + ext(原子提交;任一失败整批回滚)。
+    // ⚠️ exec_ddl 丢弃 `NOT NULL DEFAULT` ⇒ status/row_version 必须显式写值。
+    let stmts = vec![
+        DmlStatement::new(
+            "INSERT INTO bos_user_binding (user_id, scope_type, scope_id, role_code, subject_type, \
+             subject_id, username, username_norm, mobile, entry_only, status, row_version) \
+             VALUES ($1::int8, $2::text, $3::text, $4::text, $5::text, $6::text, $7::text, \
+             $8::text, $9::text, FALSE, 'active', 1)",
+            vec![
+                Value::String(user_id.clone()),
+                Value::String("end_user".to_string()),
+                Value::String(state.project_id.clone()),
+                Value::String(body.role_code.clone()),
+                Value::String(body.subject_type.clone()),
+                Value::String(body.subject_id.clone()),
+                Value::String(username.clone()),
+                Value::String(username_norm.clone()),
+                mobile.clone().map(Value::String).unwrap_or(Value::Null),
+            ],
+        ),
+        DmlStatement::new(
+            "INSERT INTO bos_account_ext (user_id, status, key_version) \
+             VALUES ($1::int8, 'issued', 1)",
+            vec![Value::String(user_id.clone())],
+        ),
+    ];
+    let results = state.db.dml_batch(&stmts).await?;
+    for (i, r) in results.iter().enumerate() {
+        if r.affected_rows != Some(1) {
+            return Err(BosError::internal(format!(
+                "账号落库第 {} 条语句 affected_rows={:?} ⛔ 1⇒ ⛔ 把 `10000` 当成功",
+                i + 1,
+                r.affected_rows
+            )));
+        }
     }
+
+    // 审计(合规留痕;不阻塞主流程:写失败记 note 但仍返成功)
+    let audit_written = state
+        .db
+        .write_audit(&AuditEvent {
+            actor_user_id: auth.user_id.clone(),
+            action: "bos.account.provision".to_string(),
+            resource_type: "account".to_string(),
+            resource_id: user_id.clone(),
+            before: None,
+            after: Some(json!({
+                "username": username,
+                "role_code": body.role_code,
+                "subject_type": body.subject_type,
+                "subject_id": body.subject_id,
+                "mobile": mobile,
+            })),
+            detail: None,
+        })
+        .await
+        .is_ok();
+
+    Ok(json!({
+        "user_id": user_id,
+        "username": username_norm,
+        "role_code": body.role_code,
+        "subject_type": body.subject_type,
+        "subject_id": body.subject_id,
+        "status": "issued",
+        "plaintext_once": Value::Null,
+        "audit_written": audit_written,
+    }))
 }
 
 #[derive(Deserialize)]
@@ -76,13 +378,109 @@ pub struct StatusReq {
 }
 
 pub async fn update_status(
+    State(state): State<AppState>,
     RequireAuth(auth): RequireAuth,
     DataBody(body): DataBody<StatusReq>,
 ) -> Response {
+    if let Err(e) = auth.require_roles(&[
+        RoleCode::Admin,
+        RoleCode::OpsMain,
+        RoleCode::TeamLead,
+        RoleCode::Ops,
+    ]) {
+        return json_err(e);
+    }
+    match do_update_status(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_update_status(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    body: StatusReq,
+) -> Result<Value, BosError> {
     if body.user_id == auth.user_id {
-        return json_err(bos_core::BosError::bad_params("不能停用当前登录账号"));
+        return Err(BosError::bad_params("不能停用当前登录账号"));
+    }
+    let new_status = match body.status.as_str() {
+        "active" | "disabled" => body.status.clone(),
+        other => {
+            return Err(BosError::bad_params(format!(
+                "status 只允许 active/disabled,收到「{other}」"
+            )))
+        }
+    };
+    // 目标在册
+    let cur = find_one(
+        state,
+        "SELECT row_version FROM bos_user_binding WHERE user_id = $1::int8",
+        [json!(&body.user_id)],
+    )
+    .await?
+    .ok_or_else(|| BosError::not_found(format!("账号 {} 不存在", body.user_id)))?;
+    let old_rv: i64 = cur
+        .get("row_version")
+        .and_then(Value::as_i64)
+        .unwrap_or(1);
+    let old_status = find_one(
+        state,
+        "SELECT status FROM bos_user_binding WHERE user_id = $1::int8",
+        [json!(&body.user_id)],
+    )
+    .await?
+    .and_then(|r| r.get("status").and_then(Value::as_str).map(String::from))
+    .unwrap_or_else(|| "active".to_string());
+
+    // 乐观锁 UPDATE
+    let sql = "UPDATE bos_user_binding SET status = $1::text, row_version = row_version + 1 \
+               WHERE user_id = $2::int8 AND row_version = $3::int8";
+    let results = state
+        .db
+        .dml_batch(&[DmlStatement::new(
+            sql,
+            vec![
+                Value::String(new_status.clone()),
+                Value::String(body.user_id.clone()),
+                Value::from(old_rv),
+            ],
+        )])
+        .await?;
+    if results.first().and_then(|r| r.affected_rows) != Some(1) {
+        return Err(BosError::biz(
+            bos_core::ErrorCode::ConflictS407,
+            "账号状态被并发修改,请刷新后重试",
+        ));
     }
-    json_ok(json!({ "user_id": body.user_id, "status": body.status }))
+
+    // 平台侧停用⛔ 服务票通路(`iam-user` 停用类接口只认 Bearer 用户令牌)⇒ 诚实标记未同步。
+    let platform_sync = json!({
+        "applied": false,
+        "reason": "平台 iam-user 停用类接口仅接受 Bearer 用户令牌(x-internal-callers=[]),\
+                   服务身份无合法调用通路;本地状态已落库,平台侧停用待人工或用户侧触发。"
+    });
+
+    let audit_written = state
+        .db
+        .write_audit(&AuditEvent {
+            actor_user_id: auth.user_id.clone(),
+            action: "bos.account.update_status".to_string(),
+            resource_type: "account".to_string(),
+            resource_id: body.user_id.clone(),
+            before: Some(json!({ "status": old_status })),
+            after: Some(json!({ "status": new_status })),
+            detail: None,
+        })
+        .await
+        .is_ok();
+
+    Ok(json!({
+        "user_id": body.user_id,
+        "status": new_status,
+        "platform_sync": platform_sync,
+        "audit_written": audit_written,
+    }))
 }
 
 #[derive(Deserialize)]
@@ -92,27 +490,93 @@ pub struct ResetCodeReq {
 
 pub async fn reset_code(
     State(state): State<AppState>,
-    RequireAuth(_auth): RequireAuth,
+    RequireAuth(auth): RequireAuth,
     DataBody(body): DataBody<ResetCodeReq>,
 ) -> Response {
-    let row: Option<(String,)> = sqlx::query_as(
-        "SELECT status FROM bos_account_ext WHERE user_id = $1",
+    if body.user_id.parse::<i64>().is_err() {
+        return json_err(BosError::bad_params("invalid user_id"));
+    }
+    match do_reset_code(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+/// CU-06 重置激活码。
+///
+/// 闸门(U-03 定案):`status=activated` ⇒ `KLT-A003`,⛔ 不发新码、⛔ 不作废原码、⛔ 不改
+/// `expire_date`、⛔ 不写重置审计。
+///
+/// 未激活侧:按设计应调平台 `revoke@v1`→`issue@v1`→`export@v1` 换新码(三跳均需 Bearer
+/// 用户令牌,`x-internal-callers=[]`)。我方 `AuthContext` ⛔ 持用户令牌 ⇒ 该链路结构性
+/// 不可达 ⇒ 本地只做能做的状态复位(`pwd_set_at=NULL`、`activated_at` 保持、`status` 回
+/// `issued`、`expire_date` 按 TTL 7 天折算),并在出参**诚实**标记 `reissued=false` +
+/// 能力待定理由,⛔ 假回新码。
+async fn do_reset_code(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    body: ResetCodeReq,
+) -> Result<Value, BosError> {
+    let row = find_one(
+        state,
+        "SELECT status FROM bos_account_ext WHERE user_id = $1::int8",
+        [json!(&body.user_id)],
     )
-    .bind(body.user_id.parse::<i64>().unwrap_or(0))
-    .fetch_optional(&state.pool)
-    .await
-    .ok()
-    .flatten();
-    let status = match row.as_ref().map(|r| r.0.as_str()) {
+    .await?
+    .ok_or_else(|| BosError::not_found(format!("账号 {} 无扩展档", body.user_id)))?;
+    let status = match row.get("status").and_then(Value::as_str) {
         Some("activated") => ActivationStatus::Activated,
         Some("issued") => ActivationStatus::Issued,
         Some("issuing") => ActivationStatus::Issuing,
         _ => ActivationStatus::None,
     };
-    if let Err(e) = assert_reset_allowed(status) {
-        return json_err(e);
+    assert_reset_allowed(status)?; // activated ⇒ A003
+
+    // 本地状态复位(能做的部分):pwd_set_at=NULL、status=issued、expire_date=今天+7 天。
+    // ⚠️ `expire_date` 是 DATE 列;UDS 对 date 参数同样静默落 NULL ⇒ 走 SQL 文本表达式。
+    let sql = "UPDATE bos_account_ext \
+               SET status = 'issued', pwd_set_at = NULL, \
+                   expire_date = (CURRENT_DATE + INTERVAL '7 days')::date \
+               WHERE user_id = $1::int8";
+    let results = state
+        .db
+        .dml_batch(&[DmlStatement::new(
+            sql,
+            vec![Value::String(body.user_id.clone())],
+        )])
+        .await?;
+    if results.first().and_then(|r| r.affected_rows) != Some(1) {
+        return Err(BosError::internal(format!(
+            "激活码重置本地状态未落库(affected_rows={:?})",
+            results.first().and_then(|r| r.affected_rows)
+        )));
     }
-    json_ok(json!({ "user_id": body.user_id, "status": "issued", "plaintext_once": null }))
+
+    let audit_written = state
+        .db
+        .write_audit(&AuditEvent {
+            actor_user_id: auth.user_id.clone(),
+            action: "bos.account.reset_code".to_string(),
+            resource_type: "account".to_string(),
+            resource_id: body.user_id.clone(),
+            before: Some(json!({ "status": "issued", "pwd_set_at_reset": false })),
+            after: Some(json!({ "status": "issued", "pwd_set_at_reset": true })),
+            detail: Some(json!({ "reissued": false, "reason": "platform_bootstrap_credential_unreachable" })),
+        })
+        .await
+        .is_ok();
+
+    Ok(json!({
+        "user_id": body.user_id,
+        "status": "issued",
+        "plaintext_once": Value::Null,
+        "reissued": false,
+        "capability_pending": true,
+        "reason": "换新码需调平台 bootstrap_credential/revoke→issue→export@v1,三跳均需 Bearer 用户令牌\
+                   (x-internal-callers=[]),服务身份无合法调用通路;本地仅复位 pwd_set_at/status,\
+                   新码发放待平台侧或用户侧触发。",
+        "audit_written": audit_written,
+    }))
 }
 
 pub async fn export_codes(
@@ -127,7 +591,7 @@ pub async fn export_codes(
     }
     json_ok(json!({
         "status": "capability_pending",
-        "message": "明文导出依赖 bootstrap_credential/export@v1;U-84 部署前按能力待定提示",
+        "message": "明文导出依赖 bootstrap_credential/export@v1;U-98(该导出权限键在我方无合法持有主体)未定前按能力待定提示,⛔ 不得改用内部令牌",
         "user_ids": body.user_ids,
     }))
 }
@@ -144,7 +608,7 @@ pub async fn change_password(
     DataBody(body): DataBody<ChangePwd>,
 ) -> Response {
     if body.old_password == body.new_password {
-        return json_err(bos_core::BosError::bad_params("新旧密码相同,不保存"));
+        return json_err(BosError::klt(KltCode::T223, "新密码不能与原密码相同"));
     }
     match state
         .platform

+ 83 - 10
src/modules/account/src/handlers/activation.rs

@@ -1,21 +1,94 @@
 use axum::extract::State;
+use axum::http::HeaderMap;
 use axum::response::Response;
-use bos_activation::{assert_rate_limit, VerifyActivationRequest};
-use bos_api::extract::{json_err, json_ok, DataBody};
+use bos_activation::VerifyActivationRequest;
+use bos_api::extract::{json_err, DataBody};
 use bos_api::AppState;
-use serde_json::json;
+use bos_core::{BosError, KltCode};
+use bos_platform::clients::uds::DmlStatement;
 
+/// 从请求头取来源 IP(X-Forwarded-For 首段 → X-Real-IP → unknown)。
+fn client_ip(headers: &HeaderMap) -> String {
+    if let Some(v) = headers
+        .get("x-forwarded-for")
+        .and_then(|v| v.to_str().ok())
+        .and_then(|s| s.split(',').next())
+    {
+        return v.trim().to_string();
+    }
+    if let Some(v) = headers
+        .get("x-real-ip")
+        .and_then(|v| v.to_str().ok())
+    {
+        return v.trim().to_string();
+    }
+    "unknown".to_string()
+}
+
+/// 固定窗口限流(按 `bucket_key`)。返回 `Ok(true)`=放行并已计数,`Ok(false)`=超限。
+///
+/// 原子 upsert:`ON CONFLICT DO UPDATE … WHERE count < limit OR window_expired`。
+/// `affected_rows=0` ⇒ 桶已满且窗口未过期 ⇒ 拒。⛔ 用 SELECT-then-UPDATE(会让并发钻空子)。
+async fn rate_limit_hit(
+    state: &AppState,
+    bucket_key: &str,
+    limit: i64,
+) -> Result<bool, BosError> {
+    // ⚠️ UDS SQL 解析器⛔ 支持 `INSERT INTO t AS alias (...)`,故用表全名引用冲突行。
+    let sql = "INSERT INTO rate_limit_bucket (bucket_key, window_start, count) \
+               VALUES ($1::text, now(), 1) \
+               ON CONFLICT (bucket_key) DO UPDATE \
+               SET count = CASE WHEN rate_limit_bucket.window_start < (now() - INTERVAL '60 seconds') THEN 1 \
+                                ELSE rate_limit_bucket.count + 1 END, \
+                   window_start = CASE WHEN rate_limit_bucket.window_start < (now() - INTERVAL '60 seconds') \
+                                       THEN now() ELSE rate_limit_bucket.window_start END \
+               WHERE rate_limit_bucket.count < $2::bigint \
+                  OR rate_limit_bucket.window_start < (now() - INTERVAL '60 seconds')";
+    let results = state
+        .db
+        .dml_batch(&[DmlStatement::new(
+            sql,
+            vec![
+                serde_json::Value::String(bucket_key.to_string()),
+                serde_json::Value::from(limit),
+            ],
+        )])
+        .await?;
+    Ok(results.first().and_then(|r| r.affected_rows) == Some(1))
+}
+
+/// 激活码核销(`bos.activation/verify@v1`,免登录)。
+///
+/// 编排(组织§4.3):本地按码定位 → 平台引导凭证消费+设密 → 状态翻 `activated`。
+/// ⚠️ 结构性约束:平台 `bootstrap_credential/verify@v1` 走「经网关 Bearer 用户令牌」通路
+/// (`x-internal-callers=[]`),而本接口免登录、`AuthContext` ⛔ 持用户令牌 ⇒ 该调用在本服务
+/// **不可达**。按总则「依赖不可用 ⇒ 失败关闭」诚实报错,⛔ 假回 `activated=true`。
 pub async fn verify(
     State(state): State<AppState>,
+    headers: HeaderMap,
     DataBody(body): DataBody<VerifyActivationRequest>,
 ) -> Response {
-    let _ = &state;
-    if let Err(e) = assert_rate_limit(0, 30) {
-        return json_err(e);
-    }
     if body.code.trim().is_empty() || body.new_password.len() < 8 {
-        return json_err(bos_core::BosError::bad_params("激活码或密码不合法"));
+        return json_err(BosError::bad_params("激活码或密码不合法"));
     }
-    // 编排:校验本地 hmac → 平台引导凭证消费 → set_password
-    json_ok(json!({ "activated": true }))
+    // 限流:按来源 IP + 码的 60s 固定窗口,>30 ⇒ T222(⛔ 锁账号)。
+    let ip = client_ip(&headers);
+    let bucket = format!("verify|{ip}|{}", body.code.trim());
+    match rate_limit_hit(&state, &bucket, 30).await {
+        Ok(true) => {}
+        Ok(false) => {
+            return json_err(BosError::klt(
+                KltCode::T222,
+                "激活尝试过于频繁,请稍后再试",
+            ));
+        }
+        Err(e) => return json_err(e),
+    }
+
+    // 平台核销链路不可达(见函数级注释)⇒ 失败关闭。
+    json_err(BosError::biz(
+        bos_core::ErrorCode::Downstream,
+        "激活核销依赖平台 bootstrap_credential/verify@v1(需 Bearer 用户令牌),\
+         本服务无合法调用通路(x-internal-callers=[]);请在平台门户完成激活或由运营代办。",
+    ))
 }

+ 240 - 0
src/modules/account/src/handlers/audit.rs

@@ -0,0 +1,240 @@
+//! 审计日志只读检索(SC-04 六列:时间/操作人/操作类型/对象/变更前/变更后)。
+//!
+//! 口径真源:`docs/详细设计说明书/10-第10册-定时任务与审计视图/05-审计日志查看与可见范围谓词.md`
+//! +`06-各角色侧变更记录与检索导出.md`。两条硬口径:
+//! * 分页=时间倒序+`(occurred_at, id)` 游标,⛔ `OFFSET`(大表翻页会漂移且扫全表);
+//! * 检索条件⛔ 拼进 SQL 原文,一律走 `params`。
+//!
+//! ⚠️ `bos_audit_log` **只有表结构、没有 BOS 侧写入口**(全库⛔ `INSERT INTO bos_audit_log`)。
+//! 2026-11-07 实测更正(原登记「恒返回空集」不成立):dev 库该表有 **11 行开发种子**,本接口
+//! 会真把它们查出来,⛔ 把种子行理解成「BOS 写出过流水」⇒ 出参 `message` 显式声明这一边界。
+//!
+//! ⚠️ **两个时间列在 dev 库全为 NULL**:`count(*) WHERE occurred_at IS NULL` 命中全部 11 行。
+//! 根因⛔ 在本模块——`20261107000004` 以 `ADD COLUMN … NOT NULL DEFAULT now()` 追加,但 UDS
+//! `/admin/exec_ddl@v1` **静默丢弃 `NOT NULL` 与 `DEFAULT`**(存量行落 NULL 而非 `now()`)。
+//! ⇒ `occurred_at` 出参回 `null`,且**游标翻页在 `occurred_at` 缺失时不可用**(此时
+//! `next_cursor` 回 `null`,⛔ 造一个翻不动的假游标);写侧通路接通后须由 INSERT 显式带 `occurred_at`。
+
+use axum::extract::State;
+use axum::response::Response;
+use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
+use bos_api::AppState;
+use bos_core::{BosError, KltCode, RoleCode};
+use bos_platform::clients::uds::de;
+use bos_scope::AuthContext;
+use bos_scope::ScopedSelect;
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+use super::listq::{push_in, Params};
+
+/// 单页上限(超出按上限截断,⛔ 报错——翻页是前端的事)。
+const MAX_PAGE_SIZE: i64 = 200;
+
+#[derive(Deserialize)]
+pub struct AuditListReq {
+    /// 游标=上一页末条的 `created_at|id`;首屏不传。
+    pub cursor: Option<String>,
+    #[serde(default = "default_size")]
+    pub page_size: i64,
+    /// 对象类型(=`resource_type`)
+    pub object_type: Option<String>,
+    /// 对象引用(精确定位一条对象的变更流水)
+    pub object_ref: Option<ObjectRef>,
+    pub actor_user_id: Option<String>,
+    pub occurred_from: Option<String>,
+    pub occurred_to: Option<String>,
+    /// 关键字:命中操作人登录名或对象 ID
+    pub keyword: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct ObjectRef {
+    #[serde(rename = "type")]
+    pub kind: String,
+    pub id: String,
+}
+
+fn default_size() -> i64 {
+    20
+}
+
+#[derive(Deserialize)]
+struct AuditRow {
+    #[serde(deserialize_with = "de::as_string")]
+    id: String,
+    /// dev 库全为 NULL(见模块头)⇒ 出参须回 `null` 表示「时刻未知」,⛔ `as_string` 抹成空串。
+    #[serde(deserialize_with = "de::as_opt_string")]
+    occurred_at: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    actor_user_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    actor_username: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    action: String,
+    #[serde(deserialize_with = "de::as_string")]
+    resource_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    resource_id: String,
+    #[serde(default)]
+    before_json: Option<Value>,
+    #[serde(default)]
+    after_json: Option<Value>,
+}
+
+/// `jsonb` 经联邦引擎可能回字符串,取值处⛔ 假定单一形态。
+fn cell(v: Option<Value>) -> Value {
+    match v {
+        Some(Value::String(s)) => serde_json::from_str(&s).unwrap_or(Value::String(s)),
+        Some(v) => v,
+        None => Value::Null,
+    }
+}
+
+/// 可见范围谓词(一期口径,逐角色精细谓词待总则§18.3 定稿):
+/// 运维侧(`admin`/`opsMain`/`opsSub`)=全量;团队侧=本团队成员的操作;
+/// 客户侧(`enterprise`/`sub`/`partner`/`operator`)=可见客户对象的流水。
+async fn visibility(
+    state: &AppState,
+    auth: &AuthContext,
+    p: &mut Params,
+) -> Result<String, BosError> {
+    match auth.role {
+        RoleCode::Admin | RoleCode::OpsMain | RoleCode::OpsSub => Ok("1 = 1".to_string()),
+        RoleCode::TeamLead | RoleCode::Ops => {
+            if auth.subject.subject_type != "ops_team" && auth.subject.subject_type != "ent_team" {
+                return Ok("1 = 0".to_string());
+            }
+            let team = p.push(Value::String(auth.subject.subject_id.clone()));
+            Ok(format!(
+                "a.actor_user_id IN (SELECT user_id FROM ops_member WHERE team_id = {team}::text \
+                 UNION SELECT user_id FROM ent_team_member WHERE team_id = {team}::text)"
+            ))
+        }
+        RoleCode::Enterprise | RoleCode::Sub | RoleCode::Partner | RoleCode::Operator => {
+            let ids = state.scope.visible_customer_ids(auth).await?;
+            let in_pred = push_in(p, "a.resource_id", &ids, "text");
+            Ok(format!("a.resource_type IN ('customer','sub_account') AND {in_pred}"))
+        }
+    }
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<AuditListReq>,
+) -> Response {
+    match query(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn query(state: &AppState, auth: &AuthContext, body: AuditListReq) -> Result<Value, BosError> {
+    let page_size = body.page_size.clamp(1, MAX_PAGE_SIZE);
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+
+    preds.push(visibility(state, auth, &mut p).await?);
+
+    if let Some(t) = p.push_eq(body.object_type.as_deref()) {
+        preds.push(format!("a.resource_type = {t}::text"));
+    }
+    if let Some(r) = &body.object_ref {
+        let t = p.push(Value::String(r.kind.clone()));
+        let i = p.push(Value::String(r.id.clone()));
+        preds.push(format!("a.resource_type = {t}::text AND a.resource_id = {i}::text"));
+    }
+    if let Some(a) = p.push_eq(body.actor_user_id.as_deref()) {
+        preds.push(format!("a.actor_user_id = {a}::bigint"));
+    }
+    // 时间筛选/排序/游标一律落在 `occurred_at`(动作发生时刻)上。
+    // ⚠️ 曾用 `created_at`:① 它是落库时刻,口径不同(模块头的设计口径就是 `occurred_at`);
+    // ② 游标由 `occurred_at|id` 写回、却按 `created_at` 比较 ⇒ 两列不同型时翻页必然错位。
+    // ⚠️ dev 库 `occurred_at` 全为 NULL ⇒ 带时间筛选必然回空集(诚实结果,⛔ 改回 created_at 蒙)。
+    if let Some(f) = p.push_eq(body.occurred_from.as_deref()) {
+        preds.push(format!("a.occurred_at >= {f}::timestamptz"));
+    }
+    if let Some(t) = p.push_eq(body.occurred_to.as_deref()) {
+        preds.push(format!("a.occurred_at <= {t}::timestamptz"));
+    }
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        preds.push(format!("(u.username LIKE {k} OR a.resource_id LIKE {k})"));
+    }
+    if let Some((c, i)) = parse_cursor(body.cursor.as_deref())? {
+        let ph_c = p.push(Value::String(c));
+        let ph_i = p.push(Value::String(i));
+        preds.push(format!(
+            "(a.occurred_at, a.id) < ({ph_c}::timestamptz, {ph_i}::bigint)"
+        ));
+    }
+
+    let from_where = format!(
+        "FROM bos_audit_log a LEFT JOIN bos_user_binding u ON u.user_id = a.actor_user_id \
+         {}",
+        p.where_clause(&preds)
+    );
+    // 多取一条判「还有下一页」,⛔ 靠 `COUNT(1)`+`OFFSET` 翻页。
+    let lim = p.push(Value::from(page_size + 1));
+    // ⚠️ 这里曾漏写 `SELECT` 列表 ⇒ 送进 UDS 的语句以 `FROM` 开头,
+    // 报 `13001 SQL 解析失败: Expected: an SQL statement, found: FROM at Line: 1, Column: 1`,
+    // 即 `/audit/get_list@v1` 自第八轮起**从未返回过一行**(此前只验过路由可达,未验行集)。
+    let sql = format!(
+        "SELECT a.id, a.occurred_at, a.actor_user_id, u.username AS actor_username, a.action, \
+         a.resource_type, a.resource_id, a.before_json, a.after_json \
+         {from_where} ORDER BY a.occurred_at DESC NULLS LAST, a.id DESC LIMIT {lim}::bigint"
+    );
+
+    let rows = state.db.query_all::<AuditRow>(&sql, p.values()).await?;
+    let has_more = rows.len() as i64 > page_size;
+    let items: Vec<Value> = rows
+        .into_iter()
+        .take(page_size as usize)
+        .map(|r| {
+            json!({
+                "occurred_at": r.occurred_at,
+                "actor": { "user_id": r.actor_user_id, "username": r.actor_username },
+                "action": r.action,
+                "object": { "type": r.resource_type, "id": r.resource_id },
+                "before": cell(r.before_json),
+                "after": cell(r.after_json),
+                // 游标真源=`(occurred_at, id)`:`occurred_at` 为 NULL 时**无法构造**,
+                // 回 `null`=「这条翻不动页」,⛔ 拼一个 `"null|id"` 假游标(喂回去会 cast 失败)。
+                "cursor": match r.occurred_at.as_deref() {
+                    Some(t) => json!(format!("{t}|{}", r.id)),
+                    None => Value::Null,
+                },
+            })
+        })
+        .collect();
+    let next_cursor = if has_more && items.len() == page_size as usize {
+        items[items.len() - 1]["cursor"].clone()
+    } else {
+        Value::Null
+    };
+    Ok(json!({
+        "items": items,
+        "page_size": page_size,
+        "next_cursor": next_cursor,
+        // 机器可读的诚实标记:`next_cursor` 为 null 时调用方能区分
+        // 「确实到底了」与「还有行,但 occurred_at 缺失导致翻页不可用」。
+        "cursor_usable": next_cursor.is_string(),
+        "audit_write_ready": false,
+        "message": "行集取自 bos_audit_log;⚠️ BOS 侧⛔ 审计写入通路,dev 库存量行是开发种子示例,\
+                    且 occurred_at 全为 NULL(UDS exec_ddl 丢弃 NOT NULL DEFAULT)⇒ occurred_at 回 null、\
+                    时间筛选与游标翻页不可用。",
+    }))
+}
+
+/// 游标形态非法必须显式失败,⛔ 静默当首屏(用户会停在第一页还以为翻页坏了)。
+fn parse_cursor(raw: Option<&str>) -> Result<Option<(String, String)>, BosError> {
+    let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
+        return Ok(None);
+    };
+    let bad = || BosError::klt(KltCode::B001, "cursor 形态非法");
+    let (c, i) = raw.rsplit_once('|').ok_or_else(bad)?;
+    if c.is_empty() || i.parse::<i64>().is_err() {
+        return Err(bad());
+    }
+    Ok(Some((c.to_string(), i.to_string())))
+}

+ 552 - 9
src/modules/account/src/handlers/catalog.rs

@@ -1,16 +1,559 @@
+//! 套餐档位目录(第 3 册)——读写两侧真落库。
+//!
+//! 列集=一期骨架(`src/migrations/dev/20261104000001_bos_core_tables.sql:365`:
+//! `plan_id/plan_name/plan_kind/annual_price_cents/status/created_at`)
+//! + 2026-11-07 业主裁定的写侧缺口列(`src/migrations/dev/20261107000002_bos_write_gap_columns.sql`:
+//! `use_category`/`sub_account_quota`/`bandwidth_committed`/`bandwidth_up_mbps`/
+//! `bandwidth_down_mbps`/`customer_id`/`row_version`)。
+//! 设计册里更深的列(`monthly_settle_cents`、`sub_mode`、`first_referred_at`、状态流转列)**仍无册内列**
+//! ⇒ 写侧⛔ 写、读侧⛔ 编,差额已登 总则§18.3。
+//!
+//! `customer_name` 不是 `catalog_plan` 的列 ⇒ 走 `customer` 表 `LEFT JOIN`(`customer_id` 现已在册)。
+//!
+//! 写侧三条硬口径:
+//! * `plan_id` 走 [`listq::next_seq`] 年度发号(`P-{:06}`),⛔ 由前端传入;
+//! * `qualify()` 会把 `DO UPDATE` 后的 `SET` 当表名改写 ⇒ ⛔ `ON CONFLICT … DO UPDATE`,
+//!   查重一律「先 `SELECT` 再写」;
+//! * `/dml/batch@v1` ⛔ 回 `RETURNING` 值 ⇒ 写完必另发一条 `SELECT` 回读真值再应答。
+
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::{BosError, ErrorCode, PageQuery, RoleCode};
+use bos_platform::clients::uds::{de, UdsClient};
+use chrono::Local;
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+use super::listq::{self, as_num, as_opt_num, total, Params};
+
+/// `catalog_plan` 里设计册有、dev 库仍缺的列 ⇒ 逐字点名回 `null`。
+/// 2026-11-07 补列后已清空(`20261107000002_bos_write_gap_columns.sql`);键⛔ 删=前端契约不变。
+const COLUMNS_PENDING: &[&str] = &[];
+
+/// 档位类型枚举(第 3 册 §2)。
+const PLAN_KINDS: &[&str] = &["fixed", "custom"];
+/// 用途分类枚举(第 3 册 §2;建后⛔ 改)。
+const USE_CATEGORIES: &[&str] = &["office", "live", "ai", "value_add", "customized"];
+/// 新建档位的起始乐观锁版本(=列 `DEFAULT 1`,显式写死让响应能回同一真值)。
+const ROW_VERSION_INIT: i64 = 1;
+
+/// 读侧列集(`p` = `catalog_plan`,`c` = `customer`)。
+const PLAN_COLS: &str = "p.plan_id, p.plan_name, p.plan_kind, p.annual_price_cents, p.status, p.created_at, \
+     p.use_category, p.sub_account_quota, p.bandwidth_committed, p.bandwidth_up_mbps, \
+     p.bandwidth_down_mbps, p.customer_id, p.row_version, c.customer_name";
+/// 读侧 `FROM`(`customer_id` 是 `customer` 主键 ⇒ LEFT JOIN 不产生行膨胀,可安全用于 `COUNT`)。
+const PLAN_FROM: &str = "FROM catalog_plan p LEFT JOIN customer c ON c.customer_id = p.customer_id";
+
+#[derive(Deserialize)]
+pub struct CatalogListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub plan_kind: Option<String>,
+    pub status: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct CatalogGetReq {
+    pub plan_id: String,
+}
+
+/// `/catalog/create@v1`(`src/openapi.yaml:2729`)。
+#[derive(Deserialize)]
+pub struct CatalogCreateReq {
+    pub plan_kind: Option<String>,
+    pub plan_name: Option<String>,
+    pub use_category: Option<String>,
+    pub annual_price_cents: Option<i64>,
+    pub sub_account_quota: Option<i64>,
+    pub bandwidth_committed: Option<bool>,
+    pub bandwidth_up_mbps: Option<i64>,
+    pub bandwidth_down_mbps: Option<i64>,
+    pub customer_id: Option<String>,
+}
+
+/// `/catalog/update@v1`(`src/openapi.yaml:2794`)。
+///
+/// `plan_kind`/`use_category` 未列进 openapi 的 `data`,但⛔ 靠 serde 忽略它们=
+/// 静默接受越权改列,故显式收下再与库里现值比对(不同 ⇒ 显式失败)。
+#[derive(Deserialize)]
+pub struct CatalogUpdateReq {
+    pub plan_id: Option<String>,
+    pub plan_name: Option<String>,
+    pub annual_price_cents: Option<i64>,
+    pub sub_account_quota: Option<i64>,
+    pub bandwidth_committed: Option<bool>,
+    pub bandwidth_up_mbps: Option<i64>,
+    pub bandwidth_down_mbps: Option<i64>,
+    pub row_version: Option<i64>,
+    pub plan_kind: Option<String>,
+    pub use_category: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct PlanRow {
+    #[serde(deserialize_with = "de::as_string")]
+    plan_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    plan_name: String,
+    #[serde(deserialize_with = "de::as_string")]
+    plan_kind: String,
+    #[serde(deserialize_with = "de::as_string")]
+    annual_price_cents: String,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_string")]
+    created_at: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    use_category: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    sub_account_quota: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    bandwidth_committed: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    bandwidth_up_mbps: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    bandwidth_down_mbps: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    customer_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    customer_name: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    row_version: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct IdRow {
+    #[serde(deserialize_with = "de::as_string")]
+    plan_id: String,
+}
+
+#[derive(Deserialize)]
+struct SumRow {
+    #[serde(deserialize_with = "de::as_string")]
+    v: String,
+}
+
+/// BOOLEAN 列(`de::as_string` 收进来是 `"true"`/`"t"` 这类形态)→ JSON 布尔;
+/// 认不出来回 `null`,⛔ 冒充 `false`。
+fn as_bool(s: Option<&str>) -> Value {
+    match s.map(str::trim).map(|v| v.to_ascii_lowercase()).as_deref() {
+        Some("true") | Some("t") | Some("1") => Value::Bool(true),
+        Some("false") | Some("f") | Some("0") => Value::Bool(false),
+        _ => Value::Null,
+    }
+}
+
+/// 可选数值请求字段 → 参数位(缺省=`NULL`,⛔ 落 `0`)。
+fn opt_val(v: Option<i64>) -> Value {
+    v.map(Value::from).unwrap_or(Value::Null)
+}
+
+/// 在册列给真值,缺册列([`COLUMNS_PENDING`])给 `null`。
+fn to_json(r: PlanRow) -> Value {
+    json!({
+        "plan_id": r.plan_id,
+        "plan_name": r.plan_name,
+        "plan_kind": r.plan_kind,
+        "annual_price_cents": as_num(&r.annual_price_cents),
+        "status": r.status,
+        "created_at": r.created_at,
+        "use_category": r.use_category,
+        "sub_account_quota": as_opt_num(r.sub_account_quota.as_deref()),
+        "bandwidth_committed": as_bool(r.bandwidth_committed.as_deref()),
+        "bandwidth_up_mbps": as_opt_num(r.bandwidth_up_mbps.as_deref()),
+        "bandwidth_down_mbps": as_opt_num(r.bandwidth_down_mbps.as_deref()),
+        "customer_id": r.customer_id,
+        "customer_name": r.customer_name,
+        "row_version": as_opt_num(r.row_version.as_deref()),
+    })
+}
+
+/// 顶层补 `columns_pending`(值恒=[`COLUMNS_PENDING`],可能为空数组)。
+fn with_pending(v: Value) -> Value {
+    let mut v = v;
+    v["columns_pending"] = json!(COLUMNS_PENDING);
+    v
+}
+
+async fn fetch_row(db: &UdsClient, plan_id: &str) -> Result<Option<PlanRow>, BosError> {
+    let mut p = Params::default();
+    let Some(pid) = p.push_eq(Some(plan_id)) else { return Ok(None) };
+    let sql = format!("SELECT {PLAN_COLS} {PLAN_FROM} WHERE p.plan_id = {pid}::text");
+    db.query_one::<PlanRow>(&sql, p.values()).await
+}
 
-pub async fn create(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
+async fn fetch_plan(db: &UdsClient, plan_id: &str) -> Result<Option<Value>, BosError> {
+    Ok(fetch_row(db, plan_id).await?.map(to_json))
+}
+
+/// 同 `plan_kind` 下档位名查重(`exclude`=编辑时排除自身);撞名 ⇒ 回对方 `plan_id`。
+async fn name_taken(
+    db: &UdsClient,
+    plan_kind: &str,
+    plan_name: &str,
+    exclude: Option<&str>,
+) -> Result<Option<String>, BosError> {
+    let mut p = Params::default();
+    let k = p.push(Value::String(plan_kind.to_string()));
+    let n = p.push(Value::String(plan_name.to_string()));
+    let mut preds = vec![format!("plan_kind = {k}::text"), format!("plan_name = {n}::text")];
+    if let Some(id) = p.push_eq(exclude) {
+        preds.push(format!("plan_id <> {id}::text"));
+    }
+    let lim = p.push(Value::from(1));
+    let sql = format!(
+        "SELECT plan_id FROM catalog_plan WHERE {} LIMIT {lim}",
+        preds.join(" AND ")
+    );
+    Ok(db.query_one::<IdRow>(&sql, p.values()).await?.map(|r| r.plan_id))
+}
+
+/// 该档位下活跃订阅已占席位数(`SUM(quota_slots)`,⛔ `cancelled`)。
+///
+/// 取不到数=取数失败(⛔ 当 `0` 放行「改小席位」)。
+async fn active_seat_demand(db: &UdsClient, plan_id: &str) -> Result<i64, BosError> {
+    let mut p = Params::default();
+    let pid = p.push(Value::String(plan_id.to_string()));
+    let st = p.push(Value::String("cancelled".to_string()));
+    let sql = format!(
+        "SELECT COALESCE(SUM(s.quota_slots), 0) AS v FROM subscription s \
+         WHERE s.plan_id = {pid}::text AND s.status <> {st}::text"
+    );
+    let row = db
+        .query_one::<SumRow>(&sql, p.values())
+        .await?
+        .ok_or_else(|| BosError::internal("活跃订阅席位数取数失败:SUM 聚合无返回行"))?;
+    row.v
+        .trim()
+        .parse::<i64>()
+        .map_err(|e| BosError::internal(format!("活跃订阅席位数不可解析:{}({e})", row.v)))
+}
+
+/// 「不承诺带宽」⇒ 上下行⛔ 带值(有值即显式失败,⛔ 静默丢弃)。
+fn check_bandwidth(committed: bool, up: Option<i64>, down: Option<i64>) -> Result<(), BosError> {
+    if !committed && (up.is_some() || down.is_some()) {
+        return Err(BosError::bad_params(
+            "bandwidth_committed=false(不承诺带宽)时 bandwidth_up_mbps/bandwidth_down_mbps 一律⛔ 传值",
+        ));
+    }
+    Ok(())
+}
+
+async fn do_create(db: &UdsClient, b: &CatalogCreateReq) -> Result<Value, BosError> {
+    let kind = b.plan_kind.as_deref().map(str::trim).filter(|s| !s.is_empty());
+    let kind = match kind {
+        Some(k) if PLAN_KINDS.contains(&k) => k,
+        other => {
+            return Err(BosError::bad_params(format!(
+                "plan_kind 只接受 {},收到:{}",
+                PLAN_KINDS.join("/"),
+                other.unwrap_or("(缺)")
+            )))
+        }
+    };
+    let name = b.plan_name.as_deref().map(str::trim).filter(|s| !s.is_empty());
+    let name = match name {
+        Some(n) => n,
+        None => return Err(BosError::bad_params("plan_name 不能为空")),
+    };
+    let cat = b.use_category.as_deref().map(str::trim).filter(|s| !s.is_empty());
+    let cat = match cat {
+        Some(c) if USE_CATEGORIES.contains(&c) => c,
+        other => {
+            return Err(BosError::bad_params(format!(
+                "use_category 只接受 {},收到:{}",
+                USE_CATEGORIES.join("/"),
+                other.unwrap_or("(缺)")
+            )))
+        }
+    };
+    let price = match b.annual_price_cents {
+        Some(v) => v,
+        None => return Err(BosError::bad_params("annual_price_cents 不能为空")),
+    };
+    check_bandwidth(b.bandwidth_committed.unwrap_or(true), b.bandwidth_up_mbps, b.bandwidth_down_mbps)?;
+
+    let cid = b.customer_id.as_deref().map(str::trim).filter(|s| !s.is_empty());
+    if kind == "custom" && cid.is_none() {
+        return Err(BosError::bad_params("自定义档(plan_kind=custom)必须带 customer_id"));
+    }
+    if kind == "fixed" && cid.is_some() {
+        return Err(BosError::bad_params("固定档(plan_kind=fixed)⛔ 带 customer_id"));
+    }
+
+    if let Some(dup) = name_taken(db, kind, name, None).await? {
+        return Err(BosError::bad_params(format!(
+            "同一档位类型({kind})下已存在同名档位:{name}({dup})"
+        )));
+    }
+
+    let year = Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))?;
+    let seq = listq::next_seq(db, "catalog_plan", "catalog_plan", year).await?;
+    let plan_id = format!("P-{seq:06}");
+
+    let mut p = Params::default();
+    let ph = [
+        p.push(Value::String(plan_id.clone())),
+        p.push(Value::String(name.to_string())),
+        p.push(Value::String(kind.to_string())),
+        p.push(Value::from(price)),
+        p.push(Value::String(cat.to_string())),
+        p.push(opt_val(b.sub_account_quota)),
+        p.push(Value::from(b.bandwidth_committed.unwrap_or(true))),
+        p.push(opt_val(b.bandwidth_up_mbps)),
+        p.push(opt_val(b.bandwidth_down_mbps)),
+        p.push(cid.map(|v| Value::String(v.to_string())).unwrap_or(Value::Null)),
+        p.push(Value::from(ROW_VERSION_INIT)),
+    ];
+    let casts = [
+        "text", "text", "text", "bigint", "text", "int", "boolean", "int", "int", "text", "int",
+    ];
+    let values = ph
+        .iter()
+        .zip(casts.iter())
+        .map(|(ph, ty)| format!("{ph}::{ty}"))
+        .collect::<Vec<_>>()
+        .join(", ");
+    let sql = format!(
+        "INSERT INTO catalog_plan (plan_id, plan_name, plan_kind, annual_price_cents, use_category, \
+         sub_account_quota, bandwidth_committed, bandwidth_up_mbps, bandwidth_down_mbps, \
+         customer_id, row_version) VALUES ({values})"
+    );
+    let affected = db.dml(&sql, p.values()).await?;
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "新建档位写入异常:plan_id={plan_id} affected_rows={affected}"
+        )));
+    }
+    fetch_plan(db, &plan_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("新建档位写入后回读失败:plan_id={plan_id}")))
+}
+
+async fn do_update(db: &UdsClient, b: &CatalogUpdateReq) -> Result<Value, BosError> {
+    let plan_id = b.plan_id.as_deref().map(str::trim).filter(|s| !s.is_empty());
+    let plan_id = match plan_id {
+        Some(v) => v,
+        None => return Err(BosError::bad_params("plan_id 不能为空")),
+    };
+    let cur = fetch_row(db, plan_id)
+        .await?
+        .ok_or_else(|| BosError::not_found(format!("套餐档位不存在:{plan_id}")))?;
+
+    // 建后⛔ 改:请求出现且与库里现值不同 ⇒ 显式失败;相同=视为未改。
+    if let Some(k) = b.plan_kind.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        if k != cur.plan_kind {
+            return Err(BosError::bad_params(format!(
+                "plan_kind 建后⛔ 可改(库里={},请求={k})",
+                cur.plan_kind
+            )));
+        }
+    }
+    if let Some(c) = b.use_category.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        if cur.use_category.as_deref().map(str::trim) != Some(c) {
+            return Err(BosError::bad_params(format!(
+                "use_category 建后⛔ 可改(库里={},请求={c})",
+                cur.use_category.as_deref().unwrap_or("(空)")
+            )));
+        }
+    }
+
+    // 生效后的承诺带宽位=请求优先,请求没带就看库里现值(现值认不出来 ⇒ 按列缺省 TRUE 处理)。
+    let committed = match b.bandwidth_committed {
+        Some(c) => c,
+        None => match as_bool(cur.bandwidth_committed.as_deref()) {
+            Value::Bool(c) => c,
+            _ => true,
+        },
+    };
+    check_bandwidth(committed, b.bandwidth_up_mbps, b.bandwidth_down_mbps)?;
+
+    let new_name = match b.plan_name.as_deref() {
+        None => None,
+        Some(raw) => {
+            let n = raw.trim();
+            if n.is_empty() {
+                return Err(BosError::bad_params("plan_name 不能为空"));
+            }
+            Some(n)
+        }
+    };
+    if let Some(n) = new_name.filter(|n| *n != cur.plan_name) {
+        if let Some(dup) = name_taken(db, &cur.plan_kind, n, Some(plan_id)).await? {
+            return Err(BosError::bad_params(format!(
+                "同一档位类型({})下已存在同名档位:{n}({dup})",
+                cur.plan_kind
+            )));
+        }
+    }
+
+    if let Some(q) = b.sub_account_quota {
+        let used = active_seat_demand(db, plan_id).await?;
+        if q < used {
+            return Err(BosError::bad_params(format!(
+                "sub_account_quota ⛔ 改小于该档位活跃订阅已占席位数:已占 {used},请求={q}"
+            )));
+        }
+    }
+
+    let mut p = Params::default();
+    let pid = p.push(Value::String(plan_id.to_string()));
+    let mut sets: Vec<String> = Vec::new();
+    if let Some(n) = new_name.filter(|n| *n != cur.plan_name) {
+        let v = p.push(Value::String(n.to_string()));
+        sets.push(format!("plan_name = {v}::text"));
+    }
+    if let Some(v) = b.annual_price_cents {
+        let ph = p.push(Value::from(v));
+        sets.push(format!("annual_price_cents = {ph}::bigint"));
+    }
+    if let Some(v) = b.sub_account_quota {
+        let ph = p.push(Value::from(v));
+        sets.push(format!("sub_account_quota = {ph}::int"));
+    }
+    if let Some(c) = b.bandwidth_committed {
+        let ph = p.push(Value::from(c));
+        sets.push(format!("bandwidth_committed = {ph}::boolean"));
+        if !c {
+            // 列口径=不承诺 ⇒ 上下行两列一律为空(值走参数位,⛔ 拼 `NULL` 字面量)。
+            let nu = p.push(Value::Null);
+            let nd = p.push(Value::Null);
+            sets.push(format!("bandwidth_up_mbps = {nu}::int"));
+            sets.push(format!("bandwidth_down_mbps = {nd}::int"));
+        }
+    }
+    if let Some(v) = b.bandwidth_up_mbps {
+        let ph = p.push(Value::from(v));
+        sets.push(format!("bandwidth_up_mbps = {ph}::int"));
+    }
+    if let Some(v) = b.bandwidth_down_mbps {
+        let ph = p.push(Value::from(v));
+        sets.push(format!("bandwidth_down_mbps = {ph}::int"));
+    }
+    if sets.is_empty() {
+        return Err(BosError::bad_params("没有需要更新的字段"));
+    }
+    sets.push("row_version = row_version + 1".to_string());
+
+    let mut preds = vec![format!("plan_id = {pid}::text")];
+    if let Some(rv) = b.row_version {
+        let ph = p.push(Value::from(rv));
+        preds.push(format!("row_version = {ph}::int"));
+    }
+    let sql = format!(
+        "UPDATE catalog_plan SET {} WHERE {}",
+        sets.join(", "),
+        preds.join(" AND ")
+    );
+    let affected = db.dml(&sql, p.values()).await?;
+    if affected == 0 {
+        // 影响 0 行=两种成因,文案⛔ 混用。
+        return Err(match fetch_row(db, plan_id).await? {
+            None => BosError::not_found(format!("套餐档位不存在:{plan_id}")),
+            Some(_) => BosError::biz(
+                ErrorCode::ConflictS407,
+                format!("档位已被他人修改(row_version 不符),请刷新后重试:{plan_id}"),
+            ),
+        });
+    }
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "档位更新影响行数异常:plan_id={plan_id} affected_rows={affected}"
+        )));
+    }
+    fetch_plan(db, plan_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("档位更新后回读失败:plan_id={plan_id}")))
+}
+
+pub async fn create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<CatalogCreateReq>,
+) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin]) { return json_err(e); }
-    json_ok(json!({ "plan_id": null, "req": b }))
+    match do_create(state.db.as_ref(), &body).await {
+        Ok(v) => json_ok(with_pending(v)),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn update(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn get_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [] }))
+
+pub async fn update(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<CatalogUpdateReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin]) { return json_err(e); }
+    match do_update(state.db.as_ref(), &body).await {
+        Ok(v) => json_ok(with_pending(v)),
+        Err(e) => json_err(e),
+    }
+}
+
+fn preds(p: &mut Params, keyword: Option<&str>, plan_kind: Option<&str>, status: Option<&str>) -> Vec<String> {
+    let mut v = Vec::new();
+    if let Some(k) = p.push_like(keyword) {
+        v.push(format!("p.plan_name LIKE {k}"));
+    }
+    if let Some(v2) = p.push_eq(plan_kind) {
+        v.push(format!("p.plan_kind = {v2}::text"));
+    }
+    if let Some(s) = p.push_eq(status) {
+        v.push(format!("p.status = {s}::text"));
+    }
+    v
 }
-pub async fn get(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "plan": b }))
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(_auth): RequireAuth,
+    DataBody(body): DataBody<CatalogListReq>,
+) -> Response {
+    let mut p = Params::default();
+    let w = preds(&mut p, body.keyword.as_deref(), body.plan_kind.as_deref(), body.status.as_deref());
+    let from_where = format!("{PLAN_FROM} {}", p.where_clause(&w));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT {PLAN_COLS} {PLAN_FROM} {} \
+         ORDER BY p.plan_kind, p.annual_price_cents, p.plan_name LIMIT {lim} OFFSET {off}",
+        p.where_clause(&w)
+    );
+    let rows = match state.db.query_all::<PlanRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    json_ok(json!({
+        "items": rows.into_iter().map(to_json).collect::<Vec<Value>>(),
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+        "columns_pending": COLUMNS_PENDING,
+    }))
+}
+
+pub async fn get(
+    State(state): State<AppState>,
+    RequireAuth(_auth): RequireAuth,
+    DataBody(body): DataBody<CatalogGetReq>,
+) -> Response {
+    match fetch_plan(state.db.as_ref(), &body.plan_id).await {
+        Ok(Some(v)) => json_ok(with_pending(v)),
+        Ok(None) => json_ok(json!({
+            "plan_id": null,
+            "columns_pending": COLUMNS_PENDING,
+            "message": "套餐档位不存在",
+        })),
+        Err(e) => json_err(e),
+    }
 }

+ 1290 - 10
src/modules/account/src/handlers/contract.rs

@@ -1,16 +1,1296 @@
+//! 合同(第 3 册)——读写侧都真落库。
+//!
+//! 2026-11-07 业主裁定「补 dev 骨架列」并落地 `20261107000002_bos_write_gap_columns.sql` 后:
+//! `contract` 的 `external_no`/`pay_cycle`/起止日/经办人四项/`attachment_url`/`updated_at`/
+//! `row_version` 已在册,两张子表 `contract_service_item`/`contract_ip_entry` 已建表
+//! ⇒ 只读侧全部给真值,[`COLUMNS_PENDING`] 清空(响应仍保留 `columns_pending` 键=空数组,
+//! 前端契约形状不变)。设计册 §2.2 的更深层额(`sort_no`/`unit_price_cents`/
+//! `monthly_settle_cents`+`settle_mode`/自定义式派生档链/`TEXT[]`+GIN 出口列)dev 未补,
+//! 本文件⛔ 写、⛔ 改迁移。
+//!
+//! 写侧落库面=dev 在册列:
+//! * `contract`:`contract_id`/`customer_id`/`contract_no`/`amount_cents`(← 请求
+//!   `contract_amount_cents`)/`external_no`/`pay_cycle`/`start_date`/`end_date`/
+//!   `agent_name`/`agent_mobile`/`agent_handover_on`/`agent_org`/`attachment_url`/
+//!   `row_version`;`status`、`created_at` 走列默认值,`updated_at` 由 UPDATE 写 `NOW()`。
+//! * `contract_service_item`:`item_id`(服务端发号 `SI-{6位}`,⛔ 沿用来请求里的 `item_id`)/
+//!   `contract_id`/`item_kind`/`plan_id`/`quantity`/`account_count`/`bandwidth_up_mbps`/
+//!   `bandwidth_down_mbps`/`line_exits`(dev 用 JSONB 承载字符串数组,读出原样回字符串数组)。
+//!   在册列 `use_category`/`annual_price_cents` 在 openapi 请求体里**没有对应入参** ⇒ ⛔ 写;
+//!   条目里多带的键(含 `item_id`)一律点名在 `service_item_fields_not_persisted`。
+//! * `contract_ip_entry`:只落 `line_exit`/`bandwidth_tier_mbps`/`ip_count` 三元组
+//!   (openapi 把元素写成无属性 object,多出来的键无处落库 ⇒ 点名在
+//!   `ip_entry_fields_not_persisted`,并回 `ip_entry_fields_persisted` 说清只存这些)。
+//!
+//! ⚠️ 两处 UDS 现实约束决定写侧形状:① `/dml/batch@v1` 同批=原子提交 ⇒ 主表与两张子表
+//! 放**同一条批**(⛔ 拆两批=主档成功、条目丢失);② 批内⛔ 条件中止(`uds.rs:180`)⇒
+//! 乐观锁只能靠「写前先读版本号([`do_update`] 开头)+ `UPDATE … WHERE row_version = $n`」
+//! 两道:读后写前这之间被并发抢改版本的极端窗口内,主表靠 `WHERE` 谓词不会误写,
+//! 但同批的子表条目仍会随批提交——该窗口⛔ 无法用 UDS 短批消除,如实留此注释。
+//!
+//! ⚠️ 可见性同 `partner.rs::customer_scope_pred` 口径:合同本身没有伙伴维度,
+//! 挂到 `customer` 上按客户归属收口 ⇒ 本账号看不见的客户,其合同一律当不存在
+//! (`get`/列表给空,⛔ 回明细)。
+//!
+//! ⚠️ `customer_name`:`contract` 只有 `customer_id`,名字在 `customer.customer_name`
+//! ⇒ 分页后按本页 `customer_id` 集合回查(⛔ JOIN 嵌套循环)。
+
+use std::collections::{BTreeSet, HashMap};
+
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, ErrorCode, RoleCode};
+use bos_platform::clients::uds::{de, DmlStatement, DmlStatementResult, UdsClient};
+use bos_scope::AuthContext;
+use chrono::{Local, NaiveDate};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+use super::listq::{as_num, as_opt_num, next_seq, pairs_by, push_in, total, Params};
+use super::partner::customer_scope_pred;
+
+/// 补列后设计列**全部在册** ⇒ 无缺列;键仍回给前端(值=空数组),契约形状不变。
+const COLUMNS_PENDING: &[&str] = &[];
+/// 账期枚举(openapi `pay_cycle`)。
+const PAY_CYCLES: [&str; 3] = ["yearly", "quarterly", "monthly"];
+/// 条目形态枚举(openapi `item_kind`)。
+const ITEM_KINDS: [&str; 2] = ["plan_based", "custom_spec"];
+/// IP 备案只接受这三个档位(设计册 §2.2 `bandwidth_tier_mbps IN (5,10,30)`,⛔ 放开连续值)。
+const IP_TIERS: [i64; 3] = [5, 10, 30];
+/// `contract_ip_entry` 本轮真正落库的字段(openapi 元素无属性 ⇒ 只认这三元组)。
+const IP_ENTRY_FIELDS_PERSISTED: [&str; 3] = ["line_exit", "bandwidth_tier_mbps", "ip_count"];
+/// `contract_service_item` 本轮真正落库的请求字段(`use_category`/`annual_price_cents` 无入参可填)。
+const SERVICE_ITEM_FIELDS_PERSISTED: [&str; 7] = [
+    "item_kind",
+    "plan_id",
+    "quantity",
+    "account_count",
+    "bandwidth_up_mbps",
+    "bandwidth_down_mbps",
+    "line_exits",
+];
+/// 新建合同的起始行版本(dev 列默认值=1)。
+const ROW_VERSION_INIT: i64 = 1;
+
+const CONTRACT_COLS: &str = "k.contract_id, k.customer_id, k.contract_no, k.status, \
+                             k.amount_cents, k.created_at, k.external_no, k.pay_cycle, \
+                             k.start_date, k.end_date, k.agent_name, k.agent_mobile, \
+                             k.agent_handover_on, k.agent_org, k.attachment_url, k.row_version";
+const CONTRACT_FROM: &str = "FROM contract k";
+
+/// 合同主表新增(14 列;`status`/`created_at`/`updated_at` 走默认值)。
+const CONTRACT_INSERT: &str = "INSERT INTO contract (contract_id, customer_id, contract_no, \
+    external_no, amount_cents, pay_cycle, start_date, end_date, agent_name, agent_mobile, \
+    agent_handover_on, agent_org, attachment_url, row_version) \
+    VALUES ($1::text, $2::text, $3::text, $4::text, $5::bigint, $6::text, $7::date, $8::date, \
+            $9::text, $10::text, $11::date, $12::text, $13::text, $14::int)";
+
+/// 服务构成条目新增(9 列;`line_exits`=JSONB 字符串数组)。
+const ITEM_INSERT: &str = "INSERT INTO contract_service_item (item_id, contract_id, item_kind, \
+    plan_id, quantity, account_count, bandwidth_up_mbps, bandwidth_down_mbps, line_exits) \
+    VALUES ($1::text, $2::text, $3::text, $4::text, $5::int, $6::int, $7::int, $8::int, $9::jsonb)";
+
+/// IP 备案条目新增(只落三元组)。
+const IP_INSERT: &str = "INSERT INTO contract_ip_entry (entry_id, contract_id, line_exit, \
+    bandwidth_tier_mbps, ip_count) VALUES ($1::text, $2::text, $3::text, $4::int, $5::int)";
+
+#[derive(Deserialize)]
+pub struct ContractListReq {
+    #[serde(default, flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub customer_id: Option<String>,
+    pub status: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct ContractIdReq {
+    pub contract_id: String,
+}
+
+/// 服务构成条目(openapi `service_items` 元素)。
+///
+/// 数值字段收 `Value`(⛔ 直接 `Option<i64>`=类型不符时只回一句泛化 400,点名不到是哪条哪列);
+/// `extra` 收下 openapi 未列的键(含 `item_id`)⇒ 如实点名,⛔ 静默丢。
+#[derive(Deserialize, Default)]
+pub struct ServiceItemReq {
+    pub item_kind: Option<String>,
+    pub plan_id: Option<String>,
+    pub quantity: Option<Value>,
+    pub account_count: Option<Value>,
+    pub bandwidth_up_mbps: Option<Value>,
+    pub bandwidth_down_mbps: Option<Value>,
+    pub line_exits: Option<Value>,
+    #[serde(flatten)]
+    pub extra: HashMap<String, Value>,
+}
+
+/// IP 备案条目(openapi 元素=无属性 object ⇒ 只认三元组,其余进 `extra` 点名)。
+#[derive(Deserialize, Default)]
+pub struct IpEntryReq {
+    pub line_exit: Option<Value>,
+    pub bandwidth_tier_mbps: Option<Value>,
+    pub ip_count: Option<Value>,
+    #[serde(flatten)]
+    pub extra: HashMap<String, Value>,
+}
+
+#[derive(Deserialize)]
+pub struct ContractCreateReq {
+    pub customer_id: Option<String>,
+    /// 合同编号(空则服务端发号 `{customer_id}-C{序号}`)。
+    pub contract_no: Option<String>,
+    pub external_no: Option<String>,
+    pub contract_amount_cents: Option<Value>,
+    pub pay_cycle: Option<String>,
+    pub start_date: Option<String>,
+    pub end_date: Option<String>,
+    pub agent_name: Option<String>,
+    pub agent_mobile: Option<String>,
+    pub agent_handover_on: Option<String>,
+    pub agent_org: Option<String>,
+    pub attachment_url: Option<String>,
+    pub service_items: Option<Vec<ServiceItemReq>>,
+    pub ip_entries: Option<Vec<IpEntryReq>>,
+    /// openapi 未列的键(含 `source`、内联建档字段)=无处落库 ⇒ 响应点名,⛔ 静默接受。
+    #[serde(flatten)]
+    pub extra: HashMap<String, Value>,
+}
+
+#[derive(Deserialize)]
+pub struct ContractUpdateReq {
+    pub contract_id: Option<String>,
+    /// 必填乐观锁(openapi `required`)。
+    pub row_version: Option<i64>,
+    /// openapi `data` 未列这两项,但⛔ 靠 serde 忽略=静默接受改主档归属,故显式收下比对。
+    pub customer_id: Option<String>,
+    pub contract_no: Option<String>,
+    pub external_no: Option<String>,
+    pub contract_amount_cents: Option<Value>,
+    pub pay_cycle: Option<String>,
+    pub start_date: Option<String>,
+    pub end_date: Option<String>,
+    pub agent_name: Option<String>,
+    pub agent_mobile: Option<String>,
+    pub agent_handover_on: Option<String>,
+    pub agent_org: Option<String>,
+    pub attachment_url: Option<String>,
+    /// `None`=不改;`Some([])`=清空整组;`Some(非空)`=整组替换(旧 `item_id` 作废、重新发号)。
+    pub service_items: Option<Vec<ServiceItemReq>>,
+    pub ip_entries: Option<Vec<IpEntryReq>>,
+    #[serde(flatten)]
+    pub extra: HashMap<String, Value>,
+}
+
+#[derive(Deserialize)]
+struct ContractRow {
+    #[serde(deserialize_with = "de::as_string")]
+    contract_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    customer_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    contract_no: String,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_string")]
+    amount_cents: String,
+    #[serde(deserialize_with = "de::as_string")]
+    created_at: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    external_no: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    pay_cycle: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    start_date: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    end_date: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    agent_name: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    agent_mobile: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    agent_handover_on: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    agent_org: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    attachment_url: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    row_version: String,
+}
+
+#[derive(Deserialize)]
+struct ItemRow {
+    #[serde(deserialize_with = "de::as_string")]
+    item_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    contract_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    item_kind: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    plan_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    quantity: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    account_count: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    bandwidth_up_mbps: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    bandwidth_down_mbps: Option<String>,
+    /// JSONB:联合引擎可能整列回字符串(同 `audit.rs:79` 的坑)⇒ 解析不了就原样回,⛔ 吞。
+    #[serde(default)]
+    line_exits: Option<Value>,
+}
+
+#[derive(Deserialize)]
+struct IpRow {
+    #[serde(deserialize_with = "de::as_string")]
+    entry_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    contract_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    line_exit: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    bandwidth_tier_mbps: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    ip_count: Option<String>,
+}
 
-pub async fn create(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
-    json_ok(json!({ "contract_id": null, "req": b }))
+#[derive(Deserialize)]
+struct IdRow {
+    #[serde(deserialize_with = "de::as_string")]
+    id: String,
 }
-pub async fn update(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn get_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [] }))
+
+#[derive(Deserialize)]
+struct CountRow {
+    #[serde(deserialize_with = "de::as_string")]
+    c: String,
+}
+
+/// 子表条目按 `contract_id` 分组。
+type Children = HashMap<String, Vec<Value>>;
+
+/// JSONB 单元格 → JSON 值(字符串形态就按 JSON 解析,解析不了原样回字符串)。
+fn json_cell(v: Option<Value>) -> Value {
+    match v {
+        Some(Value::String(s)) => serde_json::from_str::<Value>(&s).unwrap_or(Value::String(s)),
+        Some(v) => v,
+        None => Value::Null,
+    }
+}
+
+fn item_json(r: ItemRow) -> Value {
+    json!({
+        "item_id": r.item_id,
+        "item_kind": r.item_kind,
+        "plan_id": r.plan_id,
+        "quantity": as_opt_num(r.quantity.as_deref()),
+        "account_count": as_opt_num(r.account_count.as_deref()),
+        "bandwidth_up_mbps": as_opt_num(r.bandwidth_up_mbps.as_deref()),
+        "bandwidth_down_mbps": as_opt_num(r.bandwidth_down_mbps.as_deref()),
+        "line_exits": json_cell(r.line_exits),
+    })
+}
+
+fn ip_json(r: IpRow) -> Value {
+    json!({
+        "entry_id": r.entry_id,
+        "line_exit": r.line_exit,
+        "bandwidth_tier_mbps": as_opt_num(r.bandwidth_tier_mbps.as_deref()),
+        "ip_count": as_opt_num(r.ip_count.as_deref()),
+    })
 }
-pub async fn get(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "contract": b }))
+
+/// 在册列全给真值;`customer_name` 由调用方回查 `customer` 后传进来(取不到=`null`,⛔ 造名)。
+fn base_json(r: &ContractRow, customer_name: Option<&str>) -> Value {
+    json!({
+        "contract_id": r.contract_id,
+        "contract_no": r.contract_no,
+        "customer_id": r.customer_id,
+        "customer_name": customer_name,
+        "status": r.status,
+        "amount_cents": as_num(&r.amount_cents),
+        "contract_amount_cents": as_num(&r.amount_cents),
+        "external_no": r.external_no,
+        "pay_cycle": r.pay_cycle,
+        "start_date": r.start_date,
+        "end_date": r.end_date,
+        "agent_name": r.agent_name,
+        "agent_mobile": r.agent_mobile,
+        "agent_handover_on": r.agent_handover_on,
+        "agent_org": r.agent_org,
+        "attachment_url": r.attachment_url,
+        "created_at": r.created_at,
+        "row_version": as_num(&r.row_version),
+    })
+}
+
+/// 挂两张子表的真条目(⛔ 回 `null`/空数组冒充:库里没有=真没有)+ `columns_pending`。
+fn with_children(mut v: Value, cid: &str, items: &Children, ips: &Children) -> Value {
+    v["service_items"] = json!(items.get(cid).cloned().unwrap_or_default());
+    v["ip_entries"] = json!(ips.get(cid).cloned().unwrap_or_default());
+    v["columns_pending"] = json!(COLUMNS_PENDING);
+    v
+}
+
+/// 顶层补 `columns_pending`(列表响应用;值恒=[`COLUMNS_PENDING`],现为空数组)。
+fn with_pending(v: Value) -> Value {
+    let mut v = v;
+    v["columns_pending"] = json!(COLUMNS_PENDING);
+    v
+}
+
+/// 按合同 ID 集合批量回查两张子表(⛔ 逐条 N+1)。
+async fn load_children(db: &UdsClient, ids: &[String]) -> Result<(Children, Children), BosError> {
+    if ids.is_empty() {
+        return Ok((HashMap::new(), HashMap::new()));
+    }
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, "i.contract_id", ids, "text");
+    let sql = format!(
+        "SELECT i.item_id, i.contract_id, i.item_kind, i.plan_id, i.quantity, i.account_count, \
+         i.bandwidth_up_mbps, i.bandwidth_down_mbps, i.line_exits \
+         FROM contract_service_item i WHERE {in_pred} ORDER BY i.created_at, i.item_id"
+    );
+    let mut items: Children = HashMap::new();
+    for r in db.query_all::<ItemRow>(&sql, p.values()).await? {
+        items.entry(r.contract_id.clone()).or_default().push(item_json(r));
+    }
+
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, "e.contract_id", ids, "text");
+    let sql = format!(
+        "SELECT e.entry_id, e.contract_id, e.line_exit, e.bandwidth_tier_mbps, e.ip_count \
+         FROM contract_ip_entry e WHERE {in_pred} ORDER BY e.created_at, e.entry_id"
+    );
+    let mut ips: Children = HashMap::new();
+    for r in db.query_all::<IpRow>(&sql, p.values()).await? {
+        ips.entry(r.contract_id.clone()).or_default().push(ip_json(r));
+    }
+    Ok((items, ips))
+}
+
+/// 按本页 `customer_id` 集合回查 `customer.customer_name`(⛔ JOIN 嵌套循环)。
+/// 取数失败**不**降级——回 `Err`,⛔ 静默成片空名。
+async fn customer_names(db: &UdsClient, ids: &[String]) -> Result<HashMap<String, String>, BosError> {
+    let uniq: Vec<String> = ids.iter().cloned().collect::<BTreeSet<_>>().into_iter().collect();
+    let pairs = pairs_by(db, "customer", "customer_id", "customer_name", &uniq).await?;
+    Ok(pairs
+        .into_iter()
+        .filter_map(|(k, v)| {
+            v.into_iter()
+                .find(|s| !s.trim().is_empty())
+                .map(|s| (k, s.trim().to_string()))
+        })
+        .collect())
+}
+
+/// 按主键读一行(写后回读用;⛔ 带可见性谓词=刚写完又按可见性读不到=误报失败)。
+async fn fetch_row(db: &UdsClient, contract_id: &str) -> Result<Option<ContractRow>, BosError> {
+    let mut p = Params::default();
+    let Some(cid) = p.push_eq(Some(contract_id)) else { return Ok(None) };
+    let sql = format!("SELECT {CONTRACT_COLS} {CONTRACT_FROM} WHERE k.contract_id = {cid}::text");
+    db.query_one::<ContractRow>(&sql, p.values()).await
+}
+
+/// 按主键 + 可见性谓词读一行(读侧与改侧都走这里)。
+async fn fetch_scoped_row(
+    state: &AppState,
+    auth: &AuthContext,
+    contract_id: &str,
+) -> Result<Option<ContractRow>, BosError> {
+    let mut p = Params::default();
+    let Some(cid) = p.push_eq(Some(contract_id)) else { return Ok(None) };
+    let scope = customer_scope_pred(state, auth, &mut p, "k.customer_id").await?;
+    let sql = format!(
+        "SELECT {CONTRACT_COLS} {CONTRACT_FROM} WHERE {scope} AND k.contract_id = {cid}::text"
+    );
+    state.db.query_one::<ContractRow>(&sql, p.values()).await
+}
+
+/// 明细(主档 + 两张子表);⛔ 带可见性谓词(写侧刚校验过归属,回读走主键)。
+async fn fetch_detail(db: &UdsClient, contract_id: &str) -> Result<Option<Value>, BosError> {
+    let Some(r) = fetch_row(db, contract_id).await? else { return Ok(None) };
+    let ids = vec![r.contract_id.clone()];
+    let (items, ips) = load_children(db, &ids).await?;
+    Ok(Some(with_children(
+        base_json(&r, None),
+        &r.contract_id,
+        &items,
+        &ips,
+    )))
+}
+
+// ─────────────────────── 请求侧校验(逐条显式失败,⛔ 静默纠正) ───────────────────────
+
+/// 去空白后收进 `Some`;缺席或全空白=`None`。
+fn trimmed(v: &Option<String>) -> Option<&str> {
+    v.as_deref().map(str::trim).filter(|s| !s.is_empty())
+}
+
+/// 文本列参数位:空白=`NULL`(清空),⛔ 落空串。
+fn text_param(v: Option<&str>) -> Value {
+    v.map(str::trim)
+        .filter(|s| !s.is_empty())
+        .map(|s| Value::String(s.to_string()))
+        .unwrap_or(Value::Null)
+}
+
+fn required_text<'a>(v: &'a Option<String>, field: &str) -> Result<&'a str, BosError> {
+    trimmed(v).ok_or_else(|| BosError::bad_params(format!("{field} 不能为空")))
+}
+
+/// 请求值原样进错误文案(缺=`(缺)`),⛔ 把类型不对的值当空值放过。
+fn shown(v: Option<&Value>) -> String {
+    v.map(Value::to_string).unwrap_or_else(|| "(缺)".to_string())
+}
+
+/// 数值字段:认整数(数字或纯数字串);认不出来=显式失败,⛔ 当 `0`。
+fn want_int(v: Option<&Value>, field: &str) -> Result<Option<i64>, BosError> {
+    let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(None) };
+    match v {
+        Value::Number(n) => n
+            .as_i64()
+            .ok_or_else(|| BosError::bad_params(format!("{field} 须为整数,收到 {v}")))
+            .map(Some),
+        Value::String(s) => s
+            .trim()
+            .parse::<i64>()
+            .map(Some)
+            .map_err(|_| BosError::bad_params(format!("{field} 须为整数,收到 {s:?}"))),
+        _ => Err(BosError::bad_params(format!("{field} 须为整数,收到 {v}"))),
+    }
+}
+
+/// 正整数(数量/席位数)。
+fn want_pos(v: Option<&Value>, field: &str) -> Result<Option<i64>, BosError> {
+    let n = want_int(v, field)?;
+    if let Some(n) = n {
+        if n < 1 {
+            return Err(BosError::bad_params(format!("{field} 须为 ≥1 的整数,收到 {n}")));
+        }
+    }
+    Ok(n)
+}
+
+/// 带宽口径 1~1000(openapi `bandwidth_*_mbps`)。
+fn want_band(v: Option<&Value>, field: &str) -> Result<Option<i64>, BosError> {
+    let n = want_int(v, field)?;
+    if let Some(n) = n {
+        if !(1..=1000).contains(&n) {
+            return Err(BosError::bad_params(format!("{field} 须为 1~1000 的整数,收到 {n}")));
+        }
+    }
+    Ok(n)
+}
+
+/// `YYYY-MM-DD` 日期;空白=`None`,格式不对=显式失败。
+fn parse_date(raw: Option<&String>, field: &str) -> Result<Option<NaiveDate>, BosError> {
+    let Some(raw) = raw else { return Ok(None) };
+    let s = raw.trim();
+    if s.is_empty() {
+        return Ok(None);
+    }
+    NaiveDate::parse_from_str(s, "%Y-%m-%d")
+        .map(Some)
+        .map_err(|_| BosError::bad_params(format!("{field} 须为 YYYY-MM-DD 日期,收到 {s:?}")))
+}
+
+/// 库里已存的日期列(认不出来=当没有,⛔ 因脏数据卡住一次合法改写)。
+fn stored_date(v: Option<&String>) -> Option<NaiveDate> {
+    v.as_deref()
+        .and_then(|s| NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
+}
+
+fn date_param(d: Option<NaiveDate>) -> Value {
+    d.map(|d| Value::String(d.format("%Y-%m-%d").to_string()))
+        .unwrap_or(Value::Null)
+}
+
+fn year_now() -> Result<i32, BosError> {
+    Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))
+}
+
+/// `line_exits`=非空字符串数组(设计册 §2.2 每条条目至少一个出口)。
+fn line_exits_param(v: Option<&Value>, field: &str) -> Result<Option<Value>, BosError> {
+    let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(None) };
+    let arr = v
+        .as_array()
+        .ok_or_else(|| BosError::bad_params(format!("{field} 须为字符串数组,收到 {v}")))?;
+    if arr.is_empty() {
+        return Err(BosError::bad_params(format!(
+            "{field} ⛔ 空数组(每条条目至少一个落地出口)"
+        )));
+    }
+    let mut out = Vec::with_capacity(arr.len());
+    for (i, e) in arr.iter().enumerate() {
+        let s = e
+            .as_str()
+            .map(str::trim)
+            .filter(|s| !s.is_empty())
+            .ok_or_else(|| {
+                BosError::bad_params(format!(
+                    "{field}[{i}] 须为非空字符串(出口=国家/地区名称原文)"
+                ))
+            })?;
+        out.push(Value::String(s.to_string()));
+    }
+    Ok(Some(Value::Array(out)))
+}
+
+/// 一条已校验、可直接落库的服务构成条目。
+struct ItemIns {
+    kind: String,
+    plan_id: Option<String>,
+    quantity: Option<i64>,
+    account_count: Option<i64>,
+    bw_up: Option<i64>,
+    bw_down: Option<i64>,
+    line_exits: Option<Value>,
+}
+
+/// 校验整组条目 ⇒(可落库形态, 无处落库的键名)。
+///
+/// `plan_based` 必带 `plan_id`(档位存在性另发 SELECT,见 [`missing_plan_ids`]);
+/// `custom_spec` 必带 `quantity`、⛔ 带 `plan_id`——设计册 §2.2 的
+/// `CHECK ((item_kind='plan_based') = (plan_id IS NOT NULL))` 是 `(a)=(b)` 防串味语义,
+/// dev 骨架没建这条约束 ⇒ 服务端兜。
+fn validate_items(raw: &[ServiceItemReq]) -> Result<(Vec<ItemIns>, Vec<String>), BosError> {
+    let mut out = Vec::with_capacity(raw.len());
+    let mut dropped: BTreeSet<String> = BTreeSet::new();
+    for (i, it) in raw.iter().enumerate() {
+        let prefix = format!("service_items[{i}]");
+        let kind = match trimmed(&it.item_kind) {
+            Some(k) if ITEM_KINDS.contains(&k) => k,
+            Some(k) => {
+                return Err(BosError::bad_params(format!(
+                    "{prefix}.item_kind 只接受 {},收到 {k}",
+                    ITEM_KINDS.join("/")
+                )))
+            }
+            None => {
+                return Err(BosError::bad_params(format!(
+                    "{prefix}.item_kind 必填({})",
+                    ITEM_KINDS.join("/")
+                )))
+            }
+        };
+        let plan_id = trimmed(&it.plan_id).map(|s| s.to_string());
+        if kind == "plan_based" && plan_id.is_none() {
+            return Err(BosError::bad_params(format!(
+                "{prefix}:套餐式条目(plan_based)必须带 plan_id"
+            )));
+        }
+        if kind == "custom_spec" && plan_id.is_some() {
+            return Err(BosError::bad_params(format!(
+                "{prefix}:自定义式条目(custom_spec)⛔ 带 plan_id(挂档只走套餐式,设计册 §2.2):{}",
+                plan_id.unwrap_or_default()
+            )));
+        }
+        let quantity = want_pos(it.quantity.as_ref(), &format!("{prefix}.quantity"))?;
+        if kind == "custom_spec" && quantity.is_none() {
+            return Err(BosError::bad_params(format!(
+                "{prefix}:自定义式条目(custom_spec)必须带 quantity"
+            )));
+        }
+        out.push(ItemIns {
+            kind: kind.to_string(),
+            plan_id,
+            quantity,
+            account_count: want_pos(it.account_count.as_ref(), &format!("{prefix}.account_count"))?,
+            bw_up: want_band(it.bandwidth_up_mbps.as_ref(), &format!("{prefix}.bandwidth_up_mbps"))?,
+            bw_down: want_band(
+                it.bandwidth_down_mbps.as_ref(),
+                &format!("{prefix}.bandwidth_down_mbps"),
+            )?,
+            line_exits: line_exits_param(it.line_exits.as_ref(), &format!("{prefix}.line_exits"))?,
+        });
+        dropped.extend(it.extra.keys().cloned());
+    }
+    Ok((out, dropped.into_iter().collect()))
+}
+
+/// `plan_based` 引用的档位是否都在 `catalog_plan` 在册(回缺失 ID)。
+async fn missing_plan_ids(db: &UdsClient, ids: &[String]) -> Result<Vec<String>, BosError> {
+    if ids.is_empty() {
+        return Ok(Vec::new());
+    }
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, "plan_id", ids, "text");
+    let sql = format!("SELECT plan_id AS id FROM catalog_plan WHERE {in_pred}");
+    let found: Vec<String> = db
+        .query_all::<IdRow>(&sql, p.values())
+        .await?
+        .into_iter()
+        .map(|r| r.id)
+        .collect();
+    Ok(ids
+        .iter()
+        .filter(|id| !found.iter().any(|f| f == *id))
+        .cloned()
+        .collect())
+}
+
+/// 一条已校验的 IP 备案条目(三元组)。
+struct IpIns {
+    line_exit: String,
+    tier: i64,
+    count: i64,
+}
+
+/// 校验 IP 备案三元组 ⇒(可落库形态, 无处落库的键名)。
+fn validate_ip(raw: &[IpEntryReq]) -> Result<(Vec<IpIns>, Vec<String>), BosError> {
+    let mut out = Vec::with_capacity(raw.len());
+    let mut dropped: BTreeSet<String> = BTreeSet::new();
+    for (i, e) in raw.iter().enumerate() {
+        let prefix = format!("ip_entries[{i}]");
+        let line_exit = match e
+            .line_exit
+            .as_ref()
+            .and_then(Value::as_str)
+            .map(str::trim)
+            .filter(|s| !s.is_empty())
+        {
+            Some(s) => s.to_string(),
+            None => {
+                return Err(BosError::bad_params(format!(
+                    "{prefix}.line_exit 必填非空字符串(口径=线路出口=国家/地区名称原文),收到 {}",
+                    shown(e.line_exit.as_ref())
+                )))
+            }
+        };
+        let tier = want_int(
+            e.bandwidth_tier_mbps.as_ref(),
+            &format!("{prefix}.bandwidth_tier_mbps"),
+        )?
+        .filter(|t| IP_TIERS.contains(t))
+        .ok_or_else(|| {
+            BosError::bad_params(format!(
+                "{prefix}.bandwidth_tier_mbps 只接受 {} 三档,收到 {}",
+                IP_TIERS.iter().map(|t| t.to_string()).collect::<Vec<_>>().join("/"),
+                shown(e.bandwidth_tier_mbps.as_ref())
+            ))
+        })?;
+        let count = want_int(e.ip_count.as_ref(), &format!("{prefix}.ip_count"))?
+            .filter(|c| *c > 0)
+            .ok_or_else(|| {
+                BosError::bad_params(format!(
+                    "{prefix}.ip_count 必填且须 > 0,收到 {}",
+                    shown(e.ip_count.as_ref())
+                ))
+            })?;
+        out.push(IpIns { line_exit, tier, count });
+        dropped.extend(e.extra.keys().cloned());
+    }
+    Ok((out, dropped.into_iter().collect()))
+}
+
+/// 客户必须存在**且在当前账号可见范围内**(同读侧谓词,⛔ 两本账)。
+async fn ensure_customer_visible(
+    state: &AppState,
+    auth: &AuthContext,
+    customer_id: &str,
+) -> Result<(), BosError> {
+    let mut p = Params::default();
+    let Some(cid) = p.push_eq(Some(customer_id)) else {
+        return Err(BosError::bad_params("customer_id 不能为空"));
+    };
+    let scope = customer_scope_pred(state, auth, &mut p, "c.customer_id").await?;
+    let sql = format!(
+        "SELECT c.customer_id AS id FROM customer c WHERE c.customer_id = {cid}::text AND {scope}"
+    );
+    match state.db.query_one::<IdRow>(&sql, p.values()).await? {
+        Some(_) => Ok(()),
+        None => Err(BosError::bad_params(format!(
+            "customer_id 不存在或超出当前账号可见范围:{customer_id}"
+        ))),
+    }
+}
+
+/// 该客户已有合同数(对外合同号序号=它 + 1)。取不到数=取数失败,⛔ 当 `0` 造成重号。
+async fn contract_count_of(db: &UdsClient, customer_id: &str) -> Result<i64, BosError> {
+    let sql = "SELECT COUNT(1) AS c FROM contract WHERE customer_id = $1::text";
+    let row = db
+        .query_one::<CountRow>(sql, &[Value::String(customer_id.to_string())])
+        .await?
+        .ok_or_else(|| BosError::internal("合同数取数失败:COUNT 聚合无返回行"))?;
+    row.c
+        .trim()
+        .parse::<i64>()
+        .map_err(|e| BosError::internal(format!("合同数不可解析:{}({e})", row.c)))
+}
+
+/// 对外合同号=`{customer_id}-C{序号}`:2 位补零是**最小宽度**,超 99 自然进位、⛔ 截断。
+fn contract_no_of(customer_id: &str, seq: i64) -> String {
+    format!("{customer_id}-C{seq:02}")
+}
+
+/// `service_items` 的参数位(新增与整组替换共用同一条 [`ITEM_INSERT`])。
+fn item_params(contract_id: &str, item_id: &str, it: &ItemIns) -> Vec<Value> {
+    vec![
+        Value::String(item_id.to_string()),
+        Value::String(contract_id.to_string()),
+        Value::String(it.kind.clone()),
+        it.plan_id.clone().map(Value::String).unwrap_or(Value::Null),
+        it.quantity.map(Value::from).unwrap_or(Value::Null),
+        it.account_count.map(Value::from).unwrap_or(Value::Null),
+        it.bw_up.map(Value::from).unwrap_or(Value::Null),
+        it.bw_down.map(Value::from).unwrap_or(Value::Null),
+        it.line_exits.clone().unwrap_or(Value::Null),
+    ]
+}
+
+fn ip_params(contract_id: &str, entry_id: &str, e: &IpIns) -> Vec<Value> {
+    vec![
+        Value::String(entry_id.to_string()),
+        Value::String(contract_id.to_string()),
+        Value::String(e.line_exit.clone()),
+        Value::from(e.tier),
+        Value::from(e.count),
+    ]
+}
+
+/// 批量发子表主键(`SI-{6位}`/`IE-{6位}`;一枚一号=一枚 `next_seq`)。
+async fn issue_ids(
+    db: &UdsClient,
+    prefix: &str,
+    kind: &str,
+    year: i32,
+    n: usize,
+) -> Result<Vec<String>, BosError> {
+    let mut out = Vec::with_capacity(n);
+    for _ in 0..n {
+        let s = next_seq(db, kind, kind, year).await?;
+        out.push(format!("{prefix}-{s:06}"));
+    }
+    Ok(out)
+}
+
+/// 短批结果核对:结果数不符(⛔ 谎报成功)或某条未落库 ⇒ `internal`。
+fn assert_all_one(results: &[DmlStatementResult], want: usize, what: &str) -> Result<(), BosError> {
+    if results.len() != want {
+        return Err(BosError::internal(format!(
+            "{what}:短批结果数不符(期望 {want},实得 {})",
+            results.len()
+        )));
+    }
+    if let Some(i) = results.iter().position(|r| r.affected_rows != Some(1)) {
+        let got = results[i]
+            .affected_rows
+            .map(|n| n.to_string())
+            .unwrap_or_else(|| "无".to_string());
+        return Err(BosError::internal(format!(
+            "{what}:第 {} 条未落库(affected_rows={got})",
+            i + 1
+        )));
+    }
+    Ok(())
+}
+
+/// 版本不符(乐观锁撞车)=在册的通用冲突码 `KLT-S407`,⛔ 占新码。
+fn conflict(contract_id: &str) -> BosError {
+    BosError::biz(
+        ErrorCode::ConflictS407,
+        format!("合同已被他人修改(row_version 不符),请刷新后重试:{contract_id}"),
+    )
+}
+
+/// 把「无处落库」的请求字段如实点名(⛔ 静默丢弃)。
+fn persist_note(v: &mut Value, extra: &HashMap<String, Value>, item_dropped: &[String], ip_dropped: &[String]) {
+    let mut top: Vec<String> = extra.keys().cloned().collect();
+    top.sort();
+    v["service_item_fields_persisted"] = json!(SERVICE_ITEM_FIELDS_PERSISTED);
+    v["ip_entry_fields_persisted"] = json!(IP_ENTRY_FIELDS_PERSISTED);
+    v["fields_not_persisted"] = json!(top);
+    v["service_item_fields_not_persisted"] = json!(item_dropped);
+    v["ip_entry_fields_not_persisted"] = json!(ip_dropped);
+}
+
+// ───────────────────────── 写侧 ─────────────────────────
+
+async fn do_create(
+    state: &AppState,
+    auth: &AuthContext,
+    b: &ContractCreateReq,
+) -> Result<Value, BosError> {
+    let db = state.db.as_ref();
+    let customer_id = required_text(&b.customer_id, "customer_id")?;
+    ensure_customer_visible(state, auth, customer_id).await?;
+
+    let pay_cycle = match trimmed(&b.pay_cycle) {
+        Some(v) if PAY_CYCLES.contains(&v) => v,
+        Some(v) => {
+            return Err(BosError::bad_params(format!(
+                "pay_cycle 只接受 {},收到 {v}",
+                PAY_CYCLES.join("/")
+            )))
+        }
+        None => {
+            return Err(BosError::bad_params(format!(
+                "pay_cycle 必填({})",
+                PAY_CYCLES.join("/")
+            )))
+        }
+    };
+    let start = parse_date(b.start_date.as_ref(), "start_date")?
+        .ok_or_else(|| BosError::bad_params("start_date 必填(YYYY-MM-DD)"))?;
+    let end = parse_date(b.end_date.as_ref(), "end_date")?
+        .ok_or_else(|| BosError::bad_params("end_date 必填(YYYY-MM-DD)"))?;
+    if end <= start {
+        return Err(BosError::bad_params(format!(
+            "end_date 必须晚于 start_date(起 {}/止 {})",
+            start.format("%Y-%m-%d"),
+            end.format("%Y-%m-%d")
+        )));
+    }
+    let handover = parse_date(b.agent_handover_on.as_ref(), "agent_handover_on")?;
+    // 未传金额=按列默认值落 0(⛔ 造数:该列本就 `NOT NULL DEFAULT 0`)。
+    let amount = match want_int(b.contract_amount_cents.as_ref(), "contract_amount_cents")? {
+        Some(v) if v < 0 => {
+            return Err(BosError::bad_params(format!(
+                "contract_amount_cents ⛔ 小于 0(分),收到 {v}"
+            )))
+        }
+        Some(v) => v,
+        None => 0,
+    };
+
+    let raw_items = b.service_items.as_deref().unwrap_or_default();
+    if raw_items.is_empty() {
+        return Err(BosError::bad_params(
+            "service_items 不能为空:合同必须至少一条服务构成条目",
+        ));
+    }
+    let (items, item_dropped) = validate_items(raw_items)?;
+    let (ips, ip_dropped) = validate_ip(b.ip_entries.as_deref().unwrap_or_default())?;
+    let plan_ids: Vec<String> = items
+        .iter()
+        .filter(|it| it.kind == "plan_based")
+        .filter_map(|it| it.plan_id.clone())
+        .collect::<BTreeSet<String>>()
+        .into_iter()
+        .collect();
+    let missing = missing_plan_ids(db, &plan_ids).await?;
+    if !missing.is_empty() {
+        return Err(BosError::bad_params(format!(
+            "service_items 引用的套餐档位不存在:{}",
+            missing.join("、")
+        )));
+    }
+
+    // 发号(全项目统一口径:`bos_seq_year` 原子取号,年份=服务器本地年)。
+    let year = year_now()?;
+    let seq = next_seq(db, "contract", "contract", year).await?;
+    let contract_id = format!("CT-{seq:06}");
+    let contract_no = match trimmed(&b.contract_no) {
+        Some(v) => v.to_string(),
+        None => {
+            let n = contract_count_of(db, customer_id).await? + 1;
+            contract_no_of(customer_id, n)
+        }
+    };
+    let item_ids = issue_ids(db, "SI", "contract_service_item", year, items.len()).await?;
+    let entry_ids = issue_ids(db, "IE", "contract_ip_entry", year, ips.len()).await?;
+
+    // 主表 + 两张子表=**同一条批**(同批=原子提交,⛔ 拆批=主档成功、条目丢失)。
+    let mut stmts: Vec<DmlStatement> = vec![DmlStatement::new(
+        CONTRACT_INSERT,
+        vec![
+            Value::String(contract_id.clone()),
+            Value::String(customer_id.to_string()),
+            Value::String(contract_no),
+            text_param(trimmed(&b.external_no)),
+            Value::from(amount),
+            Value::String(pay_cycle.to_string()),
+            date_param(Some(start)),
+            date_param(Some(end)),
+            text_param(trimmed(&b.agent_name)),
+            text_param(trimmed(&b.agent_mobile)),
+            date_param(handover),
+            text_param(trimmed(&b.agent_org)),
+            text_param(trimmed(&b.attachment_url)),
+            Value::from(ROW_VERSION_INIT),
+        ],
+    )];
+    for (id, it) in item_ids.iter().zip(items.iter()) {
+        stmts.push(DmlStatement::new(
+            ITEM_INSERT,
+            item_params(&contract_id, id, it),
+        ));
+    }
+    for (id, e) in entry_ids.iter().zip(ips.iter()) {
+        stmts.push(DmlStatement::new(IP_INSERT, ip_params(&contract_id, id, e)));
+    }
+    let want = stmts.len();
+
+    let results = db.dml_batch(&stmts).await?;
+    assert_all_one(&results, want, "新增合同写入")?;
+
+    let mut v = fetch_detail(db, &contract_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("新增合同写入后回读失败:{contract_id}")))?;
+    persist_note(&mut v, &b.extra, &item_dropped, &ip_dropped);
+    Ok(v)
+}
+
+async fn do_update(
+    state: &AppState,
+    auth: &AuthContext,
+    b: &ContractUpdateReq,
+) -> Result<Value, BosError> {
+    let db = state.db.as_ref();
+    let contract_id = required_text(&b.contract_id, "contract_id")?;
+    let row_version = b
+        .row_version
+        .ok_or_else(|| BosError::bad_params("row_version 必填(乐观锁,取详情接口返回值)"))?;
+
+    let cur = fetch_scoped_row(state, auth, contract_id)
+        .await?
+        .ok_or_else(|| {
+            BosError::not_found(format!("合同不存在或超出当前账号可见范围:{contract_id}"))
+        })?;
+    // 建后⛔ 改:请求出现且与库里现值不同 ⇒ 显式失败;相同=视为未改。
+    if let Some(v) = trimmed(&b.customer_id) {
+        if v != cur.customer_id {
+            return Err(BosError::bad_params(format!(
+                "customer_id ⛔ 可改(库里={},请求={v})",
+                cur.customer_id
+            )));
+        }
+    }
+    if let Some(v) = trimmed(&b.contract_no) {
+        if v != cur.contract_no {
+            return Err(BosError::bad_params(format!(
+                "contract_no ⛔ 可改(库里={},请求={v})",
+                cur.contract_no
+            )));
+        }
+    }
+    // 乐观锁第一道:库里版本已不符 ⇒ 连子表都⛔ 碰。
+    let cur_version = cur.row_version.trim().parse::<i64>().map_err(|e| {
+        BosError::internal(format!(
+            "合同 row_version 不可解析:{}(contract_id={contract_id},{e})",
+            cur.row_version
+        ))
+    })?;
+    if cur_version != row_version {
+        return Err(conflict(contract_id));
+    }
+
+    let (items, item_dropped) = validate_items(b.service_items.as_deref().unwrap_or_default())?;
+    let (ips, ip_dropped) = validate_ip(b.ip_entries.as_deref().unwrap_or_default())?;
+    let plan_ids: Vec<String> = items
+        .iter()
+        .filter(|it| it.kind == "plan_based")
+        .filter_map(|it| it.plan_id.clone())
+        .collect::<BTreeSet<String>>()
+        .into_iter()
+        .collect();
+    let missing = missing_plan_ids(db, &plan_ids).await?;
+    if !missing.is_empty() {
+        return Err(BosError::bad_params(format!(
+            "service_items 引用的套餐档位不存在:{}",
+            missing.join("、")
+        )));
+    }
+
+    // ── SET 子句:字段出现即写(空白串=清空为 NULL),缺席=不改 ──
+    let mut p = Params::default();
+    let mut sets: Vec<String> = Vec::new();
+    for (col, raw) in [
+        ("external_no", &b.external_no),
+        ("agent_name", &b.agent_name),
+        ("agent_mobile", &b.agent_mobile),
+        ("agent_org", &b.agent_org),
+        ("attachment_url", &b.attachment_url),
+    ] {
+        let Some(raw) = raw else { continue };
+        let ph = p.push(text_param(Some(raw.as_str())));
+        sets.push(format!("{col} = {ph}::text"));
+    }
+    if let Some(raw) = &b.pay_cycle {
+        match trimmed(&Some(raw.clone())) {
+            Some(v) if PAY_CYCLES.contains(&v) => {
+                let ph = p.push(Value::String(v.to_string()));
+                sets.push(format!("pay_cycle = {ph}::text"));
+            }
+            Some(v) => {
+                return Err(BosError::bad_params(format!(
+                    "pay_cycle 只接受 {},收到 {v}",
+                    PAY_CYCLES.join("/")
+                )))
+            }
+            None => return Err(BosError::bad_params(
+                "pay_cycle ⛔ 清空(该列非空),请传有效账期".to_string(),
+            )),
+        }
+    }
+    if let Some(v) = &b.contract_amount_cents {
+        let amount = want_int(Some(v), "contract_amount_cents")?
+            .filter(|v| *v >= 0)
+            .ok_or_else(|| {
+                BosError::bad_params(format!(
+                    "contract_amount_cents 须为 ≥0 的整数(分),收到 {v}"
+                ))
+            })?;
+        let ph = p.push(Value::from(amount));
+        sets.push(format!("amount_cents = {ph}::bigint"));
+    }
+    // 起止日:生效值=请求优先、请求没带看库里现值 ⇒ 单改一侧也守得住 `end_date > start_date`。
+    let start = match &b.start_date {
+        Some(_) => parse_date(b.start_date.as_ref(), "start_date")?,
+        None => stored_date(cur.start_date.as_ref()),
+    };
+    let end = match &b.end_date {
+        Some(_) => parse_date(b.end_date.as_ref(), "end_date")?,
+        None => stored_date(cur.end_date.as_ref()),
+    };
+    if let (Some(s), Some(e)) = (start, end) {
+        if e <= s {
+            return Err(BosError::bad_params(format!(
+                "end_date 必须晚于 start_date(起 {}/止 {})",
+                s.format("%Y-%m-%d"),
+                e.format("%Y-%m-%d")
+            )));
+        }
+    }
+    for (col, raw) in [
+        ("start_date", &b.start_date),
+        ("end_date", &b.end_date),
+        ("agent_handover_on", &b.agent_handover_on),
+    ] {
+        let Some(raw) = raw else { continue };
+        let ph = p.push(date_param(parse_date(Some(raw), col)?));
+        sets.push(format!("{col} = {ph}::date"));
+    }
+
+    if sets.is_empty() && b.service_items.is_none() && b.ip_entries.is_none() {
+        return Err(BosError::bad_params("没有需要更新的字段"));
+    }
+    sets.push("row_version = row_version + 1".to_string());
+    sets.push("updated_at = NOW()".to_string());
+
+    let year = year_now()?;
+    let item_ids = issue_ids(db, "SI", "contract_service_item", year, items.len()).await?;
+    let entry_ids = issue_ids(db, "IE", "contract_ip_entry", year, ips.len()).await?;
+
+    let cid = p.push(Value::String(contract_id.to_string()));
+    let rv = p.push(Value::from(row_version));
+    // 乐观锁第二道(真防线):版本不符 ⇒ 主表 0 行。
+    let main_sql = format!(
+        "UPDATE contract SET {} WHERE contract_id = {cid}::text AND row_version = {rv}::int",
+        sets.join(", ")
+    );
+    // 整组替换:同批内先清后插;`None`=不碰、`Some([])`=清空(两种语义⛔ 混同)。
+    let mut stmts: Vec<DmlStatement> = vec![DmlStatement::new(main_sql, p.values().to_vec())];
+    let mut del_count = 0usize;
+    if b.service_items.is_some() {
+        stmts.push(DmlStatement::new(
+            "DELETE FROM contract_service_item WHERE contract_id = $1::text",
+            vec![Value::String(contract_id.to_string())],
+        ));
+        del_count += 1;
+        for (id, it) in item_ids.iter().zip(items.iter()) {
+            stmts.push(DmlStatement::new(ITEM_INSERT, item_params(contract_id, id, it)));
+        }
+    }
+    if b.ip_entries.is_some() {
+        stmts.push(DmlStatement::new(
+            "DELETE FROM contract_ip_entry WHERE contract_id = $1::text",
+            vec![Value::String(contract_id.to_string())],
+        ));
+        del_count += 1;
+        for (id, e) in entry_ids.iter().zip(ips.iter()) {
+            stmts.push(DmlStatement::new(IP_INSERT, ip_params(contract_id, id, e)));
+        }
+    }
+
+    let results = db.dml_batch(&stmts).await?;
+    if results.len() != stmts.len() {
+        return Err(BosError::internal(format!(
+            "合同更新:短批结果数不符(期望 {},实得 {})",
+            stmts.len(),
+            results.len()
+        )));
+    }
+    let affected = results.first().and_then(|r| r.affected_rows).unwrap_or(0);
+    if affected == 0 {
+        // 影响 0 行=两种成因,文案⛔ 混用(写前已比过版本,走到这里=并发抢改)。
+        return Err(match fetch_row(db, contract_id).await? {
+            None => BosError::not_found(format!("合同不存在:{contract_id}")),
+            Some(_) => conflict(contract_id),
+        });
+    }
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "合同更新影响行数异常:contract_id={contract_id} affected_rows={affected}"
+        )));
+    }
+    // `DELETE` 允许 0 行(原本就没有条目)⇒ 只核对插入语句。
+    for (i, r) in results.iter().skip(1 + del_count).enumerate() {
+        if r.affected_rows != Some(1) {
+            return Err(BosError::internal(format!(
+                "合同更新:第 {} 条子表条目未落库(contract_id={contract_id})",
+                i + 1
+            )));
+        }
+    }
+
+    let mut v = fetch_detail(db, contract_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("合同更新后回读失败:{contract_id}")))?;
+    v["updated"] = json!(true);
+    v["service_items_replaced"] = json!(b.service_items.is_some());
+    v["ip_entries_replaced"] = json!(b.ip_entries.is_some());
+    persist_note(&mut v, &b.extra, &item_dropped, &ip_dropped);
+    Ok(v)
+}
+
+pub async fn create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ContractCreateReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
+        return json_err(e);
+    }
+    match do_create(&state, &auth, &body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+pub async fn update(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ContractUpdateReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
+        return json_err(e);
+    }
+    match do_update(&state, &auth, &body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+// ───────────────────────── 读侧 ─────────────────────────
+
+fn preds(
+    p: &mut Params,
+    keyword: Option<&str>,
+    customer_id: Option<&str>,
+    status: Option<&str>,
+) -> Vec<String> {
+    let mut v = Vec::new();
+    if let Some(k) = p.push_like(keyword) {
+        // 合同没有名称列 ⇒ 只命中合同号与客户编号。
+        let k2 = k.clone();
+        v.push(format!("(k.contract_no LIKE {k} OR k.customer_id LIKE {k2})"));
+    }
+    if let Some(c) = p.push_eq(customer_id) {
+        v.push(format!("k.customer_id = {c}::text"));
+    }
+    if let Some(s) = p.push_eq(status) {
+        v.push(format!("k.status = {s}::text"));
+    }
+    v
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ContractListReq>,
+) -> Response {
+    let mut p = Params::default();
+    let mut w = preds(
+        &mut p,
+        body.keyword.as_deref(),
+        body.customer_id.as_deref(),
+        body.status.as_deref(),
+    );
+    // 可见性谓词排在筛选之后一起进 WHERE:`Params` 负责占位符与值的对应次序。
+    match customer_scope_pred(&state, &auth, &mut p, "k.customer_id").await {
+        Ok(s) => w.push(s),
+        Err(e) => return json_err(e),
+    }
+    let from_where = format!("{CONTRACT_FROM} {}", p.where_clause(&w));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT {CONTRACT_COLS} {CONTRACT_FROM} {} ORDER BY k.created_at DESC LIMIT {lim} OFFSET {off}",
+        p.where_clause(&w)
+    );
+    let rows = match state.db.query_all::<ContractRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let cids: Vec<String> = rows.iter().map(|r| r.contract_id.clone()).collect();
+    let uids: Vec<String> = rows.iter().map(|r| r.customer_id.clone()).collect();
+    let names = match customer_names(state.db.as_ref(), &uids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let (items, ips) = match load_children(state.db.as_ref(), &cids).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    json_ok(with_pending(json!({
+        "items": rows
+            .iter()
+            .map(|r| with_children(
+                base_json(r, names.get(&r.customer_id).map(String::as_str)),
+                &r.contract_id,
+                &items,
+                &ips,
+            ))
+            .collect::<Vec<Value>>(),
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    })))
+}
+
+pub async fn get(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ContractIdReq>,
+) -> Response {
+    let r = match fetch_scoped_row(&state, &auth, &body.contract_id).await {
+        Ok(Some(r)) => r,
+        Ok(None) => {
+            return json_ok(json!({
+                "contract_id": null,
+                "columns_pending": COLUMNS_PENDING,
+                "message": "合同不存在或超出当前账号可见范围",
+            }))
+        }
+        Err(e) => return json_err(e),
+    };
+    let ids = vec![r.contract_id.clone()];
+    let uids = vec![r.customer_id.clone()];
+    let name = match customer_names(state.db.as_ref(), &uids).await {
+        Ok(m) => m.get(&r.customer_id).cloned(),
+        Err(e) => return json_err(e),
+    };
+    let (items, ips) = match load_children(state.db.as_ref(), &ids).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    json_ok(with_children(
+        base_json(&r, name.as_deref()),
+        &r.contract_id,
+        &items,
+        &ips,
+    ))
 }

+ 953 - 10
src/modules/account/src/handlers/cost.rs

@@ -1,19 +1,962 @@
+//! 成本项与成本金额(第 4 册)——读写两侧真落库。
+//!
+//! 列集=一期骨架(`src/migrations/dev/20261104000001_bos_core_tables.sql:442`/`:452`)
+//! + 2026-11-07 业主裁定的写侧缺口列(`src/migrations/dev/20261107000002_bos_write_gap_columns.sql:94`/`:105`):
+//! * `cost_item` + `category`/`billing_unit`/`is_amortized`/`amortization_months`/
+//!   `deduct_from_base`/`remark`/`row_version` ⇒ 缺列清单 [`ITEM_COLUMNS_PENDING`] 已清空(键⛔ 删=契约不变);
+//! * `cost_amount` + `province_node_id`/`operator_id`/`row_version` ⇒ 透视表的两根轴终于有数据源,
+//!   [`amount_list`] 改为**真透视**(行=省份×运营商,列=成本项),带省份/运营商筛选走真谓词。
+//!
+//! 仍存的两处真缺口(⛔ 编数据补齐):
+//! * 存量一期种子只有 `item_id/period/amount_cents` ⇒ 两轴为 `NULL` 的差异行**不混进透视表**,
+//!   单列 [`amount_list`] 的 `rows_unattributed` +计数;
+//! * dev 库**没有区域节点名称表**(区域维度只有闭包表 `dim_node_ancestor`,
+//!   见 `src/migrations/dev/20261104000001_bos_core_tables.sql:86`)⇒ `province_name` 无处取真值,回 `null`
+//!   并在 `message` 里点名;运营商名有册内列(`operator.name`)⇒ 走 [`pairs_by`] 取真值。
+//!
+//! 写侧硬口径:
+//! * `qualify()` 把 `DO UPDATE` 后的 `SET` 当表名改写 ⇒ ⛔ `ON CONFLICT … DO UPDATE`,
+//!   upsert 一律「先 `SELECT` 命中⇒`UPDATE`,未命中⇒`INSERT`」;
+//! * `/dml/batch@v1` ⛔ 回 `RETURNING` 值 ⇒ 写完必另发 `SELECT` 回读真值再应答;
+//! * 同批=原子提交但⛔ 批内条件中止 ⇒ 乐观锁/存在性校验全部**前置**到 `SELECT` 阶段做完。
+
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::{BosError, ErrorCode, PageQuery, RoleCode};
+use bos_platform::clients::uds::{de, DmlStatement, UdsClient};
+use chrono::Local;
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::collections::{HashMap, HashSet};
+
+use super::listq::{self, as_num, as_opt_num, pairs_by, push_in, total, Params};
+
+/// `cost_item` 里设计册有、dev 库仍缺的列 ⇒ 逐字点名回 `null`。
+/// 2026-11-07 补列后已清空(`20261107000002_bos_write_gap_columns.sql:94`);键⛔ 删=前端契约不变。
+const ITEM_COLUMNS_PENDING: &[&str] = &[];
+/// 类别枚举(`src/openapi.yaml:3523`)。
+const CATEGORIES: &[&str] = &["intl_resource", "device_purchase", "project_fee"];
+/// 计费单位枚举(`src/openapi.yaml:3533`)。
+const BILLING_UNITS: &[&str] = &["per_customer", "per_account", "per_copy"];
+/// 摊销月数区间(业主当日口径;⚠️ 与 openapi:3542 的「可空」不一致,见 [`amort_months`])。
+const AMORT_MIN: i64 = 1;
+const AMORT_MAX: i64 = 120;
+/// 新建行的起始乐观锁版本(=列 `DEFAULT 1`,显式写死让响应能回同一真值)。
+const ROW_VERSION_INIT: i64 = 1;
+/// 区域维度在册表名/主键列(闭包表,一个节点一行×祖先 ⇒ 存在性判定取 `LIMIT 1`)。
+const REGION_TABLE: &str = "dim_node_ancestor";
+const REGION_KEY: &str = "node_id";
+
+/* ── 共用小助手 ─────────────────────────────────────────────────── */
+
+/// 去空白后取有效值;`None`/空串 ⇒ `None`。
+fn nn(v: Option<&String>) -> Option<&str> {
+    v.map(|s| s.trim()).filter(|s| !s.is_empty())
+}
+
+/// 必填枚举字段校验。
+fn one_of<'a>(raw: Option<&'a String>, allowed: &[&str], field: &str) -> Result<&'a str, BosError> {
+    let v = nn(raw).ok_or_else(|| BosError::bad_params(format!("{field} 不能为空")))?;
+    if allowed.contains(&v) {
+        Ok(v)
+    } else {
+        Err(BosError::bad_params(format!(
+            "{field} 只接受 {},收到:{v}",
+            allowed.join("/")
+        )))
+    }
+}
+
+/// BOOLEAN 列(`de::as_string` 收进来是 `"true"`/`"t"` 这类形态)→ JSON 布尔;
+/// 认不出来回 `null`,⛔ 冒充 `false`。
+fn as_bool(s: Option<&str>) -> Value {
+    match s.map(str::trim).map(|v| v.to_ascii_lowercase()).as_deref() {
+        Some("true") | Some("t") | Some("1") => Value::Bool(true),
+        Some("false") | Some("f") | Some("0") => Value::Bool(false),
+        _ => Value::Null,
+    }
+}
+
+/// `pairs_by` 取值:NULL 列被 `de::as_string` 摊成空串 ⇒ 归一成 `None`(⛔ 冒充空名称)。
+fn named(map: &HashMap<String, Vec<String>>, id: &str) -> Value {
+    map.get(id)
+        .and_then(|v| v.first())
+        .map(|s| s.trim())
+        .filter(|s| !s.is_empty())
+        .map(|s| Value::String(s.to_string()))
+        .unwrap_or(Value::Null)
+}
+
+#[derive(Deserialize)]
+struct IdRow {
+    #[serde(deserialize_with = "de::as_string")]
+    id: String,
+}
+
+/// 单条主键存在性判定。`table`/`key_col` 是**标识符**(拼进 SQL),
+/// 只能由调用方传字面量,⛔ 传任何用户输入。
+/// 查询本身失败=取数失败 ⇒ `?` 直接上抛(⛔ 当「不存在」或「空集放行」)。
+async fn row_exists(db: &UdsClient, table: &str, key_col: &str, id: &str) -> Result<bool, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(id.to_string()));
+    let sql = format!("SELECT {key_col} AS id FROM {table} WHERE {key_col} = {ph}::text LIMIT 1");
+    Ok(db.query_one::<IdRow>(&sql, p.values()).await?.is_some())
+}
+
+/* ── 成本项目录 ─────────────────────────────────────────────────── */
+
+#[derive(Deserialize)]
+pub struct CostItemListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub status: Option<String>,
+}
+
+/// `/cost_item/save@v1`(`src/openapi.yaml:3492`)。
+/// `cost_item_id` 空=新增(服务端发号),非空=修改。
+#[derive(Deserialize)]
+pub struct CostItemSaveReq {
+    pub cost_item_id: Option<String>,
+    pub item_name: Option<String>,
+    pub category: Option<String>,
+    pub billing_unit: Option<String>,
+    pub is_amortized: Option<bool>,
+    pub amortization_months: Option<i64>,
+    pub deduct_from_base: Option<bool>,
+    pub remark: Option<String>,
+    pub row_version: Option<i64>,
+}
+
+#[derive(Deserialize)]
+struct ItemRow {
+    #[serde(deserialize_with = "de::as_string")]
+    item_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    item_name: String,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    category: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    billing_unit: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    is_amortized: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    amortization_months: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    deduct_from_base: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    remark: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    row_version: Option<String>,
+}
+
+/// 读侧列集(在册列=全量,`cost_item` 无 JOIN ⇒ `COUNT` 可直接复用)。
+const ITEM_COLS: &str = "ci.item_id, ci.item_name, ci.status, ci.category, ci.billing_unit, \
+     ci.is_amortized, ci.amortization_months, ci.deduct_from_base, ci.remark, ci.row_version";
 
-pub async fn item_save(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
+fn item_json(r: &ItemRow) -> Value {
+    json!({
+        "cost_item_id": r.item_id,
+        "item_id": r.item_id,
+        "item_name": r.item_name,
+        "status": r.status,
+        "category": r.category,
+        "billing_unit": r.billing_unit,
+        "is_amortized": as_bool(r.is_amortized.as_deref()),
+        "amortization_months": as_opt_num(r.amortization_months.as_deref()),
+        "deduct_from_base": as_bool(r.deduct_from_base.as_deref()),
+        "remark": r.remark,
+        "row_version": as_opt_num(r.row_version.as_deref()),
+    })
+}
+
+/// 顶层补 `columns_pending`(值恒=[`ITEM_COLUMNS_PENDING`],现为空数组)。
+fn with_item_pending(v: Value) -> Value {
+    let mut v = v;
+    v["columns_pending"] = json!(ITEM_COLUMNS_PENDING);
+    v
+}
+
+async fn fetch_item(db: &UdsClient, item_id: &str) -> Result<Option<ItemRow>, BosError> {
+    let mut p = Params::default();
+    let Some(id) = p.push_eq(Some(item_id)) else { return Ok(None) };
+    let sql = format!("SELECT {ITEM_COLS} FROM cost_item ci WHERE ci.item_id = {id}::text");
+    db.query_one::<ItemRow>(&sql, p.values()).await
+}
+
+async fn fetch_item_json(db: &UdsClient, item_id: &str) -> Result<Option<Value>, BosError> {
+    Ok(fetch_item(db, item_id).await?.map(|r| item_json(&r)))
+}
+
+/// 摊销口径:勾选摊销 ⇒ 月数必填且 1~120;未勾选 ⇒ 该列写 `NULL`(⛔ 留脏值)。
+///
+/// ⚠️ `src/openapi.yaml:3542` 写「摊销月数(勾选摊销时可空=每月摊销不结束)」,
+/// 与业主当日口径「勾选摊销 ⇒ 月数必填」不一致,这里按后者实现(差额留 openapi 侧修订)。
+fn amort_months(amortized: bool, raw: Option<i64>) -> Result<Option<i64>, BosError> {
+    if !amortized {
+        return Ok(None);
+    }
+    let m = raw.ok_or_else(|| {
+        BosError::bad_params(format!(
+            "is_amortized=true 时 amortization_months 必填({AMORT_MIN}~{AMORT_MAX})"
+        ))
+    })?;
+    if !(AMORT_MIN..=AMORT_MAX).contains(&m) {
+        return Err(BosError::bad_params(format!(
+            "amortization_months 只接受 {AMORT_MIN}~{AMORT_MAX},收到:{m}"
+        )));
+    }
+    Ok(Some(m))
+}
+
+/// 成本项表单值(新增/修改共用)。元组序=`(名称, 类别, 计费单位, 是否摊销, 摊销月数, 是否冲减基数, 备注)`。
+fn check_item_form(b: &CostItemSaveReq) -> Result<(&str, &str, &str, bool, Option<i64>, bool, Option<&String>), BosError> {
+    let name = nn(b.item_name.as_ref()).ok_or_else(|| BosError::bad_params("item_name 不能为空"))?;
+    let category = one_of(b.category.as_ref(), CATEGORIES, "category")?;
+    let unit = one_of(b.billing_unit.as_ref(), BILLING_UNITS, "billing_unit")?;
+    let amortized = b
+        .is_amortized
+        .ok_or_else(|| BosError::bad_params("is_amortized 不能为空"))?;
+    let deduct = b
+        .deduct_from_base
+        .ok_or_else(|| BosError::bad_params("deduct_from_base 不能为空"))?;
+    let months = amort_months(amortized, b.amortization_months)?;
+    Ok((name, category, unit, amortized, months, deduct, b.remark.as_ref()))
+}
+
+async fn do_save_item(db: &UdsClient, b: &CostItemSaveReq) -> Result<Value, BosError> {
+    let (name, category, unit, amortized, months, deduct, remark) = check_item_form(b)?;
+    match nn(b.cost_item_id.as_ref()) {
+        None => do_insert_item(db, name, category, unit, amortized, months, deduct, remark).await,
+        Some(id) => {
+            do_update_item(db, id, name, category, unit, amortized, months, deduct, remark, b.row_version).await
+        }
+    }
+}
+
+async fn do_insert_item(
+    db: &UdsClient,
+    name: &str,
+    category: &str,
+    unit: &str,
+    amortized: bool,
+    months: Option<i64>,
+    deduct: bool,
+    remark: Option<&String>,
+) -> Result<Value, BosError> {
+    let year = Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))?;
+    let seq = listq::next_seq(db, "cost_item", "cost_item", year).await?;
+    let item_id = format!("CI-{seq:06}");
+
+    let mut p = Params::default();
+    let ph = [
+        p.push(Value::String(item_id.clone())),
+        p.push(Value::String(name.to_string())),
+        p.push(Value::String(category.to_string())),
+        p.push(Value::String(unit.to_string())),
+        p.push(Value::from(amortized)),
+        p.push(months.map(Value::from).unwrap_or(Value::Null)),
+        p.push(Value::from(deduct)),
+        p.push(nn(remark).map(|s| Value::String(s.to_string())).unwrap_or(Value::Null)),
+        p.push(Value::from(ROW_VERSION_INIT)),
+    ];
+    let casts = ["text", "text", "text", "text", "boolean", "int", "boolean", "text", "int"];
+    let values = ph
+        .iter()
+        .zip(casts.iter())
+        .map(|(ph, ty)| format!("{ph}::{ty}"))
+        .collect::<Vec<_>>()
+        .join(", ");
+    // 列序=上面 `ph` 的入参序(⛔ 错位=串列)。`status` 不写=吃列默认值 `'active'`
+    // (openapi 的 save 请求体⛔ status 字段)。
+    let sql = format!(
+        "INSERT INTO cost_item (item_id, item_name, category, billing_unit, is_amortized, \
+         amortization_months, deduct_from_base, remark, row_version) VALUES ({values})"
+    );
+    let affected = db.dml(&sql, p.values()).await?;
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "新增成本项写入异常:item_id={item_id} affected_rows={affected}"
+        )));
+    }
+    fetch_item_json(db, &item_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("新增成本项写入后回读失败:item_id={item_id}")))
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn do_update_item(
+    db: &UdsClient,
+    item_id: &str,
+    name: &str,
+    category: &str,
+    unit: &str,
+    amortized: bool,
+    months: Option<i64>,
+    deduct: bool,
+    remark: Option<&String>,
+    row_version: Option<i64>,
+) -> Result<Value, BosError> {
+    let cur = fetch_item(db, item_id)
+        .await?
+        .ok_or_else(|| BosError::not_found(format!("成本项不存在:{item_id}")))?;
+
+    let mut p = Params::default();
+    let pid = p.push(Value::String(item_id.to_string()));
+    let mut sets: Vec<String> = Vec::new();
+    if name != cur.item_name.trim() {
+        let v = p.push(Value::String(name.to_string()));
+        sets.push(format!("item_name = {v}::text"));
+    }
+    if category != cur.category.as_deref().map(str::trim).unwrap_or_default() {
+        let v = p.push(Value::String(category.to_string()));
+        sets.push(format!("category = {v}::text"));
+    }
+    if unit != cur.billing_unit.as_deref().map(str::trim).unwrap_or_default() {
+        let v = p.push(Value::String(unit.to_string()));
+        sets.push(format!("billing_unit = {v}::text"));
+    }
+    // 摊销两列=一对:未勾选 ⇒ 月数一律清空(⛔ 留脏值)。
+    let am = p.push(Value::from(amortized));
+    sets.push(format!("is_amortized = {am}::boolean"));
+    let mo = p.push(months.map(Value::from).unwrap_or(Value::Null));
+    sets.push(format!("amortization_months = {mo}::int"));
+    let dfb = p.push(Value::from(deduct));
+    sets.push(format!("deduct_from_base = {dfb}::boolean"));
+    // `remark` 非 openapi 必填 ⇒ 未提交=不动(⛔ 把库里既有备注抹掉);提交空串=清空。
+    if let Some(raw) = remark {
+        let rm = p.push(nn(Some(raw)).map(|s| Value::String(s.to_string())).unwrap_or(Value::Null));
+        sets.push(format!("remark = {rm}::text"));
+    }
+    sets.push("row_version = row_version + 1".to_string());
+
+    let mut preds = vec![format!("item_id = {pid}::text")];
+    if let Some(rv) = row_version {
+        let v = p.push(Value::from(rv));
+        preds.push(format!("row_version = {v}::int"));
+    }
+    let sql = format!(
+        "UPDATE cost_item SET {} WHERE {}",
+        sets.join(", "),
+        preds.join(" AND ")
+    );
+    let affected = db.dml(&sql, p.values()).await?;
+    if affected == 0 {
+        // 影响 0 行=两种成因,文案⛔ 混用。
+        return Err(match fetch_item(db, item_id).await? {
+            None => BosError::not_found(format!("成本项不存在:{item_id}")),
+            Some(_) => BosError::biz(
+                ErrorCode::ConflictS407,
+                format!("成本项已被他人修改(row_version 不符),请刷新后重试:{item_id}"),
+            ),
+        });
+    }
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "成本项更新影响行数异常:item_id={item_id} affected_rows={affected}"
+        )));
+    }
+    fetch_item_json(db, item_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("成本项更新后回读失败:{item_id}")))
+}
+
+pub async fn item_save(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<CostItemSaveReq>,
+) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin]) { return json_err(e); }
-    json_ok(json!({ "saved": true, "req": b }))
+    match do_save_item(state.db.as_ref(), &body).await {
+        Ok(v) => json_ok(with_item_pending(v)),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn item_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [] }))
+
+fn can_view(auth: &bos_scope::AuthContext) -> Result<(), bos_core::BosError> {
+    auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub])
+}
+
+pub async fn item_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<CostItemListReq>,
+) -> Response {
+    if let Err(e) = can_view(&auth) { return json_err(e); }
+    let mut p = Params::default();
+    let mut w: Vec<String> = Vec::new();
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        w.push(format!("ci.item_name LIKE {k}"));
+    }
+    if let Some(s) = p.push_eq(body.status.as_deref()) {
+        w.push(format!("ci.status = {s}::text"));
+    }
+    let from_where = format!("FROM cost_item ci {}", p.where_clause(&w));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT {ITEM_COLS} FROM cost_item ci {} \
+         ORDER BY ci.item_name LIMIT {lim} OFFSET {off}",
+        p.where_clause(&w)
+    );
+    let rows = match state.db.query_all::<ItemRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    json_ok(json!({
+        "items": rows.iter().map(item_json).collect::<Vec<Value>>(),
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+        "columns_pending": ITEM_COLUMNS_PENDING,
+    }))
 }
-pub async fn amount_save(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
+
+/* ── 成本金额 ───────────────────────────────────────────────────── */
+
+#[derive(Deserialize)]
+pub struct CostAmountListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub province_node_id: Option<String>,
+    pub operator_id: Option<String>,
+    pub period: Option<String>,
+}
+
+/// `/cost_amount/save@v1`(`src/openapi.yaml:3610`)。
+/// `items[].amount_cents` 空/省略=删除该差异行(`src/openapi.yaml:3613`/`:3643`/`:3652`)。
+#[derive(Deserialize)]
+pub struct CostAmountSaveReq {
+    pub province_node_id: Option<String>,
+    pub operator_id: Option<String>,
+    pub items: Option<Vec<CostAmountSaveItem>>,
+}
+
+#[derive(Deserialize)]
+pub struct CostAmountSaveItem {
+    pub cost_item_id: Option<String>,
+    pub amount_cents: Option<i64>,
+    pub row_version: Option<i64>,
+}
+
+#[derive(Deserialize)]
+struct AmountRow {
+    #[serde(deserialize_with = "de::as_string")]
+    item_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    period: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    amount_cents: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    province_node_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    operator_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    row_version: Option<String>,
+}
+
+/// 透视格(同省份×运营商×成本项×账期可能有多行 ⇒ 金额求和;任一行解析不出来 ⇒ `null`,⛔ 冒充 0)。
+#[derive(Default)]
+struct Cell {
+    item_id: String,
+    period: Option<String>,
+    amount: Option<i64>,
+    row_version: Option<String>,
+    rows: usize,
+}
+
+#[derive(Default)]
+struct PivotAgg {
+    province_node_id: String,
+    operator_id: String,
+    order: Vec<(String, Option<String>)>,
+    cells: HashMap<(String, Option<String>), Cell>,
+}
+
+/// 差异行唯一键谓词=`item_id × province_node_id × operator_id`,外加 dev 骨架附加列 `period`
+/// 作辅助键(`IS NOT DISTINCT FROM` ⇒ 参数为 `NULL` 时命中「账期为空」的行)。
+///
+/// `src/openapi.yaml:3610` 的 save 请求体⛔ `period` 字段 ⇒ 本接口只读写 `period` 为空的差异行,
+/// 存量带账期的种子行原样不动(差异登在响应 `message` 里)。
+fn axis_pred(p: &mut Params, item_id: &str, province: &str, operator: &str) -> String {
+    let i = p.push(Value::String(item_id.to_string()));
+    let pv = p.push(Value::String(province.to_string()));
+    let op = p.push(Value::String(operator.to_string()));
+    let pd = p.push(Value::Null);
+    format!(
+        "item_id = {i}::text AND province_node_id = {pv}::text AND operator_id = {op}::text \
+         AND period IS NOT DISTINCT FROM {pd}::text"
+    )
+}
+
+#[derive(Deserialize)]
+struct AmountHit {
+    #[serde(deserialize_with = "de::as_string")]
+    id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    row_version: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct SavedRow {
+    #[serde(deserialize_with = "de::as_string")]
+    item_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    amount_cents: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    row_version: Option<String>,
+}
+
+/// 命中差异行(四元组);⛔ `ON CONFLICT … DO UPDATE`(`qualify()` 会把 `DO UPDATE SET` 改写坏)。
+async fn hit_amount(db: &UdsClient, item_id: &str, province: &str, operator: &str) -> Result<Option<AmountHit>, BosError> {
+    let mut p = Params::default();
+    let pred = axis_pred(&mut p, item_id, province, operator);
+    let sql = format!(
+        "SELECT id, row_version FROM cost_amount WHERE {pred} ORDER BY id LIMIT 1"
+    );
+    db.query_one::<AmountHit>(&sql, p.values()).await
+}
+
+/// 请求带的 `row_version` 与库里现值比对(不符 ⇒ 冲突)。
+/// `/dml/batch@v1` ⛔ 批内条件中止 ⇒ 乐观锁只能在这里**前置**判定。
+fn check_version(item_id: &str, want: Option<i64>, have: Option<&str>) -> Result<(), BosError> {
+    let Some(want) = want else { return Ok(()) };
+    let cur = have.unwrap_or("").trim();
+    let cur_i = cur.parse::<i64>().ok();
+    match cur_i {
+        Some(v) if v == want => Ok(()),
+        _ => Err(BosError::biz(
+            ErrorCode::ConflictS407,
+            format!(
+                "成本金额差异行已被他人修改(row_version 不符),请刷新后重试:成本项 {item_id}(库里={})",
+                if cur.is_empty() { "(空)" } else { cur }
+            ),
+        )),
+    }
+}
+
+async fn do_save_amount(db: &UdsClient, b: &CostAmountSaveReq) -> Result<Value, BosError> {
+    let province = nn(b.province_node_id.as_ref())
+        .ok_or_else(|| BosError::bad_params("province_node_id 不能为空"))?
+        .to_string();
+    let operator = nn(b.operator_id.as_ref())
+        .ok_or_else(|| BosError::bad_params("operator_id 不能为空"))?
+        .to_string();
+    let items = b.items.as_ref().filter(|v| !v.is_empty()).ok_or_else(|| {
+        BosError::bad_params("items 为空:没有需要保存的差异行")
+    })?;
+
+    // 外键前置校验:查不到=显式失败(⛔ 当空集放行),取数失败由 `?` 上抛。
+    if !row_exists(db, REGION_TABLE, REGION_KEY, &province).await? {
+        return Err(BosError::not_found(format!(
+            "省份节点在区域维度({REGION_TABLE})中不存在:{province}"
+        )));
+    }
+    if !row_exists(db, "operator", "operator_id", &operator).await? {
+        return Err(BosError::not_found(format!("运营商不存在:{operator}")));
+    }
+
+    let mut ids: Vec<String> = Vec::new();
+    for it in items.iter() {
+        let id = nn(it.cost_item_id.as_ref())
+            .ok_or_else(|| BosError::bad_params("items[].cost_item_id 不能为空"))?
+            .to_string();
+        if ids.contains(&id) {
+            return Err(BosError::bad_params(format!(
+                "同一成本项在一次提交里出现多次:{id}(差异行唯一键=省份×运营商×成本项)"
+            )));
+        }
+        ids.push(id);
+    }
+    let mut mp = Params::default();
+    let in_pred = push_in(&mut mp, "item_id", &ids, "text");
+    let sql = format!("SELECT item_id AS id FROM cost_item WHERE {in_pred}");
+    let found: HashSet<String> = db
+        .query_all::<IdRow>(&sql, mp.values())
+        .await?
+        .into_iter()
+        .map(|r| r.id)
+        .collect();
+    let missing: Vec<String> = ids.iter().filter(|i| !found.contains(i.as_str())).cloned().collect();
+    if !missing.is_empty() {
+        return Err(BosError::not_found(format!("成本项不存在:{}", missing.join("、"))));
+    }
+
+    enum Kind {
+        Insert,
+        Update,
+        Delete,
+    }
+    let mut stmts: Vec<DmlStatement> = Vec::new();
+    let mut kinds: Vec<Kind> = Vec::new();
+
+    for it in items.iter() {
+        let item_id = nn(it.cost_item_id.as_ref()).unwrap_or_default();
+        let hit = hit_amount(db, item_id, &province, &operator).await?;
+        match (hit, it.amount_cents) {
+            (Some(h), None) => {
+                // openapi:3613/3643/3652=金额留空表示删除该差异行。
+                check_version(item_id, it.row_version, h.row_version.as_deref())?;
+                let mut p = Params::default();
+                let id = p.push(Value::String(h.id));
+                stmts.push(DmlStatement::new(
+                    format!("DELETE FROM cost_amount WHERE id = {id}::bigint"),
+                    p.values().to_vec(),
+                ));
+                kinds.push(Kind::Delete);
+            }
+            (None, None) => {}
+            (Some(h), Some(v)) => {
+                if v < 0 {
+                    return Err(BosError::bad_params(format!(
+                        "amount_cents ⛔ 为负(留空才表示删除):成本项 {item_id} 收到 {v}"
+                    )));
+                }
+                check_version(item_id, it.row_version, h.row_version.as_deref())?;
+                let mut p = Params::default();
+                let amt = p.push(Value::from(v));
+                let id = p.push(Value::String(h.id));
+                stmts.push(DmlStatement::new(
+                    format!(
+                        "UPDATE cost_amount SET amount_cents = {amt}::bigint, \
+                         row_version = row_version + 1 WHERE id = {id}::bigint"
+                    ),
+                    p.values().to_vec(),
+                ));
+                kinds.push(Kind::Update);
+            }
+            (None, Some(v)) => {
+                if v < 0 {
+                    return Err(BosError::bad_params(format!(
+                        "amount_cents ⛔ 为负(留空才表示删除):成本项 {item_id} 收到 {v}"
+                    )));
+                }
+                // 四元组未命中=新建行:请求带的 `row_version` 无从比对(库里根本没有该行)⇒ 忽略。
+                let mut p = Params::default();
+                let ph = [
+                    p.push(Value::String(item_id.to_string())),
+                    p.push(Value::String(province.clone())),
+                    p.push(Value::String(operator.clone())),
+                    p.push(Value::Null),
+                    p.push(Value::from(v)),
+                    p.push(Value::from(ROW_VERSION_INIT)),
+                ];
+                let casts = ["text", "text", "text", "text", "bigint", "int"];
+                let values = ph
+                    .iter()
+                    .zip(casts.iter())
+                    .map(|(ph, ty)| format!("{ph}::{ty}"))
+                    .collect::<Vec<_>>()
+                    .join(", ");
+                // `id` 是 BIGSERIAL ⇒ ⛔ 显式赋值,吃序列默认值。
+                stmts.push(DmlStatement::new(
+                    format!(
+                        "INSERT INTO cost_amount (item_id, province_node_id, operator_id, period, \
+                         amount_cents, row_version) VALUES ({values})"
+                    ),
+                    p.values().to_vec(),
+                ));
+                kinds.push(Kind::Insert);
+            }
+        }
+    }
+
+    let (mut inserted, mut updated, mut deleted) = (0i64, 0i64, 0i64);
+    if !stmts.is_empty() {
+        let results = db.dml_batch(&stmts).await?;
+        if results.len() != stmts.len() {
+            return Err(BosError::internal(format!(
+                "成本金额写入回执条数不符:提交 {} 条,回执 {} 条",
+                stmts.len(),
+                results.len()
+            )));
+        }
+        for (k, r) in kinds.iter().zip(results.iter()) {
+            let n = r.affected_rows.unwrap_or(0);
+            match k {
+                Kind::Insert if n == 1 => inserted += 1,
+                Kind::Update if n == 1 => updated += 1,
+                Kind::Delete => deleted += i64::try_from(n).unwrap_or(i64::MAX),
+                Kind::Insert | Kind::Update => {
+                    return Err(BosError::internal(format!(
+                        "成本金额写入影响行数异常(期望 1,实际 {n}):同批其余语句已提交,请复核后重试"
+                    )));
+                }
+            }
+        }
+    }
+
+    // 回读真值再应答(⛔ 回显请求体)。
+    let mut rp = Params::default();
+    let in_pred = push_in(&mut rp, "ca.item_id", &ids, "text");
+    let pv = rp.push(Value::String(province.clone()));
+    let op = rp.push(Value::String(operator.clone()));
+    let pd = rp.push(Value::Null);
+    let sql = format!(
+        "SELECT ca.item_id, ca.amount_cents, ca.row_version FROM cost_amount ca \
+         WHERE {in_pred} AND ca.province_node_id = {pv}::text AND ca.operator_id = {op}::text \
+         AND ca.period IS NOT DISTINCT FROM {pd}::text ORDER BY ca.item_id"
+    );
+    let saved: Vec<Value> = db
+        .query_all::<SavedRow>(&sql, rp.values())
+        .await?
+        .iter()
+        .map(|r| {
+            json!({
+                "province_node_id": province,
+                "operator_id": operator,
+                "cost_item_id": r.item_id,
+                "amount_cents": as_num(&r.amount_cents),
+                "row_version": as_opt_num(r.row_version.as_deref()),
+            })
+        })
+        .collect();
+
+    Ok(json!({
+        "province_node_id": province,
+        "operator_id": operator,
+        "saved": true,
+        "inserted_count": inserted,
+        "updated_count": updated,
+        "deleted_count": deleted,
+        "submitted_count": items.len(),
+        "rows": saved,
+        "message": "差异行唯一键=省份×运营商×成本项,dev 骨架附加列 period 以 \
+                    `IS NOT DISTINCT FROM` 参与匹配;openapi 的 save 请求体未含 period \
+                    (src/openapi.yaml:3610)⇒ 本次只读写 period 为空的差异行,\
+                    存量带账期的行不受影响。amount_cents 留空=删除该差异行\
+                    (src/openapi.yaml:3613/:3643/:3652),写 0 是真实金额、⛔ 不删行。",
+    }))
+}
+
+pub async fn amount_save(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<CostAmountSaveReq>,
+) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin]) { return json_err(e); }
-    json_ok(json!({ "saved": true, "req": b }))
+    match do_save_amount(state.db.as_ref(), &body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn amount_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [] }))
+
+/// 扁平差异行(在册真值)。
+fn flat_json(
+    r: &AmountRow,
+    province_name: Value,
+    operator_name: Value,
+    item_name: Value,
+    category: Value,
+) -> Value {
+    json!({
+        "cost_item_id": r.item_id,
+        "item_name": item_name,
+        "category": category,
+        "province_node_id": r.province_node_id,
+        "province_name": province_name,
+        "operator_id": r.operator_id,
+        "operator_name": operator_name,
+        "period": r.period,
+        "amount_cents": as_num(&r.amount_cents),
+        "row_version": as_opt_num(r.row_version.as_deref()),
+    })
+}
+
+fn uniq(ids: impl Iterator<Item = String>) -> Vec<String> {
+    let mut out: Vec<String> = ids.collect();
+    out.sort();
+    out.dedup();
+    out
+}
+
+pub async fn amount_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<CostAmountListReq>,
+) -> Response {
+    if let Err(e) = can_view(&auth) { return json_err(e); }
+    let db = state.db.as_ref();
+
+    let mut p = Params::default();
+    let mut w: Vec<String> = Vec::new();
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        w.push(format!(
+            "EXISTS (SELECT 1 FROM cost_item kai WHERE kai.item_id = ca.item_id AND kai.item_name LIKE {k})"
+        ));
+    }
+    if let Some(s) = p.push_eq(body.period.as_deref()) {
+        w.push(format!("ca.period = {s}::text"));
+    }
+    if let Some(s) = p.push_eq(body.province_node_id.as_deref()) {
+        w.push(format!("ca.province_node_id = {s}::text"));
+    }
+    if let Some(s) = p.push_eq(body.operator_id.as_deref()) {
+        w.push(format!("ca.operator_id = {s}::text"));
+    }
+    // 未归属=两根轴任一为空(一期种子遗留)。
+    let mut w_un = w.clone();
+    w_un.push("(ca.province_node_id IS NULL OR ca.operator_id IS NULL)".to_string());
+
+    let from_where = format!("FROM cost_amount ca {}", p.where_clause(&w));
+    let n = match total(db, &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let unattributed_total = match total(
+        db,
+        &format!("FROM cost_amount ca {}", p.where_clause(&w_un)),
+        p.values(),
+    )
+    .await
+    {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT ca.item_id, ca.period, ca.amount_cents, ca.province_node_id, ca.operator_id, \
+         ca.row_version FROM cost_amount ca {} \
+         ORDER BY ca.province_node_id, ca.operator_id, ca.item_id, ca.period \
+         LIMIT {lim} OFFSET {off}",
+        p.where_clause(&w)
+    );
+    let rows = match db.query_all::<AmountRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+
+    let item_ids = uniq(rows.iter().map(|r| r.item_id.clone()));
+    let op_ids = uniq(rows.iter().filter_map(|r| nn(r.operator_id.as_ref()).map(str::to_string)));
+    let item_names = match pairs_by(db, "cost_item", "item_id", "item_name", &item_ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let item_cats = match pairs_by(db, "cost_item", "item_id", "category", &item_ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let op_names = match pairs_by(db, "operator", "operator_id", "name", &op_ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+
+    let mut flat: Vec<Value> = Vec::with_capacity(rows.len());
+    let mut unattributed: Vec<Value> = Vec::new();
+    let mut pivots: HashMap<(String, String), PivotAgg> = HashMap::new();
+    for r in &rows {
+        let item_name = named(&item_names, &r.item_id);
+        let category = named(&item_cats, &r.item_id);
+        let operator_name = r
+            .operator_id
+            .as_deref()
+            .map(|o| named(&op_names, o.trim()))
+            .unwrap_or(Value::Null);
+        // dev 库没有区域节点名称表(只有闭包表 dim_node_ancestor)⇒ 省份名⛔ 编,回 null。
+        let row_json = flat_json(r, Value::Null, operator_name.clone(), item_name, category);
+        // `rows`=本批全部明细(含未归属),⛔ 把未归属行从明细里藏掉。
+        flat.push(row_json.clone());
+        let axes = (
+            nn(r.province_node_id.as_ref()).map(str::to_string),
+            nn(r.operator_id.as_ref()).map(str::to_string),
+        );
+        let (Some(pv), Some(op)) = axes else {
+            unattributed.push(row_json);
+            continue;
+        };
+
+        let agg = pivots
+            .entry((pv.clone(), op.clone()))
+            .or_insert_with(|| PivotAgg {
+                province_node_id: pv,
+                operator_id: op,
+                ..Default::default()
+            });
+        let key = (r.item_id.clone(), r.period.clone());
+        if !agg.order.contains(&key) {
+            agg.order.push(key.clone());
+        }
+        let cell = agg.cells.entry(key).or_insert_with(|| Cell {
+            item_id: r.item_id.clone(),
+            period: r.period.clone(),
+            ..Default::default()
+        });
+        cell.rows += 1;
+        let parsed = r.amount_cents.trim().parse::<i64>().ok();
+        cell.amount = match (cell.amount, parsed) {
+            (Some(a), Some(b)) => Some(a + b),
+            _ => None,
+        };
+        cell.row_version = if cell.rows == 1 {
+            r.row_version.clone()
+        } else {
+            None
+        };
+    }
+
+    let mut keys: Vec<&(String, String)> = pivots.keys().collect();
+    keys.sort();
+    let items: Vec<Value> = keys
+        .iter()
+        .map(|k| {
+            let agg = &pivots[*k];
+            let mut order = agg.order.clone();
+            order.sort();
+            json!({
+                "province_node_id": agg.province_node_id,
+                "province_name": Value::Null,
+                "operator_id": agg.operator_id,
+                "operator_name": named(&op_names, &agg.operator_id),
+                "items": order.iter().map(|key| {
+                    let c = &agg.cells[key];
+                    json!({
+                        "province_node_id": agg.province_node_id,
+                        "operator_id": agg.operator_id,
+                        "cost_item_id": c.item_id,
+                        "item_name": named(&item_names, &c.item_id),
+                        "category": named(&item_cats, &c.item_id),
+                        "period": c.period,
+                        "amount_cents": c.amount.map(Value::from).unwrap_or(Value::Null),
+                        "row_version": as_opt_num(c.row_version.as_deref()),
+                    })
+                }).collect::<Vec<Value>>(),
+            })
+        })
+        .collect();
+
+    let pivot_rows = items.len();
+    let available = pivot_rows > 0;
+    let message = format!(
+        "透视行=省份节点×运营商(列=成本项),只收两根轴齐备的差异行;total=本次真透视出的行数,\
+         明细总数见 rows_total({n})。本批明细里 {un} 行缺少省份或运营商轴(一期种子只有 \
+         item_id/period/amount_cents,见 src/migrations/dev/20261104000001_bos_core_tables.sql:452),\
+         已单列 rows_unattributed(全量计数 {unattributed_total}),未计入透视、⛔ 冒充某省数据。",
+        un = unattributed.len(),
+    ) + " dev 库无区域节点名称表(区域维度只有闭包表 dim_node_ancestor),province_name 无数据源⇒ 回 null。";
+
+    json_ok(json!({
+        "items": items,
+        "total": pivot_rows,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+        "available": available,
+        "message": message,
+        "rows": flat,
+        "rows_total": n,
+        "rows_unattributed": unattributed,
+        "rows_unattributed_total": unattributed_total,
+    }))
 }

File diff ditekan karena terlalu besar
+ 1547 - 30
src/modules/account/src/handlers/customer.rs


+ 1426 - 15
src/modules/account/src/handlers/ent_team.rs

@@ -1,22 +1,1433 @@
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, KltCode, RoleCode};
+use bos_platform::clients::uds::{de, DmlStatement, DmlStatementResult};
+use bos_scope::AuthContext;
+use chrono::Local;
+use serde::Deserialize;
+use serde_json::{json, Value};
 
-fn admin_only(auth: &bos_scope::AuthContext) -> Result<(), bos_core::BosError> {
+use super::customer::{cell, count_where, one_row};
+use super::listq::{count_by, mask_mobile, next_seq, push_in, scope_stats_by, total, Params};
+use super::operator::gen_initial_password;
+use super::ops_team::AUDIT_NOTE;
+
+/// 时间列在册缺陷:⛔ 可校验、⛔ 可还原 ⇒ 出参如实带出,探针⛔ 对其断言。
+const TIME_NOTE: &str = "dev UDS 对 timestamptz/date 写入静默落 NULL(在册基础设施缺陷)\
+                        ⇒ created_at/updated_at ⛔ 可校验";
+
+/// `bos_data_scope` 的持有者类型(与 `scope_get` 只读口径同源)。
+const HOLDER_ENT_TEAM: &str = "ent_team";
+
+/// 主账号/子账号的角色码(组织§5.4 OR-11 逐字:转交必须连 `role_code` 一起换,
+/// 权限按角色判,否则权限不随人走)。
+const ROLE_MAIN: &str = "opsMain";
+const ROLE_SUB: &str = "opsSub";
+
+/// 运营团队列表(`bos.ent_team.list@v1`):一条团队带负责人登录名与成员数。
+#[derive(Deserialize)]
+pub struct TeamListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct TeamRow {
+    #[serde(deserialize_with = "de::as_string")]
+    team_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    team_name: String,
+    is_builtin: Option<bool>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    created_at: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    owner_username: Option<String>,
+    /// 备注(`ent_team.remark`,第 1 册§2.3 在册列)。
+    #[serde(deserialize_with = "de::as_opt_string")]
+    remark: Option<String>,
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<TeamListReq>,
+) -> Response {
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+    if auth.role != RoleCode::Admin && auth.role != RoleCode::OpsMain && auth.role != RoleCode::OpsSub {
+        return json_err(bos_core::BosError::forbidden_role("无权查看运营团队列表"));
+    }
+    // 「按名称 / 备注」关键字筛选=`team_name` **OR** `remark`(第 1 册 05 册 §5.4 OR-09):
+    // 两条 OR 必须整体加括号,否则会把其余 AND 条件一起短路掉。
+    if let Some(kw) = body.keyword.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        let lik = format!("%{kw}%");
+        let k1 = p.push(Value::String(lik.clone()));
+        let k2 = p.push(Value::String(lik));
+        preds.push(format!("(t.team_name_norm LIKE {k1} OR t.remark LIKE {k2})"));
+    }
+    let from_where = format!("FROM ent_team t {}", p.where_clause(&preds));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT t.team_id, t.team_name, t.remark, t.is_builtin, t.created_at, o.username AS owner_username \
+         FROM ent_team t LEFT JOIN bos_user_binding o ON o.user_id = t.owner_user_id {} \
+         ORDER BY t.is_builtin DESC, t.team_name LIMIT {lim} OFFSET {off}",
+        p.where_clause(&preds)
+    );
+    let rows = match state.db.query_all::<TeamRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let ids: Vec<String> = rows.iter().map(|r| r.team_id.clone()).collect();
+    let counts = match count_by(state.db.as_ref(), "ent_team_member", "team_id", &ids).await {
+        Ok(c) => c,
+        Err(e) => return json_err(e),
+    };
+    // 负责范围/覆盖客户(`bos_data_scope` +挂载表 + `dim_node_ancestor` 子树)。
+    // 内置「总部·不限区域」团队的范围为空=**不限**(组织§5.4),覆盖客户取全量在册客户;
+    // 非内置团队范围为空=**未配置** ⇒ 覆盖客户回 `null`(⛔ 折算成 0 冒充"已配置且无客户")。
+    let mut scopes = match scope_stats_by(state.db.as_ref(), HOLDER_ENT_TEAM, &ids, false).await {
+        Ok(s) => s,
+        Err(e) => return json_err(e),
+    };
+    let builtin_open: Vec<String> = rows
+        .iter()
+        .filter(|r| r.is_builtin.unwrap_or(false))
+        .map(|r| r.team_id.clone())
+        .filter(|id| scopes.get(id).map(|s| s.regions.is_empty() && s.customers.is_empty()).unwrap_or(false))
+        .collect();
+    if !builtin_open.is_empty() {
+        let all = match total(state.db.as_ref(), "FROM customer c WHERE c.deleted_at IS NULL", &[]).await {
+            Ok(v) => v,
+            Err(e) => return json_err(e),
+        };
+        for id in builtin_open {
+            if let Some(s) = scopes.get_mut(&id) {
+                s.coverage = Some(all);
+            }
+        }
+    }
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            let sc = scopes.get(&r.team_id).cloned().unwrap_or_default();
+            json!({
+                "team_id": r.team_id,
+                "team_name": r.team_name,
+                // 备注(在册列 `ent_team.remark`):⛔ 参与算账与判权,⛔ 参与唯一键。
+                // ⚠️ 本行⛔ `settle_mode`/`settle_value`=分成方是封闭的三类(运营商/合伙人/
+                // 运维团队,第 4 册§5.1/§5.2),运营团队⛔ 分成方(2026-11-08 业主定案,`PG-7` 路线 A)。
+                "remark": r.remark,
+                "is_builtin": r.is_builtin.unwrap_or(false),
+                "owner_username": r.owner_username,
+                "member_count": counts.get(&r.team_id).copied().unwrap_or(0),
+                // 「所属区域」列=负责范围里的授权节点(`ent_team` 表⛔ region 列,区域归属
+                // 按设计只落在 `bos_data_scope`,第 1 册§2);空数组+`is_builtin` 由前端折算成
+                // 「不限」或「未配置」,⛔ 显示成"某个真实区域"。
+                "scope_regions": sc.regions,
+                "scope_customers": sc.customers,
+                "coverage_customers": sc.coverage,
+                "created_at": r.created_at,
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
+}
+
+// ══ 写侧守卫(组织§5.4 OR-09~OR-12)════════════════════════════════════
+
+/// 写入口闸门(OR-09 逐字「写入口限总运营」)。
+///
+/// ⚠️ 与 OR-11「运营主账号限本团队」**冲突**:`openapi.yaml` 与 AC 权限键面都是「仅 admin」
+/// (`bos.ent_team.update`/`.manage`/`.scope.manage`),代码随闸门真源 ⇒ 本轮 `opsMain`
+/// 一律 20010,冲突登 18 册待裁。
+fn admin_only(auth: &AuthContext) -> Result<(), BosError> {
     auth.require_roles(&[RoleCode::Admin])
 }
-pub async fn create(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = admin_only(&auth) { return json_err(e); }
-    json_ok(json!({ "team_id": null, "req": body }))
+
+/// 归一化(`ent_team.team_name_norm`/`bos_user_binding.username_norm` 列注释同口径:
+/// 去空白后小写)。
+fn norm(s: &str) -> String {
+    s.trim().to_lowercase()
+}
+
+fn year_now() -> Result<i32, BosError> {
+    Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))
+}
+
+/// `one_row` 回值里的布尔取法(UDS 可能回 JSON 布尔,也可能回 `'t'`/`'true'` 文本)。
+fn flag(v: &Value, col: &str) -> bool {
+    match v.get(col) {
+        Some(Value::Bool(b)) => *b,
+        Some(Value::String(s)) => matches!(s.as_str(), "true" | "t" | "1"),
+        Some(Value::Number(n)) => n.as_i64() == Some(1),
+        _ => false,
+    }
+}
+
+/// 逐语句 `affected_rows` 核对:一条未落一行即整单判失败(⛔ 把 `10000` 当成功)。
+fn zeros(results: &[DmlStatementResult], labels: &[String]) -> Vec<String> {
+    results
+        .iter()
+        .filter(|r| r.affected_rows != Some(1))
+        .map(|r| {
+            labels
+                .get(r.index)
+                .cloned()
+                .unwrap_or_else(|| format!("语句 #{}", r.index))
+        })
+        .collect()
+}
+
+/// 团队档案(写侧守卫与回读共用)。
+struct TeamMeta {
+    team_id: String,
+    team_name: String,
+    /// 备注(`ent_team.remark VARCHAR(200) NULL`,第 1 册§2.3 在册列)。
+    remark: Option<String>,
+    is_builtin: bool,
+    owner_user_id: Option<String>,
+}
+
+async fn team_meta(state: &AppState, team_id: &str) -> Result<Option<TeamMeta>, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(team_id.to_string()));
+    let sql = format!(
+        "SELECT team_id, team_name, remark, is_builtin, owner_user_id::text AS owner_user_id \
+         FROM ent_team WHERE team_id = {ph}::text LIMIT 1"
+    );
+    Ok(one_row(state, &sql, p.values()).await?.map(|v| TeamMeta {
+        team_id: cell(&v, "team_id").unwrap_or_default(),
+        team_name: cell(&v, "team_name").unwrap_or_default(),
+        remark: cell(&v, "remark"),
+        is_builtin: flag(&v, "is_builtin"),
+        owner_user_id: cell(&v, "owner_user_id"),
+    }))
+}
+
+/// 档案必须存在(⛔ 把「查不到」折算成「已保存」)。
+async fn need_team(state: &AppState, team_id: &str) -> Result<TeamMeta, BosError> {
+    let t = team_id.trim();
+    if t.is_empty() {
+        return Err(BosError::bad_params("必须带 team_id"));
+    }
+    team_meta(state, t)
+        .await?
+        .ok_or_else(|| BosError::not_found(format!("运营团队 {t} 不存在(ent_team ⛔ 该行)")))
+}
+
+/// 成员行(`(user_id, is_primary)`,按 user_id 升序保持稳定)。
+async fn member_rows(state: &AppState, team_id: &str) -> Result<Vec<(String, bool)>, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(team_id.to_string()));
+    let sql = format!(
+        "SELECT user_id::text AS user_id, is_primary FROM ent_team_member \
+         WHERE team_id = {ph}::text ORDER BY user_id"
+    );
+    let rows: Vec<Value> = state.db.query_all::<Value>(&sql, p.values()).await?;
+    Ok(rows
+        .iter()
+        .map(|v| (cell(v, "user_id").unwrap_or_default(), flag(v, "is_primary")))
+        .collect())
+}
+
+/// 该团队当前主账号(`is_primary` 部分唯一索引 ⇒ 至多一行;查不到=该团队尚无主账号)。
+async fn primary_user(state: &AppState, team_id: &str) -> Result<Option<String>, BosError> {
+    Ok(member_rows(state, team_id)
+        .await?
+        .into_iter()
+        .find(|(_, p)| *p)
+        .map(|(u, _)| u))
+}
+
+/// 某账号的绑定行(`(username, mobile, role_code)`;⛔ 该账号=未开通)。
+async fn binding_of_user(
+    state: &AppState,
+    user_id: &str,
+) -> Result<Option<(String, Option<String>, String)>, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(user_id.to_string()));
+    let sql = format!(
+        "SELECT username, mobile, role_code FROM bos_user_binding WHERE user_id = {ph}::int8 LIMIT 1"
+    );
+    Ok(one_row(state, &sql, p.values()).await?.map(|v| {
+        (
+            cell(&v, "username").unwrap_or_default(),
+            cell(&v, "mobile"),
+            cell(&v, "role_code").unwrap_or_default(),
+        )
+    }))
+}
+
+/// 团队成员的展示行(成员清单/转交回执共用;手机号按需求§5.4 掩码)。
+async fn member_views(state: &AppState, team_id: &str) -> Result<Vec<Value>, BosError> {
+    let rows = member_rows(state, team_id).await?;
+    let mut out = Vec::with_capacity(rows.len());
+    for (uid, is_primary) in rows {
+        let b = binding_of_user(state, &uid).await?;
+        out.push(json!({
+            "user_id": uid,
+            "username": b.as_ref().map(|(u, _, _)| u.clone()),
+            "mobile": mask_mobile(b.as_ref().and_then(|(_, m, _)| m.as_deref())),
+            "role_code": b.as_ref().map(|(_, _, r)| r.clone()),
+            "is_primary": is_primary,
+        }));
+    }
+    Ok(out)
+}
+
+/// 登录名/手机号唯一性守卫(B001→20020、B002→20021;`exclude_user`=改绑时排除自己)。
+async fn account_guard(
+    state: &AppState,
+    username: &str,
+    mobile: Option<&str>,
+    exclude_user: Option<&str>,
+) -> Result<(), BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(norm(username)));
+    let mut pred = format!("username_norm = {ph}::text");
+    if let Some(u) = exclude_user {
+        let e = p.push(Value::String(u.to_string()));
+        pred.push_str(&format!(" AND user_id <> {e}::int8"));
+    }
+    let sql = format!("SELECT COUNT(1) AS n FROM bos_user_binding WHERE {pred}");
+    if count_where(state, &sql, p.values()).await? > 0 {
+        return Err(BosError::klt(
+            KltCode::B001,
+            format!("登录名「{username}」已被占用"),
+        ));
+    }
+    if let Some(m) = mobile {
+        let mut p = Params::default();
+        let ph = p.push(Value::String(m.to_string()));
+        let mut pred = format!("mobile = {ph}::text");
+        if let Some(u) = exclude_user {
+            let e = p.push(Value::String(u.to_string()));
+            pred.push_str(&format!(" AND user_id <> {e}::int8"));
+        }
+        let sql = format!("SELECT COUNT(1) AS n FROM bos_user_binding WHERE {pred}");
+        if count_where(state, &sql, p.values()).await? > 0 {
+            return Err(BosError::klt(
+                KltCode::B002,
+                format!("手机号「{m}」已被占用"),
+            ));
+        }
+    }
+    Ok(())
+}
+
+/// 团队名重复(`uq_ent_team_name` 的显式前置判定,⛔ 靠索引冲突报错兜底)。
+async fn name_dup(state: &AppState, name_norm: &str, exclude: Option<&str>) -> Result<Option<String>, BosError> {
+    let mut p = Params::default();
+    let ph1 = p.push(Value::String(name_norm.to_string()));
+    let mut sql = format!("SELECT team_id FROM ent_team WHERE team_name_norm = {ph1}::text");
+    if let Some(e) = exclude {
+        let ph2 = p.push(Value::String(e.to_string()));
+        sql.push_str(&format!(" AND team_id <> {ph2}::text"));
+    }
+    sql.push_str(" LIMIT 1");
+    Ok(one_row(state, &sql, p.values())
+        .await?
+        .and_then(|v| cell(&v, "team_id")))
+}
+
+/// 团队名重复的拒绝文案(`T201`=团队名重复,第 1 册§7.1 在册 ⇒ 可直接用)。
+async fn check_name_dup(state: &AppState, name_norm: &str, exclude: Option<&str>) -> Result<(), BosError> {
+    if let Some(holder) = name_dup(state, name_norm, exclude).await? {
+        return Err(BosError::klt(
+            KltCode::T201,
+            format!("运营团队名称重复(忽略大小写与首尾空白,全站唯一):已存在团队 {holder}"),
+        ));
+    }
+    Ok(())
+}
+
+fn check_team_name(raw: &str) -> Result<String, BosError> {
+    let name = raw.trim().to_string();
+    if name.is_empty() {
+        return Err(BosError::bad_params("团队名称不能为空"));
+    }
+    if name.chars().count() > 128 {
+        return Err(BosError::bad_params(format!(
+            "团队名称去空白后长度须 ≤128 个字符(ent_team.team_name),收到 {}",
+            name.chars().count()
+        )));
+    }
+    Ok(name)
+}
+
+/// 备注(`ent_team.remark VARCHAR(200) NULL`,第 1 册§2.3 在册列):去空白后 ≤200 字符,
+/// 全空=`None`(=未配置,落库 NULL)。⛔ 参与唯一键、⛔ 参与算账与判权谓词。
+fn check_remark(raw: Option<&str>) -> Result<Option<String>, BosError> {
+    let t = match raw.map(str::trim).filter(|s| !s.is_empty()) {
+        Some(t) => t.to_string(),
+        None => return Ok(None),
+    };
+    if t.chars().count() > 200 {
+        return Err(BosError::bad_params(format!(
+            "备注去空白后长度须 ≤200 个字符(ent_team.remark VARCHAR(200)),收到 {}",
+            t.chars().count()
+        )));
+    }
+    Ok(Some(t))
+}
+
+/// 手机号格式(`bos_user_binding.mobile` 列注释=11 位)。
+fn check_mobile(raw: Option<&str>) -> Result<Option<String>, BosError> {
+    let m = match raw.map(str::trim).filter(|s| !s.is_empty()) {
+        Some(m) => m.to_string(),
+        None => return Ok(None),
+    };
+    if m.chars().count() != 11 || !m.chars().all(|c| c.is_ascii_digit()) {
+        return Err(BosError::bad_params(format!("手机号须是 11 位纯数字,收到「{m}」")));
+    }
+    Ok(Some(m))
+}
+
+fn check_username(raw: &str) -> Result<String, BosError> {
+    let u = raw.trim().to_string();
+    if u.is_empty() {
+        return Err(BosError::bad_params("登录名不能为空(用于同步开通团队账号)"));
+    }
+    if u.chars().count() > 64 {
+        return Err(BosError::bad_params(format!(
+            "登录名去空白后长度须 ≤64 个字符(bos_user_binding.username),收到 {}",
+            u.chars().count()
+        )));
+    }
+    Ok(u)
+}
+
+/// OR-10「每团队有且仅有一个主账号」的拒绝文案(点名出路=先办转交)。
+fn has_primary_err(team_id: &str, holder: &str) -> BosError {
+    BosError::bad_params(format!(
+        "运营团队 {team_id} 已有主账号 user_id={holder}(OR-10:每团队有且仅有一个主账号,\
+         库侧 uq_ent_team_primary 部分唯一索引兜底)⇒ ⛔ 再指定主账号;换主账号请办 \
+         `ent_team/transfer_primary@v1`(OR-11,同事务连 role_code 一起换)"
+    ))
+}
+
+/// 运营团队发号:号段沿用在册种子形态 `ENT-<两位序号>`(dev 种子=ENT-01~ENT-04)。
+///
+/// ⚠️ `bos_seq_year` 在册只有 `customer`/`import_batch` 两个 kind ⇒ 首次取 `ent_team` 号时
+/// `next_seq` 以 `COUNT(ent_team)` 起步,直接拼号必撞既有号 ⇒ 与 `issue_partner_id` 同口径做
+/// **有界撞号重试**(序列单调递增 ⇒ 一定停在第一个空号上,⛔ 靠主键冲突报错兜底)。
+async fn issue_team_id(state: &AppState) -> Result<String, BosError> {
+    let year = year_now()?;
+    for attempt in 1..=500_i32 {
+        let seq = next_seq(state.db.as_ref(), "ent_team", "ent_team", year).await?;
+        let candidate = format!("ENT-{seq:02}");
+        if team_meta(state, &candidate).await?.is_none() {
+            return Ok(candidate);
+        }
+        if attempt == 500 {
+            return Err(BosError::internal(format!(
+                "运营团队发号连续 {attempt} 次撞号(年段 {year})⇒ bos_seq_year 计数与既有号段严重错位,\
+                 请人工校正 last_value 后重试"
+            )));
+        }
+    }
+    Err(BosError::internal("运营团队发号未进入循环".to_string()))
+}
+
+/// 平台建号(组织§4.2 管线);返回 `(user_id, 初始密码)`。
+async fn create_account(
+    state: &AppState,
+    nickname: &str,
+    username: &str,
+    mobile: Option<&str>,
+) -> Result<(String, String), BosError> {
+    let initial_password = gen_initial_password();
+    let created = state
+        .platform
+        .user_create(json!({
+            "scope_type": "end_user",
+            "scope_id": state.project_id.clone(),
+            "project_id": state.project_id.clone(),
+            "user_type": "end_user",
+            "env": state.data_env.clone(),
+            "stage": state.seoh_env.clone(),
+            "username": username,
+            "password": initial_password.clone(),
+            "nickname": nickname,
+            "phone": mobile.unwrap_or_default()
+        }))
+        .await
+        .map_err(|e| BosError::internal(format!("团队账号建号未成功,本次⛔ 写任何本地数据:{e}")))?;
+    let user_id = created
+        .pointer("/data/id")
+        .and_then(Value::as_str)
+        .unwrap_or_default()
+        .to_string();
+    if user_id.is_empty() {
+        return Err(BosError::internal(format!("平台建号应答未回 user_id,本地⛔ 写:{created}")));
+    }
+    Ok((user_id, initial_password))
+}
+
+/// `bos_user_binding` 绑定行语句(`(opsMain|opsSub, ent_team, team_id)` 形态,
+/// 与 dev 种子逐字同构)。
+fn binding_insert(user_id: &str, role_code: &str, team_id: &str, username: &str, mobile: Option<&str>) -> DmlStatement {
+    DmlStatement::new(
+        "INSERT INTO bos_user_binding (user_id, scope_type, scope_id, role_code, subject_type, \
+         subject_id, username, username_norm, mobile, entry_only) \
+         VALUES ($1::int8, $2::text, $3::text, $4::text, $5::text, $6::text, $7::text, $8::text, $9::text, FALSE)"
+            .to_string(),
+        vec![
+            Value::String(user_id.to_string()),
+            Value::String("end_user".to_string()),
+            Value::String("".to_string()),
+            Value::String(role_code.to_string()),
+            Value::String(HOLDER_ENT_TEAM.to_string()),
+            Value::String(team_id.to_string()),
+            Value::String(username.to_string()),
+            Value::String(norm(username)),
+            mobile.map(|m| Value::String(m.to_string())).unwrap_or(Value::Null),
+        ],
+    )
+}
+
+/// 凭证出参形态(组织§5.1 逐字:初始密码随机仅当次显示,记录只写「未发送,线下告知本人」)。
+fn account_out(user_id: &str, username: &str, role_code: &str, initial_password: &str) -> Value {
+    json!({
+        "created": true,
+        "user_id": user_id,
+        "username": username,
+        "role_code": role_code,
+        "platform_role_note": "业务角色只落本地 bos_user_binding.role_code(本系统判权真源);\
+             平台 iam_user.create 无角色授予入参 ⇒ 平台侧角色未授",
+        "must_change_password": true,
+        "initial_password": initial_password,
+        "credential_note": "未发送,线下告知本人",
+        "credential_viewable": false
+    })
+}
+
+// ══ OR-09 建团队/改名 ═════════════════════════════════════════════════
+
+#[derive(Deserialize)]
+pub struct TeamCreate {
+    pub team_name: String,
+    /// 备注(选填,≤200 字;空白=落库 NULL)。
+    #[serde(default)]
+    pub remark: Option<String>,
+    /// 可空:未带=只建档、⛔ 建号(团队无成员,首个成员由 `member_add` 落)。
+    pub primary_username: Option<String>,
+    pub primary_mobile: Option<String>,
+}
+
+pub async fn create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<TeamCreate>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_create(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_create(state: &AppState, _auth: &AuthContext, body: TeamCreate) -> Result<Value, BosError> {
+    // ── 守卫全部先于建号与任何本地写库(⛔ 半成品档案/孤儿平台账号)────
+    let team_name = check_team_name(&body.team_name)?;
+    let team_name_norm = norm(&team_name);
+    let remark = check_remark(body.remark.as_deref())?;
+    check_name_dup(state, &team_name_norm, None).await?;
+
+    let username = match body.primary_username.as_deref() {
+        Some(u) => Some(check_username(u)?),
+        None => None,
+    };
+    let mobile = check_mobile(body.primary_mobile.as_deref())?;
+    if let Some(u) = &username {
+        account_guard(state, u, mobile.as_deref(), None).await?;
+    }
+
+    // ── 建号(带了登录名才建;⛔ 未带也建号=凭空造账号)────────────────
+    let account = match &username {
+        Some(u) => Some(create_account(state, &team_name, u, mobile.as_deref()).await?),
+        None => None,
+    };
+
+    let team_id = issue_team_id(state).await?;
+
+    // ── 本地单批原子落库:档案(+首成员=主账号 + 绑定行 + owner)─────
+    let mut stmts = vec![DmlStatement::new(
+        "INSERT INTO ent_team (team_id, team_name, team_name_norm, is_builtin, remark) \
+         VALUES ($1::text, $2::text, $3::text, FALSE, $4::text)".to_string(),
+        vec![
+            Value::String(team_id.clone()),
+            Value::String(team_name.clone()),
+            Value::String(team_name_norm.clone()),
+            remark.clone().map(Value::String).unwrap_or(Value::Null),
+        ],
+    )];
+    let mut labels = vec!["ent_team 建档".to_string()];
+
+    if let Some((uid, _)) = &account {
+        stmts.push(DmlStatement::new(
+            "INSERT INTO ent_team_member (team_id, user_id, is_primary) \
+             VALUES ($1::text, $2::int8, TRUE)".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(uid.clone()),
+            ],
+        ));
+        labels.push("ent_team_member 首成员(=主账号)".to_string());
+        let u = username.as_deref().unwrap_or_default();
+        stmts.push(binding_insert(uid, ROLE_MAIN, &team_id, u, mobile.as_deref()));
+        labels.push("bos_user_binding 主账号绑定行".to_string());
+        stmts.push(DmlStatement::new(
+            "UPDATE ent_team SET owner_user_id = $2::int8 WHERE team_id = $1::text".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(uid.clone()),
+            ],
+        ));
+        labels.push("ent_team.owner_user_id".to_string());
+    }
+
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad = zeros(&results, &labels);
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "建档批内语句未落库:{}(语句 affected_rows ⛔ 1)",
+            bad.join("、")
+        )));
+    }
+
+    let saved = team_meta(state, &team_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("建档后回读 ent_team 失败:{team_id}")))?;
+    let (uid, pwd) = match &account {
+        Some((u, p)) => (Some(u.clone()), Some(p.clone())),
+        None => (None, None),
+    };
+    Ok(json!({
+        "team_id": saved.team_id,
+        "team_name": saved.team_name,
+        "remark": saved.remark,
+        "is_builtin": saved.is_builtin,
+        "owner_user_id": saved.owner_user_id,
+        "member_count": member_rows(state, &team_id).await?.len(),
+        "members": member_views(state, &team_id).await?,
+        "account": match (&uid, &username, &pwd) {
+            (Some(u), Some(un), Some(p)) => account_out(u, un, ROLE_MAIN, p),
+            _ => json!({"created": false,
+                        "reason": "未带 primary_username ⇒ 只建档、⛔ 建号(组织§5.4 OR-09:新建团队\
+                                   范围与成员初始为空);主账号随首个成员产生(OR-10),\
+                                   请调 `ent_team/member_add@v1`"}),
+        },
+        "scope_note": "新建团队负责范围初始为空(OR-09)⇒ 本次⛔ 写任何 bos_data_scope 行",
+        "builtin_note": "is_builtin ⛔ 由接口置真(内置「总部 · 不限区域」是种子事实,OR-09 不可删)\
+                         ⇒ 本接口新建一律 is_builtin=false",
+        "audit_key": "bos.ent_team.create",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+#[derive(Deserialize)]
+pub struct TeamUpdate {
+    pub team_id: String,
+    pub team_name: String,
+    /// 备注:字段缺省=⛔ 改本列;传空白串=清空(落库 NULL);带文本=设值(≤200 字)。
+    #[serde(default)]
+    pub remark: Option<String>,
+    pub row_version: Option<i64>,
+}
+
+pub async fn update(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<TeamUpdate>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_update(&state, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_update(state: &AppState, body: TeamUpdate) -> Result<Value, BosError> {
+    let meta = need_team(state, &body.team_id).await?;
+    let team_id = meta.team_id.clone();
+    let team_name = check_team_name(&body.team_name)?;
+    let team_name_norm = norm(&team_name);
+    // 备注三态:字段缺省=⛔ 改本列(⛔ 把"没传"当成"清空");空白=清空为 NULL;带文本=设值。
+    let remark = body
+        .remark
+        .as_ref()
+        .map(|r| check_remark(Some(r.as_str())))
+        .transpose()?;
+    check_name_dup(state, &team_name_norm, Some(&team_id)).await?;
+
+    let mut sets = vec!["team_name = $2::text".to_string(), "team_name_norm = $3::text".to_string()];
+    let mut vals = vec![
+        Value::String(team_id.clone()),
+        Value::String(team_name.clone()),
+        Value::String(team_name_norm.clone()),
+    ];
+    let mut touched = vec!["改名"];
+    if let Some(r) = remark {
+        let ph = vals.len() + 1;
+        sets.push(format!("remark = ${ph}::text"));
+        vals.push(r.map(Value::String).unwrap_or(Value::Null));
+        touched.push("备注");
+    }
+    let labels = vec![format!("ent_team 档案更新({})", touched.join("/"))];
+    let results = state
+        .db
+        .dml_batch(&[DmlStatement::new(
+            format!("UPDATE ent_team SET {} WHERE team_id = $1::text", sets.join(", ")),
+            vals,
+        )])
+        .await?;
+    let bad = zeros(&results, &labels);
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "编辑语句未落库:{}(affected_rows ⛔ 1)",
+            bad.join("、")
+        )));
+    }
+
+    let saved = team_meta(state, &team_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("编辑后回读 ent_team 失败:{team_id}")))?;
+    Ok(json!({
+        "team_id": saved.team_id,
+        "team_name": saved.team_name,
+        "remark": saved.remark,
+        "is_builtin": saved.is_builtin,
+        "owner_user_id": saved.owner_user_id,
+        "members": member_views(state, &team_id).await?,
+        "remark_touched": touched.len() > 1,
+        "builtin_renamed_note": if saved.is_builtin {
+            "该团队是内置团队(「总部 · 不限区域」):OR-09 只规定⛔ 可删,⛔ 规定⛔ 可改名 ⇒ 本次改名\
+             已落库;名称是展示值,判定走 is_builtin,⛔ 靠名称判内置"
+        } else {
+            "未写任何 is_builtin 变更(内置性是种子事实)"
+        },
+        "platform_sync_note": "团队名⛔ 同步到平台:state.platform 只有 user_create/user_get 通路\
+                               (⛔ update 接口)⇒ 平台侧 iam_user.nickname 本次未同步,登 18 册",
+        "row_version_note": body.row_version.map(|_| "dev ent_team ⛔ 版本列(迁移在册列集=\
+                               team_id/team_name/team_name_norm/remark/is_builtin/owner_user_id/created_at)\
+                               ⇒ 乐观锁未启用,row_version 收下但⛔ 参与判定").unwrap_or("未传 row_version"),
+        "audit_key": "bos.ent_team.update",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+// ══ OR-09 删除(内置不可删)════════════════════════════════════════════
+
+#[derive(Deserialize)]
+pub struct TeamDelete {
+    pub team_id: String,
+}
+
+pub async fn delete(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<TeamDelete>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_delete(&state, &auth, &body.team_id).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_delete(state: &AppState, auth: &AuthContext, team_id: &str) -> Result<Value, BosError> {
+    let meta = need_team(state, team_id).await?;
+    let team_id = meta.team_id.clone();
+    if meta.is_builtin {
+        return Err(BosError::bad_params(format!(
+            "运营团队 {team_id}「{}」是内置团队 ⇒ ⛔ 删除(OR-09 逐字:内置「总部 · 不限区域」不可删);\
+             本接口未执行任何写库",
+            meta.team_name
+        )));
+    }
+
+    // 可判定依赖(真数)。
+    let members = count_where(
+        state,
+        "SELECT COUNT(1) AS n FROM ent_team_member WHERE team_id = $1::text",
+        &[Value::String(team_id.clone())],
+    )
+    .await?;
+    let primary_now = primary_user(state, &team_id).await?;
+    let bindings = count_where(
+        state,
+        "SELECT COUNT(1) AS n FROM bos_user_binding WHERE subject_type = 'ent_team' AND subject_id = $1::text",
+        &[Value::String(team_id.clone())],
+    )
+    .await?;
+    let scopes = count_where(
+        state,
+        "SELECT COUNT(1) AS n FROM bos_data_scope WHERE holder_type = 'ent_team' AND holder_id = $1::text",
+        &[Value::String(team_id.clone())],
+    )
+    .await?;
+
+    let mut blockers: Vec<Value> = Vec::new();
+    if members > 0 {
+        blockers.push(json!({"key": "member", "count": members,
+                             "message": "团队仍有成员,须先逐一移出(OR-10:删除主账号须先转交)"}));
+    }
+    if primary_now.is_some() {
+        blockers.push(json!({"key": "primary_account", "count": 1,
+                             "message": "团队仍有主账号,须先转交再移出(OR-10/OR-11)"}));
+    }
+    if bindings > 0 {
+        blockers.push(json!({"key": "bos_user_binding", "count": bindings,
+                             "message": "运营团队主体仍有账号绑定行,须先注销(平台⛔ 注销通路)"}));
+    }
+    if scopes > 0 {
+        blockers.push(json!({"key": "bos_data_scope", "count": scopes,
+                             "message": "仍有负责范围授权行,须先清空(ent_team/scope/save@v1);\
+                                         被勾节点同时是 组织§3.3 区域删除的引用来源(OR-12)"}));
+    }
+    if auth.subject.subject_type == HOLDER_ENT_TEAM && auth.subject.subject_id == team_id {
+        blockers.push(json!({"key": "self_login", "count": 1,
+                             "message": "不能删除当前登录身份所在的运营团队"}));
+    }
+    // ⛔ 数源依赖(OR-09 关联检查,dev 缺表/缺通路 ⇒ ⛔ 可判定 ⇒ ⛔ 放行)。
+    let unverifiable = json!([
+        {"key": "billing_share_line",
+         "reason": "账单分成明细属第 3 册,dev ⛔ 建表 ⇒ 「有分成行」⛔ 判定;\
+                    share_rule.holder_type 值域=operator/ops_team(列注释逐字)⇒ 本表⛔ 数源"},
+        {"key": "reconcile_batch", "reason": "对账清单属第 4 册,dev ⛔ 建表 ⇒ ⛔ 可判定"},
+        {"key": "ticket", "reason": "工单属第 5 册,dev ⛔ 建表 ⇒ 「有在办工单」⛔ 可判定"},
+        {"key": "account_deactivation",
+         "reason": "平台⛔ 账号注销/⛔ 资料更新通路(state.platform 只有 user_create/user_get)\
+                    ⇒ 绑定行无法随档案注销,登 18 册"}
+    ]);
+    if blockers.is_empty() {
+        return Err(BosError::bad_params(format!(
+            "本次⛔ 删除:可判定依赖为 0,但分成行/对账清单/工单/账号注销⛔ 数源⛔ 可判定\
+             (⛔ 把「查不出依赖」当「没有依赖」)⇒ 显式拒绝。未判定项={}",
+            unverifiable
+                .as_array()
+                .map(|a| a.iter().filter_map(|x| x.get("key").and_then(Value::as_str)).collect::<Vec<_>>().join("、"))
+                .unwrap_or_default()
+        )));
+    }
+    Ok(json!({
+        "team_id": team_id,
+        "team_name": meta.team_name,
+        "deleted": false,
+        "blockers": blockers,
+        "unverifiable_checks": unverifiable,
+        "audit_key": "bos.ent_team.delete",
+        "note": "存在阻塞项 ⇒ ⛔ 删除(本接口未执行任何写库),逐条消解后重试"
+    }))
+}
+
+// ══ OR-10 成员新增/移出 ═══════════════════════════════════════════════
+
+#[derive(Deserialize)]
+pub struct MemberAdd {
+    pub team_id: String,
+    pub username: String,
+    pub mobile: Option<String>,
+    pub is_primary: Option<bool>,
+}
+
+pub async fn member_add(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<MemberAdd>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_member_add(&state, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_member_add(state: &AppState, body: MemberAdd) -> Result<Value, BosError> {
+    let meta = need_team(state, &body.team_id).await?;
+    let team_id = meta.team_id.clone();
+
+    // ── 守卫先于建号(⛔ 半成品成员/孤儿平台账号)──────────────────────
+    let username = check_username(&body.username)?;
+    let mobile = check_mobile(body.mobile.as_deref())?;
+    account_guard(state, &username, mobile.as_deref(), None).await?;
+
+    let members = member_rows(state, &team_id).await?;
+    let primary_now = primary_user(state, &team_id).await?;
+    // OR-10:第一个成员即主账号;已有主账号时⛔ 再指定第二个主账号 ⇒ 须走转交。
+    let want_primary = body.is_primary.unwrap_or(false);
+    if want_primary && primary_now.is_some() {
+        return Err(has_primary_err(&team_id, &primary_now.unwrap_or_default()));
+    }
+    // 空团队的首个成员=主账号(OR-10),调用方未声明也强制置真。
+    let effective_primary = if members.is_empty() { true } else { want_primary };
+    if !members.is_empty() && primary_now.is_none() {
+        return Err(BosError::internal(format!(
+            "团队 {team_id} 有 {} 名成员却查不到主账号行(is_primary 全为假)⇒ 违反 OR-10\
+             「每团队有且仅有一个主账号」,请先人工校正 ent_team_member.is_primary 后重试",
+            members.len()
+        )));
+    }
+    let role_code = if effective_primary { ROLE_MAIN } else { ROLE_SUB };
+
+    // ── 平台建号 → 本地单批落库(绑定行+成员行+必要时回填 owner)───────
+    let (user_id, initial_password) = create_account(state, &meta.team_name, &username, mobile.as_deref()).await?;
+
+    let mut stmts = vec![
+        binding_insert(&user_id, role_code, &team_id, &username, mobile.as_deref()),
+        DmlStatement::new(
+            format!(
+                "INSERT INTO ent_team_member (team_id, user_id, is_primary) \
+                 VALUES ($1::text, $2::int8, {})",
+                if effective_primary { "TRUE" } else { "FALSE" }
+            ),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(user_id.clone()),
+            ],
+        ),
+    ];
+    let mut labels = vec![
+        "bos_user_binding 成员绑定行".to_string(),
+        format!("ent_team_member 成员行(is_primary={effective_primary})"),
+    ];
+    if effective_primary && meta.owner_user_id.as_deref() != Some(user_id.as_str()) {
+        stmts.push(DmlStatement::new(
+            "UPDATE ent_team SET owner_user_id = $2::int8 WHERE team_id = $1::text".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(user_id.clone()),
+            ],
+        ));
+        labels.push("ent_team.owner_user_id 随主账号回填".to_string());
+    }
+
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad = zeros(&results, &labels);
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "成员新增批内语句未落库:{}(affected_rows ⛔ 1)",
+            bad.join("、")
+        )));
+    }
+
+    Ok(json!({
+        "team_id": team_id,
+        "team_name": meta.team_name,
+        "added": true,
+        "user_id": user_id,
+        "role_code": role_code,
+        "is_primary": effective_primary,
+        "primary_forced": members.is_empty() && !want_primary,
+        "primary_forced_note": if members.is_empty() {
+            "该团队此前无成员 ⇒ 首个成员即主账号(OR-10),is_primary 强制置真、role_code=opsMain,\
+             与请求体 is_primary 取值无关"
+        } else {
+            "团队已有成员 ⇒ is_primary 随请求体(已有主账号时再请求置真会被拒,请办转交)"
+        },
+        "account": account_out(&user_id, &username, role_code, &initial_password),
+        "members": member_views(state, &team_id).await?,
+        "member_count": member_rows(state, &team_id).await?.len(),
+        "duplicate_member_note": "「同一账号⛔ 重复入团」一项⛔ 由本接口判定:入团要求登录名全新,\
+                                  已占用的登录名先被 `account_guard` 以 KLT-B001 拦下(登录名全站唯一)\
+                                  ⇒ 该场景在 `member_add` 的入参形态下不可达,⛔ 伪造该守卫",
+        "scope_note": "新成员⛔ 继承团队负责范围:ent_team_member ⛔ scope_mode 列(dev 在册列集),\
+                       OR-12「成员跟随团队/一次性快照」两态⛔ 表达 ⇒ 缺口登 18 册",
+        "audit_key": "bos.ent_team.member_add",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+#[derive(Deserialize)]
+pub struct MemberRemove {
+    pub team_id: String,
+    pub user_id: String,
+}
+
+pub async fn member_remove(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<MemberRemove>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_member_remove(&state, &auth, &body.team_id, &body.user_id).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_member_remove(
+    state: &AppState,
+    auth: &AuthContext,
+    team_id: &str,
+    user_id: &str,
+) -> Result<Value, BosError> {
+    let meta = need_team(state, team_id).await?;
+    let team_id = meta.team_id.clone();
+    let uid = user_id.trim().to_string();
+    if uid.is_empty() {
+        return Err(BosError::bad_params("必须带 user_id"));
+    }
+    let members = member_rows(state, &team_id).await?;
+    if !members.iter().any(|(u, _)| *u == uid) {
+        return Err(BosError::not_found(format!(
+            "账号 {uid} ⛔ 运营团队 {team_id} 的成员(ent_team_member ⛔ 该 (team_id, user_id) 行)\
+             ⇒ ⛔ 移出,本接口未执行任何写库"
+        )));
+    }
+    let binding = binding_of_user(state, &uid).await?;
+    let is_primary = members.iter().any(|(u, p)| *u == uid && *p);
+    let primary_now = primary_user(state, &team_id).await?;
+    let last_one = members.len() == 1;
+
+    let mut blockers: Vec<Value> = Vec::new();
+    if is_primary {
+        blockers.push(json!({"key": "primary_account", "count": 1,
+            "message": if meta.is_builtin {
+                "内置团队(「总部 · 不限区域」)的主账号⛔ 删除⛔ 转交(OR-10 逐字)⇒ 该成员无法移出"
+            } else {
+                "该成员是团队主账号 ⇒ 删除主账号须先转交(OR-10),请办 ent_team/transfer_primary@v1"
+            }}));
+    }
+    if last_one && !is_primary {
+        blockers.push(json!({"key": "last_member_without_primary", "count": 1,
+            "message": "移出后团队⛔ 主账号(OR-10 每团队有且仅有一个主账号)⇒ 先置主账号再移出"}));
+    }
+    if auth.user_id == uid {
+        blockers.push(json!({"key": "self_login", "count": 1,
+            "message": "不能删除当前登录账号(OR-10 逐字:删除当前登录账号拦截)"}));
+    }
+    // OR-10/组织§4.1:移出须随同注销账号;平台⛔ 注销通路 ⇒ 该义务无法履行,恒为阻塞项。
+    blockers.push(json!({"key": "account_deactivation", "count": 1,
+        "message": "移出须同事务注销平台账号并处置 bos_user_binding 绑定行;state.platform 只有 \
+                    user_create/user_get 通路(⛔ update_status/⛔ 注销)⇒ 该义务⛔ 履行,\
+                    本接口恒⛔ 写库(沿 ops_team 成员删除同口径),登 18 册"}));
+
+    Ok(json!({
+        "team_id": team_id,
+        "team_name": meta.team_name,
+        "user_id": uid,
+        "username": binding.as_ref().map(|(u, _, _)| u.clone()),
+        "role_code": binding.as_ref().map(|(_, _, r)| r.clone()),
+        "is_primary": is_primary,
+        "team_primary_user_id": primary_now,
+        "member_count": members.len(),
+        "removed": false,
+        "blockers": blockers,
+        "members": member_views(state, &team_id).await?,
+        "audit_key": "bos.ent_team.member_remove",
+        "note": "本接口恒⛔ 写库(账号注销义务无法履行 ⇒ 恒有阻塞项),⛔ 把「移出行未删」\
+                 当「成员已移出」",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+// ══ OR-11 主账号转交 ═══════════════════════════════════════════════════
+
+#[derive(Deserialize)]
+pub struct TransferPrimary {
+    pub team_id: String,
+    pub from_user_id: String,
+    pub to_user_id: String,
+}
+
+pub async fn transfer_primary(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<TransferPrimary>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_transfer_primary(&state, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_transfer_primary(state: &AppState, body: TransferPrimary) -> Result<Value, BosError> {
+    let meta = need_team(state, &body.team_id).await?;
+    let team_id = meta.team_id.clone();
+    let from = body.from_user_id.trim().to_string();
+    let to = body.to_user_id.trim().to_string();
+    if from.is_empty() || to.is_empty() {
+        return Err(BosError::bad_params("必须同时带 from_user_id 与 to_user_id"));
+    }
+    if from == to {
+        return Err(BosError::bad_params("转出账号与转入账号是同一个 ⇒ ⛔ 转交"));
+    }
+    if meta.is_builtin {
+        return Err(BosError::bad_params(format!(
+            "内置团队 {team_id}「{}」的主账号⛔ 转交(OR-10 逐字:内置主账号不可删⛔ 转交)",
+            meta.team_name
+        )));
+    }
+
+    let members = member_rows(state, &team_id).await?;
+    if !members.iter().any(|(u, _)| *u == to) {
+        return Err(BosError::bad_params(format!(
+            "接收方 {to} ⛔ 运营团队 {team_id} 的成员 ⇒ 跨团队转交直接拒(OR-11 逐字:⛔ 不得跨团队);\
+             请先 `ent_team/member_add@v1` 使其入团"
+        )));
+    }
+    let primary_now = primary_user(state, &team_id).await?;
+    match &primary_now {
+        Some(p) if *p == from => {}
+        Some(p) => {
+            return Err(BosError::bad_params(format!(
+                "转出方 {from} ⛔ 该团队当前主账号(库内主账号={p})⇒ ⛔ 转交(OR-11 只改主/子标记,\
+                 ⛔ 靠转交纠正既有主账号)"
+            )))
+        }
+        None => {
+            return Err(BosError::internal(format!(
+                "团队 {team_id} 查不到主账号行(is_primary 全为假)⇒ 违反 OR-10,⛔ 转交;\
+                 请先人工校正 ent_team_member.is_primary"
+            )))
+        }
+    }
+    let from_binding = binding_of_user(state, &from).await?;
+    let to_binding = binding_of_user(state, &to).await?;
+
+    // 事务内顺序(`uq_ent_team_primary ON ent_team_member(team_id) WHERE is_primary` 即时生效
+    // ⇒ 必须先 A→FALSE 再 B→TRUE,否则中间态撞部分唯一索引)。
+    let stmts = vec![
+        DmlStatement::new(
+            "UPDATE ent_team_member SET is_primary = FALSE WHERE team_id = $1::text \
+             AND user_id = $2::int8 AND is_primary".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(from.clone()),
+            ],
+        ),
+        DmlStatement::new(
+            "UPDATE ent_team_member SET is_primary = TRUE WHERE team_id = $1::text \
+             AND user_id = $2::int8".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(to.clone()),
+            ],
+        ),
+        DmlStatement::new(
+            "UPDATE bos_user_binding SET role_code = $3::text, updated_at = NOW() \
+             WHERE user_id = $1::int8 AND subject_type = 'ent_team' AND subject_id = $2::text".to_string(),
+            vec![
+                Value::String(from.clone()),
+                Value::String(team_id.clone()),
+                Value::String(ROLE_SUB.to_string()),
+            ],
+        ),
+        DmlStatement::new(
+            "UPDATE bos_user_binding SET role_code = $3::text, updated_at = NOW() \
+             WHERE user_id = $1::int8 AND subject_type = 'ent_team' AND subject_id = $2::text".to_string(),
+            vec![
+                Value::String(to.clone()),
+                Value::String(team_id.clone()),
+                Value::String(ROLE_MAIN.to_string()),
+            ],
+        ),
+        DmlStatement::new(
+            "UPDATE ent_team SET owner_user_id = $2::int8 WHERE team_id = $1::text".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(to.clone()),
+            ],
+        ),
+    ];
+    let labels = vec![
+        "转出方 is_primary→FALSE".to_string(),
+        "接收方 is_primary→TRUE".to_string(),
+        format!("转出方 role_code→{ROLE_SUB}"),
+        format!("接收方 role_code→{ROLE_MAIN}"),
+        "ent_team.owner_user_id→接收方".to_string(),
+    ];
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad = zeros(&results, &labels);
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "转交批内语句未落库:{}(affected_rows ⛔ 1;⚠️ 本批⛔ 单事务回滚保障——UDS \
+             `dml_batch` 的原子性属平台契约,逐条 affected_rows 只保证「未落一行即整单判失败」,\
+             中间态一致性登 18 册)",
+            bad.join("、")
+        )));
+    }
+
+    let saved = team_meta(state, &team_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("转交后回读 ent_team 失败:{team_id}")))?;
+    Ok(json!({
+        "team_id": team_id,
+        "team_name": saved.team_name,
+        "transferred": true,
+        "from_user_id": from,
+        "from_username": from_binding.as_ref().map(|(u, _, _)| u.clone()),
+        "to_user_id": to,
+        "to_username": to_binding.as_ref().map(|(u, _, _)| u.clone()),
+        "owner_user_id": saved.owner_user_id,
+        "statement_order": labels.iter().cloned().collect::<Vec<_>>(),
+        "role_switch_note": "权限按角色判 ⇒ 转连同 role_code 一起换:转出方 opsMain→opsSub、\
+                             接收方 opsSub→opsMain(OR-11 逐字)",
+        "unchanged_note": "登录名与负责范围⛔ 随转交变化(OR-11 逐字):本次⛔ 动 bos_user_binding.\
+                           username/username_norm,⛔ 动任何 bos_data_scope 行",
+        "members": member_views(state, &team_id).await?,
+        "audit_key": "bos.ent_team.transfer_primary",
+        "audit_before_after": json!({
+            "before": {"primary_user_id": primary_now, "owner_user_id": meta.owner_user_id},
+            "after": {"primary_user_id": saved.owner_user_id.clone(), "owner_user_id": saved.owner_user_id}
+        }),
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
 }
-pub async fn update(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn delete(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn member_add(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn member_remove(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn transfer_primary(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn scope_get(RequireAuth(auth): RequireAuth) -> Response {
-    if let Err(e) = admin_only(&auth) { return json_err(e); }
-    json_ok(json!({ "grants": [] }))
+
+// ══ 当前主体的负责范围(只读)══════════════════════════════════════════
+
+/// 当前主体的负责范围(`bos_data_scope` 真源);持有者由 `auth.subject` 推导。
+pub async fn scope_get(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
+    if auth.subject.subject_type != "ent_team" {
+        return json_err(bos_core::BosError::bad_params(format!(
+            "本接口只查**当前登录运营团队自己**的负责范围(holder_type='ent_team'),\
+             而当前主体类型为 `{}`;合伙人查 `/partner/scope/get@v1`,\
+             运维团队承接客户清单查 `/ops_team/coverage/get@v1`\
+             (⚠️ 运维团队的**负责区域**一期无只读接口,见总则§18.3),客户/分账号⛔ 查自己的负责范围",
+            auth.subject.subject_type
+        )));
+    }
+    let mut p = Params::default();
+    let holder = p.push(Value::String(auth.subject.subject_id.clone()));
+    let sql = format!(
+        "SELECT target_type, target_id FROM bos_data_scope WHERE holder_type = 'ent_team' \
+         AND holder_id = {holder}::text ORDER BY target_type, target_id"
+    );
+    #[derive(Deserialize)]
+    struct Grant {
+        #[serde(deserialize_with = "de::as_string")]
+        target_type: String,
+        #[serde(deserialize_with = "de::as_string")]
+        target_id: String,
+    }
+    match state.db.query_all::<Grant>(&sql, p.values()).await {
+        Ok(rows) => json_ok(json!({
+            "grants": rows.iter().map(|g| json!({
+                "target_type": g.target_type, "target_id": g.target_id
+            })).collect::<Vec<_>>(),
+            "total": rows.len(),
+        })),
+        Err(e) => json_err(e),
+    }
+}
+
+// ══ OR-12 团队负责范围调整 ═════════════════════════════════════════════
+
+#[derive(Deserialize)]
+pub struct TeamScopeSave {
+    pub team_id: String,
+    pub region_node_ids: Option<Vec<String>>,
 }
-pub async fn scope_save(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
+
+pub async fn scope_save(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<TeamScopeSave>,
+) -> Response {
+    if let Err(e) = admin_only(&auth) {
+        return json_err(e);
+    }
+    match do_scope_save(&state, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+/// 去空白、去空值、保序去重。
+fn dedup(v: &[String]) -> Vec<String> {
+    let mut out: Vec<String> = Vec::new();
+    for x in v {
+        let x = x.trim();
+        if !x.is_empty() && !out.iter().any(|y| y == x) {
+            out.push(x.to_string());
+        }
+    }
+    out
+}
+
+const SCOPE_SQL: &str = "SELECT target_type, target_id FROM bos_data_scope \
+                         WHERE holder_type = 'ent_team' AND holder_id = $1::text \
+                         ORDER BY target_type, target_id";
+
+#[derive(Deserialize)]
+struct ScopeGrant {
+    #[serde(deserialize_with = "de::as_string")]
+    target_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    target_id: String,
+}
+
+async fn current_scope(state: &AppState, team_id: &str) -> Result<Vec<String>, BosError> {
+    let ids = state
+        .db
+        .query_all::<ScopeGrant>(SCOPE_SQL, &[Value::String(team_id.to_string())])
+        .await?
+        .into_iter()
+        .filter(|g| g.target_type == "region")
+        .map(|g| g.target_id)
+        .collect();
+    Ok(ids)
+}
+
+async fn do_scope_save(state: &AppState, body: TeamScopeSave) -> Result<Value, BosError> {
+    let meta = need_team(state, &body.team_id).await?;
+    let team_id = meta.team_id;
+    let want = dedup(body.region_node_ids.as_deref().unwrap_or_default());
+
+    // 目标节点必须在册(⛔ 收下不存在的节点当作「已授权」)。
+    if !want.is_empty() {
+        let mut p = Params::default();
+        // ⚠️ UDS 的 `params` ⛔ 支持数组(实测 `13001: params 仅支持标量`)⇒ 一律展开成
+        // 标量占位符的 `IN (…)`(与 `listq::push_in` 同口径),⛔ 用 `ANY($1::text[])`。
+        let pred = push_in(&mut p, "node_id", &want, "text");
+        let sql = format!("SELECT node_id FROM bos_region_meta WHERE {pred}");
+        let rows: Vec<Value> = state.db.query_all::<Value>(&sql, p.values()).await?;
+        let known: Vec<String> = rows.iter().filter_map(|r| cell(r, "node_id")).collect();
+        let miss: Vec<&String> = want.iter().filter(|x| !known.contains(x)).collect();
+        if !miss.is_empty() {
+            return Err(BosError::bad_params(format!(
+                "区域节点 {} ⛔ bos_region_meta 在册(层级唯一真源,总则§5.3)⇒ 整单⛔ 保存(⛔ 部分落库)",
+                miss.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("、")
+            )));
+        }
+    }
+
+    let current = current_scope(state, &team_id).await?;
+    let to_insert: Vec<String> = want.iter().cloned().filter(|x| !current.contains(x)).collect();
+    let to_delete: Vec<String> = current.iter().cloned().filter(|x| !want.contains(x)).collect();
+
+    if to_insert.is_empty() && to_delete.is_empty() {
+        return Ok(json!({
+            "team_id": team_id,
+            "region_node_ids": want,
+            "total": want.len(),
+            "inserted": 0, "deleted": 0, "unchanged": want.len(),
+            "noop": true,
+            "empty_allowed": want.is_empty(),
+            "shrink_note": SHRINK_NOTE,
+            "audit_key": "bos.ent_team.scope.manage",
+            "audit_written": false,
+            "audit_note": AUDIT_NOTE,
+            "time_note": TIME_NOTE
+        }));
+    }
+
+    // 整体替换:一条 DELETE 只清 ent_team 这一族的 region 行,再逐行 INSERT。
+    // ⚠️ 每条语句各配一份参数(复用同一份跑多条语句会被判「参数个数不符」)。
+    let mut stmts = vec![DmlStatement::new(
+        "DELETE FROM bos_data_scope WHERE holder_type = 'ent_team' AND holder_id = $1::text \
+         AND target_type = 'region'".to_string(),
+        vec![Value::String(team_id.clone())],
+    )];
+    let mut labels = vec!["bos_data_scope 清空 ent_team 族 region 行".to_string()];
+    let mut expect_one = vec![false];
+    for n in &to_insert {
+        stmts.push(DmlStatement::new(
+            "INSERT INTO bos_data_scope (holder_type, holder_id, target_type, target_id) \
+             VALUES ('ent_team', $1::text, 'region', $2::text) ON CONFLICT DO NOTHING".to_string(),
+            vec![
+                Value::String(team_id.clone()),
+                Value::String(n.clone()),
+            ],
+        ));
+        labels.push(format!("region={n} 授权行"));
+        expect_one.push(true);
+    }
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad: Vec<String> = results
+        .iter()
+        .filter(|r| match r.index {
+            i if i < expect_one.len() => expect_one[i] && r.affected_rows != Some(1),
+            _ => true,
+        })
+        .map(|r| {
+            labels
+                .get(r.index)
+                .cloned()
+                .unwrap_or_else(|| format!("语句 #{}", r.index))
+        })
+        .collect();
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "负责范围保存批内语句未落库:{}(DELETE 允许影响 0 行,INSERT 须各落 1 行)",
+            bad.join("、")
+        )));
+    }
+
+    let after = current_scope(state, &team_id).await?;
+    let mut want_sorted = want.clone();
+    want_sorted.sort();
+    let mut after_sorted = after.clone();
+    after_sorted.sort();
+    Ok(json!({
+        "team_id": team_id,
+        "team_name": meta.team_name,
+        "region_node_ids": after,
+        "total": after.len(),
+        "inserted": to_insert.len(),
+        "deleted": to_delete.len(),
+        "unchanged": want.len() - to_insert.len(),
+        "empty_allowed": want.is_empty(),
+        "consistent": want_sorted == after_sorted,
+        "diff_with_requested": if want_sorted == after_sorted {
+            Value::Null
+        } else {
+            json!({"expected": want_sorted, "actual": after_sorted})
+        },
+        "shrink_note": SHRINK_NOTE,
+        "audit_key": "bos.ent_team.scope.manage",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+/// OR-12 收缩口径(含 dev 无法判定的一项拦截)。
+const SHRINK_NOTE: &str = "收缩语义同 OR-08:收缩后历史数据⛔ 迁移、对原主体仍可见(靠 组织§2.2 \
+                           期初快照);被勾节点同时成为 组织§3.3 区域删除的引用来源。\
+                           ⚠️ OR-12 的「收缩导致成员自定义范围越界」拦截⛔ 可判定——\
+                           ent_team_member ⛔ scope_mode 列、dev ⛔ 成员级范围表 ⇒ 该拦截本次\
+                           ⛔ 执行,缺口登 18 册";

+ 1298 - 15
src/modules/account/src/handlers/import_batch.rs

@@ -1,30 +1,1313 @@
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_io::assert_row_limit;
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, KltCode, RoleCode};
+use bos_io::{assert_row_limit, is_valid_identity_no, norm_identity_no};
+use bos_platform::clients::uds::{de, DmlStatement, DmlStatementResult};
+use chrono::Local;
 use serde::Deserialize;
-use serde_json::json;
+use serde_json::{json, Value};
+use std::collections::{HashMap, HashSet};
+
+use super::listq::{next_seq, total, Params};
+use super::ops_team::AUDIT_NOTE;
+use super::partner::customer_scope_pred;
 
 #[derive(Deserialize)]
 pub struct ImportSubmit { pub rows: Vec<serde_json::Value> }
+
+/// 续传入参:同批次号 + 同一套 14 列行(可只传未导入行)。
+#[derive(Deserialize)]
+pub struct ResumeReq {
+    pub batch_no: String,
+    pub rows: Vec<serde_json::Value>,
+}
+
 pub async fn template_download(RequireAuth(_a): RequireAuth) -> Response {
     json_ok(json!({ "format": "xlsx", "columns": 14, "max_rows": 500 }))
 }
-pub async fn submit(RequireAuth(_a): RequireAuth, DataBody(body): DataBody<ImportSubmit>) -> Response {
-    if let Err(e) = assert_row_limit(body.rows.len()) { return json_err(e); }
-    json_ok(json!({ "batch_no": null, "total": body.rows.len(), "status": "running" }))
+
+/// 主体类型:模板填中文显示名,库里存机器码(两者都收,其余值域外)。
+fn subject_type_code(raw: &str) -> Option<&'static str> {
+    match raw.trim() {
+        "企业" | "enterprise" => Some("enterprise"),
+        "个人" | "individual" => Some("individual"),
+        "个体工商户" | "sole_proprietor" => Some("sole_proprietor"),
+        _ => None,
+    }
+}
+
+/// 模板列取值(数字列也收,⛔ 因 JSON 形态单一假设而丢值)。
+fn text(row: &Value, key: &str) -> String {
+    match row.get(key) {
+        Some(Value::String(s)) => s.trim().to_string(),
+        Some(Value::Number(n)) => n.to_string(),
+        _ => String::new(),
+    }
+}
+
+/// 多值列(归属运维团队:多支用「;」分隔)。
+fn team_cells(row: &Value) -> Vec<String> {
+    let mut out: Vec<String> = Vec::new();
+    match row.get("ops_team_names") {
+        Some(Value::Array(a)) => {
+            for v in a {
+                if let Some(s) = v.as_str() {
+                    let s = s.trim();
+                    if !s.is_empty() {
+                        out.push(s.to_string());
+                    }
+                }
+            }
+        }
+        Some(Value::String(s)) => {
+            for seg in s.split([';', ';']) {
+                let seg = seg.trim();
+                if !seg.is_empty() {
+                    out.push(seg.to_string());
+                }
+            }
+        }
+        _ => {}
+    }
+    out
+}
+
+/// 在册可匹配值(一次载入,⛔ 逐行发查询)。
+#[derive(Default)]
+struct Lookups {
+    /// 区域节点:`bos_region_meta` 只存 node_id 与 node_id 路径,⛔ 中文名称列
+    region_ids: HashSet<String>,
+    region_options: Vec<String>,
+    /// 运营商:`(operator_id, 名称, 所属区域节点)`
+    operators: Vec<(String, String, String)>,
+    operator_options: Vec<String>,
+    /// 合伙人名称(归一化后)
+    partners: HashSet<String>,
+    partner_options: Vec<String>,
+    /// 运维团队名称(归一化后)→ team_id
+    teams: HashMap<String, String>,
+    team_options: Vec<String>,
+}
+
+fn norm_name(s: &str) -> String {
+    s.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase()
+}
+
+impl Lookups {
+    async fn load(state: &AppState) -> Result<Self, BosError> {
+        #[derive(Deserialize)]
+        struct Region {
+            #[serde(deserialize_with = "de::as_string")]
+            node_id: String,
+        }
+        #[derive(Deserialize)]
+        struct Op {
+            #[serde(deserialize_with = "de::as_string")]
+            operator_id: String,
+            #[serde(deserialize_with = "de::as_string")]
+            name: String,
+            #[serde(deserialize_with = "de::as_opt_string")]
+            region_node_id: Option<String>,
+        }
+        #[derive(Deserialize)]
+        struct Name {
+            #[serde(deserialize_with = "de::as_string")]
+            name: String,
+        }
+        #[derive(Deserialize)]
+        struct Team {
+            #[serde(deserialize_with = "de::as_string")]
+            team_id: String,
+            #[serde(deserialize_with = "de::as_string")]
+            team_name: String,
+        }
+        let mut l = Self::default();
+        for r in state
+            .db
+            .query_all::<Region>("SELECT node_id FROM bos_region_meta ORDER BY node_id", &[])
+            .await?
+        {
+            l.region_ids.insert(r.node_id.clone());
+            l.region_options.push(r.node_id);
+        }
+        // ⚠️ dev 骨架 `operator` ⛔ status/deleted_at 列(在册 schema 实测无此二列),
+        // 故运营商候选⛔ 加启用态过滤——加了即整条查询报错、导入提交不可用。缺列已登记 18 册。
+        for o in state
+            .db
+            .query_all::<Op>(
+                "SELECT operator_id, name, region_node_id FROM operator ORDER BY name",
+                &[],
+            )
+            .await?
+        {
+            l.operator_options.push(o.name.clone());
+            l.operators.push((o.operator_id, o.name, o.region_node_id.unwrap_or_default()));
+        }
+        for p in state
+            .db
+            .query_all::<Name>(
+                "SELECT DISTINCT name FROM partner WHERE status = 'active' AND name IS NOT NULL ORDER BY name",
+                &[],
+            )
+            .await?
+        {
+            l.partners.insert(norm_name(&p.name));
+            l.partner_options.push(p.name);
+        }
+        // ⚠️ 同上:dev 骨架 `ops_team` 同样 ⛔ status/deleted_at 列(在册 schema 实测无此二列),
+        // 团队候选只能取全表;「软删除团队不再出现在导入候选里」这条口径因此 ⛔ 成立,已登记 18 册。
+        for t in state
+            .db
+            .query_all::<Team>(
+                "SELECT team_id, team_name FROM ops_team ORDER BY team_name",
+                &[],
+            )
+            .await?
+        {
+            l.team_options.push(t.team_name.clone());
+            l.teams.insert(norm_name(&t.team_name), t.team_id);
+        }
+        Ok(l)
+    }
+}
+
+/// 可选值提示(第 2 册§4.4「未匹配到」一律带可选值清单)。
+fn options_hint(prefix: &str, opts: &[String]) -> String {
+    if opts.is_empty() {
+        return format!("{prefix}(当前无可选值)");
+    }
+    let shown: Vec<&String> = opts.iter().take(20).collect();
+    let mut s = shown.iter().map(|v| v.as_str()).collect::<Vec<_>>().join("、");
+    if opts.len() > shown.len() {
+        s.push_str(&format!("…(共 {} 项)", opts.len()));
+    }
+    format!("{prefix},可选值:{s}")
+}
+
+/// 逐行校验(第 2 册§4.4:一行可命中多项 ⇒ 全量报错)。
+///
+/// 返回 `(归一化识别号, 错误列表)`;错误列表为空=`valid`。
+fn validate_row(row: &Value, l: &Lookups, seen: &mut HashMap<String, i64>) -> (String, Vec<String>) {
+    let mut e: Vec<String> = Vec::new();
+
+    let name = text(row, "customer_name");
+    let n = name.chars().count();
+    if n == 0 {
+        e.push("客户名称未填写".to_string());
+    } else if !(2..=128).contains(&n) {
+        e.push("客户名称需 2~128 字".to_string());
+    }
+
+    let raw_id = text(row, "id_code");
+    let id = norm_identity_no(&raw_id);
+    if id.is_empty() {
+        e.push("识别号未填写".to_string());
+    } else {
+        let st = subject_type_code(&text(row, "subject_type"));
+        match st {
+            None => e.push("主体类型不在取值内".to_string()),
+            Some(st) => {
+                if !is_valid_identity_no(&id, st) {
+                    e.push("识别号格式不正确".to_string());
+                }
+                match seen.get(&id) {
+                    // §4.4:文件内重复=提示已有主体号+文件内首次行号,⛔ 不写主体号列
+                    Some(first) => e.push(format!(
+                        "识别号已存在,客户主体号(见文件第 {} 行)",
+                        first
+                    )),
+                    None => {
+                        seen.insert(id.clone(), text(row, "row_no").parse().unwrap_or(0));
+                        // ⚠️ 库内侧(跨文件)查重要 `identity_no_hash = HMAC(密钥, 归一化)`,
+                        // 全仓无该密钥通路(18 册在册)⇒ 此处只能做文件内查重,缺口如实回显,
+                        // ⛔ 自行发明哈希算法冒充已查重。
+                    }
+                }
+            }
+        }
+    }
+
+    let cn = text(row, "contact_name").chars().count();
+    if cn == 0 {
+        e.push("请填写经办联系人姓名".to_string());
+    } else if !(2..=64).contains(&cn) {
+        e.push("经办联系人姓名需 2~64 字".to_string());
+    }
+
+    let mob = text(row, "contact_mobile");
+    if mob.is_empty() {
+        e.push("请填写经办联系人手机号".to_string());
+    } else if !(7..=20).contains(&mob.chars().count())
+        || !mob.chars().all(|c| c.is_ascii_digit() || c == '-')
+    {
+        e.push("手机号需 7~20 位数字或短横线".to_string());
+    }
+
+    let addr = text(row, "address").chars().count();
+    if addr == 0 {
+        e.push("请填写可核查的详细地址".to_string());
+    } else if !(5..=255).contains(&addr) {
+        e.push("详细地址需 5~255 字".to_string());
+    }
+
+    let region = text(row, "region_name");
+    let region_hit = !region.is_empty() && l.region_ids.contains(&region);
+    if region.is_empty() {
+        e.push(options_hint("区域未匹配到", &l.region_options));
+    } else if !region_hit {
+        e.push(options_hint("区域未匹配到", &l.region_options));
+    }
+
+    // 运营商:「区域 / 名称」联合匹配,⛔ 只按名称取第一条
+    let op_cell = text(row, "operator_name");
+    if op_cell.is_empty() {
+        e.push(options_hint("运营商未匹配到", &l.operator_options));
+    } else {
+        let (r_part, n_part) = match op_cell.split_once('/') {
+            Some((a, b)) => (a.trim(), b.trim()),
+            None => ("", op_cell.as_str()),
+        };
+        let by_name: Vec<&(String, String, String)> = l
+            .operators
+            .iter()
+            .filter(|(_, nm, _)| norm_name(nm) == norm_name(n_part))
+            .collect();
+        let hit = match r_part {
+            "" => by_name.len() == 1,
+            _ => by_name.iter().any(|(_, _, rg)| rg == r_part),
+        };
+        if !hit {
+            e.push(options_hint("运营商未匹配到", &l.operator_options));
+        }
+    }
+
+    let partner = text(row, "partner_name");
+    if !partner.is_empty() && !l.partners.contains(&norm_name(&partner)) {
+        e.push(options_hint("合伙人未匹配到", &l.partner_options));
+    }
+
+    let teams = team_cells(row);
+    if teams.is_empty() {
+        e.push(options_hint("归属运维团队未匹配到", &l.team_options));
+    }
+    for t in &teams {
+        if !l.teams.contains_key(&norm_name(t)) {
+            e.push(options_hint(
+                &format!("归属运维团队「{t}」匹配不到,请填写名称原文且需在您的负责范围内"),
+                &l.team_options,
+            ));
+        }
+    }
+
+    if !text(row, "primary_username").is_empty() || !text(row, "primary_mobile").is_empty() {
+        e.push("主账号登录名/手机号暂不可受理(平台建号通路阻塞,见 18 册),请留空".to_string());
+    }
+
+    (id, e)
+}
+
+/// 批次号发号:`IMP-{年}-{4 位流水}`(第 2 册§4.8,四位补零、自然进位)。
+///
+/// 与 [`super::customer`] 的主体号同法:发号后**查重占位**,撞号则再发一号——
+/// `next_seq` 首次以 `COUNT(1)` 为初值,而种子批次号是稀疏的,直接用计数值必撞号。
+async fn issue_batch_no(state: &AppState) -> Result<String, BosError> {
+    let year = Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))?;
+    for _ in 0..25 {
+        let seq = next_seq(state.db.as_ref(), "import_batch", "import_batch", year).await?;
+        let no = format!("IMP-{year}-{seq:04}");
+        let mut p = Params::default();
+        let ph = p.push(Value::String(no.clone()));
+        let sql = format!("SELECT batch_id FROM import_batch WHERE batch_no = {ph}::text LIMIT 1");
+        match state.db.query_one::<Value>(&sql, p.values()).await? {
+            Some(_) => continue,
+            None => return Ok(no),
+        }
+    }
+    Err(BosError::internal("批次号连续 25 次撞号,发号中止"))
 }
-pub async fn get_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [], "total": 0 }))
+
+/// 批量导入提交(第 2 册§4.3):四道文件级闸门 → 建批次 + 逐行落 `import_batch_row`
+/// → 逐行校验写 `valid`/`invalid`。
+///
+/// ⚠️ 本接口**只校验不建档**:客户建档在「确认导入」(`import/confirm@v1`,本仓⛔ 该路由),
+/// 因此本接口不触碰平台建号,与「主账号暂不可受理」的建档侧阻塞无关。
+pub async fn submit(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ImportSubmit>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) {
+        return json_err(e);
+    }
+    // 闸门 1(D005):无数据行=空文件/无法解析
+    if body.rows.is_empty() {
+        return json_err(BosError::klt(
+            KltCode::D005,
+            "文件格式非法:未解析到任何数据行(非 .xlsx/无法解析/缺表头)",
+        ));
+    }
+    // 闸门 3(D002):单批行数上限(配置项 import_max_rows)
+    if let Err(e) = assert_row_limit(body.rows.len()) {
+        return json_err(e);
+    }
+    // 闸门 4(D003):行编号在文件内重复 ⇒ 整个文件不入库、⛔ 自动改号(§4.8)
+    let mut declared: HashSet<String> = HashSet::new();
+    let mut dup: Vec<String> = Vec::new();
+    for r in &body.rows {
+        let no = text(r, "row_no");
+        if no.is_empty() || no == "示例" {
+            continue;
+        }
+        if !declared.insert(no.clone()) {
+            dup.push(no);
+        }
+    }
+    if !dup.is_empty() {
+        return json_err(BosError::klt(
+            KltCode::D003,
+            format!("行编号在文件内重复:{},整个文件不导入", dup.join("、")),
+        ));
+    }
+
+    // 示例行:跳过、不计数、不入库(§4.4)
+    let data_rows: Vec<&Value> = body
+        .rows
+        .iter()
+        .filter(|r| text(r, "row_no") != "示例")
+        .collect();
+    if data_rows.is_empty() {
+        return json_err(BosError::klt(
+            KltCode::D005,
+            "文件格式非法:文件仅含示例行,无数据行".to_string(),
+        ));
+    }
+    if data_rows.len() > 500 {
+        return json_err(BosError::klt(
+            KltCode::D002,
+            format!("数据行数 {} 超过上限,请拆分成多个文件", data_rows.len()),
+        ));
+    }
+
+    let lookups = match Lookups::load(&state).await {
+        Ok(l) => l,
+        Err(e) => return json_err(e),
+    };
+
+    let batch_no = match issue_batch_no(&state).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+
+    // 逐行校验(行编号留空按数据行顺序填 1、2、3…)
+    let mut seen: HashMap<String, i64> = HashMap::new();
+    let mut rows: Vec<(i64, Value, bool, Vec<String>)> = Vec::with_capacity(data_rows.len());
+    let mut invalid = 0usize;
+    for (i, r) in data_rows.iter().enumerate() {
+        let row_no: i64 = match text(r, "row_no").parse() {
+            Ok(v) => v,
+            Err(_) => (i + 1) as i64,
+        };
+        let (id, errs) = validate_row(r, &lookups, &mut seen);
+        let payload = json!({
+            "columns": r,
+            "identity_no_normalized": id,
+        });
+        if !errs.is_empty() {
+            invalid += 1;
+        }
+        rows.push((row_no, payload, errs.is_empty(), errs));
+    }
+    let total_rows = rows.len() as i64;
+
+    // 建批次(status='running':§4.2 状态机里 failed_pending 由「确认导入」推进)
+    let mut p = Params::default();
+    let (pn, py, pr, po) = (p.push(Value::String(batch_no.clone())), p.push(Value::String("customer".into())), p.push(Value::String("running".into())), p.push(Value::String(auth.user_id.clone())));
+    let (pt, ps, pf) = (
+        p.push(Value::String(total_rows.to_string())),
+        p.push(Value::String("0".into())),
+        p.push(Value::String(invalid.to_string())),
+    );
+    let ins = format!(
+        "INSERT INTO import_batch (batch_no, batch_type, status, operator_user_id, total_rows, \
+         success_rows, fail_rows) VALUES ({pn}::text, {py}::text, {pr}::text, {po}::bigint, \
+         {pt}::bigint, {ps}::bigint, {pf}::bigint)"
+    );
+    let _ = match state.db.dml(&ins, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+
+    // 回读 batch_id(主键由 DB 侧 `big_serial` 生成,⛔ 假设"发号即主键")
+    #[derive(Deserialize)]
+    struct Head {
+        #[serde(deserialize_with = "de::as_string")]
+        batch_id: String,
+    }
+    let mut q = Params::default();
+    let qb = q.push(Value::String(batch_no.clone()));
+    let head = match state
+        .db
+        .query_one::<Head>(
+            &format!("SELECT batch_id FROM import_batch WHERE batch_no = {qb}::text LIMIT 1"),
+            q.values(),
+        )
+        .await
+    {
+        Ok(Some(h)) => h,
+        Ok(None) => return json_err(BosError::internal("批次写入后回读不到,写侧未生效")),
+        Err(e) => return json_err(e),
+    };
+
+    // 逐行落 import_batch_row(§4.3 第 3 步;一次 dml_batch,⛔ 逐行往返)
+    let mut stmts: Vec<DmlStatement> = Vec::with_capacity(rows.len());
+    for (row_no, payload, ok, errs) in &rows {
+        let mut rp = Params::default();
+        let b = rp.push(Value::String(head.batch_id.clone()));
+        let n = rp.push(Value::String(row_no.to_string()));
+        let j = rp.push(payload.clone());
+        let st = rp.push(Value::String(if *ok { "valid" } else { "invalid" }.to_string()));
+        let el = rp.push(Value::Array(errs.iter().cloned().map(Value::String).collect()));
+        stmts.push(DmlStatement::new(
+            format!(
+                "INSERT INTO import_batch_row (batch_id, row_no, raw_json, validate_status, \
+                 error_list) VALUES ({b}::bigint, {n}::bigint, {j}::jsonb, {st}::text, \
+                 {el}::jsonb)"
+            ),
+            rp.values().to_vec(),
+        ));
+    }
+    let written = match state.db.dml_batch(&stmts).await {
+        Ok(v) => v.iter().map(|r| r.affected_rows.unwrap_or(0)).sum::<u64>(),
+        Err(e) => return json_err(e),
+    };
+    if written as usize != rows.len() {
+        return json_err(BosError::internal(format!(
+            "行级写入未全部生效:应写 {} 行、实写 {written} 行",
+            rows.len()
+        )));
+    }
+
+    let preview: Vec<Value> = rows
+        .iter()
+        .map(|(no, _, ok, errs)| {
+            json!({
+                "row_no": no,
+                "validate_status": if *ok { "valid" } else { "invalid" },
+                "error_list": errs,
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "batch_id": head.batch_id,
+        "batch_no": batch_no,
+        "status": "running",
+        "total_rows": total_rows,
+        // §4.3:上传阶段只校验、未建档 ⇒ 成功行数恒为 0,fail_rows=行级校验失败数
+        "success_rows": 0,
+        "fail_rows": invalid,
+        "valid_rows": total_rows - invalid as i64,
+        "invalid_rows": invalid,
+        "rows_written": written,
+        "rows": preview,
+        "checks_pending": [
+            "识别号跨文件查重(需 identity_no_hash=HMAC 通路,全仓未通,见 18 册)",
+            "区域/运营商/合伙人/运维团队的「负责范围」收敛(需区域闭包展开,全仓未通,见 18 册)"
+        ],
+        "region_match_note": "bos_region_meta ⛔ 中文名称列(path_name 存 node_id 路径),\
+                              故区域列当前只能按 node_id 精确匹配,名称通路待补"
+    }))
 }
-pub async fn get(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "batch": b }))
+
+/// 导入批次列表(需求§4「批量导入」逐字:批次号/导入人/状态/总行数/成功/失败/时间)。
+#[derive(Deserialize)]
+pub struct BatchListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub status: Option<String>,
 }
-pub async fn resume(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "resumed": true, "req": b }))
+
+#[derive(Deserialize)]
+struct BatchRow {
+    #[serde(deserialize_with = "de::as_string")]
+    batch_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    batch_no: String,
+    #[serde(deserialize_with = "de::as_string")]
+    batch_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_string")]
+    total_rows: String,
+    #[serde(deserialize_with = "de::as_string")]
+    success_rows: String,
+    #[serde(deserialize_with = "de::as_string")]
+    fail_rows: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    created_at: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    operator_username: Option<String>,
 }
-pub async fn export_codes(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "async": false, "req": b }))
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<BatchListReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        preds.push(format!("b.batch_no LIKE {k}"));
+    }
+    if let Some(s) = p.push_eq(body.status.as_deref()) {
+        preds.push(format!("b.status = {s}::text"));
+    }
+    let from_where = format!("FROM import_batch b {}", p.where_clause(&preds));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT b.batch_id, b.batch_no, b.batch_type, b.status, b.total_rows, b.success_rows, \
+         b.fail_rows, b.created_at, u.username AS operator_username FROM import_batch b \
+         LEFT JOIN bos_user_binding u ON u.user_id = b.operator_user_id {} \
+         ORDER BY b.created_at DESC, b.batch_id DESC LIMIT {lim} OFFSET {off}",
+        p.where_clause(&preds)
+    );
+    let rows = match state.db.query_all::<BatchRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            json!({
+                "batch_id": r.batch_id,
+                "batch_no": r.batch_no,
+                "batch_type": r.batch_type,
+                "status": r.status,
+                "total_rows": r.total_rows,
+                "success_rows": r.success_rows,
+                "fail_rows": r.fail_rows,
+                "operator_username": r.operator_username,
+                "created_at": r.created_at,
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
 }
-pub async fn export_customers(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "async": false, "req": b }))
+
+#[derive(Deserialize)]
+pub struct BatchGetReq {
+    pub batch_no: Option<String>,
+    pub batch_id: Option<String>,
+    #[serde(flatten)]
+    pub pg: PageQuery,
+}
+
+#[derive(Deserialize)]
+struct BatchDetail {
+    #[serde(deserialize_with = "de::as_string")]
+    batch_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    batch_no: String,
+    #[serde(deserialize_with = "de::as_string")]
+    batch_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_string")]
+    total_rows: String,
+    #[serde(deserialize_with = "de::as_string")]
+    success_rows: String,
+    #[serde(deserialize_with = "de::as_string")]
+    fail_rows: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    created_at: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    operator_username: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct StatusCount {
+    #[serde(deserialize_with = "de::as_string")]
+    validate_status: String,
+    #[serde(deserialize_with = "de::as_string")]
+    n: String,
+}
+
+#[derive(Deserialize)]
+struct RowDetail {
+    #[serde(deserialize_with = "de::as_string")]
+    row_no: String,
+    #[serde(deserialize_with = "de::as_string")]
+    validate_status: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    business_id: Option<String>,
+    #[serde(default)]
+    error_list: Option<Value>,
+}
+
+/// `jsonb` 经联邦引擎可能回字符串,取值处⛔ 假定单一形态。
+fn cell(v: Option<Value>) -> Value {
+    match v {
+        Some(Value::String(s)) => serde_json::from_str(&s).unwrap_or(Value::String(s)),
+        Some(v) => v,
+        None => Value::Null,
+    }
+}
+
+/// 批次详情:批次头+行级校验态分布+行级明细(分页)。
+pub async fn get(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<BatchGetReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+    if let Some(v) = p.push_eq(body.batch_no.as_deref()) {
+        preds.push(format!("b.batch_no = {v}::text"));
+    }
+    if let Some(v) = p.push_eq(body.batch_id.as_deref()) {
+        preds.push(format!("b.batch_id = {v}::bigint"));
+    }
+    if preds.is_empty() {
+        return json_err(bos_core::BosError::bad_params("须提交 batch_no 或 batch_id"));
+    }
+    let where1 = p.where_clause(&preds);
+    let sql = format!(
+        "SELECT b.batch_id, b.batch_no, b.batch_type, b.status, b.total_rows, b.success_rows, \
+         b.fail_rows, b.created_at, u.username AS operator_username FROM import_batch b \
+         LEFT JOIN bos_user_binding u ON u.user_id = b.operator_user_id {where1} \
+         ORDER BY b.created_at DESC LIMIT 1"
+    );
+    let head = match state.db.query_one::<BatchDetail>(&sql, p.values()).await {
+        Ok(Some(r)) => r,
+        Ok(None) => return json_err(bos_core::BosError::not_found("导入批次不存在")),
+        Err(e) => return json_err(e),
+    };
+
+    let bid = p.push(Value::String(head.batch_id.clone()));
+    let dist_sql = format!(
+        "SELECT r.validate_status, COUNT(1) AS n FROM import_batch_row r WHERE r.batch_id = {bid}::bigint \
+         GROUP BY r.validate_status ORDER BY r.validate_status"
+    );
+    let dist = match state.db.query_all::<StatusCount>(&dist_sql, p.values()).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let rows_sql = format!(
+        "SELECT r.row_no, r.validate_status, r.business_id, r.error_list FROM import_batch_row r \
+         WHERE r.batch_id = {bid}::bigint ORDER BY r.row_no LIMIT {lim} OFFSET {off}"
+    );
+    let rows = match state.db.query_all::<RowDetail>(&rows_sql, p.values()).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+
+    json_ok(json!({
+        "batch": {
+            "batch_id": head.batch_id,
+            "batch_no": head.batch_no,
+            "batch_type": head.batch_type,
+            "status": head.status,
+            "total_rows": head.total_rows,
+            "success_rows": head.success_rows,
+            "fail_rows": head.fail_rows,
+            "operator_username": head.operator_username,
+            "created_at": head.created_at,
+        },
+        "status_counts": dist.iter().map(|d| json!({
+            "validate_status": d.validate_status, "count": d.n
+        })).collect::<Vec<_>>(),
+        "rows": rows.iter().map(|r| json!({
+            "row_no": r.row_no,
+            "validate_status": r.validate_status,
+            "business_id": r.business_id,
+            "errors": cell(r.error_list.clone()),
+        })).collect::<Vec<_>>(),
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
+}
+
+/// 导入批次续传(第 2 册§4.6):同批次再次上传(可只传未导入行),逐行重新校验,
+/// 未导入行覆盖、新增行 insert、已导入行 ⛔ 重复建档只回显 `customer_id`。
+///
+/// ⚠️ §4.6 的 `attempt_count + 1` 在 dev 骨架 ⛔ 该列(`import_batch_row` 无 attempt_count),
+/// 因此续传次数无法留痕,缺口如实回显并登记 18 册;⛔ 用 error_list 伪造次数。
+pub async fn resume(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ResumeReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) {
+        return json_err(e);
+    }
+    if body.batch_no.trim().is_empty() {
+        return json_err(BosError::bad_params("须提交 batch_no(续传⛔ 生成新批次号)"));
+    }
+    if let Err(e) = assert_row_limit(body.rows.len()) {
+        return json_err(e);
+    }
+
+    #[derive(Deserialize)]
+    struct Batch {
+        #[serde(deserialize_with = "de::as_string")]
+        batch_id: String,
+        #[serde(deserialize_with = "de::as_string")]
+        status: String,
+    }
+    let mut p = Params::default();
+    let bn = p.push(Value::String(body.batch_no.trim().to_string()));
+    let batch = match state
+        .db
+        .query_one::<Batch>(
+            &format!("SELECT batch_id, status FROM import_batch WHERE batch_no = {bn}::text LIMIT 1"),
+            p.values(),
+        )
+        .await
+    {
+        Ok(Some(b)) => b,
+        Ok(None) => {
+            return json_err(BosError::klt(
+                KltCode::D004,
+                format!("续传前提不成立:批次 `{}` 不存在", body.batch_no),
+            ))
+        }
+        Err(e) => return json_err(e),
+    };
+    // 状态闸(§4.6):done 后 ⛔ 续传,一律新开批次
+    if !matches!(batch.status.as_str(), "running" | "failed_pending" | "part_done") {
+        return json_err(BosError::klt(
+            KltCode::D004,
+                format!(
+                    "续传前提不成立:批次 `{}` 状态为 `{}`,导入完成的批次 ⛔ 续传,请新建导入批次",
+                    body.batch_no, batch.status
+                ),
+        ));
+    }
+
+    // 在册行(含已导入行)
+    #[derive(Deserialize)]
+    struct Exist {
+        #[serde(deserialize_with = "de::as_string")]
+        row_no: String,
+        #[serde(deserialize_with = "de::as_string")]
+        validate_status: String,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        business_id: Option<String>,
+    }
+    let mut ep = Params::default();
+    let eb = ep.push(Value::String(batch.batch_id.clone()));
+    let exist = match state
+        .db
+        .query_all::<Exist>(
+            &format!(
+                "SELECT row_no, validate_status, business_id FROM import_batch_row \
+                 WHERE batch_id = {eb}::bigint ORDER BY row_no"
+            ),
+            ep.values(),
+        )
+        .await
+    {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let known: HashSet<i64> = exist.iter().filter_map(|r| r.row_no.parse().ok()).collect();
+    let imported: HashMap<i64, Option<String>> = exist
+        .iter()
+        .filter(|r| r.validate_status == "imported")
+        .filter_map(|r| r.row_no.parse::<i64>().ok().map(|n| (n, r.business_id.clone())))
+        .collect();
+    let max_row = known.iter().copied().max().unwrap_or(0);
+
+    let lookups = match Lookups::load(&state).await {
+        Ok(l) => l,
+        Err(e) => return json_err(e),
+    };
+
+    // 行号闸(§4.6:⛔ 任意行号):不超过在册最大行号却从未出现过的行号 ⇒ 拒;
+    // 超过最大行号者=§4.6 的「新增行」,走 insert
+    let mut ghost: Vec<String> = Vec::new();
+    for r in &body.rows {
+        let no = text(r, "row_no");
+        if no == "示例" {
+            continue;
+        }
+        match no.parse::<i64>() {
+            Ok(n) if n > max_row => continue,
+            Ok(n) => {
+                if !known.contains(&n) {
+                    ghost.push(no);
+                }
+            }
+            Err(_) => ghost.push(no),
+        }
+    }
+    if !ghost.is_empty() {
+        return json_err(BosError::klt(
+            KltCode::D004,
+            format!(
+                "续传前提不成立:行号 {} 不在该批次的未导入行编号集合内(在册最大行号 {max_row})",
+                ghost.join("、")
+            ),
+        ));
+    }
+
+    let mut updates: Vec<DmlStatement> = Vec::new();
+    let mut inserts: Vec<DmlStatement> = Vec::new();
+    let mut results: Vec<Value> = Vec::new();
+    let mut seen2: HashMap<String, i64> = HashMap::new();
+    for r in &body.rows {
+        let raw_no = text(r, "row_no");
+        if raw_no == "示例" {
+            continue;
+        }
+        let row_no: i64 = match raw_no.parse() {
+            Ok(v) => v,
+            Err(_) => {
+                return json_err(BosError::klt(
+                    KltCode::D004,
+                    format!("续传前提不成立:行编号 `{raw_no}` 不可解析"),
+                ))
+            }
+        };
+        // 已导入行:⛔ 重复建档,只回显
+        if let Some(cid) = imported.get(&row_no) {
+            results.push(json!({
+                "row_no": row_no,
+                "outcome": "already_imported",
+                "customer_id": cid,
+                "note": "§4.6:已成功行不再建档,本次上传只回显"
+            }));
+            continue;
+        }
+        let (id, errs) = validate_row(r, &lookups, &mut seen2);
+        let ok = errs.is_empty();
+        let payload = json!({ "columns": r, "identity_no_normalized": id });
+        let mut rp = Params::default();
+        let b = rp.push(Value::String(batch.batch_id.clone()));
+        let n = rp.push(Value::String(row_no.to_string()));
+        let j = rp.push(payload);
+        let st = rp.push(Value::String(if ok { "valid" } else { "invalid" }.to_string()));
+        let el = rp.push(Value::Array(errs.iter().cloned().map(Value::String).collect()));
+        let stmt = if known.contains(&row_no) {
+            DmlStatement::new(
+                format!(
+                    "UPDATE import_batch_row SET raw_json = {j}::jsonb, validate_status = {st}::text, \
+                     error_list = {el}::jsonb WHERE batch_id = {b}::bigint AND row_no = {n}::bigint"
+                ),
+                rp.values().to_vec(),
+            )
+        } else {
+            DmlStatement::new(
+                format!(
+                    "INSERT INTO import_batch_row (batch_id, row_no, raw_json, validate_status, \
+                     error_list) VALUES ({b}::bigint, {n}::bigint, {j}::jsonb, {st}::text, {el}::jsonb)"
+                ),
+                rp.values().to_vec(),
+            )
+        };
+        if known.contains(&row_no) {
+            updates.push(stmt);
+        } else {
+            inserts.push(stmt);
+        }
+        results.push(json!({
+            "row_no": row_no,
+            "outcome": if known.contains(&row_no) { "overwritten" } else { "inserted" },
+            "validate_status": if ok { "valid" } else { "invalid" },
+            "error_list": errs,
+        }));
+    }
+
+    let sum_affected = |v: Vec<DmlStatementResult>| -> u64 {
+        v.iter().map(|r| r.affected_rows.unwrap_or(0)).sum()
+    };
+    let mut touched = 0u64;
+    if !updates.is_empty() {
+        touched += match state.db.dml_batch(&updates).await {
+            Ok(v) => sum_affected(v),
+            Err(e) => return json_err(e),
+        };
+    }
+    if !inserts.is_empty() {
+        touched += match state.db.dml_batch(&inserts).await {
+            Ok(v) => sum_affected(v),
+            Err(e) => return json_err(e),
+        };
+    }
+
+    // 汇总与状态推进(failed_pending / part_done → running)
+    #[derive(Deserialize)]
+    struct Head2 {
+        #[serde(deserialize_with = "de::as_string")]
+        status: String,
+        #[serde(deserialize_with = "de::as_string")]
+        total_rows: String,
+        #[serde(deserialize_with = "de::as_string")]
+        success_rows: String,
+        #[serde(deserialize_with = "de::as_string")]
+        fail_rows: String,
+    }
+    let mut sp = Params::default();
+    let sb = sp.push(Value::String(batch.batch_id.clone()));
+    let rows_cnt = format!("(SELECT COUNT(1) FROM import_batch_row WHERE batch_id = {sb}::bigint)");
+    let ok_cnt = format!(
+        "(SELECT COALESCE(SUM(CASE WHEN validate_status = 'imported' THEN 1 ELSE 0 END), 0) \
+         FROM import_batch_row WHERE batch_id = {sb}::bigint)"
+    );
+    let bad_cnt = format!(
+        "(SELECT COALESCE(SUM(CASE WHEN validate_status = 'invalid' THEN 1 ELSE 0 END), 0) \
+         FROM import_batch_row WHERE batch_id = {sb}::bigint)"
+    );
+    let sum_hit = match state
+        .db
+        .dml(
+            &format!(
+                "UPDATE import_batch SET status = 'running', total_rows = {rows_cnt}, \
+                 success_rows = {ok_cnt}, fail_rows = {bad_cnt} WHERE batch_id = {sb}::bigint"
+            ),
+            sp.values(),
+        )
+        .await
+    {
+        Ok(n) => n,
+        Err(e) => return json_err(BosError::internal(format!("批次头汇总未写入:{e}"))),
+    };
+    if sum_hit != 1 {
+        return json_err(BosError::internal("批次头汇总影响行数 ≠ 1,汇总未生效"));
+    }
+    let mut hp = Params::default();
+    let hb = hp.push(Value::String(batch.batch_id.clone()));
+    let head2 = match state
+        .db
+        .query_one::<Head2>(
+            &format!(
+                "SELECT status, total_rows, success_rows, fail_rows FROM import_batch \
+                 WHERE batch_id = {hb}::bigint LIMIT 1"
+            ),
+            hp.values(),
+        )
+        .await
+    {
+        Ok(Some(h)) => h,
+        Ok(None) => return json_err(BosError::internal("批次头回读不到")),
+        Err(e) => return json_err(e),
+    };
+
+    json_ok(json!({
+        "batch_id": batch.batch_id,
+        "batch_no": body.batch_no.trim(),
+        "status_before": batch.status,
+        "status_after": "running",
+        "updated_rows": updates.len(),
+        "inserted_rows": inserts.len(),
+        "affected_rows": touched,
+        "already_imported_rows": results.iter().filter(|v| v["outcome"] == "already_imported").count(),
+        "summary": {
+            "status": head2.status,
+            "total_rows": head2.total_rows,
+            "success_rows": head2.success_rows,
+            "fail_rows": head2.fail_rows,
+        },
+        "rows": results,
+        "checks_pending": [
+            "attempt_count 未留痕:dev import_batch_row ⛔ attempt_count 列(§4.6 要求 +1),见 18 册",
+            "识别号跨文件查重、区域闭包收敛同 submit,见 18 册"
+        ]
+    }))
+}
+
+/// 按批导出客户清单的 15 列(第 2 册§4.7:顺序固定、⛔ 增删列、⛔ 换序)。
+const EXPORT_CUSTOMER_COLUMNS: [&str; 15] = [
+    "客户主体号", "客户名称", "客户识别号", "主体类型", "所属区域", "运营商", "合伙人", "运维团队",
+    "联系电话", "地址", "服务开通状态", "激活状态", "开通时间", "行编号", "行状态",
+];
+
+/// 主体类型机器码 → 清单显示名(与模板候选值同词,⛔ 清单里写英文码)。
+fn subject_type_name(code: &str) -> &str {
+    match code.trim() {
+        "enterprise" => "企业",
+        "individual" => "个人",
+        "sole_proprietor" => "个体工商户",
+        other => other,
+    }
+}
+
+/// 两个导出接口的入参(openapi 的 `data.batch_id` 必填=单个批次)。
+#[derive(Deserialize)]
+pub struct ExportBatchReq {
+    pub batch_id: String,
+}
+
+#[derive(Deserialize)]
+struct ExportHead {
+    #[serde(deserialize_with = "de::as_string")]
+    batch_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    batch_no: String,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_string")]
+    total_rows: String,
+    #[serde(deserialize_with = "de::as_string")]
+    operator_user_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    operator_username: Option<String>,
+}
+
+/// 两道收窄的**第一道**(§4.1「批次列表可见=本人导入的批次 + `admin` 全量」):
+/// 非 `admin` 只能导自己导入的批次。越权一律回「不存在」,⛔ 用错误码泄露他人批次存在性。
+async fn load_export_head(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    batch_id: &str,
+) -> Result<ExportHead, BosError> {
+    let mut p = Params::default();
+    let b = p.push(Value::String(batch_id.trim().to_string()));
+    let sql = format!(
+        "SELECT b.batch_id, b.batch_no, b.status, b.total_rows, b.operator_user_id, \
+         u.username AS operator_username FROM import_batch b \
+         LEFT JOIN bos_user_binding u ON u.user_id = b.operator_user_id \
+         WHERE b.batch_id = {b}::bigint LIMIT 1"
+    );
+    let head = match state.db.query_one::<ExportHead>(&sql, p.values()).await {
+        Ok(Some(h)) => h,
+        Ok(None) => return Err(BosError::not_found("导入批次不存在")),
+        Err(e) => return Err(e),
+    };
+    if !matches!(auth.role, RoleCode::Admin) && head.operator_user_id.trim() != auth.user_id.trim() {
+        return Err(BosError::not_found("导入批次不存在"));
+    }
+    Ok(head)
+}
+
+/// 按批导出客户清单(§4.7):15 列固定顺序、**失败行同样输出**(主体号留空、行状态写失败原因),
+/// 数据源=`import_batch_row.raw_json` +已建档行的 `customer` 实时值。
+///
+/// ⚠️ 三列当前无数据源,按空串输出并在 `columns_pending` 点名(⛔ 编造值):
+/// 「激活状态」(激活码/IAM 通路未通=U-98)、「开通时间」(`customer` ⛔ `opened_at` 列)、
+/// 「所属区域」全路径(`bos_region_meta` ⛔ 中文名称列,只能回模板填写值)。
+/// 识别号同理:`customer` 只有密文/HMAC,⛔ 明文可逆通路,故写**导入时的归一化值**。
+pub async fn export_customers(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ExportBatchReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let head = match load_export_head(&state, &auth, &body.batch_id).await {
+        Ok(h) => h,
+        Err(e) => return json_err(e),
+    };
+
+    // 第二道收窄(§4.1):按批次取行后,再按**当前查看人**可见范围收窄一次;
+    // 未建档行(business_id 为空)无客户归属可言,按批次归属可见 ⇒ 一并输出。
+    let mut p = Params::default();
+    let b = p.push(Value::String(head.batch_id.clone()));
+    let scope = match customer_scope_pred(&state, &auth, &mut p, "r.business_id").await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let sql = format!(
+        "SELECT r.row_no, r.validate_status, r.business_id, r.error_list, r.raw_json, \
+         c.customer_name, c.subject_type, c.acct_status, o.name AS operator_name, \
+         pt.name AS partner_name FROM import_batch_row r \
+         LEFT JOIN customer c ON c.customer_id = r.business_id \
+         LEFT JOIN operator o ON o.operator_id = c.operator_id \
+         LEFT JOIN partner pt ON pt.partner_id = c.partner_id \
+         WHERE r.batch_id = {b}::bigint AND (r.business_id IS NULL OR {scope}) \
+         ORDER BY r.row_no"
+    );
+    #[derive(Deserialize)]
+    struct ExportRow {
+        #[serde(deserialize_with = "de::as_string")]
+        row_no: String,
+        #[serde(deserialize_with = "de::as_string")]
+        validate_status: String,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        business_id: Option<String>,
+        #[serde(default)]
+        error_list: Option<Value>,
+        #[serde(default)]
+        raw_json: Option<Value>,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        customer_name: Option<String>,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        subject_type: Option<String>,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        acct_status: Option<String>,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        operator_name: Option<String>,
+        #[serde(deserialize_with = "de::as_opt_string")]
+        partner_name: Option<String>,
+    }
+    let rows = match state.db.query_all::<ExportRow>(&sql, p.values()).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+
+    // 差额说明(§4.1「导出行数少于批次行数必须在结果里说明差额」):另取批次全量行编号比对。
+    #[derive(Deserialize)]
+    struct RowNo {
+        #[serde(deserialize_with = "de::as_string")]
+        row_no: String,
+    }
+    let mut q = Params::default();
+    let qb = q.push(Value::String(head.batch_id.clone()));
+    let all = match state
+        .db
+        .query_all::<RowNo>(
+            &format!(
+                "SELECT row_no FROM import_batch_row WHERE batch_id = {qb}::bigint ORDER BY row_no"
+            ),
+            q.values(),
+        )
+        .await
+    {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+
+    let exported: Vec<Value> = rows
+        .iter()
+        .map(|r| {
+            let raw = cell(r.raw_json.clone());
+            let cols = raw.get("columns").cloned().unwrap_or(Value::Null);
+            let live = |s: &Option<String>| s.clone().filter(|v| !v.is_empty());
+            let row_status = match r.validate_status.as_str() {
+                // §4.7:失败行的「行状态」写失败原因 ⇒ 这份文件是查失败原因的底稿
+                "invalid" => match cell(r.error_list.clone()).as_array().cloned() {
+                    Some(a) if !a.is_empty() => a
+                        .iter()
+                        .map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string()))
+                        .collect::<Vec<_>>()
+                        .join(";"),
+                    _ => "校验未通过(未记录原因)".to_string(),
+                },
+                "imported" => "已导入".to_string(),
+                other => other.to_string(),
+            };
+            json!([
+                r.business_id.clone().unwrap_or_default(),
+                live(&r.customer_name).unwrap_or_else(|| text(&cols, "customer_name")),
+                // 识别号、电话按文本写入(§4.7:⛔ 数值转换)
+                raw.get("identity_no_normalized")
+                    .and_then(|v| v.as_str())
+                    .unwrap_or("")
+                    .to_string(),
+                match r.subject_type.as_deref() {
+                    Some(s) if !s.is_empty() => subject_type_name(s).to_string(),
+                    _ => text(&cols, "subject_type"),
+                },
+                text(&cols, "region_name"),
+                live(&r.operator_name).unwrap_or_else(|| text(&cols, "operator_name")),
+                live(&r.partner_name).unwrap_or_else(|| text(&cols, "partner_name")),
+                team_cells(&cols).join(";"),
+                text(&cols, "contact_mobile"),
+                text(&cols, "address"),
+                live(&r.acct_status).unwrap_or_default(),
+                String::new(),
+                String::new(),
+                r.row_no.clone(),
+                row_status,
+            ])
+        })
+        .collect();
+
+    let keep: HashSet<&str> = rows.iter().map(|r| r.row_no.as_str()).collect();
+    let excluded: Vec<String> = all
+        .iter()
+        .filter(|a| !keep.contains(a.row_no.as_str()))
+        .map(|a| a.row_no.clone())
+        .collect();
+    let exported_cnt = exported.len();
+    let batch_cnt = all.len();
+
+    let mut notes: Vec<String> = Vec::new();
+    if !excluded.is_empty() {
+        notes.push(format!(
+            "§4.1 两道收窄:本批次 {batch_cnt} 行,因查看人可见范围只导出 {exported_cnt} 行,\
+             差额 {excluded_cnt} 行=行编号 {}",
+            excluded.join("、"),
+            excluded_cnt = excluded.len()
+        ));
+    }
+
+    json_ok(json!({
+        "batch_id": head.batch_id,
+        "batch_no": head.batch_no,
+        "batch_status": head.status,
+        "operator_username": head.operator_username,
+        "columns": EXPORT_CUSTOMER_COLUMNS,
+        "rows": exported,
+        "exported_rows": exported_cnt,
+        "batch_total_rows": batch_cnt,
+        "batch_total_rows_declared": head.total_rows,
+        "scope_narrowing": {
+            "importer_scope": if matches!(auth.role, RoleCode::Admin) { "admin 全量" } else { "本人导入的批次" },
+            "viewer_scope_excluded_row_nos": excluded,
+            "notes": notes,
+        },
+        "columns_pending": [
+            "激活状态:⛔ 数据源(激活码/IAM 凭证通路未通=U-98,见 18 册)⇒ 按空串输出",
+            "开通时间:customer ⛔ opened_at 列(dev 骨架缺列,见 18 册)⇒ 按空串输出",
+            "所属区域:bos_region_meta ⛔ 中文名称列(path_name 存 node_id 路径)⇒ 回模板填写值,全路径待补",
+            "客户识别号:customer 仅存密文/HMAC,⛔ 明文可逆通路 ⇒ 回导入时的归一化值"
+        ],
+        "async_note": "行数超 export_async_rows 应转 seoh-import-export 异步通道(U-81/PC-4),\
+                       本仓 ⛔ 该通道 ⇒ 超限时须人工拆分",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE
+    }))
+}
+
+/// 按批导出激活码清单(§4.8 → 第 1 册§4.3):与 `account::export_codes` 同口径。
+///
+/// ⚠️ 明文导出依赖 `bootstrap_credential/export@v1`,而 `U-98`(该导出权限键在我方
+/// 无合法持有主体)未定 ⇒ 诚实降级为「能力待定」,⛔ 改用内部令牌绕过、⛔ 返回空清单冒充成功。
+/// 批次可见性仍先过第一道收窄,⛔ 借"能力待定"泄露他人批次是否存在。
+pub async fn export_codes(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ExportBatchReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let head = match load_export_head(&state, &auth, &body.batch_id).await {
+        Ok(h) => h,
+        Err(e) => return json_err(e),
+    };
+    json_ok(json!({
+        "batch_id": head.batch_id,
+        "batch_no": head.batch_no,
+        "status": "capability_pending",
+        "message": "激活码明文导出依赖 bootstrap_credential/export@v1;U-98(该导出权限键在我方\
+                    无合法持有主体)未定前按能力待定提示,⛔ 不得改用内部令牌",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE
+    }))
 }

+ 497 - 0
src/modules/account/src/handlers/listq.rs

@@ -0,0 +1,497 @@
+//! 列表类只读接口的共用 SQL 组装。
+//!
+//! 两条硬口径在代码里的落点:
+//! * 值一律走 `params`(注入防线+绕开 `sql_guard` 对 SQL 原文的字面量子串误杀=`UDS-6`),
+//!   因此谓词只能由 [`Params`] 按顺序发 `$n` 占位符,⛔ 手拼值;
+//! * 表名改写靠 `qualify()` 认 `FROM`/`JOIN` 关键字,所以组装出的 SQL ⛔ 缺 `FROM`。
+
+use bos_core::{BosError, PageQuery};
+use bos_platform::clients::uds::{de, UdsClient};
+use serde::Deserialize;
+use serde_json::Value;
+
+/// 参数位累加器:每次 `push` 返回该值的 `$n` 占位符(同一占位符可在一条 SQL 里复用)。
+#[derive(Default)]
+pub struct Params {
+    inner: Vec<Value>,
+}
+
+impl Params {
+    pub fn push(&mut self, v: Value) -> String {
+        self.inner.push(v);
+        format!("${}", self.inner.len())
+    }
+
+    /// 关键字模糊过滤;`None`/去空白后为空 ⇒ 不加谓词。
+    pub fn push_like(&mut self, raw: Option<&str>) -> Option<String> {
+        let kw = raw.map(str::trim).filter(|s| !s.is_empty())?;
+        Some(self.push(Value::String(format!("%{kw}%"))))
+    }
+
+    /// 精确过滤;`None`/去空白后为空 ⇒ 不加谓词。
+    pub fn push_eq(&mut self, raw: Option<&str>) -> Option<String> {
+        let v = raw.map(str::trim).filter(|s| !s.is_empty())?;
+        Some(self.push(Value::String(v.to_string())))
+    }
+
+    pub fn where_clause(&self, preds: &[String]) -> String {
+        if preds.is_empty() {
+            String::new()
+        } else {
+            format!(" WHERE {}", preds.join(" AND "))
+        }
+    }
+
+    pub fn values(&self) -> &[Value] {
+        &self.inner
+    }
+
+    /// 追加 `LIMIT`/`OFFSET`(分页游标类接口⛔ 用这个,须自带 `AND` 谓词续写)。
+    pub fn push_page(&mut self, pg: &PageQuery) -> (String, String) {
+        (self.push(Value::from(pg.limit())), self.push(Value::from(pg.offset())))
+    }
+}
+
+#[derive(Deserialize)]
+struct CountRow {
+    #[serde(deserialize_with = "de::as_string")]
+    c: String,
+}
+
+/// `COUNT(1)` 总数。`from_where` = `FROM …`+可选 `WHERE …`。
+pub async fn total(db: &UdsClient, from_where: &str, params: &[Value]) -> Result<i64, BosError> {
+    let sql = format!("SELECT COUNT(1) AS c {from_where}");
+    match db.query_one::<CountRow>(&sql, params).await? {
+        Some(r) => Ok(r.c.parse().unwrap_or(0)),
+        None => Ok(0),
+    }
+}
+
+/// DB 数值列(`de::as_string` 收进来是字符串)→ JSON 数值;解析不出来回 `null`,⛔ 冒充 0。
+pub fn as_num(s: &str) -> Value {
+    let s = s.trim();
+    if let Ok(i) = s.parse::<i64>() {
+        return Value::from(i);
+    }
+    match s.parse::<f64>() {
+        Ok(v) if v.is_finite() => Value::from(v),
+        _ => Value::Null,
+    }
+}
+
+/// 可空数值列;`None` ⇒ `null`。
+pub fn as_opt_num(s: Option<&str>) -> Value {
+    s.map(as_num).unwrap_or(Value::Null)
+}
+
+#[derive(Deserialize)]
+struct SeqRow {
+    #[serde(deserialize_with = "de::as_string")]
+    v: String,
+}
+
+/// 年度流水发号(`bos_seq_year`,与 `customer`/`import_batch` 的发号器同一张表)。
+///
+/// 三步而非一条 `INSERT … RETURNING`:`/dml/batch@v1` 只回 `affected_rows`(`DmlStatementResult`
+/// ⛔ 没有返回行集),取号值必须回读。⚠️ 也⛔ 写成 `ON CONFLICT … DO UPDATE SET …`——
+/// `qualify()` 认 `UPDATE` 关键字后紧跟的第一个标识符,`DO UPDATE SET` 会被改写成
+/// `DO UPDATE uds.public.SET`=语法错。
+///
+/// 首次发号以**该表现有行数**为基线(dev 种子 ID 是 `P-010`/`CT-0001` 这类手工号,⛔ 从 1 起会撞号)。
+///
+/// `table` 是**标识符**(拼进 `FROM`),只能由调用方传字面量,⛔ 传任何用户输入。
+pub async fn next_seq(
+    db: &UdsClient,
+    kind: &str,
+    table: &str,
+    year: i32,
+) -> Result<i64, BosError> {
+    let y = Value::from(year);
+    let k = Value::String(kind.to_string());
+    let hit = db
+        .dml(
+            "UPDATE bos_seq_year SET last_value = last_value + 1 WHERE year = $1 AND kind = $2",
+            &[y.clone(), k.clone()],
+        )
+        .await?;
+    if hit == 0 {
+        db.dml(
+            &format!(
+                "INSERT INTO bos_seq_year (year, kind, last_value) \
+                 VALUES ($1, $2, (SELECT COUNT(1) FROM {table}))"
+            ),
+            &[y.clone(), k.clone()],
+        )
+        .await?;
+    }
+    let row = db
+        .query_one::<SeqRow>(
+            "SELECT last_value AS v FROM bos_seq_year WHERE year = $1 AND kind = $2",
+            &[y, k],
+        )
+        .await?
+        .filter(|r| !r.v.trim().is_empty())
+        .ok_or_else(|| BosError::internal(format!("发号失败:bos_seq_year 无 year={year} kind={kind}")))
+        .and_then(|r| {
+            r.v.trim()
+                .parse::<i64>()
+                .map_err(|e| BosError::internal(format!("发号值不可解析:{}({e})", r.v)))
+        })?;
+    Ok(row)
+}
+
+/// 手机号列表页掩码(需求§5.4:列表页⛔ 明文手机号)。
+pub fn mask_mobile(m: Option<&str>) -> Option<String> {
+    let m = m.map(str::trim).filter(|s| !s.is_empty())?;
+    let b: Vec<char> = m.chars().collect();
+    if b.len() < 7 {
+        return Some("****".to_string());
+    }
+    let head: String = b[..3].iter().collect();
+    let tail: String = b[b.len() - 4..].iter().collect();
+    Some(format!("{head}****{tail}"))
+}
+
+/// 把 ID 集合摊成 `IN ($a,$b,…)` 谓词;空集 ⇒ `1 = 0`(诚实空态,⛔ 退化成「不过滤」)。
+pub fn push_in(
+    p: &mut Params,
+    col: &str,
+    ids: &[String],
+    cast: &str,
+) -> String {
+    if ids.is_empty() {
+        return "1 = 0".to_string();
+    }
+    let ph: Vec<String> = ids.iter().map(|v| p.push(Value::String(v.clone()))).collect();
+    let cast = if cast.is_empty() { String::new() } else { format!("::{cast}") };
+    format!("{col} IN ({})", ph.iter().map(|s| format!("{s}{cast}")).collect::<Vec<_>>().join(","))
+}
+
+#[derive(Deserialize)]
+struct KeyCount {
+    #[serde(deserialize_with = "de::as_string")]
+    k: String,
+    #[serde(deserialize_with = "de::as_string")]
+    n: String,
+}
+
+/// 按主键集合取「每组条数」(团队人数等),避免在联邦读里做相关子查询。
+pub async fn count_by(
+    db: &UdsClient,
+    table: &str,
+    key_col: &str,
+    ids: &[String],
+) -> Result<std::collections::HashMap<String, i64>, BosError> {
+    let mut out = std::collections::HashMap::new();
+    if ids.is_empty() {
+        return Ok(out);
+    }
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, key_col, ids, "text");
+    let sql = format!(
+        "SELECT {key_col} AS k, COUNT(1) AS n FROM {table} WHERE {in_pred} GROUP BY {key_col}"
+    );
+    for r in db.query_all::<KeyCount>(&sql, p.values()).await? {
+        out.insert(r.k, r.n.parse().unwrap_or(0));
+    }
+    Ok(out)
+}
+
+#[derive(Deserialize)]
+struct KeyPair {
+    #[serde(deserialize_with = "de::as_string")]
+    k: String,
+    #[serde(deserialize_with = "de::as_string")]
+    v: String,
+}
+
+// ══ 区域在册信息 / 主体登录账号 / 负责范围(列表页共用取数)═══════════
+
+use std::collections::{HashMap, HashSet};
+
+/// 区域节点在册信息(`bos_region_meta`=层级唯一真源+业务侧自持路径名,总则§5.3)。
+#[derive(Debug, Clone, Default)]
+pub struct RegionMeta {
+    pub level: Option<String>,
+    pub path_name: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct RegionMetaRow {
+    #[serde(deserialize_with = "de::as_string")]
+    node_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    level: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    path_name: Option<String>,
+}
+
+/// 批量取区域节点在册信息。
+///
+/// ⚠️ 未在册的 `node_id` 不会出现在返回表里 ⇒ 调用方出参须回 `null`(=该节点未建档),
+/// ⛔ 折算成空串或拿 node_id 冒充名称。路径名当前只到**节点 ID 链**(平台 RM ⛔ 向 BOS
+/// 暴露节点中文名,18 册在册),故前端展示名旁须带口径说明。
+pub async fn region_meta_by(db: &UdsClient, node_ids: &[String]) -> Result<HashMap<String, RegionMeta>, BosError> {
+    let mut out = HashMap::new();
+    if node_ids.is_empty() {
+        return Ok(out);
+    }
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, "node_id", node_ids, "text");
+    let sql = format!("SELECT node_id, level, path_name FROM bos_region_meta WHERE {in_pred}");
+    for r in db.query_all::<RegionMetaRow>(&sql, p.values()).await? {
+        out.insert(r.node_id, RegionMeta { level: r.level, path_name: r.path_name });
+    }
+    Ok(out)
+}
+
+/// 主体名下登录账号(列表页「登录账号」列:状态+登录名+手机号)。
+#[derive(Debug, Clone)]
+pub struct SubjectAccount {
+    pub user_id: String,
+    pub username: String,
+    /// 已按需求§5.4 掩码
+    pub mobile: Option<String>,
+    pub status: String,
+    /// 该主体绑定的账号条数(>1=数据异常,前端如实呈现条数)
+    pub account_count: i64,
+}
+
+#[derive(Deserialize)]
+struct SubjectAccountRow {
+    #[serde(deserialize_with = "de::as_string")]
+    subject_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    user_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    username: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    mobile: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    status: Option<String>,
+}
+
+/// 按主体批量取登录账号(`bos_user_binding` + `bos_account_ext` 状态)。
+///
+/// 同主体多行时取 `user_id` 最小的一行(=最早开通的那个)并带 `account_count`,
+/// ⛔ 静默丢弃其余行。主体无账号 ⇒ 表中无键(出参回 `null`=未开通)。
+pub async fn accounts_by_subject(
+    db: &UdsClient,
+    subject_type: &str,
+    subject_ids: &[String],
+) -> Result<HashMap<String, SubjectAccount>, BosError> {
+    let mut out: HashMap<String, SubjectAccount> = HashMap::new();
+    if subject_ids.is_empty() {
+        return Ok(out);
+    }
+    let mut p = Params::default();
+    let t = p.push(Value::String(subject_type.to_string()));
+    let in_pred = push_in(&mut p, "b.subject_id", subject_ids, "text");
+    let sql = format!(
+        "SELECT b.subject_id, b.user_id, b.username, b.mobile, e.status \
+         FROM bos_user_binding b LEFT JOIN bos_account_ext e ON e.user_id = b.user_id \
+         WHERE b.subject_type = {t}::text AND {in_pred} ORDER BY b.subject_id, b.user_id"
+    );
+    for r in db.query_all::<SubjectAccountRow>(&sql, p.values()).await? {
+        let count = out
+            .get(&r.subject_id)
+            .map(|a| a.account_count + 1)
+            .unwrap_or(1);
+        if out.contains_key(&r.subject_id) {
+            if let Some(a) = out.get_mut(&r.subject_id) {
+                a.account_count = count;
+            }
+            continue;
+        }
+        out.insert(
+            r.subject_id,
+            SubjectAccount {
+                user_id: r.user_id,
+                username: r.username,
+                mobile: mask_mobile(r.mobile.as_deref()),
+                status: r.status.unwrap_or_else(|| "none".to_string()),
+                account_count: 1,
+            },
+        );
+    }
+    Ok(out)
+}
+
+/// 负责范围与覆盖客户(`bos_data_scope` + `customer_region_mount` + `dim_node_ancestor`)。
+#[derive(Debug, Clone, Default)]
+pub struct ScopeStat {
+    pub regions: Vec<String>,
+    pub customers: Vec<String>,
+    /// 覆盖客户数(区域子树挂载客户 ∪ 直接多选客户,按客户去重)。
+    /// `None`=范围未配置且「空=不限」不成立 ⇒ 无从计算(出参回 `null`,⛔ 折算成 0)。
+    pub coverage: Option<i64>,
+}
+
+#[derive(Deserialize)]
+struct ScopeRow {
+    #[serde(deserialize_with = "de::as_string")]
+    holder_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    target_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    target_id: String,
+}
+
+#[derive(Deserialize)]
+struct PairRow {
+    #[serde(deserialize_with = "de::as_string")]
+    k: String,
+    #[serde(deserialize_with = "de::as_string")]
+    v: String,
+}
+
+/// 按持有者批量算「负责范围/覆盖客户」。
+///
+/// 区域口径=挂载点所在节点的**整个子树**(`dim_node_ancestor`,⛔ 只算节点自身那一层);
+/// 客户口径=直接多选的客户(须⛔ 未删除)。
+/// `empty_scope_means_all`=空范围按「不限」解释(内置总部团队),此时覆盖客户=全量在册客户。
+pub async fn scope_stats_by(
+    db: &UdsClient,
+    holder_type: &str,
+    holder_ids: &[String],
+    empty_scope_means_all: bool,
+) -> Result<HashMap<String, ScopeStat>, BosError> {
+    let mut out: HashMap<String, ScopeStat> = HashMap::new();
+    if holder_ids.is_empty() {
+        return Ok(out);
+    }
+    for id in holder_ids {
+        out.insert(id.clone(), ScopeStat::default());
+    }
+    let mut p = Params::default();
+    let t = p.push(Value::String(holder_type.to_string()));
+    let in_pred = push_in(&mut p, "holder_id", holder_ids, "text");
+    let sql = format!(
+        "SELECT holder_id, target_type, target_id FROM bos_data_scope \
+         WHERE holder_type = {t}::text AND {in_pred} ORDER BY holder_id, target_type, target_id"
+    );
+    for r in db.query_all::<ScopeRow>(&sql, p.values()).await? {
+        if let Some(s) = out.get_mut(&r.holder_id) {
+            match r.target_type.as_str() {
+                "region" => s.regions.push(r.target_id),
+                "customer" => s.customers.push(r.target_id),
+                _ => {}
+            }
+        }
+    }
+
+    let all_regions: Vec<String> = out
+        .values()
+        .flat_map(|s| s.regions.iter().cloned())
+        .collect::<HashSet<_>>()
+        .into_iter()
+        .collect();
+    let mut coverage: HashMap<String, i64> = HashMap::new();
+    if !all_regions.is_empty() {
+        // ① 子树展开:祖先 → 其后代节点(含自身)。
+        let mut q = Params::default();
+        let in_pred = push_in(&mut q, "ancestor_id", &all_regions, "text");
+        let sql = format!(
+            "SELECT ancestor_id AS k, node_id AS v FROM dim_node_ancestor WHERE {in_pred}"
+        );
+        let mut desc: HashMap<String, Vec<String>> = HashMap::new();
+        for r in db.query_all::<PairRow>(&sql, q.values()).await? {
+            desc.entry(r.k).or_default().push(r.v);
+        }
+        // ② 挂载点 → 当期在册客户(⛔ 已软删客户)。
+        let nodes: Vec<String> = desc.values().flatten().cloned().collect::<HashSet<_>>().into_iter().collect();
+        let mut mounted: HashMap<String, Vec<String>> = HashMap::new();
+        if !nodes.is_empty() {
+            let mut m = Params::default();
+            let in_pred = push_in(&mut m, "m.parent_node_id", &nodes, "text");
+            let sql = format!(
+                "SELECT m.parent_node_id AS k, m.customer_id AS v FROM customer_region_mount m \
+                 JOIN customer c ON c.customer_id = m.customer_id \
+                 WHERE c.deleted_at IS NULL AND {in_pred} \
+                 AND m.customer_id IS NOT NULL ORDER BY 1, 2"
+            );
+            for r in db.query_all::<PairRow>(&sql, m.values()).await? {
+                mounted.entry(r.k).or_default().push(r.v);
+            }
+        }
+        for (id, s) in out.iter() {
+            if s.regions.is_empty() {
+                continue;
+            }
+            let mut set: HashSet<String> = HashSet::new();
+            for n in &s.regions {
+                for d in desc.get(n).map(|v| v.as_slice()).unwrap_or_default() {
+                    for c in mounted.get(d).map(|v| v.as_slice()).unwrap_or_default() {
+                        set.insert(c.clone());
+                    }
+                }
+            }
+            let direct = live_customers(db, &s.customers).await?;
+            set.extend(direct);
+            coverage.insert(id.clone(), set.len() as i64);
+        }
+    }
+    let mut total_all: Option<i64> = None;
+    for (id, s) in out.iter_mut() {
+        if let Some(n) = coverage.get(id) {
+            s.coverage = Some(*n);
+        } else if !s.customers.is_empty() {
+            let direct = live_customers(db, &s.customers).await?;
+            s.coverage = Some(direct.len() as i64);
+        } else if empty_scope_means_all {
+            let n = match total_all {
+                Some(v) => v,
+                None => {
+                    let v = total(db, "FROM customer c WHERE c.deleted_at IS NULL", &[]).await?;
+                    total_all = Some(v);
+                    v
+                }
+            };
+            s.coverage = Some(n);
+        }
+    }
+    Ok(out)
+}
+
+/// 直接多选客户里的「在册(未删除)」子集(⛔ 把已软删客户计入覆盖数)。
+async fn live_customers(db: &UdsClient, ids: &[String]) -> Result<HashSet<String>, BosError> {
+    let mut set = HashSet::new();
+    if ids.is_empty() {
+        return Ok(set);
+    }
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, "customer_id", ids, "text");
+    let sql = format!("SELECT customer_id AS v FROM customer WHERE deleted_at IS NULL AND {in_pred}");
+    #[derive(Deserialize)]
+    struct V {
+        #[serde(deserialize_with = "de::as_string")]
+        v: String,
+    }
+    for r in db.query_all::<V>(&sql, p.values()).await? {
+        set.insert(r.v);
+    }
+    Ok(set)
+}
+
+/// 按主键集合取「每组多值」(团队可承接工单类型等)。
+pub async fn pairs_by(
+    db: &UdsClient,
+    table: &str,
+    key_col: &str,
+    val_col: &str,
+    ids: &[String],
+) -> Result<std::collections::HashMap<String, Vec<String>>, BosError> {
+    let mut out: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
+    if ids.is_empty() {
+        return Ok(out);
+    }
+    let mut p = Params::default();
+    let in_pred = push_in(&mut p, key_col, ids, "text");
+    let sql = format!(
+        "SELECT {key_col} AS k, {val_col} AS v FROM {table} WHERE {in_pred} ORDER BY {key_col}, {val_col}"
+    );
+    for r in db.query_all::<KeyPair>(&sql, p.values()).await? {
+        out.entry(r.k).or_default().push(r.v);
+    }
+    Ok(out)
+}

+ 2 - 0
src/modules/account/src/handlers/mod.rs

@@ -1,4 +1,5 @@
 pub mod activation;
+pub mod audit;
 pub mod auth_ctx;
 pub mod catalog;
 pub mod contract;
@@ -17,3 +18,4 @@ pub mod subscription;
 pub mod account;
 pub mod opsview;
 pub mod jobs;
+pub mod listq;

+ 852 - 18
src/modules/account/src/handlers/operator.rs

@@ -1,40 +1,874 @@
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
+use bos_api::AppState;
+use bos_core::page::PageQuery;
 use bos_core::RoleCode;
 use bos_invariant::i6_operator_province_brand;
+use bos_platform::clients::uds::de;
 use serde::Deserialize;
-use serde_json::json;
+use serde_json::{json, Value};
+
+use super::listq::{accounts_by_subject, count_by, next_seq, region_meta_by, total, Params};
+use bos_core::BosError;
+use bos_core::KltCode;
+use bos_scope::AuthContext;
+use chrono::Local;
+
+/// 品牌值域(dev 列注释 `20261104000001_bos_core_tables.sql:113`)。
+const OPERATOR_BRANDS: [&str; 3] = ["移动", "联通", "电信"];
 
 #[derive(Deserialize)]
 pub struct OperatorUpsert {
+    /// 编辑必填、新建不传(`/operator/update@v1` 与 `/operator/delete@v1` 同用 `operator_id`)。
+    pub operator_id: Option<String>,
     pub name: String,
     pub brand: String,
     pub region_node_id: String,
     pub is_province_node: Option<bool>,
     pub settle_mode: Option<String>,
     pub settle_value: Option<f64>,
+    /// ⚠️ openapi `operator/create@v1` **未声明**这两个字段,但列表口径要显示它们
+    /// (dev 列 `recon_day`/`pay_cycle` 均可空,见同文件:103-104)。此处按列定义接收,
+    /// 契约缺口随本轮登记,⛔ 在 yaml 补齐前把这两列说成「契约内字段」。
+    pub recon_day: Option<i64>,
+    pub pay_cycle: Option<String>,
+}
+
+pub async fn create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<OperatorUpsert>,
+) -> Response {
+    match save(&state, &auth, body, None).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+pub async fn update(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<OperatorUpsert>,
+) -> Response {
+    let id = match body.operator_id.as_deref().map(str::trim) {
+        Some(s) if !s.is_empty() => s.to_string(),
+        _ => return json_err(BosError::bad_params("编辑运营商必须带 operator_id")),
+    };
+    match save(&state, &auth, body, Some(id)).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+/// 分成方式与取值成对校验(设计口径 `KLT-T214`/20074:方式与取值必须同时有或同时无)。
+///
+/// ⚠️ 取值区间按 openapi `operator/create@v1` 的码面:`ratio`=百分数 `0<x≤100`、
+/// `amount`/`per_account` 为分且 `>0`。而 `share_rule.rs` 的比例口径是 `0<x≤1`
+/// ⇒ **两族比例口径不一致**,随本轮登记待裁,⛔ 在这里悄悄统一其中一边。
+pub(super) fn settle_pair(mode: Option<&str>, value: Option<f64>) -> Result<(Option<String>, Option<f64>), BosError> {
+    let bad = |why: &str| {
+        BosError::bad_params(format!("分成方式与取值不匹配(设计口径 KLT-T214/20074):{why}"))
+    };
+    let m = mode.map(str::trim).unwrap_or("").to_string();
+    if m.is_empty() {
+        return match value {
+            Some(_) => Err(bad("给了分成取值却没选分成方式")),
+            None => Ok((None, None)),
+        };
+    }
+    let v = match value {
+        Some(v) => v,
+        None => return Err(bad("选了分成方式却没给分成取值")),
+    };
+    match m.as_str() {
+        "ratio" if v > 0.0 && v <= 100.0 => {}
+        "amount" | "per_account" if v > 0.0 => {}
+        "ratio" => return Err(bad("按比例时取值须满足 0<x≤100")),
+        "amount" | "per_account" => return Err(bad("固定金额/每账号取值须 >0")),
+        other => {
+            return Err(BosError::bad_params(format!(
+                "分成方式只能是 ratio/amount/per_account 或不填,收到「{other}」"
+            )))
+        }
+    }
+    Ok((Some(m), Some(v)))
+}
+
+/// 同区域同名(dev 唯一索引 `uq_operator_region_name` 的显式前置判定,⛔ 靠索引冲突报错兜底)。
+async fn dup_name(
+    state: &AppState,
+    node: &str,
+    norm: &str,
+    exclude: Option<&str>,
+) -> Result<Option<String>, BosError> {
+    // ⚠️ 每条语句单独配 `Params`:`Params` 按 SQL 里出现的顺序累积 bind,多取一个未用到的
+    // 占位符会被 Postgres 判「参数个数与语句不符」⇒ ⛔ 复用同一个 Params 跑多条语句。
+    let mut p = Params::default();
+    let ph1 = p.push(Value::String(node.to_string()));
+    let ph2 = p.push(Value::String(norm.to_string()));
+    let mut sql = format!(
+        "SELECT operator_id FROM operator WHERE region_node_id = {ph1}::text AND name_norm = {ph2}::text"
+    );
+    if let Some(e) = exclude {
+        let ph3 = p.push(Value::String(e.to_string()));
+        sql.push_str(&format!(" AND operator_id <> {ph3}::text"));
+    }
+    sql.push_str(" LIMIT 1");
+    Ok(one_id(state, &sql, p.values(), "operator_id").await?)
+}
+
+/// 同省份×品牌唯一(设计口径 `KLT-T224`/dev 唯一索引 `uq_operator_region_brand`)。
+async fn dup_brand(
+    state: &AppState,
+    node: &str,
+    brand: &str,
+    exclude: Option<&str>,
+) -> Result<Option<String>, BosError> {
+    let mut p = Params::default();
+    let ph1 = p.push(Value::String(node.to_string()));
+    let ph2 = p.push(Value::String(brand.to_string()));
+    let mut sql = format!(
+        "SELECT operator_id FROM operator WHERE region_node_id = {ph1}::text AND brand = {ph2}::text"
+    );
+    if let Some(e) = exclude {
+        let ph3 = p.push(Value::String(e.to_string()));
+        sql.push_str(&format!(" AND operator_id <> {ph3}::text"));
+    }
+    sql.push_str(" LIMIT 1");
+    Ok(one_id(state, &sql, p.values(), "operator_id").await?)
+}
+
+async fn one_id(
+    state: &AppState,
+    sql: &str,
+    params: &[Value],
+    col: &str,
+) -> Result<Option<String>, BosError> {
+    Ok(state
+        .db
+        .query_one::<Value>(sql, params)
+        .await?
+        .and_then(|r| match r.get(col) {
+            Some(Value::String(s)) => Some(s.clone()),
+            Some(v) => Some(v.to_string()),
+            None => None,
+        }))
+}
+
+async fn count_where(state: &AppState, sql: &str, params: &[Value]) -> Result<i64, BosError> {
+    let row = state.db.query_one::<Value>(sql, params).await?;
+    Ok(row
+        .and_then(|r| r.get("n").cloned())
+        .map(|v| match v {
+            Value::Number(n) => n.as_i64().unwrap_or(0),
+            Value::String(s) => s.trim().parse().unwrap_or(0),
+            _ => 0,
+        })
+        .unwrap_or(0))
+}
+
+/// 省级节点校验(设计口径 `KLT-T225`;dev `operator.region_node_id` 列注释:114
+/// 「运营商只能建在省级」)。
+///
+/// 层级真源=业务侧 `bos_region_meta(node_id, level, path_name, synced_at)`(总则§5.3、
+/// 05-数据建模总则:44、U-02 业主定案=层级由业务侧自持、⛔ 由平台 `depth` 推导)。
+/// 本表由迁移 `20261107000005_bos_region_meta.sql` 补建,`level` 值域=`省/市/区县`
+/// ⇒ 判级只读 `level`;节点未定级时⛔ 按 `dim_node_ancestor.depth` 猜、⛔ 放行。
+async fn assert_province(state: &AppState, node: &str) -> Result<(), BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(node.to_string()));
+    let sql = format!(
+        "SELECT level, path_name FROM bos_region_meta WHERE node_id = {ph}::text LIMIT 1"
+    );
+    match state.db.query_one::<Value>(&sql, p.values()).await {
+        Ok(Some(r)) => {
+            let lv = r.get("level").and_then(|v| v.as_str()).unwrap_or("").to_string();
+            let path = r
+                .get("path_name")
+                .and_then(|v| v.as_str())
+                .unwrap_or(node)
+                .to_string();
+            if lv == "省" {
+                Ok(())
+            } else {
+                Err(BosError::klt(
+                    KltCode::T225,
+                    format!("运营商只能建在省级节点:{path}({node})的层级={lv}"),
+                ))
+            }
+        }
+        Ok(None) => Err(BosError::bad_params(format!(
+            "所属区域 {node} 在层级真源 bos_region_meta 无记录 ⇒ 未定级,无法判定是否省级\
+             (⛔ 按 depth 猜,请先在区域建档页定级)"
+        ))),
+        Err(e) => Err(BosError::bad_params(format!(
+            "省级判定无法执行:层级真源 bos_region_meta 不可读(上游错误 {e:?})\
+             ⇒ 既不放行也不按 depth 猜"
+        ))),
+    }
+}
+
+/// 新建/修改共用主体(两路由同构,差异只有"是否限定 operator_id")。
+async fn save(
+    state: &AppState,
+    auth: &AuthContext,
+    body: OperatorUpsert,
+    editing: Option<String>,
+) -> Result<Value, BosError> {
+    // 第 1 册§5.1「仅 admin」:原桩放宽到 `opsMain` 是**放松口径**,此处收紧。
+    auth.require_roles(&[RoleCode::Admin])?;
+    if let Err(e) = i6_operator_province_brand(body.is_province_node.unwrap_or(false)) {
+        return Err(e);
+    }
+    let name = body.name.trim();
+    if name.is_empty() {
+        return Err(BosError::bad_params("运营商名称不能为空"));
+    }
+    if !OPERATOR_BRANDS.contains(&body.brand.as_str()) {
+        return Err(BosError::bad_params(format!(
+            "品牌只能是 {} 之一,收到「{}」",
+            OPERATOR_BRANDS.join("/"),
+            body.brand
+        )));
+    }
+    if let Some(d) = body.recon_day {
+        if !(1..=28).contains(&d) {
+            return Err(BosError::bad_params(format!("对账日只能是 1–28(空=跟随默认),收到 {d}")));
+        }
+    }
+    let node = body.region_node_id.trim();
+    if node.is_empty() {
+        return Err(BosError::bad_params("所属区域不能为空"));
+    }
+    assert_province(state, node).await?;
+    let (settle_mode, settle_value) = settle_pair(body.settle_mode.as_deref(), body.settle_value)?;
+
+    let norm = name.to_lowercase();
+    let exclude = editing.as_deref();
+    if let Some(dup) = dup_name(state, node, &norm, exclude).await? {
+        return Err(BosError::klt(
+            KltCode::T201,
+            format!("同区域下已存在同名运营商:{name}({dup})"),
+        ));
+    }
+    if let Some(dup) = dup_brand(state, node, &body.brand, exclude).await? {
+        return Err(BosError::klt(
+            KltCode::T224,
+            format!("同省份×品牌只允许一个运营商:{} × {node}({dup})", body.brand),
+        ));
+    }
+
+    let written = match &editing {
+        None => {
+            let year = Local::now()
+                .format("%Y")
+                .to_string()
+                .parse::<i32>()
+                .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))?;
+            let seq = next_seq(state.db.as_ref(), "operator", "operator", year).await?;
+            let operator_id = format!("OP-{seq:02}");
+            let mut p = Params::default();
+            let ph = [
+                p.push(Value::String(operator_id.clone())),
+                p.push(Value::String(body.brand.clone())),
+                p.push(Value::String(node.to_string())),
+                p.push(Value::String(name.to_string())),
+                p.push(Value::String(norm.clone())),
+                p.push(body.recon_day.map(Value::from).unwrap_or(Value::Null)),
+                p.push(body.pay_cycle.clone().map(Value::from).unwrap_or(Value::Null)),
+                // ⚠️ 必须走 `p.push` 登记进 `Params`:直接塞裸 `Value` 会让参数个数与
+                // SQL 里的占位符对不上,Postgres 判「bind 参数个数不符」。
+                p.push(settle_mode.clone().map(Value::from).unwrap_or(Value::Null)),
+                p.push(settle_value.map(Value::from).unwrap_or(Value::Null)),
+            ];
+            let casts = ["text", "text", "text", "text", "text", "int", "text", "text", "numeric"];
+            let values = ph
+                .iter()
+                .zip(casts.iter())
+                .map(|(ph, ty)| format!("{ph}::{ty}"))
+                .collect::<Vec<_>>()
+                .join(", ");
+            let sql = format!(
+                "INSERT INTO operator (operator_id, brand, region_node_id, name, name_norm, \
+                 recon_day, pay_cycle, settle_mode, settle_value) VALUES ({values})"
+            );
+            let affected = state.db.dml(&sql, p.values()).await?;
+            if affected == 0 {
+                return Err(BosError::internal("运营商建档写入未影响任何行"));
+            }
+            operator_id
+        }
+        Some(id) => {
+            // ⚠️ dev `operator` 表**没有 `updated_at` 列**(同文件:97-108)⇒ ⛔ 写审计时刻,
+            // 修改痕迹只能靠 `bos_audit_log`,而 BOS 侧⛔ 审计写入通路。
+            let mut p = Params::default();
+            let ph = [
+                p.push(Value::String(body.brand.clone())),
+                p.push(Value::String(node.to_string())),
+                p.push(Value::String(name.to_string())),
+                p.push(Value::String(norm.clone())),
+                p.push(body.recon_day.map(Value::from).unwrap_or(Value::Null)),
+                p.push(body.pay_cycle.clone().map(Value::from).unwrap_or(Value::Null)),
+                p.push(settle_mode.clone().map(Value::from).unwrap_or(Value::Null)),
+                p.push(settle_value.map(Value::from).unwrap_or(Value::Null)),
+                p.push(Value::String(id.clone())),
+            ];
+            let casts = ["text", "text", "text", "text", "int", "text", "text", "numeric", "text"];
+            let sets = ["brand", "region_node_id", "name", "name_norm", "recon_day", "pay_cycle",
+                        "settle_mode", "settle_value"]
+                .iter()
+                .zip(casts.iter())
+                .map(|(col, ty)| format!("{col} = {}::{ty}", ph[col_idx(col)]))
+                .collect::<Vec<_>>()
+                .join(", ");
+            let sql = format!(
+                "UPDATE operator SET {sets} WHERE operator_id = {}::text",
+                ph[8]
+            );
+            let affected = state.db.dml(&sql, p.values()).await?;
+            if affected == 0 {
+                return Err(BosError::not_found(format!("运营商 {id} 不存在(或已被删除)")));
+            }
+            id.clone()
+        }
+    };
+
+    // 写后回读:⛔ 把请求体原样回显成「成功」,一切出参以库内真值为准。
+    let mut p = Params::default();
+    let ph = p.push(Value::String(written.clone()));
+    let row = state
+        .db
+        .query_one::<Value>(
+            &format!(
+                "SELECT operator_id, brand, region_node_id, name, name_norm, recon_day, \
+                 pay_cycle, settle_mode, settle_value, created_at FROM operator \
+                 WHERE operator_id = {ph}::text"
+            ),
+            p.values(),
+        )
+        .await?
+        .ok_or_else(|| BosError::internal(format!("写入后回读为空:{written}")))?;
+
+    Ok(json!({
+        "operator": row,
+        "mode": match &editing { Some(_) => "update", None => "insert" },
+        "operator_id": written,
+        // 审计写通路未接通(BOS 侧⛔ `INSERT INTO bos_audit_log`)⇒ 机器可读标记。
+        "audit_written": false,
+        "level_verified": true,
+        "message": "已写入 operator 并按主键回读;省级判定已接层级真源 bos_region_meta\
+                    (迁移 20261107000005 补建,11 个节点定级;⚠️ 未定级节点一律拒建);\
+                    修改动作⛔ 落审计流水(BOS 侧无审计写入通路),表内亦无 updated_at 列。",
+    }))
+}
+
+/// `sets` 拼装时取对应占位符下标(列名与 `ph` 前 8 项一一对应)。
+fn col_idx(col: &str) -> usize {
+    ["brand", "region_node_id", "name", "name_norm", "recon_day", "pay_cycle",
+     "settle_mode", "settle_value"]
+        .iter()
+        .position(|c| *c == col)
+        .unwrap_or(0)
+}
+
+#[derive(Deserialize)]
+pub struct OperatorIdBody {
+    pub operator_id: String,
 }
 
-pub async fn create(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<OperatorUpsert>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    if let Err(e) = i6_operator_province_brand(body.is_province_node.unwrap_or(false)) { return json_err(e); }
-    json_ok(json!({ "operator_id": null, "name": body.name, "brand": body.brand, "region_node_id": body.region_node_id }))
+/// 删除前置检查(设计口径:客户挂靠/未对账账单/进行中工单/分成数据/开通记录/当前登录身份)。
+///
+/// ⚠️ dev 骨架内**只有三项可判定**:客户挂靠(`customer`)、分成规则(`share_rule`)、
+/// 当前登录身份(`bos_user_binding`)。未对账账单、进行中工单、分成明细、开停记录四类
+/// **源表不在 dev 29 表内**(`billing_statement*`/`ticket`/`billing_share_line`/开停记录
+/// 均未建,见 18 册登记)⇒ 按「查不出依赖时⛔ 放行删除」的既有纪律**显式拒绝**,
+/// 并把不可判定项如实列在 `unverifiable` 里。
+pub async fn delete(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<OperatorIdBody>,
+) -> Response {
+    match remove(&state, &auth, body.operator_id.trim()).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn update(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<OperatorUpsert>) -> Response {
-    create(RequireAuth(auth), DataBody(body)).await
+
+async fn remove(state: &AppState, auth: &AuthContext, operator_id: &str) -> Result<Value, BosError> {
+    auth.require_roles(&[RoleCode::Admin])?;
+    if operator_id.is_empty() {
+        return Err(BosError::bad_params("必须带 operator_id"));
+    }
+    let mut p = Params::default();
+    let ph = p.push(Value::String(operator_id.to_string()));
+    let exists = state
+        .db
+        .query_one::<Value>(
+            &format!("SELECT operator_id, name, brand, region_node_id FROM operator WHERE operator_id = {ph}::text"),
+            p.values(),
+        )
+        .await?;
+    let target = match exists {
+        Some(t) => t,
+        None => return Err(BosError::not_found(format!("运营商 {operator_id} 不存在"))),
+    };
+
+    let mut p = Params::default();
+    let ph = p.push(Value::String(operator_id.to_string()));
+    let customers = count_where(
+        state,
+        &format!("SELECT COUNT(1) AS n FROM customer WHERE operator_id = {ph}::text"),
+        p.values(),
+    )
+    .await?;
+    let mut p = Params::default();
+    let ph = p.push(Value::String(operator_id.to_string()));
+    let share_rules = count_where(
+        state,
+        &format!(
+            "SELECT COUNT(1) AS n FROM share_rule WHERE holder_type = 'operator' AND holder_id = {ph}::text"
+        ),
+        p.values(),
+    )
+    .await?;
+    let mut p = Params::default();
+    let ph1 = p.push(Value::String(operator_id.to_string()));
+    let ph2 = p.push(Value::String(auth.user_id.clone()));
+    let self_accounts = count_where(
+        state,
+        &format!(
+            "SELECT COUNT(1) AS n FROM bos_user_binding WHERE subject_type = 'operator' \
+             AND subject_id = {ph1}::text AND user_id::text = {ph2}::text"
+        ),
+        p.values(),
+    )
+    .await?;
+
+    let mut blockers: Vec<Value> = Vec::new();
+    if customers > 0 {
+        blockers.push(json!({ "item": "客户挂靠", "count": customers, "verified": true }));
+    }
+    if share_rules > 0 {
+        blockers.push(json!({ "item": "分成规则", "count": share_rules, "verified": true }));
+    }
+    if self_accounts > 0 {
+        blockers.push(json!({
+            "item": "当前登录身份", "count": self_accounts, "verified": true,
+            "note": "设计口径 KLT-T203/20070:不能删除当前登录账号所属主体"
+        }));
+    }
+    let unverifiable = json!([
+        { "item": "未对账账单", "reason": "源表 billing_statement/billing_statement_line 未在 dev 骨架建立" },
+        { "item": "进行中工单", "reason": "源表 ticket 未在 dev 骨架建立" },
+        { "item": "分成明细", "reason": "源表 billing_share_line 未在 dev 骨架建立(share_rule 只是规则、不是明细)" },
+        { "item": "开通/开停记录", "reason": "源表未在 dev 骨架建立" }
+    ]);
+
+    if !blockers.is_empty() {
+        return Err(BosError::bad_params(
+            format!("运营商 {operator_id} 存在依赖数据,不可删除:{}",
+                blockers.iter().map(|b| format!("{}({})", b["item"], b["count"])).collect::<Vec<_>>().join("、")),
+        ));
+    }
+    Ok(json!({
+        "operator_id": operator_id,
+        "target": target,
+        "deleted": false,
+        "verified_checks": [
+            { "item": "客户挂靠", "count": customers },
+            { "item": "分成规则", "count": share_rules },
+            { "item": "当前登录身份", "count": self_accounts }
+        ],
+        "unverifiable_checks": unverifiable,
+        "message": "可判定的三项前置检查均无依赖,但另有四类阻塞项的源表未在 dev 骨架建立 ⇒ \
+                    按「查不出依赖时⛔ 放行删除」的纪律**拒绝删除**(⛔ 用部分检查通过冒充全通过)。\
+                    待 18 册登记的四类源表落地后本接口才会真删除。",
+    }))
 }
-pub async fn delete(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    json_ok(json!({ "deleted": true, "req": body }))
+
+/// 运营商列表(需求§3「运营商管理」逐字:名称/品牌/所属区域/对账日/付款周期/分成方式+取值)。
+#[derive(Deserialize)]
+pub struct OperatorListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub region_node_id: Option<String>,
 }
-pub async fn get_list(RequireAuth(auth): RequireAuth, DataBody(_body): DataBody<serde_json::Value>) -> Response {
-    let _ = auth;
-    json_ok(json!({ "items": [], "total": 0 }))
+
+#[derive(Deserialize)]
+struct OperatorRow {
+    #[serde(deserialize_with = "de::as_string")]
+    operator_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    name: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    brand: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    region_node_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    recon_day: String,
+    #[serde(deserialize_with = "de::as_string")]
+    pay_cycle: String,
+    #[serde(deserialize_with = "de::as_string")]
+    settle_mode: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    settle_value: Option<String>,
 }
-pub async fn recon_account_create(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    json_ok(json!({ "created": true, "password_once": null, "req": body }))
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<OperatorListReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let mut p = Params::default();
+    // `operator` 表无软删列(见 src/migrations/dev/20261104000001_bos_core_tables.sql:97),
+    // 故⛔ 加 `deleted_at IS NULL` 谓词——加了会被 UDS 判 13001 Schema error。
+    let mut preds: Vec<String> = Vec::new();
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        preds.push(format!("(o.name LIKE {k} OR o.brand LIKE {k})"));
+    }
+    if let Some(r) = p.push_eq(body.region_node_id.as_deref()) {
+        preds.push(format!("o.region_node_id = {r}::text"));
+    }
+
+    let from_where = format!("FROM operator o {}", p.where_clause(&preds));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT o.operator_id, o.name, o.brand, o.region_node_id, o.recon_day, o.pay_cycle, \
+         o.settle_mode, o.settle_value FROM operator o {} \
+         ORDER BY o.name LIMIT {lim} OFFSET {off}",
+        p.where_clause(&preds)
+    );
+    let rows = match state.db.query_all::<OperatorRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let ids: Vec<String> = rows.iter().map(|r| r.operator_id.clone()).collect();
+    let counts = match count_by(state.db.as_ref(), "customer", "operator_id", &ids).await {
+        Ok(c) => c,
+        Err(e) => return json_err(e),
+    };
+    // 区域展示名(`bos_region_meta`)+名下对账账号(`bos_user_binding`)——列表页两列的取数。
+    let mut region_ids: Vec<String> = rows.iter().map(|r| r.region_node_id.clone()).collect();
+    region_ids.sort();
+    region_ids.dedup();
+    let regions = match region_meta_by(state.db.as_ref(), &region_ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let accounts = match accounts_by_subject(state.db.as_ref(), "operator", &ids).await {
+        Ok(a) => a,
+        Err(e) => return json_err(e),
+    };
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            let meta = regions.get(r.region_node_id.as_str());
+            let acct = accounts.get(&r.operator_id);
+            json!({
+                "operator_id": r.operator_id,
+                "name": r.name,
+                "brand": r.brand,
+                "region_node_id": r.region_node_id,
+                // ⛔ 编区域中文名:平台 RM ⛔ 节点名读接口,此处只到 `bos_region_meta.path_name`
+                // (现为节点 ID 链),未建档 ⇒ null(18 册在册)。
+                "region_path_name": meta.and_then(|m| m.path_name.clone()),
+                "region_level": meta.and_then(|m| m.level.clone()),
+                "recon_day": r.recon_day,
+                "pay_cycle": r.pay_cycle,
+                "settle_mode": r.settle_mode,
+                "settle_value": r.settle_value,
+                "customer_count": counts.get(&r.operator_id).copied().unwrap_or(0),
+                // 「登录账号」列(原型 acctCell=状态+登录名+手机号):null=尚未开通对账账号。
+                "account": acct.map(|a| json!({
+                    "user_id": a.user_id,
+                    "username": a.username,
+                    "mobile": a.mobile,
+                    "status": a.status,
+                    "account_count": a.account_count
+                })),
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
 }
-pub async fn recon_account_get(RequireAuth(_auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "status": "未发送,线下告知本人", "req": body }))
+
+/// 对账账号开通(OR-06;openapi `operator/recon_account/create@v1`)。
+///
+/// 三步(口径真源=第 1 册§5.1 第 3 条 + `07-业务错误码.md` +平台
+/// `iam-user/user/create@v1` 契约):① 唯一性守卫**先于**平台调用(组织§2.1/并发总则);
+/// ② 平台建 `role_code='operator'` 账号——`scope_type='end_user'`+`scope_id=<本项目>`
+///    +`user_type='end_user'`+`env/stage`(平台 `ensure_end_user_env_stage` 缺一即 `11103`),
+///    初始密码由 BOS 随机生成、`must_change_password=true` 强制首次登录改密;
+/// ③ 落 `bos_user_binding(subject_type='operator', subject_id=<operator_id>)`——
+///    绑的是**运营商**、⛔ 自然人。
+///
+/// ⚠️ 更正(本轮取证):此前在册的「缺 `bos_activation_code` ⇒ 一次性凭证无落点」**不成立**——
+/// 该表名在全部 docs 内 Grep 0 命中,系误记的虚构表名。OR-06 的一次性凭证=**随机初始密码**,
+/// 口径逐字为「初始密码随机仅当次显示,记录只写『未发送,线下告知本人』」⇒ 设计上就
+/// ⛔ 落库(BOS 骨架明令⛔ 口令/会话列,平台 `UserDto` 亦不回显口令)⇒ 本接口⛔ 需要任何码表。
+#[derive(Deserialize)]
+pub struct ReconAccountCreateBody {
+    pub operator_id: String,
+    pub username: String,
+    pub mobile: Option<String>,
+}
+
+/// 初始密码字符集:剔除 `0O1lI` 等易混字符(对账人员要手抄、要在电话里念得清)。
+const PWD_ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
+
+/// 16 位随机初始密码(⛔ 时间戳拼接:走 `rand` 的 CSPRNG)。口令⛔ 入库⛔ 入日志。
+pub(super) fn gen_initial_password() -> String {
+    use rand::Rng;
+    let mut rng = rand::thread_rng();
+    (0..16)
+        .map(|_| PWD_ALPHABET[rng.gen_range(0..PWD_ALPHABET.len())] as char)
+        .collect()
+}
+
+pub async fn recon_account_create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ReconAccountCreateBody>,
+) -> Response {
+    match do_recon_account_create(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_recon_account_create(
+    state: &AppState,
+    auth: &AuthContext,
+    body: ReconAccountCreateBody,
+) -> Result<Value, BosError> {
+    auth.require_roles(&[RoleCode::Admin])?;
+    let operator_id = body.operator_id.trim().to_string();
+    let username = body.username.trim().to_string();
+    let username_norm = username.to_lowercase();
+    let mobile = body
+        .mobile
+        .map(|m| m.trim().to_string())
+        .filter(|m| !m.is_empty());
+    if operator_id.is_empty() {
+        return Err(BosError::bad_params(
+            "必须带 operator_id(对账账号绑运营商,⛔ 绑自然人)",
+        ));
+    }
+    if username_norm.len() < 4 || username_norm.len() > 32 {
+        return Err(BosError::bad_params(format!(
+            "对账账号登录名去空白后长度须为 4–32 个字符,收到「{username}」"
+        )));
+    }
+    if let Some(m) = &mobile {
+        if m.len() != 11 || !m.chars().all(|c| c.is_ascii_digit()) {
+            return Err(BosError::bad_params(format!("手机号须为 11 位数字,收到「{m}」")));
+        }
+    }
+
+    // 运营商必须存在。OR-06 未给这档专门的错误码 ⇒ 以 11103 返回并在文案点名。
+    let mut p = Params::default();
+    let ph = p.push(Value::String(operator_id.clone()));
+    let operator_name = one_id(
+        state,
+        &format!("SELECT name FROM operator WHERE operator_id = {ph}::text"),
+        p.values(),
+        "name",
+    )
+    .await?
+    .ok_or_else(|| BosError::bad_params(format!("运营商 {operator_id} 不存在,无从开通对账账号")))?;
+
+    // OR-06:一家运营商至多一个对账账号(dev 骨架⛔ 该部分唯一索引 ⇒ 先查,缺口已登记 18 册)。
+    let mut p = Params::default();
+    let ph = p.push(Value::String(operator_id.clone()));
+    let owned = count_where(
+        state,
+        &format!(
+            "SELECT COUNT(1) AS n FROM bos_user_binding \
+             WHERE subject_type = 'operator' AND subject_id = {ph}::text"
+        ),
+        p.values(),
+    )
+    .await?;
+    if owned > 0 {
+        return Err(BosError::bad_params(format!(
+            "运营商 {operator_name} 已有 {owned} 个对账账号(OR-06:一家运营商至多一个)"
+        )));
+    }
+
+    // 唯一性守卫先于平台调用:命中即 KLT-B001/KLT-B002(组织§2.1;DB 侧另有
+    // `uq_bos_user_binding_username_norm`、`uq_bos_user_binding_mobile` 两条唯一索引兜底)。
+    // ⚠️ 平台 `user/create` 只按「当前作用域」判重 ⇒ 全站唯一必须由 BOS 兜底。
+    let mut p = Params::default();
+    let ph = p.push(Value::String(username_norm.clone()));
+    if count_where(
+        state,
+        &format!("SELECT COUNT(1) AS n FROM bos_user_binding WHERE username_norm = {ph}::text"),
+        p.values(),
+    )
+    .await?
+        > 0
+    {
+        return Err(BosError::klt(
+            KltCode::B001,
+            format!("登录名 {username} 已存在(忽略大小写、全站唯一)"),
+        ));
+    }
+    if let Some(m) = &mobile {
+        let mut p = Params::default();
+        let ph = p.push(Value::String(m.clone()));
+        if count_where(
+            state,
+            &format!("SELECT COUNT(1) AS n FROM bos_user_binding WHERE mobile = {ph}::text"),
+            p.values(),
+        )
+        .await?
+            > 0
+        {
+            return Err(BosError::klt(
+                KltCode::B002,
+                format!("手机号 {m} 已被占用(全站唯一)"),
+            ));
+        }
+    }
+
+    // 平台建号。⚠️ 实测两处阻塞(本轮取证,已登记 18 册):① 网关⛔ 注册 `iam-user` 路由
+    //(注册中心内只有 klt-bos 一枚服务)⇒ 走网关报 `10002 路由不存在`;② 绕网关直连
+    // `:3005` 又因 BOS 运行期凭证是 `end_user` 档被判「调用者类型不允许访问该控制面接口」。
+    // 建号失败即整单失败,⛔ 留半成品。
+    let initial_password = gen_initial_password();
+    let created = state
+        .platform
+        .user_create(json!({
+            "scope_type": "end_user",
+            "scope_id": state.project_id,
+            "user_type": "end_user",
+            "env": state.data_env,
+            "stage": state.seoh_env,
+            "username": username,
+            "nickname": format!("{operator_name}·对账"),
+            "phone": mobile.clone().unwrap_or_default(),
+            "password": initial_password,
+            "must_change_password": true,
+        }))
+        .await
+        .map_err(|e| BosError::internal(format!("平台建号未成功,本次⛔ 写任何本地数据:{e}")))?;
+    let user_id = created
+        .pointer("/data/id")
+        .and_then(Value::as_str)
+        .unwrap_or_default()
+        .to_string();
+    if user_id.is_empty() {
+        return Err(BosError::internal(format!(
+            "平台建号应答未回 user_id,本地绑定⛔ 写:{created}"
+        )));
+    }
+
+    // 绑定行落库:subject 指向运营商、⛔ 自然人;口令/凭证⛔ 任何列。
+    let mut p = Params::default();
+    let ph = [
+        p.push(Value::String(user_id.clone())),
+        p.push(Value::String("end_user".to_string())),
+        p.push(Value::String(state.project_id.clone())),
+        p.push(Value::String("operator".to_string())),
+        p.push(Value::String("operator".to_string())),
+        p.push(Value::String(operator_id.clone())),
+        p.push(Value::String(username.clone())),
+        p.push(Value::String(username_norm.clone())),
+        p.push(mobile.clone().map(Value::String).unwrap_or(Value::Null)),
+    ];
+    let sql = format!(
+        "INSERT INTO bos_user_binding (user_id, scope_type, scope_id, role_code, subject_type, \
+         subject_id, username, username_norm, mobile, entry_only) \
+         VALUES ({}::int8, {}::text, {}::text, {}::text, {}::text, {}::text, {}::text, \
+         {}::text, {}::text, FALSE)",
+        ph[0], ph[1], ph[2], ph[3], ph[4], ph[5], ph[6], ph[7], ph[8]
+    );
+    let affected = state.db.dml(&sql, p.values()).await.map_err(|e| {
+        BosError::internal(format!(
+            "平台账号 {user_id} 已建,但本地绑定行写入失败 ⇒ 该账号当前⛔ 能登录本系统,\
+             需人工补绑定:上游错误 {e}"
+        ))
+    })?;
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "平台账号 {user_id} 已建,但绑定行写入影响行数={affected}(期望 1)⇒ 需人工核对"
+        )));
+    }
+
+    Ok(json!({
+        "user_id": user_id,
+        "operator_id": operator_id,
+        "operator_name": operator_name,
+        "username": username,
+        "role_code": "operator",
+        "must_change_password": true,
+        // 一次性凭证:只在本次应答出现,⛔ 入库⛔ 入日志(OR-06 逐字口径)。
+        "initial_password": initial_password,
+        "credential_note": "未发送,线下告知本人",
+        "credential_viewable": false,
+        "note": "初始密码仅在本次应答返回一次,BOS 侧⛔ 存储任何口令;首次登录须先改密。",
+    }))
+}
+
+/// 对账账号查询(第 8 册只读视图):真源=`bos_user_binding` 中
+/// `subject_type='operator' AND subject_id=<operator_id>` 的绑定行。
+pub async fn recon_account_get(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<OperatorIdBody>,
+) -> Response {
+    match recon_accounts(&state, &auth, body.operator_id.trim()).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn recon_accounts(state: &AppState, auth: &AuthContext, operator_id: &str) -> Result<Value, BosError> {
+    auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub, RoleCode::Operator])?;
+    if operator_id.is_empty() {
+        return Err(BosError::bad_params("必须带 operator_id"));
+    }
+    // 运营商自身只能看自己的对账账号(越权用 `S403`,⛔ 回 10000 空集冒充「没有」)。
+    if auth.role == RoleCode::Operator && auth.subject.subject_id != operator_id {
+        return Err(BosError::klt(
+            KltCode::S403,
+            "运营商只能查询自己的对账账号".to_string(),
+        ));
+    }
+    let mut p = Params::default();
+    let ph = p.push(Value::String(operator_id.to_string()));
+    // ⚠️ ⛔ 选 `last_login_at`:该列在 dev 骨架内不存在(`20261104000001_bos_core_tables.sql:3-16`
+    // 的 `bos_user_binding` 只有 user_id/scope_*/role_code/subject_*/username*/mobile/
+    // entry_only/created_at/updated_at)⇒ 上次登录时间在平台侧,BOS 侧无从给出。
+    let sql = format!(
+        "SELECT user_id, username, mobile, role_code, entry_only, updated_at \
+         FROM bos_user_binding WHERE subject_type = 'operator' AND subject_id = {ph}::text \
+         ORDER BY user_id"
+    );
+    let items = state.db.query_all::<Value>(&sql, p.values()).await?;
+    Ok(json!({
+        "operator_id": operator_id,
+        "items": items,
+        "total": items.len(),
+        // 绑定表内⛔ 口令、⛔ 凭证明文(口令在平台侧)⇒ 本接口结构上就给不出凭证。
+        "credential_viewable": false,
+        "message": "行集取自 bos_user_binding(subject_type='operator');⚠️ 本接口只出账号标识,\
+                    ⛔ 出口令/初始凭证——OR-06 的初始密码=随机生成、仅在开通当次应答显示一次,\
+                    设计上就⛔ 落库(绑定表内⛔ 任何口令列),事后无从再取,只能走重置口令;\
+                    total=0 表示该运营商尚未开通对账账号(真值,非查询失败)。",
+    }))
 }

File diff ditekan karena terlalu besar
+ 1555 - 16
src/modules/account/src/handlers/ops_team.rs


+ 1163 - 15
src/modules/account/src/handlers/partner.rs

@@ -1,22 +1,1170 @@
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, KltCode, RoleCode};
+use bos_platform::clients::uds::{de, DmlStatement, DmlStatementResult};
+use bos_scope::{AuthContext, ScopedSelect};
+use chrono::Local;
+use serde::Deserialize;
+use serde_json::{json, Value};
 
-pub async fn create(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    json_ok(json!({ "partner_id": null, "req": body }))
+use super::customer::{cell, count_where, one_row};
+use super::listq::{
+    accounts_by_subject, count_by, mask_mobile, next_seq, push_in, region_meta_by, scope_stats_by, total, Params,
+};
+use super::operator::{gen_initial_password, settle_pair};
+use super::ops_team::AUDIT_NOTE;
+
+/// 时间列在册缺陷:⛔ 可校验、⛔ 可还原 ⇒ 出参如实带出,探针⛔ 对其断言。
+const TIME_NOTE: &str = "dev UDS 对 timestamptz/date 写入静默落 NULL(在册基础设施缺陷)\
+                        ⇒ created_at/updated_at ⛔ 可校验";
+
+/// `bos_data_scope` 的持有者类型(与 `scope_get` 只读口径同源)。
+const HOLDER_PARTNER: &str = "partner";
+
+/// 登录名归一化(`partner.name_norm`/`bos_user_binding.username_norm` 列注释同口径:
+/// 去空白后小写,全站唯一)。
+fn norm(s: &str) -> String {
+    s.trim().to_lowercase()
+}
+
+fn year_now() -> Result<i32, BosError> {
+    Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))
+}
+
+/// 合伙人发号:号段沿用在册种子形态 `PT-<两位序号>`(dev 种子=PT-01/PT-02,⛔ 另起
+/// `PRT-` 前缀造成两套号族)。
+///
+/// ⚠️ `bos_seq_year` 在册只有 `customer`/`import_batch` 两个 kind ⇒ 首次取 `partner` 号时
+/// `next_seq` 以 `COUNT(partner)`(=2)起步,直接拼号必撞 PT-02 ⇒ 与 `issue_customer_id`
+/// 同口径做**有界撞号重试**(序列单调递增 ⇒ 一定停在第一个空号上,⛔ 靠主键冲突报错兜底)。
+async fn issue_partner_id(state: &AppState) -> Result<String, BosError> {
+    let year = year_now()?;
+    for attempt in 1..=500_i32 {
+        let seq = next_seq(state.db.as_ref(), "partner", "partner", year).await?;
+        let candidate = format!("PT-{seq:02}");
+        if partner_meta(state, &candidate).await?.is_none() {
+            return Ok(candidate);
+        }
+        if attempt == 500 {
+            return Err(BosError::internal(format!(
+                "合伙人发号连续 {attempt} 次撞号(年段 {year})⇒ bos_seq_year 计数与既有号段严重错位,\
+                 请人工校正 last_value 后重试"
+            )));
+        }
+    }
+    Err(BosError::internal("合伙人发号未进入循环".to_string()))
+}
+
+/// 逐语句 `affected_rows` 核对:一条未落一行即整单判失败(⛔ 把 `10000` 当成功)。
+fn zeros(results: &[DmlStatementResult], labels: &[String]) -> Vec<String> {
+    results
+        .iter()
+        .filter(|r| r.affected_rows != Some(1))
+        .map(|r| {
+            labels
+                .get(r.index)
+                .cloned()
+                .unwrap_or_else(|| format!("语句 #{}", r.index))
+        })
+        .collect()
+}
+
+/// 合伙人档案(写侧守卫与回读共用;空值归一为 `None`)。
+struct PartnerMeta {
+    partner_id: String,
+    name: String,
+    region_node_id: String,
+    duty_desc: Option<String>,
+    mobile: Option<String>,
+    status: String,
+    settle_mode: Option<String>,
+    settle_value: Option<String>,
+}
+
+async fn partner_meta(state: &AppState, partner_id: &str) -> Result<Option<PartnerMeta>, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(partner_id.to_string()));
+    let sql = format!(
+        "SELECT partner_id, name, region_node_id, duty_desc, mobile, status, settle_mode, \
+         settle_value::text AS settle_value FROM partner WHERE partner_id = {ph}::text LIMIT 1"
+    );
+    Ok(one_row(state, &sql, p.values()).await?.map(|v| PartnerMeta {
+        partner_id: cell(&v, "partner_id").unwrap_or_default(),
+        name: cell(&v, "name").unwrap_or_default(),
+        region_node_id: cell(&v, "region_node_id").unwrap_or_default(),
+        duty_desc: cell(&v, "duty_desc"),
+        mobile: cell(&v, "mobile"),
+        status: cell(&v, "status").unwrap_or_default(),
+        settle_mode: cell(&v, "settle_mode"),
+        settle_value: cell(&v, "settle_value"),
+    }))
+}
+
+/// 档案必须存在(⛔ 把「查不到」折算成「已保存」)。
+async fn need_partner(state: &AppState, partner_id: &str) -> Result<PartnerMeta, BosError> {
+    let t = partner_id.trim();
+    if t.is_empty() {
+        return Err(BosError::bad_params("必须带 partner_id"));
+    }
+    partner_meta(state, t)
+        .await?
+        .ok_or_else(|| BosError::not_found(format!("合伙人 {t} 不存在(partner ⛔ 该行)")))
+}
+
+/// 该合伙人账号的绑定行(`subject_type='partner'` ⇒ `(user_id, username, mobile)`)。
+async fn binding_of(
+    state: &AppState,
+    partner_id: &str,
+) -> Result<Option<(String, String, Option<String>)>, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(partner_id.to_string()));
+    let sql = format!(
+        "SELECT user_id::text AS user_id, username, mobile FROM bos_user_binding \
+         WHERE subject_type = 'partner' AND subject_id = {ph}::text ORDER BY user_id LIMIT 1"
+    );
+    Ok(one_row(state, &sql, p.values()).await?.map(|v| {
+        (
+            cell(&v, "user_id").unwrap_or_default(),
+            cell(&v, "username").unwrap_or_default(),
+            cell(&v, "mobile"),
+        )
+    }))
+}
+
+/// 区域节点在册性(`bos_region_meta`=层级唯一真源,总则§5.3)。
+///
+/// 合伙人⛔ 限省级(组织§5.2:可建在建档区域节点上)⇒ 只判「在册」,⛔ 判级。
+async fn region_node(state: &AppState, node_id: &str) -> Result<Option<(String, String)>, BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(node_id.to_string()));
+    let sql = format!(
+        "SELECT coalesce(level, '') AS level, coalesce(path_name, '') AS path_name \
+         FROM bos_region_meta WHERE node_id = {ph}::text LIMIT 1"
+    );
+    Ok(one_row(state, &sql, p.values()).await?.map(|v| {
+        (
+            cell(&v, "level").unwrap_or_default(),
+            cell(&v, "path_name").unwrap_or_default(),
+        )
+    }))
+}
+
+/// opsMain 的建档区域上界(第 1 册 06-接口清单逐字:`admin`/`opsMain`(**建档区域在本范围**))。
+///
+/// 判据=网关注入的已授权实例 `auth.granted_resource_instances` ∩ 该节点的祖先闭包;
+/// 闭包沿 `bos_region_meta.path_name`(总则§5.3 层级唯一真源,dev 实测存 node_id 路径)展开,
+/// 与 `ops_team::ops_main_check` 的 `dim_node_ancestor` 闭包同语义(两表一致性属在册待裁项)。
+///
+/// ⚠️ 本人**没有**任何已授权实例 ⇒ `Ok(None)`=⛔ 判定,出参如实标 `applied=false`
+/// (⛔ 把「查不到上界」当「通过」,⛔ 静默省略该键)。
+async fn ops_main_bound(state: &AppState, auth: &AuthContext, node: &str) -> Result<Option<String>, BosError> {
+    if auth.granted_resource_instances.is_empty() {
+        return Ok(None);
+    }
+    let ancestors = match region_node(state, node).await? {
+        Some((_, path)) if !path.is_empty() => {
+            let mut v: Vec<String> = path.split('/').map(|s| s.trim().to_string()).collect();
+            v.retain(|s| !s.is_empty());
+            if !v.iter().any(|x| x == node) {
+                v.push(node.to_string());
+            }
+            v
+        }
+        _ => vec![node.to_string()],
+    };
+    let hit: Vec<&String> = ancestors
+        .iter()
+        .filter(|a| auth.granted_resource_instances.iter().any(|g| g == *a))
+        .collect();
+    if hit.is_empty() {
+        return Err(BosError::forbidden_role(format!(
+            "建档区域 {node} 超出你被授权的区域上界(已授权实例={};祖先闭包={})",
+            granted_list(auth),
+            ancestors.join("、")
+        )));
+    }
+    Ok(Some(format!(
+        "建档区域 {node} 命中授权上界 {}(祖先闭包={})",
+        hit.iter().copied().cloned().collect::<Vec<_>>().join("、"),
+        ancestors.join("、")
+    )))
+}
+
+/// 已授权实例清单的展示形态(`granted_resource_instances` 是 `HashSet`⇒ ⛔ `join`,
+/// 排序后拼接以保持报错文案稳定)。
+fn granted_list(auth: &AuthContext) -> String {
+    let mut v: Vec<&String> = auth.granted_resource_instances.iter().collect();
+    v.sort();
+    v.iter().copied().cloned().collect::<Vec<_>>().join("、")
+}
+
+/// 上界判定的 admin 口径:该判定只作用于 opsMain。
+const ADMIN_BOUND_NOTE: &str = "admin ⛔ 受「建档区域在本范围」约束(该判定只作用于 opsMain,\
+                                第 1 册 06-接口清单)⇒ applied=false ⛔ 等于「越界」";
+
+/// 上界判定的出参形态(判定/不可判定都如实带出,⛔ 静默省略)。
+fn scope_check(v: Option<String>) -> Value {
+    match v {
+        Some(e) => json!({"applied": true, "evidence": e}),
+        None => json!({"applied": false,
+                       "reason": "本人无网关注入的区域授权实例(granted_resource_instances 为空)\
+                                  ⇒ opsMain 建档区域上界⛔ 判定,⛔ 当作通过;登 18 册待平台补注入"}),
+    }
+}
+
+/// 名称全站唯一(`uq_partner_name_norm` 的显式前置判定,⛔ 靠索引冲突报错兜底)。
+///
+/// ⚠️ 第 1 册§7.1 **没有**「合伙人名称重复」这一枚错误码(`B001`=登录名已存在、
+/// `B002`=手机号已存在、`T201`=团队名重复,⛔ 挪用)⇒ 落通用参数错误,码位缺口登 18 册。
+async fn dup_name(state: &AppState, name_norm: &str, exclude: Option<&str>) -> Result<Option<String>, BosError> {
+    let mut p = Params::default();
+    let ph1 = p.push(Value::String(name_norm.to_string()));
+    let mut sql = format!("SELECT partner_id FROM partner WHERE name_norm = {ph1}::text");
+    if let Some(e) = exclude {
+        let ph2 = p.push(Value::String(e.to_string()));
+        sql.push_str(&format!(" AND partner_id <> {ph2}::text"));
+    }
+    sql.push_str(" LIMIT 1");
+    Ok(one_row(state, &sql, p.values())
+        .await?
+        .and_then(|v| cell(&v, "partner_id")))
+}
+
+/// 登录名/手机号唯一性守卫(B001→20020、B002→20021;`exclude_user`=改绑时排除自己)。
+async fn account_guard(
+    state: &AppState,
+    username: &str,
+    mobile: Option<&str>,
+    exclude_user: Option<&str>,
+) -> Result<(), BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(norm(username)));
+    let mut pred = format!("username_norm = {ph}::text");
+    if let Some(u) = exclude_user {
+        let e = p.push(Value::String(u.to_string()));
+        pred.push_str(&format!(" AND user_id <> {e}::int8"));
+    }
+    let sql = format!("SELECT COUNT(1) AS n FROM bos_user_binding WHERE {pred}");
+    if count_where(state, &sql, p.values()).await? > 0 {
+        return Err(BosError::klt(KltCode::B001, format!("登录名「{username}」已被占用")));
+    }
+    if let Some(m) = mobile {
+        let mut p = Params::default();
+        let ph = p.push(Value::String(m.to_string()));
+        let mut pred = format!("mobile = {ph}::text");
+        if let Some(u) = exclude_user {
+            let e = p.push(Value::String(u.to_string()));
+            pred.push_str(&format!(" AND user_id <> {e}::int8"));
+        }
+        let sql = format!("SELECT COUNT(1) AS n FROM bos_user_binding WHERE {pred}");
+        if count_where(state, &sql, p.values()).await? > 0 {
+            return Err(BosError::klt(KltCode::B002, format!("手机号 {m} 已被占用")));
+        }
+    }
+    Ok(())
+}
+
+/// 分成方式/取值:成对校验(`KLT-T214`/20074)+**仅 admin 可写**(openapi
+/// `partner/create@v1`/`update@v1` 逐字「仅 admin 可写」)。
+///
+/// `opsMain` 传了分成字段=越权写 ⇒ 显式拒绝(⛔ 静默丢弃后当作「按未填保存」)。
+fn settle_guard(
+    auth: &AuthContext,
+    mode: Option<&str>,
+    value: Option<f64>,
+) -> Result<(Option<String>, Option<f64>), BosError> {
+    let filled = mode.map(str::trim).filter(|s| !s.is_empty()).is_some() || value.is_some();
+    if filled && auth.role != RoleCode::Admin {
+        return Err(BosError::forbidden_role(format!(
+            "分成方式/分成取值仅 admin 可写(`partner/create@v1`/`partner/update@v1` 契约逐字),\
+             当前角色={:?} ⇒ ⛔ 保存,未写任何数据",
+            auth.role
+        )));
+    }
+    settle_pair(mode, value)
+}
+
+/// 手机号格式(`bos_user_binding.mobile` 列注释=11 位;`partner.mobile` 同口径)。
+fn check_mobile(raw: Option<&str>) -> Result<Option<String>, BosError> {
+    let m = match raw.map(str::trim).filter(|s| !s.is_empty()) {
+        Some(m) => m.to_string(),
+        None => return Ok(None),
+    };
+    if m.chars().count() != 11 || !m.chars().all(|c| c.is_ascii_digit()) {
+        return Err(BosError::bad_params(format!("手机号须是 11 位纯数字,收到「{m}」")));
+    }
+    Ok(Some(m))
+}
+
+fn check_name(raw: &str) -> Result<String, BosError> {
+    let name = raw.trim().to_string();
+    if name.is_empty() {
+        return Err(BosError::bad_params("合伙人名称不能为空"));
+    }
+    if name.chars().count() > 128 {
+        return Err(BosError::bad_params(format!(
+            "合伙人名称去空白后长度须 ≤128 个字符,收到 {}",
+            name.chars().count()
+        )));
+    }
+    Ok(name)
+}
+
+/// 名称重复的拒绝文案(点名码位缺口,⛔ 挪用 `T201`/`B001`)。
+fn dup_name_err(name: &str, holder: &str) -> BosError {
+    BosError::bad_params(format!(
+        "合伙人名称「{name}」已存在({holder},忽略大小写与首尾空白,全站唯一)。\
+         ⚠️ 第 1 册§7.1 未登记「合伙人名称重复」错误码(B001=登录名占用、B002=手机号占用、\
+         T201=团队名重复,⛔ 挪用)⇒ 本次回通用参数错误,码位缺口登 18 册"
+    ))
+}
+
+// ══ 写侧(组织§5.2 OR-07 建档/删除 · §5.3 OR-08 负责范围)═══════════════
+
+#[derive(Deserialize)]
+pub struct PartnerCreate {
+    pub name: String,
+    pub duty_desc: Option<String>,
+    pub region_node_id: String,
+    pub mobile: Option<String>,
+    /// 契约必填(`partner/create@v1`:登录名=开通账号用)。
+    pub username: String,
+    pub settle_mode: Option<String>,
+    pub settle_value: Option<f64>,
+}
+
+pub async fn create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<PartnerCreate>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) {
+        return json_err(e);
+    }
+    match do_create(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_create(state: &AppState, auth: &AuthContext, body: PartnerCreate) -> Result<Value, BosError> {
+    // ── 守卫:全部先于建号与任何本地写库(⛔ 半成品档案/孤儿平台账号)────
+    let name = check_name(&body.name)?;
+    let name_norm = norm(&name);
+    let (settle_mode, settle_value) = settle_guard(auth, body.settle_mode.as_deref(), body.settle_value)?;
+    let node = body.region_node_id.trim().to_string();
+    if node.is_empty() {
+        return Err(BosError::bad_params("建档区域节点不能为空"));
+    }
+    let (level, path) = region_node(state, &node).await?.ok_or_else(|| {
+        BosError::bad_params(format!(
+            "区域节点 {node} ⛔ bos_region_meta 在册(层级唯一真源,总则§5.3)⇒ ⛔ 建档;\
+             请先同步该节点或改选在册节点"
+        ))
+    })?;
+    // 建档区域上界:该判定只作用于 opsMain(admin ⛔ 受「建档区域在本范围」约束)。
+    let is_admin = auth.role == RoleCode::Admin;
+    let main_check = if is_admin {
+        None
+    } else {
+        ops_main_bound(state, auth, &node).await?
+    };
+    if let Some(holder) = dup_name(state, &name_norm, None).await? {
+        return Err(dup_name_err(&name, &holder));
+    }
+    let duty_desc = body.duty_desc.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(ToString::to_string);
+    let mobile = check_mobile(body.mobile.as_deref())?;
+    let username = body.username.trim().to_string();
+    if username.is_empty() {
+        return Err(BosError::bad_params("登录名不能为空(契约必填,用于同步开通合伙人账号)"));
+    }
+    if username.chars().count() > 64 {
+        return Err(BosError::bad_params(format!(
+            "登录名去空白后长度须 ≤64 个字符(bos_user_binding.username),收到 {}",
+            username.chars().count()
+        )));
+    }
+    account_guard(state, &username, mobile.as_deref(), None).await?;
+
+    // ── 平台建号(先建号,⛔ 本地写半成品;失败即整单⛔ 落库)───────────
+    let initial_password = gen_initial_password();
+    let created = state
+        .platform
+        .user_create(json!({
+            "scope_type": "end_user",
+            "scope_id": state.project_id.clone(),
+            "project_id": state.project_id.clone(),
+            "user_type": "end_user",
+            "env": state.data_env.clone(),
+            "stage": state.seoh_env.clone(),
+            "username": username.clone(),
+            "password": initial_password.clone(),
+            "nickname": name.clone(),
+            "phone": mobile.clone().unwrap_or_default()
+        }))
+        .await
+        .map_err(|e| BosError::internal(format!("合伙人账号建号未成功,本次⛔ 写任何本地数据:{e}")))?;
+    let user_id = created
+        .pointer("/data/id")
+        .and_then(Value::as_str)
+        .unwrap_or_default()
+        .to_string();
+    if user_id.is_empty() {
+        return Err(BosError::internal(format!("平台建号应答未回 user_id,本地⛔ 写:{created}")));
+    }
+
+    // ── 发号(`bos_seq_year` 原子取号,年份=服务器本地年)────────────────
+    let partner_id = issue_partner_id(state).await?;
+
+    // ── 本地单批原子落库:档案+账号绑定行 ──────────────────────────────
+    let stmts = vec![
+        DmlStatement::new(
+            "INSERT INTO partner (partner_id, name, name_norm, duty_desc, region_node_id, mobile, \
+             status, settle_mode, settle_value) \
+             VALUES ($1::text, $2::text, $3::text, $4::text, $5::text, $6::text, 'active', $7::text, $8::numeric)",
+            vec![
+                Value::String(partner_id.clone()),
+                Value::String(name.clone()),
+                Value::String(name_norm.clone()),
+                duty_desc.map(Value::String).unwrap_or(Value::Null),
+                Value::String(node.clone()),
+                mobile.clone().map(Value::String).unwrap_or(Value::Null),
+                settle_mode.clone().map(Value::String).unwrap_or(Value::Null),
+                settle_value.map(|v| Value::String(v.to_string())).unwrap_or(Value::Null),
+            ],
+        ),
+        DmlStatement::new(
+            "INSERT INTO bos_user_binding (user_id, scope_type, scope_id, role_code, subject_type, \
+             subject_id, username, username_norm, mobile, entry_only) \
+             VALUES ($1::int8, $2::text, $3::text, $4::text, $5::text, $6::text, $7::text, $8::text, $9::text, FALSE)",
+            vec![
+                Value::String(user_id.clone()),
+                Value::String("end_user".to_string()),
+                Value::String(state.project_id.clone()),
+                Value::String("partner".to_string()),
+                Value::String(HOLDER_PARTNER.to_string()),
+                Value::String(partner_id.clone()),
+                Value::String(username.clone()),
+                Value::String(norm(&username)),
+                mobile.clone().map(Value::String).unwrap_or(Value::Null),
+            ],
+        ),
+    ];
+    let labels = vec!["partner 建档".to_string(), "bos_user_binding 账号绑定行".to_string()];
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad = zeros(&results, &labels);
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "建档批内语句未落库:{}(语句 affected_rows ⛔ 1)",
+            bad.join("、")
+        )));
+    }
+
+    // ── 回读库内真值(⛔ 回显请求体)────────────────────────────────────
+    let meta = partner_meta(state, &partner_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("建档后回读 partner 失败:{partner_id}")))?;
+    Ok(json!({
+        "partner_id": meta.partner_id,
+        "name": meta.name,
+        "duty_desc": meta.duty_desc,
+        "region_node_id": meta.region_node_id,
+        "region_level": level,
+        "region_path_name": path,
+        "ops_main_scope_check": if is_admin {
+            json!({"applied": false, "reason": ADMIN_BOUND_NOTE})
+        } else {
+            scope_check(main_check)
+        },
+        "mobile": mask_mobile(meta.mobile.as_deref()),
+        "status": meta.status,
+        "settle_mode": meta.settle_mode,
+        "settle_value": meta.settle_value,
+        "settle_requested": json!({"settle_mode": settle_mode, "settle_value": settle_value}),
+        "settle_value_note": "回读=库内真值:dev UDS 对 numeric 写入存在静默落 NULL 的在册缺陷\
+                              ⇒ 与 settle_requested 不一致即未落库,⛔ 当作已配置",
+        "account": {
+            "created": true,
+            "user_id": user_id,
+            "username": username,
+            "role_code": "partner",
+            "platform_role_note": "业务角色只落本地 bos_user_binding.role_code(本系统判权真源);\
+             平台 iam_user.create 无角色授予入参 ⇒ 平台侧角色未授",
+            "must_change_password": true,
+            "initial_password": initial_password,
+            "credential_note": "未发送,线下告知本人",
+            "credential_viewable": false
+        },
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+#[derive(Deserialize)]
+pub struct PartnerUpdate {
+    pub partner_id: String,
+    pub name: String,
+    pub duty_desc: Option<String>,
+    pub region_node_id: String,
+    pub mobile: Option<String>,
+    /// 登录名⛔ 变更(`partner/update@v1` 逐字):传了就必须与库内绑定行一致,否则拒。
+    pub username: Option<String>,
+    pub settle_mode: Option<String>,
+    pub settle_value: Option<f64>,
+    pub row_version: Option<i64>,
+}
+
+pub async fn update(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<PartnerUpdate>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) {
+        return json_err(e);
+    }
+    match do_update(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_update(state: &AppState, auth: &AuthContext, body: PartnerUpdate) -> Result<Value, BosError> {
+    let meta = need_partner(state, &body.partner_id).await?;
+    let partner_id = meta.partner_id.clone();
+    let name = check_name(&body.name)?;
+    let name_norm = norm(&name);
+    let (settle_mode, settle_value) = settle_guard(auth, body.settle_mode.as_deref(), body.settle_value)?;
+    let node = body.region_node_id.trim().to_string();
+    if node.is_empty() {
+        return Err(BosError::bad_params("建档区域节点不能为空"));
+    }
+    let (level, path) = region_node(state, &node).await?.ok_or_else(|| {
+        BosError::bad_params(format!(
+            "区域节点 {node} ⛔ bos_region_meta 在册(层级唯一真源,总则§5.3)⇒ ⛔ 保存"
+        ))
+    })?;
+    // 建档区域上界(同 create:只作用于 opsMain)。
+    let is_admin = auth.role == RoleCode::Admin;
+    let main_check = if is_admin {
+        None
+    } else {
+        ops_main_bound(state, auth, &node).await?
+    };
+    if let Some(holder) = dup_name(state, &name_norm, Some(&partner_id)).await? {
+        return Err(dup_name_err(&name, &holder));
+    }
+    let duty_desc = body.duty_desc.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(ToString::to_string);
+    let mobile = check_mobile(body.mobile.as_deref())?;
+
+    // 登录名⛔ 变更:传了且与库内不一致=拒;未传=不动。
+    let binding = binding_of(state, &partner_id).await?;
+    if let Some(u) = body.username.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        match &binding {
+            Some((_, saved, _)) if norm(u) != norm(saved) => {
+                return Err(BosError::bad_params(format!(
+                    "登录名⛔ 变更(`partner/update@v1` 逐字「登录名不可改」):库内={saved},收到={u}"
+                )))
+            }
+            Some(_) => {}
+            None => {
+                return Err(BosError::bad_params(format!(
+                    "带了 username 却查不到该合伙人的账号绑定行(bos_user_binding ⛔ subject_type='partner' \
+                     & subject_id={partner_id})⇒ ⛔ 保存,⛔ 凭空新建绑定行"
+                )))
+            }
+        }
+    }
+    // 手机号同时是绑定行的全站唯一列 ⇒ 改了就要重新守卫(排除自己)。
+    if let Some(m) = &mobile {
+        let changed = binding
+            .as_ref()
+            .map(|(_, _, bm)| bm.as_deref() != Some(m.as_str()))
+            .unwrap_or(false);
+        if changed {
+            let username_now = binding.as_ref().map(|b| b.1.clone()).unwrap_or_default();
+            let user_now = binding.as_ref().map(|b| b.0.as_str());
+            account_guard(state, &username_now, Some(m), user_now).await?;
+        }
+    }
+
+    let mut stmts = vec![DmlStatement::new(
+        "UPDATE partner SET name = $2::text, name_norm = $3::text, duty_desc = $4::text, \
+         region_node_id = $5::text, mobile = $6::text, settle_mode = $7::text, \
+         settle_value = $8::numeric WHERE partner_id = $1::text",
+        vec![
+            Value::String(partner_id.clone()),
+            Value::String(name.clone()),
+            Value::String(name_norm.clone()),
+            duty_desc.map(Value::String).unwrap_or(Value::Null),
+            Value::String(node.clone()),
+            mobile.clone().map(Value::String).unwrap_or(Value::Null),
+            settle_mode.clone().map(Value::String).unwrap_or(Value::Null),
+            settle_value.map(|v| Value::String(v.to_string())).unwrap_or(Value::Null),
+        ],
+    )];
+    let mut labels = vec!["partner 档案更新".to_string()];
+    if let Some((user_id, _, old_mobile)) = &binding {
+        if mobile != *old_mobile {
+            stmts.push(DmlStatement::new(
+                "UPDATE bos_user_binding SET mobile = $2::text, updated_at = NOW() \
+                 WHERE user_id = $1::int8",
+                vec![
+                    Value::String(user_id.clone()),
+                    mobile.clone().map(Value::String).unwrap_or(Value::Null),
+                ],
+            ));
+            labels.push("bos_user_binding 手机号同步".to_string());
+        }
+    }
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad = zeros(&results, &labels);
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "编辑批内语句未落库:{}(语句 affected_rows ⛔ 1)",
+            bad.join("、")
+        )));
+    }
+
+    let saved = partner_meta(state, &partner_id)
+        .await?
+        .ok_or_else(|| BosError::internal(format!("编辑后回读 partner 失败:{partner_id}")))?;
+    let binding_after = binding_of(state, &partner_id).await?;
+    Ok(json!({
+        "partner_id": saved.partner_id,
+        "name": saved.name,
+        "duty_desc": saved.duty_desc,
+        "region_node_id": saved.region_node_id,
+        "region_level": level,
+        "region_path_name": path,
+        "ops_main_scope_check": if is_admin {
+            json!({"applied": false, "reason": ADMIN_BOUND_NOTE})
+        } else {
+            scope_check(main_check)
+        },
+        "mobile": mask_mobile(saved.mobile.as_deref()),
+        "status": saved.status,
+        "settle_mode": saved.settle_mode,
+        "settle_value": saved.settle_value,
+        "settle_requested": json!({"settle_mode": settle_mode, "settle_value": settle_value}),
+        "username": binding_after.as_ref().map(|(_, u, _)| u.clone()),
+        "form_semantics": "本接口=整档案整体保存:duty_desc/mobile 未传或空串⇒落 NULL(与 \
+                           operator/update@v1 同口径),⛔ 解释成「保持原值」",
+        "platform_sync_note": "账号名称/手机号⛔ 同步到平台:state.platform 只有 user_create/user_get \
+                               通路(⛔ update 接口)⇒ 平台侧 iam_user.nickname/phone 本次未同步,登 18 册",
+        "row_version_note": body.row_version.map(|_| "dev partner ⛔ 版本列 ⇒ 乐观锁未启用,row_version 收下但⛔ 参与判定").unwrap_or("未传 row_version"),
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+#[derive(Deserialize)]
+pub struct PartnerDelete {
+    pub partner_id: String,
+}
+
+pub async fn delete(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<PartnerDelete>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) {
+        return json_err(e);
+    }
+    match do_delete(&state, &auth, &body.partner_id).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+async fn do_delete(state: &AppState, auth: &AuthContext, partner_id: &str) -> Result<Value, BosError> {
+    let meta = need_partner(state, partner_id).await?;
+    let partner_id = meta.partner_id.clone();
+
+    // 可判定依赖(真数)。
+    let customers = count_where(
+        state,
+        "SELECT COUNT(1) AS n FROM customer WHERE partner_id = $1::text AND deleted_at IS NULL",
+        &[Value::String(partner_id.clone())],
+    )
+    .await?;
+    let scopes = count_where(
+        state,
+        "SELECT COUNT(1) AS n FROM bos_data_scope WHERE holder_type = 'partner' AND holder_id = $1::text",
+        &[Value::String(partner_id.clone())],
+    )
+    .await?;
+    let bindings = count_where(
+        state,
+        "SELECT COUNT(1) AS n FROM bos_user_binding WHERE subject_type = 'partner' AND subject_id = $1::text",
+        &[Value::String(partner_id.clone())],
+    )
+    .await?;
+    let mut blockers: Vec<Value> = Vec::new();
+    let mut note = |n: i64, key: &str, text: &str| {
+        if n > 0 {
+            blockers.push(json!({"key": key, "count": n, "message": text}));
+        }
+    };
+    note(customers, "customer", "名下仍有在册客户,须先转移归属(组织§5.2 删除前检查)");
+    note(scopes, "bos_data_scope", "仍有负责范围授权行,须先清空(partner/scope/save@v1)");
+    note(bindings, "bos_user_binding", "合伙人主体仍有账号绑定行,须先注销(平台⛔ 注销通路)");
+    if auth.subject.subject_type == HOLDER_PARTNER && auth.subject.subject_id == partner_id {
+        blockers.push(json!({"key": "self_login", "count": 1,
+                             "message": "不能删除当前登录账号所属合伙人档案"}));
+    }
+    // ⛔ 数源依赖(组织§5.2 删除前检查点名,dev 缺表 ⇒ ⛔ 可判定 ⇒ ⛔ 放行)。
+    // ⚠️ `share_rule.holder_type` 值域=operator/ops_team(列注释逐字「合伙人走档案两列,
+    // 不进本表」)⇒ 合伙人的分成口径落在档案两列,本表⛔ 数源,⛔ 把它当「分成行已判定为空」。
+    let unverifiable = json!([
+        {"key": "billing_share_line",
+         "reason": "账单分成明细属第 3 册,dev ⛔ 建表 ⇒ 「有分成行」⛔ 判定;\
+                    share_rule.holder_type 值域⛔ partner(合伙人分成落档案两列)⇒ 本表⛔ 替代数源"},
+        {"key": "reconcile_batch",
+         "reason": "对账清单属第 4 册,dev ⛔ 建表 ⇒ 「有对账清单」⛔ 判定"}
+    ]);
+    if blockers.is_empty() {
+        return Err(BosError::bad_params(format!(
+            "本次⛔ 删除:可判定依赖为 0,但分成行/账单明细/对账清单⛔ 数源⛔ 可判定(⛔ 把「查不出依赖」\
+             当「没有依赖」)⇒ 显式拒绝。未判定项={}",
+            unverifiable
+                .as_array()
+                .map(|a| a.iter().filter_map(|x| x.get("key").and_then(Value::as_str)).collect::<Vec<_>>().join("、"))
+                .unwrap_or_default()
+        )));
+    }
+    Ok(json!({
+        "partner_id": partner_id,
+        "name": meta.name,
+        "deleted": false,
+        "blockers": blockers,
+        "unverifiable_checks": unverifiable,
+        "note": "存在阻塞项 ⇒ ⛔ 删除(本接口未执行任何写库),逐条消解后重试"
+    }))
+}
+
+/// 合伙人列表(需求§3「合伙人管理」逐字:名称/职责说明/所属区域/联系手机号/
+/// 状态/分成方式+取值,另带名下客户数)。
+///
+/// 列表页手机号一律掩码(需求§5.4:列表页⛔ 明文手机号)。
+#[derive(Deserialize)]
+pub struct PartnerListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub region_node_id: Option<String>,
+    pub status: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct PartnerRow {
+    #[serde(deserialize_with = "de::as_string")]
+    partner_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    name: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    duty_desc: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    region_node_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    mobile: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    settle_mode: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    settle_value: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    created_at: Option<String>,
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<PartnerListReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        preds.push(format!("p.name_norm LIKE {k}"));
+    }
+    if let Some(r) = p.push_eq(body.region_node_id.as_deref()) {
+        preds.push(format!("p.region_node_id = {r}::text"));
+    }
+    if let Some(s) = p.push_eq(body.status.as_deref()) {
+        preds.push(format!("p.status = {s}::text"));
+    }
+
+    let from_where = format!("FROM partner p {}", p.where_clause(&preds));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT p.partner_id, p.name, p.duty_desc, p.region_node_id, p.mobile, p.status, \
+         p.settle_mode, p.settle_value, p.created_at FROM partner p {} \
+         ORDER BY p.name LIMIT {lim} OFFSET {off}",
+        p.where_clause(&preds)
+    );
+    let rows = match state.db.query_all::<PartnerRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let ids: Vec<String> = rows.iter().map(|r| r.partner_id.clone()).collect();
+    let counts = match count_by(state.db.as_ref(), "customer", "partner_id", &ids).await {
+        Ok(c) => c,
+        Err(e) => return json_err(e),
+    };
+    // 建档区域展示名(`bos_region_meta`)+名下登录账号(`bos_user_binding`)+负责范围
+    // (`bos_data_scope`)。范围随列表一起下发,「配置范围」弹窗因此⛔ 另开接口按 id 查他人
+    // ——`partner/scope/get@v1` 设计上只允许查**本人**,admin 越权读他人范围在本域是被禁止的。
+    let mut region_ids: Vec<String> = rows.iter().map(|r| r.region_node_id.clone()).collect();
+    region_ids.sort();
+    region_ids.dedup();
+    let regions = match region_meta_by(state.db.as_ref(), &region_ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let accounts = match accounts_by_subject(state.db.as_ref(), "partner", &ids).await {
+        Ok(a) => a,
+        Err(e) => return json_err(e),
+    };
+    let scopes = match scope_stats_by(state.db.as_ref(), "partner", &ids, false).await {
+        Ok(s) => s,
+        Err(e) => return json_err(e),
+    };
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            let meta = regions.get(r.region_node_id.as_str());
+            let acct = accounts.get(&r.partner_id);
+            let sc = scopes.get(&r.partner_id).cloned().unwrap_or_default();
+            json!({
+                "partner_id": r.partner_id,
+                "name": r.name,
+                "duty_desc": r.duty_desc,
+                "region_node_id": r.region_node_id,
+                // ⛔ 编区域中文名(平台 RM ⛔ 节点名读接口):只到 path_name 的节点 ID 链。
+                "region_path_name": meta.and_then(|m| m.path_name.clone()),
+                "region_level": meta.and_then(|m| m.level.clone()),
+                "mobile": mask_mobile(r.mobile.as_deref()),
+                "status": r.status,
+                "settle_mode": r.settle_mode,
+                "settle_value": r.settle_value,
+                "customer_count": counts.get(&r.partner_id).copied().unwrap_or(0),
+                // 「登录账号」列(原型 acctCell=状态+登录名+手机号):null=⛔ 开通账号。
+                "account": acct.map(|a| json!({
+                    "user_id": a.user_id,
+                    "username": a.username,
+                    "mobile": a.mobile,
+                    "status": a.status,
+                    "account_count": a.account_count
+                })),
+                // 「配置范围」弹窗的回显数据(区域=授权节点,客户=直接多选)。
+                "scope": {
+                    "regions": sc.regions,
+                    "customers": sc.customers,
+                    "coverage_customers": sc.coverage,
+                },
+                "created_at": r.created_at,
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
+}
+
+/// 当前主体的负责范围(`bos_data_scope` 真源)。
+///
+/// GET ⛔ Query 取参(全库无先例),持有者一律由 `auth.subject` 推导。
+pub async fn scope_get(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
+    if auth.subject.subject_type != "partner" {
+        return json_err(bos_core::BosError::bad_params(format!(
+            "本接口只查**当前登录主体自己**的负责范围,而当前主体类型为 `{}`(非 partner);\
+             查看他人/其他主体的负责范围⛔ 走本接口",
+            auth.subject.subject_type
+        )));
+    }
+    let mut p = Params::default();
+    let holder = p.push(Value::String(auth.subject.subject_id.clone()));
+    let sql = format!(
+        "SELECT target_type, target_id FROM bos_data_scope WHERE holder_type = 'partner' \
+         AND holder_id = {holder}::text ORDER BY target_type, target_id"
+    );
+    #[derive(Deserialize)]
+    struct Grant {
+        #[serde(deserialize_with = "de::as_string")]
+        target_type: String,
+        #[serde(deserialize_with = "de::as_string")]
+        target_id: String,
+    }
+    match state.db.query_all::<Grant>(&sql, p.values()).await {
+        Ok(rows) => json_ok(json!({
+            "grants": rows.iter().map(|g| json!({
+                "target_type": g.target_type, "target_id": g.target_id
+            })).collect::<Vec<_>>(),
+            "total": rows.len(),
+        })),
+        Err(e) => json_err(e),
+    }
+}
+
+#[derive(Deserialize)]
+pub struct PartnerScopeSave {
+    pub partner_id: String,
+    pub region_node_ids: Option<Vec<String>>,
+    pub customer_ids: Option<Vec<String>>,
+}
+
+pub async fn scope_save(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<PartnerScopeSave>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) {
+        return json_err(e);
+    }
+    match do_scope_save(&state, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn update(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn delete(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    json_ok(json!({ "deleted": true, "req": body }))
+
+/// 去空白、去空值、保序去重。
+fn dedup(v: &[String]) -> Vec<String> {
+    let mut out: Vec<String> = Vec::new();
+    for x in v {
+        let x = x.trim();
+        if !x.is_empty() && !out.iter().any(|y| y == x) {
+            out.push(x.to_string());
+        }
+    }
+    out
 }
-pub async fn get_list(RequireAuth(_auth): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [], "total": 0 }))
+
+/// 在册性批查(表名由调用方以字面量拼进 SQL ⇒ 返回在册集合)。
+async fn known_ids(
+    state: &AppState,
+    sql: String,
+    params: &[Value],
+    col: &str,
+) -> Result<Vec<String>, BosError> {
+    let rows: Vec<Value> = state.db.query_all::<Value>(&sql, params).await?;
+    Ok(rows.iter().filter_map(|r| cell(r, col)).collect())
 }
-pub async fn scope_get(RequireAuth(_auth): RequireAuth) -> Response { json_ok(json!({ "grants": [] })) }
-pub async fn scope_save(RequireAuth(auth): RequireAuth, DataBody(body): DataBody<serde_json::Value>) -> Response {
-    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    json_ok(json!({ "saved": true, "req": body }))
+
+async fn do_scope_save(state: &AppState, body: PartnerScopeSave) -> Result<Value, BosError> {
+    let meta = need_partner(state, &body.partner_id).await?;
+    let partner_id = meta.partner_id;
+    let want_regions = dedup(body.region_node_ids.as_deref().unwrap_or_default());
+    let want_customers = dedup(body.customer_ids.as_deref().unwrap_or_default());
+
+    // 目标必须在册(⛔ 收下不存在的节点/客户当作「已授权」)。
+    if !want_regions.is_empty() {
+        let mut p = Params::default();
+        // ⚠️ UDS 的 `params` ⛔ 支持数组(实测 `13001: params 仅支持标量`)⇒ 一律展开成
+        // 标量占位符的 `IN (…)`(与 `listq::push_in` 同口径),⛔ 用 `ANY($1::text[])`。
+        let pred = push_in(&mut p, "node_id", &want_regions, "text");
+        let sql = format!("SELECT node_id FROM bos_region_meta WHERE {pred}");
+        let known = known_ids(state, sql, p.values(), "node_id").await?;
+        let miss: Vec<&String> = want_regions.iter().filter(|x| !known.contains(x)).collect();
+        if !miss.is_empty() {
+            return Err(BosError::bad_params(format!(
+                "区域节点 {} ⛔ bos_region_meta 在册(层级唯一真源,总则§5.3)⇒ 整单⛔ 保存(⛔ 部分落库)",
+                miss.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("、")
+            )));
+        }
+    }
+    if !want_customers.is_empty() {
+        let mut p = Params::default();
+        let pred = push_in(&mut p, "customer_id", &want_customers, "text");
+        let sql = format!("SELECT customer_id FROM customer WHERE {pred} AND deleted_at IS NULL");
+        let known = known_ids(state, sql, p.values(), "customer_id").await?;
+        let miss: Vec<&String> = want_customers.iter().filter(|x| !known.contains(x)).collect();
+        if !miss.is_empty() {
+            return Err(BosError::bad_params(format!(
+                "客户主体号 {} ⛔ customer 在册(或已注销)⇒ 整单⛔ 保存(⛔ 部分落库)",
+                miss.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("、")
+            )));
+        }
+    }
+
+    // 现值 ⇒ 差集(整体替换只覆盖 partner 这一族,⛔ 动 ops_team/ops_member 的行)。
+    // ⚠️ 每条语句各配一份 `Params`(复用同一份跑多条语句会被判「参数个数不符」)。
+    let scope_sql = |ph: &str| {
+        format!(
+            "SELECT target_type, target_id FROM bos_data_scope WHERE holder_type = 'partner' \
+             AND holder_id = {ph}::text ORDER BY target_type, target_id"
+        )
+    };
+    let mut p = Params::default();
+    let holder = p.push(Value::String(partner_id.clone()));
+    let cur_sql = scope_sql(&holder.to_string());
+    #[derive(Deserialize)]
+    struct Grant {
+        #[serde(deserialize_with = "de::as_string")]
+        target_type: String,
+        #[serde(deserialize_with = "de::as_string")]
+        target_id: String,
+    }
+    let current: Vec<(String, String)> = state
+        .db
+        .query_all::<Grant>(&cur_sql, p.values())
+        .await?
+        .into_iter()
+        .filter(|g| g.target_type == "region" || g.target_type == "customer")
+        .map(|g| (g.target_type, g.target_id))
+        .collect();
+    let mut want: Vec<(String, String)> = Vec::new();
+    for r in &want_regions {
+        want.push(("region".to_string(), r.clone()));
+    }
+    for c in &want_customers {
+        want.push(("customer".to_string(), c.clone()));
+    }
+    let to_insert: Vec<(String, String)> = want.iter().cloned().filter(|x| !current.contains(x)).collect();
+    let to_delete: Vec<(String, String)> = current.iter().cloned().filter(|x| !want.contains(x)).collect();
+
+    if to_insert.is_empty() && to_delete.is_empty() {
+        return Ok(json!({
+            "partner_id": partner_id,
+            "grants": want.iter().map(|(t, i)| json!({"target_type": t, "target_id": i})).collect::<Vec<_>>(),
+            "region_count": want_regions.len(),
+            "customer_count": want_customers.len(),
+            "total": want.len(),
+            "inserted": 0, "deleted": 0, "unchanged": want.len(),
+            "noop": true,
+            "scope_note": "负责范围⛔ 限建档区域(本接口按在册性校验,层级⛔ 判定);\
+             可见客户口径的交集算法属 U-04 待裁项 ⇒ 本次只落授权行",
+            "audit_written": false,
+            "audit_note": AUDIT_NOTE,
+            "time_note": TIME_NOTE
+        }));
+    }
+
+    // 整体替换:一条 DELETE 清掉本族两类,再逐行 INSERT(⛔「先全删再插入失败」留空集)。
+    let mut stmts = vec![DmlStatement::new(
+        "DELETE FROM bos_data_scope WHERE holder_type = 'partner' AND holder_id = $1::text \
+         AND target_type IN ('region', 'customer')"
+            .to_string(),
+        vec![Value::String(partner_id.clone())],
+    )];
+    let mut labels = vec!["bos_data_scope 清空 partner 族".to_string()];
+    let mut expect_one = vec![false];
+    for (t, i) in &to_insert {
+        stmts.push(DmlStatement::new(
+            "INSERT INTO bos_data_scope (holder_type, holder_id, target_type, target_id) \
+             VALUES ('partner', $1::text, $2::text, $3::text) ON CONFLICT DO NOTHING",
+            vec![
+                Value::String(partner_id.clone()),
+                Value::String(t.clone()),
+                Value::String(i.clone()),
+            ],
+        ));
+        labels.push(format!("{t}={i} 授权行"));
+        expect_one.push(true);
+    }
+    let results = state.db.dml_batch(&stmts).await?;
+    let bad: Vec<String> = results
+        .iter()
+        .filter(|r| match r.index {
+            i if i < expect_one.len() => expect_one[i] && r.affected_rows != Some(1),
+            _ => true,
+        })
+        .map(|r| {
+            labels
+                .get(r.index)
+                .cloned()
+                .unwrap_or_else(|| format!("语句 #{}", r.index))
+        })
+        .collect();
+    if !bad.is_empty() {
+        return Err(BosError::internal(format!(
+            "负责范围保存批内语句未落库:{}(DELETE 允许影响 0 行,INSERT 须各落 1 行)",
+            bad.join("、")
+        )));
+    }
+
+    // 回读真值并与期望比对。
+    let mut p2 = Params::default();
+    let holder2 = p2.push(Value::String(partner_id.clone()));
+    let after: Vec<(String, String)> = state
+        .db
+        .query_all::<Grant>(&scope_sql(&holder2.to_string()), p2.values())
+        .await?
+        .into_iter()
+        .filter(|g| g.target_type == "region" || g.target_type == "customer")
+        .map(|g| (g.target_type, g.target_id))
+        .collect();
+    let mut want_sorted = want.clone();
+    want_sorted.sort();
+    let mut after_sorted = after.clone();
+    after_sorted.sort();
+    Ok(json!({
+        "partner_id": partner_id,
+        "grants": after.iter().map(|(t, i)| json!({"target_type": t, "target_id": i})).collect::<Vec<_>>(),
+        "region_count": after.iter().filter(|(t, _)| t == "region").count(),
+        "customer_count": after.iter().filter(|(t, _)| t == "customer").count(),
+        "total": after.len(),
+        "inserted": to_insert.len(),
+        "deleted": to_delete.len(),
+        "unchanged": want.len() - to_insert.len(),
+        "consistent": want_sorted == after_sorted,
+        "diff_with_requested": if want_sorted == after_sorted {
+            Value::Null
+        } else {
+            json!({
+                "expected": want_sorted.iter().map(|(t, i)| format!("{t}:{i}")).collect::<Vec<_>>(),
+                "actual": after_sorted.iter().map(|(t, i)| format!("{t}:{i}")).collect::<Vec<_>>()
+            })
+        },
+        "scope_note": "负责范围⛔ 限建档区域(本接口按在册性校验,层级⛔ 判定);\
+         可见客户口径的交集算法属 U-04 待裁项 ⇒ 本次只落授权行",
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "time_note": TIME_NOTE
+    }))
+}
+
+/// 供同域其它只读接口复用的「可见客户」谓词。
+pub(crate) async fn customer_scope_pred(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    p: &mut Params,
+    col: &str,
+) -> Result<String, bos_core::BosError> {
+    match auth.role {
+        // 运维侧=全量(与 audit.rs 同口径;⚠️ visible_customer_ids ⛔ All 分支,不能用它判 admin)
+        RoleCode::Admin | RoleCode::OpsMain | RoleCode::OpsSub => Ok("1 = 1".to_string()),
+        RoleCode::TeamLead | RoleCode::Ops => {
+            if auth.subject.subject_type != "ops_team" && auth.subject.subject_type != "ent_team" {
+                return Ok("1 = 0".to_string());
+            }
+            let team = p.push(Value::String(auth.subject.subject_id.clone()));
+            Ok(format!(
+                "EXISTS (SELECT 1 FROM customer_team_belong b WHERE b.customer_id = {col}::text \
+                 AND b.is_current AND b.team_id = {team}::text)"
+            ))
+        }
+        RoleCode::Enterprise | RoleCode::Sub | RoleCode::Partner | RoleCode::Operator => {
+            let ids = state.scope.visible_customer_ids(auth).await?;
+            Ok(push_in(p, col, &ids, "text"))
+        }
+    }
 }

+ 460 - 15
src/modules/account/src/handlers/region.rs

@@ -3,10 +3,15 @@ use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
 use bos_api::AppState;
 use bos_core::RoleCode;
+use bos_platform::clients::uds::de;
 use bos_scope::ScopedSelect;
 use serde::Deserialize;
 use serde_json::{json, Value};
 
+use super::listq::{count_by, push_in, region_meta_by, total, Params};
+use bos_scope::AuthContext;
+use std::collections::{HashMap, HashSet};
+
 #[derive(Deserialize)]
 pub struct RegionCreate {
     pub parent_node_id: Option<String>,
@@ -91,33 +96,473 @@ pub async fn delete(
     }
 }
 
-pub async fn tree(
-    State(state): State<AppState>,
-    RequireAuth(auth): RequireAuth,
-) -> Response {
-    match state.scope.visible_region_node_ids(&auth).await {
-        Ok(ids) => json_ok(json!({ "node_ids": ids, "note": "完整树经资源树取数;此处返回可见节点集合" })),
-        Err(e) => json_err(e),
+/// 层级排序键(`bos_region_meta.level`,dev 值域=`省/市/区县`,见 `ck_bos_region_meta_level`)。
+fn level_rank(level: Option<&str>) -> u8 {
+    match level.map(str::trim) {
+        Some("省") | Some("province") => 0,
+        Some("市") | Some("city") => 1,
+        Some("区县") | Some("district") => 2,
+        _ => 9,
     }
 }
 
+/// 层级中文档名:`bos_region_meta.level` 在 dev 库存的就是中文(`省/市/区县`),
+/// 故原样透出;只兜住英文码(平台侧若改下发码值不至于整列变空)。未知值 ⇒ `null`(⛔ 猜档名)。
+fn level_label(level: Option<&str>) -> Option<&str> {
+    let lv = level.map(str::trim).filter(|s| !s.is_empty())?;
+    Some(match lv {
+        "province" => "省",
+        "city" => "市",
+        "district" => "区县",
+        _ => lv,
+    })
+}
+
+#[derive(Deserialize)]
+struct AncRow {
+    #[serde(deserialize_with = "de::as_string")]
+    node_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    ancestor_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    depth: String,
+}
+
+#[derive(Deserialize)]
+struct GroupCount {
+    #[serde(deserialize_with = "de::as_string")]
+    k: String,
+    #[serde(deserialize_with = "de::as_string")]
+    n: String,
+}
+
+/// 可见区域树(`bos.region.tree@v1`)—— 树形结构、层级与承载量取**本地真表**。
+///
+/// 可见集合仍由 [`ScopedSelect::visible_region_node_ids`] 收窄(授权口径⛔ 在本函数另起一套),
+/// 在此之上补三件真数据,各自来源写清(⛔ 合成一棵"看起来完整"的树):
+///
+/// * **父子结构**=`dim_node_ancestor(node_id, ancestor_id, depth)`——平台资源树几何的本地只读
+///   投影,与 `bos-scope` 授权剪枝同源(组织§1:区域归属的**真源仍是平台资源树**,本表⛔ 真源);
+///   父节点=`depth = 1` 的祖先,取不到 ⇒ 本次可见集合内的根节点(`parent_id = null`)。
+/// * **层级**=`bos_region_meta.level`(层级唯一落地位,总则§5.3;⛔ 由 `depth` 反推)。
+/// * **承载量**=本域各主体表按 `region_node_id` 计数 + `customer_region_mount` 挂载计数。
+///
+/// ⚠️ `path_name`(展示名)当前只到**节点 ID 链**(如 `shp/sh/lg`):平台 RM 只开了
+/// create/rename/delete 三个写接口,⛔ 任何"按 node_id 批量取节点中文名"的读接口
+/// ([resource_metadata.rs](../../../../crates/bos-platform/src/clients/resource_metadata.rs) 逐字留痕),
+/// BOS 侧无从取真中文名 ⇒ ⛔ 编名字,`name_ready: false` 是该边界的机器可读标记。
+/// 已登 [18 册](../../../../../docs/详细设计说明书/00-总则与全局约定/18-未决事项与口径差异登记.md)
+/// 请平台补 RM 读接口,接通后本字段自动变真名。
+pub async fn tree(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
+    tree_inner(state, auth, None).await
+}
+
+#[derive(Deserialize)]
+pub struct SubtreeReq {
+    pub node_id: Option<String>,
+}
+
+/// 区域子树(`bos.region.subtree@v1`)—— 同 [`tree`],另按 `node_id` 收到该节点及其后代。
+///
+/// `node_id` 不在可见范围 ⇒ 回空集合+`restricted` 说明,⛔ 静默降级成"全量树"。
 pub async fn subtree(
     State(state): State<AppState>,
     RequireAuth(auth): RequireAuth,
-    DataBody(body): DataBody<Value>,
+    DataBody(body): DataBody<SubtreeReq>,
 ) -> Response {
-    let _ = body;
-    tree(State(state), RequireAuth(auth)).await
+    let node_id = body.node_id.unwrap_or_default().trim().to_string();
+    if node_id.is_empty() {
+        return tree(State(state), RequireAuth(auth)).await;
+    }
+    tree_inner(state, auth, Some(node_id)).await
 }
 
-pub async fn change_log(RequireAuth(auth): RequireAuth) -> Response {
+async fn tree_inner(state: AppState, auth: AuthContext, root: Option<String>) -> Response {
+    let visible = match state.scope.visible_region_node_ids(&auth).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let mut restricted: Option<String> = None;
+    let ids: Vec<String> = match &root {
+        Some(r) if !visible.iter().any(|n| n == r) => {
+            restricted = Some(format!("节点 {r} 不在当前账号的可见区域范围内(返回空集合)"));
+            Vec::new()
+        }
+        Some(r) => match subtree_nodes(&state, r).await {
+            Ok(set) => {
+                let mut keep: Vec<String> = set.into_iter().filter(|n| visible.iter().any(|v| v == n)).collect();
+                keep.sort();
+                restricted = Some(format!("已按父节点 {r} 收窄到子树(含自身,共 {} 个节点)", keep.len()));
+                keep
+            }
+            Err(e) => return json_err(e),
+        },
+        None => visible.clone(),
+    };
+
+    // ① 父子结构:一次取回可见节点的全部祖先行,父节点=depth=1 的那条。
+    let mut parents: HashMap<String, String> = HashMap::new();
+    if !ids.is_empty() {
+        let mut p = Params::default();
+        let in_pred = push_in(&mut p, "node_id", &ids, "text");
+        let sql = format!("SELECT node_id, ancestor_id, depth::text AS depth FROM dim_node_ancestor WHERE {in_pred}");
+        match state.db.query_all::<AncRow>(&sql, p.values()).await {
+            Ok(rows) => {
+                for r in rows {
+                    if r.depth.trim().parse::<i64>() == Ok(1) {
+                        parents.insert(r.node_id, r.ancestor_id);
+                    }
+                }
+            }
+            Err(e) => return json_err(e),
+        }
+    }
+    // ② 层级/路径名。
+    let meta = match region_meta_by(&state.db, &ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    // ③ 承载量(直接挂在该节点上的主体数;客户另给「含下级」口径)。
+    let mut operators: HashMap<String, i64> = HashMap::new();
+    let mut partners: HashMap<String, i64> = HashMap::new();
+    let mut ops_teams: HashMap<String, i64> = HashMap::new();
+    for (key, table, col) in [
+        ("operators", "operator", "region_node_id"),
+        ("partners", "partner", "region_node_id"),
+        ("ops_teams", "ops_team", "region_node_id"),
+    ] {
+        let target = match key {
+            "operators" => &mut operators,
+            "partners" => &mut partners,
+            _ => &mut ops_teams,
+        };
+        match count_by(&state.db, table, col, &ids).await {
+            Ok(m) => *target = m,
+            Err(e) => return json_err(e),
+        }
+    }
+    let mut direct: HashMap<String, i64> = HashMap::new();
+    let mut subtree: HashMap<String, i64> = HashMap::new();
+    if !ids.is_empty() {
+        let mut p = Params::default();
+        let in_pred = push_in(&mut p, "m.parent_node_id", &ids, "text");
+        let sql = format!(
+            "SELECT m.parent_node_id AS k, COUNT(DISTINCT m.customer_id) AS n FROM customer_region_mount m \
+             JOIN customer c ON c.customer_id = m.customer_id \
+             WHERE c.deleted_at IS NULL AND m.customer_id IS NOT NULL AND {in_pred} GROUP BY 1"
+        );
+        match state.db.query_all::<GroupCount>(&sql, p.values()).await {
+            Ok(rows) => {
+                for r in rows {
+                    if let Ok(n) = r.n.trim().parse::<i64>() {
+                        direct.insert(r.k, n);
+                    }
+                }
+            }
+            Err(e) => return json_err(e),
+        }
+        // 含下级:`dim_node_ancestor` 展开子树后按祖先聚合(同一客户只算一次)。
+        let mut q = Params::default();
+        let in_pred = push_in(&mut q, "a.ancestor_id", &ids, "text");
+        let sql = format!(
+            "SELECT a.ancestor_id AS k, COUNT(DISTINCT m.customer_id) AS n FROM dim_node_ancestor a \
+             JOIN customer_region_mount m ON m.parent_node_id = a.node_id \
+             JOIN customer c ON c.customer_id = m.customer_id \
+             WHERE c.deleted_at IS NULL AND m.customer_id IS NOT NULL AND {in_pred} GROUP BY 1"
+        );
+        match state.db.query_all::<GroupCount>(&sql, q.values()).await {
+            Ok(rows) => {
+                for r in rows {
+                    if let Ok(n) = r.n.trim().parse::<i64>() {
+                        subtree.insert(r.k, n);
+                    }
+                }
+            }
+            Err(e) => return json_err(e),
+        }
+    }
+
+    let mut nodes: Vec<Value> = ids
+        .iter()
+        .map(|id| {
+            let m = meta.get(id);
+            let level = m.and_then(|x| x.level.clone());
+            let path_name = m.and_then(|x| x.path_name.clone());
+            json!({
+                "node_id": id,
+                "parent_id": parents.get(id).cloned(),
+                "path_name": path_name.clone(),
+                "name": path_name,
+                "level": level,
+                "level_label": level_label(level.as_deref()),
+                "counters": {
+                    "operators": operators.get(id).copied().unwrap_or(0),
+                    "partners": partners.get(id).copied().unwrap_or(0),
+                    "ops_teams": ops_teams.get(id).copied().unwrap_or(0),
+                    "customers": direct.get(id).copied().unwrap_or(0),
+                    "customers_in_subtree": subtree.get(id).copied().unwrap_or(0),
+                    "children": parents.values().filter(|p| *p == id).count()
+                }
+            })
+        })
+        .collect();
+    nodes.sort_by(|a, b| {
+        let k = |v: &Value| {
+            (level_rank(v["level"].as_str().map(str::to_string).as_deref()), v["node_id"].as_str().unwrap_or("").to_string())
+        };
+        k(a).cmp(&k(b))
+    });
+
+    let mut note = String::from(
+        "结构取 dim_node_ancestor(资源树几何的本地只读投影),层级取 bos_region_meta;\
+         path_name 现为节点 ID 链——平台 RM ⛔ 向 BOS 暴露节点中文名读接口,⛔ 编名(18 册在册)",
+    );
+    if let Some(r) = restricted {
+        note = format!("{note};{r}");
+    }
+    json_ok(json!({
+        "node_ids": ids,
+        "nodes": nodes,
+        "root": root,
+        "name_ready": false,
+        "name_source": "bos_region_meta.path_name",
+        "note": note
+    }))
+}
+
+/// `root` 及其全部后代节点(`dim_node_ancestor` 正向展开,含 `depth = 0` 的自身行)。
+async fn subtree_nodes(state: &AppState, root: &str) -> Result<HashSet<String>, bos_core::BosError> {
+    let mut p = Params::default();
+    let ph = p.push(Value::String(root.to_string()));
+    let sql = format!("SELECT node_id FROM dim_node_ancestor WHERE ancestor_id = {ph}::text");
+    Ok(state
+        .db
+        .query_all::<NodeRow>(&sql, p.values())
+        .await?
+        .into_iter()
+        .map(|r| r.node_id)
+        .collect())
+}
+
+#[derive(Deserialize)]
+struct NodeRow {
+    #[serde(deserialize_with = "de::as_string")]
+    node_id: String,
+}
+
+/// GET 无请求体(openapi:277 只声明统一信封出参),故取固定窗口而非分页参数。
+const CHANGE_LOG_LIMIT: i64 = 100;
+/// 区域节点在审计表里的资源类型取值(区域建档/改名/删除写的都是这两类)。
+const REGION_RESOURCE_TYPES: [&str; 2] = ["region", "region_node"];
+
+#[derive(Deserialize)]
+struct ChangeRow {
+    /// dev 库该列**全为 NULL**(见本函数文档的 UDS `exec_ddl` 口径),故⛔ `as_string`
+    /// 把 NULL 抹成空串——出参须回 `null` 让调用方看得出「时刻未知」而非「时刻是 0」。
+    #[serde(deserialize_with = "de::as_opt_string")]
+    occurred_at: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    actor_user_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    actor_username: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    action: String,
+    #[serde(deserialize_with = "de::as_string")]
+    resource_type: String,
+    #[serde(deserialize_with = "de::as_string")]
+    resource_id: String,
+    #[serde(default)]
+    before_json: Option<Value>,
+    #[serde(default)]
+    after_json: Option<Value>,
+    #[serde(default)]
+    detail_json: Option<Value>,
+}
+
+/// `jsonb` 经联邦引擎可能回字符串,取值处⛔ 假定单一形态(同 `audit.rs` 的 `cell`)。
+fn cell(v: Option<Value>) -> Value {
+    match v {
+        Some(Value::String(s)) => serde_json::from_str(&s).unwrap_or(Value::String(s)),
+        Some(v) => v,
+        None => Value::Null,
+    }
+}
+
+/// 区域变更流水(仅 `admin`;运营子账号可见节点列表但不可见流水)。
+///
+/// 真源=`bos_audit_log` 中区域类资源的审计行(`before_json`/`after_json` 是变更前后快照)。
+///
+/// ⚠️ **一期现状(2026-11-07 实测更正,诚实呈现)**:
+/// 1. `bos_audit_log` **只有表结构、没有 BOS 侧写入口**(全库⛔ `INSERT INTO bos_audit_log`,
+///    同 [audit.rs](audit.rs) 顶部登记)——dev 库这 11 行是**开发种子**灌进去的示例行,
+///    ⛔ 把它们理解成「BOS 真写出过流水」;出参 `audit_write_ready: false` 就是这条边界的机器可读标记。
+/// 2. **两个时间列在 dev 库全为 NULL**:`SELECT count(*) … WHERE occurred_at IS NULL` 命中全部 11 行。
+///    根因⛔ 在本模块——`20261107000004` 以 `ADD COLUMN … NOT NULL DEFAULT now()` 追加,
+///    但 UDS `/admin/exec_ddl@v1` **静默丢弃 `NOT NULL` 与 `DEFAULT`**(同批 `created_at` 亦全 NULL),
+///    故存量行拿到的是 NULL 而非 `now()`。⇒ 排序实际退化为 `id DESC`;写侧通路接通后,
+///    ⛔ 依赖库默认值填 `occurred_at`,须由 INSERT 显式带值。
+/// 3. 本接口⛔ 编造流水、⛔ 拿平台资源树的变更记录冒充本域流水。
+pub async fn change_log(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin]) {
         return json_err(e);
     }
-    json_ok(json!({ "items": [] }))
+    let mut p = Params::default();
+    let types: Vec<String> = REGION_RESOURCE_TYPES
+        .iter()
+        .map(|t| p.push(Value::String((*t).to_string())))
+        .collect();
+    let pred = format!(
+        "a.resource_type IN ({})",
+        types.iter().map(|s| format!("{s}::text")).collect::<Vec<_>>().join(",")
+    );
+    let from_where = format!(
+        "FROM bos_audit_log a LEFT JOIN bos_user_binding u ON u.user_id = a.actor_user_id \
+         WHERE {pred}"
+    );
+    let total = total(&state.db, &from_where, p.values()).await;
+    // 多取一条判「还有下一页」(GET 无翻页参数 ⇒ 只呈现窗口是否被截断)。
+    let lim = p.push(Value::from(CHANGE_LOG_LIMIT + 1));
+    let sql = format!(
+        "SELECT a.occurred_at, a.actor_user_id, u.username AS actor_username, a.action, \
+                a.resource_type, a.resource_id, a.before_json, a.after_json, a.detail_json \
+         {from_where} ORDER BY a.created_at DESC, a.id DESC LIMIT {lim}::bigint"
+    );
+    let rows = match state.db.query_all::<ChangeRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let total = match total {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let truncated = rows.len() as i64 > CHANGE_LOG_LIMIT;
+    let items: Vec<Value> = rows
+        .into_iter()
+        .take(CHANGE_LOG_LIMIT as usize)
+        .map(|r| {
+            json!({
+                "occurred_at": r.occurred_at,
+                "actor": { "user_id": r.actor_user_id, "username": r.actor_username },
+                "action": r.action,
+                "object": { "type": r.resource_type, "id": r.resource_id },
+                "before": cell(r.before_json),
+                "after": cell(r.after_json),
+                "detail": cell(r.detail_json),
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": total,
+        "window_size": CHANGE_LOG_LIMIT,
+        "truncated": truncated,
+        "audit_write_ready": false,
+        "message": if items.is_empty() {
+            "暂无区域变更流水:BOS 侧审计写入通路尚未接通(`bos_audit_log` 只有表结构、全库无写入点),\
+             本表 0 行=流水通路未接通,不等于「区域从未变更」。"
+        } else {
+            "取自 bos_audit_log 的区域类审计行。⚠️ 该行集含开发种子示例行(BOS 侧⛔ 写入通路),\
+             且 dev 库 occurred_at/created_at 全为 NULL(UDS exec_ddl 丢弃 NOT NULL DEFAULT),\
+             故 occurred_at 回 null、排序退化为 id DESC,⛔ 据此判定变更时刻。"
+        },
+    }))
+}
+
+#[derive(Deserialize)]
+struct OrphanRow {
+    #[serde(deserialize_with = "de::as_string")]
+    mount_request_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    customer_id: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    hierarchy_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    parent_node_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    terminal_state: String,
+    #[serde(deserialize_with = "de::as_string")]
+    created_at: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    cleaned_at: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    local_customer: String,
 }
 
-pub async fn orphans(RequireAuth(auth): RequireAuth) -> Response {
-    let _ = auth;
-    json_ok(json!({ "items": [] }))
+/// 悬空挂载清单(总则§7.3):从 `customer_region_mount` 取**尚未清理完成**的挂载请求,
+/// 并 LEFT JOIN `customer` 标出「本地有没有客户行」——本地无行+树上有节点=悬空。
+///
+/// 可见性(组织§6.1):`admin` 全量;`opsSub` 不可见(谓词落 `1 = 0`);其余主体按
+/// `state.scope.visible_region_node_ids` 收窄到本区域挂载点的请求。
+///
+/// ⚠️ 边界(⛔ 冒充终判):册内 11§C12/C13 要求清理作业**先按 `mount_request_id` 回查平台终态**
+/// 再决定删,本接口是**候选清单**、⛔ 回查平台,故出参 `platform_state_verified: false`。
+pub async fn orphans(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
+    let mut p = Params::default();
+    let scope_pred = if auth.role == RoleCode::Admin {
+        "1 = 1".to_string()
+    } else if auth.role == RoleCode::OpsSub {
+        "1 = 0".to_string()
+    } else {
+        let ids = match state.scope.visible_region_node_ids(&auth).await {
+            Ok(v) => v,
+            Err(e) => return json_err(e),
+        };
+        push_in(&mut p, "m.parent_node_id", &ids, "text")
+    };
+    let preds = vec![
+        "m.cleaned_at IS NULL".to_string(),
+        "m.terminal_state <> 'cleaned'".to_string(),
+        scope_pred,
+    ];
+    let from_where = format!(
+        "FROM customer_region_mount m LEFT JOIN customer c ON c.customer_id = m.customer_id \
+         {}",
+        p.where_clause(&preds)
+    );
+    let total = match total(&state.db, &from_where, p.values()).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let lim = p.push(Value::from(CHANGE_LOG_LIMIT));
+    let sql = format!(
+        "SELECT m.mount_request_id, m.customer_id, m.hierarchy_id, m.parent_node_id, \
+                m.terminal_state, m.created_at, m.cleaned_at, \
+                CASE WHEN c.customer_id IS NULL THEN 0 ELSE 1 END AS local_customer \
+         {from_where} ORDER BY m.created_at DESC, m.mount_request_id LIMIT {lim}::bigint"
+    );
+    let rows = match state.db.query_all::<OrphanRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            json!({
+                "mount_request_id": r.mount_request_id,
+                "customer_id": r.customer_id,
+                "hierarchy_id": r.hierarchy_id,
+                "parent_node_id": r.parent_node_id,
+                "terminal_state": r.terminal_state,
+                "created_at": r.created_at,
+                "cleaned_at": r.cleaned_at,
+                "local_customer_exists": r.local_customer.trim() == "1",
+            })
+        })
+        .collect();
+    let dangling = items
+        .iter()
+        .filter(|v| v["local_customer_exists"] == Value::Bool(false))
+        .count();
+    json_ok(json!({
+        "items": items,
+        "total": total,
+        "dangling_count": dangling,
+        "window_size": CHANGE_LOG_LIMIT,
+        "platform_state_verified": false,
+        "message": format!(
+            "候选清单取自 customer_region_mount 中未清理完成(cleaned_at 为空且终态非 cleaned)的挂载请求;\
+             其中本地无客户行 {dangling} 条=疑似悬空。⚠️ 删除判定须先按 mount_request_id 回查平台终态\
+             (总则§7.3/竞态 C12),本接口⛔ 回查平台,故只作候选。"
+        ),
+    }))
 }

+ 434 - 11
src/modules/account/src/handlers/share_rule.rs

@@ -1,19 +1,442 @@
+//! 分成规则(第 4 册)——只读侧:读三张分成方档案的 `settle_mode`/`settle_value`。
+//!
+//! **真源口径(第 4 册 §2.2,业主 2026-11-04 裁定)**:逐客户分成规则对象已取消,
+//! 分成取值**唯一**来自 `operator`/`ops_team`/`partner` 三张档案的
+//! `settle_mode`/`settle_value` 两列(对分成方名下客户统一生效)。
+//! 因此本接口⛔ 读 dev 库遗留的 `share_rule` 表(`migrations/dev/…bos_core_tables.sql:464`
+//! 属裁定前的历史骨架),改由三张档案并集派生,返回的每一行都是档案里的真值。
+//!
+//! 派生代价(诚实呈现,见返回体 `derived`/`columns_pending`):
+//! * `rule_id` = `"{holder_type}:{holder_id}"` 视图键(档案两列没有独立主键,⛔ 编造 UUID);
+//! * `rule_level` 恒为 `default`(档案级默认层;逐客户层已随对象取消);
+//! * `customer_id`/`remark` 无册内数源 ⇒ `null`;
+//! * 详情四张卡(收入类摘要)宿主在结算域(第 6 册),一期无数源 ⇒ `cards: null`。
+//!
+//! 写侧(2026-11-07 业主裁定):
+//! * `/share_rule/save@v1` = **改分成=改档案**:按 `holder_type` 把 `settle_mode`/`settle_value`
+//!   写回 `operator`/`ops_team`/`partner` 对应档案表,与只读侧**共用同一份 [`HOLDERS`] 口径**;
+//!   写后**回读档案真值**出参(⛔ 把请求体里的值直接回给前端)。两列一起留空=取消分成=未配分成(计 0)。
+//! * `/share_rule/delete@v1` = **显式失败**:分成只是档案的两列属性,⛔ 没有可删的独立对象,
+//!   「删除分成」的唯一出路就是 `save` 传空值把两列清空,故本接口不执行任何写入、⛔ 假装删除成功。
+//!
+//! ⚠️ 遗留问题:按第 4 册 06-接口清单§6.3,这两枚路由按裁定**本不该存在**(写入口应是三个档案
+//! 自己的 `update@v1`)。路由去留需业主裁定后再动 openapi+网关登记,本轮只把语义落到档案上,已登 总则§18.3。
+//!
+//! ⚠️ **可见性缺口(读写同口径,本轮未动其他文件)**:本域读侧对三张档案**整表取数、没有行级收窄**,
+//! 写侧因此也只做到「角色闸(`save`=admin/opsMain 全站角色)+档案行必须在册」,
+//! 未校验「该档案行在当前账号可见范围内」。补这段要先统一三张档案的可见性谓词(涉及其他文件),已登记。
+
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, RoleCode};
+use bos_platform::clients::uds::de;
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+use super::listq::{as_opt_num, pairs_by, Params};
 
-pub async fn save(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
+pub async fn save(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ShareRuleSaveReq>,
+) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain]) { return json_err(e); }
-    json_ok(json!({ "saved": true, "req": b }))
-}
-pub async fn get_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [] }))
+    match do_save(&state, &body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn get(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "rule": b }))
+
+/// 写分成=改档案两列;出参里的 `rule` 是**写后回读**的档案真值,形状与只读侧 `rule_json` 逐字一致。
+async fn do_save(state: &AppState, body: &ShareRuleSaveReq) -> Result<Value, BosError> {
+    let Some((table, id_col, name_col)) = holder_spec(body.holder_type.as_str()) else {
+        return Err(BosError::bad_params(format!(
+            "未知持有方类型:{}(一期分成方仅 operator/ops_team/partner)",
+            body.holder_type
+        )));
+    };
+    let holder_id = body.holder_id.trim();
+    if holder_id.is_empty() {
+        return Err(BosError::bad_params("holder_id 不能为空"));
+    }
+    let (mode, value) = settle_pair(&body.rules)?;
+
+    // 写前先确认档案行在册:只靠 `affected_rows == 0` 分不清「档案不存在」与「写失败」。
+    // 可见性=与只读侧同一口径(三张档案整表在册,本域⛔ 做行级收窄,缺口已在本文件顶部登记)。
+    if archive_rows(state, table, id_col, name_col, None, Some(holder_id))
+        .await?
+        .is_empty()
+    {
+        return Err(BosError::not_found(format!(
+            "分成方档案不存在:{} {holder_id}",
+            body.holder_type
+        )));
+    }
+
+    let mut p = Params::default();
+    // 值一律走参数位(⛔ 拼字面量);清空=写 NULL(⛔ 写 0 表达「取消分成」,第 4 册§5.3)。
+    let mv = p.push(mode.clone().map(Value::String).unwrap_or(Value::Null));
+    let vv = p.push(value.map(Value::from).unwrap_or(Value::Null));
+    let hid = p.push(Value::String(holder_id.to_string()));
+    let sql = format!(
+        "UPDATE {table} SET settle_mode = {mv}::text, settle_value = {vv}::numeric \
+         WHERE {id_col} = {hid}::text"
+    );
+    let affected = state.db.dml(&sql, p.values()).await?;
+    if affected != 1 {
+        return Err(BosError::internal(format!(
+            "分成写档影响行数异常:{} {holder_id} affected_rows={affected}",
+            body.holder_type
+        )));
+    }
+
+    let rows = archive_rows(state, table, id_col, name_col, None, Some(holder_id)).await?;
+    let row = rows.first().ok_or_else(|| {
+        BosError::internal(format!("分成写档后回读档案失败:{} {holder_id}", body.holder_type))
+    })?;
+    let mut st: std::collections::HashMap<String, String> = std::collections::HashMap::new();
+    if body.holder_type == "partner" {
+        st = partner_status(state, &[row.holder_id.clone()]).await?;
+    }
+    let cleared = mode.is_none();
+    Ok(json!({
+        "holder_type": body.holder_type,
+        "holder_id": holder_id,
+        "saved": true,
+        "saved_count": 1,
+        "rule": rule_json(&body.holder_type, row, st.get(&row.holder_id).map(String::as_str)),
+        "source": "archive",
+        "derived": DERIVED,
+        "columns_pending": COLUMNS_PENDING,
+        "message": if cleared {
+            "已取消该分成方的分成:档案 settle_mode/settle_value 两列已清空(=未配分成,计 0)。"
+        } else {
+            "分成已写入该分成方档案的 settle_mode/settle_value 两列(第 4 册 §2.2:取值唯一来自档案)。"
+        },
+    }))
 }
-pub async fn delete(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
+
+/// ⚠️ 本接口**不执行任何写入**:分成规则不是独立对象,而是三张档案上的两列属性,⛔ 没有可删的行。
+/// 取 `KLT-S20008`/`20008`「功能未实现/不支持」(总则§9.2.1)——⛔ 落 `KLT-S20007` 内部错误,
+/// 那会把一个「按设计不支持」的调用报成系统故障、把人引去排障。
+/// 文案换成**成因说明**+出路(指向 `save` 传空值清空两列),⛔ 回显请求体。
+pub async fn delete(RequireAuth(auth): RequireAuth) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin]) { return json_err(e); }
-    json_ok(json!({ "deleted": true, "req": b }))
+    json_err(BosError::not_implemented(
+        "分成规则不是独立对象:分成=分成方档案(operator/ops_team/partner)上的 \
+         settle_mode/settle_value 两列,没有可删除的独立行,本接口不执行任何写入。\
+         要取消某方分成=把这两列一起清空=改用 /share_rule/save@v1(照传 holder_type/holder_id,\
+         rules[0] 的 share_mode 与 share_value 均传 null)=该方「未配分成、计 0」(第 4 册 §2.2,\
+         业主 2026-11-04 裁定)。",
+    ))
+}
+
+const COLUMNS_PENDING: &[&str] = &["customer_id", "customer_name", "remark", "row_version"];
+const DERIVED: &str = "rule_id = \"{holder_type}:{holder_id}\" 视图键;rule_level 恒 default(档案默认层)";
+
+/// (持有方类型,表名,ID 列,名称列)——三张分成方档案。
+const HOLDERS: [(&str, &str, &str, &str); 3] = [
+    ("operator", "operator", "operator_id", "name"),
+    ("ops_team", "ops_team", "team_id", "team_name"),
+    ("partner", "partner", "partner_id", "name"),
+];
+
+#[derive(Deserialize)]
+pub struct ShareRuleListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub holder_type: Option<String>,
+    pub holder_id: Option<String>,
+    pub keyword: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct ShareRuleGetReq {
+    pub holder_type: String,
+    pub holder_id: String,
+}
+
+/// `/share_rule/save@v1` 请求体(字段按 openapi:3717 的 `data`):档案只有一对取值,
+/// 故 `rules` 实际只能表达**一条**(多条时要求取值一致,⛔ 逐条落库)。
+#[derive(Deserialize)]
+pub struct ShareRuleSaveReq {
+    pub holder_type: String,
+    pub holder_id: String,
+    #[serde(default)]
+    pub rules: Vec<ShareRuleSaveRow>,
+}
+
+#[derive(Deserialize)]
+pub struct ShareRuleSaveRow {
+    #[serde(default)]
+    #[allow(dead_code)]
+    pub rule_id: Option<String>,
+    #[serde(default)]
+    pub customer_id: Option<String>,
+    #[serde(default)]
+    pub rule_level: Option<String>,
+    #[serde(default)]
+    pub share_mode: Option<String>,
+    #[serde(default)]
+    pub share_value: Option<f64>,
+    #[serde(default)]
+    pub remark: Option<String>,
+}
+
+/// 分成方式归一到**档案**值域 `ratio`/`amount`/`per_account`(第 4 册 05§5.1 枚举 +
+/// dev 迁移列注释 `20261104000001_bos_core_tables.sql:119`)。
+/// openapi/快照侧同义值按 05§5.4 line 81 的映射折回:`ratio_total→ratio`、`fixed_amount→amount`。
+fn settle_mode_of(raw: Option<&str>) -> Result<Option<String>, BosError> {
+    let Some(m) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
+        return Ok(None);
+    };
+    let norm = match m {
+        "ratio" | "ratio_total" => "ratio",
+        "amount" | "fixed_amount" => "amount",
+        "per_account" => "per_account",
+        other => {
+            return Err(BosError::bad_params(format!(
+                "未知分成方式:{other}(档案 settle_mode 仅 ratio/amount/per_account)"
+            )))
+        }
+    };
+    Ok(Some(norm.to_string()))
+}
+
+/// 空串=未填;返回该键的键名(档案上没有落点的键),全空 ⇒ `None`。
+fn unsupported_rule_key(r: &ShareRuleSaveRow) -> Option<&'static str> {
+    let filled = |s: Option<&String>| s.as_deref().map(|v| v.trim()).is_some_and(|v| !v.is_empty());
+    if filled(r.customer_id.as_ref()) {
+        Some("customer_id(逐客户规则层已取消)")
+    } else if filled(r.rule_level.as_ref()) {
+        Some("rule_level(分层已取消)")
+    } else if filled(r.remark.as_ref()) {
+        Some("remark(档案无此列)")
+    } else {
+        None
+    }
+}
+
+/// 请求体 → 档案两列的目标值;`(None, None)` = **清空两列**(=取消分成,第 4 册§5.3「填 0 表达不了」)。
+fn settle_pair(rules: &[ShareRuleSaveRow]) -> Result<(Option<String>, Option<f64>), BosError> {
+    let Some(first) = rules.first() else {
+        return Err(BosError::bad_params(
+            "rules 不能为空:分成=分成方档案上的 1 对 settle_mode/settle_value,请把目标值写进 rules[0]",
+        ));
+    };
+    if let Some(k) = rules.iter().find_map(unsupported_rule_key) {
+        return Err(BosError::bad_params(format!(
+            "分成只有档案上 1 对取值(第 4 册 §2.2):rules 里的 {k} 在档案上没有落点,不会静默丢弃"
+        )));
+    }
+    for r in &rules[1..] {
+        if r.share_mode.as_deref().map(str::trim) != first.share_mode.as_deref().map(str::trim)
+            || r.share_value != first.share_value
+        {
+            return Err(BosError::bad_params(
+                "档案只有 1 对 settle_mode/settle_value:rules 里的多条取值必须一致(逐客户分层已取消)",
+            ));
+        }
+    }
+    let mode = settle_mode_of(first.share_mode.as_deref())?;
+    match (mode, first.share_value) {
+        (None, None) => Ok((None, None)),
+        (None, Some(_)) => Err(BosError::bad_params(
+            "分成方式与分成取值必须成对:只给 settle_value 无法落库(要么两列一起写,要么一起清空)",
+        )),
+        (Some(m), None) => Err(BosError::bad_params(format!(
+            "分成方式与分成取值必须成对:settle_mode={m} 缺 settle_value"
+        ))),
+        (Some(m), Some(v)) => {
+            if !v.is_finite() {
+                return Err(BosError::bad_params(format!("settle_value 不是有限数值:{v}")));
+            }
+            // 比例:档案存 0–1 小数(第 4 册 05§5.4「取值域 >0 且 ≤1」);金额/按每账号:>0(§5.3 CHECK)。
+            // 单位(金额按分)册内未给可检判据 ⇒ 只判 >0,⛔ 猜单位。
+            let ok = if m == "ratio" { v > 0.0 && v <= 1.0 } else { v > 0.0 };
+            if !ok {
+                let want = if m == "ratio" { "(0,1](档案按小数存,界面百分数在录入侧换算)" } else { ">0" };
+                return Err(BosError::bad_params(format!(
+                    "settle_mode={m} 的 settle_value 须满足 {want},收到 {v}"
+                )));
+            }
+            Ok((Some(m), Some(v)))
+        }
+    }
+}
+
+#[derive(Deserialize)]
+struct HolderRow {
+    #[serde(deserialize_with = "de::as_string")]
+    holder_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    holder_name: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    settle_mode: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    settle_value: Option<String>,
+}
+
+fn holder_spec(holder_type: &str) -> Option<(&'static str, &'static str, &'static str)> {
+    HOLDERS.iter().find(|(t, ..)| *t == holder_type).map(|&(_, t, i, n)| (t, i, n))
+}
+
+/// 单张档案取分成两列;`only_id`=只取某个持有方(详情用)。
+async fn archive_rows(
+    state: &AppState,
+    table: &str,
+    id_col: &str,
+    name_col: &str,
+    keyword: Option<&str>,
+    only_id: Option<&str>,
+) -> Result<Vec<HolderRow>, bos_core::BosError> {
+    let mut p = Params::default();
+    let mut w: Vec<String> = Vec::new();
+    if let Some(k) = p.push_like(keyword) {
+        w.push(format!("{name_col} LIKE {k}"));
+    }
+    if let Some(id) = p.push_eq(only_id) {
+        w.push(format!("{id_col} = {id}::text"));
+    }
+    let sql = format!(
+        "SELECT {id_col} AS holder_id, {name_col} AS holder_name, settle_mode, settle_value \
+         FROM {table} {} ORDER BY {name_col}",
+        p.where_clause(&w)
+    );
+    state.db.query_all::<HolderRow>(&sql, p.values()).await
+}
+
+fn rule_json(holder_type: &str, r: &HolderRow, status: Option<&str>) -> Value {
+    json!({
+        "rule_id": format!("{holder_type}:{}", r.holder_id),
+        "holder_type": holder_type,
+        "holder_id": r.holder_id,
+        "holder_name": r.holder_name,
+        "share_mode": r.settle_mode,
+        "share_value": as_opt_num(r.settle_value.as_deref()),
+        "status": status,
+        "customer_id": null,
+        "customer_name": null,
+        "rule_level": "default",
+        "remark": null,
+        "row_version": null,
+    })
+}
+
+/// `partner` 有 `status` 列,另两张档案没有 ⇒ 只给合伙人补真值,其余回 `null`。
+async fn partner_status(state: &AppState, ids: &[String]) -> Result<std::collections::HashMap<String, String>, bos_core::BosError> {
+    pairs_by(state.db.as_ref(), "partner", "partner_id", "status", ids)
+        .await
+        .map(|m| m.into_iter().filter_map(|(k, v)| v.into_iter().next().map(|s| (k, s))).collect())
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ShareRuleListReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let want = body.holder_type.as_deref().map(str::trim).filter(|s| !s.is_empty());
+    // 未配置分成(两列为空)的档案也是事实,保留为 `share_mode: null`,⛔ 当成「没有规则」丢掉。
+    let mut merged: Vec<Value> = Vec::new();
+    for (ht, table, id_col, name_col) in HOLDERS {
+        if want.is_some_and(|t| t != ht) {
+            continue;
+        }
+        let rows = match archive_rows(&state, table, id_col, name_col, body.keyword.as_deref(), None).await {
+            Ok(r) => r,
+            Err(e) => return json_err(e),
+        };
+        let ids: Vec<String> = rows.iter().map(|r| r.holder_id.clone()).collect();
+        let st = match partner_status(&state, &ids).await {
+            Ok(m) => m,
+            Err(e) => return json_err(e),
+        };
+        merged.extend(rows.iter().map(|r| rule_json(ht, r, st.get(&r.holder_id).map(String::as_str))));
+    }
+    merged.sort_by(|a, b| {
+        let key = |v: &Value| {
+            (
+                v["holder_type"].as_str().unwrap_or_default().to_string(),
+                v["holder_name"].as_str().unwrap_or_default().to_string(),
+            )
+        };
+        key(a).cmp(&key(b))
+    });
+    let total_i = merged.len() as i64;
+    let start = (body.pg.offset().max(0) as usize).min(merged.len());
+    let end = start.saturating_add(body.pg.limit() as usize).min(merged.len());
+    let items: Vec<Value> = merged[start..end].to_vec();
+    json_ok(json!({
+        "items": items,
+        "total": total_i,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+        "source": "archive",
+        "derived": DERIVED,
+        "columns_pending": COLUMNS_PENDING,
+        "message": "分成取值唯一来自 operator/ops_team/partner 三张档案的 settle_mode/settle_value(第 4 册 §2.2);\
+                    dev 库遗留的 share_rule 表已停用,本接口不读它。",
+    }))
+}
+
+pub async fn get(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<ShareRuleGetReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::OpsSub]) {
+        return json_err(e);
+    }
+    let Some((table, id_col, name_col)) = holder_spec(&body.holder_type) else {
+        return json_ok(json!({
+            "holder_type": body.holder_type,
+            "holder_id": body.holder_id,
+            "holder_name": null,
+            "cards": null,
+            "rules": [],
+            "available": false,
+            "message": "未知持有方类型:一期分成方仅 operator/ops_team/partner。",
+        }));
+    };
+    let rows = match archive_rows(
+        &state,
+        table,
+        id_col,
+        name_col,
+        None,
+        Some(body.holder_id.as_str()),
+    )
+    .await
+    {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let ids: Vec<String> = rows.iter().map(|r| r.holder_id.clone()).collect();
+    let st = match partner_status(&state, &ids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let rules: Vec<Value> = rows
+        .iter()
+        .map(|r| rule_json(&body.holder_type, r, st.get(&r.holder_id).map(String::as_str)))
+        .collect();
+    let holder_name = rules.first().and_then(|v| v["holder_name"].as_str()).unwrap_or_default();
+    json_ok(json!({
+        "holder_type": body.holder_type,
+        "holder_id": body.holder_id,
+        "holder_name": if holder_name.is_empty() { Value::Null } else { json!(holder_name) },
+        "rules": rules,
+        "cards": null,
+        "cards_available": false,
+        "cards_message": "四张摘要卡是结算口径(收入×分成),宿主在第 6 册结算域,一期无数据源。",
+        "source": "archive",
+        "derived": DERIVED,
+        "columns_pending": COLUMNS_PENDING,
+    }))
 }

+ 320 - 7
src/modules/account/src/handlers/sub_account.rs

@@ -1,11 +1,324 @@
+use axum::extract::State;
 use axum::response::Response;
-use bos_api::extract::{json_ok, DataBody, RequireAuth};
-use serde_json::json;
+use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_platform::clients::uds::de;
+use serde::Deserialize;
+use serde_json::{json, Value};
 
-pub async fn get_list(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [], "req": b }))
+use bos_core::{BosError, RoleCode};
+use bos_platform::clients::uds::DmlStatement;
+use bos_scope::AuthContext;
+
+use super::customer::{cell, one_row};
+use super::listq::{total, Params};
+use super::ops_team::AUDIT_NOTE;
+use super::partner::customer_scope_pred;
+
+/// 客户下属分账号列表(需求§5「分账号管理」逐字:登录名/使用人/用途/
+/// 网络侧账号名/状态)。
+#[derive(Deserialize)]
+pub struct SubAccountListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub customer_id: Option<String>,
+    pub keyword: Option<String>,
+    pub status: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct SubRow {
+    #[serde(deserialize_with = "de::as_string")]
+    sub_account_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    customer_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    username: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    display_name: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    purpose: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    net_account: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    created_at: Option<String>,
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubAccountListReq>,
+) -> Response {
+    let mut p = Params::default();
+    let mut preds: Vec<String> = Vec::new();
+    match customer_scope_pred(&state, &auth, &mut p, "s.customer_id").await {
+        Ok(pred) => preds.push(pred),
+        Err(e) => return json_err(e),
+    }
+    if let Some(c) = p.push_eq(body.customer_id.as_deref()) {
+        preds.push(format!("s.customer_id = {c}::text"));
+    }
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        preds.push(format!(
+            "(u.username LIKE {k} OR s.display_name LIKE {k} OR s.net_account LIKE {k})"
+        ));
+    }
+    if let Some(s) = p.push_eq(body.status.as_deref()) {
+        preds.push(format!("s.status = {s}::text"));
+    }
+
+    let from_where = format!(
+        "FROM sub_account s LEFT JOIN bos_user_binding u ON u.user_id = s.user_id {}",
+        p.where_clause(&preds)
+    );
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "SELECT s.sub_account_id, s.customer_id, u.username, s.display_name, s.purpose, \
+         s.net_account, s.status, s.created_at FROM sub_account s \
+         LEFT JOIN bos_user_binding u ON u.user_id = s.user_id {} \
+         ORDER BY s.sub_account_id LIMIT {lim} OFFSET {off}",
+        p.where_clause(&preds)
+    );
+    let rows = match state.db.query_all::<SubRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let items: Vec<Value> = rows
+        .into_iter()
+        .map(|r| {
+            json!({
+                "sub_account_id": r.sub_account_id,
+                "customer_id": r.customer_id,
+                "username": r.username,
+                "display_name": r.display_name,
+                "purpose": r.purpose,
+                "net_account": r.net_account,
+                "status": r.status,
+                "created_at": r.created_at,
+            })
+        })
+        .collect();
+    json_ok(json!({
+        "items": items,
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+    }))
+}
+
+/// 分账号资料修改(`bos.sub_account.update@v1`)。
+///
+/// 契约逐字(`openapi.yaml`):**运营侧可改两项**(使用人显示名、网络侧账号名)、
+/// **客户主账号只许改显示名**。⚠️ `purpose`(用途说明)**不在契约可改字段内** ⇒
+/// 本接口⛔ 改该列,传了即拒(⛔ 静默忽略,一字段两义的口径差异登 18 册)。
+#[derive(Deserialize)]
+pub struct SubAccountUpdate {
+    pub sub_account_id: String,
+    pub display_name: Option<String>,
+    pub network_account_name: Option<String>,
+    /// ⛔ 契约字段:在册即拒(⛔ 借本接口改用途说明)。
+    pub purpose: Option<String>,
+}
+
+pub async fn update(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubAccountUpdate>,
+) -> Response {
+    match do_update(&state, &auth, body).await {
+        Ok(v) => json_ok(v),
+        Err(e) => json_err(e),
+    }
+}
+
+/// 分账号档案行。
+struct SubMeta {
+    sub_account_id: String,
+    customer_id: String,
+    display_name: Option<String>,
+    net_account: Option<String>,
+    purpose: Option<String>,
+    status: String,
+}
+
+async fn sub_meta(state: &AppState, id: &str, extra_pred: Option<&str>, p: &mut Params) -> Result<Option<SubMeta>, BosError> {
+    let ph = p.push(Value::String(id.to_string()));
+    let mut pred = format!("s.sub_account_id = {ph}::text");
+    if let Some(x) = extra_pred {
+        pred.push_str(&format!(" AND {x}"));
+    }
+    let sql = format!(
+        "SELECT s.sub_account_id, s.customer_id, s.display_name, s.net_account, s.purpose, s.status \
+         FROM sub_account s WHERE {pred} LIMIT 1"
+    );
+    Ok(one_row(state, &sql, p.values()).await?.map(|v| SubMeta {
+        sub_account_id: cell(&v, "sub_account_id").unwrap_or_default(),
+        customer_id: cell(&v, "customer_id").unwrap_or_default(),
+        display_name: cell(&v, "display_name"),
+        net_account: cell(&v, "net_account"),
+        purpose: cell(&v, "purpose"),
+        status: cell(&v, "status").unwrap_or_default(),
+    }))
 }
-pub async fn update(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    // 仅姓名/用途/网络侧账号名
-    json_ok(json!({ "updated": true, "req": b }))
+
+/// 显示名/网络侧账号名的取值校验(列宽 `VARCHAR(128)`;空串=清空为 NULL)。
+fn field(v: Option<&str>, label: &str) -> Result<Option<Option<String>>, BosError> {
+    let raw = match v {
+        None => return Ok(None),
+        Some(s) => s,
+    };
+    let t = raw.trim();
+    if t.is_empty() {
+        return Ok(Some(None));
+    }
+    if t.chars().count() > 128 {
+        return Err(BosError::bad_params(format!(
+            "{label}去空白后长度须 ≤128 个字符(sub_account 列宽 VARCHAR(128)),收到 {}",
+            t.chars().count()
+        )));
+    }
+    Ok(Some(Some(t.to_string())))
+}
+
+async fn do_update(
+    state: &AppState,
+    auth: &AuthContext,
+    body: SubAccountUpdate,
+) -> Result<Value, BosError> {
+    let id = body.sub_account_id.trim().to_string();
+    if id.is_empty() {
+        return Err(BosError::bad_params("必须带 sub_account_id"));
+    }
+    if body.purpose.is_some() {
+        return Err(BosError::bad_params(
+            "purpose(用途说明)⛔ 本接口的可改字段(`sub_account/update@v1` 契约只列 \
+             display_name/network_account_name)⇒ ⛔ 借本接口改用途,也⛔ 静默忽略入参;\
+             需要改用途请另立契约字段,口径差异登 18 册".to_string(),
+        ));
+    }
+
+    // ── 角色闸:运营侧两项可改,客户主账号只许改显示名,其余角色⛔ 写入口 ──
+    let ops_side = matches!(
+        auth.role,
+        RoleCode::Admin | RoleCode::OpsMain | RoleCode::OpsSub | RoleCode::TeamLead | RoleCode::Ops
+    );
+    let customer_main = auth.role == RoleCode::Enterprise;
+    if !ops_side && !customer_main {
+        return Err(BosError::forbidden_role(format!(
+            "分账号资料修改的写入口只开放给运营侧(可改两项)与客户主账号(只许改使用人显示名),\
+             当前角色 {:?} ⛔ 写入口",
+            auth.role
+        )));
+    }
+
+    let want_display = field(body.display_name.as_deref(), "使用人显示名")?;
+    let want_net = field(body.network_account_name.as_deref(), "网络侧账号名")?;
+    if want_display.is_none() && want_net.is_none() {
+        return Err(BosError::bad_params(
+            "display_name 与 network_account_name 至少要带一项(⛔ 空提交当作「已保存」)".to_string(),
+        ));
+    }
+    if customer_main && want_net.is_some() {
+        return Err(BosError::forbidden_role(
+            "客户主账号只许修改「使用人显示名」⇒ 本次带 network_account_name(网络侧账号名)\
+             属越权写入口(契约逐字),整单⛔ 保存".to_string(),
+        ));
+    }
+
+    // ── 档案在册性(先判存在,再判负责范围;⛔ 把「越界」报成「不存在」)──
+    let meta = match sub_meta(state, &id, None, &mut Params::default()).await? {
+        Some(m) => m,
+        None => {
+            return Err(BosError::not_found(format!(
+                "分账号 {id} 不存在(sub_account ⛔ 该行)⇒ ⛔ 保存"
+            )))
+        }
+    };
+
+    // ── 负责范围守卫(复用只读侧同一个谓词 ⇒ ⛔ 第二套判据)──────────────
+    let mut p = Params::default();
+    let pred = match customer_scope_pred(state, auth, &mut p, "s.customer_id").await {
+        Ok(v) => v,
+        Err(e) => return Err(e),
+    };
+    if sub_meta(state, &id, Some(&pred), &mut p).await?.is_none() {
+        return Err(BosError::forbidden_role(format!(
+            "分账号 {id}(客户 {})不在你的负责范围内(判据=与只读列表同一个可见客户谓词)\
+             ⇒ ⛔ 修改他人名下分账号",
+            meta.customer_id
+        )));
+    }
+
+    // ── 落库(在册列集只有 display_name/net_account 可写;表⛔ updated_at 列)──
+    let before = json!({"display_name": meta.display_name, "net_account": meta.net_account});
+    let mut sets: Vec<String> = Vec::new();
+    let mut params: Vec<Value> = Vec::new();
+    let mut changed: Vec<String> = Vec::new();
+    // 占位符编号一律由 `params.len()` 派生(⛔ 手工计数器:漏一次自增 ⇒ SET 与 WHERE
+    // 撞号,UDS 回 `13001 params 长度须等于最大占位符` ⇒ 两项同改恒 ⛔ 落库)
+    if let Some(v) = &want_display {
+        params.push(v.clone().map(Value::String).unwrap_or(Value::Null));
+        sets.push(format!("display_name = ${}::text", params.len()));
+        changed.push("display_name".to_string());
+    }
+    if let Some(v) = &want_net {
+        params.push(v.clone().map(Value::String).unwrap_or(Value::Null));
+        sets.push(format!("net_account = ${}::text", params.len()));
+        changed.push("net_account".to_string());
+    }
+    params.push(Value::String(id.clone()));
+    let sql = format!(
+        "UPDATE sub_account SET {} WHERE sub_account_id = ${}::text",
+        sets.join(", "),
+        params.len()
+    );
+    let results = state
+        .db
+        .dml_batch(&[DmlStatement::new(sql, params)])
+        .await
+        .map_err(|e| BosError::internal(format!("分账号资料修改未落库:{e}")))?;
+    let affected = results.first().and_then(|r| r.affected_rows);
+    if affected != Some(1) {
+        return Err(BosError::internal(format!(
+            "分账号资料修改语句未落库(affected_rows={affected:?} ⛔ 1)⇒ ⛔ 把 `10000` 当成功"
+        )));
+    }
+
+    let after = sub_meta(state, &id, None, &mut Params::default())
+        .await?
+        .ok_or_else(|| BosError::internal(format!("修改后回读 sub_account 失败:{id}")))?;
+    Ok(json!({
+        "sub_account_id": after.sub_account_id,
+        "customer_id": after.customer_id,
+        "display_name": after.display_name,
+        "network_account_name": after.net_account,
+        "purpose": after.purpose,
+        "status": after.status,
+        "updated_fields": changed,
+        "written_cols": changed,
+        "audit_key": "bos.sub_account.update",
+        "audit_before_after": json!({"before": before,
+                                    "after": {"display_name": after.display_name,
+                                              "net_account": after.net_account}}),
+        "audit_written": false,
+        "audit_note": AUDIT_NOTE,
+        "purpose_note": "purpose(用途说明)⛔ 契约可改字段 ⇒ 本次⛔ 改动,原值如实回显;\
+                         需求列表把 display_name 展示为「使用人/姓名」、契约把它命名为 \
+                         display_name,一字段两义登 18 册",
+        "platform_sync": {
+            "applied": false,
+            "reason": "网络侧账号名只落本地 sub_account.net_account:state.platform 只有 \
+                       user_create/user_get 通路(⛔ iam-user/update 类接口)⇒ 平台侧⛔ 同步,\
+                       登 18 册"
+        },
+        "time_note": "sub_account ⛔ updated_at 列(在册列集只有 created_at)⇒ 本次⛔ 写更新时间,\
+                      修改时刻只能靠审计"
+    }))
 }

+ 773 - 10
src/modules/account/src/handlers/subscription.rs

@@ -1,17 +1,780 @@
+//! 订阅(第 3 册)——读写两侧均真落库:只读侧列表/详情,写侧新订/升降配/续订。
+//!
+//! 设计列由 `src/migrations/dev/20261107000002_bos_write_gap_columns.sql` 补入 dev 骨架
+//! (`contract_item_id`/`use_category`/`start_date`/`end_date`/年费与月结算两列/
+//! `replaces_subscription_id`/`row_version`)⇒ 只读侧**不再有缺列**,`columns_pending`
+//! 保留键回空数组(键不删=前端契约不变)。
+//!
+//! ⚠️ 写侧⛔ 写一期骨架列 `effective_date`/`expire_date`,只写设计列 `start_date`/`end_date`
+//! (=唯一真源);两列语义重叠,读侧仍原样呈现(存量种子只有旧列有值),合并口径已登 18 册待裁定。
+//!
+//! ⚠️ `annual_price_cents`/`monthly_settle_cents`=在册冲突:openapi 把两列为必填,第 3 册 §2.3
+//! 口径是「只读派生、载荷出现即拒收」。本轮**按 openapi 入参落库**,每枚写侧响应回 `pricing_note`
+//! 原文点名,⛔ 自行改成派生、⛔ 静默。
+//!
+//! ⛔ `bos_audit_log`(本期不做);⛔ 本轮未补的深层设计形态(订阅快照列/`line_exit_key`/
+//! `term`/`trial_months` 等)——无处落库的入参在写侧响应 `not_persisted` 里点名。
+//!
+//! 可见性同 [`contract::get_list`]:沿用「可见客户」谓词,写侧同样据此判客户与合同可见。
+
+use axum::extract::State;
 use axum::response::Response;
 use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
-use bos_core::RoleCode;
-use serde_json::json;
+use bos_api::AppState;
+use bos_core::page::PageQuery;
+use bos_core::{BosError, RoleCode};
+use bos_platform::clients::uds::{de, DmlStatement};
+use chrono::NaiveDate;
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+use super::listq::{as_num, as_opt_num, next_seq, pairs_by, total, Params};
+use super::partner::customer_scope_pred;
+
+/// 补列后已无缺列(⛔ 删键=前端类型会缺字段)。
+const COLUMNS_PENDING: &[&str] = &[];
+
+/// 只读侧统一取列(⛔ 相关子查询取名,`plan_name`/`customer_name` 走 [`pairs_by`])。
+const SELECT_COLS: &str = "SELECT s.subscription_id, s.customer_id, s.contract_id, s.plan_id, s.status, \
+     s.effective_date, s.expire_date, s.quota_slots, s.created_at, s.contract_item_id, s.use_category, \
+     s.start_date, s.end_date, s.annual_price_cents, s.monthly_settle_cents, s.replaces_subscription_id, \
+     s.row_version";
+
+/// `use_category` 值域(第 3 册 §4)。
+const USE_CATEGORIES: [&str; 5] = ["office", "live", "ai", "value_add", "customized"];
+
+/// openapi 与设计册口径冲突的原文说明(⛔ 静默)。
+const PRICING_NOTE: &str = "annual_price_cents/monthly_settle_cents 按 openapi 入参落库;\
+     第 3 册 §2.3 口径=这两列只读派生(载荷出现即拒收、⛔ 手工改写),冲突已登记待裁定。";
+
+// ───────────────────────── 写侧:入参 ─────────────────────────
+
+#[derive(Deserialize)]
+pub struct SubscriptionCreateReq {
+    pub customer_id: String,
+    pub plan_id: String,
+    pub contract_id: String,
+    pub contract_item_id: String,
+    pub start_date: String,
+    pub annual_price_cents: i64,
+    pub monthly_settle_cents: i64,
+    pub use_category: Option<String>,
+    /// ⚠️ openapi 新建请求体未声明本列(描述写「拒收…新建时的 end_date」);本轮按「带上即
+    /// 校验并落库」处理,差异在响应 `spec_notes` 点名。
+    pub end_date: Option<String>,
+    /// openapi 未声明;带上就按乐观锁口径处理(新建无可锁既存行 ⇒ `spec_notes` 点名)。
+    pub row_version: Option<i64>,
+}
+
+#[derive(Deserialize)]
+pub struct SubscriptionChangeReq {
+    /// 被替换的原订阅 ID。
+    pub replaces_subscription_id: String,
+    #[serde(flatten)]
+    pub next: SubscriptionCreateReq,
+}
+
+#[derive(Deserialize)]
+pub struct SubscriptionStackReq {
+    pub subscription_id: Option<String>,
+    pub end_date: Option<String>,
+    pub annual_price_cents: Option<i64>,
+    pub monthly_settle_cents: Option<i64>,
+    /// 以下五列只属于 openapi 的「叠加新建」分支,本轮⛔ 新建行 ⇒ 带上就点名未落库。
+    pub customer_id: Option<String>,
+    pub plan_id: Option<String>,
+    pub contract_id: Option<String>,
+    pub contract_item_id: Option<String>,
+    pub start_date: Option<String>,
+    pub row_version: Option<i64>,
+}
+
+// ───────────────────────── 写侧:共用小件 ─────────────────────────
+
+fn trimmed(raw: &str) -> String {
+    raw.trim().to_string()
+}
+
+/// 必填串;空白=显式失败(⛔ 落成空串)。
+fn req_field(field: &str, raw: &str) -> Result<String, BosError> {
+    let s = trimmed(raw);
+    if s.is_empty() {
+        return Err(BosError::bad_params(format!("{field} 必填")));
+    }
+    Ok(s)
+}
+
+/// `YYYY-MM-DD` 解析(同时兜住「日期不可比」与「非法值传给 `::date` 后 UDS 报错」两种失效形态)。
+fn parse_date(field: &str, raw: &str) -> Result<NaiveDate, BosError> {
+    NaiveDate::parse_from_str(raw.trim(), "%Y-%m-%d")
+        .map_err(|_| BosError::bad_params(format!("{field} 须为 YYYY-MM-DD,实得 {raw}")))
+}
+
+fn date_text(d: NaiveDate) -> String {
+    d.format("%Y-%m-%d").to_string()
+}
+
+/// 按顺序把「值+类型」摊成 `$n::type` 列表(值⛔ 拼进 SQL 原文=`sql_guard` 误杀面)。
+fn push_cast(p: &mut Params, vals: &[(Value, &str)]) -> String {
+    vals.iter()
+        .map(|(v, c)| format!("{}::{}", p.push(v.clone()), c))
+        .collect::<Vec<_>>()
+        .join(", ")
+}
+
+#[derive(Deserialize)]
+struct IdRow {
+    #[serde(deserialize_with = "de::as_string")]
+    v: String,
+}
+
+#[derive(Deserialize)]
+struct CountRow {
+    #[serde(deserialize_with = "de::as_string")]
+    c: String,
+}
+
+/// 合同在主档在册**且**落在当前账号可见范围内 ⇒ 回归属客户号。
+///
+/// 客户可见性据此判定即可(合同 `customer_id` 与请求 `customer_id` 一致 ⇒ 同一套
+/// [`customer_scope_pred`] 谓词下客户必然可见且存在),⛔ 多发一趟查询。
+async fn contract_owner(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    contract_id: &str,
+) -> Result<Option<String>, BosError> {
+    let mut p = Params::default();
+    let mut w: Vec<String> = Vec::new();
+    w.push(customer_scope_pred(state, auth, &mut p, "k.customer_id").await?);
+    let cid = p.push(Value::String(contract_id.to_string()));
+    w.push(format!("k.contract_id = {cid}::text"));
+    let sql = format!("SELECT k.customer_id AS v FROM contract k {}", p.where_clause(&w));
+    Ok(state
+        .db
+        .query_one::<IdRow>(&sql, p.values())
+        .await?
+        .map(|r| r.v))
+}
+
+/// `contract_item_id` 须是该合同的服务构成条目(表 `contract_service_item`,⛔ 写它)。
+async fn ensure_contract_item(
+    state: &AppState,
+    contract_id: &str,
+    item_id: &str,
+) -> Result<(), BosError> {
+    let mut p = Params::default();
+    let a = p.push(Value::String(item_id.to_string()));
+    let b = p.push(Value::String(contract_id.to_string()));
+    let sql = format!(
+        "SELECT i.item_id AS v FROM contract_service_item i WHERE i.item_id = {a}::text \
+         AND i.contract_id = {b}::text"
+    );
+    if state.db.query_one::<IdRow>(&sql, p.values()).await?.is_none() {
+        return Err(BosError::bad_params(format!(
+            "contract_item_id {item_id} 不是合同 {contract_id} 的服务构成条目(contract_service_item 在册⛔)"
+        )));
+    }
+    Ok(())
+}
+
+async fn ensure_plan(state: &AppState, plan_id: &str) -> Result<(), BosError> {
+    let mut p = Params::default();
+    let a = p.push(Value::String(plan_id.to_string()));
+    let sql = format!("SELECT c.plan_id AS v FROM catalog_plan c WHERE c.plan_id = {a}::text");
+    if state.db.query_one::<IdRow>(&sql, p.values()).await?.is_none() {
+        return Err(BosError::bad_params(format!("plan_id {plan_id} 在 catalog_plan 在册⛔")));
+    }
+    Ok(())
+}
+
+/// 同一原订阅已被换过的次数(`replaces_subscription_id` 唯一 ⇒ ≥1 即⛔ 再换)。
+async fn replacement_count(state: &AppState, origin_id: &str) -> Result<i64, BosError> {
+    let mut p = Params::default();
+    let a = p.push(Value::String(origin_id.to_string()));
+    let sql = format!(
+        "SELECT COUNT(1) AS c FROM subscription r WHERE r.replaces_subscription_id = {a}::text"
+    );
+    Ok(state
+        .db
+        .query_one::<CountRow>(&sql, p.values())
+        .await?
+        .map(|r| r.c.trim().parse::<i64>().unwrap_or(0))
+        .unwrap_or(0))
+}
 
-pub async fn create(RequireAuth(auth): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
+/// 按 ID+可见范围取整行(写侧所有校验与「影响 0 行」复判都读它)。
+async fn scoped_sub(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    sub_id: &str,
+) -> Result<Option<SubRow>, BosError> {
+    let mut p = Params::default();
+    let mut w: Vec<String> = Vec::new();
+    w.push(customer_scope_pred(state, auth, &mut p, "s.customer_id").await?);
+    let s = p.push(Value::String(sub_id.to_string()));
+    w.push(format!("s.subscription_id = {s}::text"));
+    let sql = format!("{SELECT_COLS} FROM subscription s {}", p.where_clause(&w));
+    state.db.query_one::<SubRow>(&sql, p.values()).await
+}
+
+struct NewSub {
+    id: String,
+    sql: String,
+    params: Vec<Value>,
+}
+
+/// 新订/升降配共用的**新订阅行**:逐条校验+发号+组 INSERT(⛔ 写 `effective_date`/`expire_date`,
+/// `status`/`quota_slots`/`created_at` 走库默认值,⛔ 造值)。
+///
+/// 只组不发:升降配要把它和「原订阅置 `replaced`」塞进同一次 `dml_batch`=原子提交。
+async fn build_new_subscription(
+    state: &AppState,
+    auth: &bos_scope::AuthContext,
+    b: &SubscriptionCreateReq,
+    replaces: Option<&str>,
+) -> Result<NewSub, BosError> {
+    let customer_id = req_field("customer_id", &b.customer_id)?;
+    let plan_id = req_field("plan_id", &b.plan_id)?;
+    let contract_id = req_field("contract_id", &b.contract_id)?;
+    let item_id = req_field("contract_item_id", &b.contract_item_id)?;
+
+    let owner = contract_owner(state, auth, &contract_id)
+        .await?
+        .ok_or_else(|| BosError::not_found(format!("合同不存在或超出当前账号可见范围:{contract_id}")))?;
+    if owner != customer_id {
+        return Err(BosError::bad_params(format!(
+            "合同 {contract_id} 归属客户 {owner},与请求 customer_id {customer_id} 不一致"
+        )));
+    }
+    ensure_contract_item(state, &contract_id, &item_id).await?;
+    ensure_plan(state, &plan_id).await?;
+
+    let use_category = match b.use_category.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        Some(v) => {
+            if !USE_CATEGORIES.contains(&v) {
+                return Err(BosError::bad_params(format!(
+                    "use_category 须∈ {USE_CATEGORIES:?},实得 {v}"
+                )));
+            }
+            Value::String(v.to_string())
+        }
+        None => Value::Null,
+    };
+
+    let start_raw = req_field("start_date", &b.start_date)?;
+    let start = parse_date("start_date", &start_raw)?;
+    let end_value = match b.end_date.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        Some(raw) => {
+            let end = parse_date("end_date", raw)?;
+            if end <= start {
+                return Err(BosError::bad_params(format!(
+                    "end_date {} 须晚于 start_date {}",
+                    raw,
+                    date_text(start)
+                )));
+            }
+            Value::String(date_text(end))
+        }
+        None => Value::Null,
+    };
+
+    let year = chrono::Local::now()
+        .format("%Y")
+        .to_string()
+        .parse::<i32>()
+        .map_err(|e| BosError::internal(format!("取当年年份失败:{e}")))?;
+    let id = format!("SUB-{:06}", next_seq(state.db.as_ref(), "subscription", "subscription", year).await?);
+
+    let mut p = Params::default();
+    let vals: Vec<(Value, &str)> = vec![
+        (Value::String(id.clone()), "text"),
+        (Value::String(customer_id), "text"),
+        (Value::String(contract_id), "text"),
+        (Value::String(plan_id), "text"),
+        (Value::String(item_id), "text"),
+        (use_category, "text"),
+        (Value::String(date_text(start)), "date"),
+        (end_value, "date"),
+        (Value::from(b.annual_price_cents), "bigint"),
+        (Value::from(b.monthly_settle_cents), "bigint"),
+        match replaces {
+            Some(v) => (Value::String(v.to_string()), "text"),
+            None => (Value::Null, "text"),
+        },
+    ];
+    let sql = format!(
+        "INSERT INTO subscription (subscription_id, customer_id, contract_id, plan_id, \
+         contract_item_id, use_category, start_date, end_date, annual_price_cents, \
+         monthly_settle_cents, replaces_subscription_id) VALUES ({})",
+        push_cast(&mut p, &vals)
+    );
+    Ok(NewSub { id, sql, params: p.values().to_vec() })
+}
+
+/// 写侧统一回执:⛔ 回显请求体假装成功——落库后按 ID 回读库内真值再出参
+/// (`/dml/batch@v1` ⛔ 不回 `RETURNING` 值)。
+async fn write_back(
+    state: &AppState,
+    sub_id: &str,
+    op: &str,
+    not_persisted: Vec<String>,
+    spec_notes: Vec<String>,
+) -> Response {
+    let mut p = Params::default();
+    let s = p.push(Value::String(sub_id.to_string()));
+    let sql = format!("{SELECT_COLS} FROM subscription s WHERE s.subscription_id = {s}::text");
+    let r = match state.db.query_one::<SubRow>(&sql, p.values()).await {
+        Ok(Some(r)) => r,
+        Ok(None) => {
+            return json_err(BosError::internal(format!(
+                "写入后回读⛔ 在册:订阅 {sub_id}(短批已提交,须人工核对)"
+            )))
+        }
+        Err(e) => return json_err(e),
+    };
+    let cids = vec![r.customer_id.clone()];
+    let pids = r.plan_id.clone().into_iter().collect::<Vec<String>>();
+    let names = match pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &cids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let plans = match pairs_by(state.db.as_ref(), "catalog_plan", "plan_id", "plan_name", &pids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let mut v = to_json(
+        &r,
+        names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str),
+        r.plan_id.as_deref().and_then(|id| plans.get(id).and_then(|x| x.first())).map(String::as_str),
+    );
+    v["op"] = json!(op);
+    v["pricing_note"] = json!(PRICING_NOTE);
+    v["not_persisted"] = json!(not_persisted);
+    v["spec_notes"] = json!(spec_notes);
+    v["columns_pending"] = json!(COLUMNS_PENDING);
+    json_ok(v)
+}
+
+// ───────────────────────── 写侧:三枚 ─────────────────────────
+
+pub async fn create(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubscriptionCreateReq>,
+) -> Response {
     if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
-    json_ok(json!({ "subscription_id": null, "req": b }))
+    let mut spec_notes: Vec<String> = Vec::new();
+    if body.end_date.as_deref().is_some_and(|s| !s.trim().is_empty()) {
+        spec_notes.push(
+            "openapi /subscription/create@v1 描述为「拒收…新建时的 end_date」,本轮按「带上即校验并落库」\
+             处理,差异已登记待裁定。"
+                .to_string(),
+        );
+    }
+    if body.row_version.is_some() {
+        spec_notes.push(
+            "新建没有可锁定的既存行,入参 row_version 未参与乐观锁;新行 row_version 由库 DEFAULT 1 起算。"
+                .to_string(),
+        );
+    }
+    spec_notes.push(
+        "openapi 声明「拒收」的 line_exits/sub_mode/order_no/opened_at 未在本轮请求体建模(本轮无对应\
+         在册列),带上即忽略而非拒收。"
+            .to_string(),
+    );
+    let n = match build_new_subscription(&state, &auth, &body, None).await {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    match state.db.dml(&n.sql, &n.params).await {
+        Ok(1) => write_back(&state, &n.id, "created", Vec::new(), spec_notes).await,
+        Ok(k) => json_err(BosError::internal(format!("新订落库影响行数异常:{k}(期望 1)"))),
+        Err(e) => json_err(e),
+    }
 }
-pub async fn change(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn stack(a: RequireAuth, b: DataBody<serde_json::Value>) -> Response { create(a, b).await }
-pub async fn get_list(RequireAuth(_a): RequireAuth, DataBody(_b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "items": [] }))
+
+pub async fn change(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubscriptionChangeReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
+    let mut spec_notes: Vec<String> = Vec::new();
+    spec_notes.push(
+        "openapi /subscription/change@v1 描述「升降配须使用新的 contract_id(不得沿用原合同)」本轮未强制\
+         (未登记为校验项),差异已登记待裁定。"
+            .to_string(),
+    );
+    if body.next.row_version.is_some() {
+        spec_notes.push(
+            "入参 row_version 的乐观锁作用于**被替换的原订阅行**;新行 row_version 由库 DEFAULT 1 起算。"
+                .to_string(),
+        );
+    }
+    let rid = match req_field("replaces_subscription_id", &body.replaces_subscription_id) {
+        Ok(v) => v,
+        Err(e) => return json_err(e),
+    };
+    let cur = match scoped_sub(&state, &auth, &rid).await {
+        Ok(Some(c)) => c,
+        Ok(None) => {
+            return json_err(BosError::not_found(format!("原订阅不存在或超出当前账号可见范围:{rid}")))
+        }
+        Err(e) => return json_err(e),
+    };
+    if cur.status == "cancelled" {
+        return json_err(BosError::bad_params(format!("原订阅 {rid} 状态为 cancelled,⛔ 升降配")));
+    }
+    match replacement_count(&state, &cur.subscription_id).await {
+        Ok(0) => {}
+        Ok(k) => {
+            return json_err(BosError::bad_params(format!(
+                "原订阅 {} 已被升降配换过 {k} 次(replaces_subscription_id 唯一,⛔ 重复换)",
+                cur.subscription_id
+            )))
+        }
+        Err(e) => return json_err(e),
+    }
+    let NewSub { id, sql, params } =
+        match build_new_subscription(&state, &auth, &body.next, Some(cur.subscription_id.as_str())).await {
+            Ok(v) => v,
+            Err(e) => return json_err(e),
+        };
+
+    // 原订阅置 replaced+版本自增(谓词里带上「非 cancelled」与「凡带 row_version 即锁」);
+    // 与新行 INSERT 同批=原子提交(⚠️ UDS ⛔ 批内条件中止 ⇒ 影响行数只做事后自检)。
+    let mut up = Params::default();
+    let mut set = vec![format!("status = {}::text", up.push(Value::String("replaced".to_string())))];
+    set.push("row_version = row_version + 1".to_string());
+    let mut preds = vec![format!("subscription_id = {}::text", up.push(Value::String(rid.clone())))];
+    preds.push(format!("status <> {}::text", up.push(Value::String("cancelled".to_string()))));
+    if let Some(v) = body.next.row_version {
+        preds.push(format!("row_version = {}::int", up.push(Value::from(v))));
+    }
+    let update_sql = format!("UPDATE subscription SET {} {}", set.join(", "), up.where_clause(&preds));
+    let results = match state
+        .db
+        .dml_batch(&[
+            DmlStatement::new(sql, params),
+            DmlStatement::new(update_sql, up.values().to_vec()),
+        ])
+        .await
+    {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let hit = |i: usize| results.get(i).and_then(|r| r.affected_rows).unwrap_or(0);
+    if hit(0) != 1 || hit(1) != 1 {
+        return json_err(BosError::internal(format!(
+            "升降配短批影响行数异常(新行 {},原订阅 {}):新订阅 {id} 已随批提交落库,原订阅 {rid} \
+             未置 replaced,须人工核对",
+            hit(0),
+            hit(1)
+        )));
+    }
+    write_back(&state, &id, "changed", Vec::new(), spec_notes).await
 }
-pub async fn get(RequireAuth(_a): RequireAuth, DataBody(b): DataBody<serde_json::Value>) -> Response {
-    json_ok(json!({ "subscription": b }))
+
+pub async fn stack(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubscriptionStackReq>,
+) -> Response {
+    if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
+    let mut spec_notes: Vec<String> = Vec::new();
+    let mut not_persisted: Vec<String> = Vec::new();
+    for (name, v) in [
+        ("customer_id", &body.customer_id),
+        ("plan_id", &body.plan_id),
+        ("contract_id", &body.contract_id),
+        ("contract_item_id", &body.contract_item_id),
+        ("start_date", &body.start_date),
+    ] {
+        if v.as_deref().is_some_and(|s| !s.trim().is_empty()) {
+            not_persisted.push(name.to_string());
+        }
+    }
+    if !not_persisted.is_empty() {
+        spec_notes.push(
+            "以上 not_persisted 列只属于 openapi 的「叠加新建」分支;本轮 stack ⛔ 新建行(只在原行上延长),\
+             故未落库。"
+                .to_string(),
+    );
+    }
+
+    let sid = match body.subscription_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        Some(s) => s.to_string(),
+        None => {
+            return json_err(BosError::not_implemented(
+                "「叠加新建」分支本轮未实现:stack 只在原订阅行上延长,须带 subscription_id",
+            ))
+        }
+    };
+    let cur = match scoped_sub(&state, &auth, &sid).await {
+        Ok(Some(c)) => c,
+        Ok(None) => {
+            return json_err(BosError::not_found(format!("订阅不存在或超出当前账号可见范围:{sid}")))
+        }
+        Err(e) => return json_err(e),
+    };
+    let end_raw = match body.end_date.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+        Some(s) => s.to_string(),
+        None => return json_err(BosError::bad_params("end_date 必填:续订即在原行上延长到期日")),
+    };
+    let new_end = match parse_date("end_date", &end_raw) {
+        Ok(d) => d,
+        Err(e) => return json_err(e),
+    };
+    // 基线=设计列 end_date → 骨架列 expire_date → start_date(存量种子只有旧列有值)。
+    let baseline = cur.end_date.clone().or(cur.expire_date.clone()).or(cur.start_date.clone());
+    match baseline.as_deref() {
+        Some(b) => {
+            let bd = match parse_date("原订阅到期日", b) {
+                Ok(d) => d,
+                Err(e) => return json_err(e),
+            };
+            if new_end <= bd {
+                return json_err(BosError::bad_params(format!(
+                    "end_date {} 须晚于原到期日 {b}",
+                    date_text(new_end)
+                )));
+            }
+        }
+        None => spec_notes.push(
+            "原订阅 end_date/expire_date/start_date 均为空,无在册基线可比,未做「晚于现值」校验。"
+                .to_string(),
+        ),
+    }
+
+    let mut p = Params::default();
+    let mut set = vec![format!("end_date = {}::date", p.push(Value::String(date_text(new_end))))];
+    if let Some(a) = body.annual_price_cents {
+        set.push(format!("annual_price_cents = {}::bigint", p.push(Value::from(a))));
+    }
+    if let Some(m) = body.monthly_settle_cents {
+        set.push(format!("monthly_settle_cents = {}::bigint", p.push(Value::from(m))));
+    }
+    set.push("row_version = row_version + 1".to_string());
+    let mut preds = vec![format!("subscription_id = {}::text", p.push(Value::String(sid.clone())))];
+    if let Some(v) = body.row_version {
+        preds.push(format!("row_version = {}::int", p.push(Value::from(v))));
+    }
+    let sql = format!("UPDATE subscription SET {} {}", set.join(", "), p.where_clause(&preds));
+    let affected = match state.db.dml(&sql, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    if affected != 1 {
+        // 影响 0 行 ⇒ 回读区分「不存在」/「版本不符」/「未带版本却没命中」,⛔ 混用文案。
+        let mut q = Params::default();
+        let s = q.push(Value::String(sid.clone()));
+        let rq = match state
+            .db
+            .query_one::<IdRow>(
+                &format!("SELECT s.row_version AS v FROM subscription s WHERE s.subscription_id = {s}::text"),
+                q.values(),
+            )
+            .await
+        {
+            Ok(r) => r,
+            Err(e) => return json_err(e),
+        };
+        return match (rq, body.row_version) {
+            (None, _) => json_err(BosError::not_found(format!(
+                "续订未命中:订阅 {sid} 不存在或已不可见"
+            ))),
+            (Some(r), Some(v)) => json_err(BosError::bad_params(format!(
+                "续订未命中:携带 row_version = {v},库里现值 {},请刷新后重试",
+                r.v
+            ))),
+            (Some(r), None) => json_err(BosError::internal(format!(
+                "续订影响行数异常:{affected}(未带 row_version,订阅 {sid} 库里现值 row_version {})",
+                r.v
+            ))),
+        };
+    }
+    write_back(&state, &sid, "stacked", not_persisted, spec_notes).await
+}
+
+// ───────────────────────── 只读侧 ─────────────────────────
+
+#[derive(Deserialize)]
+pub struct SubscriptionListReq {
+    #[serde(flatten)]
+    pub pg: PageQuery,
+    pub keyword: Option<String>,
+    pub customer_id: Option<String>,
+    pub contract_id: Option<String>,
+    pub status: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct SubscriptionGetReq {
+    pub subscription_id: String,
+}
+
+#[derive(Deserialize)]
+struct SubRow {
+    #[serde(deserialize_with = "de::as_string")]
+    subscription_id: String,
+    #[serde(deserialize_with = "de::as_string")]
+    customer_id: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    contract_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    plan_id: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    status: String,
+    /// ⚠️ 一期骨架遗留列(写侧已停用),读侧原样呈现。
+    #[serde(deserialize_with = "de::as_opt_string")]
+    effective_date: Option<String>,
+    /// ⚠️ 一期骨架遗留列(写侧已停用),读侧原样呈现。
+    #[serde(deserialize_with = "de::as_opt_string")]
+    expire_date: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    quota_slots: String,
+    #[serde(deserialize_with = "de::as_string")]
+    created_at: String,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    contract_item_id: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    use_category: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    start_date: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    end_date: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    annual_price_cents: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    monthly_settle_cents: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    replaces_subscription_id: Option<String>,
+    #[serde(deserialize_with = "de::as_string")]
+    row_version: String,
+}
+
+fn to_json(r: &SubRow, customer_name: Option<&str>, plan_name: Option<&str>) -> Value {
+    json!({
+        "subscription_id": r.subscription_id,
+        "customer_id": r.customer_id,
+        "customer_name": customer_name,
+        "contract_id": r.contract_id,
+        "plan_id": r.plan_id,
+        "plan_name": plan_name,
+        "status": r.status,
+        "effective_date": r.effective_date,
+        "expire_date": r.expire_date,
+        "quota_slots": as_num(&r.quota_slots),
+        "created_at": r.created_at,
+        "contract_item_id": r.contract_item_id,
+        "use_category": r.use_category,
+        "start_date": r.start_date,
+        "end_date": r.end_date,
+        "annual_price_cents": as_opt_num(r.annual_price_cents.as_deref()),
+        "monthly_settle_cents": as_opt_num(r.monthly_settle_cents.as_deref()),
+        "replaces_subscription_id": r.replaces_subscription_id,
+        "row_version": as_num(&r.row_version),
+    })
+}
+
+pub async fn get_list(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubscriptionListReq>,
+) -> Response {
+    let mut p = Params::default();
+    let mut w: Vec<String> = Vec::new();
+    match customer_scope_pred(&state, &auth, &mut p, "s.customer_id").await {
+        Ok(pred) => w.push(pred),
+        Err(e) => return json_err(e),
+    }
+    if let Some(k) = p.push_like(body.keyword.as_deref()) {
+        w.push(format!(
+            "(s.contract_id LIKE {k} OR s.plan_id LIKE {k} OR EXISTS (SELECT 1 FROM customer ks \
+             WHERE ks.customer_id = s.customer_id AND ks.customer_name LIKE {k}))"
+        ));
+    }
+    if let Some(c) = p.push_eq(body.customer_id.as_deref()) {
+        w.push(format!("s.customer_id = {c}::text"));
+    }
+    if let Some(c) = p.push_eq(body.contract_id.as_deref()) {
+        w.push(format!("s.contract_id = {c}::text"));
+    }
+    if let Some(s) = p.push_eq(body.status.as_deref()) {
+        w.push(format!("s.status = {s}::text"));
+    }
+
+    let from_where = format!("FROM subscription s {}", p.where_clause(&w));
+    let n = match total(state.db.as_ref(), &from_where, p.values()).await {
+        Ok(n) => n,
+        Err(e) => return json_err(e),
+    };
+    let (lim, off) = p.push_page(&body.pg);
+    let sql = format!(
+        "{SELECT_COLS} FROM subscription s {} \
+         ORDER BY s.created_at DESC, s.subscription_id LIMIT {lim} OFFSET {off}",
+        p.where_clause(&w)
+    );
+    let rows = match state.db.query_all::<SubRow>(&sql, p.values()).await {
+        Ok(r) => r,
+        Err(e) => return json_err(e),
+    };
+    let cids: Vec<String> = rows.iter().map(|r| r.customer_id.clone()).collect();
+    let pids: Vec<String> = rows.iter().filter_map(|r| r.plan_id.clone()).collect();
+    let names = match pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &cids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    let plans = match pairs_by(state.db.as_ref(), "catalog_plan", "plan_id", "plan_name", &pids).await {
+        Ok(m) => m,
+        Err(e) => return json_err(e),
+    };
+    json_ok(json!({
+        "items": rows
+            .iter()
+            .map(|r| to_json(
+                r,
+                names.get(&r.customer_id).and_then(|v| v.first()).map(String::as_str),
+                r.plan_id.as_deref().and_then(|id| plans.get(id).and_then(|v| v.first())).map(String::as_str),
+            ))
+            .collect::<Vec<Value>>(),
+        "total": n,
+        "page": body.pg.page,
+        "page_size": body.pg.page_size,
+        "columns_pending": COLUMNS_PENDING,
+    }))
+}
+
+pub async fn get(
+    State(state): State<AppState>,
+    RequireAuth(auth): RequireAuth,
+    DataBody(body): DataBody<SubscriptionGetReq>,
+) -> Response {
+    match scoped_sub(&state, &auth, &trimmed(&body.subscription_id)).await {
+        Ok(Some(r)) => {
+            let cids = vec![r.customer_id.clone()];
+            let pids = r.plan_id.clone().into_iter().collect::<Vec<String>>();
+            let names = match pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &cids).await {
+                Ok(m) => m,
+                Err(e) => return json_err(e),
+            };
+            let plans = match pairs_by(state.db.as_ref(), "catalog_plan", "plan_id", "plan_name", &pids).await {
+                Ok(m) => m,
+                Err(e) => return json_err(e),
+            };
+            let mut v = to_json(
+                &r,
+                names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str),
+                r.plan_id.as_deref().and_then(|id| plans.get(id).and_then(|x| x.first())).map(String::as_str),
+            );
+            v["columns_pending"] = json!(COLUMNS_PENDING);
+            json_ok(v)
+        }
+        Ok(None) => json_ok(json!({
+            "subscription_id": null,
+            "columns_pending": COLUMNS_PENDING,
+            "message": "订阅不存在或超出当前账号可见范围",
+        })),
+        Err(e) => json_err(e),
+    }
 }

+ 11 - 7
src/modules/account/src/router.rs

@@ -5,7 +5,7 @@ use axum::{
 use bos_api::AppState;
 
 use crate::handlers::{
-    account, activation, auth_ctx, catalog, contract, cost, customer, ent_team, import_batch, jobs,
+    account, activation, audit, auth_ctx, catalog, contract, cost, customer, ent_team, import_batch, jobs,
     operator, ops_team, opsview, partner, ping, region, share_rule, sub_account, subscription,
 };
 
@@ -20,12 +20,13 @@ pub fn account_router() -> Router<AppState> {
         .route("/region/create@v1", post(region::create))
         .route("/region/rename@v1", post(region::rename))
         .route("/region/delete@v1", post(region::delete))
-        .route("/region/tree@v1", get(region::tree))
+        .route("/region/tree@v1", post(region::tree))
         .route("/region/subtree@v1", post(region::subtree))
         .route("/region/change_log@v1", get(region::change_log))
-        .route("/region/orphans@v1", get(region::orphans))
+        .route("/region/orphans@v1", post(region::orphans))
         // account
         .route("/account/provision@v1", post(account::provision))
+        .route("/account/get_list@v1", post(account::get_list))
         .route("/account/update_status@v1", post(account::update_status))
         .route("/account/reset_code@v1", post(account::reset_code))
         .route("/account/export_codes@v1", post(account::export_codes))
@@ -48,9 +49,10 @@ pub fn account_router() -> Router<AppState> {
         .route("/partner/update@v1", post(partner::update))
         .route("/partner/delete@v1", post(partner::delete))
         .route("/partner/get_list@v1", post(partner::get_list))
-        .route("/partner/scope/get@v1", get(partner::scope_get))
+        .route("/partner/scope/get@v1", post(partner::scope_get))
         .route("/partner/scope/save@v1", post(partner::scope_save))
         // ent_team
+        .route("/ent_team/get_list@v1", post(ent_team::get_list))
         .route("/ent_team/create@v1", post(ent_team::create))
         .route("/ent_team/update@v1", post(ent_team::update))
         .route("/ent_team/delete@v1", post(ent_team::delete))
@@ -60,9 +62,10 @@ pub fn account_router() -> Router<AppState> {
             "/ent_team/transfer_primary@v1",
             post(ent_team::transfer_primary),
         )
-        .route("/ent_team/scope/get@v1", get(ent_team::scope_get))
+        .route("/ent_team/scope/get@v1", post(ent_team::scope_get))
         .route("/ent_team/scope/save@v1", post(ent_team::scope_save))
         // ops_team
+        .route("/ops_team/get_list@v1", post(ops_team::get_list))
         .route("/ops_team/create@v1", post(ops_team::create))
         .route("/ops_team/update@v1", post(ops_team::update))
         .route("/ops_team/delete@v1", post(ops_team::delete))
@@ -78,7 +81,7 @@ pub fn account_router() -> Router<AppState> {
             "/ops_team/dispatch_mode/update@v1",
             post(ops_team::dispatch_mode_update),
         )
-        .route("/ops_team/coverage/get@v1", get(ops_team::coverage_get))
+        .route("/ops_team/coverage/get@v1", post(ops_team::coverage_get))
         // customer
         .route("/customer/create@v1", post(customer::create))
         .route("/customer/get_list@v1", post(customer::get_list))
@@ -89,7 +92,7 @@ pub fn account_router() -> Router<AppState> {
         .route("/customer/history@v1", post(customer::history))
         .route(
             "/customer/mount_candidates@v1",
-            get(customer::mount_candidates),
+            post(customer::mount_candidates),
         )
         .route("/customer/influence@v1", post(customer::influence))
         .route("/customer/move_region@v1", post(customer::move_region))
@@ -140,6 +143,7 @@ pub fn account_router() -> Router<AppState> {
         .route("/share_rule/get@v1", post(share_rule::get))
         .route("/share_rule/delete@v1", post(share_rule::delete))
         // opsview / jobs
+        .route("/audit/get_list@v1", post(audit::get_list))
         .route("/opsview/home@v1", get(opsview::home))
         .route("/jobs/get_list@v1", get(jobs::list))
         .route("/jobs/toggle@v1", post(jobs::toggle))

+ 1 - 0
src/modules/billing/Cargo.toml

@@ -5,6 +5,7 @@ edition = { workspace = true }
 
 [dependencies]
 bos-core = { workspace = true }
+bos-platform = { workspace = true }
 serde = { workspace = true }
 serde_json = { workspace = true }
 sqlx = { workspace = true }

+ 50 - 48
src/modules/billing/src/lib.rs

@@ -1,8 +1,9 @@
 //! 计费域:第 1 期仅提供账期期初归属快照写入口。
 
 use bos_core::BosError;
+use bos_platform::clients::uds::{DmlStatement, UdsClient};
 use chrono::NaiveDate;
-use sqlx::PgPool;
+use serde_json::{json, Value};
 
 /// 账期形态 YYYY-MM。
 pub fn validate_period(period: &str) -> Result<(), BosError> {
@@ -16,9 +17,13 @@ pub fn validate_period(period: &str) -> Result<(), BosError> {
 ///
 /// ⚠️ 2026-11-05 起团队不分类型、客户可挂多支团队 ⇒ 主表不再持有团队维度列,
 /// 「该期哪个工单类型由哪支团队承接」落子表 `billing_snapshot_customer_team`。
-/// 主表与子表**同一事务**写入:主表已存在(已定稿)即整体跳过,子表不补写。
+///
+/// UDS 短批是**原子提交但⛔ 批内条件中止**(`UDS-2` ①=是/②=否),而「主表已定稿即整体跳过」
+/// 需要中途判断,故分两批:①主表(`ON CONFLICT DO NOTHING`+影响行数自检,0 行=已定稿);
+/// ②子表全部行(同批原子)。两步之间若并发重入,第二次会在 ① 处拿到 0 行而不再补写子表,
+/// 不会与已定稿口径错位。
 pub async fn freeze_customer_snapshot(
-    pool: &PgPool,
+    db: &UdsClient,
     period: &str,
     customer_id: &str,
     region_node_id: &str,
@@ -28,55 +33,52 @@ pub async fn freeze_customer_snapshot(
     team_by_ticket_type: &[(&str, &str)],
 ) -> Result<bool, BosError> {
     validate_period(period)?;
-    let mut tx = pool
-        .begin()
-        .await
-        .map_err(|e| BosError::internal(e.to_string()))?;
-    let res = sqlx::query(
-        r#"
-        INSERT INTO billing_snapshot_customer (
-            period, customer_id, region_node_id, region_path,
-            operator_id, partner_id, frozen_at
-        ) VALUES ($1,$2,$3,$4,$5,$6, NOW())
-        ON CONFLICT (period, customer_id) DO NOTHING
-        "#,
-    )
-    .bind(period)
-    .bind(customer_id)
-    .bind(region_node_id)
-    .bind(region_path)
-    .bind(operator_id)
-    .bind(partner_id)
-    .execute(&mut *tx)
-    .await
-    .map_err(|e| BosError::internal(e.to_string()))?;
-    if res.rows_affected() == 0 {
+    let affected = db
+        .dml(
+            "INSERT INTO billing_snapshot_customer (
+                 period, customer_id, region_node_id, region_path,
+                 operator_id, partner_id, frozen_at
+             ) VALUES ($1::text, $2::text, $3::text, $4::text, $5::text, $6::text, NOW())
+             ON CONFLICT (period, customer_id) DO NOTHING",
+            &[
+                json!(period),
+                json!(customer_id),
+                json!(region_node_id),
+                json!(region_path),
+                json!(operator_id),
+                match partner_id {
+                    Some(p) => json!(p),
+                    None => Value::Null,
+                },
+            ],
+        )
+        .await?;
+    if affected == 0 {
         // 已定稿的期次不补写子表,避免与主表口径错位
-        tx.rollback()
-            .await
-            .map_err(|e| BosError::internal(e.to_string()))?;
         return Ok(false);
     }
-    for (ticket_type, team_id) in team_by_ticket_type {
-        sqlx::query(
-            r#"
-            INSERT INTO billing_snapshot_customer_team (
-                period, customer_id, ticket_type, team_id
-            ) VALUES ($1,$2,$3,$4)
-            ON CONFLICT (period, customer_id, ticket_type) DO NOTHING
-            "#,
-        )
-        .bind(period)
-        .bind(customer_id)
-        .bind(ticket_type)
-        .bind(team_id)
-        .execute(&mut *tx)
-        .await
-        .map_err(|e| BosError::internal(e.to_string()))?;
+    if !team_by_ticket_type.is_empty() {
+        let statements = team_by_ticket_type
+            .iter()
+            .map(|(ticket_type, team_id)| {
+                DmlStatement::new(
+                    "INSERT INTO billing_snapshot_customer_team (
+                         period, customer_id, ticket_type, team_id
+                     ) VALUES ($1::text, $2::text, $3::text, $4::text)
+                     ON CONFLICT (period, customer_id, ticket_type) DO NOTHING",
+                    vec![json!(period), json!(customer_id), json!(ticket_type), json!(team_id)],
+                )
+            })
+            .collect::<Vec<_>>();
+        let results = db.dml_batch(&statements).await?;
+        if results.len() != statements.len() {
+            return Err(BosError::internal(format!(
+                "子表短批结果数不符:期望 {},实得 {}",
+                statements.len(),
+                results.len()
+            )));
+        }
     }
-    tx.commit()
-        .await
-        .map_err(|e| BosError::internal(e.to_string()))?;
     Ok(true)
 }
 

File diff ditekan karena terlalu besar
+ 392 - 7
src/openapi.yaml


+ 38 - 0
src/scripts/assert_structure.sh

@@ -27,12 +27,50 @@ check_absent() {
 }
 
 # DDL/代码实义禁止项(注释中的警示语不计入——scan 已滤 -- 注释)
+# A74(总则§17.2,2026-11-06 来源=平台侧技术债审计 P-16)注册实例清单只走新口 + 游标翻到耗尽
+# ① 旧通用清单口的调用点必须为 0(该口缺省 20 且无上界校验 ⇒ 静默截断)
+check_absent 'registered_resource/get_list@v1' '禁止消费 RM 旧通用清单口(A74①)'
+# ③ ⛔ 把并不存在的"平台上限 20/50"当契约写进代码或注释
+check_absent '平台上限[[:space:]]*(20|50)|硬上限[[:space:]]*(20|50)|平台分页上限' '禁止把"平台上限 20/50"当事实依据(A74③)'
+# ② 凡按新口取清单,完成条件必须落在游标耗尽上(静态代理:同一文件必须出现 next_cursor)
+for f in $(rg -l --glob '!target/**' --glob '!scripts/**' -g '*.rs' -e 'get_list_by_type' "$ROOT" 2>/dev/null || true); do
+  if ! rg -q -e 'next_cursor' "$f" 2>/dev/null; then
+    echo "FAIL: $f 调用清单新口却未处理 next_cursor(A74②:完成条件=next_cursor 为空串/Null,⛔ 单页 len < page_size 判完成)"
+    fail=1
+  fi
+done
+
 check_absent 'customer\.region_id' '禁止 customer.region_id(N2/A1)'
 check_absent '/account/login@v1|/account/logout@v1' '禁止 login/logout 路由'
 check_absent 'CREATE TABLE[[:space:]]+(IF NOT EXISTS[[:space:]]+)?(sched_|job_|evt_task_)' '禁止平台调度影子表'
 check_absent 'CREATE TABLE[[:space:]]+(IF NOT EXISTS[[:space:]]+)?(import_task|export_task)' '禁止异步通道任务影子表'
 check_absent 'password_hash|passwd_hash|session_token' '禁止口令哈希/会话列'
 
+# 总则§9.2 二次改判(平台侧口径=开发指南 §7.2:`info.x-error-code-range` 值域须为被分配段位):
+# 本服务**产出**的数字码必须全部落在 60000–60999(⚠️ 2026-11-07 平台新口径=`60000` 以前
+# 平台已保留 ⇒ 原 `20000`–`20999` 整体 +40000 平移,块结构与段内顺位⛔ 变)。
+# ✅ 唯一在册例外=**鉴权失败类透传平台原码 `11000`/`11001`**(业主 2026-11-07 裁定=
+#    ⛔ 收段、含平台 SDK 鉴权闸门在本进程内产出的响应,业务侧⛔ 改写)⇒ 白名单**只放行这两枚**,
+#    其余 `1xxxx` 仍判 FAIL;这两枚由 error.rs 的守卫单测 `鉴权失败类透传平台原码` 锁死。
+code_hits="$(rg -n -e '=>[[:space:]]*1[0-9]{4},' \
+  "$ROOT/crates/bos-core/src/error.rs" "$ROOT/crates/bos-core/src/response.rs" 2>/dev/null \
+  | rg -v '=>[[:space:]]*1100[01],' || true)"
+stale_hits="$(rg -n -e '=>[[:space:]]*20[0-9]{3},' \
+  "$ROOT/crates/bos-core/src/error.rs" "$ROOT/crates/bos-core/src/response.rs" 2>/dev/null || true)"
+if [[ -n "$code_hits" ]]; then
+  echo "FAIL: 码表出现段外数字码字面量(须落 60000–60999;仅鉴权类 11000/11001 例外,总则§9.2)"
+  echo "$code_hits"
+  fail=1
+fi
+if [[ -n "$stale_hits" ]]; then
+  echo "FAIL: 码表残留旧段 20xxx 字面量(2026-11-07 已整体 +40000 平移至 60xxx,总则§9.1)"
+  echo "$stale_hits"
+  fail=1
+fi
+if [[ -z "$code_hits" && -z "$stale_hits" ]]; then
+  echo "OK: 码表数字码全部落在被分配段 60000–60999(鉴权类透传 11000/11001=在册例外,总则§9.2)"
+fi
+
 if [[ $fail -ne 0 ]]; then
   echo "structure asserts FAILED"
   exit 1

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini