contract-draft.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /**
  2. * 合同写侧草稿口径(04 册 §4.2/§4.3/§4.4)。
  3. *
  4. * 「新增合同」与「详情内联编辑」共用这一份 Draft:详情页不再另开一条编辑路由,
  5. * 而是把同一份草稿按字段/条目拆开渲染。这里只放**纯函数**——读入口径适配、
  6. * 提交前校验与整段替换载荷的拼装,页面只负责把结果灌进受控组件。
  7. *
  8. * 纪律同 04 册 §4.2:保存形态=全量替换;套餐式⛔ 回传年价/月结算;
  9. * 出口只从「套餐配置 → 线路出口」目录选择。
  10. * 2026-11-17:合同级「固定 IP 条目」已下线(境外 IP 改由「套餐档位 × 订阅份数」表达),
  11. * 草稿不再持有 `ip_entries`/`has_fixed_ip`,读口也不再回该键。
  12. */
  13. import type { ContractEditScope, ContractGetResult, ContractServiceItem, ReplacementCandidate } from "../lib/api/types";
  14. import {
  15. centsToYuanText,
  16. checkContractRequired,
  17. checkItemExits,
  18. exitKey,
  19. yuanTextToCents,
  20. type ContractMissing,
  21. type ContractRequiredKey,
  22. } from "./contract-items";
  23. /** P1(D-9):条目形态。`new`=本条自带链路(旧口径);`increment`=引用本客户既有 link 订阅、只补叠加服务。 */
  24. export type ItemMode = "new" | "increment";
  25. let localSeq = 0;
  26. /** 本地树身份(⛔ 提交):新条目没有主键,树上的父子引用只能靠它,不能用数组下标(删除后会漂)。 */
  27. const localKey = () => `li-${(localSeq += 1)}`;
  28. /**
  29. * 服务条目编辑态:D-15 后条目只剩「档位 × 份数 × 出口」。
  30. *
  31. * `planFamily` 只做界面判据(`link` 份数恒 1、`addon` 份数可 > 1、IP 汇总只看 `addon`),
  32. * 提交时⛔ 回传——形态由后端从所引档位带入(`item_family`)。
  33. *
  34. * P1 起多了两棵树上的关系(D-7/D-9):
  35. * - `parentKey`=父条目的**本地 key**(仅 `new` 的 `addon`;顶层=`null`)。落库换 `serves_item_id`/
  36. * `serves_item_index`,⛔ 把下标写进草稿——删掉中间的条目后下标就指错了。
  37. * - `itemMode='increment'` + `refSubscriptionId`=增量合同的只读父节点(引用既有订阅,父不在本合同内)。
  38. */
  39. export type ItemDraft = {
  40. /** 本地树身份;读口行沿用条目主键,新建行现发(⛔ 提交)。 */
  41. key: string;
  42. itemId?: string | null;
  43. planId: string;
  44. planName: string;
  45. planFamily: string;
  46. quantity: number;
  47. exits: string[];
  48. /** 被替换的原订阅(空串=按新订阅开通);进 `service_items[].succession`,仅新建合同受理。 */
  49. replacesSubscriptionId: string;
  50. /** 所选候选是否为定制档(=后端候选行的 `customized`;定制档须用户显式确认)。 */
  51. replacementCustomized: boolean;
  52. /** 定制档替换的显式勾选(未勾选⛔ 提交)。 */
  53. replacementConfirmed: boolean;
  54. /** 「改为按新订阅开通」:用户显式否决替换(候选仍在时也不再勾选)。 */
  55. replacementOptOut: boolean;
  56. /** P1(D-7):父条目本地 key;顶层条目(`link`/`increment`)恒 `null`。 */
  57. parentKey: string | null;
  58. /** P1(D-9):条目形态;读侧缺省按 `new`。 */
  59. itemMode: ItemMode;
  60. /** P1(D-9):`increment` 引用的既有链路订阅号(可跨合同);`new` 恒空串。 */
  61. refSubscriptionId: string;
  62. /** 被引用订阅的展示原文(来源合同/套餐/出口);只用于只读节点标注,⛔ 提交。 */
  63. refSubscriptionLabel?: string;
  64. };
  65. export type ContractDraft = {
  66. contractNo: string;
  67. externalNo: string;
  68. /** 合同类型:`new`(新建)/`renew`(续签)/`expand`(扩容补充协议)/`change`(变更协议)。 */
  69. contractType: string;
  70. /**
  71. * 签署日期(`YYYY-MM-DD`,必填,等同原「交接日期」):同时是写入口径 `agent_handover_on`
  72. * 的来源(业主 2026-11-19 定案:交接日期即签署日期,表单只留一个日期框)。
  73. */
  74. signDate: string;
  75. amount: string;
  76. /**
  77. * 折扣率(百分数,默认 `100`):最终合同金额=套餐总金额×本值/100。
  78. * 套餐总=Σ(档位年价×份数×出口系数);折扣只改合同总额,不进订阅冻结价。
  79. */
  80. discountRate: string;
  81. /** 服务期(月,1~600):替代原「付款周期」,结束日=生效日+服务期−1 天。 */
  82. serviceMonths: string;
  83. start: string;
  84. end: string;
  85. agent: string;
  86. agentPhone: string;
  87. attachmentUrl: string;
  88. /** 经办人机构=选填(实测不送也 `10000`、读回 `null`),⛔ 当必填拦人。 */
  89. agentOrg: string;
  90. items: ItemDraft[];
  91. /**
  92. * P1(D-9):增量合同=**页面级录入模式**,⛔ 落合同级字段。
  93. * 后端从条目 `item_mode` 派生(全部 `increment` ⇒ 详情/列表打「增量」标签)。
  94. */
  95. increment: boolean;
  96. };
  97. /** 改动即撤掉该字段的必填红显(Draft 键 → 必填校验字段键)。 */
  98. export const REQUIRED_KEY_BY_DRAFT: Partial<Record<keyof ContractDraft, ContractRequiredKey>> = {
  99. serviceMonths: "serviceMonths",
  100. amount: "amount",
  101. start: "start",
  102. agent: "agent",
  103. agentPhone: "agentPhone",
  104. signDate: "signDate",
  105. };
  106. export const emptyItem = (parentKey: string | null = null, itemMode: ItemMode = "new"): ItemDraft => ({
  107. key: localKey(),
  108. planId: "",
  109. planName: "",
  110. planFamily: "",
  111. quantity: 1,
  112. exits: [],
  113. replacesSubscriptionId: "",
  114. replacementCustomized: false,
  115. replacementConfirmed: false,
  116. replacementOptOut: false,
  117. parentKey,
  118. itemMode,
  119. refSubscriptionId: "",
  120. });
  121. /**
  122. * 候选选择矩阵(2026-11-17,纯函数以便打表单测;页面只负责把结果灌回草稿):
  123. *
  124. * - 0 个候选 ⇒ 不替换(按新订阅开通)。
  125. * - 1 个或多个候选 ⇒ **不预选**(D-CT-10/09 册 TC-CU-74:替换须显式勾选;未勾选⛔ 派生替换关系)。
  126. * 沿用已选且仍在候选里的那个;用户显式「改为按新订阅开通」(`optOut`)时清空。
  127. *
  128. * 选中项已不在候选里(换了档位/出口/客户,或刚被别处替换)⇒ 归零,⛔ 保留一个不存在的订阅号提交。
  129. */
  130. export function resolveReplacementSelection(
  131. candidates: readonly ReplacementCandidate[],
  132. current: string,
  133. optOut: boolean,
  134. ): { id: string; customized: boolean } {
  135. if (optOut) return { id: "", customized: false };
  136. const picked = candidates.find((candidate) => candidate.subscription_id === current);
  137. if (picked) return { id: picked.subscription_id, customized: Boolean(picked.customized) };
  138. return { id: "", customized: false };
  139. }
  140. /** 该候选是否定制档(后端候选行 `customized`;定制档须显式勾选确认)。 */
  141. export function isCustomizedCandidate(
  142. candidates: readonly ReplacementCandidate[],
  143. id: string,
  144. ): boolean {
  145. return Boolean(candidates.find((candidate) => candidate.subscription_id === id)?.customized);
  146. }
  147. /* ── 合同类型/服务期(2026-11-19) ───────────────────────────────── */
  148. /**
  149. * 合同类型值域与中文口径(与后端 `bos-invariant::CONTRACT_TYPES` 同字)。
  150. *
  151. * 语义:`new`=新建;`renew`=续签(须选中「续签自旧合同」);`expand`=扩容补充协议
  152. * (服务构成整批为增量叠加服务,不新开链路);`change`=变更协议(可含逐条替换)。
  153. */
  154. export const CONTRACT_TYPES: ReadonlyArray<{ value: string; label: string }> = [
  155. { value: "new", label: "新建" },
  156. { value: "renew", label: "续签" },
  157. { value: "expand", label: "扩容补充协议" },
  158. { value: "change", label: "变更协议" },
  159. ];
  160. export const CONTRACT_TYPE_LABEL: Record<string, string> = Object.fromEntries(
  161. CONTRACT_TYPES.map((item) => [item.value, item.label]),
  162. );
  163. /**
  164. * 「服务期(月)」标题右侧的快捷档:月/季/年/3 年(点一下把月数填进去)。
  165. *
  166. * 「5 年」已下线(业主 2026-11-19):快捷档只做常见租期的填充,更长租期直接输月数
  167. * (输入框仍收 1~600,60 个月照样填得进去,⛔ 因此收窄值域)。
  168. */
  169. export const SERVICE_MONTH_PRESETS: ReadonlyArray<{ label: string; months: number }> = [
  170. { label: "月", months: 1 },
  171. { label: "季", months: 3 },
  172. { label: "年", months: 12 },
  173. { label: "3 年", months: 36 },
  174. ];
  175. /** 结束日只读原因(新建表单与详情内联编辑共用一句,⛔ 各写一份)。 */
  176. export const CONTRACT_END_DERIVED = "合同结束日由「生效日+服务期(月)」自动推算(生效日加服务期月数再减一天),不可手改";
  177. /**
  178. * 合同金额只读原因(与结束日同形):金额=服务构成自动汇总,⛔ 手填。
  179. * 口径=改造稿 D-15「合同金额=Σ(所引档 annual_price_cents × quantity)」。
  180. */
  181. export const CONTRACT_AMOUNT_DERIVED = "最终合同金额=套餐总×折扣率(套餐总=档位年价×份数×计费系数),不可手改;改档位/份数/出口/折扣率即重算";
  182. /** 档位取年价所需的最小形状(目录行/测试替身都够用)。 */
  183. export type PlanPriceRef = { plan_id: string; annual_price_cents: number };
  184. /** 出口系数目录行(合同页只读带出;系数只挂线路出口目录)。 */
  185. export type ExitFactorRef = {
  186. exit_name: string;
  187. exit_key?: string;
  188. price_factor?: number | null;
  189. };
  190. /** 解析计费系数:空/非法 ⇒ `null`;合法 ⇒ `(0, 1]`(最多两位小数)。 */
  191. export function parsePriceFactor(raw: string): number | null {
  192. const text = raw.trim();
  193. if (!text) return null;
  194. if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
  195. const value = Number(text);
  196. if (!Number.isFinite(value) || value <= 0 || value > 1) return null;
  197. return value;
  198. }
  199. /** `floor(cents × factor)`:计费系数最多两位小数,与后端 `apply_price_factor_cents` 同口径。 */
  200. export function applyPriceFactorCents(cents: number, factor: number): number {
  201. if (!Number.isFinite(cents) || !Number.isFinite(factor) || factor <= 0 || factor > 1) return 0;
  202. if (factor === 1) return Math.trunc(cents);
  203. const scaled = Math.round(factor * 100);
  204. return Math.floor((cents * scaled) / 100);
  205. }
  206. /** `floor(package × discountPct / 100)`:折扣率最多两位小数。 */
  207. export function applyDiscountCents(packageCents: number, discountPct: number): number {
  208. if (!Number.isFinite(packageCents) || !Number.isFinite(discountPct) || discountPct <= 0) return 0;
  209. if (discountPct === 100) return Math.trunc(packageCents);
  210. const scaled = Math.round(discountPct * 100);
  211. return Math.floor((packageCents * scaled) / 10_000);
  212. }
  213. /** 按出口原文取目录系数(缺省 1);归一化键与 `exitKey` 同源。 */
  214. export function exitPriceFactor(
  215. exits: readonly string[],
  216. catalog: readonly ExitFactorRef[],
  217. ): number {
  218. const name = exits[0];
  219. if (!name) return 1;
  220. const key = exitKey(name);
  221. const hit = catalog.find((row) => (row.exit_key ? row.exit_key === key : exitKey(row.exit_name) === key));
  222. const factor = hit?.price_factor;
  223. return factor && factor > 0 && factor <= 1 ? factor : 1;
  224. }
  225. /**
  226. * 合同金额=套餐总×折扣率(套餐总=Σ(年价×份数×出口系数))。
  227. *
  228. * - 尚无已选档位 ⇒ `empty`(金额清空,等条目配齐);
  229. * - 已选档位但目录里还找不到(目录未载完/档已下架)⇒ `incomplete`(保留现值,⛔ 用 0 覆盖);
  230. * - 全部命中 ⇒ `ok`:`packageCents`=折前套餐总,`finalCents`/`text`=折后最终合同金额。
  231. */
  232. export function deriveContractAmount(
  233. items: readonly Pick<ItemDraft, "planId" | "quantity" | "exits">[],
  234. plans: readonly PlanPriceRef[],
  235. exitCatalog: readonly ExitFactorRef[] = [],
  236. discountRatePct = 100,
  237. ): { ok: true; packageCents: number; finalCents: number; cents: number; text: string } | { ok: false; reason: "empty" | "incomplete" } {
  238. const priced = items.filter((item) => item.planId);
  239. if (!priced.length) return { ok: false, reason: "empty" };
  240. const byId = new Map(plans.map((plan) => [plan.plan_id, plan]));
  241. let packageCents = 0;
  242. for (const item of priced) {
  243. const plan = byId.get(item.planId);
  244. if (!plan) return { ok: false, reason: "incomplete" };
  245. const quantity = Number.isInteger(item.quantity) && item.quantity > 0 ? item.quantity : 1;
  246. const unit = applyPriceFactorCents(plan.annual_price_cents, exitPriceFactor(item.exits, exitCatalog));
  247. packageCents += unit * quantity;
  248. }
  249. const finalCents = applyDiscountCents(packageCents, discountRatePct > 0 ? discountRatePct : 100);
  250. return {
  251. ok: true,
  252. packageCents,
  253. finalCents,
  254. cents: finalCents,
  255. text: centsToYuanText(finalCents),
  256. };
  257. }
  258. /** 解析折扣率输入:空/非法 ⇒ `null`;合法 ⇒ `[1, 100]`(最多两位小数)。 */
  259. export function parseDiscountRate(raw: string): number | null {
  260. const text = raw.trim();
  261. if (!text) return null;
  262. if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
  263. const value = Number(text);
  264. if (!Number.isFinite(value) || value < 1 || value > 100) return null;
  265. return value;
  266. }
  267. /**
  268. * 业务当天(`Asia/Shanghai`,`YYYY-MM-DD`)。
  269. *
  270. * ⛔ 用 `toISOString().slice(0,10)`:那是 UTC,晚 8 点后日期会跳到次日,运维晚上录合同
  271. * 就会拿到明天的日期并把它当成「录入当日」的签署日期。
  272. */
  273. export function businessToday(now: Date = new Date()): string {
  274. const parts = new Intl.DateTimeFormat("en-CA", {
  275. timeZone: "Asia/Shanghai",
  276. year: "numeric",
  277. month: "2-digit",
  278. day: "2-digit",
  279. }).formatToParts(now);
  280. const pick = (type: string) => parts.find((part) => part.type === type)?.value ?? "";
  281. return `${pick("year")}-${pick("month")}-${pick("day")}`;
  282. }
  283. /** 该年该月的天数(1 基月份;按 UTC 算,⛔ 受本机时区影响)。 */
  284. const daysInMonth = (year: number, month: number) => new Date(Date.UTC(year, month, 0)).getUTCDate();
  285. /**
  286. * 合同结束日=**生效日 + 服务期(月) − 1 天**(2026-11-19 起合同只录服务期月数)。
  287. *
  288. * 与后端 `subscription::add_months_clamped` 同一式:加月后该月无对应日**先取月末**,再减一天
  289. * (1-31 起、1 个月 ⇒ 2-28 → 2-27)。服务期缺失/非法 ⇒ 返回空串,让页面显式提示
  290. * 「先填生效日与服务期」,⛔ 留一个陈旧的结束日。
  291. */
  292. export function contractEndFromMonths(start: string, monthsRaw: string | number): string {
  293. const months = typeof monthsRaw === "number" ? monthsRaw : Number(String(monthsRaw).trim());
  294. if (!Number.isInteger(months) || months < 1 || months > 600) return "";
  295. if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) return "";
  296. const [year, month, day] = start.split("-").map(Number);
  297. if (!year || !month || !day) return "";
  298. const total = year * 12 + (month - 1) + months;
  299. const nextYear = Math.floor(total / 12);
  300. const nextMonth = (total % 12) + 1;
  301. const clampedDay = Math.min(day, daysInMonth(nextYear, nextMonth));
  302. const end = new Date(Date.UTC(nextYear, nextMonth - 1, clampedDay));
  303. end.setUTCDate(end.getUTCDate() - 1);
  304. return end.toISOString().slice(0, 10);
  305. }
  306. /** 由起止日反推服务期(月,两端月份计入):仅用于存量行没有 `service_months` 时的展示兜底。 */
  307. export function serviceMonthsFromPeriod(start: string | null | undefined, end: string | null | undefined): number | null {
  308. if (!start || !end || !/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) return null;
  309. const [sy, sm] = start.split("-").map(Number);
  310. const [ey, em] = end.split("-").map(Number);
  311. if (!sy || !sm || !ey || !em) return null;
  312. const months = (ey - sy) * 12 + (em - sm) + 1;
  313. return months > 0 ? months : null;
  314. }
  315. /**
  316. * 「生效日 → 结束日」能撑满的服务期月数:**最小的 m** 使「生效日+m 月−1 天 ≥ 结束日」。
  317. *
  318. * 扩容补充协议用(2026-11-19 业主定案):到期日锁在原合同止期、生效日可配,
  319. * 服务期跟着生效日重算。⛔ 用 [`serviceMonthsFromPeriod`] 的「月份数+1」口径:
  320. * 那是按整月数月份差算的,遇到止期日号小于生效日号时会多算一个月。
  321. */
  322. export function serviceMonthsBetween(start: string, end: string): number | null {
  323. if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end) || end < start) return null;
  324. let months = Math.max(1, serviceMonthsFromPeriod(start, end) ?? 1);
  325. /** 先往回收(同一结束日可能有多个 m 满足),再往上推,保证取最小可行值。 */
  326. while (months > 1 && contractEndFromMonths(start, months - 1) && contractEndFromMonths(start, months - 1) >= end) months -= 1;
  327. while (months < 600 && (!contractEndFromMonths(start, months) || contractEndFromMonths(start, months) < end)) months += 1;
  328. return months;
  329. }
  330. export const emptyDraft = (): ContractDraft => ({
  331. contractNo: "",
  332. externalNo: "",
  333. contractType: "new",
  334. signDate: "",
  335. amount: "",
  336. discountRate: "100",
  337. serviceMonths: "12",
  338. start: "",
  339. end: "",
  340. agent: "",
  341. agentPhone: "",
  342. attachmentUrl: "",
  343. agentOrg: "",
  344. items: [emptyItem()],
  345. increment: false,
  346. });
  347. /** 金额「分 → 元」:缺失/null 一律留空由必填校验拦下,⛔ 填 0 冒充已配置;算术走整数分口径。 */
  348. export const centsToInput = (cents: number | null | undefined) => (cents === null || cents === undefined ? "" : centsToYuanText(cents));
  349. const itemFromRow = (item: ContractServiceItem): ItemDraft => {
  350. return {
  351. key: item.item_id || localKey(),
  352. itemId: item.item_id ?? null,
  353. planId: item.plan_id ?? "",
  354. planName: item.plan_name ?? "",
  355. planFamily: item.item_family ?? "",
  356. quantity: item.quantity ?? 1,
  357. exits: item.line_exits ?? [],
  358. /** 读口回带的条目已落库,编辑合同⛔ 受理替换 ⇒ 草稿一律以「不替换」为基线。 */
  359. replacesSubscriptionId: "",
  360. replacementCustomized: false,
  361. replacementConfirmed: false,
  362. replacementOptOut: false,
  363. /** 读口回来的是主键(`serves_item_id`),下面由 `draftFromRow` 统一折算成本地 key。 */
  364. parentKey: null,
  365. itemMode: item.item_mode === "increment" ? "increment" : "new",
  366. refSubscriptionId: item.ref_subscription_id ?? "",
  367. };
  368. };
  369. export const draftFromRow = (row: ContractGetResult | null | undefined): ContractDraft => {
  370. const rows = row?.service_items ?? [];
  371. const items = rows.map(itemFromRow);
  372. /** 主键 → 本地 key:父引用在草稿里必须换成本地身份,才能在新条目插入/删除后仍指对行。 */
  373. const keyById = new Map<string, string>();
  374. rows.forEach((item, index) => {
  375. if (item.item_id) keyById.set(item.item_id, items[index].key);
  376. });
  377. rows.forEach((item, index) => {
  378. if (item.serves_item_id) items[index].parentKey = keyById.get(item.serves_item_id) ?? null;
  379. });
  380. return {
  381. contractNo: row?.contract_no ?? "",
  382. externalNo: row?.external_no ?? "",
  383. contractType: row?.contract_type ?? "new",
  384. signDate: row?.sign_date ?? row?.agent_handover_on ?? "",
  385. amount: centsToInput(row?.contract_amount_cents ?? row?.amount_cents),
  386. discountRate: row?.discount_rate_pct === null || row?.discount_rate_pct === undefined
  387. ? "100"
  388. : String(row.discount_rate_pct),
  389. serviceMonths: row?.service_months === null || row?.service_months === undefined
  390. ? String(serviceMonthsFromPeriod(row?.start_date, row?.end_date) ?? "")
  391. : String(row.service_months),
  392. start: row?.start_date ?? "",
  393. end: row?.end_date ?? "",
  394. agent: row?.agent_name ?? "",
  395. agentPhone: row?.agent_mobile ?? "",
  396. agentOrg: row?.agent_org ?? "",
  397. attachmentUrl: row?.attachment_url ?? "",
  398. items,
  399. /** 全条目皆增量 ⇒ 本合同是增量合同(后端不存合同级列,这里同样只做派生)。 */
  400. increment: items.length > 0 && items.every((item) => item.itemMode === "increment"),
  401. };
  402. };
  403. /* ── P1 树形(D-7):录入/详情共用同一份分组口径 ─────────────────────── */
  404. export type ItemTreeNode = {
  405. item: ItemDraft;
  406. /** 该条目在 `items` 里的 0 基下标(提交载荷按它排序)。 */
  407. index: number;
  408. children: { item: ItemDraft; index: number }[];
  409. };
  410. /** 父条目本地 key → 下标(父引用一律按 key 查,⛔ 按数组下标)。 */
  411. export function itemIndexByKey(items: readonly ItemDraft[]): Map<string, number> {
  412. return new Map(items.map((item, index) => [item.key, index]));
  413. }
  414. /**
  415. * 平铺草稿 → 两级树(D-7:只有两级,`addon` 不能再挂 `addon`)。
  416. *
  417. * 根=没有父引用(`link`/`increment`)或父引用已失效的行(存量脏数据也要看得见,
  418. * ⛔ 让它从界面上凭空消失);子行挂在父后面,保持原数组顺序。
  419. */
  420. export function itemTree(items: readonly ItemDraft[]): ItemTreeNode[] {
  421. const byKey = new Map(items.map((item) => [item.key, item]));
  422. const roots: ItemTreeNode[] = [];
  423. const nodeOf = new Map<string, ItemTreeNode>();
  424. items.forEach((item, index) => {
  425. const parentAlive = item.parentKey ? byKey.has(item.parentKey) : false;
  426. if (!item.parentKey || !parentAlive) {
  427. const node: ItemTreeNode = { item, index, children: [] };
  428. roots.push(node);
  429. nodeOf.set(item.key, node);
  430. }
  431. });
  432. items.forEach((item, index) => {
  433. if (!item.parentKey) return;
  434. const parent = nodeOf.get(item.parentKey);
  435. if (parent) parent.children.push({ item, index });
  436. /** 父引用指向的不是根(三级/父已被挂走)⇒ 作为根出现,宁可显示怪也不吞掉这一行。 */
  437. else if (!roots.some((node) => node.item.key === item.key)) roots.push({ item, index, children: [] });
  438. });
  439. return roots;
  440. }
  441. /** 删父要连带删哪些行(含父本身);提示里用它报数量,⛔ 静默级联。 */
  442. export function itemSubtreeKeys(items: readonly ItemDraft[], key: string): string[] {
  443. const children = items.filter((item) => item.parentKey === key).map((item) => item.key);
  444. return [key, ...children];
  445. }
  446. /**
  447. * 条目**实际提交**的线路出口(2026-11-19 业主定案):
  448. *
  449. * - **叠加服务不单独选线路出口**:子行恒依从其跨境链路父条目的出口;
  450. * - 增量叠加服务(`itemMode='increment'`)依从被引用的既有链路订阅——该出口在建条目时由
  451. * 页面从订阅行带入 `exits`,这里保持原值(父不在本合同内,草稿里找不到它);
  452. * - 跨境链路条目仍取自身所选。
  453. *
  454. * 后端对每条 `line_exits` 要求恰 1 个、且子行 ⊆ 父行 ⇒ 统一由本函数收口,⛔ 让子行按
  455. * 自己残留的旧出口提交(否则会报「不在父条目出口内」)。
  456. */
  457. export function resolvedItemExits(items: readonly ItemDraft[], item: ItemDraft): string[] {
  458. if (item.itemMode === "increment" || item.planFamily === "link") return item.exits;
  459. if (!item.parentKey) return item.exits;
  460. const parent = items.find((row) => row.key === item.parentKey);
  461. return parent ? parent.exits : item.exits;
  462. }
  463. /**
  464. * 续签的新合同生效日(2026-11-17 四轮):旧合同**结束日次日**;若该日已早于业务当天
  465. * (合同已过期一段时间才续签),取**业务当天**——续签不能倒签一段已经开始履行的期间。
  466. *
  467. * ⛔ 直接沿用旧合同的生效日:那是上一份合同的起点,本合同的开始日必须接在旧期间之后,
  468. * 否则新旧订阅期间相交 ⇒ 后端按「替换」处理(截原+第七类工单),与续签语义相反。
  469. */
  470. export function renewalStartOf(oldEnd: string | null | undefined, today: string = businessToday()): string {
  471. const end = (oldEnd ?? "").trim();
  472. if (!/^\d{4}-\d{2}-\d{2}$/.test(end)) return today;
  473. const [year, month, day] = end.split("-").map(Number);
  474. const next = new Date(Date.UTC(year, month - 1, day + 1)).toISOString().slice(0, 10);
  475. return next > today ? next : today;
  476. }
  477. /**
  478. * 扩容补充协议的生效日兜底(2026-11-19):默认业务当天;旧合同尚未开始 ⇒ 取旧合同生效日;
  479. * 当天已过旧止期 ⇒ 取旧止期(保证「生效日 ≤ 到期日」,服务期至少 1 个月)。
  480. */
  481. function expandStartOf(oldStart: string, oldEnd: string, today: string): string {
  482. const candidate = oldStart && today < oldStart ? oldStart : today;
  483. return oldEnd && candidate > oldEnd ? oldEnd : candidate;
  484. }
  485. /**
  486. * 承接旧合同的预填(2026-11-19 口径,三种非「新建」类型共用一份口径):
  487. *
  488. * - `renew`(续签):带出服务期/服务条目/经办人三件套,生效日=旧结束日次日
  489. * (不早于业务当天,见 [`renewalStartOf`]),结束日按生效日+服务期推算;提交带
  490. * `renew_from_contract_id`。合同金额由页面按服务构成自动汇总,⛔ 带入旧总额。
  491. * - `expand`(扩容补充协议):**不带金额**(补充协议金额是增量口径)、**不带服务构成**
  492. * (增量模式按既有链路订阅逐条添加,照抄旧条目会变成「自建链路」);到期日锁在旧合同止期,
  493. * 生效日可配(默认业务当天,⛔ 晚于旧止期),服务期=生效日撑到旧止期的月数。
  494. * - `change`(变更协议):带出服务期/服务条目作底稿(金额随条目自动汇总);期间沿用旧合同
  495. * (生效日/到期日都取旧合同真值,可改,⛔ 按续签口径推到旧止期次日)。
  496. *
  497. * ⛔ 三种类型都带:合同编号/外部单号(新合同要发新号)、附件(旧合同的影像不是本合同的凭证)、
  498. * 签署日期(默认录入当日;旧合同那一张是上一份合同的凭证)。
  499. * `item_id` 必须清空——新建态条目主键由服务端发号,原样回传会被写口按「改条目」点名拒绝。
  500. */
  501. export type RenewalPrefill = Partial<
  502. Pick<ContractDraft, "contractType" | "amount" | "serviceMonths" | "start" | "end" | "agent" | "agentPhone" | "agentOrg" | "items">
  503. >;
  504. export function renewalPrefill(
  505. row: ContractGetResult | null | undefined,
  506. today: string = businessToday(),
  507. contractType: "renew" | "expand" | "change" = "renew",
  508. ): RenewalPrefill | null {
  509. if (!row) return null;
  510. const base = draftFromRow(row);
  511. /** 经办人三件套三种类型都带(交接单上的运营商侧联系人不会因为协议种类而变)。 */
  512. const agent = { agent: base.agent, agentPhone: base.agentPhone, agentOrg: base.agentOrg };
  513. if (contractType === "expand") {
  514. /**
  515. * 扩容补充协议:到期日锁在旧合同止期,生效日默认业务当天(旧止期已过 ⇒ 取旧止期当天,
  516. * 让服务期至少 1 个月),服务期=生效日撑到旧止期。
  517. */
  518. const end = base.end;
  519. /** 原合同没有固定止期(长期)⇒ 一格都不带:仍按「生效日+服务期」推算到期日,⛔ 锁死空格子。 */
  520. if (!/^\d{4}-\d{2}-\d{2}$/.test(end)) return { contractType: "expand", ...agent };
  521. const start = expandStartOf(base.start, end, today);
  522. const months = serviceMonthsBetween(start, end);
  523. return {
  524. contractType: "expand",
  525. ...(months === null ? {} : { serviceMonths: String(months) }),
  526. start,
  527. end,
  528. ...agent,
  529. };
  530. }
  531. if (contractType === "change") {
  532. /** 变更协议:期间沿用旧合同真值(到期日可改),服务构成作底稿;金额由页面按条目汇总。 */
  533. return {
  534. contractType: "change",
  535. serviceMonths: base.serviceMonths,
  536. start: base.start,
  537. end: base.end,
  538. ...agent,
  539. items: (base.items.length ? base.items : [emptyItem()]).map((item) => ({ ...item, itemId: null })),
  540. };
  541. }
  542. return {
  543. contractType: "renew",
  544. serviceMonths: base.serviceMonths,
  545. start: renewalStartOf(base.end, today),
  546. ...agent,
  547. items: (base.items.length ? base.items : [emptyItem()]).map((item) => ({ ...item, itemId: null })),
  548. };
  549. }
  550. /**
  551. * 冻结守卫:草稿相对基线改了哪些**当前不可改**的字段,返回中文名供页面阻断保存。
  552. *
  553. * 判据来源=后端下发的 `edit_scope`(两轴各自独立判定,04 册 §4.2,2026-11-15 定稿),
  554. * ⛔ 页面自己按 `opened` 推——「已生效未开通」只冻计费轴、档案轴仍可改,一刀切会把
  555. * 合法的外部单号修改挡掉。
  556. *
  557. * 字段口径与页面锁定范围必须同源,否则会出现「锁了能存」或「没锁却拦」。
  558. */
  559. export function frozenChanges(
  560. draft: ContractDraft,
  561. baseline: ContractDraft,
  562. scope: Pick<ContractEditScope, "billing" | "archive"> | null | undefined,
  563. ): string[] {
  564. if (!scope) return [];
  565. const changed: string[] = [];
  566. if (!scope.billing.editable) {
  567. if (draft.amount !== baseline.amount) changed.push("合同金额");
  568. if (draft.discountRate !== baseline.discountRate) changed.push("折扣率");
  569. if (draft.serviceMonths !== baseline.serviceMonths) changed.push("服务期(月)");
  570. if (draft.start !== baseline.start) changed.push("合同生效日");
  571. if (draft.end !== baseline.end) changed.push("合同结束日");
  572. if (JSON.stringify(draft.items) !== JSON.stringify(baseline.items)) changed.push("服务构成");
  573. }
  574. if (!scope.archive.editable) {
  575. if (draft.contractType !== baseline.contractType) changed.push("合同类型");
  576. if (draft.signDate !== baseline.signDate) changed.push("签署日期");
  577. if (draft.externalNo !== baseline.externalNo) changed.push("外部单号");
  578. // 运营商经办人三件套=交接单上的商务档案,与「签署日期」同一条轴(2026-11-15 定稿)。
  579. // ⚠️ 「经办人=录入账号(created_by)」是另一列、页面只读,⛔ 参与本轴判定。
  580. if (draft.agent !== baseline.agent) changed.push("运营商经办人姓名");
  581. if (draft.agentPhone !== baseline.agentPhone) changed.push("运营商经办人电话");
  582. if (draft.agentOrg !== baseline.agentOrg) changed.push("运营商经办人机构");
  583. }
  584. return changed;
  585. }
  586. /** 提交载荷里与新建/编辑无关的那一段(编号、客户归属另由页面拼)。 */
  587. export type ContractWrite = {
  588. externalNo: string;
  589. contractType: string;
  590. signDate: string;
  591. contractAmountCents: number;
  592. discountRatePct: number;
  593. serviceMonths: number;
  594. startDate: string;
  595. endDate: string;
  596. agentName: string;
  597. agentMobile: string;
  598. agentHandoverOn: string;
  599. agentOrg: string;
  600. attachmentUrl: string;
  601. serviceItems: ContractServiceItem[];
  602. };
  603. export type ContractWriteResult =
  604. | { ok: true; write: ContractWrite }
  605. | { ok: false; error: string; fieldError?: ContractMissing };
  606. /**
  607. * 保存载荷=**只带变了的字段**(后端「键缺席=保持现值」,见 `contract/update@v1` 的 `eff()`)。
  608. *
  609. * 为什么要收窄:后端把「服务构成段出现」直接当改动判(整段替换没有可靠的"原样回传"
  610. * 判别),而页面保存原本是整份回传 ⇒ 已冻结的合同连改个外部单号都会被判越界(`KLT-L219`)。
  611. * 收窄后只有真动过的段才进载荷,页面与后端的"是否改了"口径才一致。
  612. */
  613. export function changedWriteFields(
  614. draft: ContractDraft,
  615. baseline: ContractDraft,
  616. ): Partial<ContractWrite> {
  617. const next = buildContractWrite(draft);
  618. if (!next.ok) return {};
  619. const prev = buildContractWrite(baseline);
  620. /** 基线本身就不合法(存量脏数据:缺档位/缺出口)⇒ 退回整份提交,让后端报真问题。 */
  621. if (!prev.ok) return next.write;
  622. const a = next.write;
  623. const b = prev.write;
  624. const out: Partial<ContractWrite> = {};
  625. if (a.externalNo !== b.externalNo) out.externalNo = a.externalNo;
  626. if (a.contractType !== b.contractType) out.contractType = a.contractType;
  627. if (a.signDate !== b.signDate) out.signDate = a.signDate;
  628. if (a.contractAmountCents !== b.contractAmountCents) out.contractAmountCents = a.contractAmountCents;
  629. if (a.discountRatePct !== b.discountRatePct) out.discountRatePct = a.discountRatePct;
  630. if (a.serviceMonths !== b.serviceMonths) out.serviceMonths = a.serviceMonths;
  631. if (a.startDate !== b.startDate) out.startDate = a.startDate;
  632. if (a.endDate !== b.endDate) out.endDate = a.endDate;
  633. if (a.agentName !== b.agentName) out.agentName = a.agentName;
  634. if (a.agentMobile !== b.agentMobile) out.agentMobile = a.agentMobile;
  635. if (a.agentHandoverOn !== b.agentHandoverOn) out.agentHandoverOn = a.agentHandoverOn;
  636. if (a.agentOrg !== b.agentOrg) out.agentOrg = a.agentOrg;
  637. if (a.attachmentUrl !== b.attachmentUrl) out.attachmentUrl = a.attachmentUrl;
  638. if (JSON.stringify(a.serviceItems) !== JSON.stringify(b.serviceItems)) out.serviceItems = a.serviceItems;
  639. return out;
  640. }
  641. /**
  642. * 草稿 → 提交载荷。按后端短路顺序返回第一条命中的必填项,把原话交给页面红显;
  643. * 条目的校验同源 `domain/contract-items`(镜像后端 `check_contract_items`)。
  644. */
  645. export function buildContractWrite(draft: ContractDraft): ContractWriteResult {
  646. if (!CONTRACT_TYPES.some((item) => item.value === draft.contractType)) {
  647. return { ok: false, error: `合同类型非法:${draft.contractType || "(空)"}` };
  648. }
  649. /** 类型与录入模式必须自洽:扩容补充协议=整批增量叠加服务;增量模式也只能是扩容补充协议。 */
  650. if (draft.contractType === "expand" && !draft.increment) {
  651. return { ok: false, error: "合同类型为「扩容补充协议」时,服务构成须为增量叠加服务(先在服务构成选择引用既有链路订阅)。" };
  652. }
  653. if (draft.increment && draft.contractType !== "expand") {
  654. return { ok: false, error: "服务构成是增量叠加服务,请把合同类型改为「扩容补充协议」。" };
  655. }
  656. const missing = checkContractRequired({
  657. serviceMonths: draft.serviceMonths,
  658. amount: draft.amount,
  659. start: draft.start,
  660. agent: draft.agent,
  661. agentPhone: draft.agentPhone,
  662. signDate: draft.signDate,
  663. });
  664. if (missing) return { ok: false, error: missing.message, fieldError: missing };
  665. /**
  666. * 必填都齐了才轮得到结束日:它**只能**由生效日+服务期(月)推算(2026-11-19 定案)⇒ 缺失时
  667. * 点名服务期(生效日已在上面拦过),⛔ 报「请填写生效日与结束日」让人去改一个改不了的框。
  668. */
  669. if (!draft.end) {
  670. return {
  671. ok: false,
  672. error: "请填写服务期(月):合同结束日由「生效日+服务期」自动推算。",
  673. fieldError: { key: "serviceMonths", message: "请填写服务期(月)" },
  674. };
  675. }
  676. if (draft.end < draft.start) return { ok: false, error: "合同结束日不得早于生效日。" };
  677. if (!draft.items.length) return { ok: false, error: "至少保留一个服务构成条目。" };
  678. const discountRatePct = parseDiscountRate(draft.discountRate);
  679. if (discountRatePct === null) {
  680. return { ok: false, error: "折扣率须为 1~100 的百分数(最多两位小数)。" };
  681. }
  682. /** 本地 key → 载荷 0 基下标:父引用只按 key 解析,⛔ 存下标(删除中间行后会漂)。 */
  683. const indexByKey = itemIndexByKey(draft.items);
  684. const serviceItems: ContractServiceItem[] = [];
  685. for (const [index, item] of draft.items.entries()) {
  686. const parentIndex = item.parentKey ? indexByKey.get(item.parentKey) : undefined;
  687. /**
  688. * 出口挂在条目行上(02 册 §2.2 第 95 行 NOT NULL+CHECK ≥1),两种形态同一条校验。
  689. * 2026-11-17 起单选:新建/修改条目须恰 1 个;存量多出口条目由页面置只读、不随载荷回传。
  690. * 2026-11-19:**叠加服务不单独选出口**,提交时依从父链路([`resolvedItemExits`])。
  691. */
  692. const inheritsExits = item.itemMode !== "increment" && item.planFamily !== "link" && parentIndex !== undefined;
  693. const itemExits = resolvedItemExits(draft.items, item);
  694. if (item.itemMode === "increment" && !itemExits.length) {
  695. return {
  696. ok: false,
  697. error: `条目 ${index + 1} 是增量叠加服务:线路出口依从引用的跨境链路订阅,但该订阅未登记出口,请先补登订阅的线路出口。`,
  698. };
  699. }
  700. if (inheritsExits && !itemExits.length) {
  701. return {
  702. ok: false,
  703. error: `条目 ${index + 1} 是叠加服务:线路出口依从父条目(条目 ${parentIndex + 1}),请先为父条目选择线路出口。`,
  704. };
  705. }
  706. const exitError = checkItemExits(itemExits);
  707. if (exitError) return { ok: false, error: `条目 ${index + 1} ${exitError}。` };
  708. /** 逐条替换的前置(后端 `plan_contract_replacements` 同口径,失败点名 `service_items[i]`)。 */
  709. const replaces = item.replacesSubscriptionId.trim();
  710. if (replaces) {
  711. if (item.replacementCustomized && !item.replacementConfirmed) {
  712. return { ok: false, error: `条目 ${index + 1}:所选为定制档,请勾选「确认为该定制档替换」后再提交。` };
  713. }
  714. if (item.quantity !== 1) {
  715. return { ok: false, error: `条目 ${index + 1}:一条条目只生一份订阅,替换时档位数量须为 1(当前 ${item.quantity})。` };
  716. }
  717. }
  718. if (!item.planId) return { ok: false, error: `条目 ${index + 1} 请选择套餐档位。` };
  719. if (!Number.isInteger(item.quantity) || item.quantity < 1) return { ok: false, error: `条目 ${index + 1} 的档位数量需为正整数。` };
  720. /** D-15:`link` 份数恒 1(`addon` 份数即个数,可 > 1)。 */
  721. if (item.planFamily === "link" && item.quantity !== 1) {
  722. return { ok: false, error: `条目 ${index + 1} 为跨境链路档:份数恒为 1(当前 ${item.quantity})。` };
  723. }
  724. /**
  725. * P1 树形/增量判据(镜像后端 `check_contract_items`;库层只兜得住「addon 必有父」与
  726. * 「increment 不挂 serves_item_id」,父必须是 link、子出口 ⊆ 父出口这两条只能在这里拦)。
  727. */
  728. if (item.itemMode === "increment") {
  729. if (item.planFamily && item.planFamily !== "addon") {
  730. return { ok: false, error: `条目 ${index + 1} 为增量条目:只能补叠加服务,⛔ 新建跨境链路(D-9)。` };
  731. }
  732. if (draft.increment && item.planFamily === "link") {
  733. return { ok: false, error: `条目 ${index + 1}:增量合同不新建链路,请引用既有链路订阅(D-9)。` };
  734. }
  735. if (!item.refSubscriptionId.trim()) {
  736. return { ok: false, error: `条目 ${index + 1} 为增量条目:须引用本客户一条在期跨境链路订阅(D-9)。` };
  737. }
  738. if (item.parentKey) {
  739. return { ok: false, error: `条目 ${index + 1} 为增量条目:父是既有订阅,⛔ 再挂本合同条目(D-9)。` };
  740. }
  741. if (replaces) return { ok: false, error: `条目 ${index + 1} 为增量条目:增量只叠加,⛔ 替换原订阅。` };
  742. } else if (item.planFamily === "link") {
  743. if (item.parentKey) return { ok: false, error: `条目 ${index + 1} 为跨境链路:⛔ 挂在其他条目下(D-7)。` };
  744. } else if (item.planFamily === "addon") {
  745. if (!item.parentKey || parentIndex === undefined) {
  746. return { ok: false, error: `条目 ${index + 1} 为叠加服务:必须挂在某条跨境链路条目下(D-7)。` };
  747. }
  748. const parent = draft.items[parentIndex];
  749. if (parent.planFamily && parent.planFamily !== "link") {
  750. return { ok: false, error: `条目 ${index + 1}:叠加服务的父条目必须是跨境链路(⛔ 叠加服务挂叠加服务,D-7)。` };
  751. }
  752. if (!parent.exits.length) {
  753. return { ok: false, error: `条目 ${index + 1}:父条目(条目 ${parentIndex + 1})未选线路出口,子行无法收窄。` };
  754. }
  755. const allowed = new Set(parent.exits.map(exitKey));
  756. const outside = itemExits.filter((exit) => !allowed.has(exitKey(exit)));
  757. if (outside.length) {
  758. return {
  759. ok: false,
  760. error: `条目 ${index + 1} 的线路出口(${outside.join("、")})不在父条目(条目 ${parentIndex + 1})的出口内(D-7)。`,
  761. };
  762. }
  763. }
  764. /** ⛔ 回传年价/月结算/形态:服务端从目录重取(形态由档位带入);父引用按主键/0 基序号二选一。 */
  765. const payload: ContractServiceItem = {
  766. item_id: item.itemId ?? undefined,
  767. plan_id: item.planId,
  768. quantity: item.quantity,
  769. line_exits: itemExits,
  770. ...(replaces ? { succession: { replaces_subscription_id: replaces } } : {}),
  771. };
  772. if (item.itemMode === "increment") {
  773. payload.item_mode = "increment";
  774. payload.ref_subscription_id = item.refSubscriptionId.trim();
  775. } else if (item.parentKey && parentIndex !== undefined) {
  776. const parent = draft.items[parentIndex];
  777. /** 父已落库 ⇒ 按主键;父也是本次新建 ⇒ 按**载荷** 0 基序号(后端发号后再换成主键)。 */
  778. if (parent.itemId) payload.serves_item_id = parent.itemId;
  779. else payload.serves_item_index = parentIndex;
  780. }
  781. serviceItems.push(payload);
  782. }
  783. return {
  784. ok: true,
  785. write: {
  786. externalNo: draft.externalNo.trim(),
  787. contractType: draft.contractType,
  788. signDate: draft.signDate,
  789. contractAmountCents: yuanTextToCents(draft.amount) ?? 0,
  790. discountRatePct,
  791. serviceMonths: Number(draft.serviceMonths.trim()),
  792. startDate: draft.start,
  793. endDate: draft.end,
  794. agentName: draft.agent.trim(),
  795. agentMobile: draft.agentPhone.trim(),
  796. /** 交接日期=签署日期(2026-11-19):接口仍收 `agent_handover_on`,值取签署日期。 */
  797. agentHandoverOn: draft.signDate,
  798. agentOrg: draft.agentOrg.trim(),
  799. attachmentUrl: draft.attachmentUrl.trim(),
  800. serviceItems,
  801. },
  802. };
  803. }