import { MultiTreeSelect } from "../components/ui/multi-tree-select"; import { PageIntro } from "../components/PageIntro"; import { TeamTicketTypes } from "../components/TeamTicketTypes"; import { ListPager } from "../components/ListPager"; import { OpsDialog, OpsNotice, OpsResponsiveActions, OpsTableColumns } from "../components/OperationsKit"; import { compareNum, compareText, nextSort, slicePage, useLocalPage, type SortDir } from "../lib/list-paging"; import { downloadCsv } from "../lib/csv-download"; import { useHorizontalOverflow } from "../lib/use-horizontal-overflow"; import { FilterIcon, FilterSelect } from "../components/ui/filter-select"; import { useLayoutEffect, useEffect, useMemo, useRef, useState, type CSSProperties, type FormEvent, type ReactNode } from "react"; import { createPortal } from "react-dom"; import { ArrowLeft, ArrowRight, ChevronDown, ChevronRight, Download, Info, MapPinned, PencilLine, Plus, Search, Trash2, UserRound, Users, Wrench, X } from "lucide-react"; import { Link, useParams, useSearchParams } from "react-router"; import { Button as FilterResetButton } from "../components/ui/button"; import { TreeSelect } from "../components/ui/tree-select"; import { regionLevelText, regionParentInTree, regionTreeNodes } from "../lib/region-tree"; import { markPeerOccupiedTreeNodes, peerCoveredRegionIdsForCustomers, peerOccupiedRegionIds, regionAncestorChain } from "../lib/region-ownership"; import { OrganizationAccountDialog, type AccountTarget } from "../components/OrganizationAccountDialog"; import { OrganizationAccountInline } from "../components/OrganizationAccountInline"; import { OrganizationAccountStatus } from "../components/OrganizationAccountStatus"; import { MaintenanceAccounts, OperationsAccounts } from "../components/OrganizationTeamAccounts"; import { FIELD_UNAVAILABLE, descendants, enterpriseTeamIds, levelNames, payCycleOptions, peekOrganizationData, reconcileDayText, reconcileDayTitle, reloadOrganizationData, regionPath, scopeEnterpriseIndexes, scopeSummary, settleKeyOf, settleOptions, suppressDeletedRegion, upsertRegionFromCreate, useOrganizationData, useOrganizationLoaded, useOrganizationSnapshot, useOrganizationStatus, type MaintenanceTeam, type OperationsTeam, type Operator, type OrganizationData, type OrganizationStatus, type Partner, type Region, type Scope, type ShareFields, } from "../lib/organization-demo"; import * as bos from "../lib/api/bos"; import { MAINTENANCE_TICKET_TYPES, typeLabel } from "../lib/api/ticket"; import { useDemoIdentity } from "../lib/demo-session"; import { useSession } from "../auth/session"; import { Tri } from "../components/triState"; import "../styles/operations.css"; import "../styles/organization.css"; type EditorKind = "region" | "operator" | "partner" | "operations" | "maintenance"; /** 后端 `operator.brand` 只接受这三值(`OPERATOR_BRANDS`,非法值 `30001`),故表单用下拉而非自由文本。 */ const OPERATOR_BRANDS = ["移动", "联通", "电信"]; /** 平台资源树虚根:只作父子链中转,⛔ 当业务区域节点渲染/当作建档区域。 */ const V_ROOT = "V-ALL"; type Editor = { kind: EditorKind; id?: string; parent?: string }; const freshScope = (): Scope => ({ regions: [], enterprises: [] }); /** 负责范围是否与档案原值一致:按集合内容比较(⛔ 比顺序,⛔ 每次保存都重写范围)。 */ const sameScope = (current: Scope | undefined, next: Scope) => Boolean(current) && current!.regions.length === next.regions.length && next.regions.every((id) => current!.regions.includes(id)) && current!.enterprises.length === next.enterprises.length && next.enterprises.every((index) => current!.enterprises.includes(index)); const shareText = (item: ShareFields) => item.shareMode === "按比例" ? `${(item.shareValue * 100).toLocaleString("zh-CN", { maximumFractionDigits: 2 })}%` : item.shareMode === "按每账号" ? `¥${item.shareValue} / 账号` : `¥${item.shareValue} / 月`; const operationsRegionLabel = (data: OrganizationData, id: string) => regionPath(data, id).split(" / ").filter((part, index, parts) => part !== parts[index - 1]).join(" / "); /** 工单类型选项:**值=后端类型码**(`ops::domain::TYPES`,落库与传输一律用码),标签=同源中文名。 * * ⚠️ 运维团队的可分配类型**不含 `renewal`**(业主 2026-11-17「运维不可接续签工单」, * 后端 `domain::MAINTENANCE_TYPES`):勾选项用 [`MAINTENANCE_TICKET_TYPES`], * ⛔ 用 `TICKET_TYPES`——后端 `ops_team/*` 会整次拒掉。 */ const maintenanceTicketOptions = MAINTENANCE_TICKET_TYPES.map((code) => ({ value: code, label: typeLabel(code) })); const maintenanceTicketCodes = maintenanceTicketOptions.map((option) => option.value); /** 团队档案上的类型码集合;缺省=全部类型(⛔ 用中文标签当值,后端会按非法码拒绝)。 */ const teamTicketTypes = (team: MaintenanceTeam) => team.ticketTypes?.length ? team.ticketTypes : maintenanceTicketCodes; function PageHead({ eyebrow, title, description, action }: { eyebrow: string; title: string; description: string; action?: ReactNode }) { return

{eyebrow}

{title}

{description}
{action}
; } /** 账号列手机号展示:后端§5.4 已掩码则原样;偶发明文 11 位时再罩一层(⛔ 当拨号明文)。 */ function phoneDisplay(phone?: string): string { if (!phone) return "未绑手机号"; if (phone.includes("*")) return phone; const digits = phone.replace(/\D/g, ""); return digits.length === 11 ? `${digits.slice(0, 3)}****${digits.slice(7)}` : phone; } /** 区域删除 blocked 英文 key → 中文(对齐 advisory/RG-10/RG-05)。 */ const REGION_BLOCKED_LABELS: Record = { has_children: "存在下级区域", has_children_customers: "存在在册客户(含下级)", has_operator_profiles: "被运营商档案引用", has_partner_profiles: "被合伙人档案引用", has_ops_teams: "被运维团队档案引用", has_team_scope_refs: "被负责范围引用", }; /** 后端删除/解绑类回执统一口径:`deleted:false` + blockers/blocked ⇒ 原文展示,⛔ 假装成功。空串=已删除。 */ function refuseText(res: unknown): string { const r = res as { deleted?: boolean; blockers?: { key: string; count: number | null; message: string }[]; blocked?: string[]; note?: string; unverifiable_checks?: { key: string; reason: string }[] } | undefined; if (r?.deleted) return ""; const parts = [ ...(r?.blockers ?? []).map((b) => (b.count === null || b.count === undefined ? b.message : `${b.message}(${b.count})`)), ...(r?.blocked ?? []).map((key) => REGION_BLOCKED_LABELS[key] ?? key), ...(r?.unverifiable_checks ?? []).map((c) => c.reason), ].filter(Boolean); return parts.length ? parts.join(";") : (r?.note || "后端未删除该档案"); } /** 取数门:整体失败原文+重试、逐集合失败原文、后端降级说明(⛔ 加载中 helper,其它页也不用)。 */ function OrgFetchState({ status, collections }: { status: OrganizationStatus; collections?: (keyof OrganizationStatus["partial"])[] }) { const fails = (collections ?? []).map((key) => status.partial[key]).filter(Boolean) as string[]; const notes = [status.regionNameNote, status.customerNote, status.loadPending].filter(Boolean) as string[]; if (!status.error && !fails.length && !notes.length) return null; return <> {status.error &&

组织档案读取失败:{status.error.message}

} {notes.map((msg) =>

{msg}

)} {fails.map((msg) =>

部分数据未取得:{msg}

)} ; } /** 计数列三态:`undefined`=后端 ⛔ 下发该字段,`null`=后端回「无」,其余为接口原值(⛔ 折算 0)。 */ function Count({ v, note }: { v: number | null | undefined; note?: string }) { if (v === undefined) return ; if (v === null) return ; return <>{v}{note ? {note} : null}; } /** 计数文案:缺省/空值带 title,供字符串插值;需要悬停语义时优先用 `Count`。 */ const countText = (v?: number | null) => v === undefined ? FIELD_UNAVAILABLE : v === null ? "—" : String(v); const countTitle = (v?: number | null, note?: string) => v === undefined ? "后端接口未返回该字段" : v === null ? (note || "后端回空(无计数/未覆盖),不是接口未实现") : undefined; /** 某集合整体失败时,表格位置显示失败原文+重试,⛔ 用空表冒充「0 条」。 */ function CollectionFailed({ status, collection, title }: { status: OrganizationStatus; collection: keyof OrganizationStatus["partial"]; title: string }) { const msg = status.partial[collection]; if (!msg) return null; return

{title}列表未能取得:{msg}

为避免把接口失败显示成 0 条,此处不展示列表。

; } function Button({ children, onClick, quiet = false, tone, disabled = false, title }: { children: ReactNode; onClick?: () => void; quiet?: boolean; tone?: "info" | "scope"; disabled?: boolean; title?: string }) { return ; } /** 空态统一两类:无数据/筛选无结果(RG-19)。 */ function Empty({ children, filtered }: { children?: ReactNode; filtered?: boolean }) { const text = children ?? (filtered ? "没有符合筛选条件的数据" : "暂无数据"); return
{text}
; } function RegionSelect({ data, value, onChange, all = false }: { data: OrganizationData; value: string; onChange: (v: string) => void; all?: boolean }) { const treeData = useMemo(() => regionTreeNodes(data.regions), [data.regions]); return : undefined} ariaLabel="区域" treeData={treeData} value={value} onChange={onChange} clearable={all} placeholder={all ? "全部区域" : "请选择区域"} />; } function SearchBox({ value, onChange, placeholder }: { value: string; onChange: (value: string) => void; placeholder: string }) { return ; } /** * 档案保存成功回执(TC-FN-17/18 步1:弹窗关闭+「XX信息已保存」提示)。 * ⛔ 静默关闭——用户改完看不到任何确认,只能靠列表刷新增疑。 * 停留时长由 `OpsNotice` 自己计时(约 2.6s 自动收起),⛔ 这里再挂一个计时器。 */ function useSaveNotice() { const [notice, setNotice] = useState(""); return { show: setNotice, node: notice ? setNotice("")} /> : null }; } function OrgEditor({ editor, onClose, onSaved }: { editor: Editor; onClose: () => void; onSaved?: (message: string) => void }) { // 只订阅:编辑器由已取数的页面挂载,⛔ 打开弹窗再把集合重拉一遍。 const data = useOrganizationSnapshot(); const { ctx } = useSession(); /** 区域新建仅总部管理员(与区域管理页同权)。 */ const canCreateRegion = ctx?.role_code === "admin"; const existing = editor.kind === "region" ? data.regions.find((r) => r.id === editor.id) : editor.kind === "operator" ? data.operators.find((o) => o.id === editor.id) : editor.kind === "partner" ? data.partners.find((p) => p.id === editor.id) : editor.kind === "operations" ? data.operationsTeams.find((t) => t.id === editor.id) : data.maintenanceTeams.find((t) => t.id === editor.id); const [name, setName] = useState(existing?.name ?? ""); // 层级=业务侧自持属性(⛔ 由父子深度推导);新建时按上级推断默认值,仍可改。 const [regionLevelSel, setRegionLevelSel] = useState(() => { if (editor.kind !== "region") return ""; if (editor.id) { const level = (existing as Region | undefined)?.level; return level === null || level === undefined ? "" : levelNames[level] ?? ""; } const parent = data.regions.find((r) => r.id === editor.parent); if (!parent || parent.id === V_ROOT || !parent.parent && parent.level === null) return "省"; if (parent.level === 0) return "市"; if (parent.level === 1) return "区县"; return "省"; }); const [region, setRegion] = useState(() => { if ("region" in (existing ?? {})) return (existing as { region: string }).region; /** 运营商只能建档在省级节点:新建时留空,⛔ 默认落到市/区县节点再被后端拒绝。 */ if (editor.kind === "operator") return ""; return editor.parent ?? data.regions[0]?.id ?? ""; }); const [username, setUsername] = useState(""); // 编辑回填:列表手机号已脱敏(`139****0002`)⇒ 留空表示「不改」;⛔ 把脱敏串当写入值上行。 const [mobile, setMobile] = useState(() => { if (!(existing && "phone" in existing) || editor.id === undefined) { return existing && "phone" in existing ? ((existing as { phone?: string }).phone ?? "") : ""; } const raw = ((existing as { phone?: string }).phone ?? "").trim(); return raw.includes("*") ? "" : raw; }); const [busy, setBusy] = useState(false); const [confirmDispatch, setConfirmDispatch] = useState(false); const [title, setTitle] = useState(editor.kind === "partner" ? (existing as Partner | undefined)?.title ?? "" : ""); /** 后端 `operator/create|update` 必填 `brand`,故运营商表单增加品牌输入。 */ const [brand, setBrand] = useState(editor.kind === "operator" ? (existing as Operator | undefined)?.brand ?? "" : ""); /** 空串=跟随系统默认(后端 `recon_day = NULL`);其余为 1–28 的日号。 */ const [reconDay, setReconDay] = useState(editor.kind === "operator" ? String((existing as Operator | undefined)?.reconcileDay ?? "") : ""); /** 付款周期原值(`按月|按季度|按年`);空串=未配置(后端 `pay_cycle = NULL`)。 */ const [payCycle, setPayCycle] = useState(editor.kind === "operator" ? (existing as Operator | undefined)?.payCycle ?? "" : ""); const [desc, setDesc] = useState(editor.kind === "operations" ? (existing as OperationsTeam | undefined)?.desc ?? "" : ""); const [mode, setMode] = useState(editor.kind === "maintenance" ? (existing as MaintenanceTeam | undefined)?.mode ?? "手工" : "手工"); const [ticketTypes, setTicketTypes] = useState(editor.kind === "maintenance" && existing ? teamTicketTypes(existing as MaintenanceTeam) : maintenanceTicketCodes); const initSettleMode = settleKeyOf((existing as ShareFields | undefined)?.shareMode ?? "按比例"); const [settleMode, setSettleMode] = useState(initSettleMode); // 后端 ratio 存小数(0–1),表单按百分比(0–100)录入与回显;amount/per_account 为金额原值。 const initShareRaw = (existing as ShareFields | undefined)?.shareValue ?? 0; /** 档案两列为空(`sharePending`=`toShare` 的「按比例 0」占位)⇒ 取值框留空,⛔ 拿 0 冒充「已配置成 0 的分成」(TC-FN-24:未配置⛔ 显示 0)。 */ const shareUnset = (existing as ShareFields | undefined)?.sharePending === true; const initShareText = shareUnset ? "" : String(initSettleMode === "ratio" ? initShareRaw * 100 : initShareRaw); const [shareValue, setShareValue] = useState(initShareText); /** * 按「分成方式」暂存已填值:切换方式时⛔ 把取值抹成 0(TC-FN-14 步2「弹窗不重绘,已填内容不丢」 * +步4「切回按比例回填原值」);未填过的方式留空,由保存校验给必填文案。 */ const [shareByMode, setShareByMode] = useState>({ [initSettleMode]: initShareText }); const [scope, setScope] = useState("scope" in (existing ?? {}) ? structuredClone((existing as { scope: Scope }).scope) : editor.parent && editor.kind !== "region" ? { regions: [editor.parent], enterprises: [] } : freshScope()); /** 负责范围旁嵌套「新建区域」:挂靠上级(空=平台树根=建省)。 */ const [regionCreateParent, setRegionCreateParent] = useState(""); const [regionModal, setRegionModal] = useState(null); const [regionCreateNote, setRegionCreateNote] = useState(""); const [error, setError] = useState(""); /** 开通回执(合伙人/运维团队创建):一次性初始密码只在回执里出现一次。 */ const [createdInfo, setCreatedInfo] = useState<{ title: string; label: string; username: string | null; password: string | null } | null>(null); /** * 省级节点 → 已建档品牌集合(编辑时排除自身)。 * 新建运营商只有一省一品牌唯一一条:省份三品牌齐了就 ⛔ 再选,省内已有品牌也 ⛔ 再选。 */ const takenBrands = useMemo(() => { const map = new Map>(); if (editor.kind !== "operator") return map; for (const item of data.operators) { if (editor.id && item.id === editor.id) continue; const brands = map.get(item.region) ?? new Set(); if (item.brand) brands.add(item.brand); map.set(item.region, brands); } return map; }, [data.operators, editor.kind, editor.id]); /** 运营商所属区域只到省级;新建时某省三品牌均已建档则该项置灰。 */ const operatorProvinceNodes = useMemo(() => { if (editor.kind !== "operator") return []; return data.regions.filter((item) => item.level === 0).map((item) => { const brands = takenBrands.get(item.id); const full = OPERATOR_BRANDS.every((name) => brands?.has(name)); return { value: item.id, label: item.name, hint: full ? "品牌已满" : "省", disabled: !editor.id && full }; }); }, [data.regions, editor.kind, editor.id, takenBrands]); const kindTitle = { region: "区域节点", operator: "运营商", partner: "合伙人", operations: "运营团队", maintenance: "运维团队" }[editor.kind]; /** 保存:一律走 klt-bos 接口;失败显示后端 `message` 原文,成功后整包刷新。 */ async function submit(event: FormEvent) { event.preventDefault(); if (busy) return; const trimmed = name.trim(); const shareValueText = shareValue.trim(); const shareNumber = Number(shareValueText); // 后端 ratio 存小数(0–1),表单录入百分比(0–100)⇒ 提交前换算;金额类直传。 const settleValue = settleMode === "ratio" ? shareNumber / 100 : shareNumber; // 运维「指定客户」入口已隐去:区域可改,客户清单只透传档案原值(⛔ 表单未展示却改写)。 const customerIds = editor.kind === "maintenance" ? ((existing as MaintenanceTeam | undefined)?.scope.enterprises ?? []).map((i) => data.enterprises[i]?.no).filter((v): v is string => Boolean(v)) : scope.enterprises.map((i) => data.enterprises[i]?.no).filter((v): v is string => Boolean(v)); if (!trimmed) { setError("请填写名称"); return; } // 品牌是后端唯一定位键的一部分(`operator.brand` 只认三值);空值⛔ 拿运营商名兜底,否则后端按非法品牌拒绝。 if (editor.kind === "operator" && !brand) { setError("请选择品牌"); return; } if (editor.kind === "maintenance" && !ticketTypes.length) { setError("请至少选择一种可分配工单类型"); return; } // 校验提示逐字取自需求:按比例=「分成比例必须大于 0 且不超过 100(%)」(04_组织与区域.md:397、07_分成成本对账.md:330); // 按金额/按每账号=对应标签+「必须大于 0(人民币元)」(07_分成成本对账.md:331)。 const settleInvalidMessage = settleMode === "ratio" ? "分成比例必须大于 0 且不超过 100(%)" : `${settleMode === "amount" ? "每月分成金额" : "每账号分成金额"}必须大于 0(人民币元)`; if (editor.kind !== "region" && editor.kind !== "operations" && (!/^\d+(?:\.\d{1,2})?$/.test(shareValueText) || shareNumber <= 0 || (settleMode === "ratio" && shareNumber > 100))) { setError(settleInvalidMessage); return; } const dispatchChanging = editor.kind === "maintenance" && Boolean(editor.id) && existing && (existing as MaintenanceTeam).mode !== mode; if (dispatchChanging && !confirmDispatch) { setConfirmDispatch(true); setError(""); return; } const run = async (): Promise<{ title: string; label: string; username: string | null; password: string | null } | null> => { if (!region && editor.kind !== "operations") throw new Error("请选择所属区域"); if (editor.kind === "operator" && data.regions.find((item) => item.id === region)?.level !== 0) throw new Error("运营商只能建档在省级区域"); if (editor.kind === "operator") { // `is_province_node` 是后端 I6 的显式入参(上层已限定只能选省级节点,后端另有 `bos_region_meta` 权威校验)。 if (editor.id) await bos.operatorUpdate({ operator_id: editor.id, name: trimmed, brand, region_node_id: region, is_province_node: true, settle_mode: settleMode, settle_value: settleValue, recon_day: reconDay ? Number(reconDay) : null, pay_cycle: payCycle || null }); else await bos.operatorCreate({ name: trimmed, brand, region_node_id: region, is_province_node: true, settle_mode: settleMode, settle_value: settleValue, recon_day: reconDay ? Number(reconDay) : null, pay_cycle: payCycle || null }); } else if (editor.kind === "partner") { if (editor.id) { // 脱敏串/非法手机号一律不携带 mobile(留空=不改);合法 11 位才上行。 const nextMobile = mobile.trim(); const mobilePayload = !nextMobile ? undefined : /^1[3-9]\d{9}$/.test(nextMobile) ? nextMobile : (() => { throw new Error("请输入 11 位中国大陆手机号,或留空表示不改"); })(); await bos.partnerUpdate({ partner_id: editor.id, name: trimmed, duty_desc: title.trim(), region_node_id: region, ...(mobilePayload !== undefined ? { mobile: mobilePayload } : {}), settle_mode: settleMode, settle_value: settleValue }); // 负责范围并入本弹窗:只在确有改动时提交(含清空),⛔ 每次保存都重写一遍。 if (!sameScope((existing as Partner | undefined)?.scope, scope)) await bos.partnerScopeSave({ partner_id: editor.id, region_node_ids: scope.regions, customer_ids: customerIds }); } else { if (!username.trim()) throw new Error("请填写登录名——后端创建合伙人时同步创建其登录账号"); const created = await bos.partnerCreate({ name: trimmed, region_node_id: region, username: username.trim(), duty_desc: title.trim(), mobile: mobile.trim() || undefined, settle_mode: settleMode, settle_value: settleValue }); const acct = (created as { account?: { provision_failed?: boolean; message?: string; reason?: string; initial_password?: string | null; username?: string | null } }).account; if (acct?.provision_failed) throw new Error(`合伙人档案已创建,但登录账号开设失败:${[acct.message, acct.reason].filter(Boolean).join(" ") || "后端未说明原因"}`); if (scope.regions.length || customerIds.length) await bos.partnerScopeSave({ partner_id: created.partner_id, region_node_ids: scope.regions, customer_ids: customerIds }); return { title: "合伙人已开通", label: created.name || trimmed, username: acct?.username ?? username.trim(), password: acct?.initial_password ?? null }; } } else if (editor.kind === "operations") { if (editor.id) { await bos.entTeamUpdate({ team_id: editor.id, team_name: trimmed, remark: desc.trim() }); // 负责范围并入本弹窗:后端运营团队范围只支持区域节点,只在确有改动时提交。 if (!sameScope((existing as OperationsTeam | undefined)?.scope, scope)) await bos.entTeamScopeSave({ team_id: editor.id, region_node_ids: scope.regions }); } else { const created = await bos.entTeamCreate({ team_name: trimmed, remark: desc.trim() || undefined }); if (scope.regions.length) await bos.entTeamScopeSave({ team_id: created.team_id, region_node_ids: scope.regions }); } } else { const dispatchMode = mode === "手工" ? "manual" : "auto_avg"; if (editor.id) { // 档案更新与分派方式串行:先写档案,再切分派;任一步失败原文上抛,⛔ 并发无事务保证。 await bos.opsTeamUpdate({ team_id: editor.id, team_name: trimmed, region_node_id: region, ticket_types: ticketTypes, settle_mode: settleMode, settle_value: settleValue }); if (dispatchChanging) await bos.opsTeamDispatchModeUpdate({ team_id: editor.id, dispatch_mode: dispatchMode }); // 只在区域确有改动时写范围;客户清单透传档案原值(入口已隐去,⛔ 表单改写)。 const prev = (existing as MaintenanceTeam | undefined)?.scope; const regionsChanged = JSON.stringify([...(prev?.regions ?? [])].sort()) !== JSON.stringify([...scope.regions].sort()); if (regionsChanged) await bos.opsTeamScopeSave({ team_id: editor.id, region_node_ids: scope.regions, customer_ids: customerIds }); } else { const created = await bos.opsTeamCreate({ team_name: trimmed, region_node_id: region, ticket_types: ticketTypes, dispatch_mode: dispatchMode, settle_mode: settleMode, settle_value: settleValue }); if (scope.regions.length) await bos.opsTeamScopeSave({ team_id: created.team_id, region_node_ids: scope.regions, customer_ids: customerIds }); return { title: "运维团队已开通", label: created.team_name || trimmed, username: created.primary_account?.username ?? null, password: created.primary_account?.initial_password ?? null }; } } return null; }; setBusy(true); setError(""); setConfirmDispatch(false); try { const receipt = await run(); await reloadOrganizationData(); if (receipt) setCreatedInfo(receipt); else { // 运营商分成取值改动次月生效(TC-FN-18 步1)⇒ 提示里带上生效口径。 onSaved?.(editor.kind === "operator" ? "运营商信息已保存,分成取值修正自下一个自然月起生效。" : `${kindTitle}信息已保存`); onClose(); } } catch (e) { setError((e as Error)?.message || "保存失败"); setBusy(false); } } // 合伙人/运维/运营团队的负责范围并入「编辑」弹窗(2026-11-16 业主指示:列表不再单列「配置负责范围」动作); // 新建时首次配置也走同一段表单。 const hasScope = ["partner", "maintenance", "operations"].includes(editor.kind); /** 同类其它主体已占用区域(含子树/祖先);已勾选项保留可取消,便于清脏数据。后端硬拦 KLT-T216。 */ const scopeRegionNodes = useMemo(() => { if (!hasScope) return regionTreeNodes(data.regions); const peers = editor.kind === "partner" ? data.partners.filter((item) => item.id !== editor.id) : editor.kind === "operations" ? data.operationsTeams.filter((item) => item.id !== editor.id && !item.hq) : data.maintenanceTeams.filter((item) => item.id !== editor.id); const peerRegionGrants = peers.flatMap((item) => item.scope.regions); const occupied = peerOccupiedRegionIds(data.regions, peerRegionGrants); // 对方点客户:勾选挂载区或其祖先会把对方点客户收进本方闭包(⛔ 不因此灰掉挂载区子孙)。 for (const item of peers) { for (const index of item.scope.enterprises) { const mount = data.enterprises[index]?.region; if (!mount) continue; for (const id of regionAncestorChain(data.regions, mount)) occupied.add(id); } } return markPeerOccupiedTreeNodes(regionTreeNodes(data.regions), occupied, scope.regions); }, [data.partners, data.operationsTeams, data.maintenanceTeams, data.enterprises, data.regions, editor.kind, editor.id, hasScope, scope.regions]); /** 新建区域挂靠上级:区县(level=2)不可再挂下级 ⇒ 置灰;清空=挂平台树根建省。 */ const regionCreateParentNodes = useMemo(() => { const mark = (nodes: ReturnType): ReturnType => nodes.map((n) => { const region = data.regions.find((r) => r.id === n.value); const disableLeaf = region?.level === 2; return { ...n, disabled: disableLeaf || undefined, hint: disableLeaf ? "区县不可再挂下级" : n.hint, children: n.children?.length ? mark(n.children) : n.children, }; }); return mark(regionTreeNodes(data.regions)); }, [data.regions]); /** 合伙人点客户:挂载区落入同类占用子树,或已被同类点选 ⇒ 置灰(已勾选项仍可取消)。 */ const scopeCustomerNodes = useMemo(() => { if (editor.kind !== "partner") return []; const peers = data.partners.filter((item) => item.id !== editor.id); const coveredRegions = peerCoveredRegionIdsForCustomers(data.regions, peers.flatMap((item) => item.scope.regions)); const pickedNos = new Set(peers.flatMap((item) => item.scope.enterprises.map((index) => data.enterprises[index]?.no).filter(Boolean) as string[])); const keep = new Set(scope.enterprises.map(String)); return data.enterprises.map((enterprise, index) => { const blocked = (Boolean(enterprise.region) && coveredRegions.has(enterprise.region)) || (enterprise.no ? pickedNos.has(enterprise.no) : false); const keepOn = keep.has(String(index)); return { value: String(index), label: enterprise.name, hint: blocked && !keepOn ? "已被同类其他主体占用" : (enterprise.no || ""), disabled: blocked && !keepOn, }; }); }, [data.partners, data.regions, data.enterprises, editor.kind, editor.id, scope.enterprises]); const existingRegionLevel = (existing as Region | undefined)?.level; const selectedRegionLevel = regionLevelSel ? levelNames.indexOf(regionLevelSel) : -1; const regionLevelTitle = editor.kind === "region" && !editor.id ? selectedRegionLevel >= 0 ? ["省级区域", "市级区域", "区县区域"][selectedRegionLevel] : "区域" : existingRegionLevel === null || existingRegionLevel === undefined ? "未定级区域" : ["省级区域", "市级区域", "区县区域"][existingRegionLevel] || "未定级区域"; const regionParentRaw = editor.parent ?? (existing as Region | undefined)?.parent; const regionParent = regionParentRaw && regionParentRaw !== V_ROOT ? regionParentRaw : null; const editorTitle = editor.kind === "region" ? editor.id ? "重命名区域" : `新建${regionLevelTitle}` : `${editor.id ? "编辑" : "新建"}${kindTitle}`; if (createdInfo) { return
e.stopPropagation()} role="dialog">
ORGANIZATION / CREATED

