import { useHorizontalOverflow } from "../lib/use-horizontal-overflow"; import { PageIntro } from "../components/PageIntro"; import { FilterSelect } from "../components/ui/filter-select"; import { MonthFilter } from "../components/ui/month-filter"; import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { ArrowLeft, ArrowRight, FilePenLine, PencilLine, Plus, Search, Trash2, X } from "lucide-react"; import { ListPager, ServerListPager } from "../components/ListPager"; import { slicePage, useLocalPage, LIST_PAGE_SIZE } from "../lib/list-paging"; import { Button } from "../components/ui/button"; import { Input } from "../components/ui/input"; import { FieldHint } from "../components/ui/field-hint"; import { OpsHint, OpsNotice, OpsResponsiveActions, OpsStatus, OpsTag, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit"; import { TreeSelect } from "../components/ui/tree-select"; import { regionTreeNodes } from "../lib/region-tree"; import { Link, useLocation } from "react-router"; import { detailBack, detailLinkState, type DetailLinkState } from "../lib/detail-navigation"; import { Tri } from "../components/triState"; import { ApiError, hasBizCode } from "../lib/api/http"; import { clearCorrectionDraft, readCorrectionDraft, saveCorrectionDraft, submitCorrectionCreate, useBillCandidates, useCorrectionDetail, useCorrectionList, } from "../lib/recon"; import { BACKEND_NOT_WIRED, CONFIG_CONFLICT_NOTE, CONFIG_SAVED_NOTE, CORRECTION_CREATED_FEEDBACK, CORRECTION_DETAIL_NOTE, CORRECTION_H20501_INLINE, CORRECTION_H20501_TEXT, CORRECTION_NEED_BILL, CORRECTION_NEED_ERROR_TEXT, CORRECTION_NEED_REF, CORRECTION_UNMATCHED_TAG, CORRECTION_WIRING_NOTE, } from "../lib/copy-billing"; import { COST_AMORTIZED_HINT, COST_AMOUNT_DIALOG_DISCARD_NOTE, COST_COMBO_FORBIDDEN, COST_CONFLICT_NOTE, COST_DEDUCT_HINT, COST_DELETE_CONFIRM_NOTE, COST_NO_PROVINCE_NOTE, COST_STALE_PANEL_NOTE, COST_UNSAVED_DISCARD_NOTE, costRefBlocked, } from "../lib/copy-cost"; import { WORD_FETCH_FAILED, WORD_NOT_PROVIDED } from "../lib/api/lockedCopy"; import { COST_BILLING_UNIT, COST_CATEGORY, COST_CYCLE } from "../lib/api/labels"; import { boolView, costCellKey, useCostAmounts, useCostItems, type CostComboView, type CostItemView } from "../lib/cost-demo"; import { costAmountSave, costItemDelete, costItemSave } from "../lib/api/bos"; import { useSubmit } from "../lib/useLoad"; import { onboardingRegions, provinceId } from "../lib/customer-onboarding"; import { useBusinessView } from "../lib/use-business-view"; import { useComboCustomerCounts } from "../lib/customer-list-store"; import "../styles/operations.css"; import "../styles/correction-notes.css"; type CostDefinition = { kind: string; name: string; calc: "每客户" | "每账号" | "每份"; repeat: "每月"; amortizationMonths?: number; deduct: boolean; amounts: Record }; export const seedCosts: CostDefinition[] = [ { kind: "国际资源", name: "国家 IP 地址月摊销", calc: "每份", repeat: "每月", deduct: true, amounts: { "上海市 / 联通": 50, "江苏省 / 联通": 45, "上海市 / 电信": 55, "江苏省 / 电信": 48, "上海市 / 移动": 46, "广东省 / 电信": 60, "江苏省 / 移动": 42, "广东省 / 移动": 52 } }, { kind: "国际资源", name: "国际云主机月摊销", calc: "每份", repeat: "每月", deduct: true, amounts: { "上海市 / 联通": 30, "江苏省 / 联通": 28, "上海市 / 电信": 33, "上海市 / 移动": 26, "广东省 / 电信": 35, "广东省 / 移动": 32 } }, { kind: "国际资源", name: "国际出口带宽月摊销", calc: "每账号", repeat: "每月", deduct: true, amounts: { "上海市 / 联通": 80, "江苏省 / 联通": 72, "广东省 / 电信": 90, "江苏省 / 移动": 65 } }, { kind: "项目费用", name: "园区机房改造项目月摊销", calc: "每客户", repeat: "每月", deduct: false, amounts: { "上海市 / 联通": 1200 } }, ]; /** 成本类别/计算方式选项=后端值域(`labels.COST_CATEGORY`/`COST_BILLING_UNIT`,⛔ 页面另抄字面量)。 */ const CATEGORY_OPTIONS = Object.entries(COST_CATEGORY).map(([value, text]) => ({ value, text })); const BILLING_OPTIONS = Object.entries(COST_BILLING_UNIT).map(([value, text]) => ({ value, text })); /** 运营商品牌固定展示序(需求 §6.1 ②:联通/电信/移动三值),品牌下拉按此排序而非字典序。 */ const COST_BRAND_ORDER = ["联通", "电信", "移动"]; /** 后端 `cost_amount` 唯一轴=`province_node_id × operator_id`(与 `costCellKey` 同一前缀口径)。 */ const axisKey = (provinceNodeId: string, operatorId: string) => `${provinceNodeId}|${operatorId}`; const yuan = (value: number) => "¥" + value.toFixed(2); /** D-3:`available:false` 面向操作人的提示;技术原因(迁移路径/表名等)只记日志,⛔ 渲染原文。 */ const AMOUNT_UNAVAILABLE_NOTE = "后端金额明细缺少省份/运营商维度,暂无法展示透视金额"; /** 11103/KLT-E00x 的结构化 detail 随应答 data 位下发;读不到 ⇒ 空对象(⛔ 前端拼句子)。 */ type BizDetail = { field?: string; reason?: string; referring_plan_count?: number; cost_item_id?: string; fields?: { field?: string; reason?: string }[]; }; const bizDetail = (e: unknown): BizDetail => { const d = (e as ApiError | null)?.detail; return d && typeof d === "object" ? (d as BizDetail) : {}; }; /** 11103 ⇒ `detail.fields[].reason` 原文逐条(14.5「该字段由系统带出,不接受录入」同纪律)。 */ const fieldReasons = (e: unknown): string[] => (bizDetail(e).fields ?? []).map((item) => item?.reason ?? "").filter(Boolean); const errorMessage = (e: unknown): string => (e instanceof Error && e.message ? e.message : ""); /** 成本项定义表单(字段与 `/cost_item/save@v1` 载荷一一对应;⛔ 后端⛔ 的字段如 cycle)。 */ type CostDraft = { costItemId?: string; rowVersion: number | string | null; category: string; itemName: string; billingUnit: string; /** U-34:「是否摊销」默认不勾选。 */ amortized: boolean; /** U-34:「总摊销月份数」选填且仅勾选时允许填;留空=每月摊销不结束。 */ amortMonths: string; deduct: boolean; remark: string; }; const emptyCostDraft = (): CostDraft => ({ rowVersion: null, category: CATEGORY_OPTIONS[0].value, itemName: "", billingUnit: BILLING_OPTIONS[0].value, amortized: false, amortMonths: "", deduct: true, remark: "", }); /** * 成本金额录入弹窗(按「省份 × 运营商」组合录入各成本项金额)。 * `new`=新增组合(省份/运营商可选,已有组合⛔ 选);`edit`=改已有组合(两个下拉锁死)。 * `cells` 存输入**原文**:空串=该项不配置(14.1.2:留空项=删除该差异行),不在输入期做数值归一。 * `baseline`=打开弹窗那一刻的格值快照:只有真改过才提示「丢弃」,⛔ 把回填的基线当成未确认草稿。 */ type AmountForm = { mode: "new" | "edit"; regionId: string; operatorId: string; cells: Record; baseline: Record; }; /** 弹窗内是否有真改动(与打开时的快照逐格比)。 */ const amountFormDirty = (form: AmountForm): boolean => Object.keys({ ...form.baseline, ...form.cells }) .some((id) => (form.cells[id] ?? "") !== (form.baseline[id] ?? "")); function CostLedger({ kind, count = 0, children }: { kind: "definitions" | "matrix"; count?: number; children: ReactNode | ((expanded: boolean) => ReactNode) }) { const scroll = useHorizontalOverflow(); const expanded = scroll.width >= 1680; /** * 定义表 11 列=序号/项目/成本类别/计算方式/周期/是否摊销/总摊销月份数/计入分成基数/ * 金额配置情况/被套餐档引用/操作。⚠️ minimums 与 weights 必须逐列对齐(`OpsTableColumns` * 只按数组长度下发 ``):少一项,多出的列在 `table-layout:fixed` 下宽度为 0,表头与内容被挤没。 * 1500 窗口 ⇒ 表格容器≈1182px,故最小宽度合计收在 1156,避免无谓横向滚动。 */ const minimums = kind === "definitions" ? [56, 120, 76, 76, 56, 88, 132, 132, 148, 116, 156] : [110, 84, ...Array(count).fill(110), 76, 142, 120]; const weights = kind === "definitions" ? [0, 17, 10, 8, 7, 6, 8, 8, 24, 12, 0] : [0, 0, ...Array(count).fill(1), 0, count ? 0 : 1, 0]; const minWidth = minimums.reduce((total, minimum) => total + minimum, 0); const weightTotal = weights.reduce((total, weight) => total + weight, 0); const extraWidth = Math.max(0, scroll.width - minWidth); const columns = minimums.map((minimum, index) => minimum + extraWidth * weights[index] / weightTotal); return
= 640 ? " can-pin-identity" : ""}${scroll.canScrollLeft ? " can-scroll-left" : ""}${scroll.canScrollRight ? " can-scroll-right" : ""}`}> {typeof children === "function" ? children(expanded) : children}
; } export function CostManagementPage() { const { identity, organization, readOnly } = useBusinessView(["regions", "operators", "operationsTeams", "enterprises"]); const canEdit = !identity || identity.role === "admin"; const visibleProvinceIds = new Set(onboardingRegions(organization, identity).map((id) => provinceId(organization, id))); const ownerProvinces = organization.regions.filter((region) => visibleProvinceIds.has(region.id)); /** * 省份下拉=**省级**节点(`level` 为「省」)。 * ⛔ 把层级为空(`level` 为 `null`)的根节点「全网」也列进来:它不是省份,选它等于给 * 「全网 × 运营商」写金额行(后端只校验节点存在、不校验层级,脏行落库后才暴露)。 * 层级投影整体缺失时(历史档案)退回区域直属口径,避免下拉为空、整页不可录入。 */ const levelProvinces = ownerProvinces.filter((region) => region.level === 0); const provinceNodes = levelProvinces.length ? levelProvinces : ownerProvinces; const provinceIds = new Set(provinceNodes.map((region) => region.id)); /** * 可配组合=「可见省份 × 该省在册运营商」:后端 `cost_amount` 的唯一键是 * `province_node_id × operator_id`(handler `cost.rs` 两侧分别校验区域维度与 operator 表), * 因此只列运营商档案真实归属到该省的组合,⛔ 造出「某省 × 该省未在册品牌」的假组合。 */ const operatorOptions = organization.operators.flatMap((item) => { const owner = item.region ? provinceId(organization, item.region) : undefined; return owner && provinceIds.has(owner) ? [{ id: item.id, name: item.name, brand: item.brand, provinceId: owner }] : []; }); const allCombos = operatorOptions.map((item) => ({ key: axisKey(item.provinceId, item.id), provinceId: item.provinceId, operatorId: item.id, })); /** 省份显示名:区域树优先(第 1 册口径);树里没有该节点时用后端 `bos_region_meta` 叶子名(`pivotProvinceNames`), * 都没有才回落节点 id(⛔ 把 id 当名字却不说来源)。 */ const provinceNameOf = (id: string) => provinceNodes.find((region) => region.id === id)?.name ?? pivotProvinceNames.get(id) ?? id; const operatorNameOf = (id: string) => operatorOptions.find((item) => item.id === id)?.name ?? id; const [tab, setTab] = useState<"definitions" | "amounts">("definitions"); const [query, setQuery] = useState(""); const [kindFilter, setKindFilter] = useState(""); const [matrixProvince, setMatrixProvince] = useState(""); const [matrixBrand, setMatrixBrand] = useState(""); const [defPage, setDefPage] = useState(0); const [searchQuery, setSearchQuery] = useState(""); useEffect(() => { const timer = window.setTimeout(() => setSearchQuery(query.trim()), 300); return () => window.clearTimeout(timer); }, [query]); /** * 定义 tab 关键字/分类/分页下推;金额 tab 再拉透视(定义口 allPages 取满列头)。 * 非当前 tab 不预拉另一口。 */ const items = useCostItems({ keyword: tab === "definitions" ? searchQuery || undefined : undefined, category: tab === "definitions" ? (kindFilter || undefined) : undefined, page: tab === "definitions" ? defPage : 0, pageSize: LIST_PAGE_SIZE, allPages: tab === "amounts", }); const amounts = useCostAmounts({ enabled: tab === "amounts" }); /** * 「命中客户」列=按「省 × 运营商」组合向后端取客户数(D-2:旧实现读恒空的 * localStorage 快照恒显 0 家)。仅金额 tab 启用;page_size=1 探针取 total,⛔ 全量拉取。 */ const comboCounts = useComboCustomerCounts(allCombos, tab === "amounts"); /** D-3:后端 `available:false` 的技术 message 可能含迁移路径/表名,只打控制台日志,不向操作人渲染。 */ useEffect(() => { if (amounts.data && !amounts.data.available && amounts.data.message) { console.warn("[costs] 金额透视 available:false,技术原因仅记日志不向操作人展示:", amounts.data.message); } }, [amounts.data?.available, amounts.data?.message]); /** 后端透视行自带的省份名(`bos_region_meta.path_name` 叶子)——区域树查不到该节点时兜底显示。 */ const pivotProvinceNames = new Map(); for (const pivot of amounts.data?.combos ?? []) { if (pivot.provinceName) pivotProvinceNames.set(pivot.provinceNodeId, pivot.provinceName); } const saveItem = useSubmit(); const saveAmount = useSubmit(); /** 删除成本项(引用检查通过后真删;服务端仍会复判引用面)。 */ const removeItem = useSubmit(); /** 金额录入弹窗:`null`=关闭;`cells` 存输入原文(元),空串=该项不配置。 */ const [amountForm, setAmountForm] = useState(null); const [editing, setEditing] = useState(null); const [draftDef, setDraftDef] = useState(emptyCostDraft); const [error, setError] = useState(""); /** 金额弹窗的错误行(提交失败/参数不合法;E006/E007 同时按成本项行内红显)。 */ const [amountError, setAmountError] = useState(""); const [notice, setNotice] = useState(""); /** KLT-E001 ⇒「项目名称」框行内红显(14.1.1)。 */ const [nameError, setNameError] = useState(""); /** KLT-E006 ⇒ 行内红显该行(键=cost_item_id,文案带出当前上限)。 */ const [cellErrors, setCellErrors] = useState>({}); /** KLT-E007 ⇒ 该行输入框标灰+出路句(键=cost_item_id),不清空其余已填。 */ const [staleItems, setStaleItems] = useState>({}); /** KLT-E004 且 reason=no_province ⇒ 整页 ② 不可用。 */ const [panelBlocked, setPanelBlocked] = useState(""); /** 删除确认框选中的成本项(`null`=未打开);`deleteError` 只在框内显示。 */ const [deleteTarget, setDeleteTarget] = useState(null); const [deleteError, setDeleteError] = useState(""); const costItems = items.data?.items ?? []; const costItemTotal = items.data?.total ?? costItems.length; /** 定义 tab:筛选已下推服务端;金额 tab:全量定义行作列头,本地不再按 query 二次筛。 */ const filtered = useMemo( () => [...costItems].sort((a, b) => a.name.localeCompare(b.name, "zh-Hans-CN")), [costItems], ); /** * 一览表运营商筛选的候选=「所选省份的在册品牌」(⚠️ 2026-11-15 业主改判:选省后只列该省的, * ⛔ 再恒列全部三值——那时选出来的组合恒为空表,用户会误读成「该省没配」)。 * 未选省份(全部省份)时列全部可见省份的品牌。 * ⚠️ 选项值取**品牌**而非档案 id:运营商档案按省各建一行(同省同品牌唯一), * 按档案 id 列会在「全部省份」下出现两条同名「移动」,且选中一条会把另一省的同品牌行筛掉。 */ const brandOfOperator = new Map(operatorOptions.map((item) => [item.id, item.brand || item.name])); const matrixBrandOptions = (() => { const scope = matrixProvince ? operatorOptions.filter((item) => item.provinceId === matrixProvince) : operatorOptions; const brands = [...new Set(scope.map((item) => brandOfOperator.get(item.id) ?? item.id))]; return brands.sort((a, b) => { const ia = COST_BRAND_ORDER.indexOf(a); const ib = COST_BRAND_ORDER.indexOf(b); return (ia < 0 ? COST_BRAND_ORDER.length : ia) - (ib < 0 ? COST_BRAND_ORDER.length : ib) || a.localeCompare(b, "zh-Hans-CN"); }); })(); const matrixRows = allCombos.filter((row) => (!matrixProvince || row.provinceId === matrixProvince) && (!matrixBrand || brandOfOperator.get(row.operatorId) === matrixBrand)); const matrixPaging = useLocalPage(matrixRows.length); const filteredPage = filtered; const matrixPageRows = slicePage(matrixRows, matrixPaging.safePage); useEffect(() => { setDefPage(0); }, [searchQuery, kindFilter]); useEffect(() => { matrixPaging.resetPage(); }, [matrixProvince, matrixBrand]); /** * 已有金额行的组合(后端透视行=该组合至少配过一项金额)。 * 「新增运营商成本」弹窗只列**尚未配过**的组合:同组合再选一次就是覆盖写,入口收在一览表行内「编辑金额」。 */ const configuredCombos = new Set((amounts.data?.combos ?? []).map((row) => axisKey(row.provinceNodeId, row.operatorId))); const isComboConfigured = (regionId: string, operatorId: string) => configuredCombos.has(axisKey(regionId, operatorId)); /** 该格后端基线:`undefined`=无差异行(未配置),`null`=有行但金额为空,数字=已配金额(元)。 */ const baselineOf = (regionId: string, operatorId: string, itemId: string) => amounts.data?.cells.get(costCellKey(regionId, operatorId, itemId)); /** 该省在册运营商(组合第二维只取档案真实归属该省的,⛔ 造「某省 × 该省未在册」的假组合)。 */ const operatorsOf = (regionId: string) => operatorOptions.filter((item) => item.provinceId === regionId); /** 该省还没配金额的运营商个数(省份下拉据此标「均已配置」并禁用该省)。 */ const pendingCountOf = (regionId: string) => operatorsOf(regionId).filter((item) => !isComboConfigured(regionId, item.id)).length; /** 弹窗前置条件:成本项定义与金额基线都在手才开表单,否则只说明缺口(⛔ 开一个判不了「已有组合」的空表单)。 */ function amountFormBlocked(): string { if (items.error) return `成本项定义取数失败:${items.error.message},不可录入金额。`; if (!costItems.length) return "「成本项定义」里还没有成本项,先新增成本项再录入金额。"; if (amounts.error) return `金额一览取数失败:${amounts.error.message}——判不了哪些组合已有金额,先重试取数。`; if (!amounts.data) return "金额一览取数中,取到基线后再录入金额。"; return ""; } /** 打开金额弹窗:`new`=新增组合(可选预设组合),`edit`=改已有组合(省份/运营商锁死)。 */ function openAmountForm(mode: AmountForm["mode"], preset?: { regionId: string; operatorId: string }) { if (!canEdit) return; const blocked = amountFormBlocked(); if (blocked) { setNotice(blocked); return; } let target = preset ?? null; if (!target && mode === "new") { const region = provinceNodes.find((node) => pendingCountOf(node.id) > 0); const item = region ? operatorsOf(region.id).find((operator) => !isComboConfigured(region.id, operator.id)) : undefined; if (!region || !item) { setNotice("当前可见省份的在册运营商组合都已配好金额;要改金额请在一览表对应行点「编辑金额」。"); return; } target = { regionId: region.id, operatorId: item.id }; } if (!target) return; const cells: Record = {}; if (mode === "edit") { for (const item of costItems) { const value = baselineOf(target.regionId, target.operatorId, item.id); if (typeof value === "number") cells[item.id] = String(value); } } setAmountError(""); setCellErrors({}); setStaleItems({}); saveAmount.clear(); setAmountForm({ mode, ...target, cells, baseline: cells }); } /** 弹窗内换省份:运营商跟着落到该省首个**未配置**的;已填金额随成本项走,不清空。 */ function pickFormRegion(regionId: string) { setAmountForm((current) => { if (!current) return current; const options = operatorsOf(regionId); const next = options.find((item) => current.mode === "edit" || !isComboConfigured(regionId, item.id)) ?? options[0]; return { ...current, regionId, operatorId: next?.id ?? "" }; }); setAmountError(""); } /** * 弹窗内换运营商=换组合(14.6:不保留跨组合草稿 ⇒ 已填金额清空并如实说明)。 * ⚠️ 只在**真改过**金额时提示:空表单/只回填基线就切换,不算「丢弃修改」。 */ function pickFormOperator(operatorId: string) { if (!amountForm) return; const changed = amountFormDirty(amountForm); if (changed) setNotice(COST_UNSAVED_DISCARD_NOTE); setAmountForm({ ...amountForm, operatorId, cells: changed ? {} : amountForm.cells, baseline: changed ? {} : amountForm.baseline }); setAmountError(""); } /** 关闭弹窗:真改过但没确认的金额不落库,给出路句而不是静默丢失。 */ function closeAmountForm() { if (amountForm && amountFormDirty(amountForm)) setNotice(COST_AMOUNT_DIALOG_DISCARD_NOTE); setAmountForm(null); setAmountError(""); setCellErrors({}); setStaleItems({}); } function editAmountCell(itemId: string, raw: string) { setCellErrors((cur) => { if (!cur[itemId]) return cur; const next = { ...cur }; delete next[itemId]; return next; }); setAmountForm((current) => current ? { ...current, cells: { ...current.cells, [itemId]: raw } } : current); } function startEdit(target: CostItemView | "new") { if (!canEdit) return; setEditing(target); setError(""); setNameError(""); saveItem.clear(); setDraftDef(target === "new" ? emptyCostDraft() : { costItemId: target.id, rowVersion: target.rowVersion, category: target.categoryKey ?? CATEGORY_OPTIONS[0].value, itemName: target.name, billingUnit: target.billingUnitKey ?? BILLING_OPTIONS[0].value, amortized: target.amortized === true, amortMonths: target.amortizationMonths === null ? "" : String(target.amortizationMonths), deduct: target.deduct ?? true, remark: target.remark ?? "", }); } /** 新增/编辑成本项失败分支(14.1.1/14.6):弹窗不关、已填保留;KLT-E001 行内红显「项目名称」框。 */ function classifyDefinitionError(e: unknown) { const detail = bizDetail(e); if (hasBizCode(e, "KLT-E001")) { setNameError(errorMessage(e)); return; } if (hasBizCode(e, "KLT-E002")) { setError(costRefBlocked(typeof detail.referring_plan_count === "number" ? detail.referring_plan_count : null)); return; } if (hasBizCode(e, "KLT-S407")) { setError(COST_CONFLICT_NOTE); return; } const reasons = fieldReasons(e); if (hasBizCode(e, "11103") && reasons.length) setError(reasons.join(";")); } async function submitDefinition() { if (!canEdit) return; const name = draftDef.itemName.trim(); if (name.length < 2 || name.length > 64) return setError("成本项名称须为 2–64 个字符。"); let months: number | undefined; const monthsText = draftDef.amortMonths.trim(); // U-34:仅勾选「是否摊销」时允许填月份数;留空=每月摊销不结束(载荷不下发月份数);未勾选时给了值 ⇒ 后端 11103(表单压根不提交)。 if (draftDef.amortized && monthsText !== "") { const parsed = Number(monthsText); if (!Number.isSafeInteger(parsed) || parsed < 1) return setError("总摊销月份数须为大于 0 的整数(留空表示每月摊销、不结束)。"); months = parsed; } if (costItems.some((item) => item.name === name && item.id !== draftDef.costItemId)) return setError(`已有同名成本项「${name}」,全局同名只记一条。`); setError(""); setNameError(""); const ok = await saveItem.run(() => costItemSave({ category: draftDef.category, item_name: name, billing_unit: draftDef.billingUnit, is_amortized: draftDef.amortized, deduct_from_base: draftDef.deduct, amortization_months: draftDef.amortized ? months : undefined, remark: draftDef.remark.trim() || undefined, cost_item_id: draftDef.costItemId, row_version: typeof draftDef.rowVersion === "number" ? draftDef.rowVersion : undefined, }).catch((e: unknown) => { classifyDefinitionError(e); throw e; })); if (!ok) return; setEditing(null); items.reload(); setNotice(draftDef.costItemId ? `成本项「${name}」已保存;此后出账按新定义计入,已出账月份保留当月快照。` : `成本项「${name}」已新增,请切到「成本金额定义」标签页选到对应的「省份 × 运营商」组合后录入该组合的金额;本条${draftDef.deduct ? "从分成基数扣除" : "不从分成基数扣除"}。`); } /** * 删除成本项(契约 14.6):先开二次确认框;「能否删除」由服务端按 `plan_cost_item.cost_item_id` * id 强引用复判——页面只在**后端明确回了 0 个引用**时放行入口,`null`(未下发概况)一律不开。 */ function startDelete(item: CostItemView) { if (!canEdit) return; if (item.referringPlans === null) { setNotice("后端未下发「被套餐档引用」概况,判不了这项能否删除;请刷新列表后再试。"); return; } if (item.referringPlans.length > 0) { setNotice(costRefBlocked(item.referringPlans.length)); return; } setDeleteError(""); removeItem.clear(); setDeleteTarget(item); } async function confirmDelete() { if (!canEdit || !deleteTarget) return; const target = deleteTarget; const ok = await removeItem.run(() => costItemDelete({ cost_item_id: target.id }).catch((e: unknown) => { const detail = bizDetail(e); if (hasBizCode(e, "KLT-E002")) { // 页面状态过期(开框后才被档位引用)⇒ 框内给引用档位数+「先在档位上解除引用」,并刷新引用面。 setDeleteError(costRefBlocked(typeof detail.referring_plan_count === "number" ? detail.referring_plan_count : null)); items.reload(); throw e; } if (hasBizCode(e, "60005")) { setDeleteError("这项已被删除或不存在,刷新列表后重试。"); items.reload(); throw e; } setDeleteError(errorMessage(e) || "删除失败,请重试。"); throw e; })); if (!ok) return; setDeleteTarget(null); items.reload(); amounts.reload(); setNotice(`成本项「${target.name}」已删除。${COST_DELETE_CONFIRM_NOTE}。`); } /** * 一览表省份筛选:换省或改回「全部省份」时,若已选的品牌不在新候选里就一并清空, * 否则残留的品牌筛选会把新省份的列表筛成空表(用户会误读成「该省无组合」)。 */ function changeMatrixProvince(next: string) { setMatrixProvince(next); setMatrixBrand((current) => { if (!current || !next) return current; const available = new Set(operatorOptions.filter((item) => item.provinceId === next).map((item) => item.brand || item.name)); return available.has(current) ? current : ""; }); } /** 保存组合金额失败分支(14.1.2/14.6):弹窗保持、已填全保留;E006 行内红显该行;E007 该行标灰出路;E004 按 reason 两文案;S407 重载并清空已填。 */ function classifyAmountError(e: unknown) { const detail = bizDetail(e); if (hasBizCode(e, "KLT-E006")) { const message = errorMessage(e); if (detail.cost_item_id) setCellErrors((cur) => ({ ...cur, [detail.cost_item_id as string]: message })); setAmountError(message); return; } if (hasBizCode(e, "KLT-E007")) { if (detail.cost_item_id) setStaleItems((cur) => ({ ...cur, [detail.cost_item_id as string]: true })); setAmountError(COST_STALE_PANEL_NOTE); return; } if (hasBizCode(e, "KLT-E004")) { // not_province_node ⇒ 只红显该行(当前组合,服务端原文);no_province ⇒ 整页 ② 不可用+出路句(两文案必须不同)。 if (detail.reason === "no_province") { setPanelBlocked(COST_NO_PROVINCE_NOTE); setAmountForm(null); } else setAmountError(errorMessage(e)); return; } if (hasBizCode(e, "KLT-E005")) { setAmountError(COST_COMBO_FORBIDDEN); return; } if (hasBizCode(e, "KLT-S407")) { // 通用冲突码 ⇒ 重载基线、金额以库为准、不保留本地已填顺序(弹窗留着,格子清空)。 setAmountForm((current) => current ? { ...current, cells: {} } : current); amounts.reload(); setAmountError(CONFIG_CONFLICT_NOTE); return; } const reasons = fieldReasons(e); if (hasBizCode(e, "11103") && reasons.length) setAmountError(reasons.join(";")); } /** * 弹窗确认:按「省份 × 运营商」提交**差异**金额(契约 14.1.2:留空项=删除该差异行)。 * ⚠️ 只写差异:与后端基线相同的格不发;新增组合的基线恒为空 ⇒ 只发已填项。 */ async function submitAmountForm() { if (!canEdit || !amountForm) return; const blocked = amountFormBlocked(); if (blocked) { setAmountError(blocked); return; } const { mode, regionId, operatorId, cells } = amountForm; if (!regionId || !operatorId) { setAmountError("请选择省份与该省在册运营商。"); return; } if (mode === "new" && isComboConfigured(regionId, operatorId)) { setAmountError("该「省份 × 运营商」组合已有金额,请在一览表对应行点「编辑金额」。"); return; } const payload: { cost_item_id: string; amount_cents?: number }[] = []; const nextErrors: Record = {}; for (const item of costItems) { const raw = (cells[item.id] ?? "").trim(); const baseline = mode === "edit" ? baselineOf(regionId, operatorId, item.id) : undefined; if (raw === "") { if (typeof baseline === "number") payload.push({ cost_item_id: item.id }); continue; } const value = Number(raw); if (!Number.isFinite(value) || value < 0) { nextErrors[item.id] = `成本项「${item.name}」的金额请填写正确的非负数值(留空才表示不配置)。`; continue; } if (baseline === value) continue; payload.push({ cost_item_id: item.id, amount_cents: Math.round(value * 100) }); } if (Object.keys(nextErrors).length) { setCellErrors(nextErrors); setAmountError("有金额填写不正确,按行修改后再确认。"); return; } if (!payload.length) { setAmountError(mode === "new" ? "请至少填一个成本项的金额:全部留空=这套组合没有任何金额可落库。" : "本组合没有需要保存的改动。"); return; } setAmountError(""); setCellErrors({}); setStaleItems({}); const ok = await saveAmount.run(() => costAmountSave({ province_node_id: regionId, operator_id: operatorId, items: payload }) .catch((e: unknown) => { classifyAmountError(e); throw e; })); if (!ok) return; setAmountForm(null); amounts.reload(); items.reload(); /** 成功提示按 effective_mode 二选一(14.5:文案由后端随配置返回,⛔ 前端自行判断; * 配置读口未接线 ⇒ CONFIG_SAVED_NOTE 常量兜底(默认 period_snapshot 句),待后端随配置返回后改读响应)。 */ setNotice(`已提交 ${payload.length} 条金额(${provinceNameOf(regionId)} × ${operatorNameOf(operatorId)})。${CONFIG_SAVED_NOTE.period_snapshot}`); } /** 后端透视返回、但不在「可见省份 × 该省在册运营商」档案范围内的组合(口径不一致时如实说明)。 */ const pivotExtras = (amounts.data?.combos ?? []).filter((row) => !allCombos.some((item) => item.key === axisKey(row.provinceNodeId, row.operatorId))); /** 金额格三态:取数失败/后端未下发/真实未配置(灰显 0 是 14.1.2 的口径,不是兜底值)。 */ function amountCell(itemId: string, pivotRow: CostComboView | undefined): ReactNode { if (amounts.error) return ; if (!amounts.data) return ; if (!amounts.data.available) return ; if (!pivotRow) return 0; const value = pivotRow.amounts.get(itemId); if (value === undefined) return 0; if (value === null) return ; return {yuan(value)}; } function rowTotal(pivotRow: CostComboView | undefined): ReactNode { if (amounts.error) return ; if (!amounts.data) return ; if (!amounts.data.available) return ; if (!pivotRow) return 0; let sum = 0; for (const item of costItems) { const value = pivotRow.amounts.get(item.id); if (value === undefined) continue; if (value === null) return ; sum += value; } return {yuan(sum)}; } /** 命中客户数三态:取数失败/取数中/真值(D-2:真值来自后端 customer/get_list 现算 total)。 */ function hitCountCell(rowKey: string): ReactNode { if (comboCounts.error) return —; if (!comboCounts.data) return …; return {comboCounts.data.get(rowKey) ?? 0} 家; } if (readOnly) return
当前身份无权查看成本配置。
; return

成本管理

为不同区域和运营商设定适用的成本金额,作为出账核算的依据。
{tab === "definitions" ? <>
setKindFilter(event.target.value)}>{CATEGORY_OPTIONS.map((item) => )} {(kindFilter || query) && }
{canEdit ? : 只读}
{(expanded) => <>序号项目成本类别计算方式周期是否摊销总摊销月份数计入分成基数金额配置情况被套餐档引用操作{filteredPage.map((item, index) => { const noCycle = item.amortized === null && item.amortizationMonths === null; const deduct = boolView(item.deduct, "是(计入分成基数)", "否(不扣基数)"); return {String(defPage * LIST_PAGE_SIZE + index + 1).padStart(2, "0")} {item.name} {expanded && item.remark ? {item.remark} : null} {noCycle ? : {item.amortized ? "是" : "否"}} {noCycle ? : {item.amortized ? (item.amortizationMonths === null ? "每月摊销(不结束)" : {item.amortizationMonths} 个月) : —}} {deduct.pending ? : {deduct.text}} {item.configuredComboCount === null ? : item.configuredComboCount === 0 ? (item.configuredRowCount ?? 0) > 0 ? 0 个可用组合 · {item.configuredRowCount} 条金额行缺省份/运营商轴 : 尚未配置任何组合(按 0 元 / 月计) : 已配 {item.configuredComboCount} 个组合 · 月合计 {yuan((item.configuredTotalCents ?? 0) / 100)}} {item.referringPlans === null ? : item.referringPlans.length ? item.referringPlans.map((plan) => {plan.name}) : 0} {canEdit ?
, disabled: (item.referringPlans?.length ?? 1) !== 0, title: item.referringPlans === null ? "后端未下发「被套餐档引用」概况,判不了能否删除" : item.referringPlans.length ? `被 ${item.referringPlans.length} 个套餐档引用,先在档位上解除引用` : "未被任何套餐档引用,可删除", onSelect: () => startDelete(item) }]} />
: 只读(全局成本项定义由总运营维护)} ; })}{(items.error || !filtered.length) && {items.error ? "成本项加载失败" : items.loading ? "正在读取成本项…" : query || kindFilter ? "没有符合筛选条件的成本项" : "暂无成本项"} }}
{!items.error && !items.loading && } : panelBlocked ?

成本金额暂不可用

{panelBlocked}(KLT-E004 · no_province)

: <>
changeMatrixProvince(event.target.value)}>{provinceNodes.map((region) => )} setMatrixBrand(event.target.value)}>{matrixBrandOptions.map((brand) => )} {(matrixProvince || matrixBrand) && } {amounts.data && !amounts.error && !amounts.data.available &&

后端金额一览 available:false:{AMOUNT_UNAVAILABLE_NOTE}(明细 {amounts.data.rowsTotal} 行、其中 {amounts.data.unattributedTotal} 行缺省份/运营商轴)⇒ 下表金额格一律标「后端未下发」,不得写成「空数据」或 0。

}
{canEdit ? : 只读(金额由总运营维护)}
省份运营商{costItems.map((item) => {item.name}({item.calc.pending ? WORD_NOT_PROVIDED : item.calc.text}))}命中客户摊销额合计(元 / 月)操作{amounts.error && 成本金额加载失败}{matrixPageRows.map((row) => { const pivotRow = amounts.data?.combos.find((cell) => cell.provinceNodeId === row.provinceId && cell.operatorId === row.operatorId); const configured = isComboConfigured(row.provinceId, row.operatorId); return {provinceNameOf(row.provinceId)} {operatorNameOf(row.operatorId)} {costItems.map((item) => {amountCell(item.id, pivotRow)})} {hitCountCell(row.key)} {rowTotal(pivotRow)} {!canEdit ? 只读 :
} ; })}{!amounts.error && !matrixRows.length && {!allCombos.length ? "暂无可配置成本金额的运营商" : "没有符合筛选条件的区域与运营商组合"}}
{pivotExtras.length > 0 &&

后端透视另返回 {pivotExtras.length} 个「省份节点 × 运营商」组合不在当前可见档案范围内(区域/运营商口径不一致),未列入上表。

} }
{amountForm &&
event.stopPropagation()}>

成本管理 / 成本金额定义

{amountForm.mode === "new" ? "新增运营商成本" : "编辑运营商成本"}

{costItems.map((item) => { const deduct = boolView(item.deduct, "计入基数", "不扣基数"); return ; })}
{amounts.data && !amounts.data.available &&

后端金额一览 available:false({AMOUNT_UNAVAILABLE_NOTE})⇒ 判不出哪些组合已有金额:已有组合请走一览表行内「编辑金额」,本弹窗只用于新增,不得拿它覆盖已有组合。

} {amountError || (saveAmount.error && !saveAmount.busy) ?

{amountError || `金额保存失败:${saveAmount.error?.message ?? ""}`}

: null} {/* ⛔ 弹窗底部不再挂「只提交本次改动过的格子(契约 14.1.2)…」整段说明(2026-11-18 业主指出): 那段是跨两种模式的通用口径,放在「编辑运营商成本」里有一半句子(新增组合才写、去一览表点编辑金额) 与当前场景相悖,且把契约编号等实现口径摆给操作人看。「留空=该项不配置」由每行输入框的 placeholder 承担,「已配金额的组合不在此新增」由运营商下拉禁用+「(已有金额)」承担。 */}
} {editing !== null &&
setEditing(null)}>
event.stopPropagation()}>

成本管理 / 成本项定义

{editing === "new" ? "新增成本项" : "编辑成本项定义"}

{COST_AMORTIZED_HINT.map((line) =>

{line}

)}
{COST_DEDUCT_HINT.map((line) =>

{line}

)}
{(error || (!nameError && saveItem.error)) &&

{error || `保存失败:${saveItem.error?.message ?? ""}(后端校验:11102 乐观锁冲突/11103 参数不合法)`}

} {editing !== "new" && draftDef.rowVersion === null &&

该行后端未下发 row_version ⇒ 本次保存不带乐观锁,他人同时修改不会被拦下。

} {editing !== "new" && (editing.categoryKey === null || editing.billingUnitKey === null || editing.deduct === null) &&

该行的 category/billing_unit/deduct_from_base 后端本期未灌值(columns_pending),表单已按默认值预填——保存会把预填值真实写入这些列。

}
} {deleteTarget &&
!removeItem.busy && setDeleteTarget(null)}>
event.stopPropagation()}>

删除成本项「{deleteTarget.name}」?

该项当前未被任何套餐档引用(引用数 0),可以删除。{COST_DELETE_CONFIRM_NOTE}。此操作无法撤销。

{deleteError &&

{deleteError}

}
} {notice && setNotice("")} />}
; } /* ═══ 出账更正记录(FN-10 登记/FN-11 查看,册 6 §14.6) ════════════════════ * 数据源=correction/create、get_list、detail、draft_save、draft_get 全 [位] stub * (openapi.yaml 未声明 ⇒ 11001 契约占位分支:结构按契约落位、数据区标「后端未下发」); * ⛔ localStorage 台账冒充记录真源(旧 oss-demo-billing-corrections-v2 台账本版移除)。 * 表单只有两项(关联账单+错误内容):⛔ 级别/原因下拉(severity 恒 severe、scope 由对象形态推出); * ⛔ 编辑/删除/核验/审批/办结/导出;⛔ 推测匹配(没命中候选=正常受理+「未关联到系统账目」)。 * 角色:admin ●;regAdmin(=opsMain/opsSub)◐ 服务端按归属区域收窄(越权 KLT-C007 直读 message); * 其余角色不授键 ⇒ 整页不开放。文案唯一真源 ../lib/copy-billing(逐字,⛔ 手打转述)。 */ function CorrectionDialog({ title, subtitle, onClose, detail = false, children }: { title: string; subtitle: string; onClose: () => void; detail?: boolean; children: ReactNode; }) { const ref = useRef(null); useEffect(() => { const dialog = ref.current; if (!dialog) return; dialog.showModal(); return () => dialog.close(); }, []); return { event.preventDefault(); onClose(); }} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
{detail ? "RECORD DETAIL / 更正追踪" : "NEW RECORD / 差错留痕"}

{title}

{subtitle}

{children}
; } /** * 登记时间本地化:后端下发 UTC(`...T17:28:44Z` 裸 ISO),直接入列既难读又与 * 手册「登记时间」口径不符 ⇒ 按浏览器时区显示,原文留在 `title` 里可核。 */ function localTime(iso: string): string { const d = new Date(iso); if (Number.isNaN(d.getTime())) return iso; const p = (n: number) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; } export function CorrectionNotesPage() { const { identity, organization, readOnly } = useBusinessView(["regions", "operationsTeams", "enterprises"]); const location = useLocation(); /** 批次详情「登记更正」入口带来的预填关联对象(state.ref=对账单号,进页即开登记窗、一次性消费)。 */ const { ref: prefillRef = "", correctionView } = (location.state ?? {}) as { ref?: string; correctionView?: { period: string; regionNodeId: string; operatorKeyword: string; keyword: string; page: number; detailId: string | null }; }; const back = detailBack(location.state, "/correction-notes", "返回出账更正记录"); const allowed = useMemo(() => onboardingRegions(organization, identity), [organization, identity]); const tree = useMemo(() => regionTreeNodes(organization.regions, [...allowed]), [organization.regions, allowed]); /** * 归属区域名称:后端 `region_label` 在 dev 库无名称表可回填(区域名走 seoh 层级服务, * `cost.rs` 同源口径回 null),而本页已握有 `region/tree` 的区域清单 ⇒ 由 `region_node_id` * 就地取名,⛔ 让系统已推导出的归属区域显示成「—」(区域筛选按 ID 生效,展示却读不出)。 */ const regionNames = useMemo(() => new Map(organization.regions.map((r) => [r.id, r.name])), [organization.regions]); // 筛选四件:自然月(⛔ 预选——记录永久保留,预选会把「本期没有更正」看成「从没有过更正」)+归属区域+登记人+关键字(只查错误内容,⛔ 扩到关联对象)。 const [period, setPeriod] = useState(correctionView?.period ?? ""); const [regionNodeId, setRegionNodeId] = useState(correctionView?.regionNodeId ?? ""); const [operatorKeyword, setOperatorKeyword] = useState(correctionView?.operatorKeyword ?? ""); const [keyword, setKeyword] = useState(correctionView?.keyword ?? ""); const [page, setPage] = useState(correctionView?.page ?? 1); const list = useCorrectionList({ period, regionNodeId, operatorKeyword, keyword, page }); const wiring = list.fail?.kind === "wiring"; const total = list.data?.total ?? 0; const pageSize = list.data?.page_size ?? 20; const [creating, setCreating] = useState(false); const [detailId, setDetailId] = useState(correctionView?.detailId ?? null); const outgoingState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, ref: "", correctionView: { period, regionNodeId, operatorKeyword, keyword, page, detailId }, }); const [notice, setNotice] = useState(""); useEffect(() => { if (prefillRef) setCreating(true); }, [prefillRef]); const hasFilter = Boolean(period || regionNodeId || operatorKeyword.trim() || keyword.trim()); /** 重置筛选=清空四件+回到「全部自然月」(与进入态相同)。 */ function resetFilters() { setPeriod(""); setRegionNodeId(""); setOperatorKeyword(""); setKeyword(""); setPage(1); } // 不授键角色(只读三类+运维团队三类)整页不开放;regAdmin 可登记,范围由服务端收窄(越权 KLT-C007 直读 message)。 if (readOnly) return
当前身份无权查看出账更正记录。
; return
{back.to !== "/correction-notes" &&
; } /** FN-10 登记窗:表单只有两项(关联账单+错误内容);H20501 停弹窗不丢内容、可顺手存草稿。 */ function CorrectionCreateDialog({ userKey, initialRef, onClose, onCreated }: { userKey: string; initialRef: string; onClose: () => void; onCreated: () => void; }) { // 候选只列已被 executed 批次覆盖过的账(bill/list 应答行恒满足);弹窗挂载才取数,取数失败不拒登(可手工填写)。 const candidates = useBillCandidates(); const [choice, setChoice] = useState(initialRef ? "manual" : ""); const [ref, setRef] = useState(initialRef); const [errorText, setErrorText] = useState(""); const [error, setError] = useState(""); const [regionHint, setRegionHint] = useState(""); const [draftNote, setDraftNote] = useState(""); const [busy, setBusy] = useState(false); const manual = choice === "manual"; const chosen = (candidates.data?.items ?? []).find((item) => item.bill_detail_id === choice); // 草稿预填(按登录账号一份;draft_get 无草稿 ⇒ 成功+空对象;读取失败不阻断登记)。来路预填优先于草稿。 useEffect(() => { if (initialRef) return; let alive = true; readCorrectionDraft(userKey) .then((form) => { if (!alive || !form) return; if (form.ref) { setChoice("manual"); setRef(form.ref); } if (form.error_text) setErrorText(form.error_text); }) .catch(() => undefined); return () => { alive = false; }; }, [userKey, initialRef]); function saveDraft() { const chosenLabel = chosen ? `${chosen.customer_name} · ${chosen.period} · ${chosen.holder_name} · ${chosen.batch_no}` : ""; saveCorrectionDraft(userKey, { ref: manual ? ref.trim() : chosenLabel, error_text: errorText }) .then(() => setDraftNote("草稿已暂存,下次打开登记窗自动带出。")) .catch((e: unknown) => setDraftNote(e instanceof Error && e.message ? e.message : "草稿暂存失败,请重试。")); } function submit() { const text = errorText.trim(); // 自有校验(缺陷 O-7):两件事必填⛔ 交给浏览器原生气泡,一律落 `.ops-form-error` 内联红字 // (与同域其他页同一风格,且被拦原因留在弹窗里,⛔ 一闪即逝)。 if (!choice) { setError(CORRECTION_NEED_BILL); return; } if (manual && !ref.trim()) { setError(CORRECTION_NEED_REF); return; } if (!text) { setError(CORRECTION_NEED_ERROR_TEXT); return; } // 载荷只两项:bill_detail_id(选中候选)或 ref(手工填写原文)+ error_text;⛔ scope/severity/region_node_id(11103 禁传键)。 const payload = manual ? { ref: ref.trim(), error_text: text } : { bill_detail_id: choice, error_text: text }; setBusy(true); setError(""); setRegionHint(""); submitCorrectionCreate(payload) .then(() => { clearCorrectionDraft(userKey).catch(() => undefined); onCreated(); }) .catch((e: unknown) => { // 闸一 KLT-H20501(连是哪一笔账都认不出 ⇒ 推不出归属区域,⛔ 落 NULL):逐字提示+就地提示,停弹窗、已填内容不丢; // 闸二 KLT-H20507(候选带值但不合法)、KLT-C007(超出负责范围)与其余码:直读后端 message。 if (hasBizCode(e, "KLT-H20501") || hasBizCode(e, "60501")) { setError(CORRECTION_H20501_TEXT); setRegionHint(CORRECTION_H20501_INLINE); } else { // 兜底(缺陷 D-55):任何被拦⛔ 静默——后端带文案就直读文案(网关剥码后 `hasBizCode` 会失配, // 但 message 仍在),连文案都没有才回固定句,⛔ 出现「点了没反应」。 const m = e instanceof Error ? e.message.trim() : typeof e === "string" ? e.trim() : ""; setError(m || "登记失败,请重试。"); } }) .finally(() => setBusy(false)); } return {/* `noValidate`:必填拦截交给自有校验(缺陷 O-7),⛔ 让浏览器原生气泡替页面说话。 */}
{ event.preventDefault(); submit(); }}>
{candidates.fail &&

候选清单{candidates.fail.kind === "wiring" ? `待后端接线(${BACKEND_NOT_WIRED})` : "取数失败"},可改用「手工填写」。

} {manual && } {regionHint &&

{regionHint}

}