Forráskód Böngészése

fix(ticket): 收口工单全流程余量 D-06/D-07/D-10/D-11

补齐续签配置 GET 路由与十席回填单批写入,施工详情补账号/带宽/历史开通,列表按合同命中续签与并单。

Co-authored-by: Cursor <cursoragent@cursor.com>
cg 1 napja
szülő
commit
ef649d5a61

+ 23 - 2
src/bin/klt-bos/openapi.yaml

@@ -6932,7 +6932,9 @@ paths:
                       description: 订单(订阅)过滤:只回本订单的工单(订单详情「关联工单」现查,P3-D6)。空串=不过滤
                     contract_id:
                       type: string
-                      description: 合同过滤:服务端先把该合同下的订单解成集合再过滤,合同还没有订单时回空集(不退化成不过滤,P3-D7)。空串=不过滤
+                      description: >-
+                        合同过滤(D-10):命中主订阅合同、并单成员订阅、续签来源合同(renew_from_contract_id)
+                        与续签结果合同(renew_contract_id)。合同下既无订阅也无续签关联时回空集(不退化成不过滤)。空串=不过滤
                     customer_id:
                       type: string
                       description: 客户过滤:只回本客户的工单。空串=不过滤
@@ -6969,7 +6971,9 @@ paths:
         D-04:续签单 ticket 投影含 `renew_from_contract_id`/`renew_contract_id`,并补
         `renew_from_contract_no`/`renew_from_end_date`/`renew_contract_no`。
         D-07:customer 含 `address_missing`/`contact_*_missing`/台账侧 `contact_mobile_full`;
-        停机类可回落 `open_stop.accounts` 预览;construction_guide 可标 `subscription_missing`。
+        停机类可回落 `open_stop.accounts` 预览(无在用再回落已停);开通类 `construction_guide.pending_accounts`
+        列待开通分账号;档位承诺位与兆数不一致时标 `bandwidth_missing`;故障/售后亦带 `prior_activation`。
+        D-10:`ticket.contract_id`/`order.contract_id` 经订阅或续签字段投影。
       operationId: ticket_detail
       tags:
       - 工单与开停交付
@@ -8694,6 +8698,23 @@ paths:
 
 
   /contract/renewal_config@v1:
+    get:
+      summary: 合同续签提醒配置查询(GET)
+      description: 与 POST 同义;补齐 GET 路由声明,供网关与直连读取。
+      operationId: contract_renewal_config_get
+      tags:
+      - 合同
+      x-require-auth: true
+      x-resource-type:
+        $ref: '#/components/x-resource-types/contract/code'
+      x-action:
+        $ref: '#/components/x-actions/renewal_config/code'
+      x-version: v1
+      x-permission-visibility: catalog
+      x-error-codes: [11104]
+      responses:
+        "200":
+          description: 成功。统一信封 code/message/data;data 含 notice_days、generate_mode、generate_mode_name、row_version、updated_at、updated_by
     post:
       summary: 合同续签提醒配置查询
       description: |

+ 14 - 0
src/migrations/dev/20261125000001_plan_bandwidth_committed_repair.sql

@@ -0,0 +1,14 @@
+-- 套餐带宽承诺位脏数据再修(2026-11-25,D-07)。
+--
+-- 现象:工单详情 `bandwidth_committed=true` 但上下行恒 null(P-001/P-002 等),
+--   施工指导无法给出上下行建议。
+-- 根因:`20261107000002` 补列 DEFAULT TRUE;`20261120000001` 已把「真+两空」改成
+--   不承诺,但本环境仍有存量/再导入行未吃到该回填。
+--
+-- 口径与 20261120 一致:上下行都空=未配置带宽=不承诺。幂等,已有兆数的承诺档不动。
+
+UPDATE catalog_plan
+SET bandwidth_committed = FALSE
+WHERE bandwidth_committed IS TRUE
+  AND bandwidth_up_mbps IS NULL
+  AND bandwidth_down_mbps IS NULL;

+ 96 - 5
src/modules/ops/src/handlers/construction_guide.rs

@@ -18,14 +18,16 @@ pub async fn build(
     members: &[Value],
     service_items: &[Value],
 ) -> Result<Value, BosError> {
-    let plan = plan_summary(subscription);
     let member_plans: Vec<Value> = members.iter().map(plan_summary).collect();
 
-    let defaults = defaults_from_plan(subscription);
-
+    // D-07:停机/变更/排障都需要历史开通参数(链路、出口、带宽实测);故障单此前 prior 恒空。
     let needs_prior = matches!(
         ticket_type,
-        domain::T_EXPIRY_STOP | domain::T_SERVICE_STOP | domain::T_UPDOWN
+        domain::T_EXPIRY_STOP
+            | domain::T_SERVICE_STOP
+            | domain::T_UPDOWN
+            | domain::T_FAULT
+            | domain::T_AFTER_SALE
     );
     let prior = if needs_prior {
         prior_activation(db, customer_id, sfield(subscription, "subscription_id").as_deref()).await?
@@ -33,6 +35,11 @@ pub async fn build(
         Value::Null
     };
 
+    // D-07:档位带宽空时,回落历史开通通路的上下行建议值(现场至少有可参照的实测数)。
+    let mut plan = plan_summary(subscription);
+    let mut defaults = defaults_from_plan(subscription);
+    enrich_bandwidth_from_prior(&mut plan, &mut defaults, &prior);
+
     let (plan_before, plan_after) = if ticket_type == domain::T_UPDOWN {
         updown_plan_pair(service_items, subscription)
     } else {
@@ -50,6 +57,88 @@ pub async fn build(
     }))
 }
 
