| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759 |
- import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
- import { ArrowLeft, Plus, Trash2, Upload, X } from "lucide-react";
- import { FetchError } from "../components/fetchError";
- import { useNavigate, useParams } from "react-router";
- import { Button } from "../components/ui/button";
- import { Input } from "../components/ui/input";
- import { TreeSelect } from "../components/ui/tree-select";
- import { CustomerTeamSelect } from "../components/CustomerTeamSelect";
- import { contractRawByParam } from "../lib/contract-demo";
- import { contractAttachmentDiscard, contractCreate, contractCustomerLookup, contractUpdate, rowsOf } from "../lib/api/bos";
- import { ApiError } from "../lib/api/http";
- import { OPTIONS, label, PAY_CYCLE, SUBJECT_TYPE, USE_CATEGORY } from "../lib/api/labels";
- import { WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
- import { Tri } from "../components/triState";
- import { useCatalogPlans, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
- import { IP_BANDWIDTH_TIERS, IP_COUNT_MAX, IP_TIER_UNCOMMITTED, LINE_EXIT_MAX } from "../domain/contract-items";
- import type { ContractMissing, ContractRequiredKey, IpRowDraft } from "../domain/contract-items";
- import { REQUIRED_KEY_BY_DRAFT, buildContractWrite, draftFromRow, emptyDraft, emptyItem, emptyIpRow, firstItemExit, type ContractDraft as Draft, type ItemDraft } from "../domain/contract-draft";
- import { regionTreeNodes } from "../lib/region-tree";
- import { useOrganizationData } from "../lib/organization-demo";
- import type { ContractCreateResult } from "../lib/api/types";
- import { uploadContractAttachment, uploadCustomerLicense, type UploadedObject } from "../lib/api/oss-upload";
- import { contractAttachmentLabel } from "../lib/contract-attachments";
- import { useLoad } from "../lib/useLoad";
- import { useDemoIdentity } from "../lib/demo-session";
- import "../styles/operations.css";
- /**
- * 客户候选:`contract/customer_lookup` 三种命中方式,未命中转自由录入(⛔ 红叉、⛔ 11102)。
- *
- * **输入防抖**:连击期间只重置计时器,`CUSTOMER_LOOKUP_DEBOUNCE_MS` 内不再发第二次请求;
- * 检索词去空白后才作为依赖 ⇒ 尾部空格/前后空白变动不触发重取。
- */
- const CUSTOMER_LOOKUP_DEBOUNCE_MS = 300;
- function useCustomerCandidates(term: string) {
- const [debounced, setDebounced] = useState(term);
- useEffect(() => {
- const timer = window.setTimeout(() => setDebounced(term), CUSTOMER_LOOKUP_DEBOUNCE_MS);
- return () => window.clearTimeout(timer);
- }, [term]);
- /** 服务端只认 `query_type` + `value` 两键(`identity` 走 HMAC 密钥通路、dev 未接线会回 `KLT-S406`)⇒ 主体号走 `credit_code`,其余走名称模糊。 */
- const query = debounced.trim();
- const load = useLoad(() => {
- if (query.length < 2) return Promise.resolve(null);
- const queryType = /^KL-\d{4}-\d{6}$/.test(query) ? "credit_code" : "keyword";
- return contractCustomerLookup({ query_type: queryType, value: query });
- }, [query]);
- /** 回带结果对应的检索词:调用方据此判断「候选还是上一次的」(⛔ 据此清空候选,见页面内注释)。 */
- return { ...load, term: query };
- }
- export function ContractEditorPage() {
- const { no } = useParams();
- const navigate = useNavigate();
- const identity = useDemoIdentity();
- const editing = Boolean(no);
- const catalog = useCatalogPlans();
- const plans = useMemo(() => rowsOf(catalog.data?.items), [catalog.data]);
- /** 线路出口目录(套餐配置统一维护):合同条目与 IP 条目只从这里选(2026-11-15 裁定)。 */
- const exitCatalog = useLineExits();
- /** 带宽档位目录(2026-11-16 起可配置):IP 条目的档位只从这里选。 */
- const tierCatalog = useIpBandwidthTiers();
- const tierOptions = useMemo(() => {
- const items = tierCatalog.data?.items ?? [];
- if (items.length) {
- return items.map((item) => ({
- value: item.bandwidth_tier_mbps === null ? IP_TIER_UNCOMMITTED : String(item.bandwidth_tier_mbps),
- label: item.tier_name,
- }));
- }
- return [
- ...IP_BANDWIDTH_TIERS.map((tier) => ({ value: String(tier), label: `${tier} 兆` })),
- { value: IP_TIER_UNCOMMITTED, label: "不承诺带宽" },
- ];
- }, [tierCatalog.data]);
- const tierValues = useMemo(() => tierOptions.map((option) => option.value), [tierOptions]);
- const record = useLoad(() => contractRawByParam(no), [no]);
- const [draft, setDraft] = useState<Draft>(emptyDraft);
- const [customerId, setCustomerId] = useState<string | null>(null);
- const [customerTerm, setCustomerTerm] = useState("");
- const [error, setError] = useState("");
- /** 必填项的单字段红显(需求 §5.3 第 522 行「不保存并红显该字段」),提示语照抄后端 `60004` 原话,⛔ 只弹一句总提示找不到错在哪。 */
- const [fieldError, setFieldError] = useState<ContractMissing | null>(null);
- const [submitting, setSubmitting] = useState(false);
- /**
- * 合同附件(单份,2026-11-16 定案):选中即直传平台对象存储,成功后只把**对象键**挂进
- * `draft.attachmentUrl`(字面量须与后端 `CONTRACT_ATTACHMENT_KEY_PREFIX` 同前缀)。
- * ⛔ 字节流/上传凭证经本服务;查看地址由详情读口现签,⛔ 前端缓存签名。
- */
- const attachmentInput = useRef<HTMLInputElement | null>(null);
- const [attachmentBusy, setAttachmentBusy] = useState(false);
- const [attachmentError, setAttachmentError] = useState("");
- /** 本次刚上传的原始文件名(键里不含文件名 ⇒ 刷新后按后缀显示「合同附件.<ext>」)。 */
- const [attachmentName, setAttachmentName] = useState("");
- /**
- * 本页**刚上传、还没被任何合同引用**的对象键(孤儿回收清单)。
- *
- * 平台只有「即时删除」一条通道(`object/delete@v1`,见 unified-oss §6.6.10:不做后台遍历删对象),
- * 所以「换了/移除了/取消了」的那一刻必须由本页把没人要的那一份退回去([`discardPendingAttachments`])。
- * 服务端还会再查一次引用面(仍被合同引用就拒删)⇒ 这里可以放宽心调,⛔ 当成前端独占真相。
- */
- const pendingAttachmentKeys = useRef<string[]>([]);
- useEffect(() => {
- if (record.data) setDraft(draftFromRow(record.data));
- }, [record.data]);
- /**
- * 把清单里的对象键交给服务端回收(best-effort):失败⛔ 拦用户、⛔ 回滚草稿——
- * 用户的动作(换文件/移除/取消)已经完成,回收只是桶侧的清尾。
- */
- const discardPendingAttachments = (keys?: string[]) => {
- const targets = keys ?? pendingAttachmentKeys.current;
- if (!targets.length) return;
- pendingAttachmentKeys.current = pendingAttachmentKeys.current.filter(
- (key) => !targets.includes(key),
- );
- for (const objectKey of targets) {
- void contractAttachmentDiscard({ object_key: objectKey }).catch(() => {});
- }
- };
- /** 离开本页(返回/取消)时把没落库的上传一起退掉:`useRef` 读的是最新清单,⛔ 闭包快照。 */
- useEffect(() => () => discardPendingAttachments(), []);
- /**
- * 新建态的「运营商经办人」姓名默认取当前登录身份(与姓名同一来源、可改,⛔ 写死号码);
- * `auth/context@v1` 实测只回 7 个键、不含手机号 ⇒ 取不到就留空由必填校验拦下,⛔ 造号。
- * ⚠️ 这一组是**交接单上的运营商侧联系人**,不是「录入账号」(`created_by`,服务端另写、恒只读);
- * 建后它随档案轴(未开通且 72h 内或未到期)仍可改,与「交接单日期」同一命运。
- */
- useEffect(() => {
- if (editing || !identity) return;
- setDraft((current) => ({ ...current, agent: current.agent || identity.name, agentPhone: current.agentPhone || identity.phone || "" }));
- }, [editing, identity]);
- /**
- * 客户检索=**输入防抖**(300ms 内的连击只打一次 `contract/customer_lookup@v1`)
- * + **沿用上一次结果**:防抖窗口里⛔ 把候选清空——否则每敲一个字下拉就消失再出现,列表整体抖一下。
- */
- const lookup = useCustomerCandidates(customerTerm);
- const trimmedTerm = customerTerm.trim();
- /** 输入已变、检索还没跟上(防抖计时中或请求在飞):候选沿用旧结果,只在列表底部标「正在检索…」。 */
- const lookupStale = lookup.term !== trimmedTerm;
- const searching = trimmedTerm.length >= 2 && (lookupStale || lookup.loading);
- const candidates = lookup.data?.customers ?? [];
- const freeText = !lookup.data?.matched && trimmedTerm.length >= 2;
- const customerLabel = record.data?.customer_name || (record.data?.customer_id ? record.data.customer_id : WORD_UNCONFIGURED);
- /**
- * 客户检索=**输入框内下拉**(业主 2026-11-16 定案):命中项直接挂在输入框下方的候选列表,
- * ⛔ 另起一个「命中的客户档案」下拉。选中后输入框锁定该客户并显示 × 清除,再输入即重新检索。
- */
- const customerInput = useRef<HTMLInputElement | null>(null);
- const [customerOpen, setCustomerOpen] = useState(false);
- const [customerActive, setCustomerActive] = useState(0);
- const showCustomerOptions = customerOpen && !customerId && trimmedTerm.length >= 2 && (candidates.length > 0 || searching);
- const activeCustomer = showCustomerOptions && candidates.length ? (customerActive < candidates.length ? customerActive : 0) : -1;
- const pickCustomer = (hit: (typeof candidates)[number]) => {
- setCustomerId(hit.customer_id);
- setCustomerTerm(hit.customer_name);
- setCustomerOpen(false);
- setCustomerActive(0);
- setError("");
- };
- const clearCustomer = () => {
- setCustomerId(null);
- setCustomerTerm("");
- setCustomerOpen(false);
- setCustomerActive(0);
- setError("");
- customerInput.current?.focus();
- };
- const onCustomerKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
- if (customerId) {
- if (event.key === "Escape") { event.preventDefault(); clearCustomer(); }
- return;
- }
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
- if (!candidates.length) return;
- event.preventDefault();
- if (!customerOpen) { setCustomerOpen(true); return; }
- const delta = event.key === "ArrowDown" ? 1 : -1;
- setCustomerActive((current) => (current + delta + candidates.length) % candidates.length);
- return;
- }
- if (event.key === "Enter") {
- if (!showCustomerOptions || activeCustomer < 0) return;
- event.preventDefault();
- pickCustomer(candidates[activeCustomer]);
- return;
- }
- if (event.key === "Escape" && customerOpen) { event.preventDefault(); setCustomerOpen(false); }
- };
- /**
- * 客户内联建档段(需求 §5.3 CU-13;业主 2026-11-16 定案):
- * **命中已有客户 ⇒ 本段整段不出现**(命中项直接选在上方输入框内的候选下拉,选中后输入框锁定并带 × 清除);
- * 未命中 ⇒ 在客户名称下方展开建档必填项,含运营商与运维团队两个下拉。
- * ⚠️ 本段只收集 CU-13 第 1 步字段,逐项与 `/customer/create@v1` 同源;
- * 企业营业执照影像**可留空**(本通道例外),建档后到客户档案「登记材料」格补传。
- */
- const org = useOrganizationData(["regions", "operators", "maintenanceTeams"]);
- const regionTree = useMemo(() => regionTreeNodes(org.regions, org.regions.map((item) => item.id)), [org.regions]);
- const [inline, setInline] = useState({ subject: "enterprise", idNo: "", contact: "", phone: "", address: "", regionId: "", operatorId: "", teamId: "", login: "", mobile: "" });
- const [licenseObj, setLicenseObj] = useState<UploadedObject | null>(null);
- const [licenseBusy, setLicenseBusy] = useState(false);
- const [licenseError, setLicenseError] = useState("");
- /** 内联建档成功后的回执(客户号/主账号/激活码口径);合同已生成,下一步是去合同详情。 */
- const [created, setCreated] = useState<{ contractId: string; customer: NonNullable<ContractCreateResult["inline_customer"]> } | null>(null);
- const setInlineField = <K extends keyof typeof inline>(key: K, value: (typeof inline)[K]) => {
- setInline((current) => ({ ...current, [key]: value }));
- setError("");
- };
- /** 所挂区域沿父链找到最近的「省」节点(与后端 `province_of` 同口径:⛔ 按名字前缀猜)。 */
- const provinceId = useMemo(() => {
- if (!inline.regionId) return "";
- const byId = new Map(org.regions.map((item) => [item.id, item]));
- let node = byId.get(inline.regionId);
- // `Region.level` 是层级序号(0=省、1=市、2=区县;null=未定级,⛔ 按父子深度猜)。
- while (node && node.level !== 0 && node.parent) node = byId.get(node.parent);
- return node && node.level === 0 ? node.id : "";
- }, [org.regions, inline.regionId]);
- /** 运营商候选=所挂区域省份下可见的档案(省份一致性是后端硬校验 KLT-C008);为空则退回全量,由后端判定。 */
- const operatorOptions = useMemo(() => {
- const sameProvince = provinceId ? org.operators.filter((item) => item.region === provinceId) : [];
- return (sameProvince.length ? sameProvince : org.operators).map((item) => ({ id: item.id, name: item.name }));
- }, [org.operators, provinceId]);
- useEffect(() => {
- setInline((current) => (current.operatorId || !operatorOptions.length ? current : { ...current, operatorId: operatorOptions[0].id }));
- }, [operatorOptions]);
- useEffect(() => {
- setInline((current) => (current.teamId || !org.maintenanceTeams.length ? current : { ...current, teamId: org.maintenanceTeams[0].id }));
- }, [org.maintenanceTeams]);
- /** 区域换了 ⇒ 原运营商可能跨省,重新预选第一个(⛔ 留着让后端回 C008)。 */
- useEffect(() => {
- setInline((current) => {
- if (!provinceId || operatorOptions.some((item) => item.id === current.operatorId)) return current;
- return { ...current, operatorId: operatorOptions[0]?.id ?? "" };
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [provinceId]);
- const inlineSubjectOptions = (["enterprise", "individual", "sole_proprietor"] as const).map((code) => ({ code, name: SUBJECT_TYPE[code] ?? code }));
- const set = <K extends keyof Draft>(key: K, value: Draft[K]) => {
- setDraft((current) => ({ ...current, [key]: value }));
- setError("");
- setFieldError((current) => (current && REQUIRED_KEY_BY_DRAFT[key] === current.key ? null : current));
- };
- /** 命中必填项的字段红显+原话(需求 §5.3 第 522 行「不保存并红显该字段」)。 */
- const invalidOf = (key: ContractRequiredKey) => (fieldError?.key === key ? "true" : undefined);
- const requiredErrorOf = (key: ContractRequiredKey) => (fieldError?.key === key ? <span className="ops-field-error">{fieldError.message}</span> : null);
- const patchItem = (index: number, patch: Partial<ItemDraft>) => {
- setDraft((current) => ({ ...current, items: current.items.map((item, i) => (i === index ? { ...item, ...patch } : item)) }));
- setError("");
- };
- const removeItem = (index: number) => setDraft((current) => ({ ...current, items: current.items.filter((_, i) => i !== index) }));
- /** 换档位只换档位带出的口径(数量/带宽/价格),⛔ 清空已选出口——出口是独立于档位的目录配置。 */
- const pickPlan = (index: number, planId: string) => patchItem(index, { planId, planName: plans.find((plan) => plan.plan_id === planId)?.plan_name ?? "" });
- /** 线路出口只允许从套餐配置选择(2026-11-15 裁定):出口清单在「套餐配置 → 线路出口」维护。 */
- const toggleExit = (index: number, exit: string) => {
- const item = draft.items[index];
- const active = item.exits.includes(exit);
- if (!active && item.exits.length >= LINE_EXIT_MAX) {
- setError(`条目 ${index + 1} 的线路出口最多 ${LINE_EXIT_MAX} 个。`);
- return;
- }
- patchItem(index, { exits: active ? item.exits.filter((value) => value !== exit) : [...item.exits, exit] });
- };
- /** 合同级 IP 条目(04 册 §4.4):未勾选「有固定 IP 需求」⇒ 本表零行,勾选才给一条空行。 */
- const setNeedIp = (on: boolean) => {
- setDraft((current) => ({ ...current, needIp: on, ipRows: on ? (current.ipRows.length ? current.ipRows : [emptyIpRow(firstItemExit(current.items))]) : [] }));
- setError("");
- };
- const patchIpRow = (index: number, patch: Partial<IpRowDraft>) => {
- setDraft((current) => ({ ...current, ipRows: current.ipRows.map((row, i) => (i === index ? { ...row, ...patch } : row)) }));
- setError("");
- };
- const addIpRow = () => {
- setDraft((current) => ({ ...current, ipRows: [...current.ipRows, emptyIpRow(firstItemExit(current.items))] }));
- setError("");
- };
- const removeIpRow = (index: number) => {
- setDraft((current) => ({ ...current, ipRows: current.ipRows.filter((_, i) => i !== index) }));
- setError("");
- };
- /** 出口候选=套餐配置清单;历史数据里已出现的值也保留,避免旧合同编辑时选项凭空消失。 */
- const exitOptions = useMemo(() => {
- const names = (exitCatalog.data?.items ?? []).map((item) => item.exit_name);
- const legacy = [...draft.items.flatMap((item) => item.exits), ...draft.ipRows.map((row) => row.line_exit.trim()).filter(Boolean)];
- return [...new Set([...names, ...legacy])];
- }, [exitCatalog.data, draft.items, draft.ipRows]);
- /** 固定 IP 条目的出口候选=**上方服务构成条目已选出口**(2026-11-16 裁定,⛔ 全量目录)。 */
- const itemExitOptions = useMemo(
- () => [...new Set(draft.items.flatMap((item) => item.exits))],
- [draft.items],
- );
- async function save() {
- if (!identity) { setError("请先登录后再提交合同;写入权限由服务端判定。"); return; }
- if (submitting) return;
- if (!editing && !customerId && !freeText) { setError("请输入客户名称或信用码检索签约主体。"); return; }
- /** 未命中客户 ⇒ 内联建档段的必填集(CU-13 第 1 步;识别号同时是重试幂等键,⛔ 省)。 */
- if (!editing && !customerId) {
- const idNo = inline.idNo.trim().replace(/[\s-]/g, "").toUpperCase();
- const missing: string[] = [];
- if (!idNo) missing.push("客户识别号");
- if (!inline.regionId) missing.push("挂载区域");
- if (!inline.operatorId) missing.push("运营商");
- if (!inline.teamId) missing.push("运维团队");
- if (missing.length) { setError(`新建客户缺少:${missing.join("、")}(需求 §5.3 CU-13 第 1 步必填)`); return; }
- if (!/^[A-Z0-9]{18}$|^\d{15}$/.test(idNo)) {
- setError("客户识别号格式不符:应为 18 位统一社会信用代码/组织代码,或 15 位旧营业执照号。");
- return;
- }
- }
- const built = buildContractWrite(draft, tierValues);
- if (!built.ok) { setFieldError(built.fieldError ?? null); setError(built.error); return; }
- const w = built.write;
- /**
- * 写入口径必填 5 项(2026-11-14 探针实测 `contract/create@v1` 逐字段短路的 `60004`):
- * 付款周期(需求 §5.3 第 523 行)→ 合同金额(第 522 行「须大于 0…不保存并红显该字段」)→
- * 经办人姓名 → 经办人联系电话 → 交接单日期;提示语照抄后端原话并红显命中的那个字段,
- * `agent_org` 选填(不送也 `10000`)⇒ ⛔ 参与校验。校验同源 `domain/contract-draft`。
- */
- /** IP 条目随合同整表替换(04 册 §4.3);未勾选=送空数组=清空。⛔ 另送 `has_fixed_ip`:后端按 `ip_entries` 非空推导该触发位,`false` 却不带空表反而回 11103。 */
- const shared = {
- ...(w.externalNo ? { external_no: w.externalNo } : {}),
- contract_amount_cents: w.contractAmountCents,
- pay_cycle: w.payCycle,
- start_date: w.startDate,
- end_date: w.endDate,
- agent_name: w.agentName,
- agent_mobile: w.agentMobile,
- agent_handover_on: w.agentHandoverOn,
- /** `agent_org`=选填:恒送 trim 值(空串=后端 `text_param` 置 `NULL`),⛔ 因缺它而拦人。 */
- agent_org: w.agentOrg,
- /** 附件单值:空串=清空(后端 `text_param` 置 `NULL`)⇒ ⛔ 省略键,否则「移除附件」永远存不下去。 */
- attachment_url: w.attachmentUrl.trim(),
- service_items: w.serviceItems,
- ...(w.ipCarried ? { ip_entries: w.ipEntries } : {}),
- };
- setSubmitting(true);
- setError("");
- try {
- if (editing) {
- const row = record.data;
- if (!row?.contract_id) { setError("合同主键未取到,无法保存。"); return; }
- const version = Number(row.row_version);
- if (!row.contract_id || !Number.isFinite(version)) { setError("未取到合同主键或并发版本(row_version),无法保存。"); return; }
- await contractUpdate({
- contract_id: row.contract_id,
- row_version: version,
- ...shared,
- });
- // 落库成功 ⇒ 清单里的对象键已被合同引用(服务端也会拒删),⛔ 别再当孤儿回收。
- pendingAttachmentKeys.current = [];
- navigate(`/contracts/${encodeURIComponent(row.contract_id)}`);
- } else {
- const res = await contractCreate({
- ...shared,
- ...(draft.contractNo.trim() ? { contract_no: draft.contractNo.trim() } : {}),
- ...(customerId
- ? { customer_id: customerId }
- : {
- customer_inline: {
- customer_name: customerTerm.trim(),
- subject_type: inline.subject,
- id_code: inline.idNo.trim().replace(/[\s-]/g, "").toUpperCase(),
- ...(inline.contact.trim() ? { contact_name: inline.contact.trim() } : {}),
- ...(inline.phone.trim() ? { contact_mobile: inline.phone.trim() } : {}),
- ...(inline.address.trim() ? { address: inline.address.trim() } : {}),
- parent_node_id: inline.regionId,
- operator_id: inline.operatorId,
- ops_team_ids: [inline.teamId],
- // 影像本通道可留空;非企业⛔ 送(与 `/customer/create@v1` 同一条判据)。
- ...(inline.subject === "enterprise" && licenseObj ? { license: { object_key: licenseObj.object_key, file_name: licenseObj.file_name } } : {}),
- ...(inline.login.trim() ? { primary_username: inline.login.trim() } : {}),
- ...(inline.mobile.trim() ? { primary_mobile: inline.mobile.trim() } : {}),
- },
- }),
- });
- // 合同已生成 ⇒ 附件对象已被引用(服务端也会拒删)⇒ 清空孤儿清单。
- pendingAttachmentKeys.current = [];
- // 内联建档成功 ⇒ 停在回执页展示客户号与主账号(激活码明文由「导出激活码」取,⛔ 在此伪造)。
- if (res?.inline_customer) {
- setCreated({ contractId: res.contract_id, customer: res.inline_customer });
- return;
- }
- navigate(`/contracts/${encodeURIComponent(res?.contract_id ?? "")}`);
- }
- } catch (e) {
- setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。");
- setSubmitting(false);
- }
- }
- /**
- * 营业执照影像:选中即直传平台对象存储(与客户建档同一通路、同一前缀),成功后才把对象键挂进载荷。
- * 本通道**可留空**(业主 2026-11-16 定案);留空时回执会带 `license_pending`,
- * 由客户档案「登记材料」格补传。
- */
- async function pickLicense(file: File | null) {
- if (!file) return;
- setLicenseError("");
- setLicenseBusy(true);
- try {
- setLicenseObj(await uploadCustomerLicense(file));
- } catch (e) {
- setLicenseObj(null);
- setLicenseError((e as Error)?.message || "影像上传失败。");
- } finally {
- setLicenseBusy(false);
- }
- }
- /**
- * 合同附件:选中即直传平台桶(同一两段式通路,前缀换成合同附件),成功才写进草稿;
- * `attachment_url` 在提交时才随合同落库 ⇒ 上传成功但未保存=库里仍是旧附件。
- *
- * 孤儿回收(2026-11-16):上一份若也是**本页刚上传、还没落库**的,换掉的那一刻它就没人引用了
- * ⇒ 立刻退回服务端(库里那份仍在引用,由写口的 `attachment_object_delete` 回收,⛔ 在这里删)。
- */
- async function pickAttachment(file: File | null) {
- if (!file) return;
- setAttachmentError("");
- setAttachmentBusy(true);
- try {
- const previous = draft.attachmentUrl.trim();
- const uploaded = await uploadContractAttachment(file);
- if (previous && previous !== record.data?.attachment_url) {
- discardPendingAttachments([previous]);
- }
- pendingAttachmentKeys.current = [
- ...pendingAttachmentKeys.current.filter((key) => key !== previous),
- uploaded.object_key,
- ];
- set("attachmentUrl", uploaded.object_key);
- setAttachmentName(uploaded.file_name);
- } catch (e) {
- // 失败⛔ 清掉上一份:用户点的是「更换」,换失败时旧附件仍在库里,草稿也保持旧值。
- setAttachmentError((e as Error)?.message || "合同附件上传失败。");
- } finally {
- setAttachmentBusy(false);
- }
- }
- /** 现签查看地址只在「库里那一条=草稿这一条」时有效(刚换过/未保存的还没签)。 */
- const attachmentView = useMemo(() => {
- const current = draft.attachmentUrl.trim();
- if (!current) return "";
- const row = record.data;
- if (row && row.attachment_url === current) return row.attachment_view_url ?? "";
- return /^https?:\/\//i.test(current) ? current : "";
- }, [draft.attachmentUrl, record.data]);
- const attachmentLabelText = attachmentName || contractAttachmentLabel(draft.attachmentUrl);
- if (created) {
- const c = created.customer;
- return <section className="ops-page ops-record-page">
- <div className="ops-record-card customer-created-result">
- <h1>合同已生成,客户已随合同建档</h1>
- <p>客户资料按 <code>POST /customer/create@v1</code> 的同一套规则推入客户档案,再签本合同(两个事务,⛔ 合并)。</p>
- <dl>
- <dt>合同号</dt><dd>{created.contractId}</dd>
- <dt>客户号</dt><dd>{c.customer_id}</dd>
- <dt>客户名称</dt><dd>{c.customer_name ?? WORD_UNCONFIGURED}</dd>
- <dt>客户主账号</dt><dd>{c.primary_username ?? <Tri tone="missing" text="后端未下发" title="建档回执未带主账号登录名" />}</dd>
- <dt>服务开通状态</dt><dd>未开通(业务开通走工单)</dd>
- <dt>账号激活状态</dt><dd>未激活(待激活)</dd>
- <dt>激活码</dt><dd>{c.code_issued ? "已发放(明文不在本页展示)" : "本次未发码,见建档回执"}</dd>
- <dt>营业执照影像</dt><dd>{c.subject_type && c.subject_type !== "enterprise"
- ? "不适用(非企业主体无需营业执照)"
- : c.license_pending ? "本次留空 ⇒ 请到客户档案「登记材料」格补传" : "已登记"}</dd>
- </dl>
- <p className="ops-form-note">激活码请用客户列表的「导出激活码」经平台凭证通道取;⛔ 本页不留存明文。</p>
- <div className="ops-form-actions">
- <Button onClick={() => navigate(`/contracts/${encodeURIComponent(created.contractId)}`)}>查看合同详情</Button>
- <Button variant="outline" onClick={() => navigate(`/customers/${encodeURIComponent(c.customer_id)}`)}>查看客户档案</Button>
- </div>
- </div>
- </section>;
- }
- return <section className="ops-page ops-record-page contract-editor">
- <header className="ops-page-head">
- <div>
- <p className="ops-eyebrow"><span /> 合同管理 · {editing ? "编辑" : "新增"}</p>
- <h1>{editing ? "编辑合同" : "新增合同"}</h1>
- <p>{editing ? `合同 ${no}` : "录入合同与固定套餐式、自定义规格式两类服务构成。"}</p>
- </div>
- <div className="ops-head-actions">
- <Button variant="outline" size="sm" onClick={() => navigate("/contracts")}><ArrowLeft size={15} />返回合同台账</Button>
- </div>
- </header>
- {record.loading && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">正在从合同接口读取…</p></section></div>}
- {record.error && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="ops-form-error" role="alert">{record.error.message}</p><div className="ops-form-actions"><Button variant="outline" size="sm" onClick={() => navigate("/contracts")}>返回合同台账</Button></div></section></div>}
- {!record.loading && !record.error && editing && !record.data && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">未找到合同 {no},可能已被删除。请从合同台账重新进入,或返回台账检索。</p><div className="ops-form-actions"><Button variant="outline" size="sm" onClick={() => navigate("/contracts")}>返回合同台账</Button></div></section></div>}
- {(!editing || record.data) && <div className="ops-record-layout">
- <div className="ops-record-stack">
- <section className="ops-record-card">
- <h2>一、客户资料 <span>必填</span></h2>
- {editing ? (
- <div className="ops-form-grid ops-form-grid--business">
- <label htmlFor="contract-customer"><span className="ops-field-title">所属客户</span><Input id="contract-customer" value={customerLabel} readOnly disabled /></label>
- </div>
- ) : (
- <div className="ops-form-grid ops-form-grid--business">
- {/* 客户检索=输入框内下拉(业主 2026-11-16 定案):命中项直接挂在输入框下方,⛔ 另起「命中的客户档案」下拉框。 */}
- <div className="contract-customer-combobox ops-form-span-2" onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setCustomerOpen(false); }}>
- <label htmlFor="contract-customer" className="ops-field-title">客户名称或信用码 <b title="必填">*</b></label>
- <div className="contract-customer-combobox-control">
- <Input
- ref={customerInput}
- id="contract-customer"
- role="combobox"
- autoComplete="off"
- aria-expanded={showCustomerOptions}
- aria-controls="contract-customer-options"
- aria-autocomplete="list"
- aria-activedescendant={showCustomerOptions && activeCustomer >= 0 ? `contract-customer-option-${activeCustomer}` : undefined}
- placeholder="客户名称至少 2 个字,或输入统一社会信用代码"
- value={customerTerm}
- readOnly={Boolean(customerId)}
- onFocus={() => { if (!customerId) setCustomerOpen(true); }}
- onKeyDown={onCustomerKeyDown}
- onChange={(event) => { setCustomerTerm(event.target.value); setCustomerId(null); setCustomerOpen(true); setCustomerActive(0); setError(""); }}
- />
- {customerId && <button type="button" className="contract-customer-combobox-clear" aria-label="清除已选客户" title="清除已选客户" onClick={clearCustomer}><X size={14} /></button>}
- {showCustomerOptions && (
- <ul id="contract-customer-options" role="listbox" aria-label="命中的客户档案" className="contract-customer-combobox-options">
- {candidates.map((item, index) => <li
- key={item.customer_id}
- id={`contract-customer-option-${index}`}
- role="option"
- aria-selected={index === activeCustomer}
- className={index === activeCustomer ? "is-active" : undefined}
- onMouseDown={(event) => event.preventDefault()}
- onMouseEnter={() => setCustomerActive(index)}
- onClick={() => pickCustomer(item)}
- >
- <strong>{item.customer_name}</strong>
- {item.identity_no_masked && <span>{item.identity_no_masked}</span>}
- {item.province_name && <small>{item.province_name}</small>}
- </li>)}
- {/* 检索在飞时只加一行状态,⛔ 收起整个候选列表(收起再展开就是「抖动」)。 */}
- {searching && <li className="contract-customer-combobox-status" role="presentation">正在检索…</li>}
- </ul>
- )}
- </div>
- </div>
- </div>
- )}
- {lookup.error && !editing && <FetchError message={lookup.error.message} onRetry={lookup.reload} />}
- {/* 提示行常驻(⛔ 随请求起落显隐):检索状态只在候选列表内以一行「正在检索…」呈现,避免整块内容上下跳。 */}
- {!editing && !customerId && !lookup.error && <p className="contract-form-summary">{freeText ? CONTRACT_FREE_TEXT_HINT : CONTRACT_CUSTOMER_LOOKUP_HINT}</p>}
- {/**
- * 未命中 ⇒ 展开客户建档必填段(CU-13 第 1 步;业主 2026-11-16 定案):
- * 客户名称沿用上方检索框(保存时按它建档);命中已有客户时本段整段不出现。
- */}
- {!editing && !customerId && freeText && (
- <div className="ops-form-grid ops-form-grid--business">
- <label htmlFor="inline-subject"><span className="ops-field-title">主体类型 <b title="必填">*</b></span>
- <select id="inline-subject" value={inline.subject} onChange={(event) => setInlineField("subject", event.target.value)}>
- {inlineSubjectOptions.map((item) => <option key={item.code} value={item.code}>{item.name}</option>)}
- </select>
- </label>
- <label htmlFor="inline-id"><span className="ops-field-title">客户识别号 <b title="必填">*</b></span>
- <Input id="inline-id" placeholder="18 位统一社会信用代码 / 15 位旧执照号" value={inline.idNo} onChange={(event) => setInlineField("idNo", event.target.value)} />
- <small>同时是查重与重试幂等键:合同保存失败后重新保存会按它命中已建客户。</small>
- </label>
- <label htmlFor="inline-contact"><span className="ops-field-title">经办联系人</span><Input id="inline-contact" placeholder="客户方经办人" value={inline.contact} onChange={(event) => setInlineField("contact", event.target.value)} /></label>
- <label htmlFor="inline-phone"><span className="ops-field-title">联系电话</span><Input id="inline-phone" placeholder="支持固定电话或手机号" value={inline.phone} onChange={(event) => setInlineField("phone", event.target.value)} /></label>
- <label htmlFor="inline-address" className="ops-form-span-2"><span className="ops-field-title">地址</span><Input id="inline-address" placeholder="客户地址(含楼栋与房间号)" value={inline.address} onChange={(event) => setInlineField("address", event.target.value)} /></label>
- <label htmlFor="inline-region" className="ops-form-span-2"><span className="ops-field-title">挂载区域 <b title="必填">*</b></span>
- <TreeSelect treeData={regionTree} value={inline.regionId} onChange={(value) => setInlineField("regionId", value)} ariaLabel="挂载区域" placeholder="请选择区域节点" name="inline-region" />
- </label>
- <label htmlFor="inline-operator"><span className="ops-field-title">运营商 <b title="必填">*</b></span>
- <select id="inline-operator" value={inline.operatorId} onChange={(event) => setInlineField("operatorId", event.target.value)}>
- <option value="">请选择运营商</option>
- {operatorOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
- </select>
- <small>{provinceId ? "候选=所挂区域省份下可见的运营商档案(按需预选第一个,可改)。" : "先选挂载区域:运营商档案须与该区域同省,否则建档会被省份一致性校验拦下。"}</small>
- </label>
- <div className="customer-team-field"><span className="ops-field-title">运维团队 <b title="必填">*</b></span>
- <CustomerTeamSelect options={org.maintenanceTeams.map((item) => ({ id: item.id, name: item.name, hint: (item.ticketTypes ?? []).join("、") }))} value={inline.teamId} onChange={(id) => setInlineField("teamId", id)} />
- <small>单支定案:一个客户同一时刻恰好挂 1 支运维团队;默认预选范围内的第一支,可改。</small>
- </div>
- <label htmlFor="inline-login"><span className="ops-field-title">主账号登录名 <small>选填</small></span><Input id="inline-login" placeholder="留空按客户号派生" value={inline.login} onChange={(event) => setInlineField("login", event.target.value)} /></label>
- <label htmlFor="inline-mobile"><span className="ops-field-title">主账号绑定手机号 <small>选填</small></span><Input id="inline-mobile" inputMode="numeric" maxLength={11} placeholder="11 位手机号" value={inline.mobile} onChange={(event) => setInlineField("mobile", event.target.value)} /></label>
- {inline.subject === "enterprise" ? (
- <div className="ops-form-span-2 customer-document-picker">
- <div><strong>营业执照影像(本通道可留空)</strong>
- <label className="customer-upload-button" title="选择后立即直传平台对象存储(字节流不经过本系统)">
- <Upload size={15} />{licenseBusy ? "正在上传…" : licenseObj ? "重新选择" : "选择文件"}
- <input aria-label="上传营业执照影像" type="file" disabled={licenseBusy || submitting} onChange={(event) => { const file = event.target.files?.[0] ?? null; event.target.value = ""; void pickLicense(file); }} />
- </label>
- </div>
- <p>{licenseObj ? `已上传:${licenseObj.file_name}` : "留空=建档后到客户档案「登记材料」格补传;企业建档要求影像,本通道是唯一例外。"}</p>
- {licenseError && <small className="customer-field-error">{licenseError}</small>}
- </div>
- ) : null}
- </div>
- )}
- {editing && <p className="contract-form-summary">修改合同的客户归属需要后端提供迁移接口,此处不提供换客户。</p>}
- </section>
- <section className="ops-record-card">
- <h2>二、合同基本要素 <span>必填</span></h2>
- <div className="ops-form-grid ops-form-grid--business">
- <label htmlFor="contract-no"><span className="ops-field-title">合同编号 <small>{editing ? "服务端生成" : "可选"}</small></span><Input id="contract-no" placeholder={editing ? "" : "不填由服务端生成"} value={draft.contractNo} disabled={editing} onChange={(event) => set("contractNo", event.target.value)} /></label>
- <label htmlFor="external-no"><span className="ops-field-title">外部单号</span><Input id="external-no" placeholder="外部单号" value={draft.externalNo} onChange={(event) => set("externalNo", event.target.value)} /></label>
- <label htmlFor="contract-amount"><span className="ops-field-title">合同金额(元) <b title="必填">*</b></span><Input id="contract-amount" inputMode="decimal" placeholder="0.00" aria-invalid={invalidOf("amount")} value={draft.amount} onChange={(event) => set("amount", event.target.value)} />{requiredErrorOf("amount")}</label>
- <label htmlFor="pay-cycle"><span className="ops-field-title">付款周期 <b title="必填">*</b></span><select id="pay-cycle" aria-invalid={invalidOf("payCycle")} value={draft.payCycle} onChange={(event) => set("payCycle", event.target.value)}><option value="">未配置</option>{OPTIONS.pay_cycle.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</select>{requiredErrorOf("payCycle")}</label>
- <label htmlFor="start-date"><span className="ops-field-title">合同生效日</span><Input id="start-date" type="date" value={draft.start} onChange={(event) => set("start", event.target.value)} /></label>
- <label htmlFor="end-date"><span className="ops-field-title">合同结束日</span><Input id="end-date" type="date" value={draft.end} onChange={(event) => set("end", event.target.value)} /></label>
- {/* 运营商经办人=交接单口径的三段,独占一行(机构/姓名/联系方式),⛔ 与上面六个商务格混排。 */}
- <div className="ops-form-span-full contract-agent-block">
- <span className="ops-field-title">运营商经办人</span>
- <div className="ops-form-grid contract-agent-grid">
- <label htmlFor="agent-org"><span className="ops-field-title">机构 <small>选填</small></span><Input id="agent-org" placeholder="经办人所属机构" value={draft.agentOrg} onChange={(event) => set("agentOrg", event.target.value)} /><span className="ops-field-note">选填,不填也可提交;清空后保存即清除已记录的机构。</span></label>
- <label htmlFor="agent-name"><span className="ops-field-title">姓名 <b title="必填">*</b></span><Input id="agent-name" aria-invalid={invalidOf("agent")} value={draft.agent} onChange={(event) => set("agent", event.target.value)} />{requiredErrorOf("agent")}</label>
- <label htmlFor="agent-phone"><span className="ops-field-title">联系方式 <b title="必填">*</b></span><Input id="agent-phone" inputMode="numeric" aria-invalid={invalidOf("agentPhone")} value={draft.agentPhone} onChange={(event) => set("agentPhone", event.target.value)} />{requiredErrorOf("agentPhone")}<span className="ops-field-note">必填。当前登录身份未提供手机号时留空,请手工录入经办人实际联系电话。</span></label>
- </div>
- </div>
- {/*
- * 录入经办人=界面录入账号,服务端从鉴权上下文写入(⛔ 入参、建后恒只读):
- * 机构取账号绑定团队(运营/运维团队名,`hq` 回落「总运营」)、姓名取账号显示名、联系方式取绑定手机号(出参已掩码)。
- * 新建态只在提交后才拿得到机构,故此处不给可编辑控件,⛔ 让前端「代填」一个值造成与后端不一致。
- * 独占一行(`ops-form-span-full`),⛔ 与运营商经办人挤在同一行。
- */}
- <div className="ops-form-span-full contract-agent-readonly">
- <span className="ops-field-title">录入经办人 <small>=当前录入账号,提交时自动带入</small></span>
- <div className="contract-inline-group">
- <span className="contract-inline-seg"><small>机构</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_org || "未记录" : "取账号绑定团队"}</span></span>
- <span className="contract-inline-seg"><small>姓名</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_name || record.data?.created_by || "未记录" : identity?.name || "未登录"}</span></span>
- <span className="contract-inline-seg"><small>联系方式</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_mobile || "未绑定" : identity?.phone || "账号未绑手机号"}</span></span>
- </div>
- <span className="ops-field-note">这三段由录入时账号自动带入,建后恒只读(KLT-L221),不得手工改。</span>
- </div>
- <label htmlFor="handover-on"><span className="ops-field-title">交接单日期 <b title="必填">*</b></span><Input id="handover-on" type="date" aria-invalid={invalidOf("handoverOn")} value={draft.handoverOn} onChange={(event) => set("handoverOn", event.target.value)} />{requiredErrorOf("handoverOn")}</label>
- </div>
- {record.data?.source_label !== undefined && <p className="contract-form-summary">来源:{record.data.source_label === null ? WORD_UNCONFIGURED : record.data.source_label}{record.data.pay_cycle ? `;付款周期 ${record.data.pay_cycle} → ${label(PAY_CYCLE, record.data.pay_cycle)}` : ""}</p>}
- </section>
- <section className="ops-record-card">
- <h2>三、服务构成 <span>固定套餐式/自定义规格式</span></h2>
- {!plans.length && <p className="contract-form-summary">{catalog.error ? <>套餐配置取数失败:{catalog.error.message}</> : catalog.loading ? "正在载入套餐配置…" : "套餐配置暂无可选档位。"}</p>}
- <div className="ops-contract-items">
- {draft.items.map((item, index) => (
- <article key={`${item.itemId ?? "new"}-${index}`} className="ops-contract-item">
- <header className="ops-contract-item-head">
- <span className="ops-contract-index">条目 {index + 1}</span>
- <Button variant="ghost" size="sm" disabled={draft.items.length === 1} onClick={() => removeItem(index)}><Trash2 size={15} />删除</Button>
- </header>
- <div className="ops-form-grid ops-form-grid--business">
- <label><span className="ops-field-title">条目形态</span><select value={item.kind} onChange={(event) => patchItem(index, { kind: event.target.value as ItemDraft["kind"] })}><option value="plan_based">固定套餐式</option><option value="custom_spec">自定义规格式</option></select></label>
- {item.kind === "plan_based" ? <>
- <label><span className="ops-field-title">套餐档位</span><select value={item.planId} onChange={(event) => pickPlan(index, event.target.value)}><option value="">{catalog.loading ? "载入中…" : WORD_UNCONFIGURED}</option>{plans.map((plan) => <option key={plan.plan_id} value={plan.plan_id}>{plan.plan_name}</option>)}</select></label>
- <label><span className="ops-field-title">档位数量</span><Input type="number" min={1} value={item.quantity} onChange={(event) => patchItem(index, { quantity: Number(event.target.value) })} /></label>
- </> : <>
- <label><span className="ops-field-title">账号数</span><Input type="number" min={1} value={item.accountCount} onChange={(event) => patchItem(index, { accountCount: Number(event.target.value) })} /></label>
- <label><span className="ops-field-title">下行带宽(Mbps)</span><Input type="number" min={0} max={1000} value={item.bwDown} onChange={(event) => patchItem(index, { bwDown: Number(event.target.value) })} /></label>
- <label><span className="ops-field-title">上行带宽(Mbps)</span><Input type="number" min={0} max={1000} value={item.bwUp} onChange={(event) => patchItem(index, { bwUp: Number(event.target.value) })} /></label>
- <label><span className="ops-field-title">条目年价(元)</span><Input inputMode="decimal" placeholder="0.00" value={item.annualPrice} onChange={(event) => patchItem(index, { annualPrice: event.target.value })} /></label>
- {/* D-32:自定义规格补齐「用途分类」——订单方式与出账分类都按它派生,套餐式由所引目录档带出、此处不录。 */}
- <label><span className="ops-field-title">用途分类</span><select value={item.useCategory} onChange={(event) => patchItem(index, { useCategory: event.target.value })}><option value="">请选择用途分类</option>{Object.entries(USE_CATEGORY).map(([value, text]) => <option key={value} value={value}>{text}</option>)}</select></label>
- </>}
- <fieldset className="ops-form-span-full ops-contract-exit-fieldset">
- <legend>线路出口(从套餐配置选择,1–{LINE_EXIT_MAX} 个)</legend>
- {exitCatalog.error && <FetchError message={exitCatalog.error.message} onRetry={exitCatalog.reload} />}
- {!exitCatalog.error && !exitOptions.length && !exitCatalog.loading && <p className="contract-form-summary">套餐配置尚未配置线路出口;请先到「套餐配置 → 线路出口」维护。</p>}
- {!!exitOptions.length && <div className="ops-contract-exits">{exitOptions.map((exit) => {
- const active = item.exits.includes(exit);
- return <button type="button" key={exit} className={active ? "ops-contract-exit is-active" : "ops-contract-exit"} aria-pressed={active} onClick={() => toggleExit(index, exit)}>{exit}{active ? <X size={13} /> : <Plus size={13} />}</button>;
- })}</div>}
- <span className="ops-field-note">已选 {item.exits.length}/{LINE_EXIT_MAX}。线路出口在「套餐配置 → 线路出口」统一维护,此处只做选择。</span>
- </fieldset>
- </div>
- </article>
- ))}
- </div>
- <div className="ops-contract-item-actions">
- <p className="contract-form-summary"><span><strong>{draft.items.length}</strong> 个构成条目</span><span>套餐式 {draft.items.filter((item) => item.kind === "plan_based").length} · 自定义式 {draft.items.filter((item) => item.kind === "custom_spec").length}</span></p>
- <Button variant="outline" size="sm" onClick={() => setDraft((current) => ({ ...current, items: [...current.items, emptyItem()] }))}><Plus size={15} />添加条目</Button>
- </div>
- </section>
- <div className="ops-record-pair">
- <section className="ops-record-card">
- <h2>四、固定 IP 条目 <span>每条=线路出口+带宽档位+IP 数量</span></h2>
- <label className="ops-form-check"><input type="checkbox" checked={draft.needIp} onChange={(event) => setNeedIp(event.target.checked)} /><span>有固定 IP 需求(默认无固定 IP;勾上才核定 IP)</span></label>
- {!draft.ipCarried && <p className="contract-form-summary">读口没回 `ip_entries` 这个键=读不到已备案条目,本次提交不带 IP(拿空表覆盖会清掉库里已有的条目)。</p>}
- {draft.needIp ? <>
- <div className="ops-contract-ip-rows">{draft.ipRows.map((row, index) => (
- <div key={row.key} className="ops-contract-ip-row">
- <label><span className="ops-field-title">线路出口</span><select aria-label={`IP 条目 ${index + 1} 线路出口`} value={row.line_exit} onChange={(event) => patchIpRow(index, { line_exit: event.target.value })}><option value="">请选择服务构成出口</option>{[...new Set([...itemExitOptions, row.line_exit.trim()].filter(Boolean))].map((exit) => <option key={exit} value={exit}>{itemExitOptions.includes(exit) ? exit : `${exit}(不在服务构成已选出口中)`}</option>)}</select></label>
- <label><span className="ops-field-title">带宽档位</span><select aria-label={`IP 条目 ${index + 1} 带宽档位`} value={row.bandwidth_tier_mbps} onChange={(event) => patchIpRow(index, { bandwidth_tier_mbps: event.target.value })}><option value="">{WORD_UNCONFIGURED}</option>{[...tierOptions, ...(row.bandwidth_tier_mbps && !tierValues.includes(row.bandwidth_tier_mbps) ? [{ value: row.bandwidth_tier_mbps, label: `${row.bandwidth_tier_mbps}(目录外,需重新配置)` }] : [])].map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
- <label><span className="ops-field-title">IP 数量</span><Input type="number" min={1} max={IP_COUNT_MAX} aria-label={`IP 条目 ${index + 1} IP 数量`} value={row.ip_count} onChange={(event) => patchIpRow(index, { ip_count: event.target.value })} /></label>
- <Button variant="ghost" size="sm" onClick={() => removeIpRow(index)}><Trash2 size={15} />删除</Button>
- </div>
- ))}</div>
- {!itemExitOptions.length && <p className="contract-form-summary">上方服务构成条目尚未选择线路出口 ⇒ IP 条目没有可选项;请先在条目上勾选线路出口。</p>}
- <div className="ops-contract-item-actions"><Button variant="outline" size="sm" onClick={addIpRow}><Plus size={15} />添加 IP 条目</Button></div>
- <p className="contract-form-summary">每条=线路出口+带宽档位+IP 数量,三元组缺一项后端回 `KLT-L217`;带宽档位从「套餐配置 → 线路出口」的档位清单里选(可含「不承诺带宽」=该条 IP 不带带宽承诺,对应 `bandwidth_committed=false`)。出口<strong>只能从上方服务构成条目已选出口中选</strong>,初始默认带出第一个已选出口。</p>
- </> : <p className="contract-form-summary">未勾选=本表零行(提交时随合同送 `ip_entries: []`=清空旧条目)。</p>}
- </section>
- <section className="ops-record-card">
- <h2>五、合同附件 <span>可选 · 单份</span></h2>
- <div className="ops-contract-upload-list">
- {draft.attachmentUrl.trim()
- ? <div><span>{attachmentLabelText} · 已上传</span></div>
- : <div><Tri tone="missing" text={WORD_UNCONFIGURED} title="尚未选择附件文件" /></div>}
- </div>
- <input
- ref={attachmentInput}
- type="file"
- accept=".pdf,.ofd,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx"
- hidden
- aria-label="选择合同附件文件"
- onChange={(event) => { void pickAttachment(event.target.files?.[0] ?? null); event.target.value = ""; }}
- />
- <div className="ops-contract-item-actions">
- <Button variant="outline" size="sm" disabled={attachmentBusy || submitting} onClick={() => attachmentInput.current?.click()}>
- <Upload size={15} />{attachmentBusy ? "正在上传…" : draft.attachmentUrl.trim() ? "更换附件" : "选择并上传附件"}
- </Button>
- {attachmentView && <Button variant="ghost" size="sm" onClick={() => window.open(attachmentView, "_blank", "noopener,noreferrer")}>查看附件</Button>}
- {draft.attachmentUrl.trim() && <Button variant="ghost" size="sm" disabled={attachmentBusy || submitting} onClick={() => {
- // 移除的若是「本页刚上传、还没落库」的那一份 ⇒ 它当场失去引用,立即退回;
- // 库里那份仍被合同引用(保存后才由写口回收),这里⛔ 提前删。
- const current = draft.attachmentUrl.trim();
- if (current && current !== record.data?.attachment_url) discardPendingAttachments([current]);
- set("attachmentUrl", ""); setAttachmentName(""); setAttachmentError("");
- }}><X size={15} />移除</Button>}
- </div>
- {attachmentError && <p className="ops-form-error" role="alert">{attachmentError}</p>}
- <p className="contract-form-summary">文件选中即直传平台对象存储(字节流与上传凭证都不经本服务),成功后随合同保存对象键;单份,重传即替换,保存前不影响库里已有附件。查看地址由详情读口按需现签。</p>
- </section>
- </div>
- </div>
- <aside className="ops-record-side">
- <section className="ops-record-card">
- <h2>提交校验</h2>
- <div className="ops-contract-summary">
- <div><span>客户</span><strong>{editing ? customerLabel : (customerId ? candidates.find((item) => item.customer_id === customerId)?.customer_name ?? "" : freeText ? `${customerTerm.trim()}(自由录入)` : "待检索")}</strong></div>
- <div><span>合同编号</span><strong>{draft.contractNo || "服务端生成"}</strong></div>
- <div><span>合同金额</span><strong>{/^\d+(?:\.\d{1,2})?$/.test(draft.amount.trim()) ? `¥${Number(draft.amount).toLocaleString("zh-CN")}` : "待填写"}</strong></div>
- <div><span>付款周期</span><strong>{draft.payCycle ? label(PAY_CYCLE, draft.payCycle) : WORD_UNCONFIGURED}</strong></div>
- <div><span>合同期间</span><strong>{draft.start && draft.end ? `${draft.start} 至 ${draft.end}` : "待填写"}</strong></div>
- <div><span>构成条目</span><strong>{draft.items.length} 个</strong></div>
- <div><span>固定 IP 条目</span><strong>{draft.needIp ? `${draft.ipRows.length} 条/${draft.ipRows.reduce((sum, row) => sum + (Number(row.ip_count) || 0), 0)} 个 IP` : "无固定 IP 需求"}</strong></div>
- <div><span>附件</span><strong>{draft.attachmentUrl.trim() ? (attachmentBusy ? "上传中…" : attachmentLabelText) : "无附件"}</strong></div>
- </div>
- {error && <p className="ops-form-error" role="alert">{error}</p>}
- <div className="ops-form-actions"><Button size="sm" variant="outline" onClick={() => navigate(-1)}>取消</Button><Button size="sm" disabled={submitting || attachmentBusy || (editing && record.loading)} onClick={save}>{submitting ? "正在提交…" : editing ? "保存修改" : "提交合同"}</Button></div>
- </section>
- </aside>
- </div>}
- </section>;
- }
- const CONTRACT_FREE_TEXT_HINT = "未命中客户档案:继续填下方建档必填项,保存时先建客户档案(含客户主账号)再签本合同;命中后本段自动收起。";
- /** 检索进行中/尚无候选时的常驻提示(⛔ 用「正在检索」替换本行,那句话改成候选列表里的一行)。 */
- const CONTRACT_CUSTOMER_LOOKUP_HINT = "输入客户名称(至少 2 个字)或统一社会信用代码检索:命中项直接列在输入框下方,选中后可用 × 清除重选;未命中则继续填下方建档必填项。";
|