FinanceReferencePages.tsx 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
  2. import { PageIntro } from "../components/PageIntro";
  3. import { FilterSelect } from "../components/ui/filter-select";
  4. import { MonthFilter } from "../components/ui/month-filter";
  5. import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
  6. import { ArrowLeft, ArrowRight, FilePenLine, PencilLine, Plus, Search, Trash2, X } from "lucide-react";
  7. import { ListPager, ServerListPager } from "../components/ListPager";
  8. import { slicePage, useLocalPage, LIST_PAGE_SIZE } from "../lib/list-paging";
  9. import { Button } from "../components/ui/button";
  10. import { Input } from "../components/ui/input";
  11. import { FieldHint } from "../components/ui/field-hint";
  12. import { OpsHint, OpsNotice, OpsResponsiveActions, OpsStatus, OpsTag, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit";
  13. import { TreeSelect } from "../components/ui/tree-select";
  14. import { regionTreeNodes } from "../lib/region-tree";
  15. import { Link, useLocation } from "react-router";
  16. import { detailBack, detailLinkState, type DetailLinkState } from "../lib/detail-navigation";
  17. import { Tri } from "../components/triState";
  18. import { ApiError, hasBizCode } from "../lib/api/http";
  19. import {
  20. clearCorrectionDraft, readCorrectionDraft, saveCorrectionDraft, submitCorrectionCreate,
  21. useBillCandidates, useCorrectionDetail, useCorrectionList,
  22. } from "../lib/recon";
  23. import {
  24. BACKEND_NOT_WIRED,
  25. CONFIG_CONFLICT_NOTE,
  26. CONFIG_SAVED_NOTE,
  27. CORRECTION_CREATED_FEEDBACK,
  28. CORRECTION_DETAIL_NOTE,
  29. CORRECTION_H20501_INLINE,
  30. CORRECTION_H20501_TEXT,
  31. CORRECTION_NEED_BILL,
  32. CORRECTION_NEED_ERROR_TEXT,
  33. CORRECTION_NEED_REF,
  34. CORRECTION_UNMATCHED_TAG,
  35. CORRECTION_WIRING_NOTE,
  36. } from "../lib/copy-billing";
  37. import {
  38. COST_AMORTIZED_HINT,
  39. COST_AMOUNT_DIALOG_DISCARD_NOTE,
  40. COST_COMBO_FORBIDDEN,
  41. COST_CONFLICT_NOTE,
  42. COST_DEDUCT_HINT,
  43. COST_DELETE_CONFIRM_NOTE,
  44. COST_NO_PROVINCE_NOTE,
  45. COST_STALE_PANEL_NOTE,
  46. COST_UNSAVED_DISCARD_NOTE,
  47. costRefBlocked,
  48. } from "../lib/copy-cost";
  49. import { WORD_FETCH_FAILED, WORD_NOT_PROVIDED } from "../lib/api/lockedCopy";
  50. import { COST_BILLING_UNIT, COST_CATEGORY, COST_CYCLE } from "../lib/api/labels";
  51. import { boolView, costCellKey, useCostAmounts, useCostItems, type CostComboView, type CostItemView } from "../lib/cost-demo";
  52. import { costAmountSave, costItemDelete, costItemSave } from "../lib/api/bos";
  53. import { useSubmit } from "../lib/useLoad";
  54. import { onboardingRegions, provinceId } from "../lib/customer-onboarding";
  55. import { useBusinessView } from "../lib/use-business-view";
  56. import { useComboCustomerCounts } from "../lib/customer-list-store";
  57. import "../styles/operations.css";
  58. import "../styles/correction-notes.css";
  59. type CostDefinition = { kind: string; name: string; calc: "每客户" | "每账号" | "每份"; repeat: "每月"; amortizationMonths?: number; deduct: boolean; amounts: Record<string, number> };
  60. export const seedCosts: CostDefinition[] = [
  61. { kind: "国际资源", name: "国家 IP 地址月摊销", calc: "每份", repeat: "每月", deduct: true, amounts: { "上海市 / 联通": 50, "江苏省 / 联通": 45, "上海市 / 电信": 55, "江苏省 / 电信": 48, "上海市 / 移动": 46, "广东省 / 电信": 60, "江苏省 / 移动": 42, "广东省 / 移动": 52 } },
  62. { kind: "国际资源", name: "国际云主机月摊销", calc: "每份", repeat: "每月", deduct: true, amounts: { "上海市 / 联通": 30, "江苏省 / 联通": 28, "上海市 / 电信": 33, "上海市 / 移动": 26, "广东省 / 电信": 35, "广东省 / 移动": 32 } },
  63. { kind: "国际资源", name: "国际出口带宽月摊销", calc: "每账号", repeat: "每月", deduct: true, amounts: { "上海市 / 联通": 80, "江苏省 / 联通": 72, "广东省 / 电信": 90, "江苏省 / 移动": 65 } },
  64. { kind: "项目费用", name: "园区机房改造项目月摊销", calc: "每客户", repeat: "每月", deduct: false, amounts: { "上海市 / 联通": 1200 } },
  65. ];
  66. /** 成本类别/计算方式选项=后端值域(`labels.COST_CATEGORY`/`COST_BILLING_UNIT`,⛔ 页面另抄字面量)。 */
  67. const CATEGORY_OPTIONS = Object.entries(COST_CATEGORY).map(([value, text]) => ({ value, text }));
  68. const BILLING_OPTIONS = Object.entries(COST_BILLING_UNIT).map(([value, text]) => ({ value, text }));
  69. /** 运营商品牌固定展示序(需求 §6.1 ②:联通/电信/移动三值),品牌下拉按此排序而非字典序。 */
  70. const COST_BRAND_ORDER = ["联通", "电信", "移动"];
  71. /** 后端 `cost_amount` 唯一轴=`province_node_id × operator_id`(与 `costCellKey` 同一前缀口径)。 */
  72. const axisKey = (provinceNodeId: string, operatorId: string) => `${provinceNodeId}|${operatorId}`;
  73. const yuan = (value: number) => "¥" + value.toFixed(2);
  74. /** D-3:`available:false` 面向操作人的提示;技术原因(迁移路径/表名等)只记日志,⛔ 渲染原文。 */
  75. const AMOUNT_UNAVAILABLE_NOTE = "后端金额明细缺少省份/运营商维度,暂无法展示透视金额";
  76. /** 11103/KLT-E00x 的结构化 detail 随应答 data 位下发;读不到 ⇒ 空对象(⛔ 前端拼句子)。 */
  77. type BizDetail = {
  78. field?: string;
  79. reason?: string;
  80. referring_plan_count?: number;
  81. cost_item_id?: string;
  82. fields?: { field?: string; reason?: string }[];
  83. };
  84. const bizDetail = (e: unknown): BizDetail => {
  85. const d = (e as ApiError | null)?.detail;
  86. return d && typeof d === "object" ? (d as BizDetail) : {};
  87. };
  88. /** 11103 ⇒ `detail.fields[].reason` 原文逐条(14.5「该字段由系统带出,不接受录入」同纪律)。 */
  89. const fieldReasons = (e: unknown): string[] =>
  90. (bizDetail(e).fields ?? []).map((item) => item?.reason ?? "").filter(Boolean);
  91. const errorMessage = (e: unknown): string => (e instanceof Error && e.message ? e.message : "");
  92. /** 成本项定义表单(字段与 `/cost_item/save@v1` 载荷一一对应;⛔ 后端⛔ 的字段如 cycle)。 */
  93. type CostDraft = {
  94. costItemId?: string;
  95. rowVersion: number | string | null;
  96. category: string;
  97. itemName: string;
  98. billingUnit: string;
  99. /** U-34:「是否摊销」默认不勾选。 */
  100. amortized: boolean;
  101. /** U-34:「总摊销月份数」选填且仅勾选时允许填;留空=每月摊销不结束。 */
  102. amortMonths: string;
  103. deduct: boolean;
  104. remark: string;
  105. };
  106. const emptyCostDraft = (): CostDraft => ({
  107. rowVersion: null,
  108. category: CATEGORY_OPTIONS[0].value,
  109. itemName: "",
  110. billingUnit: BILLING_OPTIONS[0].value,
  111. amortized: false,
  112. amortMonths: "",
  113. deduct: true,
  114. remark: "",
  115. });
  116. /**
  117. * 成本金额录入弹窗(按「省份 × 运营商」组合录入各成本项金额)。
  118. * `new`=新增组合(省份/运营商可选,已有组合⛔ 选);`edit`=改已有组合(两个下拉锁死)。
  119. * `cells` 存输入**原文**:空串=该项不配置(14.1.2:留空项=删除该差异行),不在输入期做数值归一。
  120. * `baseline`=打开弹窗那一刻的格值快照:只有真改过才提示「丢弃」,⛔ 把回填的基线当成未确认草稿。
  121. */
  122. type AmountForm = {
  123. mode: "new" | "edit";
  124. regionId: string;
  125. operatorId: string;
  126. cells: Record<string, string>;
  127. baseline: Record<string, string>;
  128. };
  129. /** 弹窗内是否有真改动(与打开时的快照逐格比)。 */
  130. const amountFormDirty = (form: AmountForm): boolean => Object.keys({ ...form.baseline, ...form.cells })
  131. .some((id) => (form.cells[id] ?? "") !== (form.baseline[id] ?? ""));
  132. function CostLedger({ kind, count = 0, children }: { kind: "definitions" | "matrix"; count?: number; children: ReactNode | ((expanded: boolean) => ReactNode) }) {
  133. const scroll = useHorizontalOverflow();
  134. const expanded = scroll.width >= 1680;
  135. /**
  136. * 定义表 11 列=序号/项目/成本类别/计算方式/周期/是否摊销/总摊销月份数/计入分成基数/
  137. * 金额配置情况/被套餐档引用/操作。⚠️ minimums 与 weights 必须逐列对齐(`OpsTableColumns`
  138. * 只按数组长度下发 `<col>`):少一项,多出的列在 `table-layout:fixed` 下宽度为 0,表头与内容被挤没。
  139. * 1500 窗口 ⇒ 表格容器≈1182px,故最小宽度合计收在 1156,避免无谓横向滚动。
  140. */
  141. const minimums = kind === "definitions" ? [56, 120, 76, 76, 56, 88, 132, 132, 148, 116, 156]
  142. : [110, 84, ...Array<number>(count).fill(110), 76, 142, 120];
  143. const weights = kind === "definitions" ? [0, 17, 10, 8, 7, 6, 8, 8, 24, 12, 0]
  144. : [0, 0, ...Array<number>(count).fill(1), 0, count ? 0 : 1, 0];
  145. const minWidth = minimums.reduce((total, minimum) => total + minimum, 0);
  146. const weightTotal = weights.reduce((total, weight) => total + weight, 0);
  147. const extraWidth = Math.max(0, scroll.width - minWidth);
  148. const columns = minimums.map((minimum, index) => minimum + extraWidth * weights[index] / weightTotal);
  149. return <div ref={scroll.ref} tabIndex={0} role="region" aria-label={{ definitions: "成本项定义表", matrix: "成本金额一览表" }[kind]} className={`measured-table-scroll ops-table-wrap cost-ledger-scroll cost-ledger-${kind}${scroll.overflow ? " has-horizontal-overflow" : ""}${scroll.width >= 640 ? " can-pin-identity" : ""}${scroll.canScrollLeft ? " can-scroll-left" : ""}${scroll.canScrollRight ? " can-scroll-right" : ""}`}>
  150. <table className="ops-table cost-ledger" style={{ minWidth }}><OpsTableColumns widths={columns} />{typeof children === "function" ? children(expanded) : children}</table>
  151. </div>;
  152. }
  153. export function CostManagementPage() {
  154. const { identity, organization, readOnly } = useBusinessView(["regions", "operators", "operationsTeams", "enterprises"]);
  155. const canEdit = !identity || identity.role === "admin";
  156. const visibleProvinceIds = new Set(onboardingRegions(organization, identity).map((id) => provinceId(organization, id)));
  157. const ownerProvinces = organization.regions.filter((region) => visibleProvinceIds.has(region.id));
  158. /**
  159. * 省份下拉=**省级**节点(`level` 为「省」)。
  160. * ⛔ 把层级为空(`level` 为 `null`)的根节点「全网」也列进来:它不是省份,选它等于给
  161. * 「全网 × 运营商」写金额行(后端只校验节点存在、不校验层级,脏行落库后才暴露)。
  162. * 层级投影整体缺失时(历史档案)退回区域直属口径,避免下拉为空、整页不可录入。
  163. */
  164. const levelProvinces = ownerProvinces.filter((region) => region.level === 0);
  165. const provinceNodes = levelProvinces.length ? levelProvinces : ownerProvinces;
  166. const provinceIds = new Set(provinceNodes.map((region) => region.id));
  167. /**
  168. * 可配组合=「可见省份 × 该省在册运营商」:后端 `cost_amount` 的唯一键是
  169. * `province_node_id × operator_id`(handler `cost.rs` 两侧分别校验区域维度与 operator 表),
  170. * 因此只列运营商档案真实归属到该省的组合,⛔ 造出「某省 × 该省未在册品牌」的假组合。
  171. */
  172. const operatorOptions = organization.operators.flatMap((item) => {
  173. const owner = item.region ? provinceId(organization, item.region) : undefined;
  174. return owner && provinceIds.has(owner)
  175. ? [{ id: item.id, name: item.name, brand: item.brand, provinceId: owner }]
  176. : [];
  177. });
  178. const allCombos = operatorOptions.map((item) => ({
  179. key: axisKey(item.provinceId, item.id),
  180. provinceId: item.provinceId,
  181. operatorId: item.id,
  182. }));
  183. /** 省份显示名:区域树优先(第 1 册口径);树里没有该节点时用后端 `bos_region_meta` 叶子名(`pivotProvinceNames`),
  184. * 都没有才回落节点 id(⛔ 把 id 当名字却不说来源)。 */
  185. const provinceNameOf = (id: string) => provinceNodes.find((region) => region.id === id)?.name ?? pivotProvinceNames.get(id) ?? id;
  186. const operatorNameOf = (id: string) => operatorOptions.find((item) => item.id === id)?.name ?? id;
  187. const [tab, setTab] = useState<"definitions" | "amounts">("definitions");
  188. const [query, setQuery] = useState("");
  189. const [kindFilter, setKindFilter] = useState("");
  190. const [matrixProvince, setMatrixProvince] = useState("");
  191. const [matrixBrand, setMatrixBrand] = useState("");
  192. const [defPage, setDefPage] = useState(0);
  193. const [searchQuery, setSearchQuery] = useState("");
  194. useEffect(() => {
  195. const timer = window.setTimeout(() => setSearchQuery(query.trim()), 300);
  196. return () => window.clearTimeout(timer);
  197. }, [query]);
  198. /**
  199. * 定义 tab 关键字/分类/分页下推;金额 tab 再拉透视(定义口 allPages 取满列头)。
  200. * 非当前 tab 不预拉另一口。
  201. */
  202. const items = useCostItems({
  203. keyword: tab === "definitions" ? searchQuery || undefined : undefined,
  204. category: tab === "definitions" ? (kindFilter || undefined) : undefined,
  205. page: tab === "definitions" ? defPage : 0,
  206. pageSize: LIST_PAGE_SIZE,
  207. allPages: tab === "amounts",
  208. });
  209. const amounts = useCostAmounts({ enabled: tab === "amounts" });
  210. /**
  211. * 「命中客户」列=按「省 × 运营商」组合向后端取客户数(D-2:旧实现读恒空的
  212. * localStorage 快照恒显 0 家)。仅金额 tab 启用;page_size=1 探针取 total,⛔ 全量拉取。
  213. */
  214. const comboCounts = useComboCustomerCounts(allCombos, tab === "amounts");
  215. /** D-3:后端 `available:false` 的技术 message 可能含迁移路径/表名,只打控制台日志,不向操作人渲染。 */
  216. useEffect(() => {
  217. if (amounts.data && !amounts.data.available && amounts.data.message) {
  218. console.warn("[costs] 金额透视 available:false,技术原因仅记日志不向操作人展示:", amounts.data.message);
  219. }
  220. }, [amounts.data?.available, amounts.data?.message]);
  221. /** 后端透视行自带的省份名(`bos_region_meta.path_name` 叶子)——区域树查不到该节点时兜底显示。 */
  222. const pivotProvinceNames = new Map<string, string>();
  223. for (const pivot of amounts.data?.combos ?? []) {
  224. if (pivot.provinceName) pivotProvinceNames.set(pivot.provinceNodeId, pivot.provinceName);
  225. }
  226. const saveItem = useSubmit();
  227. const saveAmount = useSubmit();
  228. /** 删除成本项(引用检查通过后真删;服务端仍会复判引用面)。 */
  229. const removeItem = useSubmit();
  230. /** 金额录入弹窗:`null`=关闭;`cells` 存输入原文(元),空串=该项不配置。 */
  231. const [amountForm, setAmountForm] = useState<AmountForm | null>(null);
  232. const [editing, setEditing] = useState<CostItemView | "new" | null>(null);
  233. const [draftDef, setDraftDef] = useState<CostDraft>(emptyCostDraft);
  234. const [error, setError] = useState("");
  235. /** 金额弹窗的错误行(提交失败/参数不合法;E006/E007 同时按成本项行内红显)。 */
  236. const [amountError, setAmountError] = useState("");
  237. const [notice, setNotice] = useState("");
  238. /** KLT-E001 ⇒「项目名称」框行内红显(14.1.1)。 */
  239. const [nameError, setNameError] = useState("");
  240. /** KLT-E006 ⇒ 行内红显该行(键=cost_item_id,文案带出当前上限)。 */
  241. const [cellErrors, setCellErrors] = useState<Record<string, string>>({});
  242. /** KLT-E007 ⇒ 该行输入框标灰+出路句(键=cost_item_id),不清空其余已填。 */
  243. const [staleItems, setStaleItems] = useState<Record<string, boolean>>({});
  244. /** KLT-E004 且 reason=no_province ⇒ 整页 ② 不可用。 */
  245. const [panelBlocked, setPanelBlocked] = useState("");
  246. /** 删除确认框选中的成本项(`null`=未打开);`deleteError` 只在框内显示。 */
  247. const [deleteTarget, setDeleteTarget] = useState<CostItemView | null>(null);
  248. const [deleteError, setDeleteError] = useState("");
  249. const costItems = items.data?.items ?? [];
  250. const costItemTotal = items.data?.total ?? costItems.length;
  251. /** 定义 tab:筛选已下推服务端;金额 tab:全量定义行作列头,本地不再按 query 二次筛。 */
  252. const filtered = useMemo(
  253. () => [...costItems].sort((a, b) => a.name.localeCompare(b.name, "zh-Hans-CN")),
  254. [costItems],
  255. );
  256. /**
  257. * 一览表运营商筛选的候选=「所选省份的在册品牌」(⚠️ 2026-11-15 业主改判:选省后只列该省的,
  258. * ⛔ 再恒列全部三值——那时选出来的组合恒为空表,用户会误读成「该省没配」)。
  259. * 未选省份(全部省份)时列全部可见省份的品牌。
  260. * ⚠️ 选项值取**品牌**而非档案 id:运营商档案按省各建一行(同省同品牌唯一),
  261. * 按档案 id 列会在「全部省份」下出现两条同名「移动」,且选中一条会把另一省的同品牌行筛掉。
  262. */
  263. const brandOfOperator = new Map(operatorOptions.map((item) => [item.id, item.brand || item.name]));
  264. const matrixBrandOptions = (() => {
  265. const scope = matrixProvince ? operatorOptions.filter((item) => item.provinceId === matrixProvince) : operatorOptions;
  266. const brands = [...new Set(scope.map((item) => brandOfOperator.get(item.id) ?? item.id))];
  267. return brands.sort((a, b) => {
  268. const ia = COST_BRAND_ORDER.indexOf(a); const ib = COST_BRAND_ORDER.indexOf(b);
  269. return (ia < 0 ? COST_BRAND_ORDER.length : ia) - (ib < 0 ? COST_BRAND_ORDER.length : ib)
  270. || a.localeCompare(b, "zh-Hans-CN");
  271. });
  272. })();
  273. const matrixRows = allCombos.filter((row) => (!matrixProvince || row.provinceId === matrixProvince)
  274. && (!matrixBrand || brandOfOperator.get(row.operatorId) === matrixBrand));
  275. const matrixPaging = useLocalPage(matrixRows.length);
  276. const filteredPage = filtered;
  277. const matrixPageRows = slicePage(matrixRows, matrixPaging.safePage);
  278. useEffect(() => { setDefPage(0); }, [searchQuery, kindFilter]);
  279. useEffect(() => { matrixPaging.resetPage(); }, [matrixProvince, matrixBrand]);
  280. /**
  281. * 已有金额行的组合(后端透视行=该组合至少配过一项金额)。
  282. * 「新增运营商成本」弹窗只列**尚未配过**的组合:同组合再选一次就是覆盖写,入口收在一览表行内「编辑金额」。
  283. */
  284. const configuredCombos = new Set((amounts.data?.combos ?? []).map((row) => axisKey(row.provinceNodeId, row.operatorId)));
  285. const isComboConfigured = (regionId: string, operatorId: string) => configuredCombos.has(axisKey(regionId, operatorId));
  286. /** 该格后端基线:`undefined`=无差异行(未配置),`null`=有行但金额为空,数字=已配金额(元)。 */
  287. const baselineOf = (regionId: string, operatorId: string, itemId: string) => amounts.data?.cells.get(costCellKey(regionId, operatorId, itemId));
  288. /** 该省在册运营商(组合第二维只取档案真实归属该省的,⛔ 造「某省 × 该省未在册」的假组合)。 */
  289. const operatorsOf = (regionId: string) => operatorOptions.filter((item) => item.provinceId === regionId);
  290. /** 该省还没配金额的运营商个数(省份下拉据此标「均已配置」并禁用该省)。 */
  291. const pendingCountOf = (regionId: string) => operatorsOf(regionId).filter((item) => !isComboConfigured(regionId, item.id)).length;
  292. /** 弹窗前置条件:成本项定义与金额基线都在手才开表单,否则只说明缺口(⛔ 开一个判不了「已有组合」的空表单)。 */
  293. function amountFormBlocked(): string {
  294. if (items.error) return `成本项定义取数失败:${items.error.message},不可录入金额。`;
  295. if (!costItems.length) return "「成本项定义」里还没有成本项,先新增成本项再录入金额。";
  296. if (amounts.error) return `金额一览取数失败:${amounts.error.message}——判不了哪些组合已有金额,先重试取数。`;
  297. if (!amounts.data) return "金额一览取数中,取到基线后再录入金额。";
  298. return "";
  299. }
  300. /** 打开金额弹窗:`new`=新增组合(可选预设组合),`edit`=改已有组合(省份/运营商锁死)。 */
  301. function openAmountForm(mode: AmountForm["mode"], preset?: { regionId: string; operatorId: string }) {
  302. if (!canEdit) return;
  303. const blocked = amountFormBlocked();
  304. if (blocked) { setNotice(blocked); return; }
  305. let target = preset ?? null;
  306. if (!target && mode === "new") {
  307. const region = provinceNodes.find((node) => pendingCountOf(node.id) > 0);
  308. const item = region ? operatorsOf(region.id).find((operator) => !isComboConfigured(region.id, operator.id)) : undefined;
  309. if (!region || !item) { setNotice("当前可见省份的在册运营商组合都已配好金额;要改金额请在一览表对应行点「编辑金额」。"); return; }
  310. target = { regionId: region.id, operatorId: item.id };
  311. }
  312. if (!target) return;
  313. const cells: Record<string, string> = {};
  314. if (mode === "edit") {
  315. for (const item of costItems) {
  316. const value = baselineOf(target.regionId, target.operatorId, item.id);
  317. if (typeof value === "number") cells[item.id] = String(value);
  318. }
  319. }
  320. setAmountError("");
  321. setCellErrors({});
  322. setStaleItems({});
  323. saveAmount.clear();
  324. setAmountForm({ mode, ...target, cells, baseline: cells });
  325. }
  326. /** 弹窗内换省份:运营商跟着落到该省首个**未配置**的;已填金额随成本项走,不清空。 */
  327. function pickFormRegion(regionId: string) {
  328. setAmountForm((current) => {
  329. if (!current) return current;
  330. const options = operatorsOf(regionId);
  331. const next = options.find((item) => current.mode === "edit" || !isComboConfigured(regionId, item.id)) ?? options[0];
  332. return { ...current, regionId, operatorId: next?.id ?? "" };
  333. });
  334. setAmountError("");
  335. }
  336. /**
  337. * 弹窗内换运营商=换组合(14.6:不保留跨组合草稿 ⇒ 已填金额清空并如实说明)。
  338. * ⚠️ 只在**真改过**金额时提示:空表单/只回填基线就切换,不算「丢弃修改」。
  339. */
  340. function pickFormOperator(operatorId: string) {
  341. if (!amountForm) return;
  342. const changed = amountFormDirty(amountForm);
  343. if (changed) setNotice(COST_UNSAVED_DISCARD_NOTE);
  344. setAmountForm({ ...amountForm, operatorId, cells: changed ? {} : amountForm.cells, baseline: changed ? {} : amountForm.baseline });
  345. setAmountError("");
  346. }
  347. /** 关闭弹窗:真改过但没确认的金额不落库,给出路句而不是静默丢失。 */
  348. function closeAmountForm() {
  349. if (amountForm && amountFormDirty(amountForm)) setNotice(COST_AMOUNT_DIALOG_DISCARD_NOTE);
  350. setAmountForm(null);
  351. setAmountError("");
  352. setCellErrors({});
  353. setStaleItems({});
  354. }
  355. function editAmountCell(itemId: string, raw: string) {
  356. setCellErrors((cur) => { if (!cur[itemId]) return cur; const next = { ...cur }; delete next[itemId]; return next; });
  357. setAmountForm((current) => current ? { ...current, cells: { ...current.cells, [itemId]: raw } } : current);
  358. }
  359. function startEdit(target: CostItemView | "new") {
  360. if (!canEdit) return;
  361. setEditing(target);
  362. setError("");
  363. setNameError("");
  364. saveItem.clear();
  365. setDraftDef(target === "new" ? emptyCostDraft() : {
  366. costItemId: target.id,
  367. rowVersion: target.rowVersion,
  368. category: target.categoryKey ?? CATEGORY_OPTIONS[0].value,
  369. itemName: target.name,
  370. billingUnit: target.billingUnitKey ?? BILLING_OPTIONS[0].value,
  371. amortized: target.amortized === true,
  372. amortMonths: target.amortizationMonths === null ? "" : String(target.amortizationMonths),
  373. deduct: target.deduct ?? true,
  374. remark: target.remark ?? "",
  375. });
  376. }
  377. /** 新增/编辑成本项失败分支(14.1.1/14.6):弹窗不关、已填保留;KLT-E001 行内红显「项目名称」框。 */
  378. function classifyDefinitionError(e: unknown) {
  379. const detail = bizDetail(e);
  380. if (hasBizCode(e, "KLT-E001")) { setNameError(errorMessage(e)); return; }
  381. if (hasBizCode(e, "KLT-E002")) { setError(costRefBlocked(typeof detail.referring_plan_count === "number" ? detail.referring_plan_count : null)); return; }
  382. if (hasBizCode(e, "KLT-S407")) { setError(COST_CONFLICT_NOTE); return; }
  383. const reasons = fieldReasons(e);
  384. if (hasBizCode(e, "11103") && reasons.length) setError(reasons.join(";"));
  385. }
  386. async function submitDefinition() {
  387. if (!canEdit) return;
  388. const name = draftDef.itemName.trim();
  389. if (name.length < 2 || name.length > 64) return setError("成本项名称须为 2–64 个字符。");
  390. let months: number | undefined;
  391. const monthsText = draftDef.amortMonths.trim();
  392. // U-34:仅勾选「是否摊销」时允许填月份数;留空=每月摊销不结束(载荷不下发月份数);未勾选时给了值 ⇒ 后端 11103(表单压根不提交)。
  393. if (draftDef.amortized && monthsText !== "") {
  394. const parsed = Number(monthsText);
  395. if (!Number.isSafeInteger(parsed) || parsed < 1) return setError("总摊销月份数须为大于 0 的整数(留空表示每月摊销、不结束)。");
  396. months = parsed;
  397. }
  398. if (costItems.some((item) => item.name === name && item.id !== draftDef.costItemId)) return setError(`已有同名成本项「${name}」,全局同名只记一条。`);
  399. setError("");
  400. setNameError("");
  401. const ok = await saveItem.run(() => costItemSave({
  402. category: draftDef.category,
  403. item_name: name,
  404. billing_unit: draftDef.billingUnit,
  405. is_amortized: draftDef.amortized,
  406. deduct_from_base: draftDef.deduct,
  407. amortization_months: draftDef.amortized ? months : undefined,
  408. remark: draftDef.remark.trim() || undefined,
  409. cost_item_id: draftDef.costItemId,
  410. row_version: typeof draftDef.rowVersion === "number" ? draftDef.rowVersion : undefined,
  411. }).catch((e: unknown) => { classifyDefinitionError(e); throw e; }));
  412. if (!ok) return;
  413. setEditing(null);
  414. items.reload();
  415. setNotice(draftDef.costItemId
  416. ? `成本项「${name}」已保存;此后出账按新定义计入,已出账月份保留当月快照。`
  417. : `成本项「${name}」已新增,请切到「成本金额定义」标签页选到对应的「省份 × 运营商」组合后录入该组合的金额;本条${draftDef.deduct ? "从分成基数扣除" : "不从分成基数扣除"}。`);
  418. }
  419. /**
  420. * 删除成本项(契约 14.6):先开二次确认框;「能否删除」由服务端按 `plan_cost_item.cost_item_id`
  421. * id 强引用复判——页面只在**后端明确回了 0 个引用**时放行入口,`null`(未下发概况)一律不开。
  422. */
  423. function startDelete(item: CostItemView) {
  424. if (!canEdit) return;
  425. if (item.referringPlans === null) {
  426. setNotice("后端未下发「被套餐档引用」概况,判不了这项能否删除;请刷新列表后再试。");
  427. return;
  428. }
  429. if (item.referringPlans.length > 0) { setNotice(costRefBlocked(item.referringPlans.length)); return; }
  430. setDeleteError("");
  431. removeItem.clear();
  432. setDeleteTarget(item);
  433. }
  434. async function confirmDelete() {
  435. if (!canEdit || !deleteTarget) return;
  436. const target = deleteTarget;
  437. const ok = await removeItem.run(() => costItemDelete({ cost_item_id: target.id }).catch((e: unknown) => {
  438. const detail = bizDetail(e);
  439. if (hasBizCode(e, "KLT-E002")) {
  440. // 页面状态过期(开框后才被档位引用)⇒ 框内给引用档位数+「先在档位上解除引用」,并刷新引用面。
  441. setDeleteError(costRefBlocked(typeof detail.referring_plan_count === "number" ? detail.referring_plan_count : null));
  442. items.reload();
  443. throw e;
  444. }
  445. if (hasBizCode(e, "60005")) {
  446. setDeleteError("这项已被删除或不存在,刷新列表后重试。");
  447. items.reload();
  448. throw e;
  449. }
  450. setDeleteError(errorMessage(e) || "删除失败,请重试。");
  451. throw e;
  452. }));
  453. if (!ok) return;
  454. setDeleteTarget(null);
  455. items.reload();
  456. amounts.reload();
  457. setNotice(`成本项「${target.name}」已删除。${COST_DELETE_CONFIRM_NOTE}。`);
  458. }
  459. /**
  460. * 一览表省份筛选:换省或改回「全部省份」时,若已选的品牌不在新候选里就一并清空,
  461. * 否则残留的品牌筛选会把新省份的列表筛成空表(用户会误读成「该省无组合」)。
  462. */
  463. function changeMatrixProvince(next: string) {
  464. setMatrixProvince(next);
  465. setMatrixBrand((current) => {
  466. if (!current || !next) return current;
  467. const available = new Set(operatorOptions.filter((item) => item.provinceId === next).map((item) => item.brand || item.name));
  468. return available.has(current) ? current : "";
  469. });
  470. }
  471. /** 保存组合金额失败分支(14.1.2/14.6):弹窗保持、已填全保留;E006 行内红显该行;E007 该行标灰出路;E004 按 reason 两文案;S407 重载并清空已填。 */
  472. function classifyAmountError(e: unknown) {
  473. const detail = bizDetail(e);
  474. if (hasBizCode(e, "KLT-E006")) {
  475. const message = errorMessage(e);
  476. if (detail.cost_item_id) setCellErrors((cur) => ({ ...cur, [detail.cost_item_id as string]: message }));
  477. setAmountError(message);
  478. return;
  479. }
  480. if (hasBizCode(e, "KLT-E007")) {
  481. if (detail.cost_item_id) setStaleItems((cur) => ({ ...cur, [detail.cost_item_id as string]: true }));
  482. setAmountError(COST_STALE_PANEL_NOTE);
  483. return;
  484. }
  485. if (hasBizCode(e, "KLT-E004")) {
  486. // not_province_node ⇒ 只红显该行(当前组合,服务端原文);no_province ⇒ 整页 ② 不可用+出路句(两文案必须不同)。
  487. if (detail.reason === "no_province") { setPanelBlocked(COST_NO_PROVINCE_NOTE); setAmountForm(null); }
  488. else setAmountError(errorMessage(e));
  489. return;
  490. }
  491. if (hasBizCode(e, "KLT-E005")) { setAmountError(COST_COMBO_FORBIDDEN); return; }
  492. if (hasBizCode(e, "KLT-S407")) {
  493. // 通用冲突码 ⇒ 重载基线、金额以库为准、不保留本地已填顺序(弹窗留着,格子清空)。
  494. setAmountForm((current) => current ? { ...current, cells: {} } : current);
  495. amounts.reload();
  496. setAmountError(CONFIG_CONFLICT_NOTE);
  497. return;
  498. }
  499. const reasons = fieldReasons(e);
  500. if (hasBizCode(e, "11103") && reasons.length) setAmountError(reasons.join(";"));
  501. }
  502. /**
  503. * 弹窗确认:按「省份 × 运营商」提交**差异**金额(契约 14.1.2:留空项=删除该差异行)。
  504. * ⚠️ 只写差异:与后端基线相同的格不发;新增组合的基线恒为空 ⇒ 只发已填项。
  505. */
  506. async function submitAmountForm() {
  507. if (!canEdit || !amountForm) return;
  508. const blocked = amountFormBlocked();
  509. if (blocked) { setAmountError(blocked); return; }
  510. const { mode, regionId, operatorId, cells } = amountForm;
  511. if (!regionId || !operatorId) { setAmountError("请选择省份与该省在册运营商。"); return; }
  512. if (mode === "new" && isComboConfigured(regionId, operatorId)) { setAmountError("该「省份 × 运营商」组合已有金额,请在一览表对应行点「编辑金额」。"); return; }
  513. const payload: { cost_item_id: string; amount_cents?: number }[] = [];
  514. const nextErrors: Record<string, string> = {};
  515. for (const item of costItems) {
  516. const raw = (cells[item.id] ?? "").trim();
  517. const baseline = mode === "edit" ? baselineOf(regionId, operatorId, item.id) : undefined;
  518. if (raw === "") { if (typeof baseline === "number") payload.push({ cost_item_id: item.id }); continue; }
  519. const value = Number(raw);
  520. if (!Number.isFinite(value) || value < 0) { nextErrors[item.id] = `成本项「${item.name}」的金额请填写正确的非负数值(留空才表示不配置)。`; continue; }
  521. if (baseline === value) continue;
  522. payload.push({ cost_item_id: item.id, amount_cents: Math.round(value * 100) });
  523. }
  524. if (Object.keys(nextErrors).length) { setCellErrors(nextErrors); setAmountError("有金额填写不正确,按行修改后再确认。"); return; }
  525. if (!payload.length) {
  526. setAmountError(mode === "new" ? "请至少填一个成本项的金额:全部留空=这套组合没有任何金额可落库。" : "本组合没有需要保存的改动。");
  527. return;
  528. }
  529. setAmountError("");
  530. setCellErrors({});
  531. setStaleItems({});
  532. const ok = await saveAmount.run(() => costAmountSave({ province_node_id: regionId, operator_id: operatorId, items: payload })
  533. .catch((e: unknown) => { classifyAmountError(e); throw e; }));
  534. if (!ok) return;
  535. setAmountForm(null);
  536. amounts.reload();
  537. items.reload();
  538. /** 成功提示按 effective_mode 二选一(14.5:文案由后端随配置返回,⛔ 前端自行判断;
  539. * 配置读口未接线 ⇒ CONFIG_SAVED_NOTE 常量兜底(默认 period_snapshot 句),待后端随配置返回后改读响应)。 */
  540. setNotice(`已提交 ${payload.length} 条金额(${provinceNameOf(regionId)} × ${operatorNameOf(operatorId)})。${CONFIG_SAVED_NOTE.period_snapshot}`);
  541. }
  542. /** 后端透视返回、但不在「可见省份 × 该省在册运营商」档案范围内的组合(口径不一致时如实说明)。 */
  543. const pivotExtras = (amounts.data?.combos ?? []).filter((row) => !allCombos.some((item) => item.key === axisKey(row.provinceNodeId, row.operatorId)));
  544. /** 金额格三态:取数失败/后端未下发/真实未配置(灰显 0 是 14.1.2 的口径,不是兜底值)。 */
  545. function amountCell(itemId: string, pivotRow: CostComboView | undefined): ReactNode {
  546. if (amounts.error) return <Tri tone="fail" text={WORD_FETCH_FAILED} title={`金额一览取数失败:${amounts.error?.message ?? ""}`} />;
  547. if (!amounts.data) return <Tri tone="missing" text="取数中…" title="金额一览取数中…" />;
  548. if (!amounts.data.available) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title={`后端 available:false,透视表本期无行 ⇒ 既不能判定「未配置」也不能判定为 0。${AMOUNT_UNAVAILABLE_NOTE}`} />;
  549. if (!pivotRow) return <span className="ops-matrix-unset" title="后端没有该「省份 × 运营商」的金额行=整套未配置(按 0 元 / 月计)">0</span>;
  550. const value = pivotRow.amounts.get(itemId);
  551. if (value === undefined) return <span className="ops-matrix-unset" title="该组合已配其他成本项,这一项没有差异行=未配置(按 0 元 / 月计)">0</span>;
  552. if (value === null) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端下发该格但 amount_cents 为空" />;
  553. return <span className="ops-money">{yuan(value)}</span>;
  554. }
  555. function rowTotal(pivotRow: CostComboView | undefined): ReactNode {
  556. if (amounts.error) return <Tri tone="fail" text={WORD_FETCH_FAILED} title="金额一览取数失败,合计不可算" />;
  557. if (!amounts.data) return <Tri tone="missing" text="取数中…" title="金额一览取数中…" />;
  558. if (!amounts.data.available) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端透视表本期无行 ⇒ 合计不可算" />;
  559. if (!pivotRow) return <span className="ops-matrix-unset" title="该组合未配置任何金额=0">0</span>;
  560. let sum = 0;
  561. for (const item of costItems) {
  562. const value = pivotRow.amounts.get(item.id);
  563. if (value === undefined) continue;
  564. if (value === null) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="该组合存在金额为空的格 ⇒ 合计不完整" />;
  565. sum += value;
  566. }
  567. return <span className="ops-money">{yuan(sum)}</span>;
  568. }
  569. /** 命中客户数三态:取数失败/取数中/真值(D-2:真值来自后端 customer/get_list 现算 total)。 */
  570. function hitCountCell(rowKey: string): ReactNode {
  571. if (comboCounts.error) return <span title={`命中客户取数失败:${comboCounts.error.message ?? ""}`}>—</span>;
  572. if (!comboCounts.data) return <span title="命中客户取数中">…</span>;
  573. return <span className="table-number">{comboCounts.data.get(rowKey) ?? 0} 家</span>;
  574. }
  575. if (readOnly) return <div className="ops-empty">当前身份无权查看成本配置。</div>;
  576. return <section className="ops-page ops-page--costs page-fill page-fill-window"><header className="ops-heading"><div><h1>成本管理</h1><PageIntro>为不同区域和运营商设定适用的成本金额,作为出账核算的依据。</PageIntro></div></header>
  577. <div className="ops-list-shell list-shell-fill">
  578. <div className="ops-tabs" role="tablist" aria-label="成本管理视图"><button role="tab" aria-selected={tab === "definitions"} className={tab === "definitions" ? "active" : ""} onClick={() => setTab("definitions")}>成本项定义 <span>{costItemTotal}</span></button><button role="tab" aria-selected={tab === "amounts"} className={tab === "amounts" ? "active" : ""} onClick={() => setTab("amounts")}>成本金额定义 <span>{allCombos.length}</span></button></div>
  579. {tab === "definitions" ? <>
  580. <div className="ops-toolbar">
  581. <label className="ops-search"><Search size={17} /><Input aria-label="搜索成本项" placeholder="输入关键字,例如 带宽" value={query} onChange={(event) => setQuery(event.target.value)} />{query && <button type="button" aria-label="清空搜索" onClick={() => setQuery("")}><X size={15} /></button>}</label>
  582. <FilterSelect icon="type" aria-label="成本类别筛选" value={kindFilter} onChange={(event) => setKindFilter(event.target.value)}><option value="">全部成本类别</option>{CATEGORY_OPTIONS.map((item) => <option key={item.value} value={item.value}>{item.text}</option>)}</FilterSelect>
  583. {(kindFilter || query) && <Button variant="ghost" size="sm" onClick={() => { setKindFilter(""); setQuery(""); setDefPage(0); }}>重置筛选</Button>}
  584. <div className="ops-toolbar-end">{canEdit ? <Button onClick={() => startEdit("new")}><Plus size={16} />新增成本项</Button> : <span className="ops-muted">只读</span>}</div>
  585. </div>
  586. <CostLedger key="definitions" kind="definitions">{(expanded) => <><thead><tr><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>{filteredPage.map((item, index) => { const noCycle = item.amortized === null && item.amortizationMonths === null; const deduct = boolView(item.deduct, "是(计入分成基数)", "否(不扣基数)"); return <tr key={item.id}>
  587. <td><span className="ops-mono table-number">{String(defPage * LIST_PAGE_SIZE + index + 1).padStart(2, "0")}</span></td>
  588. <td><strong className="table-cell-title" title={item.name}>{item.name}</strong></td>
  589. <td><Tri tone={item.category.pending ? "missing" : "val"} text={item.category.text} title={item.category.pending ? "该历史行 category 未灌值(20261107000002 补列前的存量行、名称不在回填映射内)⇒ 只标「后端未下发」,不折算成任一类别" : `后端 category=${item.categoryKey ?? ""}`} /></td>
  590. <td><Tri tone={item.calc.pending ? "missing" : "val"} text={item.calc.text} title={item.calc.pending ? "该历史行 billing_unit 未灌值(同上)" : `后端 billing_unit=${item.billingUnitKey ?? ""}`} /></td>
  591. <td><Tri tone={item.cycle.pending ? "missing" : "val"} text={item.cycle.text} title={item.cycle.pending ? "该历史行 cycle 未灌值(20261115000005 补列前的存量行)" : `后端 cycle=${item.cycleKey ?? ""}(设计册 分成§2.1:一期恒 monthly)`} />{expanded && item.remark ? <small className="ops-muted"> {item.remark}</small> : null}</td>
  592. <td>{noCycle ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="该历史行 is_amortized 未灌值 ⇒ 不折算「否」" /> : <OpsStatus tone={item.amortized ? "success" : "neutral"}>{item.amortized ? "是" : "否"}</OpsStatus>}</td>
  593. <td>{noCycle ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="该历史行 amortization_months 未灌值" /> : <span>{item.amortized ? (item.amortizationMonths === null ? "每月摊销(不结束)" : <span className="ops-mono table-number">{item.amortizationMonths} 个月</span>) : <span className="table-placeholder">—</span>}</span>}</td>
  594. <td>{deduct.pending ? <Tri tone="missing" text={deduct.text} title="该历史行 deduct_from_base 未灌值 ⇒ 不折算成「否」" /> : <OpsStatus tone={item.deduct ? "success" : "neutral"}>{deduct.text}</OpsStatus>}</td>
  595. <td>{item.configuredComboCount === null
  596. ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端未下发「已配组合数/月度合计」概况列" />
  597. : item.configuredComboCount === 0
  598. ? (item.configuredRowCount ?? 0) > 0
  599. ? <span title={`后端 cost_amount 有 ${item.configuredRowCount} 条金额行,但都缺省份/运营商轴,无法进入「省份 × 运营商」透视(见金额一览说明)`}>0 个可用组合<small className="ops-muted"> · {item.configuredRowCount} 条金额行缺省份/运营商轴</small></span>
  600. : <small className="ops-muted">尚未配置任何组合(按 0 元 / 月计)</small>
  601. : <span title={`后端 cost_amount 现算:${item.configuredComboCount} 个「省份 × 运营商」组合有金额行`}>已配 <b className="table-number">{item.configuredComboCount}</b> 个组合<small className="ops-muted"> · 月合计 <span className="table-number">{yuan((item.configuredTotalCents ?? 0) / 100)}</span></small></span>}</td>
  602. <td>{item.referringPlans === null
  603. ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端未下发套餐档引用概况" />
  604. : item.referringPlans.length
  605. ? item.referringPlans.map((plan) => <small className="ops-stacked" title={`档位 ID:${plan.id}(按 plan_cost_item.cost_item_id 强引用,改成本项名不断引用)`} key={plan.id}>{plan.name}</small>)
  606. : <span className="ops-mono table-number" title="后端现算:plan_cost_item 里没有 cost_item_id 指向该成本项的引用行(未被引用 ⇒ 可删除)">0</span>}</td>
  607. <td>{canEdit ? <div className="ops-inline-actions"><button type="button" onClick={() => startEdit(item)}><PencilLine size={15} />编辑定义</button><OpsResponsiveActions expanded={expanded} items={[{ label: "删除成本项", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, disabled: (item.referringPlans?.length ?? 1) !== 0, title: item.referringPlans === null ? "后端未下发「被套餐档引用」概况,判不了能否删除" : item.referringPlans.length ? `被 ${item.referringPlans.length} 个套餐档引用,先在档位上解除引用` : "未被任何套餐档引用,可删除", onSelect: () => startDelete(item) }]} /></div> : <small className="ops-muted">只读(全局成本项定义由总运营维护)</small>}</td>
  608. </tr>; })}{(items.error || !filtered.length) && <OpsTableEmpty colSpan={11} kind={items.error ? "error" : items.loading ? "loading" : "empty"} details={items.error?.message} onRetry={items.error ? items.reload : undefined}>
  609. {items.error ? "成本项加载失败" : items.loading ? "正在读取成本项…" : query || kindFilter ? "没有符合筛选条件的成本项" : "暂无成本项"}
  610. </OpsTableEmpty>}</tbody></>}</CostLedger>
  611. {!items.error && !items.loading && <ListPager total={costItemTotal} page={defPage} pageSize={LIST_PAGE_SIZE} onPageChange={setDefPage} />}
  612. </> : panelBlocked ? <div className="ops-empty" role="alert"><h1>成本金额暂不可用</h1><p>{panelBlocked}(KLT-E004 · no_province)</p></div> : <>
  613. <div className="ops-toolbar">
  614. <FilterSelect icon="region" aria-label="一览表省份筛选" value={matrixProvince} onChange={(event) => changeMatrixProvince(event.target.value)}><option value="">全部省份</option>{provinceNodes.map((region) => <option key={region.id} value={region.id}>{region.name}</option>)}</FilterSelect>
  615. <FilterSelect icon="operator" aria-label="一览表运营商筛选" value={matrixBrand} onChange={(event) => setMatrixBrand(event.target.value)}><option value="">全部运营商</option>{matrixBrandOptions.map((brand) => <option key={brand} value={brand}>{brand}</option>)}</FilterSelect>
  616. {(matrixProvince || matrixBrand) && <Button variant="ghost" size="sm" onClick={() => { setMatrixProvince(""); setMatrixBrand(""); }}>重置筛选</Button>}
  617. {amounts.data && !amounts.error && !amounts.data.available && <p className="ops-form-error" role="alert">后端金额一览 available:false:{AMOUNT_UNAVAILABLE_NOTE}(明细 {amounts.data.rowsTotal} 行、其中 {amounts.data.unattributedTotal} 行缺省份/运营商轴)⇒ 下表金额格一律标「后端未下发」,不得写成「空数据」或 0。</p>}
  618. <div className="ops-toolbar-end">{canEdit ? <Button onClick={() => openAmountForm("new")}><Plus size={16} />新增运营商成本</Button> : <span className="ops-muted">只读(金额由总运营维护)</span>}</div>
  619. </div>
  620. <CostLedger key="matrix" kind="matrix" count={costItems.length}><thead><tr><th>省份</th><th>运营商</th>{costItems.map((item) => <th key={item.id}>{item.name}<small>({item.calc.pending ? WORD_NOT_PROVIDED : item.calc.text})</small></th>)}<th>命中客户</th><th>摊销额合计(元 / 月)</th><th>操作</th></tr></thead><tbody>{amounts.error && <OpsTableEmpty colSpan={costItems.length + 5} kind="error" details={amounts.error.message} onRetry={amounts.reload}>成本金额加载失败</OpsTableEmpty>}{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 <tr key={row.key}>
  621. <td><strong>{provinceNameOf(row.provinceId)}</strong></td>
  622. <td>{operatorNameOf(row.operatorId)}</td>
  623. {costItems.map((item) => <td key={item.id}>{amountCell(item.id, pivotRow)}</td>)}
  624. <td title="该省(含下级)归属该运营商的客户数,由后端 customer/get_list 按可见范围现算">{hitCountCell(row.key)}</td>
  625. <td>{rowTotal(pivotRow)}</td>
  626. <td>{!canEdit ? <small className="ops-muted">只读</small> : <div className="ops-inline-actions"><button type="button" onClick={() => openAmountForm(configured ? "edit" : "new", { regionId: row.provinceId, operatorId: row.operatorId })}><PencilLine size={15} />{configured ? "编辑金额" : "录入金额"}</button></div>}</td>
  627. </tr>; })}{!amounts.error && !matrixRows.length && <OpsTableEmpty colSpan={costItems.length + 5}>{!allCombos.length ? "暂无可配置成本金额的运营商" : "没有符合筛选条件的区域与运营商组合"}</OpsTableEmpty>}</tbody></CostLedger>
  628. <ListPager total={matrixRows.length} page={matrixPaging.safePage} pageSize={matrixPaging.pageSize} onPageChange={matrixPaging.setPage} unit="个" />
  629. {pivotExtras.length > 0 && <p className="ops-muted">后端透视另返回 {pivotExtras.length} 个「省份节点 × 运营商」组合不在当前可见档案范围内(区域/运营商口径不一致),未列入上表。</p>}
  630. </>}
  631. </div>
  632. {amountForm && <div className="ops-confirm-backdrop" role="presentation" onMouseDown={closeAmountForm}><div className="ops-batch-dialog ops-cost-amount-dialog" role="dialog" aria-modal="true" aria-labelledby="cost-amount-title" onMouseDown={(event) => event.stopPropagation()}>
  633. <header><div><p>成本管理 / 成本金额定义</p><h2 id="cost-amount-title">{amountForm.mode === "new" ? "新增运营商成本" : "编辑运营商成本"}</h2></div><Button variant="ghost" size="icon" aria-label="关闭" onClick={closeAmountForm}><X size={18} /></Button></header>
  634. <div className="ops-batch-dialog-body">
  635. <div className="ops-form-grid">
  636. <label><span className="ops-field-title">省份 <b>*</b><FieldHint label="省份说明">{amountForm.mode === "edit" ? "改金额不改组合:省份与运营商在已有组合上锁死。" : "只列还有未配运营商的省份;括号内是该省可新增的运营商数。"}</FieldHint></span><select value={amountForm.regionId} disabled={amountForm.mode === "edit"} onChange={(event) => pickFormRegion(event.target.value)}>{provinceNodes.map((region) => { const count = operatorsOf(region.id).length; const pending = pendingCountOf(region.id); return <option key={region.id} value={region.id} disabled={!count || (amountForm.mode === "new" && pending === 0)}>{region.name}{!count ? "(无在册运营商)" : pending === 0 ? "(均已配置)" : `(可新增 ${pending} 个运营商)`}</option>; })}</select></label>
  637. <label><span className="ops-field-title">运营商 <b>*</b><FieldHint label="运营商说明">新增时已有金额的组合在下拉里禁用;改金额请到一览表行内「编辑金额」。省份与运营商在已有组合上锁死,⛔ 借编辑改组合。</FieldHint></span><select value={amountForm.operatorId} disabled={amountForm.mode === "edit"} onChange={(event) => pickFormOperator(event.target.value)}>{operatorsOf(amountForm.regionId).length ? operatorsOf(amountForm.regionId).map((item) => { const configured = isComboConfigured(amountForm.regionId, item.id); return <option key={item.id} value={item.id} disabled={amountForm.mode === "new" && configured}>{item.name}{configured ? "(已有金额)" : ""}</option>; }) : <option value="">该省无在册运营商</option>}</select></label>
  638. </div>
  639. <div className="ops-cost-amount-rows">
  640. <div className="ops-cost-amount-row ops-cost-amount-row--head" aria-hidden="true"><span>成本项</span><span>计算方式</span><span>具体金额(元 / 月)</span></div>
  641. {costItems.map((item) => { const deduct = boolView(item.deduct, "计入基数", "不扣基数"); return <label key={item.id} className="ops-cost-amount-row">
  642. <span><strong title={item.name}>{item.name}</strong><small>{item.category.pending ? WORD_NOT_PROVIDED : item.category.text}{item.amortized ? ` · ${item.amortizationMonths === null ? "每月摊销,不结束" : `摊销 ${item.amortizationMonths} 个月`}` : ""}{deduct.pending ? "" : ` · ${deduct.text}`}</small></span>
  643. <span className="ops-muted">{item.calc.pending ? WORD_NOT_PROVIDED : item.calc.text}</span>
  644. <span className="ops-cost-amount-input">
  645. <Input disabled={Boolean(staleItems[item.id])} className="ops-cost-input" type="number" min="0" step="0.01" aria-invalid={Boolean(cellErrors[item.id]) || undefined} aria-label={`${item.name}在${provinceNameOf(amountForm.regionId)} × ${operatorNameOf(amountForm.operatorId)}的金额`} value={amountForm.cells[item.id] ?? ""} onChange={(event) => editAmountCell(item.id, event.target.value)} placeholder={staleItems[item.id] ? "已失效" : "留空=该项不配置"} />
  646. {cellErrors[item.id] && <small className="ops-form-error" role="alert">{cellErrors[item.id]}</small>}
  647. {staleItems[item.id] && <small className="ops-form-error" role="alert">{COST_STALE_PANEL_NOTE}</small>}
  648. </span>
  649. </label>; })}
  650. </div>
  651. {amounts.data && !amounts.data.available && <p className="ops-form-error" role="alert">后端金额一览 available:false({AMOUNT_UNAVAILABLE_NOTE})⇒ 判不出哪些组合已有金额:已有组合请走一览表行内「编辑金额」,本弹窗只用于新增,不得拿它覆盖已有组合。</p>}
  652. {amountError || (saveAmount.error && !saveAmount.busy) ? <p className="ops-form-error" role="alert">{amountError || `金额保存失败:${saveAmount.error?.message ?? ""}`}</p> : null}
  653. {/* ⛔ 弹窗底部不再挂「只提交本次改动过的格子(契约 14.1.2)…」整段说明(2026-11-18 业主指出):
  654. 那段是跨两种模式的通用口径,放在「编辑运营商成本」里有一半句子(新增组合才写、去一览表点编辑金额)
  655. 与当前场景相悖,且把契约编号等实现口径摆给操作人看。「留空=该项不配置」由每行输入框的
  656. placeholder 承担,「已配金额的组合不在此新增」由运营商下拉禁用+「(已有金额)」承担。 */}
  657. </div>
  658. <footer><Button variant="outline" onClick={closeAmountForm}>取消</Button><Button disabled={saveAmount.busy} onClick={submitAmountForm}>{saveAmount.busy ? "保存中…" : amountForm.mode === "new" ? "确认新增" : "确认保存"}</Button></footer>
  659. </div></div>}
  660. {editing !== null && <div className="ops-confirm-backdrop" role="presentation" onMouseDown={() => setEditing(null)}><div className="ops-batch-dialog ops-cost-def-dialog" role="dialog" aria-modal="true" aria-labelledby="cost-def-title" onMouseDown={(event) => event.stopPropagation()}>
  661. <header><div><p>成本管理 / 成本项定义</p><h2 id="cost-def-title">{editing === "new" ? "新增成本项" : "编辑成本项定义"}</h2></div><Button variant="ghost" size="icon" aria-label="关闭" onClick={() => setEditing(null)}><X size={18} /></Button></header>
  662. <div className="ops-batch-dialog-body">
  663. <div className="ops-form-grid">
  664. <label><span className="ops-field-title">成本类别 <b>*</b></span><select value={draftDef.category} onChange={(event) => setDraftDef({ ...draftDef, category: event.target.value })}>{CATEGORY_OPTIONS.map((item) => <option key={item.value} value={item.value}>{item.text}</option>)}</select></label>
  665. <label><span className="ops-field-title">项目(成本项名称) <b>*</b></span><Input aria-invalid={Boolean(nameError) || undefined} value={draftDef.itemName} onChange={(event) => { setDraftDef({ ...draftDef, itemName: event.target.value }); if (nameError) setNameError(""); }} placeholder="例如 国际出口带宽月摊销" />{nameError && <small className="ops-form-error" role="alert">{nameError}</small>}</label>
  666. <label><span className="ops-field-title">计算方式</span><select value={draftDef.billingUnit} onChange={(event) => setDraftDef({ ...draftDef, billingUnit: event.target.value })}>{BILLING_OPTIONS.map((item) => <option key={item.value} value={item.value}>{item.text}</option>)}</select></label>
  667. <label><span className="ops-field-title">周期<FieldHint label="周期说明">周期一期恒 monthly(设计册 分成§2.1,后端 CHECK 钉死),由服务端写常量;表单不提交该键。</FieldHint></span><select value="monthly" disabled><option value="monthly">{COST_CYCLE.monthly}</option></select></label>
  668. <div className="ops-form-check-row">
  669. <label className="ops-form-check"><input type="checkbox" checked={draftDef.amortized} onChange={(event) => setDraftDef({ ...draftDef, amortized: event.target.checked, amortMonths: event.target.checked ? draftDef.amortMonths : "" })} title="勾选后可填「总摊销月份数」;取消勾选立即清空并置灰" />是否摊销</label>
  670. <OpsHint label="「是否摊销」口径说明" title="是否摊销">{COST_AMORTIZED_HINT.map((line) => <p key={line}>{line}</p>)}</OpsHint>
  671. </div>
  672. <label><span className="ops-field-title">总摊销月份数<FieldHint label="总摊销月份数说明">留空表示每月摊销、不结束;填值须为正整数。需先勾选「是否摊销」才可填。</FieldHint></span><Input type="number" min="1" step="1" disabled={!draftDef.amortized} placeholder={draftDef.amortized ? "留空表示每月摊销、不结束" : "勾选「是否摊销」后可填"} value={draftDef.amortMonths} onChange={(event) => setDraftDef({ ...draftDef, amortMonths: event.target.value })} /></label>
  673. <div className="ops-form-check-row">
  674. <label className="ops-form-check"><input type="checkbox" checked={draftDef.deduct} onChange={(event) => setDraftDef({ ...draftDef, deduct: event.target.checked })} />从分成基数中扣除</label>
  675. <OpsHint label="「从分成基数中扣除」口径说明" title="从分成基数中扣除">{COST_DEDUCT_HINT.map((line) => <p key={line}>{line}</p>)}</OpsHint>
  676. </div>
  677. </div>
  678. {(error || (!nameError && saveItem.error)) && <p className="ops-form-error" role="alert">{error || `保存失败:${saveItem.error?.message ?? ""}(后端校验:11102 乐观锁冲突/11103 参数不合法)`}</p>}
  679. {editing !== "new" && draftDef.rowVersion === null && <p className="ops-import-note">该行后端未下发 row_version ⇒ 本次保存不带乐观锁,他人同时修改不会被拦下。</p>}
  680. {editing !== "new" && (editing.categoryKey === null || editing.billingUnitKey === null || editing.deduct === null) && <p className="ops-import-note">该行的 category/billing_unit/deduct_from_base 后端本期未灌值(columns_pending),表单已按默认值预填——保存会把预填值真实写入这些列。</p>}
  681. </div>
  682. <footer><Button variant="outline" onClick={() => setEditing(null)}>取消</Button><Button disabled={saveItem.busy} onClick={submitDefinition}>{saveItem.busy ? "保存中…" : editing === "new" ? "新增成本项" : "保存"}</Button></footer>
  683. </div></div>}
  684. {deleteTarget && <div className="ops-confirm-backdrop" role="presentation" onMouseDown={() => !removeItem.busy && setDeleteTarget(null)}><div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="cost-delete-title" onMouseDown={(event) => event.stopPropagation()}>
  685. <h2 id="cost-delete-title">删除成本项「{deleteTarget.name}」?</h2>
  686. <p>该项当前未被任何套餐档引用(引用数 0),可以删除。{COST_DELETE_CONFIRM_NOTE}。此操作无法撤销。</p>
  687. {deleteError && <p className="ops-form-error" role="alert">{deleteError}</p>}
  688. <div><Button variant="outline" disabled={removeItem.busy} onClick={() => setDeleteTarget(null)}>取消</Button><Button variant="destructive" disabled={removeItem.busy} onClick={confirmDelete}>{removeItem.busy ? "正在删除…" : "确认删除"}</Button></div>
  689. </div></div>}
  690. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  691. </section>;
  692. }
  693. /* ═══ 出账更正记录(FN-10 登记/FN-11 查看,册 6 §14.6) ════════════════════
  694. * 数据源=correction/create、get_list、detail、draft_save、draft_get 全 [位] stub
  695. * (openapi.yaml 未声明 ⇒ 11001 契约占位分支:结构按契约落位、数据区标「后端未下发」);
  696. * ⛔ localStorage 台账冒充记录真源(旧 oss-demo-billing-corrections-v2 台账本版移除)。
  697. * 表单只有两项(关联账单+错误内容):⛔ 级别/原因下拉(severity 恒 severe、scope 由对象形态推出);
  698. * ⛔ 编辑/删除/核验/审批/办结/导出;⛔ 推测匹配(没命中候选=正常受理+「未关联到系统账目」)。
  699. * 角色:admin ●;regAdmin(=opsMain/opsSub)◐ 服务端按归属区域收窄(越权 KLT-C007 直读 message);
  700. * 其余角色不授键 ⇒ 整页不开放。文案唯一真源 ../lib/copy-billing(逐字,⛔ 手打转述)。
  701. */
  702. function CorrectionDialog({ title, subtitle, onClose, detail = false, children }: {
  703. title: string; subtitle: string; onClose: () => void; detail?: boolean; children: ReactNode;
  704. }) {
  705. const ref = useRef<HTMLDialogElement>(null);
  706. useEffect(() => {
  707. const dialog = ref.current;
  708. if (!dialog) return;
  709. dialog.showModal();
  710. return () => dialog.close();
  711. }, []);
  712. return <dialog ref={ref} className={`correction-notes-dialog correction-modal${detail ? " correction-notes-detail" : ""}`}
  713. aria-labelledby="correction-dialog-title"
  714. onCancel={(event) => { event.preventDefault(); onClose(); }}
  715. onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
  716. <header>
  717. <div>
  718. <span>{detail ? "RECORD DETAIL / 更正追踪" : "NEW RECORD / 差错留痕"}</span>
  719. <h2 id="correction-dialog-title">{title}</h2>
  720. <p>{subtitle}</p>
  721. </div>
  722. <button type="button" aria-label="关闭" onClick={onClose}><X size={18} /></button>
  723. </header>
  724. {children}
  725. </dialog>;
  726. }
  727. /**
  728. * 登记时间本地化:后端下发 UTC(`...T17:28:44Z` 裸 ISO),直接入列既难读又与
  729. * 手册「登记时间」口径不符 ⇒ 按浏览器时区显示,原文留在 `title` 里可核。
  730. */
  731. function localTime(iso: string): string {
  732. const d = new Date(iso);
  733. if (Number.isNaN(d.getTime())) return iso;
  734. const p = (n: number) => String(n).padStart(2, "0");
  735. return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
  736. }
  737. export function CorrectionNotesPage() {
  738. const { identity, organization, readOnly } = useBusinessView(["regions", "operationsTeams", "enterprises"]);
  739. const location = useLocation();
  740. /** 批次详情「登记更正」入口带来的预填关联对象(state.ref=对账单号,进页即开登记窗、一次性消费)。 */
  741. const { ref: prefillRef = "", correctionView } = (location.state ?? {}) as {
  742. ref?: string;
  743. correctionView?: { period: string; regionNodeId: string; operatorKeyword: string; keyword: string; page: number; detailId: string | null };
  744. };
  745. const back = detailBack(location.state, "/correction-notes", "返回出账更正记录");
  746. const allowed = useMemo(() => onboardingRegions(organization, identity), [organization, identity]);
  747. const tree = useMemo(() => regionTreeNodes(organization.regions, [...allowed]), [organization.regions, allowed]);
  748. /**
  749. * 归属区域名称:后端 `region_label` 在 dev 库无名称表可回填(区域名走 seoh 层级服务,
  750. * `cost.rs` 同源口径回 null),而本页已握有 `region/tree` 的区域清单 ⇒ 由 `region_node_id`
  751. * 就地取名,⛔ 让系统已推导出的归属区域显示成「—」(区域筛选按 ID 生效,展示却读不出)。
  752. */
  753. const regionNames = useMemo(() => new Map(organization.regions.map((r) => [r.id, r.name])), [organization.regions]);
  754. // 筛选四件:自然月(⛔ 预选——记录永久保留,预选会把「本期没有更正」看成「从没有过更正」)+归属区域+登记人+关键字(只查错误内容,⛔ 扩到关联对象)。
  755. const [period, setPeriod] = useState(correctionView?.period ?? "");
  756. const [regionNodeId, setRegionNodeId] = useState(correctionView?.regionNodeId ?? "");
  757. const [operatorKeyword, setOperatorKeyword] = useState(correctionView?.operatorKeyword ?? "");
  758. const [keyword, setKeyword] = useState(correctionView?.keyword ?? "");
  759. const [page, setPage] = useState(correctionView?.page ?? 1);
  760. const list = useCorrectionList({ period, regionNodeId, operatorKeyword, keyword, page });
  761. const wiring = list.fail?.kind === "wiring";
  762. const total = list.data?.total ?? 0;
  763. const pageSize = list.data?.page_size ?? 20;
  764. const [creating, setCreating] = useState(false);
  765. const [detailId, setDetailId] = useState<string | null>(correctionView?.detailId ?? null);
  766. const outgoingState = detailLinkState(location.pathname + location.search + location.hash, {
  767. ...location.state, ref: "", correctionView: { period, regionNodeId, operatorKeyword, keyword, page, detailId },
  768. });
  769. const [notice, setNotice] = useState("");
  770. useEffect(() => { if (prefillRef) setCreating(true); }, [prefillRef]);
  771. const hasFilter = Boolean(period || regionNodeId || operatorKeyword.trim() || keyword.trim());
  772. /** 重置筛选=清空四件+回到「全部自然月」(与进入态相同)。 */
  773. function resetFilters() { setPeriod(""); setRegionNodeId(""); setOperatorKeyword(""); setKeyword(""); setPage(1); }
  774. // 不授键角色(只读三类+运维团队三类)整页不开放;regAdmin 可登记,范围由服务端收窄(越权 KLT-C007 直读 message)。
  775. if (readOnly) return <div className="ops-empty">当前身份无权查看出账更正记录。</div>;
  776. return <section className="ops-page ops-page--corrections page-fill page-fill-window">
  777. {back.to !== "/correction-notes" && <Link className="ops-back-link self-start" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
  778. <header className="ops-heading">
  779. <div><h1>出账更正记录</h1><PageIntro>发现已出账的差错时,在这里登记问题、关联账单,便于日后核查。</PageIntro></div>
  780. <Button onClick={() => setCreating(true)}><FilePenLine size={15} aria-hidden="true" />登记更正</Button>
  781. </header>
  782. <div className="ops-list-shell correction-notes-ledger list-shell-fill">
  783. <div className="ops-toolbar flex-wrap">
  784. <label className="ops-search"><Search size={17} /><Input aria-label="搜索错误内容" placeholder="搜索错误内容" value={keyword} onChange={(event) => { setKeyword(event.target.value); setPage(1); }} /></label>
  785. <MonthFilter value={period} onChange={(value) => { setPeriod(value); setPage(1); }} />
  786. <TreeSelect treeData={tree} value={regionNodeId} onChange={(value) => { setRegionNodeId(value); setPage(1); }} clearable ariaLabel="归属区域(含下级)" placeholder="全部区域" />
  787. <label className="ops-search"><Search size={17} /><Input aria-label="登记人筛选" placeholder="登记人" value={operatorKeyword} onChange={(event) => { setOperatorKeyword(event.target.value); setPage(1); }} /></label>
  788. {hasFilter && <Button variant="ghost" size="sm" onClick={resetFilters}>重置筛选</Button>}
  789. </div>
  790. <div className="correction-notes-table-wrap list-scroll-fill" role="region" aria-label="出账更正台账" tabIndex={0}>
  791. <table className="correction-notes-table">
  792. <colgroup>
  793. <col className="correction-col-registrar" />
  794. <col className="correction-col-month" />
  795. <col className="correction-col-object" />
  796. <col className="correction-col-region" />
  797. <col />
  798. <col className="correction-col-registrar" />
  799. <col className="correction-col-action" />
  800. </colgroup>
  801. <thead><tr><th>登记时间</th><th>自然月</th><th>关联对象</th><th>归属区域</th><th>错误内容</th><th>登记人</th><th>操作</th></tr></thead>
  802. <tbody>{(list.data?.items ?? []).map((item) => <tr key={item.correction_id}>
  803. <td title={item.created_at}>{localTime(item.created_at)}</td>
  804. {/* 自然月不落库、现推;取不到 ⇒「—」(⛔ 相似度推测)。 */}
  805. <td>{item.period ?? <span className="table-placeholder">—</span>}</td>
  806. <td><strong className="correction-object-text table-cell-title" title={item.ref_label}>{item.ref_label || <span className="table-placeholder">—</span>}</strong>{!item.matched && <OpsTag tone="warning">{CORRECTION_UNMATCHED_TAG}</OpsTag>}</td>
  807. <td>{item.region_label ?? regionNames.get(item.region_node_id ?? "") ?? <span className="table-placeholder">—</span>}</td>
  808. {/* 列表只放摘要(后端截断),全文只在详情,⛔ 复制第二份。 */}
  809. <td><span title={item.error_excerpt} className="correction-notes-excerpt">{item.error_excerpt}</span></td>
  810. <td>{item.operator_name}</td>
  811. <td><button className="ops-table-action" type="button" onClick={() => setDetailId(item.correction_id)}>详情</button></td>
  812. </tr>)}{(list.fail || !list.data?.items?.length) && <OpsTableEmpty colSpan={7} kind={list.fail ? "error" : list.loading ? "loading" : "empty"} details={list.fail?.message} onRetry={list.fail && !wiring ? list.reload : undefined}>
  813. {wiring ? CORRECTION_WIRING_NOTE : list.fail ? "更正记录加载失败" : list.loading ? "正在读取更正记录…" : hasFilter ? "没有符合条件的更正记录。" : "暂无出账更正记录"}
  814. </OpsTableEmpty>}</tbody>
  815. </table>
  816. </div>
  817. {!list.fail && !list.loading && (
  818. <ServerListPager total={total} page={page} pageSize={pageSize} onPageChange={setPage} />
  819. )}
  820. </div>
  821. {creating && <CorrectionCreateDialog userKey={identity?.login ?? "anonymous"} initialRef={prefillRef}
  822. onClose={() => setCreating(false)}
  823. onCreated={() => { setCreating(false); setNotice(CORRECTION_CREATED_FEEDBACK); list.reload(); }} />}
  824. {detailId && <CorrectionDetailDialog id={detailId} regionNames={regionNames} linkState={outgoingState} refLabel={(list.data?.items ?? []).find((item) => item.correction_id === detailId)?.ref_label ?? "更正记录"} onClose={() => setDetailId(null)} />}
  825. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  826. </section>;
  827. }
  828. /** FN-10 登记窗:表单只有两项(关联账单+错误内容);H20501 停弹窗不丢内容、可顺手存草稿。 */
  829. function CorrectionCreateDialog({ userKey, initialRef, onClose, onCreated }: {
  830. userKey: string; initialRef: string; onClose: () => void; onCreated: () => void;
  831. }) {
  832. // 候选只列已被 executed 批次覆盖过的账(bill/list 应答行恒满足);弹窗挂载才取数,取数失败不拒登(可手工填写)。
  833. const candidates = useBillCandidates();
  834. const [choice, setChoice] = useState(initialRef ? "manual" : "");
  835. const [ref, setRef] = useState(initialRef);
  836. const [errorText, setErrorText] = useState("");
  837. const [error, setError] = useState("");
  838. const [regionHint, setRegionHint] = useState("");
  839. const [draftNote, setDraftNote] = useState("");
  840. const [busy, setBusy] = useState(false);
  841. const manual = choice === "manual";
  842. const chosen = (candidates.data?.items ?? []).find((item) => item.bill_detail_id === choice);
  843. // 草稿预填(按登录账号一份;draft_get 无草稿 ⇒ 成功+空对象;读取失败不阻断登记)。来路预填优先于草稿。
  844. useEffect(() => {
  845. if (initialRef) return;
  846. let alive = true;
  847. readCorrectionDraft(userKey)
  848. .then((form) => {
  849. if (!alive || !form) return;
  850. if (form.ref) { setChoice("manual"); setRef(form.ref); }
  851. if (form.error_text) setErrorText(form.error_text);
  852. })
  853. .catch(() => undefined);
  854. return () => { alive = false; };
  855. }, [userKey, initialRef]);
  856. function saveDraft() {
  857. const chosenLabel = chosen ? `${chosen.customer_name} · ${chosen.period} · ${chosen.holder_name} · ${chosen.batch_no}` : "";
  858. saveCorrectionDraft(userKey, { ref: manual ? ref.trim() : chosenLabel, error_text: errorText })
  859. .then(() => setDraftNote("草稿已暂存,下次打开登记窗自动带出。"))
  860. .catch((e: unknown) => setDraftNote(e instanceof Error && e.message ? e.message : "草稿暂存失败,请重试。"));
  861. }
  862. function submit() {
  863. const text = errorText.trim();
  864. // 自有校验(缺陷 O-7):两件事必填⛔ 交给浏览器原生气泡,一律落 `.ops-form-error` 内联红字
  865. // (与同域其他页同一风格,且被拦原因留在弹窗里,⛔ 一闪即逝)。
  866. if (!choice) { setError(CORRECTION_NEED_BILL); return; }
  867. if (manual && !ref.trim()) { setError(CORRECTION_NEED_REF); return; }
  868. if (!text) { setError(CORRECTION_NEED_ERROR_TEXT); return; }
  869. // 载荷只两项:bill_detail_id(选中候选)或 ref(手工填写原文)+ error_text;⛔ scope/severity/region_node_id(11103 禁传键)。
  870. const payload = manual ? { ref: ref.trim(), error_text: text } : { bill_detail_id: choice, error_text: text };
  871. setBusy(true); setError(""); setRegionHint("");
  872. submitCorrectionCreate(payload)
  873. .then(() => { clearCorrectionDraft(userKey).catch(() => undefined); onCreated(); })
  874. .catch((e: unknown) => {
  875. // 闸一 KLT-H20501(连是哪一笔账都认不出 ⇒ 推不出归属区域,⛔ 落 NULL):逐字提示+就地提示,停弹窗、已填内容不丢;
  876. // 闸二 KLT-H20507(候选带值但不合法)、KLT-C007(超出负责范围)与其余码:直读后端 message。
  877. if (hasBizCode(e, "KLT-H20501") || hasBizCode(e, "60501")) { setError(CORRECTION_H20501_TEXT); setRegionHint(CORRECTION_H20501_INLINE); }
  878. else {
  879. // 兜底(缺陷 D-55):任何被拦⛔ 静默——后端带文案就直读文案(网关剥码后 `hasBizCode` 会失配,
  880. // 但 message 仍在),连文案都没有才回固定句,⛔ 出现「点了没反应」。
  881. const m = e instanceof Error ? e.message.trim() : typeof e === "string" ? e.trim() : "";
  882. setError(m || "登记失败,请重试。");
  883. }
  884. })
  885. .finally(() => setBusy(false));
  886. }
  887. return <CorrectionDialog title="登记出账更正" subtitle="选择已出账账单,或手工填写关联对象;登记只留痕,不改动任何账目。" onClose={onClose}>
  888. {/* `noValidate`:必填拦截交给自有校验(缺陷 O-7),⛔ 让浏览器原生气泡替页面说话。 */}
  889. <form noValidate onSubmit={(event) => { event.preventDefault(); submit(); }}>
  890. <div className="correction-notes-dialog-body">
  891. <label className="correction-notes-field"><span>关联账单 <b>*</b></span>
  892. <select aria-required value={choice} onChange={(event) => { setChoice(event.target.value); setError(""); setRegionHint(""); }}>
  893. <option value="" disabled>请选择已出账账单</option>
  894. {(candidates.data?.items ?? []).map((item) => (
  895. <option key={item.bill_detail_id} value={item.bill_detail_id}>{item.customer_name} · {item.period} · {item.holder_name} · {item.batch_no}</option>
  896. ))}
  897. <option value="manual">手工填写</option>
  898. </select>
  899. </label>
  900. {candidates.fail && <p className="correction-notes-form-hint" role="status">候选清单{candidates.fail.kind === "wiring" ? `待后端接线(${BACKEND_NOT_WIRED})` : "取数失败"},可改用「手工填写」。</p>}
  901. {manual && <label className="correction-notes-field"><span>关联对象 <b>*</b></span>
  902. <Input aria-required value={ref} onChange={(event) => { setRef(event.target.value); setError(""); setRegionHint(""); }} placeholder="对账单号,或粘贴「客户名 · 自然月 · 对账单号」" />
  903. </label>}
  904. {regionHint && <p className="correction-notes-form-hint" role="status">{regionHint}</p>}
  905. <label className="correction-notes-field"><span>错误内容 <b>*</b></span>
  906. <textarea aria-required rows={5} maxLength={2000} value={errorText} onChange={(event) => setErrorText(event.target.value)} />
  907. </label>
  908. {error && <p className="ops-form-error" role="alert">{error}</p>}
  909. {draftNote && <p className="correction-notes-form-hint" role="status">{draftNote}</p>}
  910. </div>
  911. <footer>
  912. <Button type="button" variant="outline" onClick={onClose} disabled={busy}>取消</Button>
  913. <Button type="button" variant="outline" onClick={saveDraft} disabled={busy}>存草稿</Button>
  914. <Button type="submit" disabled={busy}>{busy ? "登记中…" : "登记记录"}</Button>
  915. </footer>
  916. </form>
  917. </CorrectionDialog>;
  918. }
  919. /** FN-11 详情窗:命中/未命中两种展示同源一个接口;能进列表就能进详情(11104 越权与查无同码 ⇒ fail 分支)。 */
  920. function CorrectionDetailDialog({ id, refLabel, regionNames, linkState, onClose }: { id: string; refLabel: string; regionNames: Map<string, string>; linkState: DetailLinkState; onClose: () => void }) {
  921. const detail = useCorrectionDetail(id);
  922. const d = detail.data;
  923. const wiring = detail.fail?.kind === "wiring";
  924. return <CorrectionDialog detail title="出账更正记录详情" subtitle={refLabel} onClose={onClose}>
  925. <div className="correction-notes-dialog-body">
  926. {wiring && <p className="ops-import-note" role="status">{CORRECTION_WIRING_NOTE}</p>}
  927. {detail.fail && !wiring && <p className="ops-form-error" role="alert">{detail.fail.message} <Button variant="ghost" size="sm" onClick={detail.reload}>重试</Button></p>}
  928. {!d && detail.loading && <p className="correction-notes-form-hint" role="status">详情取数中…</p>}
  929. {d && <>
  930. <div className="correction-notes-detail-facts" style={{ gridTemplateColumns: "repeat(4, minmax(0, 1fr))" }}>
  931. <div><span>登记时间</span><strong title={d.created_at}>{localTime(d.created_at)}</strong></div>
  932. <div><span>自然月</span><strong>{d.period ?? "—"}</strong></div>
  933. {/* 归属区域与列表同口径:后端已按 region_node_id 回填名称,仍留一层区域树兜底(D-54)。 */}
  934. <div><span>归属区域</span><strong>{d.region_label || regionNames.get(String(d.region_node_id ?? "")) || "—"}</strong></div>
  935. <div><span>登记人</span><strong>{d.operator_name}</strong></div>
  936. </div>
  937. {/* 口径复述:登记后也要能复核"不动账",⛔ 只在登记窗说一次(O-8)。 */}
  938. <p className="correction-notes-form-hint" role="note">{CORRECTION_DETAIL_NOTE}</p>
  939. <section className="correction-notes-detail-section"><h3>错误内容</h3><p>{d.error_text}</p></section>
  940. <section className="correction-notes-detail-section"><h3>关联对象</h3>
  941. {d.matched ? (
  942. <ul>
  943. {d.matched_bill_detail_id && <li><Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(d.matched_bill_detail_id)}`} state={linkState}>进入账单明细({d.matched_bill_detail_id}) <ArrowRight size={14} /></Link></li>}
  944. {d.matched_batch_no && <li>{d.matched_holder_id
  945. ? <Link className="ops-table-action" to={`/settlement-batches/${encodeURIComponent(d.matched_holder_id)}/${encodeURIComponent(d.matched_batch_no)}`} state={linkState}>进入对账批次({d.matched_batch_no}) <ArrowRight size={14} /></Link>
  946. : <span>对账批次 {d.matched_batch_no} <small title="批次持有方未随详情下发,批次入口暂不可用(已登记缺口清单)">(批次入口{BACKEND_NOT_WIRED})</small></span>}</li>}
  947. </ul>
  948. ) : (
  949. <p><OpsTag tone="warning">{CORRECTION_UNMATCHED_TAG}</OpsTag> {d.raw_ref ?? ""}</p>
  950. )}
  951. </section>
  952. </>}
  953. </div>
  954. <footer><Button type="button" variant="outline" onClick={onClose}>关闭</Button></footer>
  955. </CorrectionDialog>;
  956. }