+/// 档位上下行为空时,用历史开通路的众数/首条 up/down 填建议值(不伪造承诺位)。
+fn enrich_bandwidth_from_prior(plan: &mut Value, defaults: &mut Value, prior: &Value) {
+    if prior.is_null() {
+        return;
+    }
+    let Some(routes) = prior.get("routes").and_then(|x| x.as_array()) else {
+        return;
+    };
+    let mut down: Option<f64> = None;
+    let mut up: Option<f64> = None;
+    for r in routes {
+        if down.is_none() {
+            down = num_field(r, "down_mbps");
+        }
+        if up.is_none() {
+            up = num_field(r, "up_mbps");
+        }
+        if down.is_some() && up.is_some() {
+            break;
+        }
+    }
+    if let Some(o) = defaults.as_object_mut() {
+        if o.get("suggest_down_mbps").and_then(|x| {
+            x.as_f64()
+                .or_else(|| x.as_i64().map(|n| n as f64))
+                .or_else(|| x.as_str().and_then(|s| s.parse().ok()))
+        }).is_none()
+        {
+            if let Some(d) = down {
+                o.insert("suggest_down_mbps".into(), json!(d));
+            }
+        }
+        if o.get("suggest_up_mbps").and_then(|x| {
+            x.as_f64()
+                .or_else(|| x.as_i64().map(|n| n as f64))
+                .or_else(|| x.as_str().and_then(|s| s.parse().ok()))
+        }).is_none()
+        {
+            if let Some(u) = up {
+                o.insert("suggest_up_mbps".into(), json!(u));
+            }
+        }
+        // IP 档建议:有下行时按 defaults_from_plan 同一分档。
+        if o.get("suggest_ip_bandwidth_mbps").is_none()
+            || o.get("suggest_ip_bandwidth_mbps") == Some(&Value::Null)
+        {
+            if let Some(d) = down {
+                let n = d as i64;
+                let tier = if n <= 5 {
+                    5
+                } else if n <= 10 {
+                    10
+                } else {
+                    30
+                };
+                o.insert("suggest_ip_bandwidth_mbps".into(), json!(tier));
+            }
+        }
+    }
+    if let Some(o) = plan.as_object_mut() {
+        if o.get("bandwidth_down_mbps").and_then(Value::as_f64).is_none()
+            && o
+                .get("bandwidth_down_mbps")
+                .and_then(|x| x.as_i64())
+                .is_none()
+        {
+            if let Some(d) = down {
+                o.insert("bandwidth_down_mbps".into(), json!(d));
+                o.insert("bandwidth_from_prior".into(), json!(true));
+            }
+        }
+        if o.get("bandwidth_up_mbps").and_then(Value::as_f64).is_none()
+            && o.get("bandwidth_up_mbps").and_then(|x| x.as_i64()).is_none()
+        {
+            if let Some(u) = up {
+                o.insert("bandwidth_up_mbps".into(), json!(u));
+                o.insert("bandwidth_from_prior".into(), json!(true));
+            }
+        }
+    }
+}
+
 fn plan_summary(sub: &Value) -> Value {
     if sub.is_null() {
         return Value::Null;
@@ -66,6 +155,7 @@ fn plan_summary(sub: &Value) -> Value {
         "bandwidth_up_mbps": num_field(sub, "bandwidth_up_mbps"),
         "bandwidth_down_mbps": num_field(sub, "bandwidth_down_mbps"),
         "bandwidth_committed": boolish(sub, "bandwidth_committed"),
+        "bandwidth_missing": sub.get("bandwidth_missing").and_then(|x| x.as_bool()).unwrap_or(false),
         "line_exits": sub.get("line_exits").cloned().unwrap_or(Value::Null),
         "status": sfield(sub, "status"),
         "parent_subscription_id": sfield(sub, "parent_subscription_id"),
@@ -225,7 +315,8 @@ async fn prior_activation(
     // 绑定账号(只读指导,无 PIN)。
     let binds = rows_1(
         db,
-        "SELECT a.backfill_ip_id::text AS backfill_ip_id, a.sub_account_id::text AS sub_account_id \
+        "SELECT a.id::text AS id, a.backfill_ip_id::text AS backfill_ip_id, \
+         a.sub_account_id::text AS sub_account_id \
          FROM ticket_backfill_ip_account a WHERE a.ticket_id = $1::bigint ORDER BY id",
         Value::String(tid.clone()),
     )

+ 79 - 37
src/modules/ops/src/handlers/handle.rs

@@ -1206,33 +1206,29 @@ async fn backfill_inner(state: &AppState, auth: &AuthContext, body: BackfillReq)
     ));
     // 组一+组二:⛔ `::inet`——物理列是 `varchar(64)`(数据模型§2.4:DM 类型白名单无 `inet`)。
     // `FROM ticket` 是刻意的条件插:主行没落成就一条明细也不插。
-    for (ri, r) in picked.iter().enumerate() {
-        let encap = r
-            .tunnel_encap
-            .as_deref()
-            .map(str::trim)
-            .filter(|s| !s.is_empty())
-            .unwrap_or("none");
-        let (pin_c, pin_kv, cpid_c, cpid_kv) = match route_sealed.get(ri).and_then(|s| s.as_ref()) {
-            Some(sec) => (
-                Value::String(sec.0.clone()),
-                Value::String(sec.1.clone()),
-                sec.2.clone().map(Value::String).unwrap_or(Value::Null),
-                sec.3.clone().map(Value::String).unwrap_or(Value::Null),
-            ),
-            None => (Value::Null, Value::Null, Value::Null, Value::Null),
-        };
-        stmts.push(DmlStatement::new(
-            "INSERT INTO ticket_backfill_route (id, backfill_id, ticket_id, sub_account_id, \
-             network_account_name, intranet_ip, subnet_mask, gateway, vlan, tunnel_encap, vni, \
-             src_endpoint, dst_endpoint, egress_pop, down_mbps, up_mbps, proxy_host, proxy_port, \
-             pin_cipher, pin_key_version, cpid_cipher, cpid_key_version, created_at) \
-             SELECT $1::bigint, $2::bigint, $3::bigint, $4::text, $5::text, $6::varchar, \
-             $7::varchar, $8::varchar, $9::text, $10::text, $11::text, $12::text, $13::text, \
-             $14::text, $15::numeric, $16::numeric, $17::text, $18::int, $19::text, $20::text, \
-             $21::text, $22::text, now() FROM ticket tt WHERE tt.ticket_id = $3::bigint"
-                .to_string(),
-            vec![
+    // D-11:全部通路合成一条 `INSERT … SELECT … UNION ALL`,避免 10 席逐行插入撑破
+    // UDS 单批 32 条语句上限;仍与其余写入同批原子提交。
+    if !picked.is_empty() {
+        let mut p = Params::default();
+        let mut selects = Vec::with_capacity(picked.len());
+        for (ri, r) in picked.iter().enumerate() {
+            let encap = r
+                .tunnel_encap
+                .as_deref()
+                .map(str::trim)
+                .filter(|s| !s.is_empty())
+                .unwrap_or("none");
+            let (pin_c, pin_kv, cpid_c, cpid_kv) =
+                match route_sealed.get(ri).and_then(|s| s.as_ref()) {
+                    Some(sec) => (
+                        Value::String(sec.0.clone()),
+                        Value::String(sec.1.clone()),
+                        sec.2.clone().map(Value::String).unwrap_or(Value::Null),
+                        sec.3.clone().map(Value::String).unwrap_or(Value::Null),
+                    ),
+                    None => (Value::Null, Value::Null, Value::Null, Value::Null),
+                };
+            let values = vec![
                 dbx::as_num(&ids::snowflake().to_string()),
                 hid.clone(),
                 idn.clone(),
@@ -1255,7 +1251,33 @@ async fn backfill_inner(state: &AppState, auth: &AuthContext, body: BackfillReq)
                 pin_kv,
                 cpid_c,
                 cpid_kv,
-            ],
+            ];
+            let ph: Vec<String> = values.into_iter().map(|v| p.push(v)).collect();
+            const CASTS: [&str; 22] = [
+                "bigint", "bigint", "bigint", "text", "text", "varchar", "varchar", "varchar",
+                "text", "text", "text", "text", "text", "text", "numeric", "numeric", "text",
+                "int", "text", "text", "text", "text",
+            ];
+            let exprs: Vec<String> = ph
+                .iter()
+                .zip(CASTS)
+                .map(|(ph, cast)| format!("{ph}::{cast}"))
+                .collect();
+            selects.push(format!(
+                "SELECT {}, now() FROM ticket tt WHERE tt.ticket_id = {}::bigint",
+                exprs.join(", "),
+                ph[2]
+            ));
+        }
+        stmts.push(DmlStatement::new(
+            format!(
+                "INSERT INTO ticket_backfill_route (id, backfill_id, ticket_id, sub_account_id, \
+                 network_account_name, intranet_ip, subnet_mask, gateway, vlan, tunnel_encap, vni, \
+                 src_endpoint, dst_endpoint, egress_pop, down_mbps, up_mbps, proxy_host, proxy_port, \
+                 pin_cipher, pin_key_version, cpid_cipher, cpid_key_version, created_at) {}",
+                selects.join(" UNION ALL ")
+            ),
+            p.values().to_vec(),
         ));
     }
     // 组三:按行级动作(D-14)分流写入——
@@ -1986,14 +2008,13 @@ pub(crate) async fn open_stop_apply(
     if let Some(edate) = effect_date {
         let oid = plan.open_stop_id.clone().unwrap_or_default();
         // 第 4 步:逐账号事实 append(⛔ UPDATE 覆盖——每账号一行、含生效日期)。
-        for (id, before) in &accounts {
-            plan.stmts.push(DmlStatement::new(
-                "INSERT INTO ticket_open_stop_account (id, open_stop_id, sub_account_id, \
-                 before_status, after_status, effective_date, source, created_at) \
-                 SELECT $1::bigint, $2::bigint, $3::text, $4::text, $5::text, $6::date, $7::text, \
-                 now() FROM ticket_open_stop o WHERE o.open_stop_id = $2::bigint"
-                    .to_string(),
-                vec![
+        // D-11:账号事实同样合并为一条 INSERT,保留逐行条件插语义,避免与通路明细叠加后
+        // 超过 UDS 单批 32 条语句上限。
+        if !accounts.is_empty() {
+            let mut p = Params::default();
+            let mut selects = Vec::with_capacity(accounts.len());
+            for (id, before) in &accounts {
+                let values = vec![
                     dbx::as_num(&ids::snowflake().to_string()),
                     dbx::as_num(&oid),
                     Value::String(id.clone()),
@@ -2001,7 +2022,28 @@ pub(crate) async fn open_stop_apply(
                     Value::String(after.to_string()),
                     dbx::bind_date(Some(edate)),
                     Value::String(source.to_string()),
-                ],
+                ];
+                let ph: Vec<String> = values.into_iter().map(|v| p.push(v)).collect();
+                const CASTS: [&str; 7] =
+                    ["bigint", "bigint", "text", "text", "text", "date", "text"];
+                let exprs: Vec<String> = ph
+                    .iter()
+                    .zip(CASTS)
+                    .map(|(ph, cast)| format!("{ph}::{cast}"))
+                    .collect();
+                selects.push(format!(
+                    "SELECT {}, now() FROM ticket_open_stop o WHERE o.open_stop_id = {}::bigint",
+                    exprs.join(", "),
+                    ph[1]
+                ));
+            }
+            plan.stmts.push(DmlStatement::new(
+                format!(
+                    "INSERT INTO ticket_open_stop_account (id, open_stop_id, sub_account_id, \
+                     before_status, after_status, effective_date, source, created_at) {}",
+                    selects.join(" UNION ALL ")
+                ),
+                p.values().to_vec(),
             ));
         }
         // 第 5 步:客户主档状态(条件更新带原状态入 WHERE)+一条变更历史。

+ 146 - 8
src/modules/ops/src/handlers/read.rs

@@ -520,11 +520,19 @@ async fn list_inner(state: AppState, auth: AuthContext, body: ListReq) -> Result
         fp.push(format!("t.assignee_user_id::text = {ph}::text"));
     }
     if let Some(v) = trim_opt(body.contract_id.as_deref()) {
+        // D-10:合同口径=订阅主挂 + 并单成员 + 续签来源/结果合同(renew_*),
+        // ⛔ 只用 `t.subscription_id IN (合同下订阅)`——续签单无订阅、并单成员不在主列会被漏。
+        // UDS ⛔ EXISTS 子查询 ⇒ 先把订阅/成员工单解成字面量再拼 OR。
         #[derive(Deserialize)]
         struct SubIdRow {
             #[serde(deserialize_with = "de::as_string")]
             subscription_id: String,
         }
+        #[derive(Deserialize)]
+        struct TidRow {
+            #[serde(deserialize_with = "de::as_string")]
+            ticket_id: String,
+        }
         let mut q = Params::default();
         let c = q.push(Value::String(v.to_string()));
         let subs = state
@@ -538,12 +546,35 @@ async fn list_inner(state: AppState, auth: AuthContext, body: ListReq) -> Result
             )
             .await?;
         let ids: Vec<String> = subs.into_iter().map(|r| r.subscription_id).collect();
-        if ids.is_empty() {
-            // 合同还没有订单:诚实空集,⛔ 退化成「不过滤」而把同客户别的单捞进来。
-            fp.push("1 = 0".to_string());
-        } else {
-            fp.push(push_in(&mut p, "t.subscription_id::text", &ids, "text"));
+        let mut member_tids: Vec<String> = Vec::new();
+        if !ids.is_empty() {
+            let mut mq = Params::default();
+            let in_pred = push_in(&mut mq, "m.subscription_id::text", &ids, "text");
+            member_tids = state
+                .db
+                .query_all::<TidRow>(
+                    &format!(
+                        "SELECT DISTINCT m.ticket_id::text AS ticket_id \
+                         FROM ticket_subscription m WHERE {in_pred}"
+                    ),
+                    mq.values(),
+                )
+                .await?
+                .into_iter()
+                .map(|r| r.ticket_id)
+                .collect();
+        }
+        let mut ors: Vec<String> = Vec::new();
+        if !ids.is_empty() {
+            ors.push(push_in(&mut p, "t.subscription_id::text", &ids, "text"));
         }
+        if !member_tids.is_empty() {
+            ors.push(push_in(&mut p, "t.ticket_id::text", &member_tids, "text"));
+        }
+        let ph = p.push(Value::String(v.to_string()));
+        ors.push(format!("t.renew_from_contract_id = {ph}::text"));
+        ors.push(format!("t.renew_contract_id = {ph}::text"));
+        fp.push(format!("({})", ors.join(" OR ")));
     }
     let filter = fp.join(" AND ");
     let outer = outer_where(&state, &auth, &mut p, &filter).await?;
@@ -1636,6 +1667,34 @@ pub(crate) fn sfield(v: &Value, key: &str) -> Option<String> {
         .map(str::to_string)
 }
 
+/// D-07:详情订阅带宽归一——承诺位真但上下行皆空 ⇒ 标 missing 并改写为不承诺。
+fn normalize_subscription_bandwidth(subscription: &mut Value) {
+    let Some(obj) = subscription.as_object_mut() else {
+        return;
+    };
+    let up = obj
+        .get("bandwidth_up_mbps")
+        .and_then(|x| x.as_str())
+        .map(str::trim)
+        .filter(|s| !s.is_empty());
+    let down = obj
+        .get("bandwidth_down_mbps")
+        .and_then(|x| x.as_str())
+        .map(str::trim)
+        .filter(|s| !s.is_empty());
+    let committed = obj
+        .get("bandwidth_committed")
+        .and_then(|x| x.as_str())
+        .map(|s| matches!(s.trim(), "true" | "1" | "t"))
+        .unwrap_or(false);
+    if committed && up.is_none() && down.is_none() {
+        obj.insert("bandwidth_committed".into(), json!("false"));
+        obj.insert("bandwidth_missing".into(), json!(true));
+    } else {
+        obj.insert("bandwidth_missing".into(), json!(false));
+    }
+}
+
 /// 联系方式:像号码才按工单§5.3 遮蔽(前 3 后 4)。
 ///
 /// 客户联系方式是自由文本(电话/分机/邮箱都可能),
@@ -1919,6 +1978,7 @@ async fn detail_inner(
             .unwrap_or(Value::Null),
     };
     let sub_sql = "SELECT s.subscription_id::text AS subscription_id, s.customer_id, \
+                 s.contract_id::text AS contract_id, \
                  s.plan_id, s.plan_name, s.plan_kind, s.plan_family, s.sub_mode, s.line_exits, \
                  s.order_no, s.term, s.quantity::text AS quantity, \
                  s.quota_slots::text AS quota_slots, \
@@ -1937,6 +1997,7 @@ async fn detail_inner(
             .db
             .query_one::<Value>(
                 // 施工指导需要档位带宽/席位/份数:join catalog_plan,快照列仍以订阅为准。
+                // D-10:投影 `contract_id`(工单表本身不存合同列,经订阅间接关联)。
                 &format!("{sub_sql} WHERE s.subscription_id = $1::text LIMIT 1"),
                 &[Value::String(s.to_string())],
             )
@@ -1964,6 +2025,9 @@ async fn detail_inner(
             }
         }
     }
+    // D-07:档位「承诺位=真但上下行皆空」是存量脏数据(迁移 20261120 口径=不承诺)。
+    // 须在订阅回落之后再归一,否则故障单的 fallback 订阅会漏标 `bandwidth_missing`。
+    normalize_subscription_bandwidth(&mut subscription);
     /*
      * P1(D-2/D-7):并单成员订阅(`ticket_subscription`)**平铺**出参。
      *
@@ -2016,7 +2080,9 @@ async fn detail_inner(
             .await?
         }
     };
-    // D-07:停机类在尚未回填落 open_stop_account 时,回落客户在用分账号清单,告知「将停哪些」。
+    // D-07:停机类在尚未回填落 open_stop_account 时,回落客户分账号清单,告知「将停/已停哪些」。
+    // 优先 in_use(待停);若客户已全部停机(历史单/复测残留)再回落 stopped,避免空清单。
+    // ORDER BY 必须用投影别名(⛔ `sa.sub_account_id`)——DataFusion 会把限定列追加进投影并 13001。
     let ticket_type_now = sfield(&head, "ticket_type").unwrap_or_default();
     if os_accounts.is_empty()
         && matches!(ticket_type_now.as_str(), domain::T_EXPIRY_STOP | domain::T_SERVICE_STOP)
@@ -2029,7 +2095,52 @@ async fn detail_inner(
                  sa.status AS before_status, 'preview'::text AS source \
                  FROM sub_account sa \
                  WHERE sa.customer_id = $1::text AND sa.status = 'in_use' \
-                 ORDER BY sa.sub_account_id",
+                 ORDER BY sub_account_id",
+                Value::String(cid.to_string()),
+            )
+            .await?;
+            if os_accounts.is_empty() {
+                os_accounts = rows_1(
+                    state.db.as_ref(),
+                    "SELECT sa.sub_account_id::text AS sub_account_id, sa.display_name, sa.net_account, \
+                     sa.status AS before_status, 'preview'::text AS source \
+                     FROM sub_account sa \
+                     WHERE sa.customer_id = $1::text AND sa.status = 'stopped' \
+                     ORDER BY sub_account_id",
+                    Value::String(cid.to_string()),
+                )
+                .await?;
+            }
+        }
+    }
+    // D-07:开通类下发待开通分账号预览(not_opened),条数按本单套餐席位封顶——
+    // ⛔ 把客户名下全部未开通席一股脑倒出(同客户多合同会到上百行)。
+    let mut pending_accounts: Vec<Value> = Vec::new();
+    if matches!(
+        ticket_type_now.as_str(),
+        domain::T_OPEN | domain::T_SERVICE_OPEN | domain::T_UPDOWN
+    ) {
+        if let Some(cid) = customer_id.as_deref() {
+            let seat_cap = subscription
+                .get("quota_slots")
+                .and_then(|x| {
+                    x.as_str()
+                        .and_then(|s| s.parse::<i64>().ok())
+                        .or_else(|| x.as_i64())
+                })
+                .filter(|&n| n > 0)
+                .unwrap_or(12);
+            // UDS 对 LIMIT 绑参偶发不稳 ⇒ 字面量封顶(席位上限与 PATH_SEAT_MAX 同量级)。
+            let lim = seat_cap.clamp(1, 50);
+            pending_accounts = rows_1(
+                state.db.as_ref(),
+                &format!(
+                    "SELECT sa.sub_account_id::text AS sub_account_id, sa.display_name, sa.net_account, \
+                     sa.status AS before_status, 'preview'::text AS source \
+                     FROM sub_account sa \
+                     WHERE sa.customer_id = $1::text AND sa.status = 'not_opened' \
+                     ORDER BY sub_account_id LIMIT {lim}"
+                ),
                 Value::String(cid.to_string()),
             )
             .await?;
@@ -2072,7 +2183,8 @@ async fn detail_inner(
     .await?;
     let ip_binds = rows_1(
         state.db.as_ref(),
-        "SELECT a.backfill_ip_id::text AS backfill_ip_id, a.sub_account_id::text AS sub_account_id \
+        "SELECT a.id::text AS id, a.backfill_ip_id::text AS backfill_ip_id, \
+         a.sub_account_id::text AS sub_account_id \
          FROM ticket_backfill_ip_account a WHERE a.ticket_id = $1::bigint ORDER BY id",
         Value::String(id.clone()),
     )
@@ -2258,6 +2370,23 @@ async fn detail_inner(
             g.insert("subscription_missing".to_string(), json!(true));
             g.insert("hint".to_string(), json!("无关联订阅"));
         }
+        // D-07:开通类待开通席位清单(与停机 open_stop.accounts 对称)。
+        if !pending_accounts.is_empty() {
+            g.insert("pending_accounts".to_string(), json!(pending_accounts));
+        }
+        if subscription
+            .get("bandwidth_missing")
+            .and_then(|x| x.as_bool())
+            == Some(true)
+        {
+            g.insert("bandwidth_missing".to_string(), json!(true));
+            if g.get("hint").is_none() {
+                g.insert(
+                    "hint".to_string(),
+                    json!("套餐未配置上下行带宽(档位承诺位与兆数不一致),现场按合同/客户确认"),
+                );
+            }
+        }
     }
     let backfill_draft = super::backfill_draft::load_for_detail(state.db.as_ref(), &id)
         .await
@@ -2537,6 +2666,15 @@ async fn finish(
         }
     }
     ticket["overdue"] = json!(overdue);
+    // D-10:工单表无 contract_id 列——主订阅合同投影到 ticket;续签单优先 renew_from。
+    if ticket.get("contract_id").and_then(|x| x.as_str()).map(str::trim).filter(|s| !s.is_empty()).is_none() {
+        if let Some(cid) = sfield(&p.subscription, "contract_id")
+            .or_else(|| sfield(&ticket, "renew_from_contract_id"))
+            .or_else(|| sfield(&ticket, "renew_contract_id"))
+        {
+            ticket["contract_id"] = json!(cid);
+        }
+    }
     // 执行锁与服务开始日(2026-11-17):前端据此显示「未到执行日」提示、把实际开通日的
     // `min` 设成服务开始日;`execution_not_before` 对开通类恒有值(=`expected_done_date`)。
     ticket["execution_locked"] = json!(exec_locked);

+ 1 - 1
src/modules/ops/src/handlers/renewal.rs

@@ -111,7 +111,7 @@ fn mode_label(mode: &str) -> &'static str {
 
 // ══════════════════════════ ① 读配置 ══════════════════════════
 
-/// `POST /contract/renewal_config@v1`——读续签提醒配置(运营侧三类可读;网关只转 POST,GET 仅直连调试)。
+/// `GET|POST /contract/renewal_config@v1`——读续签提醒配置(运营侧三类可读;两种方法同义)。
 pub async fn config_get(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
     if let Err(e) = guard::gate(&auth, guard::OPS_SIDE, "查看续签提醒配置") {
         return Fail::from(e).render();

+ 1 - 2
src/modules/ops/src/router.rs

@@ -85,8 +85,7 @@ pub fn ops_router() -> Router<AppState> {
             post(handlers::form_template::form_template_publish),
         )
         // ── §6.9 合同到期续签(2026-11-17)────────────────────────────────────
-        // D-CT-05:网关对 klt-bos 一律 POST;只挂 GET 时经网关回 50000「未找到匹配路由」。
-        // GET 保留给直连调试;POST 与契约/前端/其它合同口同形。
+        // D-06:GET/POST 同义且都写入 OpenAPI;⛔ 只注册 POST 会让网关 GET 回 50000。
         .route(
             "/contract/renewal_config@v1",
             get(handlers::renewal::config_get).post(handlers::renewal::config_get),

+ 23 - 2
src/openapi.yaml

@@ -6932,7 +6932,9 @@ paths:
                       description: 订单(订阅)过滤:只回本订单的工单(订单详情「关联工单」现查,P3-D6)。空串=不过滤
                     contract_id:
                       type: string
-                      description: 合同过滤:服务端先把该合同下的订单解成集合再过滤,合同还没有订单时回空集(不退化成不过滤,P3-D7)。空串=不过滤
+                      description: >-
+                        合同过滤(D-10):命中主订阅合同、并单成员订阅、续签来源合同(renew_from_contract_id)
+                        与续签结果合同(renew_contract_id)。合同下既无订阅也无续签关联时回空集(不退化成不过滤)。空串=不过滤
                     customer_id:
                       type: string
                       description: 客户过滤:只回本客户的工单。空串=不过滤
@@ -6969,7 +6971,9 @@ paths:
         D-04:续签单 ticket 投影含 `renew_from_contract_id`/`renew_contract_id`,并补
         `renew_from_contract_no`/`renew_from_end_date`/`renew_contract_no`。
         D-07:customer 含 `address_missing`/`contact_*_missing`/台账侧 `contact_mobile_full`;
-        停机类可回落 `open_stop.accounts` 预览;construction_guide 可标 `subscription_missing`。
+        停机类可回落 `open_stop.accounts` 预览(无在用再回落已停);开通类 `construction_guide.pending_accounts`
+        列待开通分账号;档位承诺位与兆数不一致时标 `bandwidth_missing`;故障/售后亦带 `prior_activation`。
+        D-10:`ticket.contract_id`/`order.contract_id` 经订阅或续签字段投影。
       operationId: ticket_detail
       tags:
       - 工单与开停交付
@@ -8695,6 +8699,23 @@ paths:
 
 
   /contract/renewal_config@v1:
+    get:
+      summary: 合同续签提醒配置查询(GET)
+      description: 与 POST 同义;补齐 GET 路由声明,供网关与直连读取。
+      operationId: contract_renewal_config_get
+      tags:
+      - 合同
+      x-require-auth: true
+      x-resource-type:
+        $ref: '#/components/x-resource-types/contract/code'
+      x-action:
+        $ref: '#/components/x-actions/renewal_config/code'
+      x-version: v1
+      x-permission-visibility: catalog
+      x-error-codes: [11104]
+      responses:
+        "200":
+          description: 成功。统一信封 code/message/data;data 含 notice_days、generate_mode、generate_mode_name、row_version、updated_at、updated_by
     post:
       summary: 合同续签提醒配置查询
       description: |

+ 31 - 5
web-scaffold/src/components/work-order/ConstructionGuidePanel.tsx

@@ -29,9 +29,12 @@ function PlanCard({ title, plan }: { title: string; plan: ConstructionPlanSummar
         <div><span>份数</span><strong>{plan.quantity ?? "—"}</strong></div>
         <div><span>分账号额度</span><strong>{plan.quota_slots ?? plan.sub_account_quota ?? "—"}</strong></div>
         <div><span>承诺带宽</span><strong>
-          {[plan.bandwidth_down_mbps != null && `↓${plan.bandwidth_down_mbps}`, plan.bandwidth_up_mbps != null && `↑${plan.bandwidth_up_mbps}`]
-            .filter(Boolean).join(" / ") || "—"}
-          {plan.bandwidth_committed === false ? "(不承诺)" : ""}
+          {plan.bandwidth_missing
+            ? "资料缺失(档位未配上下行)"
+            : ([plan.bandwidth_down_mbps != null && `↓${plan.bandwidth_down_mbps}`, plan.bandwidth_up_mbps != null && `↑${plan.bandwidth_up_mbps}`]
+                .filter(Boolean).join(" / ") || "—")}
+          {plan.bandwidth_committed === false && !plan.bandwidth_missing ? "(不承诺)" : ""}
+          {plan.bandwidth_from_prior ? "(取自历史开通)" : ""}
         </strong></div>
         <div className="wide"><span>线路出口</span><strong>{exitsText(plan.line_exits)}</strong></div>
       </div>
@@ -97,10 +100,13 @@ export function ConstructionGuidePanel({ guide }: { guide: ConstructionGuide | n
   const t = guide.ticket_type ?? "";
   const isStop = t === "expiry_stop" || t === "service_stop";
   const isUpdown = t === "updown";
+  const isFault = t === "fault" || t === "after_sale";
+  const pending = guide.pending_accounts ?? [];
 
   return (
     <section className="wo-guide" aria-label="施工指导">
       <h3 className="work-order-section-title">施工指导</h3>
+      {guide.hint ? <p className="work-order-detail-footnote wo-guide-hint">{guide.hint}</p> : null}
       {isUpdown ? (
         <>
           <PlanCard title="变更前" plan={guide.plan_before} />
@@ -122,8 +128,28 @@ export function ConstructionGuidePanel({ guide }: { guide: ConstructionGuide | n
           </ul>
         </div>
       )}
-      {(isStop || isUpdown) && guide.prior_activation && <PriorBlock prior={guide.prior_activation} />}
-      {guide.defaults && (guide.defaults.suggest_down_mbps != null || (guide.defaults.line_exits?.length ?? 0) > 0) && (
+      {pending.length > 0 && (
+        <div className="wo-guide-card">
+          <h4 className="work-order-subhead">待开通账号({pending.length})</h4>
+          <div className="work-order-table-wrap compact">
+            <table>
+              <thead><tr><th>分账号</th><th>显示名</th><th>网络账户</th><th>当前状态</th></tr></thead>
+              <tbody>
+                {pending.map((a) => (
+                  <tr key={a.sub_account_id ?? a.display_name ?? Math.random()}>
+                    <td>{a.sub_account_id ?? "—"}</td>
+                    <td>{a.display_name ?? "—"}</td>
+                    <td>{a.net_account ?? "—"}</td>
+                    <td>{a.before_status ?? "—"}</td>
+                  </tr>
+                ))}
+              </tbody>
+            </table>
+          </div>
+        </div>
+      )}
+      {(isStop || isUpdown || isFault) && guide.prior_activation && <PriorBlock prior={guide.prior_activation} />}
+      {guide.defaults && (guide.defaults.suggest_down_mbps != null || guide.defaults.suggest_up_mbps != null || (guide.defaults.line_exits?.length ?? 0) > 0) && (
         <p className="work-order-detail-footnote">
           系统建议(可改):出口 {exitsText(guide.defaults.line_exits)}
           {guide.defaults.suggest_down_mbps != null ? ` · 下行 ${guide.defaults.suggest_down_mbps} Mbps` : ""}

+ 34 - 15
web-scaffold/src/lib/api/ticket.ts

@@ -387,6 +387,8 @@ export type TicketHead = {
   detail: string | null;
   customer_id: string | null;
   subscription_id: string | null;
+  /** D-10:经订阅/续签投影的合同 ID(工单表本身不存)。 */
+  contract_id?: string | null;
   reporter_account_id: string | null;
   carrier_order_no: string | null;
   submitter_type: string | null;
@@ -427,31 +429,34 @@ export type TicketHead = {
 };
 
 export type OpenStopAccount = {
-  id: string;
+  /** 回填落库行有 id;D-07 预览行可能缺席。 */
+  id?: string;
   sub_account_id: string | null;
   before_status: string | null;
-  after_status: string | null;
-  effective_date: string | null;
+  after_status?: string | null;
+  effective_date?: string | null;
   source: string | null;
   display_name: string | null;
   net_account: string | null;
 };
 
 export type OpenStop = {
-  open_stop_id: string;
-  customer_id: string | null;
-  subscription_id: string | null;
-  action: string | null;
-  exec_status: string | null;
-  exec_date: string | null;
+  open_stop_id?: string;
+  customer_id?: string | null;
+  subscription_id?: string | null;
+  action?: string | null;
+  exec_status?: string | null;
+  exec_date?: string | null;
   effective_account_count: string | null;
-  backfill_id: string | null;
-  deferred_until: string | null;
-  note: string | null;
-  closed_flag: string | null;
-  row_version: string;
+  backfill_id?: string | null;
+  deferred_until?: string | null;
+  note?: string | null;
+  closed_flag?: string | null;
+  row_version?: string;
   accounts: OpenStopAccount[];
-  overdue: boolean;
+  overdue?: boolean;
+  /** D-07:尚无 open_stop 行时的待停账号预览块。 */
+  preview?: boolean;
 };
 
 export type RouteRow = {
@@ -716,6 +721,8 @@ export type TicketDetail = {  ticket: TicketHead;
   order: {
     subscription_id: string;
     customer_id: string | null;
+    /** D-10:经订阅投影的合同 ID(工单表本身不存)。 */
+    contract_id?: string | null;
     plan_id?: string | null;
     plan_name: string | null;
     plan_kind: string | null;
@@ -733,6 +740,8 @@ export type TicketDetail = {  ticket: TicketHead;
     bandwidth_up_mbps?: string | number | null;
     bandwidth_down_mbps?: string | number | null;
     bandwidth_committed?: string | boolean | null;
+    /** D-07:档位承诺位与兆数不一致时为 true。 */
+    bandwidth_missing?: boolean;
     replaces_subscription_id?: string | null;
     /** P1(D-9):本单主订阅若是增量叠加服务,这里指向它叠加的既有链路订阅。 */
     parent_subscription_id?: string | null;
@@ -779,6 +788,10 @@ export type ConstructionPlanSummary = {
   bandwidth_up_mbps?: number | null;
   bandwidth_down_mbps?: number | null;
   bandwidth_committed?: boolean | null;
+  /** D-07:档位未配齐上下行。 */
+  bandwidth_missing?: boolean;
+  /** D-07:带宽取自历史开通通路,非档位承诺值。 */
+  bandwidth_from_prior?: boolean;
   line_exits?: string[] | string | null;
   status?: string | null;
   parent_subscription_id?: string | null;
@@ -813,6 +826,12 @@ export type ConstructionGuide = {
   prior_activation?: PriorActivation | null;
   plan_before?: ConstructionPlanSummary | null;
   plan_after?: ConstructionPlanSummary | null;
+  /** D-07:开通类待开通分账号预览。 */
+  pending_accounts?: OpenStopAccount[];
+  bandwidth_missing?: boolean;
+  subscription_missing?: boolean;
+  subscription_fallback?: boolean;
+  hint?: string | null;
 };
 
 export type BackfillDraft = {

+ 7 - 5
web-scaffold/src/pages/WorkOrderRecordPage.tsx

@@ -1491,10 +1491,10 @@ export function WorkOrderRecordPage() {
           <p className="work-order-seg-foot">{checklistNote}</p>
         </FactSeg>}
         {(d.open_stop?.accounts.length ?? 0) > 0 && <FactSeg title="账号清单" open={openSeg === "accounts"}
-          summary={`${d.open_stop!.accounts.length} 个账号 · ${d.open_stop!.exec_status === "pending" ? "待生效" : "已生效"}`}
-          badge={d.open_stop!.exec_status === "pending" ? "待生效" : "已生效"} tone={d.open_stop!.exec_status === "pending" ? "warn" : "ok"}>
-          <div className="work-order-table-wrap compact"><table><thead><tr><th>显示名</th><th>网络账户名</th><th>停机前 → 生效后</th><th>生效日</th><th>来源</th></tr></thead><tbody>{d.open_stop!.accounts.map((a) => <tr key={a.id}><td>{a.display_name ?? "-"}</td><td>{a.net_account ?? "-"}</td><td>{label(ACCT_STATUS, a.before_status) || "-"} → {label(ACCT_STATUS, a.after_status) || "-"}</td><td>{a.effective_date ? fmtDate(a.effective_date) : "-"}</td><td>{a.source ?? "-"}</td></tr>)}</tbody></table></div>
-          {d.open_stop && <p className="work-order-seg-foot">开停记录:{d.open_stop.action ? (OPEN_STOP_ACTION_NAMES[d.open_stop.action] ?? d.open_stop.action) : "-"} / {d.open_stop.exec_status ? (EXEC_STATUS_NAMES[d.open_stop.exec_status] ?? d.open_stop.exec_status) : "-"} / 生效账号 {numText(d.open_stop.effective_account_count)} 个{d.open_stop.exec_status === "pending" ? "(待生效)" : ""}{isYes(d.open_stop.closed_flag) ? " · 已随工单关闭" : ""}。</p>}
+          summary={`${d.open_stop!.accounts.length} 个账号 · ${d.open_stop!.preview ? "待停预览" : d.open_stop!.exec_status === "pending" ? "待生效" : "已生效"}`}
+          badge={d.open_stop!.preview ? "预览" : d.open_stop!.exec_status === "pending" ? "待生效" : "已生效"} tone={d.open_stop!.preview || d.open_stop!.exec_status === "pending" ? "warn" : "ok"}>
+          <div className="work-order-table-wrap compact"><table><thead><tr><th>显示名</th><th>网络账户名</th><th>停机前 → 生效后</th><th>生效日</th><th>来源</th></tr></thead><tbody>{d.open_stop!.accounts.map((a) => <tr key={a.id ?? a.sub_account_id ?? `${a.display_name}-${a.net_account}`}><td>{a.display_name ?? "-"}</td><td>{a.net_account ?? "-"}</td><td>{label(ACCT_STATUS, a.before_status) || "-"} → {label(ACCT_STATUS, a.after_status) || (a.source === "preview" ? "待停" : "-")}</td><td>{a.effective_date ? fmtDate(a.effective_date) : "-"}</td><td>{a.source ?? "-"}</td></tr>)}</tbody></table></div>
+          {d.open_stop && <p className="work-order-seg-foot">{d.open_stop.preview ? `待停账号预览 ${numText(d.open_stop.effective_account_count)} 个(回填前供现场核对)。` : <>开停记录:{d.open_stop.action ? (OPEN_STOP_ACTION_NAMES[d.open_stop.action] ?? d.open_stop.action) : "-"} / {d.open_stop.exec_status ? (EXEC_STATUS_NAMES[d.open_stop.exec_status] ?? d.open_stop.exec_status) : "-"} / 生效账号 {numText(d.open_stop.effective_account_count)} 个{d.open_stop.exec_status === "pending" ? "(待生效)" : ""}{isYes(d.open_stop.closed_flag) ? " · 已随工单关闭" : ""}。</>}</p>}
         </FactSeg>}
         {showCompletion && <FactSeg title="竣工与回执" open={openSeg === "completion"}
           summary={d.completion ? `${d.completion.completion_no ?? "—"} · ${receiptState.text}` : "未生成 · 缺口齐备后可生成"}
@@ -1554,7 +1554,9 @@ export function WorkOrderRecordPage() {
                       : (refCustomer.contact_mobile_full || refCustomer.contact_mobile),
                   ].filter(Boolean).join(" / ") || "-"
             }</strong></div>
-            <div className="work-order-trace"><span>通信地址</span><strong>{refCustomer.address_missing ? "资料缺失" : (refCustomer.address ?? "-")}</strong></div>
+            <div className="work-order-trace"><span>通信地址</span><strong>{refCustomer.address_missing
+              ? <button type="button" className="work-order-trace-link work-order-trace-missing" onClick={() => openRef({ kind: "customer", id: refCustomer.customer_id, name: refCustomer.customer_name })}>资料缺失,需补充</button>
+              : (refCustomer.address ?? "-")}</strong></div>
           </> : <p className="work-order-reference-empty">该单未关联客户档案。</p>}
           {refOrder && <div className="work-order-trace"><span>关联订阅</span><strong><button type="button" className="work-order-trace-link" onClick={() => openRef({ kind: "order", id: refOrder.subscription_id, name: refOrder.plan_name })}>{refOrder.plan_name ?? refOrder.subscription_id}</button></strong><small>{[refOrder.subscription_id, label(PLAN_KIND, refOrder.plan_kind), label(PLAN_FAMILY, refOrder.plan_family), label(ORDER_STATUS, refOrder.status), refOrder.actual_opened_at ? `实际开通 ${fmtDate(refOrder.actual_opened_at)}` : null].filter(Boolean).join(" · ")}</small>{refOrder.parent_subscription_id && <small className="order-parent-mark">叠加于 {refOrder.parent_subscription_id}</small>}</div>}
           {/* P1(D-2/D-7):并单成员订阅**平铺**列出,附加成员只标「叠加于 SUB-xxx」,⛔ 折叠成树。 */}

+ 1 - 0
web-scaffold/src/styles/work-order-record.css

@@ -273,6 +273,7 @@
 .work-order-trace-link { padding: 0; border: 0; background: none; color: var(--primary); font: inherit; font-weight: 650; text-align: left; overflow-wrap: anywhere; cursor: pointer; }
 .work-order-trace-link:hover { text-decoration: underline; }
 .work-order-trace-link:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; border-radius: 3px; }
+.work-order-trace-missing { color: var(--danger, #b42318); }
 
 /* 材料行的动作行:各流程段内的「补充过程材料」入口(抽屉触发器,表单不常驻) */
 .work-order-materials-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }