| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855 |
- /**
- * 合同写侧草稿口径(04 册 §4.2/§4.3/§4.4)。
- *
- * 「新增合同」与「详情内联编辑」共用这一份 Draft:详情页不再另开一条编辑路由,
- * 而是把同一份草稿按字段/条目拆开渲染。这里只放**纯函数**——读入口径适配、
- * 提交前校验与整段替换载荷的拼装,页面只负责把结果灌进受控组件。
- *
- * 纪律同 04 册 §4.2:保存形态=全量替换;套餐式⛔ 回传年价/月结算;
- * 出口只从「套餐配置 → 线路出口」目录选择。
- * 2026-11-17:合同级「固定 IP 条目」已下线(境外 IP 改由「套餐档位 × 订阅份数」表达),
- * 草稿不再持有 `ip_entries`/`has_fixed_ip`,读口也不再回该键。
- */
- import type { ContractEditScope, ContractGetResult, ContractServiceItem, ReplacementCandidate } from "../lib/api/types";
- import {
- centsToYuanText,
- checkContractRequired,
- checkItemExits,
- exitKey,
- yuanTextToCents,
- type ContractMissing,
- type ContractRequiredKey,
- } from "./contract-items";
- /** P1(D-9):条目形态。`new`=本条自带链路(旧口径);`increment`=引用本客户既有 link 订阅、只补叠加服务。 */
- export type ItemMode = "new" | "increment";
- let localSeq = 0;
- /** 本地树身份(⛔ 提交):新条目没有主键,树上的父子引用只能靠它,不能用数组下标(删除后会漂)。 */
- const localKey = () => `li-${(localSeq += 1)}`;
- /**
- * 服务条目编辑态:D-15 后条目只剩「档位 × 份数 × 出口」。
- *
- * `planFamily` 只做界面判据(`link` 份数恒 1、`addon` 份数可 > 1、IP 汇总只看 `addon`),
- * 提交时⛔ 回传——形态由后端从所引档位带入(`item_family`)。
- *
- * P1 起多了两棵树上的关系(D-7/D-9):
- * - `parentKey`=父条目的**本地 key**(仅 `new` 的 `addon`;顶层=`null`)。落库换 `serves_item_id`/
- * `serves_item_index`,⛔ 把下标写进草稿——删掉中间的条目后下标就指错了。
- * - `itemMode='increment'` + `refSubscriptionId`=增量合同的只读父节点(引用既有订阅,父不在本合同内)。
- */
- export type ItemDraft = {
- /** 本地树身份;读口行沿用条目主键,新建行现发(⛔ 提交)。 */
- key: string;
- itemId?: string | null;
- planId: string;
- planName: string;
- planFamily: string;
- quantity: number;
- exits: string[];
- /** 被替换的原订阅(空串=按新订阅开通);进 `service_items[].succession`,仅新建合同受理。 */
- replacesSubscriptionId: string;
- /** 所选候选是否为定制档(=后端候选行的 `customized`;定制档须用户显式确认)。 */
- replacementCustomized: boolean;
- /** 定制档替换的显式勾选(未勾选⛔ 提交)。 */
- replacementConfirmed: boolean;
- /** 「改为按新订阅开通」:用户显式否决替换(候选仍在时也不再勾选)。 */
- replacementOptOut: boolean;
- /** P1(D-7):父条目本地 key;顶层条目(`link`/`increment`)恒 `null`。 */
- parentKey: string | null;
- /** P1(D-9):条目形态;读侧缺省按 `new`。 */
- itemMode: ItemMode;
- /** P1(D-9):`increment` 引用的既有链路订阅号(可跨合同);`new` 恒空串。 */
- refSubscriptionId: string;
- /** 被引用订阅的展示原文(来源合同/套餐/出口);只用于只读节点标注,⛔ 提交。 */
- refSubscriptionLabel?: string;
- };
- export type ContractDraft = {
- contractNo: string;
- externalNo: string;
- /** 合同类型:`new`(新建)/`renew`(续签)/`expand`(扩容补充协议)/`change`(变更协议)。 */
- contractType: string;
- /**
- * 签署日期(`YYYY-MM-DD`,必填,等同原「交接日期」):同时是写入口径 `agent_handover_on`
- * 的来源(业主 2026-11-19 定案:交接日期即签署日期,表单只留一个日期框)。
- */
- signDate: string;
- amount: string;
- /**
- * 折扣率(百分数,默认 `100`):最终合同金额=套餐总金额×本值/100。
- * 套餐总=Σ(档位年价×份数×出口系数);折扣只改合同总额,不进订阅冻结价。
- */
- discountRate: string;
- /** 服务期(月,1~600):替代原「付款周期」,结束日=生效日+服务期−1 天。 */
- serviceMonths: string;
- start: string;
- end: string;
- agent: string;
- agentPhone: string;
- attachmentUrl: string;
- /** 经办人机构=选填(实测不送也 `10000`、读回 `null`),⛔ 当必填拦人。 */
- agentOrg: string;
- items: ItemDraft[];
- /**
- * P1(D-9):增量合同=**页面级录入模式**,⛔ 落合同级字段。
- * 后端从条目 `item_mode` 派生(全部 `increment` ⇒ 详情/列表打「增量」标签)。
- */
- increment: boolean;
- };
- /** 改动即撤掉该字段的必填红显(Draft 键 → 必填校验字段键)。 */
- export const REQUIRED_KEY_BY_DRAFT: Partial<Record<keyof ContractDraft, ContractRequiredKey>> = {
- serviceMonths: "serviceMonths",
- amount: "amount",
- start: "start",
- agent: "agent",
- agentPhone: "agentPhone",
- signDate: "signDate",
- };
- export const emptyItem = (parentKey: string | null = null, itemMode: ItemMode = "new"): ItemDraft => ({
- key: localKey(),
- planId: "",
- planName: "",
- planFamily: "",
- quantity: 1,
- exits: [],
- replacesSubscriptionId: "",
- replacementCustomized: false,
- replacementConfirmed: false,
- replacementOptOut: false,
- parentKey,
- itemMode,
- refSubscriptionId: "",
- });
- /**
- * 候选选择矩阵(2026-11-17,纯函数以便打表单测;页面只负责把结果灌回草稿):
- *
- * - 0 个候选 ⇒ 不替换(按新订阅开通)。
- * - 1 个或多个候选 ⇒ **不预选**(D-CT-10/09 册 TC-CU-74:替换须显式勾选;未勾选⛔ 派生替换关系)。
- * 沿用已选且仍在候选里的那个;用户显式「改为按新订阅开通」(`optOut`)时清空。
- *
- * 选中项已不在候选里(换了档位/出口/客户,或刚被别处替换)⇒ 归零,⛔ 保留一个不存在的订阅号提交。
- */
- export function resolveReplacementSelection(
- candidates: readonly ReplacementCandidate[],
- current: string,
- optOut: boolean,
- ): { id: string; customized: boolean } {
- if (optOut) return { id: "", customized: false };
- const picked = candidates.find((candidate) => candidate.subscription_id === current);
- if (picked) return { id: picked.subscription_id, customized: Boolean(picked.customized) };
- return { id: "", customized: false };
- }
- /** 该候选是否定制档(后端候选行 `customized`;定制档须显式勾选确认)。 */
- export function isCustomizedCandidate(
- candidates: readonly ReplacementCandidate[],
- id: string,
- ): boolean {
- return Boolean(candidates.find((candidate) => candidate.subscription_id === id)?.customized);
- }
- /* ── 合同类型/服务期(2026-11-19) ───────────────────────────────── */
- /**
- * 合同类型值域与中文口径(与后端 `bos-invariant::CONTRACT_TYPES` 同字)。
- *
- * 语义:`new`=新建;`renew`=续签(须选中「续签自旧合同」);`expand`=扩容补充协议
- * (服务构成整批为增量叠加服务,不新开链路);`change`=变更协议(可含逐条替换)。
- */
- export const CONTRACT_TYPES: ReadonlyArray<{ value: string; label: string }> = [
- { value: "new", label: "新建" },
- { value: "renew", label: "续签" },
- { value: "expand", label: "扩容补充协议" },
- { value: "change", label: "变更协议" },
- ];
- export const CONTRACT_TYPE_LABEL: Record<string, string> = Object.fromEntries(
- CONTRACT_TYPES.map((item) => [item.value, item.label]),
- );
- /**
- * 「服务期(月)」标题右侧的快捷档:月/季/年/3 年(点一下把月数填进去)。
- *
- * 「5 年」已下线(业主 2026-11-19):快捷档只做常见租期的填充,更长租期直接输月数
- * (输入框仍收 1~600,60 个月照样填得进去,⛔ 因此收窄值域)。
- */
- export const SERVICE_MONTH_PRESETS: ReadonlyArray<{ label: string; months: number }> = [
- { label: "月", months: 1 },
- { label: "季", months: 3 },
- { label: "年", months: 12 },
- { label: "3 年", months: 36 },
- ];
- /** 结束日只读原因(新建表单与详情内联编辑共用一句,⛔ 各写一份)。 */
- export const CONTRACT_END_DERIVED = "合同结束日由「生效日+服务期(月)」自动推算(生效日加服务期月数再减一天),不可手改";
- /**
- * 合同金额只读原因(与结束日同形):金额=服务构成自动汇总,⛔ 手填。
- * 口径=改造稿 D-15「合同金额=Σ(所引档 annual_price_cents × quantity)」。
- */
- export const CONTRACT_AMOUNT_DERIVED = "最终合同金额=套餐总×折扣率(套餐总=档位年价×份数×计费系数),不可手改;改档位/份数/出口/折扣率即重算";
- /** 档位取年价所需的最小形状(目录行/测试替身都够用)。 */
- export type PlanPriceRef = { plan_id: string; annual_price_cents: number };
- /** 出口系数目录行(合同页只读带出;系数只挂线路出口目录)。 */
- export type ExitFactorRef = {
- exit_name: string;
- exit_key?: string;
- price_factor?: number | null;
- };
- /** 解析计费系数:空/非法 ⇒ `null`;合法 ⇒ `(0, 1]`(最多两位小数)。 */
- export function parsePriceFactor(raw: string): number | null {
- const text = raw.trim();
- if (!text) return null;
- if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
- const value = Number(text);
- if (!Number.isFinite(value) || value <= 0 || value > 1) return null;
- return value;
- }
- /** `floor(cents × factor)`:计费系数最多两位小数,与后端 `apply_price_factor_cents` 同口径。 */
- export function applyPriceFactorCents(cents: number, factor: number): number {
- if (!Number.isFinite(cents) || !Number.isFinite(factor) || factor <= 0 || factor > 1) return 0;
- if (factor === 1) return Math.trunc(cents);
- const scaled = Math.round(factor * 100);
- return Math.floor((cents * scaled) / 100);
- }
- /** `floor(package × discountPct / 100)`:折扣率最多两位小数。 */
- export function applyDiscountCents(packageCents: number, discountPct: number): number {
- if (!Number.isFinite(packageCents) || !Number.isFinite(discountPct) || discountPct <= 0) return 0;
- if (discountPct === 100) return Math.trunc(packageCents);
- const scaled = Math.round(discountPct * 100);
- return Math.floor((packageCents * scaled) / 10_000);
- }
- /** 按出口原文取目录系数(缺省 1);归一化键与 `exitKey` 同源。 */
- export function exitPriceFactor(
- exits: readonly string[],
- catalog: readonly ExitFactorRef[],
- ): number {
- const name = exits[0];
- if (!name) return 1;
- const key = exitKey(name);
- const hit = catalog.find((row) => (row.exit_key ? row.exit_key === key : exitKey(row.exit_name) === key));
- const factor = hit?.price_factor;
- return factor && factor > 0 && factor <= 1 ? factor : 1;
- }
- /**
- * 合同金额=套餐总×折扣率(套餐总=Σ(年价×份数×出口系数))。
- *
- * - 尚无已选档位 ⇒ `empty`(金额清空,等条目配齐);
- * - 已选档位但目录里还找不到(目录未载完/档已下架)⇒ `incomplete`(保留现值,⛔ 用 0 覆盖);
- * - 全部命中 ⇒ `ok`:`packageCents`=折前套餐总,`finalCents`/`text`=折后最终合同金额。
- */
- export function deriveContractAmount(
- items: readonly Pick<ItemDraft, "planId" | "quantity" | "exits">[],
- plans: readonly PlanPriceRef[],
- exitCatalog: readonly ExitFactorRef[] = [],
- discountRatePct = 100,
- ): { ok: true; packageCents: number; finalCents: number; cents: number; text: string } | { ok: false; reason: "empty" | "incomplete" } {
- const priced = items.filter((item) => item.planId);
- if (!priced.length) return { ok: false, reason: "empty" };
- const byId = new Map(plans.map((plan) => [plan.plan_id, plan]));
- let packageCents = 0;
- for (const item of priced) {
- const plan = byId.get(item.planId);
- if (!plan) return { ok: false, reason: "incomplete" };
- const quantity = Number.isInteger(item.quantity) && item.quantity > 0 ? item.quantity : 1;
- const unit = applyPriceFactorCents(plan.annual_price_cents, exitPriceFactor(item.exits, exitCatalog));
- packageCents += unit * quantity;
- }
- const finalCents = applyDiscountCents(packageCents, discountRatePct > 0 ? discountRatePct : 100);
- return {
- ok: true,
- packageCents,
- finalCents,
- cents: finalCents,
- text: centsToYuanText(finalCents),
- };
- }
- /** 解析折扣率输入:空/非法 ⇒ `null`;合法 ⇒ `[1, 100]`(最多两位小数)。 */
- export function parseDiscountRate(raw: string): number | null {
- const text = raw.trim();
- if (!text) return null;
- if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
- const value = Number(text);
- if (!Number.isFinite(value) || value < 1 || value > 100) return null;
- return value;
- }
- /**
- * 业务当天(`Asia/Shanghai`,`YYYY-MM-DD`)。
- *
- * ⛔ 用 `toISOString().slice(0,10)`:那是 UTC,晚 8 点后日期会跳到次日,运维晚上录合同
- * 就会拿到明天的日期并把它当成「录入当日」的签署日期。
- */
- export function businessToday(now: Date = new Date()): string {
- const parts = new Intl.DateTimeFormat("en-CA", {
- timeZone: "Asia/Shanghai",
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- }).formatToParts(now);
- const pick = (type: string) => parts.find((part) => part.type === type)?.value ?? "";
- return `${pick("year")}-${pick("month")}-${pick("day")}`;
- }
- /** 该年该月的天数(1 基月份;按 UTC 算,⛔ 受本机时区影响)。 */
- const daysInMonth = (year: number, month: number) => new Date(Date.UTC(year, month, 0)).getUTCDate();
- /**
- * 合同结束日=**生效日 + 服务期(月) − 1 天**(2026-11-19 起合同只录服务期月数)。
- *
- * 与后端 `subscription::add_months_clamped` 同一式:加月后该月无对应日**先取月末**,再减一天
- * (1-31 起、1 个月 ⇒ 2-28 → 2-27)。服务期缺失/非法 ⇒ 返回空串,让页面显式提示
- * 「先填生效日与服务期」,⛔ 留一个陈旧的结束日。
- */
- export function contractEndFromMonths(start: string, monthsRaw: string | number): string {
- const months = typeof monthsRaw === "number" ? monthsRaw : Number(String(monthsRaw).trim());
- if (!Number.isInteger(months) || months < 1 || months > 600) return "";
- if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) return "";
- const [year, month, day] = start.split("-").map(Number);
- if (!year || !month || !day) return "";
- const total = year * 12 + (month - 1) + months;
- const nextYear = Math.floor(total / 12);
- const nextMonth = (total % 12) + 1;
- const clampedDay = Math.min(day, daysInMonth(nextYear, nextMonth));
- const end = new Date(Date.UTC(nextYear, nextMonth - 1, clampedDay));
- end.setUTCDate(end.getUTCDate() - 1);
- return end.toISOString().slice(0, 10);
- }
- /** 由起止日反推服务期(月,两端月份计入):仅用于存量行没有 `service_months` 时的展示兜底。 */
- export function serviceMonthsFromPeriod(start: string | null | undefined, end: string | null | undefined): number | null {
- if (!start || !end || !/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) return null;
- const [sy, sm] = start.split("-").map(Number);
- const [ey, em] = end.split("-").map(Number);
- if (!sy || !sm || !ey || !em) return null;
- const months = (ey - sy) * 12 + (em - sm) + 1;
- return months > 0 ? months : null;
- }
- /**
- * 「生效日 → 结束日」能撑满的服务期月数:**最小的 m** 使「生效日+m 月−1 天 ≥ 结束日」。
- *
- * 扩容补充协议用(2026-11-19 业主定案):到期日锁在原合同止期、生效日可配,
- * 服务期跟着生效日重算。⛔ 用 [`serviceMonthsFromPeriod`] 的「月份数+1」口径:
- * 那是按整月数月份差算的,遇到止期日号小于生效日号时会多算一个月。
- */
- export function serviceMonthsBetween(start: string, end: string): number | null {
- if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end) || end < start) return null;
- let months = Math.max(1, serviceMonthsFromPeriod(start, end) ?? 1);
- /** 先往回收(同一结束日可能有多个 m 满足),再往上推,保证取最小可行值。 */
- while (months > 1 && contractEndFromMonths(start, months - 1) && contractEndFromMonths(start, months - 1) >= end) months -= 1;
- while (months < 600 && (!contractEndFromMonths(start, months) || contractEndFromMonths(start, months) < end)) months += 1;
- return months;
- }
- export const emptyDraft = (): ContractDraft => ({
- contractNo: "",
- externalNo: "",
- contractType: "new",
- signDate: "",
- amount: "",
- discountRate: "100",
- serviceMonths: "12",
- start: "",
- end: "",
- agent: "",
- agentPhone: "",
- attachmentUrl: "",
- agentOrg: "",
- items: [emptyItem()],
- increment: false,
- });
- /** 金额「分 → 元」:缺失/null 一律留空由必填校验拦下,⛔ 填 0 冒充已配置;算术走整数分口径。 */
- export const centsToInput = (cents: number | null | undefined) => (cents === null || cents === undefined ? "" : centsToYuanText(cents));
- const itemFromRow = (item: ContractServiceItem): ItemDraft => {
- return {
- key: item.item_id || localKey(),
- itemId: item.item_id ?? null,
- planId: item.plan_id ?? "",
- planName: item.plan_name ?? "",
- planFamily: item.item_family ?? "",
- quantity: item.quantity ?? 1,
- exits: item.line_exits ?? [],
- /** 读口回带的条目已落库,编辑合同⛔ 受理替换 ⇒ 草稿一律以「不替换」为基线。 */
- replacesSubscriptionId: "",
- replacementCustomized: false,
- replacementConfirmed: false,
- replacementOptOut: false,
- /** 读口回来的是主键(`serves_item_id`),下面由 `draftFromRow` 统一折算成本地 key。 */
- parentKey: null,
- itemMode: item.item_mode === "increment" ? "increment" : "new",
- refSubscriptionId: item.ref_subscription_id ?? "",
- };
- };
- export const draftFromRow = (row: ContractGetResult | null | undefined): ContractDraft => {
- const rows = row?.service_items ?? [];
- const items = rows.map(itemFromRow);
- /** 主键 → 本地 key:父引用在草稿里必须换成本地身份,才能在新条目插入/删除后仍指对行。 */
- const keyById = new Map<string, string>();
- rows.forEach((item, index) => {
- if (item.item_id) keyById.set(item.item_id, items[index].key);
- });
- rows.forEach((item, index) => {
- if (item.serves_item_id) items[index].parentKey = keyById.get(item.serves_item_id) ?? null;
- });
- return {
- contractNo: row?.contract_no ?? "",
- externalNo: row?.external_no ?? "",
- contractType: row?.contract_type ?? "new",
- signDate: row?.sign_date ?? row?.agent_handover_on ?? "",
- amount: centsToInput(row?.contract_amount_cents ?? row?.amount_cents),
- discountRate: row?.discount_rate_pct === null || row?.discount_rate_pct === undefined
- ? "100"
- : String(row.discount_rate_pct),
- serviceMonths: row?.service_months === null || row?.service_months === undefined
- ? String(serviceMonthsFromPeriod(row?.start_date, row?.end_date) ?? "")
- : String(row.service_months),
- start: row?.start_date ?? "",
- end: row?.end_date ?? "",
- agent: row?.agent_name ?? "",
- agentPhone: row?.agent_mobile ?? "",
- agentOrg: row?.agent_org ?? "",
- attachmentUrl: row?.attachment_url ?? "",
- items,
- /** 全条目皆增量 ⇒ 本合同是增量合同(后端不存合同级列,这里同样只做派生)。 */
- increment: items.length > 0 && items.every((item) => item.itemMode === "increment"),
- };
- };
- /* ── P1 树形(D-7):录入/详情共用同一份分组口径 ─────────────────────── */
- export type ItemTreeNode = {
- item: ItemDraft;
- /** 该条目在 `items` 里的 0 基下标(提交载荷按它排序)。 */
- index: number;
- children: { item: ItemDraft; index: number }[];
- };
- /** 父条目本地 key → 下标(父引用一律按 key 查,⛔ 按数组下标)。 */
- export function itemIndexByKey(items: readonly ItemDraft[]): Map<string, number> {
- return new Map(items.map((item, index) => [item.key, index]));
- }
- /**
- * 平铺草稿 → 两级树(D-7:只有两级,`addon` 不能再挂 `addon`)。
- *
- * 根=没有父引用(`link`/`increment`)或父引用已失效的行(存量脏数据也要看得见,
- * ⛔ 让它从界面上凭空消失);子行挂在父后面,保持原数组顺序。
- */
- export function itemTree(items: readonly ItemDraft[]): ItemTreeNode[] {
- const byKey = new Map(items.map((item) => [item.key, item]));
- const roots: ItemTreeNode[] = [];
- const nodeOf = new Map<string, ItemTreeNode>();
- items.forEach((item, index) => {
- const parentAlive = item.parentKey ? byKey.has(item.parentKey) : false;
- if (!item.parentKey || !parentAlive) {
- const node: ItemTreeNode = { item, index, children: [] };
- roots.push(node);
- nodeOf.set(item.key, node);
- }
- });
- items.forEach((item, index) => {
- if (!item.parentKey) return;
- const parent = nodeOf.get(item.parentKey);
- if (parent) parent.children.push({ item, index });
- /** 父引用指向的不是根(三级/父已被挂走)⇒ 作为根出现,宁可显示怪也不吞掉这一行。 */
- else if (!roots.some((node) => node.item.key === item.key)) roots.push({ item, index, children: [] });
- });
- return roots;
- }
- /** 删父要连带删哪些行(含父本身);提示里用它报数量,⛔ 静默级联。 */
- export function itemSubtreeKeys(items: readonly ItemDraft[], key: string): string[] {
- const children = items.filter((item) => item.parentKey === key).map((item) => item.key);
- return [key, ...children];
- }
- /**
- * 条目**实际提交**的线路出口(2026-11-19 业主定案):
- *
- * - **叠加服务不单独选线路出口**:子行恒依从其跨境链路父条目的出口;
- * - 增量叠加服务(`itemMode='increment'`)依从被引用的既有链路订阅——该出口在建条目时由
- * 页面从订阅行带入 `exits`,这里保持原值(父不在本合同内,草稿里找不到它);
- * - 跨境链路条目仍取自身所选。
- *
- * 后端对每条 `line_exits` 要求恰 1 个、且子行 ⊆ 父行 ⇒ 统一由本函数收口,⛔ 让子行按
- * 自己残留的旧出口提交(否则会报「不在父条目出口内」)。
- */
- export function resolvedItemExits(items: readonly ItemDraft[], item: ItemDraft): string[] {
- if (item.itemMode === "increment" || item.planFamily === "link") return item.exits;
- if (!item.parentKey) return item.exits;
- const parent = items.find((row) => row.key === item.parentKey);
- return parent ? parent.exits : item.exits;
- }
- /**
- * 续签的新合同生效日(2026-11-17 四轮):旧合同**结束日次日**;若该日已早于业务当天
- * (合同已过期一段时间才续签),取**业务当天**——续签不能倒签一段已经开始履行的期间。
- *
- * ⛔ 直接沿用旧合同的生效日:那是上一份合同的起点,本合同的开始日必须接在旧期间之后,
- * 否则新旧订阅期间相交 ⇒ 后端按「替换」处理(截原+第七类工单),与续签语义相反。
- */
- export function renewalStartOf(oldEnd: string | null | undefined, today: string = businessToday()): string {
- const end = (oldEnd ?? "").trim();
- if (!/^\d{4}-\d{2}-\d{2}$/.test(end)) return today;
- const [year, month, day] = end.split("-").map(Number);
- const next = new Date(Date.UTC(year, month - 1, day + 1)).toISOString().slice(0, 10);
- return next > today ? next : today;
- }
- /**
- * 扩容补充协议的生效日兜底(2026-11-19):默认业务当天;旧合同尚未开始 ⇒ 取旧合同生效日;
- * 当天已过旧止期 ⇒ 取旧止期(保证「生效日 ≤ 到期日」,服务期至少 1 个月)。
- */
- function expandStartOf(oldStart: string, oldEnd: string, today: string): string {
- const candidate = oldStart && today < oldStart ? oldStart : today;
- return oldEnd && candidate > oldEnd ? oldEnd : candidate;
- }
- /**
- * 承接旧合同的预填(2026-11-19 口径,三种非「新建」类型共用一份口径):
- *
- * - `renew`(续签):带出服务期/服务条目/经办人三件套,生效日=旧结束日次日
- * (不早于业务当天,见 [`renewalStartOf`]),结束日按生效日+服务期推算;提交带
- * `renew_from_contract_id`。合同金额由页面按服务构成自动汇总,⛔ 带入旧总额。
- * - `expand`(扩容补充协议):**不带金额**(补充协议金额是增量口径)、**不带服务构成**
- * (增量模式按既有链路订阅逐条添加,照抄旧条目会变成「自建链路」);到期日锁在旧合同止期,
- * 生效日可配(默认业务当天,⛔ 晚于旧止期),服务期=生效日撑到旧止期的月数。
- * - `change`(变更协议):带出服务期/服务条目作底稿(金额随条目自动汇总);期间沿用旧合同
- * (生效日/到期日都取旧合同真值,可改,⛔ 按续签口径推到旧止期次日)。
- *
- * ⛔ 三种类型都带:合同编号/外部单号(新合同要发新号)、附件(旧合同的影像不是本合同的凭证)、
- * 签署日期(默认录入当日;旧合同那一张是上一份合同的凭证)。
- * `item_id` 必须清空——新建态条目主键由服务端发号,原样回传会被写口按「改条目」点名拒绝。
- */
- export type RenewalPrefill = Partial<
- Pick<ContractDraft, "contractType" | "amount" | "serviceMonths" | "start" | "end" | "agent" | "agentPhone" | "agentOrg" | "items">
- >;
- export function renewalPrefill(
- row: ContractGetResult | null | undefined,
- today: string = businessToday(),
- contractType: "renew" | "expand" | "change" = "renew",
- ): RenewalPrefill | null {
- if (!row) return null;
- const base = draftFromRow(row);
- /** 经办人三件套三种类型都带(交接单上的运营商侧联系人不会因为协议种类而变)。 */
- const agent = { agent: base.agent, agentPhone: base.agentPhone, agentOrg: base.agentOrg };
- if (contractType === "expand") {
- /**
- * 扩容补充协议:到期日锁在旧合同止期,生效日默认业务当天(旧止期已过 ⇒ 取旧止期当天,
- * 让服务期至少 1 个月),服务期=生效日撑到旧止期。
- */
- const end = base.end;
- /** 原合同没有固定止期(长期)⇒ 一格都不带:仍按「生效日+服务期」推算到期日,⛔ 锁死空格子。 */
- if (!/^\d{4}-\d{2}-\d{2}$/.test(end)) return { contractType: "expand", ...agent };
- const start = expandStartOf(base.start, end, today);
- const months = serviceMonthsBetween(start, end);
- return {
- contractType: "expand",
- ...(months === null ? {} : { serviceMonths: String(months) }),
- start,
- end,
- ...agent,
- };
- }
- if (contractType === "change") {
- /** 变更协议:期间沿用旧合同真值(到期日可改),服务构成作底稿;金额由页面按条目汇总。 */
- return {
- contractType: "change",
- serviceMonths: base.serviceMonths,
- start: base.start,
- end: base.end,
- ...agent,
- items: (base.items.length ? base.items : [emptyItem()]).map((item) => ({ ...item, itemId: null })),
- };
- }
- return {
- contractType: "renew",
- serviceMonths: base.serviceMonths,
- start: renewalStartOf(base.end, today),
- ...agent,
- items: (base.items.length ? base.items : [emptyItem()]).map((item) => ({ ...item, itemId: null })),
- };
- }
- /**
- * 冻结守卫:草稿相对基线改了哪些**当前不可改**的字段,返回中文名供页面阻断保存。
- *
- * 判据来源=后端下发的 `edit_scope`(两轴各自独立判定,04 册 §4.2,2026-11-15 定稿),
- * ⛔ 页面自己按 `opened` 推——「已生效未开通」只冻计费轴、档案轴仍可改,一刀切会把
- * 合法的外部单号修改挡掉。
- *
- * 字段口径与页面锁定范围必须同源,否则会出现「锁了能存」或「没锁却拦」。
- */
- export function frozenChanges(
- draft: ContractDraft,
- baseline: ContractDraft,
- scope: Pick<ContractEditScope, "billing" | "archive"> | null | undefined,
- ): string[] {
- if (!scope) return [];
- const changed: string[] = [];
- if (!scope.billing.editable) {
- if (draft.amount !== baseline.amount) changed.push("合同金额");
- if (draft.discountRate !== baseline.discountRate) changed.push("折扣率");
- if (draft.serviceMonths !== baseline.serviceMonths) changed.push("服务期(月)");
- if (draft.start !== baseline.start) changed.push("合同生效日");
- if (draft.end !== baseline.end) changed.push("合同结束日");
- if (JSON.stringify(draft.items) !== JSON.stringify(baseline.items)) changed.push("服务构成");
- }
- if (!scope.archive.editable) {
- if (draft.contractType !== baseline.contractType) changed.push("合同类型");
- if (draft.signDate !== baseline.signDate) changed.push("签署日期");
- if (draft.externalNo !== baseline.externalNo) changed.push("外部单号");
- // 运营商经办人三件套=交接单上的商务档案,与「签署日期」同一条轴(2026-11-15 定稿)。
- // ⚠️ 「经办人=录入账号(created_by)」是另一列、页面只读,⛔ 参与本轴判定。
- if (draft.agent !== baseline.agent) changed.push("运营商经办人姓名");
- if (draft.agentPhone !== baseline.agentPhone) changed.push("运营商经办人电话");
- if (draft.agentOrg !== baseline.agentOrg) changed.push("运营商经办人机构");
- }
- return changed;
- }
- /** 提交载荷里与新建/编辑无关的那一段(编号、客户归属另由页面拼)。 */
- export type ContractWrite = {
- externalNo: string;
- contractType: string;
- signDate: string;
- contractAmountCents: number;
- discountRatePct: number;
- serviceMonths: number;
- startDate: string;
- endDate: string;
- agentName: string;
- agentMobile: string;
- agentHandoverOn: string;
- agentOrg: string;
- attachmentUrl: string;
- serviceItems: ContractServiceItem[];
- };
- export type ContractWriteResult =
- | { ok: true; write: ContractWrite }
- | { ok: false; error: string; fieldError?: ContractMissing };
- /**
- * 保存载荷=**只带变了的字段**(后端「键缺席=保持现值」,见 `contract/update@v1` 的 `eff()`)。
- *
- * 为什么要收窄:后端把「服务构成段出现」直接当改动判(整段替换没有可靠的"原样回传"
- * 判别),而页面保存原本是整份回传 ⇒ 已冻结的合同连改个外部单号都会被判越界(`KLT-L219`)。
- * 收窄后只有真动过的段才进载荷,页面与后端的"是否改了"口径才一致。
- */
- export function changedWriteFields(
- draft: ContractDraft,
- baseline: ContractDraft,
- ): Partial<ContractWrite> {
- const next = buildContractWrite(draft);
- if (!next.ok) return {};
- const prev = buildContractWrite(baseline);
- /** 基线本身就不合法(存量脏数据:缺档位/缺出口)⇒ 退回整份提交,让后端报真问题。 */
- if (!prev.ok) return next.write;
- const a = next.write;
- const b = prev.write;
- const out: Partial<ContractWrite> = {};
- if (a.externalNo !== b.externalNo) out.externalNo = a.externalNo;
- if (a.contractType !== b.contractType) out.contractType = a.contractType;
- if (a.signDate !== b.signDate) out.signDate = a.signDate;
- if (a.contractAmountCents !== b.contractAmountCents) out.contractAmountCents = a.contractAmountCents;
- if (a.discountRatePct !== b.discountRatePct) out.discountRatePct = a.discountRatePct;
- if (a.serviceMonths !== b.serviceMonths) out.serviceMonths = a.serviceMonths;
- if (a.startDate !== b.startDate) out.startDate = a.startDate;
- if (a.endDate !== b.endDate) out.endDate = a.endDate;
- if (a.agentName !== b.agentName) out.agentName = a.agentName;
- if (a.agentMobile !== b.agentMobile) out.agentMobile = a.agentMobile;
- if (a.agentHandoverOn !== b.agentHandoverOn) out.agentHandoverOn = a.agentHandoverOn;
- if (a.agentOrg !== b.agentOrg) out.agentOrg = a.agentOrg;
- if (a.attachmentUrl !== b.attachmentUrl) out.attachmentUrl = a.attachmentUrl;
- if (JSON.stringify(a.serviceItems) !== JSON.stringify(b.serviceItems)) out.serviceItems = a.serviceItems;
- return out;
- }
- /**
- * 草稿 → 提交载荷。按后端短路顺序返回第一条命中的必填项,把原话交给页面红显;
- * 条目的校验同源 `domain/contract-items`(镜像后端 `check_contract_items`)。
- */
- export function buildContractWrite(draft: ContractDraft): ContractWriteResult {
- if (!CONTRACT_TYPES.some((item) => item.value === draft.contractType)) {
- return { ok: false, error: `合同类型非法:${draft.contractType || "(空)"}` };
- }
- /** 类型与录入模式必须自洽:扩容补充协议=整批增量叠加服务;增量模式也只能是扩容补充协议。 */
- if (draft.contractType === "expand" && !draft.increment) {
- return { ok: false, error: "合同类型为「扩容补充协议」时,服务构成须为增量叠加服务(先在服务构成选择引用既有链路订阅)。" };
- }
- if (draft.increment && draft.contractType !== "expand") {
- return { ok: false, error: "服务构成是增量叠加服务,请把合同类型改为「扩容补充协议」。" };
- }
- const missing = checkContractRequired({
- serviceMonths: draft.serviceMonths,
- amount: draft.amount,
- start: draft.start,
- agent: draft.agent,
- agentPhone: draft.agentPhone,
- signDate: draft.signDate,
- });
- if (missing) return { ok: false, error: missing.message, fieldError: missing };
- /**
- * 必填都齐了才轮得到结束日:它**只能**由生效日+服务期(月)推算(2026-11-19 定案)⇒ 缺失时
- * 点名服务期(生效日已在上面拦过),⛔ 报「请填写生效日与结束日」让人去改一个改不了的框。
- */
- if (!draft.end) {
- return {
- ok: false,
- error: "请填写服务期(月):合同结束日由「生效日+服务期」自动推算。",
- fieldError: { key: "serviceMonths", message: "请填写服务期(月)" },
- };
- }
- if (draft.end < draft.start) return { ok: false, error: "合同结束日不得早于生效日。" };
- if (!draft.items.length) return { ok: false, error: "至少保留一个服务构成条目。" };
- const discountRatePct = parseDiscountRate(draft.discountRate);
- if (discountRatePct === null) {
- return { ok: false, error: "折扣率须为 1~100 的百分数(最多两位小数)。" };
- }
- /** 本地 key → 载荷 0 基下标:父引用只按 key 解析,⛔ 存下标(删除中间行后会漂)。 */
- const indexByKey = itemIndexByKey(draft.items);
- const serviceItems: ContractServiceItem[] = [];
- for (const [index, item] of draft.items.entries()) {
- const parentIndex = item.parentKey ? indexByKey.get(item.parentKey) : undefined;
- /**
- * 出口挂在条目行上(02 册 §2.2 第 95 行 NOT NULL+CHECK ≥1),两种形态同一条校验。
- * 2026-11-17 起单选:新建/修改条目须恰 1 个;存量多出口条目由页面置只读、不随载荷回传。
- * 2026-11-19:**叠加服务不单独选出口**,提交时依从父链路([`resolvedItemExits`])。
- */
- const inheritsExits = item.itemMode !== "increment" && item.planFamily !== "link" && parentIndex !== undefined;
- const itemExits = resolvedItemExits(draft.items, item);
- if (item.itemMode === "increment" && !itemExits.length) {
- return {
- ok: false,
- error: `条目 ${index + 1} 是增量叠加服务:线路出口依从引用的跨境链路订阅,但该订阅未登记出口,请先补登订阅的线路出口。`,
- };
- }
- if (inheritsExits && !itemExits.length) {
- return {
- ok: false,
- error: `条目 ${index + 1} 是叠加服务:线路出口依从父条目(条目 ${parentIndex + 1}),请先为父条目选择线路出口。`,
- };
- }
- const exitError = checkItemExits(itemExits);
- if (exitError) return { ok: false, error: `条目 ${index + 1} ${exitError}。` };
- /** 逐条替换的前置(后端 `plan_contract_replacements` 同口径,失败点名 `service_items[i]`)。 */
- const replaces = item.replacesSubscriptionId.trim();
- if (replaces) {
- if (item.replacementCustomized && !item.replacementConfirmed) {
- return { ok: false, error: `条目 ${index + 1}:所选为定制档,请勾选「确认为该定制档替换」后再提交。` };
- }
- if (item.quantity !== 1) {
- return { ok: false, error: `条目 ${index + 1}:一条条目只生一份订阅,替换时档位数量须为 1(当前 ${item.quantity})。` };
- }
- }
- if (!item.planId) return { ok: false, error: `条目 ${index + 1} 请选择套餐档位。` };
- if (!Number.isInteger(item.quantity) || item.quantity < 1) return { ok: false, error: `条目 ${index + 1} 的档位数量需为正整数。` };
- /** D-15:`link` 份数恒 1(`addon` 份数即个数,可 > 1)。 */
- if (item.planFamily === "link" && item.quantity !== 1) {
- return { ok: false, error: `条目 ${index + 1} 为跨境链路档:份数恒为 1(当前 ${item.quantity})。` };
- }
- /**
- * P1 树形/增量判据(镜像后端 `check_contract_items`;库层只兜得住「addon 必有父」与
- * 「increment 不挂 serves_item_id」,父必须是 link、子出口 ⊆ 父出口这两条只能在这里拦)。
- */
- if (item.itemMode === "increment") {
- if (item.planFamily && item.planFamily !== "addon") {
- return { ok: false, error: `条目 ${index + 1} 为增量条目:只能补叠加服务,⛔ 新建跨境链路(D-9)。` };
- }
- if (draft.increment && item.planFamily === "link") {
- return { ok: false, error: `条目 ${index + 1}:增量合同不新建链路,请引用既有链路订阅(D-9)。` };
- }
- if (!item.refSubscriptionId.trim()) {
- return { ok: false, error: `条目 ${index + 1} 为增量条目:须引用本客户一条在期跨境链路订阅(D-9)。` };
- }
- if (item.parentKey) {
- return { ok: false, error: `条目 ${index + 1} 为增量条目:父是既有订阅,⛔ 再挂本合同条目(D-9)。` };
- }
- if (replaces) return { ok: false, error: `条目 ${index + 1} 为增量条目:增量只叠加,⛔ 替换原订阅。` };
- } else if (item.planFamily === "link") {
- if (item.parentKey) return { ok: false, error: `条目 ${index + 1} 为跨境链路:⛔ 挂在其他条目下(D-7)。` };
- } else if (item.planFamily === "addon") {
- if (!item.parentKey || parentIndex === undefined) {
- return { ok: false, error: `条目 ${index + 1} 为叠加服务:必须挂在某条跨境链路条目下(D-7)。` };
- }
- const parent = draft.items[parentIndex];
- if (parent.planFamily && parent.planFamily !== "link") {
- return { ok: false, error: `条目 ${index + 1}:叠加服务的父条目必须是跨境链路(⛔ 叠加服务挂叠加服务,D-7)。` };
- }
- if (!parent.exits.length) {
- return { ok: false, error: `条目 ${index + 1}:父条目(条目 ${parentIndex + 1})未选线路出口,子行无法收窄。` };
- }
- const allowed = new Set(parent.exits.map(exitKey));
- const outside = itemExits.filter((exit) => !allowed.has(exitKey(exit)));
- if (outside.length) {
- return {
- ok: false,
- error: `条目 ${index + 1} 的线路出口(${outside.join("、")})不在父条目(条目 ${parentIndex + 1})的出口内(D-7)。`,
- };
- }
- }
- /** ⛔ 回传年价/月结算/形态:服务端从目录重取(形态由档位带入);父引用按主键/0 基序号二选一。 */
- const payload: ContractServiceItem = {
- item_id: item.itemId ?? undefined,
- plan_id: item.planId,
- quantity: item.quantity,
- line_exits: itemExits,
- ...(replaces ? { succession: { replaces_subscription_id: replaces } } : {}),
- };
- if (item.itemMode === "increment") {
- payload.item_mode = "increment";
- payload.ref_subscription_id = item.refSubscriptionId.trim();
- } else if (item.parentKey && parentIndex !== undefined) {
- const parent = draft.items[parentIndex];
- /** 父已落库 ⇒ 按主键;父也是本次新建 ⇒ 按**载荷** 0 基序号(后端发号后再换成主键)。 */
- if (parent.itemId) payload.serves_item_id = parent.itemId;
- else payload.serves_item_index = parentIndex;
- }
- serviceItems.push(payload);
- }
- return {
- ok: true,
- write: {
- externalNo: draft.externalNo.trim(),
- contractType: draft.contractType,
- signDate: draft.signDate,
- contractAmountCents: yuanTextToCents(draft.amount) ?? 0,
- discountRatePct,
- serviceMonths: Number(draft.serviceMonths.trim()),
- startDate: draft.start,
- endDate: draft.end,
- agentName: draft.agent.trim(),
- agentMobile: draft.agentPhone.trim(),
- /** 交接日期=签署日期(2026-11-19):接口仍收 `agent_handover_on`,值取签署日期。 */
- agentHandoverOn: draft.signDate,
- agentOrg: draft.agentOrg.trim(),
- attachmentUrl: draft.attachmentUrl.trim(),
- serviceItems,
- },
- };
- }
|