{createdInfo.title}

档案与登录账号已开通

名称{createdInfo.label}登录名{createdInfo.username || "—"}{createdInfo.password ? <>一次性凭据{createdInfo.password}由开通回执一次性下发(初始密码/激活码),关闭后无法再次查询,请立即转交本人。 : 后端未回传一次性凭据(`credential_viewable=false` 或不含 `initial_password`),请通过账号设置重置激活码。}
; } if (confirmDispatch) { return
setConfirmDispatch(false)}>
e.stopPropagation()} role="dialog">
DISPATCH MODE

确认切换分派方式

分派方式影响该团队后续工单派发。将从「{(existing as MaintenanceTeam | undefined)?.mode}」改为「{mode}」。

档案字段与分派方式将依次提交;任一步失败会原文提示,请按提示重试,避免只改了一半。

{error &&

{error}

}
; } return
e.stopPropagation()} role="dialog">
ORGANIZATION RECORD

{editorTitle}

{hasScope &&

{editor.kind === "operations" ? "负责范围只支持区域节点,所选区域包含其下级客户。" : editor.kind === "maintenance" ? "所选区域包含其下级客户。" : "所选区域包含下级客户,并与指定客户合并。"}

}
{editor.kind === "region" && !editor.id && } {editor.kind === "region" &&
{regionParent ? "所属上级区域" : "区域层级"}{regionParent ? regionPath(data, regionParent) : "省级 · 挂在平台树根下"}

{editor.id ? "调整区域名称,所属层级与挂载关系保持不变。" : "层级由业务侧自持,请在上方点名(跨级挂靠是常态,系统不按上级推导)。"}

} {editor.kind === "operator" && } {editor.kind === "operator" && } {["partner", "maintenance"].includes(editor.kind) && } {editor.kind === "operations" &&

运营团队在后端没有独立的「所属区域」字段,区域归属即下方负责范围里的区域节点。

} {!["region", "operations"].includes(editor.kind) && <>} {editor.kind === "operator" && } {editor.kind === "operations" &&

运营团队分成的口径与取值由结算域维护,后端未在团队档案上开放修改入参。

} {editor.kind === "operations" &&