contract-demo.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import type { StatusTone } from "../domain/statuses";
  2. import { centsToYuan } from "./package-catalog";
  3. import { contractGet, contractGetList, rowsOf } from "./api/bos";
  4. import type {
  5. ContractCustomerProfile,
  6. ContractGetResult,
  7. ContractListResult,
  8. ContractRow,
  9. ContractServiceItem,
  10. } from "./api/types";
  11. import { CONTRACT_TYPE_LABEL } from "../domain/contract-draft";
  12. import { fetchAllPages } from "./fetch-all-pages";
  13. import { useLoad, type Load } from "./useLoad";
  14. /** 合同视图模型口径取自原型《需求规格说明》5.3 的合同记录,数据一律由下方 klt-bos 接口适配产出。 */
  15. export type ContractSource = "运营商同步" | "界面录入" | "批量导入";
  16. /** 服务条目(D-15):只剩「档位 × 份数 × 出口」,形态来自档位 `plan_family`。 */
  17. export type ContractItem = {
  18. type: "套餐";
  19. pkg: string;
  20. qty: number;
  21. /** `link`/`addon`(档位交付形态)。 */
  22. family: string | null;
  23. exits: string[];
  24. ipCount: number;
  25. accounts?: number | null;
  26. bandwidth?: string | null;
  27. planItemId?: string | null;
  28. itemId?: string | null;
  29. /** P1(D-9):`new`=新签链路、`increment`=挂在既有生效订阅上的增量条目。 */
  30. itemMode?: string | null;
  31. /** P1(D-7):叠加服务挂的父条目主键(读口原值)。 */
  32. servesItemId?: string | null;
  33. /** P1(D-9):增量条目引用的既有订阅。 */
  34. refSubscriptionId?: string | null;
  35. };
  36. export type DemoContract = {
  37. no: string;
  38. customer: string;
  39. customerNo?: string;
  40. extNo: string;
  41. amount: number;
  42. /** 合同类型中文(新建/续签/扩容补充协议/变更协议)。 */
  43. contractType: string;
  44. /** 签署日期(`YYYY-MM-DD`;空串=未配置)。 */
  45. signDate: string;
  46. /** 服务期(月);`null`=未配置。 */
  47. serviceMonths: number | null;
  48. start: string;
  49. end: string;
  50. items: ContractItem[];
  51. agent: string;
  52. agentPhone: string;
  53. handoverOn: string;
  54. source: ContractSource;
  55. file: string;
  56. files?: string[];
  57. opened: boolean;
  58. openedOn: string | null;
  59. orderCount: number;
  60. /** 后端主键与并发版本,真实接口数据才有。 */
  61. contractId?: string | null;
  62. rowVersion?: number | null;
  63. customerId?: string | null;
  64. /** 合同类型后端编码(new/renew/expand/change),未知编码原样显示。 */
  65. contractTypeCode?: string | null;
  66. /** 线路出口随服务条目下发,⛔ 前端按本地清单校验。 */
  67. lineExitOptions?: string[];
  68. /** 合同状态原值(页面需要区分「未配置」时读取)。 */
  69. statusCode?: string | null;
  70. /** 关联订阅(详情口 `contract/get` 才有)。 */
  71. relatedOrders?: {
  72. orderId: string; planName: string | null; status: string; startDate: string | null; endDate: string | null;
  73. /** D-75:订阅方式(历史派生值)与交付形态,随 `contract/get` 的 `orders[]` 下发。 */
  74. orderMode?: string | null; planFamily?: string | null; actualOpenedAt?: string | null;
  75. /** D-76:年订阅价/月结算标准(整数分)与订单号。 */
  76. annualPriceCents?: number | null; monthlySettleCents?: number | null; orderNo?: string | null;
  77. /** 关联关系落点(2026-11-17):签约条目与服务条目主键/替换来源。 */
  78. contractItemId?: string | null; replacesSubscriptionId?: string | null;
  79. /** 订阅份数(2026-11-17):可叠加档可 > 1(例:境外 IP 按个),其余恒 1。 */
  80. quantity?: number | null;
  81. /** P1(D-7):附加订阅的父订阅;平铺标注「叠加于 SUB-xxx」,⛔ 折叠嵌套。 */
  82. parentSubscriptionId?: string | null;
  83. }[];
  84. };
  85. export const contractSourceTone = {
  86. 运营商同步: "info", 界面录入: "brand", 批量导入: "neutral",
  87. } as const satisfies Record<ContractSource, StatusTone | "brand">;
  88. /** 合同状态与订阅同一套推导:只由生效日与结束日对比当天得出,不表示网络侧已开通。 */
  89. export type ContractStatus = "待生效" | "生效中" | "已到期";
  90. export function contractStatusOf(start: string, end: string, today = new Date()): ContractStatus {
  91. const stamp = (value: string) => { const [year, month, day] = value.split("-").map(Number); return Date.UTC(year, month - 1, day); };
  92. const now = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
  93. if (now < stamp(start)) return "待生效";
  94. if (now > stamp(end)) return "已到期";
  95. return "生效中";
  96. }
  97. export const contractStatusTone: Record<ContractStatus, StatusTone> = {
  98. 待生效: "neutral", 生效中: "success", 已到期: "neutral",
  99. };
  100. /** 服务构成派生口径:账号数取条目自带 `accounts`(=档位 `sub_account_quota`),⛔ 再按套餐名查本地种子。 */
  101. export function contractAccountsOf(items: ContractItem[]): number {
  102. return items.reduce((sum, item) => sum + (item.accounts ?? 0), 0);
  103. }
  104. export function contractIpTotalOf(items: ContractItem[]): number {
  105. return items.reduce((sum, item) => sum + item.ipCount, 0);
  106. }
  107. export function contractExitsOf(items: ContractItem[]): string[] {
  108. return [...new Set(items.flatMap((item) => item.exits))];
  109. }
  110. export function contractItemBandwidth(item: ContractItem): string {
  111. // 叠加服务不设带宽(D-18);链路档带宽随条目/档位下发,⛔ 回落本地种子名录。
  112. if (item.family === "addon") return "不设带宽(叠加服务)";
  113. return item.bandwidth ?? "按档位口径";
  114. }
  115. export function contractItemBrief(item: ContractItem): string {
  116. return `${item.pkg} × ${item.qty}`;
  117. }
  118. /* ------------------------------------------------------------------ *
  119. * klt-bos 合同接口适配
  120. * ------------------------------------------------------------------ */
  121. /**
  122. * 后端合同行 → 页面视图。
  123. *
  124. * `DemoContract` 的 `source`/`file`/`opened`/`openedOn`/`orderCount` 是演示数据口径,
  125. * klt-bos 未逐一下发;这里把它们放开为可空,页面据 `undefined` 渲染「取数失败」、`null` 渲染
  126. * 「未配置」,⛔ 用假值兜底,也⛔ 改动 `DemoContract` 影响其他册的引用方。
  127. */
  128. export type ContractRowView = Omit<DemoContract, "source" | "file" | "opened" | "openedOn" | "orderCount"> & {
  129. source?: string | null;
  130. file?: string | null;
  131. opened?: boolean | null;
  132. openedOn?: string | null;
  133. orderCount?: number | null;
  134. /** 合同金额三态:`contract_amount_cents` 缺失=取数失败,⛔ 显示 ¥0.00。 */
  135. amountState?: "val" | "missing" | "fail";
  136. payCycleState?: "val" | "missing" | "fail";
  137. serviceMonthsState?: "val" | "missing" | "fail";
  138. periodState?: "val" | "missing" | "fail";
  139. /** 仅 `/contract/get@v1` 下发(D-23):`undefined`=未取数,`null`=档案不可读(客户已注销)。 */
  140. customerProfile?: ContractCustomerProfile | null;
  141. };
  142. /** 合同服务条目 → 页面两形态;套餐式的分账号额度需由目录额度换算,未取到=未配置。 */
  143. export function contractItemFromRow(item: ContractServiceItem, quotaById?: Record<string, number | null | undefined>): ContractItem {
  144. return {
  145. type: "套餐",
  146. pkg: item.plan_name ?? "",
  147. qty: item.quantity ?? 1,
  148. family: item.item_family ?? null,
  149. exits: item.line_exits ?? [],
  150. // 叠加服务份数即 IP 个数(D-15);链路档不计 IP。
  151. ipCount: item.item_family === "addon" ? item.quantity ?? 1 : 0,
  152. // 账号额度优先取合同出参自带的档位额度(D-22:⛔ 依赖目录列表才显示得出来),目录表仅作回落
  153. accounts: item.sub_account_quota ?? (item.plan_id && quotaById ? quotaById[item.plan_id] ?? null : null),
  154. bandwidth: null,
  155. planItemId: item.plan_id ?? null,
  156. itemId: item.item_id ?? null,
  157. itemMode: item.item_mode ?? null,
  158. servesItemId: item.serves_item_id ?? null,
  159. refSubscriptionId: item.ref_subscription_id ?? null,
  160. };
  161. }
  162. /** 后端合同行 → 页面合同口径;后端没下发的口径留空,由页面按「未配置」渲染。 */
  163. export function contractFromRow(row: ContractRow, quotaById?: Record<string, number | null | undefined>): ContractRowView {
  164. const items = rowsOf(row.service_items).map((item) => contractItemFromRow(item, quotaById));
  165. const cents = row.contract_amount_cents === undefined ? row.amount_cents : row.contract_amount_cents;
  166. return {
  167. no: row.contract_no ?? "",
  168. customer: row.customer_name ?? row.customer_free_text ?? "",
  169. extNo: row.external_no ?? "",
  170. amount: centsToYuan(cents) ?? 0,
  171. amountState: cents === undefined ? "fail" : cents === null ? "missing" : "val",
  172. contractType: CONTRACT_TYPE_LABEL[row.contract_type ?? "new"] ?? (row.contract_type ?? "新建"),
  173. contractTypeCode: row.contract_type ?? null,
  174. signDate: row.sign_date ?? "",
  175. serviceMonths: row.service_months === undefined ? null : row.service_months ?? null,
  176. serviceMonthsState: row.service_months === undefined ? "fail" : row.service_months === null ? "missing" : "val",
  177. start: row.start_date ?? "",
  178. end: row.end_date ?? "",
  179. periodState: row.start_date === undefined && row.end_date === undefined ? "fail" : !row.start_date || !row.end_date ? "missing" : "val",
  180. items,
  181. agent: row.agent_name ?? "",
  182. agentPhone: row.agent_mobile ?? "",
  183. handoverOn: row.agent_handover_on ?? "",
  184. source: row.source_label ?? undefined,
  185. /** ⚠️ 后端确实下发 `attachment_url: null`=真未配置,⛔ 折成 `undefined`(那是"本次取数失败"信号),
  186. * 否则未挂附件的合同会被误标成「取数失败」。键完全缺失才回 `undefined`。 */
  187. file: row.attachment_url === undefined ? undefined : row.attachment_url,
  188. files: row.attachment_url ? [row.attachment_url] : [],
  189. opened: row.opened === undefined ? undefined : row.opened,
  190. // `actual_opened_at` 落库是 TIMESTAMPTZ、接口原样下发 ISO 时间;此处只取日历日,
  191. // ⛔ 让「已开通 · 2026-11-16T00:00:00.000000Z」这种时间串进页面。
  192. openedOn: row.actual_opened_at ? row.actual_opened_at.slice(0, 10) : null,
  193. contractId: row.contract_id ?? null,
  194. rowVersion: row.row_version === undefined || row.row_version === null ? null : Number(row.row_version),
  195. customerId: row.customer_id ?? null,
  196. statusCode: row.status ?? null,
  197. };
  198. }
  199. /** 合同详情:在列表口径上叠加「关联订阅」面板数据。 */
  200. export function contractFromDetail(row: ContractGetResult, quotaById?: Record<string, number | null | undefined>): ContractRowView {
  201. return {
  202. ...contractFromRow(row, quotaById),
  203. // D-23:「01 客户资料」段改读详情出参的档案联查,⛔ 靠客户列表命中(分页外=查不到)
  204. customerProfile: row.customer_profile === undefined ? undefined : row.customer_profile,
  205. relatedOrders: row.subscriptions === undefined ? undefined : rowsOf(row.subscriptions).map((s) => ({
  206. orderId: s.subscription_id,
  207. planName: s.plan_name,
  208. status: s.status,
  209. startDate: s.start_date,
  210. endDate: s.end_date,
  211. orderMode: s.sub_mode,
  212. planFamily: s.plan_family,
  213. actualOpenedAt: s.actual_opened_at,
  214. annualPriceCents: s.annual_price_cents,
  215. monthlySettleCents: s.monthly_settle_cents,
  216. orderNo: s.order_no,
  217. contractItemId: s.contract_item_id,
  218. replacesSubscriptionId: s.replaces_subscription_id,
  219. quantity: s.quantity ?? null,
  220. parentSubscriptionId: s.parent_subscription_id ?? null,
  221. })),
  222. };
  223. }
  224. /** 服务构成派生账号数是否可判:套餐式条目拿不到目录额度时=未配置,⛔ 计 0。 */
  225. export function contractAccountsKnown(items: ContractItem[]) {
  226. return !items.some((item) => item.accounts === null || item.accounts === undefined);
  227. }
  228. /**
  229. * 合同列表(详情页「第 N 份」等需同客户全集):按 total 逐页取满。
  230. * 台账翻页请用 `useContractLedger`,⛔ 本钩子做分页 UI。
  231. */
  232. export function useContracts(opts?: { keyword?: string; customerId?: string }): Load<ContractListResult> {
  233. const kw = opts?.keyword?.trim() || undefined;
  234. const customerId = opts?.customerId?.trim() || undefined;
  235. return useLoad(
  236. () => fetchAllPages((page, page_size) =>
  237. contractGetList({ page, page_size, keyword: kw, customer_id: customerId }),
  238. ),
  239. [kw ?? "", customerId ?? ""],
  240. );
  241. }
  242. /**
  243. * 合同台账列表:关键字/状态/来源/出口/快到期/分页一律下推服务端。
  244. * ⛔ 再开 wide=200 本地二次筛。
  245. */
  246. export function useContractLedger(opts: {
  247. keyword?: string;
  248. status?: string;
  249. source?: string;
  250. lineExit?: string;
  251. expiringWithinDays?: number;
  252. page?: number;
  253. pageSize?: number;
  254. }): Load<ContractListResult> {
  255. const kw = opts.keyword?.trim() || undefined;
  256. const status = opts.status?.trim() || undefined;
  257. const source = opts.source?.trim() || undefined;
  258. const lineExit = opts.lineExit?.trim() || undefined;
  259. const expiring = opts.expiringWithinDays;
  260. const page = Math.max(0, opts.page ?? 0);
  261. const pageSize = Math.max(1, opts.pageSize ?? 20);
  262. return useLoad(
  263. () => contractGetList({
  264. page,
  265. page_size: pageSize,
  266. keyword: kw,
  267. status,
  268. source,
  269. line_exit: lineExit,
  270. expiring_within_days: expiring,
  271. }),
  272. [kw ?? "", status ?? "", source ?? "", lineExit ?? "", expiring ?? "", page, pageSize],
  273. );
  274. }
  275. /** 按 contract_id 取单份合同(详情/台账共用)。 */
  276. export function contractById(contractId: string | null | undefined, quotaById?: Record<string, number | null | undefined>) {
  277. return contractGet({ contract_id: contractId ?? "" }).then((row) => (row ? contractFromDetail(row, quotaById) : null));
  278. }
  279. /**
  280. * 按路由参数取原始合同行——参数可能是 `contract_id`,也可能是历史链接里的合同编号。
  281. * 先按主键取;失败再按编号检索出主键后取。两次都拿不到时抛出首个错误,⛔ 把取数失败渲染成「不存在」。
  282. */
  283. export async function contractRawByParam(param: string | null | undefined): Promise<ContractGetResult | null> {
  284. if (!param) return null;
  285. try {
  286. return await contractGet({ contract_id: param });
  287. } catch (cause) {
  288. const hit = rowsOf((await contractGetList({ keyword: param, page: 0, page_size: 20 })).items).find((row) => row.contract_no === param);
  289. if (!hit) throw cause;
  290. return await contractGet({ contract_id: hit.contract_id });
  291. }
  292. }
  293. /** 路由参数 → 页面合同口径(含关联订阅面板)。 */
  294. export async function contractByParam(param: string | null | undefined, quotaById?: Record<string, number | null | undefined>) {
  295. const row = await contractRawByParam(param);
  296. return row ? contractFromDetail(row, quotaById) : null;
  297. }