Explorar o código

fix(contract): 固定 IP 条目出口只能取服务构成已选出口

新增/编辑合同时,IP 条目的线路出口此前只在「套餐配置 → 线路出口」目录内校验,
可从全量目录任取;本次收紧为必须是本合同服务构成条目已选出口的子集。

- 后端 contract.rs:`check_ip_exits_in_items` 拆出通用版 `check_exits_within_items`,
  按归一化键(去空白+小写)比对生效条目的 `line_exits`;create/update 载荷带
  `ip_entries` 时校验本次生效条目,只改条目未重发 IP 时回代库内 IP 条目,
  防止「删掉条目出口、IP 条目照旧」留悬空值。目录校验 `check_configured` 照旧并列。
- 前端两个合同页:IP 条目出口下拉改取上方条目已选出口并集;条目未选出口时显式提示,
  历史值不在集合内仍列出但标注「(不在服务构成已选出口中)」,保存时由校验拦下。
- 域层 `checkIpExitWithinItems` 在 `buildContractWrite` 接线,新建与详情内联编辑共用。
- 单测:后端 2 例(子集命中/空集合不放行、JSONB 文本回传兼容)、前端 1 例。

Co-authored-by: Cursor <cursoragent@cursor.com>
cg hai 1 semana
pai
achega
6296d8ea72

+ 40 - 5
src/modules/account/src/handlers/contract.rs

