import type { OrderStatus } from "../domain/statuses"; /** 全部订阅的前端初始数据;字段口径与 prototype/data.js 保持一致。 */ export type OrderDemo = { id: string; enterprise: string; enterpriseAccount: string; planName: string; planKind: "固定套餐" | "自定义套餐"; changeKind: "首次订阅" | "续订" | "升级" | "升降配" | "叠加"; relatedOrderId: string | null; contractNumber: string; orderNumber: string; exits: string[]; contractStartDate: string; contractEndDate: string; actualNetworkOpenDate: string | null; annualPrice: string; monthlySettlementAmount: string; trialMonths?: 1 | 2; trialDiscount?: string; subAccountQuota: number; totalBandwidthMbps: number; status: OrderStatus; files?: string[]; voidOn?: string; voidReason?: string; }; export function sameOrderExits(left: readonly string[], right: readonly string[]) { const a = new Set(left), b = new Set(right); return a.size === b.size && [...a].every((exit) => b.has(exit)); } export const initialOrders: OrderDemo[] = [ { id: "SUB-2025-001", enterprise: "澄澜科技有限公司", enterpriseAccount: "KL-2026-0001", planName: "跨境办公 · 基础档", planKind: "固定套餐", changeKind: "首次订阅", relatedOrderId: null, 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", actualNetworkOpenDate: "2025-03-20", annualPrice: "1080.00", monthlySettlementAmount: "90.00", subAccountQuota: 10, totalBandwidthMbps: 0, status: "已到期", }, { id: "SUB-2026-002", enterprise: "澄澜科技有限公司", enterpriseAccount: "KL-2026-0001", planName: "跨境办公 · 标准档", planKind: "固定套餐", changeKind: "续订", relatedOrderId: "SUB-2025-001", 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", actualNetworkOpenDate: "2026-03-20", annualPrice: "1440.00", monthlySettlementAmount: "120.00", subAccountQuota: 10, totalBandwidthMbps: 10, status: "生效中", }, { id: "SUB-2026-003", enterprise: "临港跨境贸易", enterpriseAccount: "KL-2026-0008", planName: "临港 ICT 定制套餐", planKind: "自定义套餐", changeKind: "首次订阅", relatedOrderId: null, 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", actualNetworkOpenDate: null, annualPrice: "24000.00", monthlySettlementAmount: "2000.00", subAccountQuota: 8, totalBandwidthMbps: 150, status: "生效中", }, { id: "SUB-2026-004", enterprise: "陈阿福", enterpriseAccount: "KL-2026-0012", planName: "直播高需求 · A 类", planKind: "固定套餐", changeKind: "首次订阅", relatedOrderId: null, 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", actualNetworkOpenDate: "2026-09-01", annualPrice: "10800.00", monthlySettlementAmount: "900.00", subAccountQuota: 2, totalBandwidthMbps: 10, status: "生效中", }, { id: "SUB-2026-005", enterprise: "王敏", enterpriseAccount: "KL-2026-0019", planName: "AI 应用 · 5M 档", planKind: "固定套餐", changeKind: "首次订阅", relatedOrderId: null, contractNumber: "HT-WM-20260601", orderNumber: "", files: ["oss://contracts/HT-WM-20260601.pdf"], exits: ["日本"], contractStartDate: "2026-06-01", contractEndDate: "2027-05-31", actualNetworkOpenDate: "2026-06-01", annualPrice: "5760.00", monthlySettlementAmount: "480.00", subAccountQuota: 3, totalBandwidthMbps: 5, status: "生效中", }, { id: "SUB-2026-006", enterprise: "王敏", enterpriseAccount: "KL-2026-0019", planName: "单独境外 IP(按个叠加)", planKind: "固定套餐", changeKind: "叠加", relatedOrderId: "SUB-2026-005", contractNumber: "HT-WM-20260801", orderNumber: "", files: ["oss://contracts/HT-WM-20260801.pdf"], exits: ["日本"], contractStartDate: "2026-08-01", contractEndDate: "2027-07-31", actualNetworkOpenDate: "2026-08-01", annualPrice: "1920.00", monthlySettlementAmount: "160.00", subAccountQuota: 0, totalBandwidthMbps: 0, status: "生效中", }, { id: "SUB-2025-011", enterprise: "澄澜科技有限公司", enterpriseAccount: "KL-2026-0001", planName: "单独境外 IP(按个叠加)", planKind: "固定套餐", changeKind: "叠加", relatedOrderId: "SUB-2025-001", 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", actualNetworkOpenDate: "2025-03-20", annualPrice: "960.00", monthlySettlementAmount: "80.00", subAccountQuota: 0, totalBandwidthMbps: 0, status: "已到期", }, ]; /* ------------------------------------------------------------------ * * klt-bos 订阅接口适配 * * ⛔ 复用上面的 `OrderDemo`:后端字段面与演示数据不同源,缺的口径宁可留空由页面 * 渲染「未配置」,也不能往演示类型里塞假值。页面直接用 `OrderView`。 * ------------------------------------------------------------------ */ import { orderGet, orderGetList, orderListAll } from "./api/bos"; import type { RelatedOrderRef, OrderGetResult, OrderListResult, OrderRow } from "./api/types"; import { label, PLAN_FAMILY, PLAN_KIND, ORDER_MODE, ORDER_STATUS, TERM } from "./api/labels"; import { WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "./api/lockedCopy"; import { moneyCell } from "./package-catalog"; import { useLoad, type Load } from "./useLoad"; /** 中文状态筛 → `list_all`/`get_list` 的 `status` 编码。 */ export function orderStatusCode(labelZh: string | undefined | null): string | undefined { if (!labelZh || labelZh === "全部状态") return undefined; const hit = Object.entries(ORDER_STATUS).find(([, text]) => text === labelZh); return hit?.[0]; } /** `subscription/get` 行 → `orderView` 入参(related 嵌套 → 顶层对照行)。 */ export function orderRowFromGet(row: OrderGetResult): OrderRow { const replaced = row.related?.replaced_by; const replacedOne = Array.isArray(replaced) ? (replaced[0] ?? null) : (replaced ?? null); return { ...row, original: row.related?.original ?? row.original ?? null, replaced_by: replacedOne ?? row.replaced_by ?? null, }; } /** 单条订阅详情(出账四卡随 `get` 下发;⛔ 再靠 list_all 凑行)。 */ export function useOrderRecord(subscriptionId: string | undefined): Load { return useLoad(async () => { if (!subscriptionId) return null; const row = await orderGet({ subscription_id: subscriptionId }); return orderView(orderRowFromGet(row)); }, [subscriptionId ?? ""]); } /** 后端订阅行 → 页面视图:金额一律走三态,⛔ 缺字段回 0。 */ export type OrderView = { row: OrderRow; /** 订阅编号:后端未下发独立编号,以主键兜展示位(空=取数失败)。 */ no: string; customer: string; customerId: string; contractNo?: string | null; planName?: string | null; planKindLabel?: string | null; /** 交付形态/订阅方式/规格:未知编码原样显示。 */ familyLabel: string; modeLabel: string; termLabel: string; start?: string | null; end?: string | null; exits?: string[] | null; annual: { tone: "val" | "missing" | "fail"; text: string }; settle: { tone: "val" | "missing" | "fail"; text: string }; cost: { tone: "val" | "missing" | "fail"; text: string }; /** 额度上限:`quota_slots`;当前使用量属客户域口径,本册未接线=未配置。 */ quotaSlots?: number | null; statusLabel: string; statusCode?: string; /** 主键与引用(详情跳转、替换链、同合同并列);⛔ 前端造号。 */ contractId: string; contractItemId?: string | null; /** P1(D-2/D-7):附加订阅的父订阅;非空即平铺标注「叠加于 SUB-xxx」,⛔ 折叠嵌套。 */ parentSubscriptionId?: string | null; planId: string; /** 升降配替换:本条替代了谁 / 谁替代了本条(后端下发对照行,⛔ 前端拼关系)。 */ original?: RelatedOrderRef | null; replacedBy?: RelatedOrderRef | null; trialMonths?: number | null; /** 试用优惠金额(分);`undefined`=键未下发。 */ trialDiscount?: number | null; reason?: string | null; /** 写口可见性由后端给出,⛔ 前端自行推导。 */ editable?: boolean; createdAt: string; rowVersion: string; openedOn?: string | null; /** 提前停机日(起止日不变时的停机完成日)。 */ earlyStoppedOn?: string | null; orderNo?: string | null; /** 派生档标识(合同条目派生)。 */ derived: boolean; /** * 出账四卡(第 6 册):应收合计/已出账/未出账/累计成本 + 期次数。 * 键未下发 ⇒ `undefined`(取数失败);`no_receivable` ⇒ 四值 `null` → 未配置。 */ billing?: OrderBilling | null; }; type MoneyCellView = { tone: "val" | "missing" | "fail"; text: string }; /** 订阅出账四卡(视图层),四值均为分转元的三态格。 */ export type OrderBilling = { receivable: MoneyCellView; billed: MoneyCellView; unbilled: MoneyCellView; cost: MoneyCellView; /** 应收期次数(服务端 `COUNT(1)`);`no_receivable` ⇒ 0。 */ periods: number; }; /** 后端出账聚合 → 三态格:键未下发⇒取数失败,`null`⇒未配置,⛔ 回 0 冒充有值。 */ function billingView(row: OrderRow): OrderView["billing"] { if (row.billing === undefined) return undefined; if (row.billing === null) return null; const b = row.billing; return { receivable: moneyCell(b.receivable_cents), billed: moneyCell(b.billed_cents), unbilled: moneyCell(b.unbilled_cents), cost: moneyCell(b.cost_cents), periods: b.periods, }; } /** `actual_opened_at` 落库为 TIMESTAMPTZ,接口原样下发 ISO 时间;日期算法只认 YYYY-MM-DD。 */ const dayOnly = (value?: string | null) => value ? (value.length >= 10 ? value.slice(0, 10) : value) : null; export function orderView(row: OrderRow): OrderView { const cents = (v: number | null | undefined) => moneyCell(v); return { row, no: row.subscription_id ?? "", customer: row.customer_name ?? "", customerId: row.customer_id ?? "", contractId: row.contract_id ?? "", contractItemId: row.contract_item_id, parentSubscriptionId: row.parent_subscription_id ?? null, planId: row.plan_id ?? "", original: row.original, replacedBy: row.replaced_by, trialMonths: row.trial_months, trialDiscount: row.discount_monthly_cents, reason: row.reason, editable: row.editable, createdAt: row.created_at ?? "", rowVersion: row.row_version ?? "", contractNo: row.contract_no ?? (row.contract_id || null), planName: row.plan_name ?? (row.plan_id || null), planKindLabel: row.plan_kind === null || row.plan_kind === undefined ? null : label(PLAN_KIND, row.plan_kind), familyLabel: row.plan_family ? label(PLAN_FAMILY, row.plan_family) : "", modeLabel: row.sub_mode_label ?? (row.sub_mode ? label(ORDER_MODE, row.sub_mode) : ""), termLabel: row.term ? label(TERM, row.term) : "", start: row.start_date, end: row.end_date, exits: row.line_exits, annual: cents(row.annual_price_cents), settle: cents(row.monthly_settle_cents), 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$/, "")}` }, quotaSlots: row.quota_slots ?? null, // `status` 是库值,`status_display` 是读侧按日期三要素推导的对外口径;两者可能不一致, // 展示与筛选一律以 `status_display` 为准(见 09 册 TC-CU-162),⛔ 回退去比对库值。 statusLabel: row.status_display?.label ?? (row.status ? label(ORDER_STATUS, row.status) : ""), statusCode: row.status_display?.key ?? row.status, openedOn: dayOnly(row.actual_opened_at), earlyStoppedOn: dayOnly(row.early_stopped_at), orderNo: row.order_no, derived: row.contract_item_id !== null && row.contract_item_id !== undefined && row.plan_kind === "custom", billing: billingView(row), }; } /** 订阅列表:`get_list` 按客户维度(服务端分页;调用方传 page/page_size)。 */ export function useOrders( customerId: string | undefined, opts?: { page?: number; pageSize?: number; status?: string; keyword?: string }, ): Load { const page = Math.max(0, opts?.page ?? 0); const pageSize = Math.max(1, opts?.pageSize ?? 20); const status = opts?.status || undefined; const keyword = opts?.keyword?.trim() || undefined; return useLoad( () => (customerId ? orderGetList({ customer_id: customerId, page, page_size: pageSize, status, keyword }) : Promise.resolve({ items: [], total: 0, page: 0, page_size: pageSize })), [customerId ?? "", page, pageSize, status ?? "", keyword ?? ""], ); } export type SubscriptionLedgerOpts = { keyword?: string; status?: string; planKind?: "fixed" | "custom"; lineExit?: string; expiringWithinDays?: number; page?: number; pageSize?: number; }; /** * 「全部订阅」台账(`POST /subscription/list_all@v1`):筛选项与分页一律下推服务端。 * ⛔ 再拉 page_size=200 后本地切页。 */ export function useSubscriptionLedger(opts: SubscriptionLedgerOpts): Load { const kw = opts.keyword?.trim() || undefined; const status = opts.status || undefined; const planKind = opts.planKind; const lineExit = opts.lineExit?.trim() || undefined; const expiring = opts.expiringWithinDays; const page = Math.max(0, opts.page ?? 0); const pageSize = Math.max(1, opts.pageSize ?? 20); return useLoad( () => orderListAll({ page, page_size: pageSize, keyword: kw, status, plan_kind: planKind, line_exit: lineExit, expiring_within_days: expiring, }), [kw ?? "", status ?? "", planKind ?? "", lineExit ?? "", expiring ?? "", page, pageSize], ); } /** 状态 Tab 计数:各状态 `page_size:1` 探 `total`(与当前非状态筛同口径)。 */ export function useSubscriptionStatusCounts(opts: { keyword?: string; planKind?: "fixed" | "custom"; lineExit?: string; expiringWithinDays?: number; statusCodes: readonly string[]; }): Load> { const kw = opts.keyword?.trim() || undefined; const planKind = opts.planKind; const lineExit = opts.lineExit?.trim() || undefined; const expiring = opts.expiringWithinDays; const codes = opts.statusCodes; return useLoad(async () => { const base = { page: 0, page_size: 1, keyword: kw, plan_kind: planKind, line_exit: lineExit, expiring_within_days: expiring, }; const all = await orderListAll(base); const out: Record = { "": Number(all.total ?? 0) }; await Promise.all(codes.map(async (code) => { const res = await orderListAll({ ...base, status: code }); out[code] = Number(res.total ?? 0); })); return out; }, [kw ?? "", planKind ?? "", lineExit ?? "", expiring ?? "", codes.join(",")]); }