| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979 |
- 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<string, number> };
- 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<string, string>;
- baseline: Record<string, string>;
- };
- /** 弹窗内是否有真改动(与打开时的快照逐格比)。 */
- 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`
- * 只按数组长度下发 `<col>`):少一项,多出的列在 `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<number>(count).fill(110), 76, 142, 120];
- const weights = kind === "definitions" ? [0, 17, 10, 8, 7, 6, 8, 8, 24, 12, 0]
- : [0, 0, ...Array<number>(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 <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" : ""}`}>
- <table className="ops-table cost-ledger" style={{ minWidth }}><OpsTableColumns widths={columns} />{typeof children === "function" ? children(expanded) : children}</table>
- </div>;
- }
- 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<string, string>();
- 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<AmountForm | null>(null);
- const [editing, setEditing] = useState<CostItemView | "new" | null>(null);
- const [draftDef, setDraftDef] = useState<CostDraft>(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<Record<string, string>>({});
- /** KLT-E007 ⇒ 该行输入框标灰+出路句(键=cost_item_id),不清空其余已填。 */
- const [staleItems, setStaleItems] = useState<Record<string, boolean>>({});
- /** KLT-E004 且 reason=no_province ⇒ 整页 ② 不可用。 */
- const [panelBlocked, setPanelBlocked] = useState("");
- /** 删除确认框选中的成本项(`null`=未打开);`deleteError` 只在框内显示。 */
- const [deleteTarget, setDeleteTarget] = useState<CostItemView | null>(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<string, string> = {};
- 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<string, string> = {};
- 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 <Tri tone="fail" text={WORD_FETCH_FAILED} title={`金额一览取数失败:${amounts.error?.message ?? ""}`} />;
- if (!amounts.data) return <Tri tone="missing" text="取数中…" title="金额一览取数中…" />;
- if (!amounts.data.available) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title={`后端 available:false,透视表本期无行 ⇒ 既不能判定「未配置」也不能判定为 0。${AMOUNT_UNAVAILABLE_NOTE}`} />;
- if (!pivotRow) return <span className="ops-matrix-unset" title="后端没有该「省份 × 运营商」的金额行=整套未配置(按 0 元 / 月计)">0</span>;
- const value = pivotRow.amounts.get(itemId);
- if (value === undefined) return <span className="ops-matrix-unset" title="该组合已配其他成本项,这一项没有差异行=未配置(按 0 元 / 月计)">0</span>;
- if (value === null) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端下发该格但 amount_cents 为空" />;
- return <span className="ops-money">{yuan(value)}</span>;
- }
- function rowTotal(pivotRow: CostComboView | undefined): ReactNode {
- if (amounts.error) return <Tri tone="fail" text={WORD_FETCH_FAILED} title="金额一览取数失败,合计不可算" />;
- if (!amounts.data) return <Tri tone="missing" text="取数中…" title="金额一览取数中…" />;
- if (!amounts.data.available) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端透视表本期无行 ⇒ 合计不可算" />;
- if (!pivotRow) return <span className="ops-matrix-unset" title="该组合未配置任何金额=0">0</span>;
- let sum = 0;
- for (const item of costItems) {
- const value = pivotRow.amounts.get(item.id);
- if (value === undefined) continue;
- if (value === null) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="该组合存在金额为空的格 ⇒ 合计不完整" />;
- sum += value;
- }
- return <span className="ops-money">{yuan(sum)}</span>;
- }
- /** 命中客户数三态:取数失败/取数中/真值(D-2:真值来自后端 customer/get_list 现算 total)。 */
- function hitCountCell(rowKey: string): ReactNode {
- if (comboCounts.error) return <span title={`命中客户取数失败:${comboCounts.error.message ?? ""}`}>—</span>;
- if (!comboCounts.data) return <span title="命中客户取数中">…</span>;
- return <span className="table-number">{comboCounts.data.get(rowKey) ?? 0} 家</span>;
- }
- if (readOnly) return <div className="ops-empty">当前身份无权查看成本配置。</div>;
- return <section className="ops-page ops-page--costs page-fill page-fill-window"><header className="ops-heading"><div><h1>成本管理</h1><PageIntro>为不同区域和运营商设定适用的成本金额,作为出账核算的依据。</PageIntro></div></header>
- <div className="ops-list-shell list-shell-fill">
- <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>
- {tab === "definitions" ? <>
- <div className="ops-toolbar">
- <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>
- <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>
- {(kindFilter || query) && <Button variant="ghost" size="sm" onClick={() => { setKindFilter(""); setQuery(""); setDefPage(0); }}>重置筛选</Button>}
- <div className="ops-toolbar-end">{canEdit ? <Button onClick={() => startEdit("new")}><Plus size={16} />新增成本项</Button> : <span className="ops-muted">只读</span>}</div>
- </div>
- <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}>
- <td><span className="ops-mono table-number">{String(defPage * LIST_PAGE_SIZE + index + 1).padStart(2, "0")}</span></td>
- <td><strong className="table-cell-title" title={item.name}>{item.name}</strong></td>
- <td><Tri tone={item.category.pending ? "missing" : "val"} text={item.category.text} title={item.category.pending ? "该历史行 category 未灌值(20261107000002 补列前的存量行、名称不在回填映射内)⇒ 只标「后端未下发」,不折算成任一类别" : `后端 category=${item.categoryKey ?? ""}`} /></td>
- <td><Tri tone={item.calc.pending ? "missing" : "val"} text={item.calc.text} title={item.calc.pending ? "该历史行 billing_unit 未灌值(同上)" : `后端 billing_unit=${item.billingUnitKey ?? ""}`} /></td>
- <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>
- <td>{noCycle ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="该历史行 is_amortized 未灌值 ⇒ 不折算「否」" /> : <OpsStatus tone={item.amortized ? "success" : "neutral"}>{item.amortized ? "是" : "否"}</OpsStatus>}</td>
- <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>
- <td>{deduct.pending ? <Tri tone="missing" text={deduct.text} title="该历史行 deduct_from_base 未灌值 ⇒ 不折算成「否」" /> : <OpsStatus tone={item.deduct ? "success" : "neutral"}>{deduct.text}</OpsStatus>}</td>
- <td>{item.configuredComboCount === null
- ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端未下发「已配组合数/月度合计」概况列" />
- : item.configuredComboCount === 0
- ? (item.configuredRowCount ?? 0) > 0
- ? <span title={`后端 cost_amount 有 ${item.configuredRowCount} 条金额行,但都缺省份/运营商轴,无法进入「省份 × 运营商」透视(见金额一览说明)`}>0 个可用组合<small className="ops-muted"> · {item.configuredRowCount} 条金额行缺省份/运营商轴</small></span>
- : <small className="ops-muted">尚未配置任何组合(按 0 元 / 月计)</small>
- : <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>
- <td>{item.referringPlans === null
- ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端未下发套餐档引用概况" />
- : item.referringPlans.length
- ? item.referringPlans.map((plan) => <small className="ops-stacked" title={`档位 ID:${plan.id}(按 plan_cost_item.cost_item_id 强引用,改成本项名不断引用)`} key={plan.id}>{plan.name}</small>)
- : <span className="ops-mono table-number" title="后端现算:plan_cost_item 里没有 cost_item_id 指向该成本项的引用行(未被引用 ⇒ 可删除)">0</span>}</td>
- <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>
- </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}>
- {items.error ? "成本项加载失败" : items.loading ? "正在读取成本项…" : query || kindFilter ? "没有符合筛选条件的成本项" : "暂无成本项"}
- </OpsTableEmpty>}</tbody></>}</CostLedger>
- {!items.error && !items.loading && <ListPager total={costItemTotal} page={defPage} pageSize={LIST_PAGE_SIZE} onPageChange={setDefPage} />}
- </> : panelBlocked ? <div className="ops-empty" role="alert"><h1>成本金额暂不可用</h1><p>{panelBlocked}(KLT-E004 · no_province)</p></div> : <>
- <div className="ops-toolbar">
- <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>
- <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>
- {(matrixProvince || matrixBrand) && <Button variant="ghost" size="sm" onClick={() => { setMatrixProvince(""); setMatrixBrand(""); }}>重置筛选</Button>}
- {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>}
- <div className="ops-toolbar-end">{canEdit ? <Button onClick={() => openAmountForm("new")}><Plus size={16} />新增运营商成本</Button> : <span className="ops-muted">只读(金额由总运营维护)</span>}</div>
- </div>
- <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}>
- <td><strong>{provinceNameOf(row.provinceId)}</strong></td>
- <td>{operatorNameOf(row.operatorId)}</td>
- {costItems.map((item) => <td key={item.id}>{amountCell(item.id, pivotRow)}</td>)}
- <td title="该省(含下级)归属该运营商的客户数,由后端 customer/get_list 按可见范围现算">{hitCountCell(row.key)}</td>
- <td>{rowTotal(pivotRow)}</td>
- <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>
- </tr>; })}{!amounts.error && !matrixRows.length && <OpsTableEmpty colSpan={costItems.length + 5}>{!allCombos.length ? "暂无可配置成本金额的运营商" : "没有符合筛选条件的区域与运营商组合"}</OpsTableEmpty>}</tbody></CostLedger>
- <ListPager total={matrixRows.length} page={matrixPaging.safePage} pageSize={matrixPaging.pageSize} onPageChange={matrixPaging.setPage} unit="个" />
- {pivotExtras.length > 0 && <p className="ops-muted">后端透视另返回 {pivotExtras.length} 个「省份节点 × 运营商」组合不在当前可见档案范围内(区域/运营商口径不一致),未列入上表。</p>}
- </>}
- </div>
- {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()}>
- <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>
- <div className="ops-batch-dialog-body">
- <div className="ops-form-grid">
- <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>
- <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>
- </div>
- <div className="ops-cost-amount-rows">
- <div className="ops-cost-amount-row ops-cost-amount-row--head" aria-hidden="true"><span>成本项</span><span>计算方式</span><span>具体金额(元 / 月)</span></div>
- {costItems.map((item) => { const deduct = boolView(item.deduct, "计入基数", "不扣基数"); return <label key={item.id} className="ops-cost-amount-row">
- <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>
- <span className="ops-muted">{item.calc.pending ? WORD_NOT_PROVIDED : item.calc.text}</span>
- <span className="ops-cost-amount-input">
- <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] ? "已失效" : "留空=该项不配置"} />
- {cellErrors[item.id] && <small className="ops-form-error" role="alert">{cellErrors[item.id]}</small>}
- {staleItems[item.id] && <small className="ops-form-error" role="alert">{COST_STALE_PANEL_NOTE}</small>}
- </span>
- </label>; })}
- </div>
- {amounts.data && !amounts.data.available && <p className="ops-form-error" role="alert">后端金额一览 available:false({AMOUNT_UNAVAILABLE_NOTE})⇒ 判不出哪些组合已有金额:已有组合请走一览表行内「编辑金额」,本弹窗只用于新增,不得拿它覆盖已有组合。</p>}
- {amountError || (saveAmount.error && !saveAmount.busy) ? <p className="ops-form-error" role="alert">{amountError || `金额保存失败:${saveAmount.error?.message ?? ""}`}</p> : null}
- {/* ⛔ 弹窗底部不再挂「只提交本次改动过的格子(契约 14.1.2)…」整段说明(2026-11-18 业主指出):
- 那段是跨两种模式的通用口径,放在「编辑运营商成本」里有一半句子(新增组合才写、去一览表点编辑金额)
- 与当前场景相悖,且把契约编号等实现口径摆给操作人看。「留空=该项不配置」由每行输入框的
- placeholder 承担,「已配金额的组合不在此新增」由运营商下拉禁用+「(已有金额)」承担。 */}
- </div>
- <footer><Button variant="outline" onClick={closeAmountForm}>取消</Button><Button disabled={saveAmount.busy} onClick={submitAmountForm}>{saveAmount.busy ? "保存中…" : amountForm.mode === "new" ? "确认新增" : "确认保存"}</Button></footer>
- </div></div>}
- {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()}>
- <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>
- <div className="ops-batch-dialog-body">
- <div className="ops-form-grid">
- <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>
- <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>
- <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>
- <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>
- <div className="ops-form-check-row">
- <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>
- <OpsHint label="「是否摊销」口径说明" title="是否摊销">{COST_AMORTIZED_HINT.map((line) => <p key={line}>{line}</p>)}</OpsHint>
- </div>
- <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>
- <div className="ops-form-check-row">
- <label className="ops-form-check"><input type="checkbox" checked={draftDef.deduct} onChange={(event) => setDraftDef({ ...draftDef, deduct: event.target.checked })} />从分成基数中扣除</label>
- <OpsHint label="「从分成基数中扣除」口径说明" title="从分成基数中扣除">{COST_DEDUCT_HINT.map((line) => <p key={line}>{line}</p>)}</OpsHint>
- </div>
- </div>
- {(error || (!nameError && saveItem.error)) && <p className="ops-form-error" role="alert">{error || `保存失败:${saveItem.error?.message ?? ""}(后端校验:11102 乐观锁冲突/11103 参数不合法)`}</p>}
- {editing !== "new" && draftDef.rowVersion === null && <p className="ops-import-note">该行后端未下发 row_version ⇒ 本次保存不带乐观锁,他人同时修改不会被拦下。</p>}
- {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>}
- </div>
- <footer><Button variant="outline" onClick={() => setEditing(null)}>取消</Button><Button disabled={saveItem.busy} onClick={submitDefinition}>{saveItem.busy ? "保存中…" : editing === "new" ? "新增成本项" : "保存"}</Button></footer>
- </div></div>}
- {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()}>
- <h2 id="cost-delete-title">删除成本项「{deleteTarget.name}」?</h2>
- <p>该项当前未被任何套餐档引用(引用数 0),可以删除。{COST_DELETE_CONFIRM_NOTE}。此操作无法撤销。</p>
- {deleteError && <p className="ops-form-error" role="alert">{deleteError}</p>}
- <div><Button variant="outline" disabled={removeItem.busy} onClick={() => setDeleteTarget(null)}>取消</Button><Button variant="destructive" disabled={removeItem.busy} onClick={confirmDelete}>{removeItem.busy ? "正在删除…" : "确认删除"}</Button></div>
- </div></div>}
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- </section>;
- }
- /* ═══ 出账更正记录(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<HTMLDialogElement>(null);
- useEffect(() => {
- const dialog = ref.current;
- if (!dialog) return;
- dialog.showModal();
- return () => dialog.close();
- }, []);
- return <dialog ref={ref} className={`correction-notes-dialog correction-modal${detail ? " correction-notes-detail" : ""}`}
- aria-labelledby="correction-dialog-title"
- onCancel={(event) => { event.preventDefault(); onClose(); }}
- onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
- <header>
- <div>
- <span>{detail ? "RECORD DETAIL / 更正追踪" : "NEW RECORD / 差错留痕"}</span>
- <h2 id="correction-dialog-title">{title}</h2>
- <p>{subtitle}</p>
- </div>
- <button type="button" aria-label="关闭" onClick={onClose}><X size={18} /></button>
- </header>
- {children}
- </dialog>;
- }
- /**
- * 登记时间本地化:后端下发 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<string | null>(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 <div className="ops-empty">当前身份无权查看出账更正记录。</div>;
- return <section className="ops-page ops-page--corrections page-fill page-fill-window">
- {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>}
- <header className="ops-heading">
- <div><h1>出账更正记录</h1><PageIntro>发现已出账的差错时,在这里登记问题、关联账单,便于日后核查。</PageIntro></div>
- <Button onClick={() => setCreating(true)}><FilePenLine size={15} aria-hidden="true" />登记更正</Button>
- </header>
- <div className="ops-list-shell correction-notes-ledger list-shell-fill">
- <div className="ops-toolbar flex-wrap">
- <label className="ops-search"><Search size={17} /><Input aria-label="搜索错误内容" placeholder="搜索错误内容" value={keyword} onChange={(event) => { setKeyword(event.target.value); setPage(1); }} /></label>
- <MonthFilter value={period} onChange={(value) => { setPeriod(value); setPage(1); }} />
- <TreeSelect treeData={tree} value={regionNodeId} onChange={(value) => { setRegionNodeId(value); setPage(1); }} clearable ariaLabel="归属区域(含下级)" placeholder="全部区域" />
- <label className="ops-search"><Search size={17} /><Input aria-label="登记人筛选" placeholder="登记人" value={operatorKeyword} onChange={(event) => { setOperatorKeyword(event.target.value); setPage(1); }} /></label>
- {hasFilter && <Button variant="ghost" size="sm" onClick={resetFilters}>重置筛选</Button>}
- </div>
- <div className="correction-notes-table-wrap list-scroll-fill" role="region" aria-label="出账更正台账" tabIndex={0}>
- <table className="correction-notes-table">
- <colgroup>
- <col className="correction-col-registrar" />
- <col className="correction-col-month" />
- <col className="correction-col-object" />
- <col className="correction-col-region" />
- <col />
- <col className="correction-col-registrar" />
- <col className="correction-col-action" />
- </colgroup>
- <thead><tr><th>登记时间</th><th>自然月</th><th>关联对象</th><th>归属区域</th><th>错误内容</th><th>登记人</th><th>操作</th></tr></thead>
- <tbody>{(list.data?.items ?? []).map((item) => <tr key={item.correction_id}>
- <td title={item.created_at}>{localTime(item.created_at)}</td>
- {/* 自然月不落库、现推;取不到 ⇒「—」(⛔ 相似度推测)。 */}
- <td>{item.period ?? <span className="table-placeholder">—</span>}</td>
- <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>
- <td>{item.region_label ?? regionNames.get(item.region_node_id ?? "") ?? <span className="table-placeholder">—</span>}</td>
- {/* 列表只放摘要(后端截断),全文只在详情,⛔ 复制第二份。 */}
- <td><span title={item.error_excerpt} className="correction-notes-excerpt">{item.error_excerpt}</span></td>
- <td>{item.operator_name}</td>
- <td><button className="ops-table-action" type="button" onClick={() => setDetailId(item.correction_id)}>详情</button></td>
- </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}>
- {wiring ? CORRECTION_WIRING_NOTE : list.fail ? "更正记录加载失败" : list.loading ? "正在读取更正记录…" : hasFilter ? "没有符合条件的更正记录。" : "暂无出账更正记录"}
- </OpsTableEmpty>}</tbody>
- </table>
- </div>
- {!list.fail && !list.loading && (
- <ServerListPager total={total} page={page} pageSize={pageSize} onPageChange={setPage} />
- )}
- </div>
- {creating && <CorrectionCreateDialog userKey={identity?.login ?? "anonymous"} initialRef={prefillRef}
- onClose={() => setCreating(false)}
- onCreated={() => { setCreating(false); setNotice(CORRECTION_CREATED_FEEDBACK); list.reload(); }} />}
- {detailId && <CorrectionDetailDialog id={detailId} regionNames={regionNames} linkState={outgoingState} refLabel={(list.data?.items ?? []).find((item) => item.correction_id === detailId)?.ref_label ?? "更正记录"} onClose={() => setDetailId(null)} />}
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- </section>;
- }
- /** 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 <CorrectionDialog title="登记出账更正" subtitle="选择已出账账单,或手工填写关联对象;登记只留痕,不改动任何账目。" onClose={onClose}>
- {/* `noValidate`:必填拦截交给自有校验(缺陷 O-7),⛔ 让浏览器原生气泡替页面说话。 */}
- <form noValidate onSubmit={(event) => { event.preventDefault(); submit(); }}>
- <div className="correction-notes-dialog-body">
- <label className="correction-notes-field"><span>关联账单 <b>*</b></span>
- <select aria-required value={choice} onChange={(event) => { setChoice(event.target.value); setError(""); setRegionHint(""); }}>
- <option value="" disabled>请选择已出账账单</option>
- {(candidates.data?.items ?? []).map((item) => (
- <option key={item.bill_detail_id} value={item.bill_detail_id}>{item.customer_name} · {item.period} · {item.holder_name} · {item.batch_no}</option>
- ))}
- <option value="manual">手工填写</option>
- </select>
- </label>
- {candidates.fail && <p className="correction-notes-form-hint" role="status">候选清单{candidates.fail.kind === "wiring" ? `待后端接线(${BACKEND_NOT_WIRED})` : "取数失败"},可改用「手工填写」。</p>}
- {manual && <label className="correction-notes-field"><span>关联对象 <b>*</b></span>
- <Input aria-required value={ref} onChange={(event) => { setRef(event.target.value); setError(""); setRegionHint(""); }} placeholder="对账单号,或粘贴「客户名 · 自然月 · 对账单号」" />
- </label>}
- {regionHint && <p className="correction-notes-form-hint" role="status">{regionHint}</p>}
- <label className="correction-notes-field"><span>错误内容 <b>*</b></span>
- <textarea aria-required rows={5} maxLength={2000} value={errorText} onChange={(event) => setErrorText(event.target.value)} />
- </label>
- {error && <p className="ops-form-error" role="alert">{error}</p>}
- {draftNote && <p className="correction-notes-form-hint" role="status">{draftNote}</p>}
- </div>
- <footer>
- <Button type="button" variant="outline" onClick={onClose} disabled={busy}>取消</Button>
- <Button type="button" variant="outline" onClick={saveDraft} disabled={busy}>存草稿</Button>
- <Button type="submit" disabled={busy}>{busy ? "登记中…" : "登记记录"}</Button>
- </footer>
- </form>
- </CorrectionDialog>;
- }
- /** FN-11 详情窗:命中/未命中两种展示同源一个接口;能进列表就能进详情(11104 越权与查无同码 ⇒ fail 分支)。 */
- function CorrectionDetailDialog({ id, refLabel, regionNames, linkState, onClose }: { id: string; refLabel: string; regionNames: Map<string, string>; linkState: DetailLinkState; onClose: () => void }) {
- const detail = useCorrectionDetail(id);
- const d = detail.data;
- const wiring = detail.fail?.kind === "wiring";
- return <CorrectionDialog detail title="出账更正记录详情" subtitle={refLabel} onClose={onClose}>
- <div className="correction-notes-dialog-body">
- {wiring && <p className="ops-import-note" role="status">{CORRECTION_WIRING_NOTE}</p>}
- {detail.fail && !wiring && <p className="ops-form-error" role="alert">{detail.fail.message} <Button variant="ghost" size="sm" onClick={detail.reload}>重试</Button></p>}
- {!d && detail.loading && <p className="correction-notes-form-hint" role="status">详情取数中…</p>}
- {d && <>
- <div className="correction-notes-detail-facts" style={{ gridTemplateColumns: "repeat(4, minmax(0, 1fr))" }}>
- <div><span>登记时间</span><strong title={d.created_at}>{localTime(d.created_at)}</strong></div>
- <div><span>自然月</span><strong>{d.period ?? "—"}</strong></div>
- {/* 归属区域与列表同口径:后端已按 region_node_id 回填名称,仍留一层区域树兜底(D-54)。 */}
- <div><span>归属区域</span><strong>{d.region_label || regionNames.get(String(d.region_node_id ?? "")) || "—"}</strong></div>
- <div><span>登记人</span><strong>{d.operator_name}</strong></div>
- </div>
- {/* 口径复述:登记后也要能复核"不动账",⛔ 只在登记窗说一次(O-8)。 */}
- <p className="correction-notes-form-hint" role="note">{CORRECTION_DETAIL_NOTE}</p>
- <section className="correction-notes-detail-section"><h3>错误内容</h3><p>{d.error_text}</p></section>
- <section className="correction-notes-detail-section"><h3>关联对象</h3>
- {d.matched ? (
- <ul>
- {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>}
- {d.matched_batch_no && <li>{d.matched_holder_id
- ? <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>
- : <span>对账批次 {d.matched_batch_no} <small title="批次持有方未随详情下发,批次入口暂不可用(已登记缺口清单)">(批次入口{BACKEND_NOT_WIRED})</small></span>}</li>}
- </ul>
- ) : (
- <p><OpsTag tone="warning">{CORRECTION_UNMATCHED_TAG}</OpsTag> {d.raw_ref ?? ""}</p>
- )}
- </section>
- </>}
- </div>
- <footer><Button type="button" variant="outline" onClick={onClose}>关闭</Button></footer>
- </CorrectionDialog>;
- }
|