@@ -1541,21 +1541,36 @@ fn check_ip_exits_in_items<'a>(
     ips: &[IpIns],
     item_exits: impl IntoIterator<Item = Option<&'a Value>>,
 ) -> Result<(), BosError> {
-    if ips.is_empty() {
+    let uses: Vec<(String, String)> = ips
+        .iter()
+        .enumerate()
+        .map(|(index, e)| (format!("ip_entries[{index}].line_exit"), e.line_exit.clone()))
+        .collect();
+    check_exits_within_items(&uses, item_exits)
+}
+
+/// 通用版:`uses`=(字段路径, 出口原文),`item_exits`=生效条目的 `line_exits`。
+///
+/// 拆出通用版是给「改服务构成但未重发 IP」的路径复用:那时要拿**库内 IP 条目**回代,
+/// 不能让「删掉条目出口、IP 条目照旧」从 `ip_entries` 缺席的口子溜过去。
+fn check_exits_within_items<'a>(
+    uses: &[(String, String)],
+    item_exits: impl IntoIterator<Item = Option<&'a Value>>,
+) -> Result<(), BosError> {
+    if uses.is_empty() {
         return Ok(());
     }
     let mut allowed: HashSet<String> = HashSet::new();
     for value in item_exits.into_iter().flatten() {
         collect_item_exit_keys(value, &mut allowed);
     }
-    let bad: Vec<String> = ips
+    let bad: Vec<String> = uses
         .iter()
-        .enumerate()
-        .filter(|(_, e)| match super::line_exit::exit_key(&e.line_exit) {
+        .filter(|(_, raw)| match super::line_exit::exit_key(raw) {
             Some(key) => !allowed.contains(&key),
             None => true,
         })
-        .map(|(index, e)| format!("ip_entries[{index}].line_exit「{}」", e.line_exit))
+        .map(|(field, raw)| format!("{field}「{raw}」"))
         .collect();
     if bad.is_empty() {
         return Ok(());
@@ -2714,6 +2729,26 @@ async fn do_update(
         let (mut items, dropped) = resolve_items(db, &cur.customer_id, raw_items).await?;
         // 固定 IP 条目的出口只能取自**本次生效**的服务构成已选出口(2026-11-16 裁定)。
         check_ip_exits_in_items(&ips, items.iter().map(|item| Some(&item.line_exits)))?;
+        if !replace_ips {
+            // 只改服务构成、未重发 IP ⇒ 库内 IP 条目的出口也必须仍落在新条目出口集合内,
+            // 否则「把条目的出口删掉」就能留下一批悬空的 IP 出口。
+            let stored_ips = load_children(db, &[contract_id.to_string()])
+                .await?
+                .1
+                .get(contract_id)
+                .cloned()
+                .unwrap_or_default();
+            let used: Vec<(String, String)> = stored_ips
+                .iter()
+                .enumerate()
+                .filter_map(|(index, e)| {
+                    e.get("line_exit").and_then(Value::as_str).map(|raw| {
+                        (format!("ip_entries[{index}].line_exit"), raw.to_string())
+                    })
+                })
+                .collect();
+            check_exits_within_items(&used, items.iter().map(|item| Some(&item.line_exits)))?;
+        }
         item_dropped = dropped;
         let new_ids =
             issue_ids(db, "SI", "contract_service_item", year, items.iter().filter(|i| i.item_id.is_none()).count())

+ 3 - 3
web-scaffold/src/domain/__tests__/contract-draft.test.ts

@@ -90,7 +90,7 @@ describe("frozenChanges · 编辑口径守卫(两轴独立判定)", () => {
     const base = baseline();
     expect(frozenChanges({ ...base, amount: "1" }, base, billingOnlyLocked)).toEqual(["合同金额"]);
     expect(
-      frozenChanges({ ...base, needIp: true, ipRows: [{ key: "ip-1", line_exit: "德国", bandwidth_tier_mbps: "5", ip_count: "2" }] }, base, billingOnlyLocked),
+      frozenChanges({ ...base, needIp: true, ipRows: [{ key: "ip-1", line_exit: "香港", bandwidth_tier_mbps: "5", ip_count: "2" }] }, base, billingOnlyLocked),
     ).toEqual(["需分配 IP"]);
     expect(frozenChanges({ ...base, externalNo: "WB-NEW" }, base, billingOnlyLocked)).toEqual([]);
     expect(frozenChanges({ ...base, agent: "李四" }, base, billingOnlyLocked)).toEqual([]);
@@ -100,7 +100,7 @@ describe("frozenChanges · 编辑口径守卫(两轴独立判定)", () => {
     const base = baseline();
     expect(frozenChanges({ ...base, amount: "1", externalNo: "WB-NEW" }, base, allOpen)).toEqual([]);
     expect(
-      frozenChanges({ ...base, needIp: true, ipRows: [{ key: "ip-1", line_exit: "德国", bandwidth_tier_mbps: "5", ip_count: "2" }] }, base, allOpen),
+      frozenChanges({ ...base, needIp: true, ipRows: [{ key: "ip-1", line_exit: "香港", bandwidth_tier_mbps: "5", ip_count: "2" }] }, base, allOpen),
     ).toEqual([]);
   });
 
@@ -126,7 +126,7 @@ describe("changedWriteFields · 只提交变了的字段", () => {
     const items = changedWriteFields({ ...base, items: [{ ...base.items[0], quantity: 2 }] }, base);
     expect(Object.keys(items)).toEqual(["serviceItems"]);
     const ip = changedWriteFields(
-      { ...base, needIp: true, ipRows: [{ key: "ip-1", line_exit: "德国", bandwidth_tier_mbps: "5", ip_count: "2" }] },
+      { ...base, needIp: true, ipRows: [{ key: "ip-1", line_exit: "香港", bandwidth_tier_mbps: "5", ip_count: "2" }] },
       base,
     );
     expect(Object.keys(ip).sort()).toEqual(["ipCarried", "ipEntries"]);

+ 8 - 2
web-scaffold/src/pages/ContractDetailPages.tsx

@@ -217,6 +217,11 @@ export function ContractEditorPage() {
     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; }
@@ -569,14 +574,15 @@ export function ContractEditorPage() {
             {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([...exitOptions, row.line_exit.trim()].filter(Boolean))].map((exit) => <option key={exit} value={exit}>{exit}</option>)}</select></label>
+                  <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 数量,三元组缺一项后端回 `KLT-L217`;带宽档位从「套餐配置 → 线路出口」的档位清单里选(可含「不承诺带宽」=该条 IP 不带带宽承诺,对应 `bandwidth_committed=false`)。出口<strong>只能从上方服务构成条目已选出口中选</strong>,初始默认带出第一个已选出口。</p>
             </> : <p className="contract-form-summary">未勾选=本表零行(提交时随合同送 `ip_entries: []`=清空旧条目)。</p>}
           </section>
           <section className="ops-record-card">

+ 8 - 2
web-scaffold/src/pages/ContractRecordPage.tsx

@@ -212,6 +212,11 @@ export function ContractRecordPage() {
     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]);
+  /** 固定 IP 条目的出口候选=**上方服务构成条目已选出口**(2026-11-16 裁定,⛔ 全量目录)。 */
+  const itemExitOptions = useMemo(() => {
+    if (!draft) return [];
+    return [...new Set(draft.items.flatMap((item) => item.exits))];
+  }, [draft]);
 
   const patch = <K extends keyof ContractDraft>(key: K, value: ContractDraft[K]) => {
     setDraft((current) => (current ? { ...current, [key]: value } : current));
@@ -507,14 +512,15 @@ export function ContractRecordPage() {
             {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([...exitOptions, row.line_exit.trim()].filter(Boolean))].map((exit) => <option key={exit} value={exit}>{exit}</option>)}</select></label>
+                  <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-record-note">上方服务构成条目尚未选择线路出口 ⇒ IP 条目没有可选项;请先在条目上勾选线路出口。</p>}
               <div className="ops-contract-item-actions"><Button variant="outline" size="sm" onClick={addIpRow}><Plus size={15} />添加 IP 条目</Button></div>
-              <p className="contract-record-note">每条=线路出口+带宽档位+IP 数量,三元组缺一项后端回 `KLT-L217`;带宽档位从「套餐配置 → 线路出口」的档位清单里选(可含「不承诺带宽」=该条 IP 不带带宽承诺)。出口从套餐配置清单选择,默认带出上方条目的第一个出口。</p>
+              <p className="contract-record-note">每条=线路出口+带宽档位+IP 数量,三元组缺一项后端回 `KLT-L217`;带宽档位从「套餐配置 → 线路出口」的档位清单里选(可含「不承诺带宽」=该条 IP 不带带宽承诺)。出口<strong>只能从上方服务构成条目已选出口中选</strong>,初始默认带出第一个已选出口。</p>
             </> : <p className="contract-record-note">未勾选=本表零行(提交时随合同送 `ip_entries: []`=清空旧条目)。</p>}
           </> : draft.needIp ? <>
             <div className="ops-table-wrap">

+ 11 - 0
web-scaffold/tests/domain-foundation.test.mjs

@@ -21,6 +21,7 @@ import {
   checkAmountCents,
   checkContractRequired,
   checkIpRows,
+  checkIpExitWithinItems,
   checkItemExits,
   splitExitInput,
   yuanTextToCents,
@@ -82,6 +83,16 @@ test("IP 条目要凑齐三元组,带宽档位只认 5/10/30 兆三值", (
   assert.match(checkIpRows([{ line_exit: "美国", bandwidth_tier_mbps: "5", ip_count: "1" }], false) ?? "", /未勾选/);
 });
 
+test("固定 IP 条目的出口只能取自服务构成已选出口(去空白+小写比对)", () => {
+  const rows = [{ line_exit: "美国", bandwidth_tier_mbps: "5", ip_count: "1" }];
+  assert.equal(checkIpExitWithinItems(rows, [["美国", "日本"]]), null);
+  // 归一化命中:条目写「美 国」,IP 写「美国」仍算同一出口。
+  assert.equal(checkIpExitWithinItems(rows, [["美 国"]]), null);
+  assert.match(checkIpExitWithinItems(rows, [["日本"]]) ?? "", /不在服务构成已选出口中/);
+  // 未选择出口=交给 checkIpRows 报「缺线路出口」,本函数不重复拦。
+  assert.equal(checkIpExitWithinItems([{ line_exit: " ", bandwidth_tier_mbps: "5", ip_count: "1" }], []), null);
+});
+
 test("出口提交校验对两种形态同一条:必须从目录选择 1–8 个", () => {
   const planBased = appendLineExits([], splitExitInput("中国香港、美国")).exits;
   assert.deepEqual(planBased, ["中国香港", "美国"]);