order-demo.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import type { OrderStatus } from "../domain/statuses";
  2. /** 全部订阅的前端初始数据;字段口径与 prototype/data.js 保持一致。 */
  3. export type OrderDemo = {
  4. id: string;
  5. enterprise: string;
  6. enterpriseAccount: string;
  7. planName: string;
  8. planKind: "固定套餐" | "自定义套餐";
  9. changeKind: "首次订阅" | "续订" | "升级" | "升降配" | "叠加";
  10. relatedOrderId: string | null;
  11. contractNumber: string;
  12. orderNumber: string;
  13. exits: string[];
  14. contractStartDate: string;
  15. contractEndDate: string;
  16. actualNetworkOpenDate: string | null;
  17. annualPrice: string;
  18. monthlySettlementAmount: string;
  19. trialMonths?: 1 | 2;
  20. trialDiscount?: string;
  21. subAccountQuota: number;
  22. totalBandwidthMbps: number;
  23. status: OrderStatus;
  24. files?: string[];
  25. voidOn?: string;
  26. voidReason?: string;
  27. };
  28. export function sameOrderExits(left: readonly string[], right: readonly string[]) {
  29. const a = new Set(left), b = new Set(right);
  30. return a.size === b.size && [...a].every((exit) => b.has(exit));
  31. }
  32. export const initialOrders: OrderDemo[] = [
  33. {
  34. id: "SUB-2025-001", enterprise: "澄澜科技有限公司", enterpriseAccount: "KL-2026-0001",
  35. planName: "跨境办公 · 基础档", planKind: "固定套餐", changeKind: "首次订阅", relatedOrderId: null,
  36. contractNumber: "HT-CL-20250318", orderNumber: "CU-SH-20250315-011", files: ["oss://contracts/HT-CL-20250318.pdf"], exits: ["中国香港"], contractStartDate: "2025-03-18", contractEndDate: "2026-03-17",
  37. actualNetworkOpenDate: "2025-03-20", annualPrice: "1080.00", monthlySettlementAmount: "90.00",
  38. subAccountQuota: 10, totalBandwidthMbps: 0, status: "已到期",
  39. },
  40. {
  41. id: "SUB-2026-002", enterprise: "澄澜科技有限公司", enterpriseAccount: "KL-2026-0001",
  42. planName: "跨境办公 · 标准档", planKind: "固定套餐", changeKind: "续订", relatedOrderId: "SUB-2025-001",
  43. contractNumber: "HT-CL-20260318", orderNumber: "CU-SH-20260316-023", files: ["oss://contracts/HT-CL-20260318.pdf"], exits: ["中国香港"], contractStartDate: "2026-03-18", contractEndDate: "2027-03-17",
  44. actualNetworkOpenDate: "2026-03-20", annualPrice: "1440.00", monthlySettlementAmount: "120.00",
  45. subAccountQuota: 10, totalBandwidthMbps: 10, status: "生效中",
  46. },
  47. {
  48. id: "SUB-2026-003", enterprise: "临港跨境贸易", enterpriseAccount: "KL-2026-0008",
  49. planName: "临港 ICT 定制套餐", planKind: "自定义套餐", changeKind: "首次订阅", relatedOrderId: null,
  50. contractNumber: "ICT-LG-20260902", orderNumber: "CU-SH-20261006-077", files: ["oss://contracts/ICT-LG-20260902.pdf"], exits: ["中国香港"], contractStartDate: "2026-09-02", contractEndDate: "2027-09-01",
  51. actualNetworkOpenDate: null, annualPrice: "24000.00", monthlySettlementAmount: "2000.00",
  52. subAccountQuota: 8, totalBandwidthMbps: 150, status: "生效中",
  53. },
  54. {
  55. id: "SUB-2026-004", enterprise: "陈阿福", enterpriseAccount: "KL-2026-0012",
  56. planName: "直播高需求 · A 类", planKind: "固定套餐", changeKind: "首次订阅", relatedOrderId: null,
  57. contractNumber: "HT-CFA-20260901", orderNumber: "CM-SZ-20260828-042", files: ["oss://contracts/HT-CFA-20260901.pdf"], exits: ["美国"], contractStartDate: "2026-09-01", contractEndDate: "2026-10-31",
  58. actualNetworkOpenDate: "2026-09-01", annualPrice: "10800.00", monthlySettlementAmount: "900.00",
  59. subAccountQuota: 2, totalBandwidthMbps: 10, status: "生效中",
  60. },
  61. {
  62. id: "SUB-2026-005", enterprise: "王敏", enterpriseAccount: "KL-2026-0019",
  63. planName: "AI 应用 · 5M 档", planKind: "固定套餐", changeKind: "首次订阅", relatedOrderId: null,
  64. contractNumber: "HT-WM-20260601", orderNumber: "", files: ["oss://contracts/HT-WM-20260601.pdf"], exits: ["日本"], contractStartDate: "2026-06-01", contractEndDate: "2027-05-31",
  65. actualNetworkOpenDate: "2026-06-01", annualPrice: "5760.00", monthlySettlementAmount: "480.00",
  66. subAccountQuota: 3, totalBandwidthMbps: 5, status: "生效中",
  67. },
  68. {
  69. id: "SUB-2026-006", enterprise: "王敏", enterpriseAccount: "KL-2026-0019",
  70. planName: "单独境外 IP(按个叠加)", planKind: "固定套餐", changeKind: "叠加", relatedOrderId: "SUB-2026-005",
  71. contractNumber: "HT-WM-20260801", orderNumber: "", files: ["oss://contracts/HT-WM-20260801.pdf"], exits: ["日本"], contractStartDate: "2026-08-01", contractEndDate: "2027-07-31",
  72. actualNetworkOpenDate: "2026-08-01", annualPrice: "1920.00", monthlySettlementAmount: "160.00",
  73. subAccountQuota: 0, totalBandwidthMbps: 0, status: "生效中",
  74. },
  75. {
  76. id: "SUB-2025-011", enterprise: "澄澜科技有限公司", enterpriseAccount: "KL-2026-0001",
  77. planName: "单独境外 IP(按个叠加)", planKind: "固定套餐", changeKind: "叠加", relatedOrderId: "SUB-2025-001",
  78. contractNumber: "HT-CL-20250318", orderNumber: "CU-SH-20250315-011", files: ["oss://contracts/HT-CL-20250318.pdf"], exits: ["中国香港"], contractStartDate: "2025-03-18", contractEndDate: "2026-03-17",
  79. actualNetworkOpenDate: "2025-03-20", annualPrice: "960.00", monthlySettlementAmount: "80.00",
  80. subAccountQuota: 0, totalBandwidthMbps: 0, status: "已到期",
  81. },
  82. ];
  83. /* ------------------------------------------------------------------ *
  84. * klt-bos 订阅接口适配
  85. *
  86. * ⛔ 复用上面的 `OrderDemo`:后端字段面与演示数据不同源,缺的口径宁可留空由页面
  87. * 渲染「未配置」,也不能往演示类型里塞假值。页面直接用 `OrderView`。
  88. * ------------------------------------------------------------------ */
  89. import { orderGet, orderGetList, orderListAll } from "./api/bos";
  90. import type { RelatedOrderRef, OrderGetResult, OrderListResult, OrderRow } from "./api/types";
  91. import { label, PLAN_FAMILY, PLAN_KIND, ORDER_MODE, ORDER_STATUS, TERM } from "./api/labels";
  92. import { WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "./api/lockedCopy";
  93. import { moneyCell } from "./package-catalog";
  94. import { useLoad, type Load } from "./useLoad";
  95. /** 中文状态筛 → `list_all`/`get_list` 的 `status` 编码。 */
  96. export function orderStatusCode(labelZh: string | undefined | null): string | undefined {
  97. if (!labelZh || labelZh === "全部状态") return undefined;
  98. const hit = Object.entries(ORDER_STATUS).find(([, text]) => text === labelZh);
  99. return hit?.[0];
  100. }
  101. /** `subscription/get` 行 → `orderView` 入参(related 嵌套 → 顶层对照行)。 */
  102. export function orderRowFromGet(row: OrderGetResult): OrderRow {
  103. const replaced = row.related?.replaced_by;
  104. const replacedOne = Array.isArray(replaced) ? (replaced[0] ?? null) : (replaced ?? null);
  105. return {
  106. ...row,
  107. original: row.related?.original ?? row.original ?? null,
  108. replaced_by: replacedOne ?? row.replaced_by ?? null,
  109. };
  110. }
  111. /** 单条订阅详情(出账四卡随 `get` 下发;⛔ 再靠 list_all 凑行)。 */
  112. export function useOrderRecord(subscriptionId: string | undefined): Load<OrderView | null> {
  113. return useLoad(async () => {
  114. if (!subscriptionId) return null;
  115. const row = await orderGet({ subscription_id: subscriptionId });
  116. return orderView(orderRowFromGet(row));
  117. }, [subscriptionId ?? ""]);
  118. }
  119. /** 后端订阅行 → 页面视图:金额一律走三态,⛔ 缺字段回 0。 */
  120. export type OrderView = {
  121. row: OrderRow;
  122. /** 订阅编号:后端未下发独立编号,以主键兜展示位(空=取数失败)。 */
  123. no: string;
  124. customer: string;
  125. customerId: string;
  126. contractNo?: string | null;
  127. planName?: string | null;
  128. planKindLabel?: string | null;
  129. /** 交付形态/订阅方式/规格:未知编码原样显示。 */
  130. familyLabel: string;
  131. modeLabel: string;
  132. termLabel: string;
  133. start?: string | null;
  134. end?: string | null;
  135. exits?: string[] | null;
  136. annual: { tone: "val" | "missing" | "fail"; text: string };
  137. settle: { tone: "val" | "missing" | "fail"; text: string };
  138. cost: { tone: "val" | "missing" | "fail"; text: string };
  139. /** 额度上限:`quota_slots`;当前使用量属客户域口径,本册未接线=未配置。 */
  140. quotaSlots?: number | null;
  141. statusLabel: string;
  142. statusCode?: string;
  143. /** 主键与引用(详情跳转、替换链、同合同并列);⛔ 前端造号。 */
  144. contractId: string;
  145. contractItemId?: string | null;
  146. /** P1(D-2/D-7):附加订阅的父订阅;非空即平铺标注「叠加于 SUB-xxx」,⛔ 折叠嵌套。 */
  147. parentSubscriptionId?: string | null;
  148. planId: string;
  149. /** 升降配替换:本条替代了谁 / 谁替代了本条(后端下发对照行,⛔ 前端拼关系)。 */
  150. original?: RelatedOrderRef | null;
  151. replacedBy?: RelatedOrderRef | null;
  152. trialMonths?: number | null;
  153. /** 试用优惠金额(分);`undefined`=键未下发。 */
  154. trialDiscount?: number | null;
  155. reason?: string | null;
  156. /** 写口可见性由后端给出,⛔ 前端自行推导。 */
  157. editable?: boolean;
  158. createdAt: string;
  159. rowVersion: string;
  160. openedOn?: string | null;
  161. /** 提前停机日(起止日不变时的停机完成日)。 */
  162. earlyStoppedOn?: string | null;
  163. orderNo?: string | null;
  164. /** 派生档标识(合同条目派生)。 */
  165. derived: boolean;
  166. /**
  167. * 出账四卡(第 6 册):应收合计/已出账/未出账/累计成本 + 期次数。
  168. * 键未下发 ⇒ `undefined`(取数失败);`no_receivable` ⇒ 四值 `null` → 未配置。
  169. */
  170. billing?: OrderBilling | null;
  171. };
  172. type MoneyCellView = { tone: "val" | "missing" | "fail"; text: string };
  173. /** 订阅出账四卡(视图层),四值均为分转元的三态格。 */
  174. export type OrderBilling = {
  175. receivable: MoneyCellView;
  176. billed: MoneyCellView;
  177. unbilled: MoneyCellView;
  178. cost: MoneyCellView;
  179. /** 应收期次数(服务端 `COUNT(1)`);`no_receivable` ⇒ 0。 */
  180. periods: number;
  181. };
  182. /** 后端出账聚合 → 三态格:键未下发⇒取数失败,`null`⇒未配置,⛔ 回 0 冒充有值。 */
  183. function billingView(row: OrderRow): OrderView["billing"] {
  184. if (row.billing === undefined) return undefined;
  185. if (row.billing === null) return null;
  186. const b = row.billing;
  187. return {
  188. receivable: moneyCell(b.receivable_cents),
  189. billed: moneyCell(b.billed_cents),
  190. unbilled: moneyCell(b.unbilled_cents),
  191. cost: moneyCell(b.cost_cents),
  192. periods: b.periods,
  193. };
  194. }
  195. /** `actual_opened_at` 落库为 TIMESTAMPTZ,接口原样下发 ISO 时间;日期算法只认 YYYY-MM-DD。 */
  196. const dayOnly = (value?: string | null) =>
  197. value ? (value.length >= 10 ? value.slice(0, 10) : value) : null;
  198. export function orderView(row: OrderRow): OrderView {
  199. const cents = (v: number | null | undefined) => moneyCell(v);
  200. return {
  201. row,
  202. no: row.subscription_id ?? "",
  203. customer: row.customer_name ?? "",
  204. customerId: row.customer_id ?? "",
  205. contractId: row.contract_id ?? "",
  206. contractItemId: row.contract_item_id,
  207. parentSubscriptionId: row.parent_subscription_id ?? null,
  208. planId: row.plan_id ?? "",
  209. original: row.original,
  210. replacedBy: row.replaced_by,
  211. trialMonths: row.trial_months,
  212. trialDiscount: row.discount_monthly_cents,
  213. reason: row.reason,
  214. editable: row.editable,
  215. createdAt: row.created_at ?? "",
  216. rowVersion: row.row_version ?? "",
  217. contractNo: row.contract_no ?? (row.contract_id || null),
  218. planName: row.plan_name ?? (row.plan_id || null),
  219. planKindLabel: row.plan_kind === null || row.plan_kind === undefined ? null : label(PLAN_KIND, row.plan_kind),
  220. familyLabel: row.plan_family ? label(PLAN_FAMILY, row.plan_family) : "",
  221. modeLabel: row.sub_mode_label ?? (row.sub_mode ? label(ORDER_MODE, row.sub_mode) : ""),
  222. termLabel: row.term ? label(TERM, row.term) : "",
  223. start: row.start_date,
  224. end: row.end_date,
  225. exits: row.line_exits,
  226. annual: cents(row.annual_price_cents),
  227. settle: cents(row.monthly_settle_cents),
  228. cost: { tone: row.plan_cost_state === "error" ? "fail" : row.plan_cost_state === "unconfigured" || row.plan_cost_cents === null || row.plan_cost_cents === undefined ? "missing" : "val", text: row.plan_cost_cents === null || row.plan_cost_cents === undefined ? (row.plan_cost_state === "error" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED) : `¥${(row.plan_cost_cents / 100).toFixed(2).replace(/\.00$/, "")}` },
  229. quotaSlots: row.quota_slots ?? null,
  230. // `status` 是库值,`status_display` 是读侧按日期三要素推导的对外口径;两者可能不一致,
  231. // 展示与筛选一律以 `status_display` 为准(见 09 册 TC-CU-162),⛔ 回退去比对库值。
  232. statusLabel: row.status_display?.label
  233. ?? (row.status ? label(ORDER_STATUS, row.status) : ""),
  234. statusCode: row.status_display?.key ?? row.status,
  235. openedOn: dayOnly(row.actual_opened_at),
  236. earlyStoppedOn: dayOnly(row.early_stopped_at),
  237. orderNo: row.order_no,
  238. derived: row.contract_item_id !== null && row.contract_item_id !== undefined && row.plan_kind === "custom",
  239. billing: billingView(row),
  240. };
  241. }
  242. /** 订阅列表:`get_list` 按客户维度(服务端分页;调用方传 page/page_size)。 */
  243. export function useOrders(
  244. customerId: string | undefined,
  245. opts?: { page?: number; pageSize?: number; status?: string; keyword?: string },
  246. ): Load<OrderListResult> {
  247. const page = Math.max(0, opts?.page ?? 0);
  248. const pageSize = Math.max(1, opts?.pageSize ?? 20);
  249. const status = opts?.status || undefined;
  250. const keyword = opts?.keyword?.trim() || undefined;
  251. return useLoad(
  252. () => (customerId
  253. ? orderGetList({ customer_id: customerId, page, page_size: pageSize, status, keyword })
  254. : Promise.resolve({ items: [], total: 0, page: 0, page_size: pageSize })),
  255. [customerId ?? "", page, pageSize, status ?? "", keyword ?? ""],
  256. );
  257. }
  258. export type SubscriptionLedgerOpts = {
  259. keyword?: string;
  260. status?: string;
  261. planKind?: "fixed" | "custom";
  262. lineExit?: string;
  263. expiringWithinDays?: number;
  264. page?: number;
  265. pageSize?: number;
  266. };
  267. /**
  268. * 「全部订阅」台账(`POST /subscription/list_all@v1`):筛选项与分页一律下推服务端。
  269. * ⛔ 再拉 page_size=200 后本地切页。
  270. */
  271. export function useSubscriptionLedger(opts: SubscriptionLedgerOpts): Load<OrderListResult> {
  272. const kw = opts.keyword?.trim() || undefined;
  273. const status = opts.status || undefined;
  274. const planKind = opts.planKind;
  275. const lineExit = opts.lineExit?.trim() || undefined;
  276. const expiring = opts.expiringWithinDays;
  277. const page = Math.max(0, opts.page ?? 0);
  278. const pageSize = Math.max(1, opts.pageSize ?? 20);
  279. return useLoad(
  280. () => orderListAll({
  281. page,
  282. page_size: pageSize,
  283. keyword: kw,
  284. status,
  285. plan_kind: planKind,
  286. line_exit: lineExit,
  287. expiring_within_days: expiring,
  288. }),
  289. [kw ?? "", status ?? "", planKind ?? "", lineExit ?? "", expiring ?? "", page, pageSize],
  290. );
  291. }
  292. /** 状态 Tab 计数:各状态 `page_size:1` 探 `total`(与当前非状态筛同口径)。 */
  293. export function useSubscriptionStatusCounts(opts: {
  294. keyword?: string;
  295. planKind?: "fixed" | "custom";
  296. lineExit?: string;
  297. expiringWithinDays?: number;
  298. statusCodes: readonly string[];
  299. }): Load<Record<string, number>> {
  300. const kw = opts.keyword?.trim() || undefined;
  301. const planKind = opts.planKind;
  302. const lineExit = opts.lineExit?.trim() || undefined;
  303. const expiring = opts.expiringWithinDays;
  304. const codes = opts.statusCodes;
  305. return useLoad(async () => {
  306. const base = {
  307. page: 0,
  308. page_size: 1,
  309. keyword: kw,
  310. plan_kind: planKind,
  311. line_exit: lineExit,
  312. expiring_within_days: expiring,
  313. };
  314. const all = await orderListAll(base);
  315. const out: Record<string, number> = { "": Number(all.total ?? 0) };
  316. await Promise.all(codes.map(async (code) => {
  317. const res = await orderListAll({ ...base, status: code });
  318. out[code] = Number(res.total ?? 0);
  319. }));
  320. return out;
  321. }, [kw ?? "", planKind ?? "", lineExit ?? "", expiring ?? "", codes.join(",")]);
  322. }