Selaa lähdekoodia

feat(api,web): 合同签订表单重构——合同类型/签署日期/服务期(月)替代付款周期

合同主档口径(后端+迁移)
- 新增 contract_type(new/renew/expand/change)与 sign_date;pay_cycle 换成 service_months(1..600),
  结束日仍由「生效日 + 服务期 − 1 天」推算;存量行按旧周期换算、按起止日兜底、签署日期取交接日期回填。
- 写口/读口、bos-invariant 校验与 60004 短路顺序同步改口径,openapi 两份契约同步。

合同签订表单(前端)
- 页面更名「合同签订表单」,眉标「合同管理 · 签订」,副标题改为采集客户、商务、订购额度与合规信息口径。
- 02 合同基本信息改一行三列:合同编号/外部单号/合同类型;运营商经办人姓名/电话/签署日期;
  服务期(月)(月/季/年/3 年快捷)/生效日期/到期日期(自动推算)。
- 交接日期并入签署日期(同值写 agent_handover_on);去掉录入经办人块、机构项与「5 年」快捷。
- 合同附件复用营业执照影像的整块拖曳卡片,落在 02 卡片最下面。
- 所属区域下拉摘掉「全网」虚根直接以省为根,且不再默认选中;区域未选时点击运营商/合伙人/
  运营团队/运维团队就地提示「请先选取所属区域」。
- 必填完成度、业务口径摘要与右栏卡片同步瘦身,提交区只留「校验并提交/取消」。

Co-authored-by: Cursor <cursoragent@cursor.com>
cg 3 päivää sitten
vanhempi
commit
7a83df21ca

+ 44 - 13
src/bin/klt-bos/openapi.yaml

@@ -4357,23 +4357,40 @@ paths:
                     external_no:
                       type: string
                       description: 外部合同号(可选)
+                    contract_type:
+                      type: string
+                      description: >-
+                        合同类型:new(新建,缺省)/renew(续签)/expand(扩容补充协议)/change(变更协议)。
+                        语义收口:renew 必须同时给 renew_from_contract_id;expand 的服务构成必须整批为增量附加项;
+                        带 renew_from_contract_id 的合同类型只能是 renew。
+                      enum:
+                      - new
+                      - renew
+                      - expand
+                      - change
+                    sign_date:
+                      type: string
+                      description: 签署日期(YYYY-MM-DD;选填,缺省按 agent_handover_on 兜底)
+                      format: date
                     contract_amount_cents:
                       type: integer
                       description: 合同金额(分,可选)
-                    pay_cycle:
-                      type: string
-                      description: 付款周期:yearly/quarterly/monthly
-                      enum:
-                      - yearly
-                      - quarterly
-                      - monthly
+                    service_months:
+                      type: integer
+                      description: >-
+                        服务期(月,1~600,必填):替代原 pay_cycle;结束日=生效日+服务期−1 天
+                        (该月无对应日先取月末),页面锁定为只读推算值。
+                      minimum: 1
+                      maximum: 600
                     start_date:
                       type: string
                       description: 合同开始日期(YYYY-MM-DD)
                       format: date
                     end_date:
                       type: string
-                      description: 合同结束日期(YYYY-MM-DD)
+                      description: >-
+                        合同结束日期(YYYY-MM-DD,可省略):省略时服务端按「生效日+服务期(月)−1 天」
+                        推算(该月无对应日先取月末);显式给出则按显式值落库。
                       format: date
                     agent_name:
                       type: string
@@ -4475,7 +4492,7 @@ paths:
                             - replaces_subscription_id
                   required:
                   - contract_amount_cents
-                  - pay_cycle
+                  - service_months
                   - start_date
                   - end_date
                   - agent_name
@@ -4490,7 +4507,7 @@ paths:
   /contract/update@v1:
     post:
       summary: 编辑合同
-      description: 编号与签约客户不可改;条目按 item_id 三向对比增删改。可改范围=bos-invariant::contract_edit_scope 的两条轴(billing:金额/付款周期/期间/服务构成;archive:外部单号/交接日期),两轴独立判定、source=operator_sync 全只读(KLT-L220)、已开通两轴全冻(KLT-L219)、录后 72 小时内两轴全开、未生效只放 billing、未到期只放 archive;经办人(created_by 与录入经办人机构/姓名/联系方式)建后恒只读(KLT-L221);agent_* 为运营商交接单上的经办人,受各自轴约束。⚠️ 2026-11-17:`ip_entries`/`has_fixed_ip` 已下线(视为未知键 ⇒ 11103,境外 IP 由套餐档位 × 订阅份数表达)。保存形态=只提交变了的字段(键缺席=保持现值);审计 INSERT 与业务语句同批提交。
+      description: 编号与签约客户不可改;条目按 item_id 三向对比增删改。可改范围=bos-invariant::contract_edit_scope 的两条轴(billing:金额/服务期(月)/期间/服务构成;archive:合同类型/签署日期/外部单号/交接日期),两轴独立判定、source=operator_sync 全只读(KLT-L220)、已开通两轴全冻(KLT-L219)、录后 72 小时内两轴全开、未生效只放 billing、未到期只放 archive;经办人(created_by 与录入经办人机构/姓名/联系方式)建后恒只读(KLT-L221);agent_* 为运营商交接单上的经办人,受各自轴约束。⚠️ 2026-11-17:`ip_entries`/`has_fixed_ip` 已下线(视为未知键 ⇒ 11103,境外 IP 由套餐档位 × 订阅份数表达)。保存形态=只提交变了的字段(键缺席=保持现值);审计 INSERT 与业务语句同批提交。
       operationId: contract_update
       tags:
       - 合同
@@ -4523,12 +4540,26 @@ paths:
                     external_no:
                       type: string
                       description: 外部合同号
+                    contract_type:
+                      type: string
+                      description: 合同类型(new/renew/expand/change);受 archive 轴约束
+                      enum:
+                      - new
+                      - renew
+                      - expand
+                      - change
+                    sign_date:
+                      type: string
+                      description: 签署日期(受 archive 轴约束)
+                      format: date
                     contract_amount_cents:
                       type: integer
                       description: 合同金额(分)
-                    pay_cycle:
-                      type: string
-                      description: 付款周期
+                    service_months:
+                      type: integer
+                      description: 服务期(月,1~600);受 billing 轴约束,结束日按「生效日+服务期−1 天」重算
+                      minimum: 1
+                      maximum: 600
                     start_date:
                       type: string
                       description: 开始日期

+ 65 - 10
src/crates/bos-invariant/src/lib.rs

@@ -320,8 +320,13 @@ pub struct ContractRaw<'a> {
     pub readonly_keys: &'a [&'a str],
     pub contract_no: Option<&'a str>,
     pub external_no: Option<&'a str>,
+    /// 合同类型:`new`(新建,缺省)/`renew`(续签)/`expand`(扩容补充协议)/`change`(变更协议)。
+    pub contract_type: Option<&'a str>,
+    /// 签署日期(选填;缺省按经办交接日期兜底,见写口)。
+    pub sign_date: Option<&'a str>,
     pub total_amount_cents: Option<i64>,
-    pub payment_cycle: Option<&'a str>,
+    /// 服务期(月):替代原「付款周期」,结束日=生效日+服务期−1 天。
+    pub service_months: Option<i64>,
     pub start_date: Option<&'a str>,
     pub end_date: Option<&'a str>,
     pub agent_name: Option<&'a str>,
@@ -340,8 +345,10 @@ pub struct ContractDraft {
     pub customer_id: String,
     pub contract_no: Option<String>,
     pub external_no: Option<String>,
+    pub contract_type: String,
+    pub sign_date: Option<String>,
     pub total_amount_cents: i64,
-    pub payment_cycle: String,
+    pub service_months: i64,
     pub start_date: String,
     pub end_date: String,
     pub agent_name: String,
@@ -351,6 +358,11 @@ pub struct ContractDraft {
     pub attachment_url: Option<String>,
 }
 
+/// 合同类型值域(与 `contract.contract_type` 的 CHECK 同字)。
+/// 业务语义:`renew`=续签(须有 `renew_from_contract_id`);`expand`=扩容补充协议(只补附加项);
+/// `change`=变更协议(可含逐条替换);`new`=新建(缺省)。
+pub const CONTRACT_TYPES: [&str; 4] = ["new", "renew", "expand", "change"];
+
 /// `YYYY-MM-DD` 轻量形态校验(总则§5.1 按 `Asia/Shanghai` 解释;日历合法性交给库)。
 fn norm_date(raw: &str, field: &str) -> Result<String, BosError> {
     let b = raw.as_bytes();
@@ -403,13 +415,28 @@ pub fn validate_contract_payload(raw: &ContractRaw<'_>) -> Result<ContractDraft,
             return Err(BosError::klt(KltCode::L214, "不允许更换签约客户"));
         }
     }
-    let payment_cycle = match raw.payment_cycle.map(str::trim) {
-        Some(v @ ("yearly" | "quarterly" | "monthly")) => v.to_string(),
+    let contract_type = match raw.contract_type.map(str::trim).filter(|v| !v.is_empty()) {
+        None => "new".to_string(),
+        Some(v) if CONTRACT_TYPES.contains(&v) => v.to_string(),
         Some(other) => {
-            return Err(BosError::bad_params(format!("付款周期非法:{other}")));
+            return Err(BosError::bad_params(format!(
+                "合同类型非法:{other}(只接受 new/renew/expand/change)"
+            )));
+        }
+    };
+    let service_months = match raw.service_months {
+        Some(v) if (1..=600).contains(&v) => v,
+        Some(v) => {
+            return Err(BosError::bad_params(format!(
+                "服务期(月)须为 1~600 的整数,收到 {v}"
+            )));
         }
-        None => return Err(BosError::bad_params("请选择付款周期")),
+        None => return Err(BosError::bad_params("请填写服务期(月)")),
     };
+    let sign_date = raw
+        .sign_date
+        .map(|v| norm_date(v, "签署日期"))
+        .transpose()?;
     let total_amount_cents = require_amount(raw.total_amount_cents, "合同金额")?;
     let start_date = raw
         .start_date
@@ -468,8 +495,10 @@ pub fn validate_contract_payload(raw: &ContractRaw<'_>) -> Result<ContractDraft,
             .map(str::trim)
             .filter(|s| !s.is_empty())
             .map(str::to_string),
+        contract_type,
+        sign_date,
         total_amount_cents,
-        payment_cycle,
+        service_months,
         start_date,
         end_date,
         agent_name,
@@ -1676,7 +1705,9 @@ mod tests {
     fn raw_ok() -> ContractRaw<'static> {
         ContractRaw {
             customer_id: "C01",
-            payment_cycle: Some("yearly"),
+            contract_type: Some("new"),
+            sign_date: Some("2026-11-09"),
+            service_months: Some(12),
             total_amount_cents: Some(3_000_000),
             start_date: Some("2026-11-09"),
             end_date: Some("2027-11-08"),
@@ -1691,13 +1722,37 @@ mod tests {
     fn validate_contract_payload_accepts_full_form() {
         let d = validate_contract_payload(&raw_ok()).unwrap();
         assert_eq!(d.customer_id, "C01");
-        assert_eq!(d.payment_cycle, "yearly");
+        assert_eq!(d.contract_type, "new");
+        assert_eq!(d.sign_date.as_deref(), Some("2026-11-09"));
+        assert_eq!(d.service_months, 12);
         assert_eq!(d.total_amount_cents, 3_000_000);
         assert_eq!(d.contract_no, None, "留空=交由 resolve_contract_no 发号");
         assert_eq!(d.agent_org, None);
         assert_eq!(d.attachment_url, None);
     }
 
+    #[test]
+    fn validate_contract_payload_types_and_service_months() {
+        // 缺省合同类型=新建
+        let d = validate_contract_payload(&ContractRaw { contract_type: None, ..raw_ok() }).unwrap();
+        assert_eq!(d.contract_type, "new");
+        // 四值域逐一接受
+        for kind in CONTRACT_TYPES {
+            let raw = ContractRaw { contract_type: Some(kind), ..raw_ok() };
+            assert_eq!(validate_contract_payload(&raw).unwrap().contract_type, kind);
+        }
+        // 反:类型非法 / 服务期缺失 / 越界 / 非正 / 签署日期非法
+        for raw in [
+            ContractRaw { contract_type: Some("upgrade"), ..raw_ok() },
+            ContractRaw { service_months: None, ..raw_ok() },
+            ContractRaw { service_months: Some(0), ..raw_ok() },
+            ContractRaw { service_months: Some(601), ..raw_ok() },
+            ContractRaw { sign_date: Some("2026/11/09"), ..raw_ok() },
+        ] {
+            assert_eq!(biz(&validate_contract_payload(&raw).unwrap_err()).0, 60004);
+        }
+    }
+
     #[test]
     fn validate_contract_payload_rejects_readonly_field_and_customer_swap() {
         // 反 1:只读键出现在载荷 ⇒ 11103(⛔ 静默忽略)
@@ -1714,7 +1769,7 @@ mod tests {
         for raw in [
             ContractRaw { end_date: Some("2026-11-08"), ..raw_ok() },
             ContractRaw { start_date: Some("2026/11/09"), ..raw_ok() },
-            ContractRaw { payment_cycle: Some("weekly"), ..raw_ok() },
+            ContractRaw { contract_type: Some("weekly"), ..raw_ok() },
             ContractRaw { total_amount_cents: Some(0), ..raw_ok() },
             ContractRaw { attachment_urls: &["https://a", "https://b"], ..raw_ok() },
         ] {

+ 58 - 0
src/migrations/dev/20261119000003_contract_type_sign_service_months.sql

@@ -0,0 +1,58 @@
+-- 2026-11-19 合同主档口径调整:
+--   ① 新增「合同类型」contract_type:new/renew/expand/change(新建/续签/扩容补充协议/变更协议);
+--   ② 新增「签署日期」sign_date(存量行按交接日期回填);
+--   ③ 「付款周期」pay_cycle 改为「服务期(月)」service_months:页面直接录月数,
+--      结束日仍由「生效日 + 服务期月数 - 1 天」推算(原年/季/月三档不再作为合同口径)。
+-- 说明:service_months 允许 NULL 只为兼容无期间的存量行;新建/编辑接口仍把它列为必填。
+
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS contract_type VARCHAR(16) NOT NULL DEFAULT 'new';
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS sign_date DATE NULL;
+ALTER TABLE contract ADD COLUMN IF NOT EXISTS service_months INT NULL;
+
+COMMENT ON COLUMN contract.contract_type IS '合同类型:new(新建)/renew(续签)/expand(扩容补充协议)/change(变更协议)';
+COMMENT ON COLUMN contract.sign_date IS '签署日期;存量行按经办交接日期回填';
+COMMENT ON COLUMN contract.service_months IS '服务期(月);结束日=生效日+服务期−1 天(替代原 pay_cycle)';
+
+-- 服务期回填:先按旧付款周期三档换算,再按既有起止日兜底(加月取整不追求月末精度)。
+UPDATE contract SET service_months = CASE pay_cycle
+    WHEN 'yearly' THEN 12
+    WHEN 'quarterly' THEN 3
+    WHEN 'monthly' THEN 1
+  END
+ WHERE service_months IS NULL
+   AND pay_cycle IN ('yearly', 'quarterly', 'monthly');
+
+UPDATE contract SET service_months = GREATEST(
+    1,
+    (EXTRACT(YEAR FROM age(end_date, start_date)) * 12
+     + EXTRACT(MONTH FROM age(end_date, start_date)))::int + 1
+  )
+ WHERE service_months IS NULL
+   AND start_date IS NOT NULL
+   AND end_date IS NOT NULL
+   AND end_date >= start_date;
+
+-- 签署日期回填:旧口径只有「经办交接日期」,作为签署日期的最近真值。
+UPDATE contract SET sign_date = agent_handover_on WHERE sign_date IS NULL AND agent_handover_on IS NOT NULL;
+
+-- 合同类型回填:挂了续签来源的活动合同=续签;其余保持 new。
+UPDATE contract SET contract_type = 'renew'
+ WHERE renew_from_contract_id IS NOT NULL
+   AND contract_type = 'new';
+
+-- 结束日仍允许显式给出(运营商同步可表达跨多个服务期的合同),
+-- 但服务期本身只接受 1..600 的正整数。
+DO $$
+BEGIN
+  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'contract_service_months_range') THEN
+    ALTER TABLE contract ADD CONSTRAINT contract_service_months_range
+      CHECK (service_months IS NULL OR (service_months >= 1 AND service_months <= 600));
+  END IF;
+  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'contract_type_enum') THEN
+    ALTER TABLE contract ADD CONSTRAINT contract_type_enum
+      CHECK (contract_type IN ('new', 'renew', 'expand', 'change'));
+  END IF;
+END $$;
+
+-- 单一真源:合同期间只认 service_months,旧 pay_cycle 不再读写。
+ALTER TABLE contract DROP COLUMN IF EXISTS pay_cycle;

+ 132 - 39
src/modules/account/src/handlers/contract.rs

@@ -1,7 +1,8 @@
 //! 合同(第 3 册)——读写侧都真落库。
 //!
 //! 2026-11-07 业主裁定「补 dev 骨架列」并落地 `20261107000002_bos_write_gap_columns.sql` 后:
-//! `contract` 的 `external_no`/`pay_cycle`/起止日/经办人四项/`attachment_url`/`updated_at`/
+//! `contract` 的 `external_no`/`contract_type`/`sign_date`/`service_months`/起止日/经办人四项/
+//! `attachment_url`/`updated_at`/
 //! `row_version` 已在册,两张子表 `contract_service_item`/`contract_ip_entry` 已建表
 //! ⇒ 只读侧全部给真值,[`COLUMNS_PENDING`] 清空(响应仍保留 `columns_pending` 键=空数组,
 //! 前端契约形状不变)。设计册 §2.2 的更深层额(`sort_no`/`unit_price_cents`/
@@ -10,7 +11,8 @@
 //!
 //! 写侧落库面=dev 在册列:
 //! * `contract`:`contract_id`/`customer_id`/`contract_no`/`amount_cents`(← 请求
-//!   `contract_amount_cents`)/`external_no`/`pay_cycle`/`start_date`/`end_date`/
+//!   `contract_amount_cents`)/`external_no`/`contract_type`/`sign_date`/`service_months`/
+//!   `start_date`/`end_date`/
 //!   `agent_name`/`agent_mobile`/`agent_handover_on`/`agent_org`/`attachment_url`/
 //!   `row_version`;`status`、`created_at` 走列默认值,`updated_at` 由 UPDATE 写 `NOW()`。
 //! * `contract_service_item`(D-15 后只剩「档位 × 份数」):`item_id`(服务端发号
@@ -106,7 +108,8 @@ const SERVICE_ITEM_BANNED_KEYS: [&str; 10] = [
 const ROW_VERSION_INIT: i64 = 1;
 
 const CONTRACT_COLS: &str = "k.contract_id, k.customer_id, k.contract_no, k.status, \
-                             k.amount_cents, k.created_at, k.external_no, k.pay_cycle, \
+                             k.amount_cents, k.created_at, k.external_no, k.contract_type, \
+                             k.sign_date, k.service_months, \
                              k.start_date, k.end_date, k.agent_name, k.agent_mobile, \
                              k.agent_handover_on, k.agent_org, k.attachment_url, k.row_version, \
                              k.source, k.created_by, \
@@ -127,18 +130,20 @@ const CONTRACT_FROM: &str = "FROM contract k \
      LEFT JOIN ent_team et ON et.team_id = u.subject_id AND u.subject_type = 'ent_team' \
      LEFT JOIN ops_team ot ON ot.team_id = u.subject_id AND u.subject_type = 'ops_team'";
 
-/// 合同主表新增(15 列;`status`/`created_at`/`updated_at` 走默认值)。
+/// 合同主表新增(18 列;`status`/`created_at`/`updated_at` 走默认值)。
 ///
 /// `source` 恒 `'manual'` 且⛔ 取入参(04 册 §4.2「来源由服务端定」+写口拒收
 /// `source`):本语句=合同录入=唯一写入口,`import`/`operator_sync` 要等各自的
 /// 同步写入口落地才可能出现在库里。
 const CONTRACT_INSERT: &str = "INSERT INTO contract (contract_id, customer_id, contract_no, \
-    external_no, amount_cents, pay_cycle, start_date, end_date, agent_name, agent_mobile, \
+    external_no, amount_cents, contract_type, sign_date, service_months, start_date, end_date, \
+    agent_name, agent_mobile, \
     agent_handover_on, agent_org, attachment_url, row_version, source, created_by, \
     renew_from_contract_id) \
-    VALUES ($1::text, $2::text, $3::text, $4::text, $5::bigint, $6::text, $7::date, $8::date, \
-            $9::text, $10::text, $11::date, $12::text, $13::text, $14::int, 'manual', $15::text, \
-            $16::text)";
+    VALUES ($1::text, $2::text, $3::text, $4::text, $5::bigint, $6::text, $7::date, $8::int, \
+            $9::date, $10::date, \
+            $11::text, $12::text, $13::date, $14::text, $15::text, $16::int, 'manual', $17::text, \
+            $18::text)";
 
 /// 条目删除(三向对比里「库有载荷无」的一支;删前先过订阅引用=`KLT-L213`)。
 const ITEM_DELETE: &str =
@@ -152,10 +157,11 @@ const IP_DELETE_ALL: &str = "DELETE FROM contract_ip_entry WHERE contract_id = $
 /// 为什么全列写回:判据跑在**合并后的整份载荷**上(请求 ?? 库里现值),落库⛔ 只写请求
 /// 带来的那几个字段——否则「判据校验过的值」与「写进库的值」就是两套账。
 const CONTRACT_UPDATE_ALL: &str = "UPDATE contract SET external_no = $2::text, \
-    amount_cents = $3::bigint, pay_cycle = $4::text, start_date = $5::date, end_date = $6::date, \
-    agent_name = $7::text, agent_mobile = $8::text, agent_handover_on = $9::date, \
-    agent_org = $10::text, attachment_url = $11::text, row_version = row_version + 1, \
-    updated_at = NOW() WHERE contract_id = $1::text AND row_version = $12::int";
+    amount_cents = $3::bigint, contract_type = $4::text, sign_date = $5::date, \
+    service_months = $6::int, start_date = $7::date, end_date = $8::date, \
+    agent_name = $9::text, agent_mobile = $10::text, agent_handover_on = $11::date, \
+    agent_org = $12::text, attachment_url = $13::text, row_version = row_version + 1, \
+    updated_at = NOW() WHERE contract_id = $1::text AND row_version = $14::int";
 
 /// 条目新增的**全列**形态(D-15:六列=主键、合同、档位、份数、形态、出口;
 /// P1 加三列=条目形态、父条目、增量引用订阅)。
@@ -299,8 +305,13 @@ pub struct ContractCreateReq {
     /// 合同编号(空则服务端发号 `{customer_id}-C{序号}`)。
     pub contract_no: Option<String>,
     pub external_no: Option<String>,
+    /// 合同类型:`new`/`renew`/`expand`/`change`(缺省=`new`)。
+    pub contract_type: Option<String>,
+    /// 签署日期(YYYY-MM-DD,选填;缺省按经办交接日期兜底)。
+    pub sign_date: Option<String>,
     pub contract_amount_cents: Option<Value>,
-    pub pay_cycle: Option<String>,
+    /// 服务期(月):替代原 `pay_cycle`,结束日=生效日+服务期−1 天。
+    pub service_months: Option<Value>,
     pub start_date: Option<String>,
     pub end_date: Option<String>,
     pub agent_name: Option<String>,
@@ -327,8 +338,13 @@ pub struct ContractUpdateReq {
     pub customer_id: Option<String>,
     pub contract_no: Option<String>,
     pub external_no: Option<String>,
+    /// 合同类型:`new`/`renew`/`expand`/`change`。
+    pub contract_type: Option<String>,
+    /// 签署日期(YYYY-MM-DD)。
+    pub sign_date: Option<String>,
     pub contract_amount_cents: Option<Value>,
-    pub pay_cycle: Option<String>,
+    /// 服务期(月):替代原 `pay_cycle`。
+    pub service_months: Option<Value>,
     pub start_date: Option<String>,
     pub end_date: Option<String>,
     pub agent_name: Option<String>,
@@ -359,7 +375,11 @@ struct ContractRow {
     #[serde(deserialize_with = "de::as_opt_string")]
     external_no: Option<String>,
     #[serde(deserialize_with = "de::as_opt_string")]
-    pay_cycle: Option<String>,
+    contract_type: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    sign_date: Option<String>,
+    #[serde(deserialize_with = "de::as_opt_string")]
+    service_months: Option<String>,
     #[serde(deserialize_with = "de::as_opt_string")]
     start_date: Option<String>,
     #[serde(deserialize_with = "de::as_opt_string")]
@@ -508,7 +528,9 @@ fn base_json(r: &ContractRow, customer_name: Option<&str>) -> Value {
         "amount_cents": as_num(&r.amount_cents),
         "contract_amount_cents": as_num(&r.amount_cents),
         "external_no": r.external_no,
-        "pay_cycle": r.pay_cycle,
+        "contract_type": blank(&r.contract_type).unwrap_or("new"),
+        "sign_date": r.sign_date,
+        "service_months": as_opt_num(r.service_months.as_deref()),
         "start_date": r.start_date,
         "end_date": r.end_date,
         "agent_name": r.agent_name,
@@ -1561,8 +1583,10 @@ struct ContractAuditView<'a> {
     customer_id: &'a str,
     contract_no: &'a str,
     external_no: Option<&'a str>,
+    contract_type: Option<&'a str>,
+    sign_date: Option<&'a str>,
     amount_cents: Option<i64>,
-    pay_cycle: Option<&'a str>,
+    service_months: Option<i64>,
     start_date: Option<&'a str>,
     end_date: Option<&'a str>,
     agent_name: Option<&'a str>,
@@ -1581,8 +1605,10 @@ impl ContractAuditView<'_> {
             "customer_id": self.customer_id,
             "contract_no": self.contract_no,
             "external_no": self.external_no,
+            "contract_type": self.contract_type,
+            "sign_date": self.sign_date,
             "contract_amount_cents": self.amount_cents,
-            "pay_cycle": self.pay_cycle,
+            "service_months": self.service_months,
             "start_date": self.start_date,
             "end_date": self.end_date,
             "agent_name": self.agent_name,
@@ -1602,8 +1628,10 @@ fn draft_audit_view<'a>(contract_id: &'a str, contract_no: &'a str, source: &'a
         customer_id: &d.customer_id,
         contract_no,
         external_no: d.external_no.as_deref(),
+        contract_type: Some(d.contract_type.as_str()),
+        sign_date: d.sign_date.as_deref(),
         amount_cents: Some(d.total_amount_cents),
-        pay_cycle: Some(d.payment_cycle.as_str()),
+        service_months: Some(d.service_months),
         start_date: Some(d.start_date.as_str()),
         end_date: Some(d.end_date.as_str()),
         agent_name: Some(d.agent_name.as_str()),
@@ -1622,8 +1650,10 @@ fn row_audit_view(r: &ContractRow) -> ContractAuditView<'_> {
         customer_id: &r.customer_id,
         contract_no: &r.contract_no,
         external_no: r.external_no.as_deref(),
+        contract_type: r.contract_type.as_deref(),
+        sign_date: r.sign_date.as_deref(),
         amount_cents: r.amount_cents.parse::<i64>().ok(),
-        pay_cycle: r.pay_cycle.as_deref(),
+        service_months: r.service_months.as_deref().and_then(|v| v.parse::<i64>().ok()),
         start_date: r.start_date.as_deref(),
         end_date: r.end_date.as_deref(),
         agent_name: r.agent_name.as_deref(),
@@ -1879,6 +1909,44 @@ fn inline_failure_note(e: BosError, customer_id: &str, info: &Value) -> BosError
     }
 }
 
+/// 合同类型归一与语义校验(2026-11-19)。
+///
+/// * 缺省=`new`;兼容旧客户端:只带 `renew_from_contract_id` 不带类型 ⇒ 视为续签,
+///   服务构成整批为增量条目 ⇒ 视为扩容补充协议(显式给了别的类型则按下面的规则报错)。
+/// * `renew` **必须**有续签来源(否则类型在撒谎);
+/// * `expand` **必须**全部条目都是增量附加项(扩容补充协议不新开链路)。
+fn resolve_contract_type(
+    declared: Option<&str>,
+    renew_from: Option<&str>,
+    items: &[ItemIns],
+) -> Result<String, BosError> {
+    let kind = declared.map(str::trim).filter(|v| !v.is_empty()).unwrap_or("new");
+    if !bos_invariant::CONTRACT_TYPES.contains(&kind) {
+        return Err(BosError::bad_params(format!(
+            "合同类型非法:{kind}(只接受 new/renew/expand/change)"
+        )));
+    }
+    let has_increment = items.iter().any(|it| it.item_mode == ItemMode::Increment);
+    let all_increment = !items.is_empty() && items.iter().all(|it| it.item_mode == ItemMode::Increment);
+    match kind {
+        "new" if renew_from.is_some() => Ok("renew".to_string()),
+        "new" if has_increment && all_increment => Ok("expand".to_string()),
+        "new" if has_increment => Err(BosError::bad_params(
+            "服务构成混有增量条目与自建链路:扩容补充协议须整批为增量附加项,新建合同须整批自建链路",
+        )),
+        "renew" if renew_from.is_none() => Err(BosError::bad_params(
+            "合同类型为续签,但没有给出 renew_from_contract_id(续签须指定续签自哪份旧合同)",
+        )),
+        "expand" | "change" if renew_from.is_some() => Err(BosError::bad_params(
+            "续签合同(带 renew_from_contract_id)的合同类型只能是 renew",
+        )),
+        "expand" if !all_increment => Err(BosError::bad_params(
+            "合同类型为扩容补充协议,但服务构成不是整批增量附加项(扩容不新开跨境链路)",
+        )),
+        other => Ok(other.to_string()),
+    }
+}
+
 async fn do_create_for_customer(
     state: &AppState,
     auth: &AuthContext,
@@ -1902,26 +1970,31 @@ async fn do_create_for_customer(
     //    合同侧不再有独立的 IP 三元组表,`KLT-L217` 随之退役。
     let (mut items, item_dropped) = resolve_items(db, customer_id, raw_items).await?;
 
-    // ③ 主档字段:金额 >0、账期枚举、起 < 止、经办人三件套、附件 ≤1 ⇒ 11103 口径。
+    // ③ 主档字段:金额 >0、类型/服务期合法、起 < 止、经办人三件套、附件 ≤1 ⇒ 11103 口径。
     //    判据=`bos-invariant::validate_contract_payload`(与第 1 册录入表单同一份真源)。
-    //    结束日可省略(2026-11-17 定案):页面已把它锁成只读推算值,接口侧按同一式兜底——
-    //    生效日+付款周期月数−1 天;显式给了就按显式值(运营商同步可表达跨多个付款周期的合同)。
+    //    结束日可省略(2026-11-19 定案):页面已把它锁成只读推算值,接口侧按同一式兜底——
+    //    生效日+服务期(月)−1 天;显式给了就按显式值(运营商同步可表达跨多个服务期的合同)。
+    let service_months = want_int(b.service_months.as_ref(), "service_months")?;
     let end_date = match trimmed(&b.end_date) {
         Some(v) => Some(v.to_string()),
-        None => super::succession::contract_end_from_cycle(
+        None => super::succession::contract_end_from_months(
             trimmed(&b.start_date).unwrap_or_default(),
-            trimmed(&b.pay_cycle).unwrap_or_default(),
+            service_months.unwrap_or_default(),
         ),
     };
+    // 签署日期选填:缺省按经办交接日期兜底(旧口径只有交接日期)。
+    let sign_date = trimmed(&b.sign_date).or_else(|| trimmed(&b.agent_handover_on));
     let attachment: Vec<&str> = trimmed(&b.attachment_url).into_iter().collect();
-    let draft = validate_contract_payload(&ContractRaw {
+    let mut draft = validate_contract_payload(&ContractRaw {
         customer_id,
         original_customer_id: None,
         readonly_keys: &ro_refs,
         contract_no: trimmed(&b.contract_no),
         external_no: trimmed(&b.external_no),
+        contract_type: trimmed(&b.contract_type),
+        sign_date,
         total_amount_cents: want_int(b.contract_amount_cents.as_ref(), "contract_amount_cents")?,
-        payment_cycle: trimmed(&b.pay_cycle),
+        service_months,
         start_date: trimmed(&b.start_date),
         end_date: end_date.as_deref(),
         agent_name: trimmed(&b.agent_name),
@@ -1984,6 +2057,12 @@ async fn do_create_for_customer(
             ));
         }
     }
+    // 合同类型归一(2026-11-19):续签来源/增量条目的语义在这里收口,⛔ 让类型与内容两张皮。
+    draft.contract_type = resolve_contract_type(
+        Some(draft.contract_type.as_str()),
+        renew_from.as_deref(),
+        &items,
+    )?;
     let planned = plan_contract_subs(
         state,
         customer_id,
@@ -2031,7 +2110,9 @@ async fn do_create_for_customer(
             Value::String(no.contract_no.clone()),
             text_param(draft.external_no.as_deref()),
             Value::from(draft.total_amount_cents),
-            Value::String(draft.payment_cycle.to_string()),
+            Value::String(draft.contract_type.clone()),
+            text_param(draft.sign_date.as_deref()),
+            Value::from(draft.service_months),
             Value::String(draft.start_date.clone()),
             Value::String(draft.end_date.clone()),
             Value::String(draft.agent_name.clone()),
@@ -2912,7 +2993,8 @@ async fn do_update(
         &b.external_no,
         &b.contract_no,
         &b.customer_id,
-        &b.pay_cycle,
+        &b.contract_type,
+        &b.sign_date,
         &b.start_date,
         &b.end_date,
         &b.agent_name,
@@ -2923,20 +3005,24 @@ async fn do_update(
     ]
     .iter()
     .any(|v| v.is_some())
-        || b.contract_amount_cents.is_some();
+        || b.contract_amount_cents.is_some()
+        || b.service_months.is_some();
 
-    // 结束日锁定为推算值(2026-11-17 定案):生效日/付款周期**确实被改**而没显式给结束日 ⇒ 按同一式重算,
+    // 结束日锁定为推算值(2026-11-19 定案):生效日/服务期**确实被改**而没显式给结束日 ⇒ 按同一式重算,
     // ⛔ 留一个与期间对不上的旧止期;两项都没变(整份回传)⇒ 沿用库里现值,免得顺手改掉存量多周期合同。
     let eff_start = eff(&b.start_date, &cur.start_date);
-    let eff_cycle = eff(&b.pay_cycle, &cur.pay_cycle);
+    let eff_months = match b.service_months.as_ref() {
+        Some(_) => want_int(b.service_months.as_ref(), "service_months")?,
+        None => cur.service_months.as_ref().and_then(|v| parse_i64(Some(v))),
+    };
     let period_changed = !same_text(eff_start, cur.start_date.as_deref())
-        || !same_text(eff_cycle, cur.pay_cycle.as_deref());
+        || eff_months != cur.service_months.as_ref().and_then(|v| parse_i64(Some(v)));
     let end_date: Option<String> = if b.end_date.is_some() {
         eff(&b.end_date, &cur.end_date).map(str::to_string)
     } else if period_changed {
-        super::succession::contract_end_from_cycle(
+        super::succession::contract_end_from_months(
             eff_start.unwrap_or_default(),
-            eff_cycle.unwrap_or_default(),
+            eff_months.unwrap_or_default(),
         )
     } else {
         eff(&b.end_date, &cur.end_date).map(str::to_string)
@@ -2948,8 +3034,10 @@ async fn do_update(
         readonly_keys: &ro_refs,
         contract_no: Some(&cur.contract_no),
         external_no: eff(&b.external_no, &cur.external_no),
+        contract_type: eff(&b.contract_type, &cur.contract_type),
+        sign_date: eff(&b.sign_date, &cur.sign_date),
         total_amount_cents: amount,
-        payment_cycle: eff_cycle,
+        service_months: eff_months,
         start_date: eff_start,
         end_date: end_date.as_deref(),
         agent_name: eff(&b.agent_name, &cur.agent_name),
@@ -2971,13 +3059,16 @@ async fn do_update(
     // 「是否改了」按**合并后的生效值 vs 库里现值**判,⛔ 按"请求里有没有这个键"判——
     // 页面保存是整份回传,按键判会把没动过的字段全算成改动、给冻结合同报假错。
     let billing_touched = amount != parse_i64(Some(&cur.amount_cents))
-        || !same_text(Some(draft.payment_cycle.as_str()), cur.pay_cycle.as_deref())
+        || eff_months != cur.service_months.as_ref().and_then(|v| parse_i64(Some(v)))
         || !same_text(Some(draft.start_date.as_str()), cur.start_date.as_deref())
         || !same_text(Some(draft.end_date.as_str()), cur.end_date.as_deref())
         // 服务构成是**整段替换** ⇒ 没有可靠的「原样回传」判别,按段是否出现判。
         // 前端保存已改为**只在草稿真改动时才带该段**。
         || b.service_items.is_some();
     let archive_touched = !same_text(draft.external_no.as_deref(), cur.external_no.as_deref())
+        // 合同类型/签署日期=商务档案(与外部单号、交接日期同一轴)。
+        || !same_text(Some(draft.contract_type.as_str()), cur.contract_type.as_deref())
+        || !same_text(draft.sign_date.as_deref(), cur.sign_date.as_deref())
         || !same_text(Some(draft.agent_handover_on.as_str()), cur.agent_handover_on.as_deref())
         // 运营商经办人三件套(姓名/电话/机构)在交接单口径里=商务档案,与「交接日期」同一条轴。
         // 「经办人=录入账号」是另一列(`contract.created_by`),恒只读、⛔ 与本组混用。
@@ -3000,7 +3091,7 @@ async fn do_update(
         let frozen_axis = if !scope.billing.editable && billing_touched {
             Some(("计费口径", &scope.billing))
         } else if !scope.archive.editable && archive_touched {
-            Some(("档案字段(外部单号/交接日期/运营商经办人)", &scope.archive))
+            Some(("档案字段(合同类型/签署日期/外部单号/交接日期/运营商经办人)", &scope.archive))
         } else {
             None
         };
@@ -3058,7 +3149,9 @@ async fn do_update(
             Value::String(contract_id.to_string()),
             text_param(draft.external_no.as_deref()),
             Value::from(draft.total_amount_cents),
-            Value::String(draft.payment_cycle.to_string()),
+            Value::String(draft.contract_type.clone()),
+            text_param(draft.sign_date.as_deref()),
+            Value::from(draft.service_months),
             Value::String(draft.start_date.clone()),
             Value::String(draft.end_date.clone()),
             Value::String(draft.agent_name.clone()),

+ 25 - 20
src/modules/account/src/handlers/succession.rs

@@ -48,17 +48,18 @@ use super::subscription::{
 
 // ═══════════════════════════ 期间派生 ═══════════════════════════
 
-/// 合同结束日=**生效日 + 付款周期月数 − 1 天**(2026-11-17 定案,页面锁定为推算值)。
+/// 合同结束日=**生效日 + 服务期(月) − 1 天**(2026-11-19 起合同只录服务期月数)。
 ///
 /// 与 [`add_months_clamped`] 同一式:加月后该月无对应日**先取月末**再减一天
-/// (1-31 起、月付 ⇒ 2-28 → 2-27)。`pay_cycle` 与订阅 `term` 同枚举(年/季/月),
-/// 但⚠️ 付款周期在**出账**里仍只记录、不折算(04 册 §4.2),这里只用于推合同期间。
+/// (1-31 起、1 个月 ⇒ 2-28 → 2-27)。
 ///
 /// 入参任一项缺失/非法 ⇒ `None`(调用方退回既有的必填校验,⛔ 造一个默认期间)。
-pub(crate) fn contract_end_from_cycle(start: &str, pay_cycle: &str) -> Option<String> {
+pub(crate) fn contract_end_from_months(start: &str, months: i64) -> Option<String> {
     let start = parse_date("生效日", start).ok()?;
-    let months = term_months(pay_cycle).ok()?;
-    Some(date_text(add_months_clamped(start, months) - chrono::Duration::days(1)))
+    if !(1..=600).contains(&months) {
+        return None;
+    }
+    Some(date_text(add_months_clamped(start, months as u32) - chrono::Duration::days(1)))
 }
 
 /// 结束日口径:两条入口的唯一差异点。
@@ -218,21 +219,25 @@ mod tests {
     }
 
     #[test]
-    fn 合同结束日按生效日与付款周期推算() {
-        // 年付:整一年 −1 天
-        assert_eq!(contract_end_from_cycle("2026-11-17", "yearly").as_deref(), Some("2027-11-16"));
-        // 季付/月付
-        assert_eq!(contract_end_from_cycle("2026-11-17", "quarterly").as_deref(), Some("2027-02-16"));
-        assert_eq!(contract_end_from_cycle("2026-11-17", "monthly").as_deref(), Some("2026-12-16"));
-        // 该月无对应日先取月末再减一天(1-31 起、月付 ⇒ 2-28 → 2-27)
-        assert_eq!(contract_end_from_cycle("2026-01-31", "monthly").as_deref(), Some("2026-02-27"));
-        // 闰年 2-29 起、年付 ⇒ 次年 2-28 → 2-27
-        assert_eq!(contract_end_from_cycle("2028-02-29", "yearly").as_deref(), Some("2029-02-27"));
+    fn 合同结束日按生效日与服务期月数推算() {
+        // 12 个月:整一年 −1 天
+        assert_eq!(contract_end_from_months("2026-11-17", 12).as_deref(), Some("2027-11-16"));
+        // 3 个月/1 个月
+        assert_eq!(contract_end_from_months("2026-11-17", 3).as_deref(), Some("2027-02-16"));
+        assert_eq!(contract_end_from_months("2026-11-17", 1).as_deref(), Some("2026-12-16"));
+        // 该月无对应日先取月末再减一天(1-31 起、1 个月 ⇒ 2-28 → 2-27)
+        assert_eq!(contract_end_from_months("2026-01-31", 1).as_deref(), Some("2026-02-27"));
+        // 闰年 2-29 起、12 个月 ⇒ 次年 2-28 → 2-27
+        assert_eq!(contract_end_from_months("2028-02-29", 12).as_deref(), Some("2029-02-27"));
         // 跨年(12 月加 3 个月)
-        assert_eq!(contract_end_from_cycle("2026-12-01", "quarterly").as_deref(), Some("2027-02-28"));
-        // 付款周期非法/生效日缺失 ⇒ 不造期间
-        assert_eq!(contract_end_from_cycle("2026-11-17", "weekly"), None);
-        assert_eq!(contract_end_from_cycle("", "yearly"), None);
+        assert_eq!(contract_end_from_months("2026-12-01", 3).as_deref(), Some("2027-02-28"));
+        // 36/60 个月(3 年/5 年快捷档)
+        assert_eq!(contract_end_from_months("2026-11-17", 36).as_deref(), Some("2029-11-16"));
+        assert_eq!(contract_end_from_months("2026-11-17", 60).as_deref(), Some("2031-11-16"));
+        // 服务期非法/生效日缺失 ⇒ 不造期间
+        assert_eq!(contract_end_from_months("2026-11-17", 0), None);
+        assert_eq!(contract_end_from_months("2026-11-17", 601), None);
+        assert_eq!(contract_end_from_months("", 12), None);
     }
 
     #[test]

+ 43 - 15
src/openapi.yaml

@@ -3951,16 +3951,31 @@ paths:
                     external_no:
                       type: string
                       description: 外部合同号(可选)
+                    contract_type:
+                      type: string
+                      description: >-
+                        合同类型:new(新建,缺省)/renew(续签)/expand(扩容补充协议)/change(变更协议)。
+                        语义收口:renew 必须同时给 renew_from_contract_id;expand 的服务构成必须整批为增量附加项;
+                        带 renew_from_contract_id 的合同类型只能是 renew。
+                      enum:
+                      - new
+                      - renew
+                      - expand
+                      - change
+                    sign_date:
+                      type: string
+                      description: 签署日期(YYYY-MM-DD;选填,缺省按 agent_handover_on 兜底)
+                      format: date
                     contract_amount_cents:
                       type: integer
                       description: 合同金额(分,可选)
-                    pay_cycle:
-                      type: string
-                      description: 付款周期:yearly/quarterly/monthly
-                      enum:
-                      - yearly
-                      - quarterly
-                      - monthly
+                    service_months:
+                      type: integer
+                      description: >-
+                        服务期(月,1~600,必填):替代原 pay_cycle;结束日=生效日+服务期−1 天
+                        (该月无对应日先取月末),页面锁定为只读推算值。
+                      minimum: 1
+                      maximum: 600
                     start_date:
                       type: string
                       description: 合同开始日期(YYYY-MM-DD)
@@ -3968,9 +3983,8 @@ paths:
                     end_date:
                       type: string
                       description: >-
-                        合同结束日期(YYYY-MM-DD)。**可省略**(2026-11-17 定案):省略时服务端按
-                        「生效日+付款周期」推算=年付 12/季付 3/月付 1 个月再减一天,该月无对应日先取月末
-                        (录入页面已把它锁成只读推算值)。显式给出则按显式值落库(运营商同步可表达跨多个付款周期的合同)。
+                        合同结束日期(YYYY-MM-DD,可省略):省略时服务端按「生效日+服务期(月)−1 天」
+                        推算(该月无对应日先取月末);显式给出则按显式值落库。
                       format: date
                     agent_name:
                       type: string
@@ -4063,7 +4077,7 @@ paths:
                         与 service_items[].succession **互斥**(同时出现即 KLT-L222)。
                         应答仍走 data.replacements[],其中 mode=renewed、replaces_subscription_id=null。
                   required:
-                  - pay_cycle
+                  - service_months
                   - start_date
               required:
               - data
@@ -4073,7 +4087,7 @@ paths:
   /contract/update@v1:
     post:
       summary: 编辑合同
-      description: 编号与签约客户不可改;条目按 item_id 三向对比增删改。可改范围=bos-invariant::contract_edit_scope 的两条轴(billing:金额/付款周期/期间/服务构成;archive:外部单号/交接日期),两轴独立判定、source=operator_sync 全只读(KLT-L220)、已开通两轴全冻(KLT-L219)、录后 72 小时内两轴全开、未生效只放 billing、未到期只放 archive;经办人(created_by 与录入经办人机构/姓名/联系方式)建后恒只读(KLT-L221);agent_* 为运营商交接单上的经办人,受各自轴约束。⚠️ 2026-11-17:service_items[].succession 与 renew_from_contract_id 都只在新建合同时受理,编辑载荷出现任一 ⇒ KLT-L222(替换/续签是一次性动作,改合同不得反向动订阅);⛔ 静默忽略。保存形态=只提交变了的字段(键缺席=保持现值);审计 INSERT 与业务语句同批提交。⚠️ 2026-11-17:结束日锁定为「生效日+付款周期」推算值 ⇒ 生效日/付款周期确实被改而载荷未给出 `end_date` 时,服务端按同一式重算(⛔ 留一个与期间对不上的旧止期);三项都没动则沿用库里现值。
+      description: 编号与签约客户不可改;条目按 item_id 三向对比增删改。可改范围=bos-invariant::contract_edit_scope 的两条轴(billing:金额/服务期(月)/期间/服务构成;archive:合同类型/签署日期/外部单号/交接日期),两轴独立判定、source=operator_sync 全只读(KLT-L220)、已开通两轴全冻(KLT-L219)、录后 72 小时内两轴全开、未生效只放 billing、未到期只放 archive;经办人(created_by 与录入经办人机构/姓名/联系方式)建后恒只读(KLT-L221);agent_* 为运营商交接单上的经办人,受各自轴约束。⚠️ 2026-11-17:service_items[].succession 与 renew_from_contract_id 都只在新建合同时受理,编辑载荷出现任一 ⇒ KLT-L222(替换/续签是一次性动作,改合同不得反向动订阅);⛔ 静默忽略。保存形态=只提交变了的字段(键缺席=保持现值);审计 INSERT 与业务语句同批提交。⚠️ 2026-11-19:结束日锁定为「生效日+服务期(月)」推算值 ⇒ 生效日/服务期确实被改而载荷未给出 `end_date` 时,服务端按同一式重算(⛔ 留一个与期间对不上的旧止期);三项都没动则沿用库里现值。
       operationId: contract_update
       tags:
       - 合同
@@ -4104,12 +4118,26 @@ paths:
                     external_no:
                       type: string
                       description: 外部合同号
+                    contract_type:
+                      type: string
+                      description: 合同类型(new/renew/expand/change);受 archive 轴约束
+                      enum:
+                      - new
+                      - renew
+                      - expand
+                      - change
+                    sign_date:
+                      type: string
+                      description: 签署日期(受 archive 轴约束)
+                      format: date
                     contract_amount_cents:
                       type: integer
                       description: 合同金额(分)
-                    pay_cycle:
-                      type: string
-                      description: 付款周期
+                    service_months:
+                      type: integer
+                      description: 服务期(月,1~600);受 billing 轴约束,结束日按「生效日+服务期−1 天」重算
+                      minimum: 1
+                      maximum: 600
                     start_date:
                       type: string
                       description: 开始日期

+ 1 - 1
web-scaffold/src/app/App.tsx

@@ -212,7 +212,7 @@ function Workspace() {
         <Route path="/customers/:no/orders" element={<AppShell pageTitle="套餐订阅管理"><CustomerOrdersPage /></AppShell>} />
         <Route path="/customers/:no" element={<AppShell pageTitle="客户档案"><CustomerWorkspacePage /></AppShell>} />
         <Route path="/contracts" element={<AppShell pageTitle="合同管理"><ContractManagementPage /></AppShell>} />
-        <Route path="/contracts/new" element={readOnlyViewer ? <Navigate to="/contracts" replace /> : <AppShell pageTitle="新增合同"><ContractEditorPage /></AppShell>} />
+        <Route path="/contracts/new" element={readOnlyViewer ? <Navigate to="/contracts" replace /> : <AppShell pageTitle="合同签订表单"><ContractEditorPage /></AppShell>} />
         {/* @deprecated 详情与编辑已二合一:旧的 /edit 深链落到同一个详情页,编辑在详情内联完成。 */}
         <Route path="/contracts/:no/edit" element={<AppShell pageTitle="合同详情"><ContractRecordPage /></AppShell>} />
         <Route path="/contracts/:no" element={<AppShell pageTitle="合同详情"><ContractRecordPage /></AppShell>} />

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

@@ -1,6 +1,6 @@
 // @vitest-environment jsdom
 import { describe, expect, it } from "vitest";
-import { buildContractWrite, businessToday, changedWriteFields, contractEndFromCycle, emptyDraft, emptyItem, frozenChanges, renewalPrefill, renewalStartOf, resolveReplacementSelection } from "../contract-draft";
+import { buildContractWrite, businessToday, changedWriteFields, contractEndFromMonths, emptyDraft, emptyItem, frozenChanges, renewalPrefill, renewalStartOf, resolveReplacementSelection } from "../contract-draft";
 import type { ContractEditScope, ReplacementCandidate } from "../../lib/api/types";
 
 /** 基线:一份可正常保存的未开通合同草稿。 */
@@ -9,12 +9,14 @@ const baseline = () => {
   return {
     ...draft,
     amount: "10800.00",
-    payCycle: "yearly",
+    contractType: "new",
+    serviceMonths: "12",
     start: "2026-01-01",
     end: "2026-12-31",
     agent: "张三",
     agentPhone: "13800000000",
-    handoverOn: "2026-01-05",
+    /** 交接日期=签署日期(2026-11-19):草稿只留 signDate,写口按 agent_handover_on 同值落库。 */
+    signDate: "2026-01-05",
     items: [{ ...emptyItem(), planId: "CP-000001", planName: "标准套餐", quantity: 1, exits: ["香港"] }],
   };
 };
@@ -50,10 +52,10 @@ describe("frozenChanges · 编辑口径守卫(两轴独立判定)", () => {
     expect(frozenChanges({ ...base, agent: "张三" }, base, allLocked)).toEqual([]);
   });
 
-  it("金额/付款周期/期间各自命中,且一次列出全部越界项", () => {
+  it("金额/服务期/期间各自命中,且一次列出全部越界项", () => {
     const base = baseline();
     expect(frozenChanges({ ...base, amount: "12000.00" }, base, allLocked)).toEqual(["合同金额"]);
-    expect(frozenChanges({ ...base, payCycle: "monthly" }, base, allLocked)).toEqual(["付款周期"]);
+    expect(frozenChanges({ ...base, serviceMonths: "3" }, base, allLocked)).toEqual(["服务期(月)"]);
     expect(frozenChanges({ ...base, start: "2026-02-01" }, base, allLocked)).toEqual(["合同生效日"]);
     expect(frozenChanges({ ...base, end: "2027-12-31" }, base, allLocked)).toEqual(["合同结束日"]);
     expect(frozenChanges({ ...base, amount: "1", start: "2026-02-01", end: "2027-01-01" }, base, allLocked)).toEqual([
@@ -70,11 +72,12 @@ describe("frozenChanges · 编辑口径守卫(两轴独立判定)", () => {
     // 2026-11-17:IP 条目不属草稿(配置已下线)⇒ 只按服务构成判计费轴。
   });
 
-  it("档案轴:已冻结时外部单号/交接日期/运营商经办人被拦", () => {
+  it("档案轴:已冻结时外部单号/签署日期/运营商经办人被拦", () => {
     const base = baseline();
     expect(frozenChanges({ ...base, externalNo: "WB-NEW" }, base, allLocked)).toEqual(["外部单号"]);
-    expect(frozenChanges({ ...base, handoverOn: "2026-02-02" }, base, allLocked)).toEqual(["交接日期"]);
-    // 运营商经办人三件套=交接单上的商务档案,与交接日期同轴;⛔ 与「录入账号」混用。
+    expect(frozenChanges({ ...base, contractType: "renew" }, base, allLocked)).toEqual(["合同类型"]);
+    expect(frozenChanges({ ...base, signDate: "2026-02-02" }, base, allLocked)).toEqual(["签署日期"]);
+    // 运营商经办人三件套=交接单上的商务档案,与签署日期同轴;⛔ 与「录入账号」混用。
     expect(frozenChanges({ ...base, agent: "李四" }, base, allLocked)).toEqual(["运营商经办人姓名"]);
     expect(frozenChanges({ ...base, agentPhone: "13900000000" }, base, allLocked)).toEqual(["运营商经办人电话"]);
     expect(frozenChanges({ ...base, agentOrg: "华东运营中心" }, base, allLocked)).toEqual(["运营商经办人机构"]);
@@ -144,23 +147,29 @@ describe("resolveReplacementSelection · 候选选择矩阵(2026-11-17)", ()
   });
 });
 
-describe("contractEndFromCycle · 合同结束日推算(2026-11-17)", () => {
-  it("结束日=生效日+付款周期月数−1 天", () => {
-    expect(contractEndFromCycle("2026-11-17", "yearly")).toBe("2027-11-16");
-    expect(contractEndFromCycle("2026-11-17", "quarterly")).toBe("2027-02-16");
-    expect(contractEndFromCycle("2026-11-17", "monthly")).toBe("2026-12-16");
+describe("contractEndFromMonths · 合同结束日推算(2026-11-19:生效日+服务期月数−1 天)", () => {
+  it("结束日=生效日+服务期(月)−1 天", () => {
+    expect(contractEndFromMonths("2026-11-17", 12)).toBe("2027-11-16");
+    expect(contractEndFromMonths("2026-11-17", "12")).toBe("2027-11-16");
+    expect(contractEndFromMonths("2026-11-17", 3)).toBe("2027-02-16");
+    expect(contractEndFromMonths("2026-11-17", 1)).toBe("2026-12-16");
+    expect(contractEndFromMonths("2026-11-17", 36)).toBe("2029-11-16");
+    expect(contractEndFromMonths("2026-11-17", 60)).toBe("2031-11-16");
   });
 
   it("该月无对应日先取月末再减一天(与后端 add_months_clamped 同式)", () => {
-    expect(contractEndFromCycle("2026-01-31", "monthly")).toBe("2026-02-27");
-    expect(contractEndFromCycle("2028-02-29", "yearly")).toBe("2029-02-27");
-    expect(contractEndFromCycle("2026-12-01", "quarterly")).toBe("2027-02-28");
+    expect(contractEndFromMonths("2026-01-31", 1)).toBe("2026-02-27");
+    expect(contractEndFromMonths("2028-02-29", 12)).toBe("2029-02-27");
+    expect(contractEndFromMonths("2026-12-01", 3)).toBe("2027-02-28");
   });
 
-  it("付款周期非法或生效日缺失 ⇒ 空串(⛔ 留陈旧值)", () => {
-    expect(contractEndFromCycle("2026-11-17", "weekly")).toBe("");
-    expect(contractEndFromCycle("", "yearly")).toBe("");
-    expect(contractEndFromCycle("2026/11/17", "yearly")).toBe("");
+  it("服务期非法(0/601/小数/空)或生效日缺失 ⇒ 空串(⛔ 留陈旧值)", () => {
+    expect(contractEndFromMonths("2026-11-17", 0)).toBe("");
+    expect(contractEndFromMonths("2026-11-17", 601)).toBe("");
+    expect(contractEndFromMonths("2026-11-17", 1.5)).toBe("");
+    expect(contractEndFromMonths("2026-11-17", "")).toBe("");
+    expect(contractEndFromMonths("", 12)).toBe("");
+    expect(contractEndFromMonths("2026/11/17", 12)).toBe("");
   });
 });
 
@@ -179,7 +188,9 @@ describe("renewalPrefill · 续签带入(2026-11-17)", () => {
     external_no: "EXT-9",
     status: "effective",
     contract_amount_cents: 1_080_000,
-    pay_cycle: "yearly",
+    contract_type: "renew",
+    sign_date: "2024-12-28",
+    service_months: 12,
     start_date: "2025-01-01",
     end_date: "2025-12-31",
     agent_name: "李四",
@@ -195,12 +206,13 @@ describe("renewalPrefill · 续签带入(2026-11-17)", () => {
     ],
   };
 
-  it("带出金额/账期/条目/经办人;条目主键清空(新建态由服务端发号)", () => {
+  it("带出金额/服务期/条目/经办人;合同类型置为续签;条目主键清空(新建态由服务端发号)", () => {
     const p = renewalPrefill(oldRow as never);
     expect(p).not.toBeNull();
     if (!p) return;
     expect(p.amount).toBe("10800.00");
-    expect(p.payCycle).toBe("yearly");
+    expect(p.serviceMonths).toBe("12");
+    expect(p.contractType).toBe("renew");
     expect(p.agent).toBe("李四");
     expect(p.agentPhone).toBe("13900000000");
     expect(p.agentOrg).toBe("省公司");
@@ -210,10 +222,10 @@ describe("renewalPrefill · 续签带入(2026-11-17)", () => {
     expect(p.items[1].quantity).toBe(2);
   });
 
-  it("⛔ 带编号/外部单号/结束日/附件/交接日期;生效日取旧止期次日(不早于业务当天)", () => {
+  it("⛔ 带编号/外部单号/结束日/附件/签署日期;生效日取旧止期次日(不早于业务当天)", () => {
     const p = renewalPrefill(oldRow as never) as unknown as Record<string, unknown>;
     expect(p).not.toBeNull();
-    for (const key of ["contractNo", "externalNo", "end", "attachmentUrl", "handoverOn"]) {
+    for (const key of ["contractNo", "externalNo", "end", "attachmentUrl", "signDate"]) {
       expect(p[key]).toBeUndefined();
     }
     /** 2026-11-17 四轮:新合同接在旧期间之后,旧合同已过期 ⇒ 取业务当天(⛔ 倒签)。 */
@@ -236,8 +248,8 @@ describe("buildContractWrite · 合同期间(2026-11-17:结束日锁定为
     expect(built.fieldError?.key).toBe("start");
   });
 
-  it("结束日按草稿原样提交(页面只在生效日/付款周期变化时重算)", () => {
-    const draft = { ...baseline(), start: "2026-11-17", payCycle: "yearly", end: contractEndFromCycle("2026-11-17", "yearly") };
+  it("结束日按草稿原样提交(页面只在生效日/服务期变化时重算)", () => {
+    const draft = { ...baseline(), start: "2026-11-17", serviceMonths: "12", end: contractEndFromMonths("2026-11-17", 12) };
     const built = buildContractWrite(draft);
     expect(built.ok).toBe(true);
     if (!built.ok) return;
@@ -400,7 +412,7 @@ describe("buildContractWrite · P1 树形与增量(D-7/D-9)", () => {
   it("增量条目:带 item_mode/ref_subscription_id,且 ⛔ 挂 serves_item_id", () => {
     const base = baseline();
     const item = { ...emptyItem(null, "increment"), planFamily: "addon", planId: "CP-A", quantity: 3, exits: ["香港"], refSubscriptionId: "SUB-1" };
-    const built = buildContractWrite({ ...base, increment: true, items: [item] });
+    const built = buildContractWrite({ ...base, increment: true, contractType: "expand", items: [item] });
     expect(built.ok).toBe(true);
     if (!built.ok) return;
     const payload = built.write.serviceItems[0];
@@ -413,14 +425,14 @@ describe("buildContractWrite · P1 树形与增量(D-7/D-9)", () => {
   it("增量条目缺引用订阅 ⇒ 拦下(D-9)", () => {
     const base = baseline();
     const item = { ...emptyItem(null, "increment"), planFamily: "addon", planId: "CP-A", exits: ["香港"] };
-    const built = buildContractWrite({ ...base, increment: true, items: [item] });
+    const built = buildContractWrite({ ...base, increment: true, contractType: "expand", items: [item] });
     expect(built.ok).toBe(false);
     if (!built.ok) expect(built.error).toContain("须引用本客户一条在期跨境链路订阅");
   });
 
   it("增量合同 ⛔ 把链路条目改成 increment(D-9:增量只补附加项)", () => {
     const base = baseline();
-    const bad = buildContractWrite({ ...base, increment: true, items: [{ ...base.items[0], planFamily: "link", itemMode: "increment", refSubscriptionId: "SUB-1" }] });
+    const bad = buildContractWrite({ ...base, increment: true, contractType: "expand", items: [{ ...base.items[0], planFamily: "link", itemMode: "increment", refSubscriptionId: "SUB-1" }] });
     expect(bad.ok).toBe(false);
     if (!bad.ok) expect(bad.error).toContain("只能补附加项");
   });

+ 105 - 41
web-scaffold/src/domain/contract-draft.ts

@@ -69,13 +69,20 @@ export type ItemDraft = {
 export type ContractDraft = {
   contractNo: string;
   externalNo: string;
+  /** 合同类型:`new`(新建)/`renew`(续签)/`expand`(扩容补充协议)/`change`(变更协议)。 */
+  contractType: string;
+  /**
+   * 签署日期(`YYYY-MM-DD`,必填,等同原「交接日期」):同时是写入口径 `agent_handover_on`
+   * 的来源(业主 2026-11-19 定案:交接日期即签署日期,表单只留一个日期框)。
+   */
+  signDate: string;
   amount: string;
-  payCycle: string;
+  /** 服务期(月,1~600):替代原「付款周期」,结束日=生效日+服务期−1 天。 */
+  serviceMonths: string;
   start: string;
   end: string;
   agent: string;
   agentPhone: string;
-  handoverOn: string;
   attachmentUrl: string;
   /** 经办人机构=选填(实测不送也 `10000`、读回 `null`),⛔ 当必填拦人。 */
   agentOrg: string;
@@ -89,12 +96,12 @@ export type ContractDraft = {
 
 /** 改动即撤掉该字段的必填红显(Draft 键 → 必填校验字段键)。 */
 export const REQUIRED_KEY_BY_DRAFT: Partial<Record<keyof ContractDraft, ContractRequiredKey>> = {
-  payCycle: "payCycle",
+  serviceMonths: "serviceMonths",
   amount: "amount",
   start: "start",
   agent: "agent",
   agentPhone: "agentPhone",
-  handoverOn: "handoverOn",
+  signDate: "signDate",
 };
 
 export const emptyItem = (parentKey: string | null = null, itemMode: ItemMode = "new"): ItemDraft => ({
@@ -146,22 +153,46 @@ export function isCustomizedCandidate(
 }
 
 
+/* ── 合同类型/服务期(2026-11-19) ───────────────────────────────── */
+
 /**
- * 付款周期 → 月数(与后端 `subscription::term_months` 同口径:年=12/季=3/月=1)。
+ * 合同类型值域与中文口径(与后端 `bos-invariant::CONTRACT_TYPES` 同字)。
  *
- * ⚠️ 付款周期在**出账**里仍然只记录、不参与任何折算(04 册 §4.2 明文);这里只用它推
- * **合同期间**,两件事不要混。
+ * 语义:`new`=新建;`renew`=续签(须选中「续签自旧合同」);`expand`=扩容补充协议
+ * (服务构成整批为增量附加项,不新开链路);`change`=变更协议(可含逐条替换)。
  */
-export const PAY_CYCLE_MONTHS: Record<string, number> = { yearly: 12, quarterly: 3, monthly: 1 };
+export const CONTRACT_TYPES: ReadonlyArray<{ value: string; label: string }> = [
+  { value: "new", label: "新建" },
+  { value: "renew", label: "续签" },
+  { value: "expand", label: "扩容补充协议" },
+  { value: "change", label: "变更协议" },
+];
+
+export const CONTRACT_TYPE_LABEL: Record<string, string> = Object.fromEntries(
+  CONTRACT_TYPES.map((item) => [item.value, item.label]),
+);
+
+/**
+ * 「服务期(月)」标题右侧的快捷档:月/季/年/3 年(点一下把月数填进去)。
+ *
+ * 「5 年」已下线(业主 2026-11-19):快捷档只做常见租期的填充,更长租期直接输月数
+ * (输入框仍收 1~600,60 个月照样填得进去,⛔ 因此收窄值域)。
+ */
+export const SERVICE_MONTH_PRESETS: ReadonlyArray<{ label: string; months: number }> = [
+  { label: "月", months: 1 },
+  { label: "季", months: 3 },
+  { label: "年", months: 12 },
+  { label: "3 年", months: 36 },
+];
 
 /** 结束日只读原因(新建表单与详情内联编辑共用一句,⛔ 各写一份)。 */
-export const CONTRACT_END_DERIVED = "合同结束日由「生效日+付款周期」自动推算(年付 12/季付 3/月付 1 个月再减一天),不可手改";
+export const CONTRACT_END_DERIVED = "合同结束日由「生效日+服务期(月)」自动推算(生效日加服务期月数再减一天),不可手改";
 
 /**
  * 业务当天(`Asia/Shanghai`,`YYYY-MM-DD`)。
  *
  * ⛔ 用 `toISOString().slice(0,10)`:那是 UTC,晚 8 点后日期会跳到次日,运维晚上录合同
- * 就会拿到明天的日期并把它当成「录入当日」的交接日期。
+ * 就会拿到明天的日期并把它当成「录入当日」的签署日期。
  */
 export function businessToday(now: Date = new Date()): string {
   const parts = new Intl.DateTimeFormat("en-CA", {
@@ -178,15 +209,16 @@ export function businessToday(now: Date = new Date()): string {
 const daysInMonth = (year: number, month: number) => new Date(Date.UTC(year, month, 0)).getUTCDate();
 
 /**
- * 合同结束日=**生效日 + 付款周期月数 − 1 天**(2026-11-17 定案:结束日锁定为推算值,⛔ 手填)。
+ * 合同结束日=**生效日 + 服务期(月) − 1 天**(2026-11-19 起合同只录服务期月数)。
  *
  * 与后端 `subscription::add_months_clamped` 同一式:加月后该月无对应日**先取月末**,再减一天
- * (1-31 起、月付 ⇒ 2-28 → 2-27)。任一项缺失/非法 ⇒ 返回空串,让页面显式提示「先填生效日与
- * 付款周期」,⛔ 留一个陈旧的结束日。
+ * (1-31 起、1 个月 ⇒ 2-28 → 2-27)。服务期缺失/非法 ⇒ 返回空串,让页面显式提示
+ * 「先填生效日与服务期」,⛔ 留一个陈旧的结束日。
  */
-export function contractEndFromCycle(start: string, payCycle: string): string {
-  const months = PAY_CYCLE_MONTHS[payCycle];
-  if (!months || !/^\d{4}-\d{2}-\d{2}$/.test(start)) return "";
+export function contractEndFromMonths(start: string, monthsRaw: string | number): string {
+  const months = typeof monthsRaw === "number" ? monthsRaw : Number(String(monthsRaw).trim());
+  if (!Number.isInteger(months) || months < 1 || months > 600) return "";
+  if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) return "";
   const [year, month, day] = start.split("-").map(Number);
   if (!year || !month || !day) return "";
   const total = year * 12 + (month - 1) + months;
@@ -198,16 +230,27 @@ export function contractEndFromCycle(start: string, payCycle: string): string {
   return end.toISOString().slice(0, 10);
 }
 
+/** 由起止日反推服务期(月,两端月份计入):仅用于存量行没有 `service_months` 时的展示兜底。 */
+export function serviceMonthsFromPeriod(start: string | null | undefined, end: string | null | undefined): number | null {
+  if (!start || !end || !/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) return null;
+  const [sy, sm] = start.split("-").map(Number);
+  const [ey, em] = end.split("-").map(Number);
+  if (!sy || !sm || !ey || !em) return null;
+  const months = (ey - sy) * 12 + (em - sm) + 1;
+  return months > 0 ? months : null;
+}
+
 export const emptyDraft = (): ContractDraft => ({
   contractNo: "",
   externalNo: "",
+  contractType: "new",
+  signDate: "",
   amount: "",
-  payCycle: "yearly",
+  serviceMonths: "12",
   start: "",
   end: "",
   agent: "",
   agentPhone: "",
-  handoverOn: "",
   attachmentUrl: "",
   agentOrg: "",
   items: [emptyItem()],
@@ -252,13 +295,16 @@ export const draftFromRow = (row: ContractGetResult | null | undefined): Contrac
   return {
     contractNo: row?.contract_no ?? "",
     externalNo: row?.external_no ?? "",
+    contractType: row?.contract_type ?? "new",
+    signDate: row?.sign_date ?? row?.agent_handover_on ?? "",
     amount: centsToInput(row?.contract_amount_cents ?? row?.amount_cents),
-    payCycle: row?.pay_cycle ?? "",
+    serviceMonths: row?.service_months === null || row?.service_months === undefined
+      ? String(serviceMonthsFromPeriod(row?.start_date, row?.end_date) ?? "")
+      : String(row.service_months),
     start: row?.start_date ?? "",
     end: row?.end_date ?? "",
     agent: row?.agent_name ?? "",
     agentPhone: row?.agent_mobile ?? "",
-    handoverOn: row?.agent_handover_on ?? "",
     agentOrg: row?.agent_org ?? "",
     attachmentUrl: row?.attachment_url ?? "",
     items,
@@ -338,19 +384,18 @@ export function renewalStartOf(oldEnd: string | null | undefined, today: string
 }
 
 /**
- * 续签预填(2026-11-17 定案):从旧合同带出**合同金额、付款周期、服务条目、经办人三件套**,
- * 以及**新的合同生效日**(=旧结束日次日,不早于业务当天,见 [`renewalStartOf`];
- * 结束日仍由生效日+付款周期推算,⛔ 直接照抄旧止期)。
+ * 续签预填(2026-11-19 口径):从旧合同带出**合同金额、服务期、服务条目、经办人三件套**,
+ * 合同类型置为「续签」,以及**新的合同生效日**(=旧结束日次日,不早于业务当天,见
+ * [`renewalStartOf`];结束日仍由生效日+服务期推算,⛔ 直接照抄旧止期)。
  *
  * ⛔ 带:合同编号/外部单号(新合同要发新号)、旧合同的起止日(照抄会让新合同期间与旧期间
- * 重叠或错位)、附件(旧合同的影像不是本合同的凭证)、**交接日期**(2026-11-17 三轮:
- * 交接日期默认录入当日;旧合同那一张是上一份合同的凭证,带过来等于把新合同的交接单
- * 改成去年的日期)。
+ * 重叠或错位)、附件(旧合同的影像不是本合同的凭证)、**签署日期**(2026-11-17 三轮:
+ * 默认录入当日;旧合同那一张是上一份合同的凭证,带过来等于把新合同的交接单改成去年的日期)。
  * `item_id` 必须清空——新建态条目主键由服务端发号,原样回传会被写口按「改条目」点名拒绝。
  */
 export type RenewalPrefill = Pick<
   ContractDraft,
-  "amount" | "payCycle" | "start" | "agent" | "agentPhone" | "agentOrg" | "items"
+  "contractType" | "amount" | "serviceMonths" | "start" | "agent" | "agentPhone" | "agentOrg" | "items"
 >;
 
 export function renewalPrefill(
@@ -360,8 +405,9 @@ export function renewalPrefill(
   if (!row) return null;
   const base = draftFromRow(row);
   return {
+    contractType: "renew",
     amount: base.amount,
-    payCycle: base.payCycle,
+    serviceMonths: base.serviceMonths,
     start: renewalStartOf(base.end, today),
     agent: base.agent,
     agentPhone: base.agentPhone,
@@ -388,15 +434,16 @@ export function frozenChanges(
   const changed: string[] = [];
   if (!scope.billing.editable) {
     if (draft.amount !== baseline.amount) changed.push("合同金额");
-    if (draft.payCycle !== baseline.payCycle) changed.push("付款周期");
+    if (draft.serviceMonths !== baseline.serviceMonths) changed.push("服务期(月)");
     if (draft.start !== baseline.start) changed.push("合同生效日");
     if (draft.end !== baseline.end) changed.push("合同结束日");
     if (JSON.stringify(draft.items) !== JSON.stringify(baseline.items)) changed.push("服务构成");
   }
   if (!scope.archive.editable) {
+    if (draft.contractType !== baseline.contractType) changed.push("合同类型");
+    if (draft.signDate !== baseline.signDate) changed.push("签署日期");
     if (draft.externalNo !== baseline.externalNo) changed.push("外部单号");
-    if (draft.handoverOn !== baseline.handoverOn) changed.push("交接日期");
-    // 运营商经办人三件套=交接单上的商务档案,与「交接日期」同一条轴(2026-11-15 定稿)。
+    // 运营商经办人三件套=交接单上的商务档案,与「签署日期」同一条轴(2026-11-15 定稿)。
     // ⚠️ 「经办人=录入账号(created_by)」是另一列、页面只读,⛔ 参与本轴判定。
     if (draft.agent !== baseline.agent) changed.push("运营商经办人姓名");
     if (draft.agentPhone !== baseline.agentPhone) changed.push("运营商经办人电话");
@@ -408,8 +455,10 @@ export function frozenChanges(
 /** 提交载荷里与新建/编辑无关的那一段(编号、客户归属另由页面拼)。 */
 export type ContractWrite = {
   externalNo: string;
+  contractType: string;
+  signDate: string;
   contractAmountCents: number;
-  payCycle: string;
+  serviceMonths: number;
   startDate: string;
   endDate: string;
   agentName: string;
@@ -444,8 +493,10 @@ export function changedWriteFields(
   const b = prev.write;
   const out: Partial<ContractWrite> = {};
   if (a.externalNo !== b.externalNo) out.externalNo = a.externalNo;
+  if (a.contractType !== b.contractType) out.contractType = a.contractType;
+  if (a.signDate !== b.signDate) out.signDate = a.signDate;
   if (a.contractAmountCents !== b.contractAmountCents) out.contractAmountCents = a.contractAmountCents;
-  if (a.payCycle !== b.payCycle) out.payCycle = a.payCycle;
+  if (a.serviceMonths !== b.serviceMonths) out.serviceMonths = a.serviceMonths;
   if (a.startDate !== b.startDate) out.startDate = a.startDate;
   if (a.endDate !== b.endDate) out.endDate = a.endDate;
   if (a.agentName !== b.agentName) out.agentName = a.agentName;
@@ -462,25 +513,35 @@ export function changedWriteFields(
  * 条目的校验同源 `domain/contract-items`(镜像后端 `check_contract_items`)。
  */
 export function buildContractWrite(draft: ContractDraft): ContractWriteResult {
+  if (!CONTRACT_TYPES.some((item) => item.value === draft.contractType)) {
+    return { ok: false, error: `合同类型非法:${draft.contractType || "(空)"}` };
+  }
+  /** 类型与录入模式必须自洽:扩容补充协议=整批增量附加项;增量模式也只能是扩容补充协议。 */
+  if (draft.contractType === "expand" && !draft.increment) {
+    return { ok: false, error: "合同类型为「扩容补充协议」时,服务构成须为增量附加项(先在服务构成选择引用既有链路订阅)。" };
+  }
+  if (draft.increment && draft.contractType !== "expand") {
+    return { ok: false, error: "服务构成是增量附加项,请把合同类型改为「扩容补充协议」。" };
+  }
   const missing = checkContractRequired({
-    payCycle: draft.payCycle,
+    serviceMonths: draft.serviceMonths,
     amount: draft.amount,
     start: draft.start,
     agent: draft.agent,
     agentPhone: draft.agentPhone,
-    handoverOn: draft.handoverOn,
+    signDate: draft.signDate,
   });
   if (missing) return { ok: false, error: missing.message, fieldError: missing };
 
   /**
-   * 必填都齐了才轮得到结束日:它**只能**由生效日+付款周期推算(2026-11-17 定案)⇒ 缺失时
-   * 点名付款周期(生效日已在上面拦过),⛔ 报「请填写生效日与结束日」让人去改一个改不了的框。
+   * 必填都齐了才轮得到结束日:它**只能**由生效日+服务期(月)推算(2026-11-19 定案)⇒ 缺失时
+   * 点名服务期(生效日已在上面拦过),⛔ 报「请填写生效日与结束日」让人去改一个改不了的框。
    */
   if (!draft.end) {
     return {
       ok: false,
-      error: "请选择付款周期:合同结束日由「生效日+付款周期」自动推算。",
-      fieldError: { key: "payCycle", message: "请选择付款周期" },
+      error: "请填写服务期(月):合同结束日由「生效日+服务期」自动推算。",
+      fieldError: { key: "serviceMonths", message: "请填写服务期(月)" },
     };
   }
   if (draft.end < draft.start) return { ok: false, error: "合同结束日不得早于生效日。" };
@@ -576,13 +637,16 @@ export function buildContractWrite(draft: ContractDraft): ContractWriteResult {
     ok: true,
     write: {
       externalNo: draft.externalNo.trim(),
+      contractType: draft.contractType,
+      signDate: draft.signDate,
       contractAmountCents: yuanTextToCents(draft.amount) ?? 0,
-      payCycle: draft.payCycle,
+      serviceMonths: Number(draft.serviceMonths.trim()),
       startDate: draft.start,
       endDate: draft.end,
       agentName: draft.agent.trim(),
       agentMobile: draft.agentPhone.trim(),
-      agentHandoverOn: draft.handoverOn,
+      /** 交接日期=签署日期(2026-11-19):接口仍收 `agent_handover_on`,值取签署日期。 */
+      agentHandoverOn: draft.signDate,
       agentOrg: draft.agentOrg.trim(),
       attachmentUrl: draft.attachmentUrl.trim(),
       serviceItems,

+ 11 - 4
web-scaffold/src/domain/contract-items.ts

@@ -106,19 +106,20 @@ export function checkAmountCents(raw: string): string | null {
  * `agent_org`(经办人机构)实测选填(不送也 `10000`、读回 `null`)⇒ ⛔ 当必填拦人。
  */
 export const CONTRACT_REQUIRED_FIELDS = [
-  { key: "payCycle", label: "付款周期", message: "请选择付款周期" },
+  { key: "serviceMonths", label: "服务期(月)", message: "请填写服务期(月)" },
   { key: "amount", label: "合同金额", message: "请填写合同金额" },
-  // 2026-11-17:结束日锁定为「生效日+付款周期」推算值 ⇒ 生效日成为期间唯一的人工入口,必填前移。
+  // 2026-11-19:结束日锁定为「生效日+服务期(月)」推算值 ⇒ 生效日成为期间唯一的人工入口,必填前移。
   { key: "start", label: "生效日", message: "请选择生效日" },
   { key: "agent", label: "经办人姓名", message: "请填写运营商经办人姓名" },
   { key: "agentPhone", label: "经办人联系电话", message: "请填写经办人联系电话" },
-  { key: "handoverOn", label: "交接日期", message: "请选择交接日期" },
+  // 2026-11-19:交接日期即签署日期,表单只留「签署日期」,写入口径仍送 agent_handover_on。
+  { key: "signDate", label: "签署日期", message: "请选择签署日期" },
 ] as const;
 
 export type ContractRequiredKey = (typeof CONTRACT_REQUIRED_FIELDS)[number]["key"];
 export type ContractMissing = { key: ContractRequiredKey; message: string };
 
-/** **按后端短路顺序**(付款周期 → 合同金额 → 生效日 → 经办人姓名 → 联系电话 → 交接日期)返回第一条命中的必填项;金额非空时再套「元、两位小数/须大于 0」的更具体口径。 */
+/** **按后端短路顺序**(服务期 → 合同金额 → 生效日 → 经办人姓名 → 联系电话 → 签署日期)返回第一条命中的必填项;金额非空时再套「元、两位小数/须大于 0」的更具体口径。 */
 export function checkContractRequired(values: Record<ContractRequiredKey, string>): ContractMissing | null {
   for (const field of CONTRACT_REQUIRED_FIELDS) {
     const raw = values[field.key];
@@ -126,6 +127,12 @@ export function checkContractRequired(values: Record<ContractRequiredKey, string
       if (!raw.trim()) return { key: field.key, message: field.message };
       const amountError = checkAmountCents(raw);
       if (amountError) return { key: field.key, message: amountError };
+    } else if (field.key === "serviceMonths") {
+      if (!raw.trim()) return { key: field.key, message: field.message };
+      const months = Number(raw);
+      if (!Number.isInteger(months) || months < 1 || months > 600) {
+        return { key: field.key, message: "服务期须为 1~600 的整数(月)" };
+      }
     } else if (!raw.trim()) {
       return { key: field.key, message: field.message };
     }

+ 7 - 2
web-scaffold/src/lib/api/bos.ts

@@ -696,9 +696,12 @@ export const ipBandwidthTierSave = (d: {
 
 /** 新建合同 [位] —— 客户段+合同段+服务构成条目+IP 条件一次提交;拒收 source。 */
 export const contractCreate = (d: {
-  pay_cycle: string;
+  /** 服务期(月,1~600):结束日=生效日+服务期−1 天。 */
+  service_months: number;
   start_date: string;
   end_date: string;
+  contract_type?: string;
+  sign_date?: string;
   customer_id?: string;
   contract_no?: string;
   external_no?: string;
@@ -761,8 +764,10 @@ export const contractUpdate = (d: {
   contract_id: string;
   row_version: number;
   external_no?: string;
+  contract_type?: string;
+  sign_date?: string;
   contract_amount_cents?: number;
-  pay_cycle?: string;
+  service_months?: number;
   start_date?: string;
   end_date?: string;
   agent_name?: string;

+ 6 - 1
web-scaffold/src/lib/api/types.ts

@@ -2056,7 +2056,12 @@ export type ContractRow = {
   status: string;
   contract_amount_cents: number;
   amount_cents?: number;
-  pay_cycle: string | null;
+  /** 合同类型:`new`(新建)/`renew`(续签)/`expand`(扩容补充协议)/`change`(变更协议)。 */
+  contract_type?: string | null;
+  /** 签署日期(`YYYY-MM-DD`;存量行按交接日期回填)。 */
+  sign_date?: string | null;
+  /** 服务期(月):结束日=生效日+服务期−1 天(替代原 `pay_cycle`)。 */
+  service_months?: number | null;
   start_date: string | null;
   end_date: string | null;
   agent_name: string | null;

+ 6 - 3
web-scaffold/src/lib/contract-audit.ts

@@ -7,13 +7,15 @@
  * diff 一旦分叉,日志与后端拦截就会各说各话。
  */
 import type { ContractChangeLogItem } from "./api/types";
-import { PAY_CYCLE, label } from "./api/labels";
+import { CONTRACT_TYPE_LABEL } from "../domain/contract-draft";
 import { attachmentKindOf, contractAttachmentLabel } from "./contract-attachments";
 
 /** 审计字段键 → 中文名(与 `draft_audit_view`/`row_audit_view` 的快照键一一对应)。 */
 const FIELD_LABELS: Record<string, string> = {
   amount_cents: "合同金额",
-  pay_cycle: "付款周期",
+  contract_type: "合同类型",
+  sign_date: "签署日期",
+  service_months: "服务期(月)",
   start_date: "合同生效日",
   end_date: "合同结束日",
   external_no: "外部单号",
@@ -33,7 +35,8 @@ function formatValue(key: string, value: unknown): string {
   if (key === "amount_cents" && typeof value === "number") {
     return `¥${(value / 100).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
   }
-  if (key === "pay_cycle" && typeof value === "string") return label(PAY_CYCLE, value);
+  if (key === "contract_type" && typeof value === "string") return CONTRACT_TYPE_LABEL[value] ?? value;
+  if (key === "service_months" && typeof value === "number") return `${value} 个月`;
   // 附件(单值):库里可能是平台对象键(末段是随机串)⇒ 显示可读名,⛔ 把随机串糊进审计卡;
   // 查看地址由读口现签,审计只说明「改了哪个附件」。
   if (key === "attachment_url" && typeof value === "string") {

+ 15 - 7
web-scaffold/src/lib/contract-demo.ts

@@ -8,7 +8,7 @@ import type {
   ContractRow,
   ContractServiceItem,
 } from "./api/types";
-import { label, PAY_CYCLE } from "./api/labels";
+import { CONTRACT_TYPE_LABEL } from "../domain/contract-draft";
 import { useLoad, type Load } from "./useLoad";
 
 /** 合同视图模型口径取自原型《需求规格说明》5.3 的合同记录,数据一律由下方 klt-bos 接口适配产出。 */
@@ -42,7 +42,12 @@ export type DemoContract = {
   customerNo?: string;
   extNo: string;
   amount: number;
-  payCycle: "按年" | "按季度" | "按月";
+  /** 合同类型中文(新建/续签/扩容补充协议/变更协议)。 */
+  contractType: string;
+  /** 签署日期(`YYYY-MM-DD`;空串=未配置)。 */
+  signDate: string;
+  /** 服务期(月);`null`=未配置。 */
+  serviceMonths: number | null;
   start: string;
   end: string;
   items: ContractItem[];
@@ -59,8 +64,8 @@ export type DemoContract = {
   contractId?: string | null;
   rowVersion?: number | null;
   customerId?: string | null;
-  /** 付款周期后端编码,未知编码原样显示。 */
-  payCycleCode?: string | null;
+  /** 合同类型后端编码(new/renew/expand/change),未知编码原样显示。 */
+  contractTypeCode?: string | null;
   /** 线路出口随服务条目下发,⛔ 前端按本地清单校验。 */
   lineExitOptions?: string[];
   /** 合同状态原值(页面需要区分「未配置」时读取)。 */
@@ -147,6 +152,7 @@ export type ContractRowView = Omit<DemoContract, "source" | "file" | "opened" |
   /** 合同金额三态:`contract_amount_cents` 缺失=取数失败,⛔ 显示 ¥0.00。 */
   amountState?: "val" | "missing" | "fail";
   payCycleState?: "val" | "missing" | "fail";
+  serviceMonthsState?: "val" | "missing" | "fail";
   periodState?: "val" | "missing" | "fail";
   /** 仅 `/contract/get@v1` 下发(D-23):`undefined`=未取数,`null`=档案不可读(客户已注销)。 */
   customerProfile?: ContractCustomerProfile | null;
@@ -183,9 +189,11 @@ export function contractFromRow(row: ContractRow, quotaById?: Record<string, num
     extNo: row.external_no ?? "",
     amount: centsToYuan(cents) ?? 0,
     amountState: cents === undefined ? "fail" : cents === null ? "missing" : "val",
-    payCycle: (row.pay_cycle ? label(PAY_CYCLE, row.pay_cycle) : "") as DemoContract["payCycle"],
-    payCycleState: row.pay_cycle === undefined ? "fail" : row.pay_cycle === null ? "missing" : "val",
-    payCycleCode: row.pay_cycle ?? null,
+    contractType: CONTRACT_TYPE_LABEL[row.contract_type ?? "new"] ?? (row.contract_type ?? "新建"),
+    contractTypeCode: row.contract_type ?? null,
+    signDate: row.sign_date ?? "",
+    serviceMonths: row.service_months === undefined ? null : row.service_months ?? null,
+    serviceMonthsState: row.service_months === undefined ? "fail" : row.service_months === null ? "missing" : "val",
     start: row.start_date ?? "",
     end: row.end_date ?? "",
     periodState: row.start_date === undefined && row.end_date === undefined ? "fail" : !row.start_date || !row.end_date ? "missing" : "val",

+ 398 - 217
web-scaffold/src/pages/ContractDetailPages.tsx

@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
 import { ArrowLeft, Lock, Plus, Trash2, Upload, X } from "lucide-react";
 import { FetchError } from "../components/fetchError";
 import { useNavigate, useParams, useSearchParams } from "react-router";
@@ -8,20 +8,19 @@ import { TreeSelect } from "../components/ui/tree-select";
 import { FieldHint } from "../components/ui/field-hint";
 import { CustomerTeamSelect } from "../components/CustomerTeamSelect";
 import { contractRawByParam } from "../lib/contract-demo";
-import { contractAttachmentDiscard, contractCreate, contractCustomerLookup, contractGet, contractGetList, contractUpdate, customerGet, orderGetList, rowsOf, subscriptionReplacementCandidates } from "../lib/api/bos";
+import { contractCreate, contractCustomerLookup, contractGet, contractGetList, contractUpdate, customerGet, orderGetList, rowsOf, subscriptionReplacementCandidates } from "../lib/api/bos";
 import { ApiError } from "../lib/api/http";
-import { OPTIONS, label, PAY_CYCLE, PLAN_FAMILY } from "../lib/api/labels";
+import { label, PLAN_FAMILY } from "../lib/api/labels";
 import { WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
 import { Tri } from "../components/triState";
 import { useCatalogPlans, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
-import { centsToYuanText, LINE_EXIT_MAX } from "../domain/contract-items";
+import { CONTRACT_REQUIRED_FIELDS, centsToYuanText, LINE_EXIT_MAX, yuanTextToCents } from "../domain/contract-items";
 import type { ContractMissing, ContractRequiredKey } from "../domain/contract-items";
-import { REQUIRED_KEY_BY_DRAFT, buildContractWrite, businessToday, childExitOptions, contractEndFromCycle, draftFromRow, emptyDraft, emptyItem, itemSubtreeKeys, itemTree, renewalPrefill, resolveReplacementSelection, type ContractDraft as Draft, type ItemDraft } from "../domain/contract-draft";
+import { CONTRACT_TYPES, REQUIRED_KEY_BY_DRAFT, SERVICE_MONTH_PRESETS, buildContractWrite, businessToday, childExitOptions, contractEndFromMonths, draftFromRow, emptyDraft, emptyItem, itemSubtreeKeys, itemTree, renewalPrefill, resolveReplacementSelection, type ContractDraft as Draft, type ItemDraft } from "../domain/contract-draft";
 import { regionTreeNodes } from "../lib/region-tree";
 import { useOrganizationData } from "../lib/organization-demo";
 import type { ContractCreateResult, ContractReplacementResult, ReplacementCandidate, ReplacementSkipped } from "../lib/api/types";
 import { uploadContractAttachment, uploadCustomerLicense, type UploadedObject } from "../lib/api/oss-upload";
-import { contractAttachmentLabel } from "../lib/contract-attachments";
 import { useLoad } from "../lib/useLoad";
 import { useDemoIdentity } from "../lib/demo-session";
 import { PackagePlanEditor, type EditorState } from "../components/PackagePlanEditor";
@@ -39,6 +38,10 @@ type ReplacementProbe = { loading: boolean; error: string; candidates: Replaceme
 
 const CUSTOMER_LOOKUP_DEBOUNCE_MS = 300;
 
+/** 拖进来的确实是文件(⛔ 文本/选区/页内元素),拖曳上传区只对文件亮起并接管落点。 */
+const hasFiles = (transfer: DataTransfer | null): boolean =>
+  Boolean(transfer && Array.from(transfer.types ?? []).includes("Files"));
+
 /**
  * 续签源下拉的选项文案(合同号 · 期间 · 金额)。深链续签(`?renew=`)也要用同一句,
  * 否则列表没回这份合同时下拉会空着、看不出带了哪一份。
@@ -95,6 +98,29 @@ function emptyInlineCustomer() {
   };
 }
 
+/**
+ * 区域门禁(业主 2026-11-19):「所属区域」未选时,运营商/合伙人/运营团队/运维团队一律只读。
+ * 原生 `disabled` 控件**不派发点击事件也不冒泡**,点上去毫无反馈 ⇒ 外面包一层接管点击、就地弹提示;
+ * 门禁生效时子节点 `pointer-events:none`(样式里),点击必落在包装层上。
+ */
+function RegionGate({ gated, children }: { gated: boolean; children: ReactNode }) {
+  const [tip, setTip] = useState(false);
+  const timer = useRef<number | undefined>(undefined);
+  useEffect(() => () => window.clearTimeout(timer.current), []);
+  if (!gated) return <>{children}</>;
+  const openTip = () => {
+    setTip(true);
+    window.clearTimeout(timer.current);
+    timer.current = window.setTimeout(() => setTip(false), 3000);
+  };
+  return (
+    <span className="contract-region-gate" onClick={openTip}>
+      {children}
+      {tip && <span className="contract-region-gate-tip" role="status">请先选取所属区域</span>}
+    </span>
+  );
+}
+
 export function ContractEditorPage() {
   const { no } = useParams();
   const navigate = useNavigate();
@@ -107,10 +133,11 @@ export function ContractEditorPage() {
   const exitCatalog = useLineExits();
   const record = useLoad(() => contractRawByParam(no), [no]);
   /**
-   * 新建态草稿:**交接日期默认录入当日**(2026-11-17 定案;`Asia/Shanghai` 业务日,
-   * 编辑态恒以库里的值为准,⛔ 拿今天覆盖已记录的历史交接单)。
+   * 新建态草稿:**签署日期默认录入当日**(2026-11-17 定案;`Asia/Shanghai` 业务日,
+   * 编辑态恒以库里的值为准,⛔ 拿今天覆盖已记录的历史签署日)。
+   * 2026-11-19 起「交接日期」并入签署日期:表单只留一个日期框,写口仍按 `agent_handover_on` 送。
    */
-  const [draft, setDraft] = useState<Draft>(() => ({ ...emptyDraft(), handoverOn: businessToday() }));
+  const [draft, setDraft] = useState<Draft>(() => ({ ...emptyDraft(), signDate: businessToday() }));
   const [customerId, setCustomerId] = useState<string | null>(null);
   /**
    * P1(D-9)增量合同的「既有链路」候选:本客户 `active` ∧ 未到期 ∧ `plan_family='link'` 的订阅
@@ -290,6 +317,8 @@ export function ContractEditorPage() {
     setRenewFrom(contractId);
     setRenewError("");
     setRenewSourceLabel("");
+    /** 选/清续签来源即同步合同类型(续签 ⇄ 新建),⛔ 让类型与来源各说一套。 */
+    setDraft((current) => (current.increment ? current : { ...current, contractType: contractId ? "renew" : "new" }));
     if (!contractId) return;
     setRenewLoading(true);
     try {
@@ -303,8 +332,8 @@ export function ContractEditorPage() {
       setRenewSourceLabel(renewalOptionLabel(row));
       setDraft((current) => {
         const next = { ...current, ...prefill };
-        /** 账期被带出后结束日跟着重算(结束日恒由生效日+付款周期推算)。 */
-        next.end = contractEndFromCycle(next.start, next.payCycle);
+        /** 服务期被带出后结束日跟着重算(结束日恒由生效日+服务期(月)推算)。 */
+        next.end = contractEndFromMonths(next.start, next.serviceMonths);
         return next;
       });
       /** 续签=按新订阅开通:清掉可能残留的替换选择与探测结果。 */
@@ -348,7 +377,7 @@ export function ContractEditorPage() {
         setRenewSourceLabel(renewalOptionLabel(row));
         setDraft((current) => {
           const next = { ...current, ...prefill };
-          next.end = contractEndFromCycle(next.start, next.payCycle);
+          next.end = contractEndFromMonths(next.start, next.serviceMonths);
           return next;
         });
         setReplacementProbes({});
@@ -364,53 +393,16 @@ export function ContractEditorPage() {
     // `navigate`/setters 都是稳定引用,只在带进来的合同号变化时重跑。
     // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [renewParam]);
-  /**
-   * 合同附件(单份,2026-11-16 定案):选中即直传平台对象存储,成功后只把**对象键**挂进
-   * `draft.attachmentUrl`(字面量须与后端 `CONTRACT_ATTACHMENT_KEY_PREFIX` 同前缀)。
-   * ⛔ 字节流/上传凭证经本服务;查看地址由详情读口现签,⛔ 前端缓存签名。
-   */
-  const attachmentInput = useRef<HTMLInputElement | null>(null);
-  const [attachmentBusy, setAttachmentBusy] = useState(false);
-  const [attachmentError, setAttachmentError] = useState("");
-  /** 本次刚上传的原始文件名(键里不含文件名 ⇒ 刷新后按后缀显示「合同附件.<ext>」)。 */
-  const [attachmentName, setAttachmentName] = useState("");
-  /**
-   * 本页**刚上传、还没被任何合同引用**的对象键(孤儿回收清单)。
-   *
-   * 平台只有「即时删除」一条通道(`object/delete@v1`,见 unified-oss §6.6.10:不做后台遍历删对象),
-   * 所以「换了/移除了/取消了」的那一刻必须由本页把没人要的那一份退回去([`discardPendingAttachments`])。
-   * 服务端还会再查一次引用面(仍被合同引用就拒删)⇒ 这里可以放宽心调,⛔ 当成前端独占真相。
-   */
-  const pendingAttachmentKeys = useRef<string[]>([]);
+  /** 右栏上次落库的附件(只用于保存时原样回传,页面不再提供上传入口:附件在详情页维护)。 */
   useEffect(() => {
     if (record.data) setDraft(draftFromRow(record.data));
   }, [record.data]);
   /**
-   * 把清单里的对象键交给服务端回收(best-effort):失败⛔ 拦用户、⛔ 回滚草稿——
-   * 用户的动作(换文件/移除/取消)已经完成,回收只是桶侧的清尾。
-   */
-  const discardPendingAttachments = (keys?: string[]) => {
-    const targets = keys ?? pendingAttachmentKeys.current;
-    if (!targets.length) return;
-    pendingAttachmentKeys.current = pendingAttachmentKeys.current.filter(
-      (key) => !targets.includes(key),
-    );
-    for (const objectKey of targets) {
-      void contractAttachmentDiscard({ object_key: objectKey }).catch(() => {});
-    }
-  };
-  /** 离开本页(返回/取消)时把没落库的上传一起退掉:`useRef` 读的是最新清单,⛔ 闭包快照。 */
-  useEffect(() => () => discardPendingAttachments(), []);
-  /**
-   * 新建态的「运营商经办人」姓名默认取当前登录身份(与姓名同一来源、可改,⛔ 写死号码);
-   * `auth/context@v1` 实测只回 7 个键、不含手机号 ⇒ 取不到就留空由必填校验拦下,⛔ 造号。
-   * ⚠️ 这一组是**交接单上的运营商侧联系人**,不是「录入账号」(`created_by`,服务端另写、恒只读);
-   * 建后它随档案轴(未开通且 72h 内或未到期)仍可改,与「交接日期」同一命运。
+   * 「运营商经办人」**恒由人工填写**(2026-11-19 定案):它是**交接单上的运营商侧联系人**,
+   * 与「录入账号」(`created_by`,服务端从鉴权上下文写入、页面恒只读)是两个不同的人
+   * ⇒ ⛔ 拿当前登录身份的姓名/手机号预填,否则一线会把自家账号当成运营商对接人提交。
+   * 必填校验照旧拦(姓名+联系电话成对),留空即报 `60004` 原话。
    */
-  useEffect(() => {
-    if (editing || !identity) return;
-    setDraft((current) => ({ ...current, agent: current.agent || identity.name, agentPhone: current.agentPhone || identity.phone || "" }));
-  }, [editing, identity]);
   /**
    * 客户检索=**输入防抖**(300ms 内的连击只打一次 `contract/customer_lookup@v1`)
    * + **沿用上一次结果**:防抖窗口里⛔ 把候选清空——否则每敲一个字下拉就消失再出现,列表整体抖一下。
@@ -486,15 +478,30 @@ export function ContractEditorPage() {
    * 企业营业执照影像**选填**(业主 2026-11-19 定案,⛔ 强制登记),建档后到客户档案「登记材料」格补传。
    */
   const org = useOrganizationData(["regions", "operators", "partners", "operationsTeams", "maintenanceTeams"]);
-  /** 区域树:保留「全网」为层级上下文但不能选中(业主 2026-11-19 定案)。 */
+  /**
+   * 区域树:「全网」是平台虚根,**整层不进下拉**(业主 2026-11-19 定案,替代原「保留但置灰」)——
+   * 直接以省一级为根,选起来少一层展开。把它从建树集合里摘掉即可:省节点的父级不在可见集合内,
+   * `regionTreeNodes` 会按根渲染(与「授权子树只回省」同一口径,⛔ 另写一套 re-root 逻辑)。
+   */
   const regionTree = useMemo(() => {
     const blocked = new Set(org.regions.filter((item) => item.name.trim() === "全网" || (item.pathName ?? "").trim() === "全网").map((item) => item.id));
-    return regionTreeNodes(org.regions, org.regions.filter((item) => !blocked.has(item.id)).map((item) => item.id));
+    const visible = org.regions.filter((item) => !blocked.has(item.id));
+    return regionTreeNodes(visible, visible.map((item) => item.id));
   }, [org.regions]);
   const [inline, setInline] = useState(emptyInlineCustomer);
   const [licenseObj, setLicenseObj] = useState<UploadedObject | null>(null);
   const [licenseBusy, setLicenseBusy] = useState(false);
   const [licenseError, setLicenseError] = useState("");
+  /** 拖曳悬停态(只用于整块上传区的视觉反馈;离开/落下即复位)。 */
+  const [licenseDragging, setLicenseDragging] = useState(false);
+  /**
+   * 合同附件(业主 2026-11-19):与营业执照影像同一套整块拖曳卡片,放在 02 合同基本信息最下面。
+   * 附件是**单值**(`contract.attachment_url`)⇒ 只存对象键;`file_name` 仅用于回显。
+   */
+  const [attachmentObj, setAttachmentObj] = useState<UploadedObject | null>(null);
+  const [attachmentBusy, setAttachmentBusy] = useState(false);
+  const [attachmentError, setAttachmentError] = useState("");
+  const [attachmentDragging, setAttachmentDragging] = useState(false);
   /** 内联建档成功后的回执(客户号/主账号/激活码口径);合同已生成,下一步是去合同详情。 */
   const [created, setCreated] = useState<{ contractId: string; customer: NonNullable<ContractCreateResult["inline_customer"]>; replacements: ContractReplacementResult[] } | null>(null);
   const setInlineField = <K extends keyof typeof inline>(key: K, value: (typeof inline)[K]) => {
@@ -657,12 +664,12 @@ export function ContractEditorPage() {
     setDraft((current) => {
       const next = { ...current, [key]: value };
       /**
-       * 合同结束日=生效日+付款周期推算(2026-11-17 定案,**锁定手填**):
+       * 合同结束日=生效日+服务期(月)推算(2026-11-19 定案,**锁定手填**):
        * 两个输入项任一变化即重算,⛔ 只改其一留下一个与期间对不上的旧结束日。
        * 任一为空 ⇒ 结束日一并清空,由页面提示先补齐两项。
        */
-      if (key === "start" || key === "payCycle") {
-        next.end = contractEndFromCycle(next.start, next.payCycle);
+      if (key === "start" || key === "serviceMonths") {
+        next.end = contractEndFromMonths(next.start, next.serviceMonths);
       }
       return next;
     });
@@ -720,13 +727,41 @@ export function ContractEditorPage() {
     });
     setError("");
   };
-  /** 切换录入模式会清空服务构成:两种模式的根节点不是同一类东西(链路 vs 引用订阅),⛔ 硬转。 */
-  const toggleIncrement = (on: boolean) => {
-    setDraft((current) => (current.items.length && !window.confirm("切换合同类型会清空当前服务构成,继续?")
-      ? current
-      : { ...current, increment: on, items: [] }));
-    setReplacementProbes({});
-    setItemNotice("");
+  /**
+   * 合同类型下拉(2026-11-19):类型决定服务构成的录入模式。
+   * `expand` ⇒ 切到增量模式(引用既有链路、只补附加项);`renew` ⇒ 普通模式且须选续签来源;
+   * `new`/`change` ⇒ 普通模式。两种模式的根节点不是同一类东西(链路 vs 引用订阅),
+   * 切换会清空服务构成 ⇒ 先征得确认,用户取消就整次不改。
+   */
+  const pickContractType = (value: string) => {
+    if (editing) return;
+    /** 模式切换会清空服务构成(根节点不是同一类东西),先征得确认;用户取消就整次不改。 */
+    const willClear = draft.items.length > 0;
+    if (value === "expand") {
+      if (!draft.increment) {
+        if (willClear && !window.confirm("切换合同类型会清空当前服务构成,继续?")) return;
+        setDraft((current) => ({ ...current, increment: true, items: [], contractType: "expand" }));
+        setReplacementProbes({});
+        setItemNotice("");
+      } else {
+        setDraft((current) => ({ ...current, contractType: "expand" }));
+      }
+      return;
+    }
+    if (draft.increment) {
+      if (willClear && !window.confirm("切换合同类型会清空当前服务构成,继续?")) return;
+      setDraft((current) => ({ ...current, increment: false, items: [], contractType: value }));
+      setReplacementProbes({});
+      setItemNotice("");
+    } else {
+      setDraft((current) => ({ ...current, contractType: value }));
+    }
+    /** 续签来源只在「续签」类型下有意义:类型改走后清掉,避免带一份对不上的来源提交。 */
+    if (value !== "renew" && renewFrom) {
+      setRenewFrom("");
+      setRenewSourceLabel("");
+    }
+    setError("");
   };
   const removeItem = (index: number) => setDraft((current) => {
     const item = current.items[index];
@@ -813,6 +848,100 @@ export function ContractEditorPage() {
     return [...new Set([...names, ...legacy])];
   }, [exitCatalog.data, draft.items]);
 
+  /**
+   * 右侧「业务口径摘要」(2026-11-19,随原型):订购项/带宽/境外 IP/账号上限/月度费用
+   * **一律按所选档位×份数实时汇总**,⛔ 手填;目录没配的一律显示「未配置」,⛔ 兜底 0。
+   *
+   * 口径来源:带宽=`bandwidth_committed` 为真时的上/下行 Mbps(附加项不占带宽);
+   * 境外固定 IP=附加项里名称含「IP」的档位份数(D-9:单独境外 IP 按份叠加);
+   * 账号上限=`sub_account_quota × 份数`;月度费用=`monthly_settle_cents × 份数`。
+   */
+  const sideMetrics = useMemo(() => {
+    const planById = new Map(plans.map((plan) => [plan.plan_id, plan]));
+    let up = 0;
+    let down = 0;
+    let bandwidthKnown = 0;
+    let bandwidthMissing = 0;
+    let ip = 0;
+    let quota = 0;
+    let quotaKnown = false;
+    let quotaMissing = false;
+    let feeCents = 0;
+    let feeKnown = false;
+    let feeMissing = false;
+    for (const item of draft.items) {
+      const plan = planById.get(item.planId);
+      const quantity = item.quantity > 0 ? item.quantity : 1;
+      if (!plan) {
+        bandwidthMissing += 1;
+        quotaMissing = true;
+        feeMissing = true;
+        continue;
+      }
+      if (plan.bandwidth_committed) {
+        if (plan.bandwidth_up_mbps !== null && plan.bandwidth_up_mbps !== undefined && plan.bandwidth_down_mbps !== null && plan.bandwidth_down_mbps !== undefined) {
+          up += plan.bandwidth_up_mbps * quantity;
+          down += plan.bandwidth_down_mbps * quantity;
+          bandwidthKnown += 1;
+        } else {
+          bandwidthMissing += 1;
+        }
+      }
+      if (plan.plan_family === "addon" && /ip/i.test(plan.plan_name)) ip += quantity;
+      if (plan.sub_account_quota === null || plan.sub_account_quota === undefined) quotaMissing = true;
+      else {
+        quota += plan.sub_account_quota * quantity;
+        quotaKnown = true;
+      }
+      if (plan.monthly_settle_cents === null || plan.monthly_settle_cents === undefined) feeMissing = true;
+      else {
+        feeCents += plan.monthly_settle_cents * quantity;
+        feeKnown = true;
+      }
+    }
+    const money = (cents: number) => `¥${Number(centsToYuanText(cents)).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+    return {
+      items: draft.items.length,
+      bandwidth: bandwidthKnown === 0
+        ? (bandwidthMissing ? "未配置" : "—")
+        : `上行 ${up} / 下行 ${down} Mbps${bandwidthMissing ? `(${bandwidthMissing} 条未配置)` : ""}`,
+      ip: `${ip} 个`,
+      quota: quotaKnown ? `${quota} 个${quotaMissing ? "(部分未配置)" : ""}` : "未配置",
+      fee: feeKnown ? `${money(feeCents)}${feeMissing ? "(部分未配置)" : ""}` : "未配置",
+    };
+  }, [draft.items, plans]);
+
+  /** 右侧「必填完成度」:客户+6 个写入口径必填(同源 `CONTRACT_REQUIRED_FIELDS`),⛔ 另写一套判据。 */
+  const requiredProgress = useMemo(() => {
+    const values: Record<ContractRequiredKey, string> = {
+      serviceMonths: draft.serviceMonths,
+      amount: draft.amount,
+      start: draft.start,
+      agent: draft.agent,
+      agentPhone: draft.agentPhone,
+      signDate: draft.signDate,
+    };
+    const missing: string[] = [];
+    for (const field of CONTRACT_REQUIRED_FIELDS) {
+      const raw = (values[field.key] ?? "").trim();
+      let filled = Boolean(raw);
+      if (filled && field.key === "amount") {
+        const cents = yuanTextToCents(raw);
+        filled = cents !== null && cents > 0;
+      }
+      if (filled && field.key === "serviceMonths") {
+        const months = Number(raw);
+        filled = Number.isInteger(months) && months >= 1 && months <= 600;
+      }
+      if (!filled) missing.push(field.label);
+    }
+    const customerFilled = editing || Boolean(customerId) || customerTerm.trim().length >= 2;
+    if (!customerFilled) missing.unshift("客户");
+    const total = CONTRACT_REQUIRED_FIELDS.length + 1;
+    const done = total - missing.length;
+    return { done, total, pct: total ? Math.round((done / total) * 100) : 100, missing };
+  }, [customerId, customerTerm, draft.agent, draft.agentPhone, draft.amount, draft.serviceMonths, draft.signDate, draft.start, editing]);
+
   async function save() {
     if (!identity) { setError("请先登录后再提交合同;写入权限由服务端判定。"); return; }
     if (submitting) return;
@@ -839,25 +968,32 @@ export function ContractEditorPage() {
       const half = pairs.find(([, name, phone]) => Boolean(name.trim()) !== Boolean(phone.trim()));
       if (half) { setError(`${half[0]}需同时填写姓名与电话(只填一项会留下残缺的联系人)。`); return; }
     }
+    /** 类型与来源必须自洽(2026-11-19):续签必须有旧合同可接,⛔ 只改个标签就提交。 */
+    if (!editing && draft.contractType === "renew" && !renewFrom) {
+      setError("合同类型为「续签」:请在 02 合同基本信息里选定「续签自旧合同」,或把类型改为「新建」。");
+      return;
+    }
     const built = buildContractWrite(draft);
     if (!built.ok) {
       setFieldError(built.fieldError ?? null);
       setError(built.error);
-      // 失败⛔ 清空任何已录入内容(合同、条目、替换选择、已上传附件),只把视口带到首个出错条目。
+      // 失败⛔ 清空任何已录入内容(合同、条目、替换选择),只把视口带到首个出错条目。
       focusFirstErrorItem(built.error);
       return;
     }
     const w = built.write;
     /**
      * 写入口径必填 5 项(2026-11-14 探针实测 `contract/create@v1` 逐字段短路的 `60004`):
-     * 付款周期(需求 §5.3 第 523 行)→ 合同金额(第 522 行「须大于 0…不保存并红显该字段」)→
-     * 经办人姓名 → 经办人联系电话 → 交接日期;提示语照抄后端原话并红显命中的那个字段,
+     * 服务期(月)(需求 §5.3 第 523 行)→ 合同金额(第 522 行「须大于 0…不保存并红显该字段」)→
+     * 经办人姓名 → 经办人联系电话 → 签署日期;提示语照抄后端原话并红显命中的那个字段,
      * `agent_org` 选填(不送也 `10000`)⇒ ⛔ 参与校验。校验同源 `domain/contract-draft`。
      */
     const shared = {
       ...(w.externalNo ? { external_no: w.externalNo } : {}),
+      contract_type: w.contractType,
+      sign_date: w.signDate,
       contract_amount_cents: w.contractAmountCents,
-      pay_cycle: w.payCycle,
+      service_months: w.serviceMonths,
       start_date: w.startDate,
       end_date: w.endDate,
       agent_name: w.agentName,
@@ -865,7 +1001,10 @@ export function ContractEditorPage() {
       agent_handover_on: w.agentHandoverOn,
       /** `agent_org`=选填:恒送 trim 值(空串=后端 `text_param` 置 `NULL`),⛔ 因缺它而拦人。 */
       agent_org: w.agentOrg,
-      /** 附件单值:空串=清空(后端 `text_param` 置 `NULL`)⇒ ⛔ 省略键,否则「移除附件」永远存不下去。 */
+      /**
+       * 附件原样回传(2026-11-19 起录入页不再放上传格:新建态为空串,编辑态是读口回带的库值)。
+       * ⛔ 省略键:存量合同带附件时,省略在新建口等于「没传」,语义不如显式空串清楚。
+       */
       attachment_url: w.attachmentUrl.trim(),
       service_items: w.serviceItems,
     };
@@ -882,8 +1021,6 @@ export function ContractEditorPage() {
           row_version: version,
           ...shared,
         });
-        // 落库成功 ⇒ 清单里的对象键已被合同引用(服务端也会拒删),⛔ 别再当孤儿回收。
-        pendingAttachmentKeys.current = [];
         navigate(`/contracts/${encodeURIComponent(row.contract_id)}`);
       } else {
         const res = await contractCreate({
@@ -917,8 +1054,6 @@ export function ContractEditorPage() {
                 },
               }),
         });
-        // 合同已生成 ⇒ 附件对象已被引用(服务端也会拒删)⇒ 清空孤儿清单。
-        pendingAttachmentKeys.current = [];
         // 内联建档成功 ⇒ 停在回执页展示客户号与主账号(激活码明文由「导出激活码」取,⛔ 在此伪造)。
         if (res?.inline_customer) {
           setCreated({ contractId: res.contract_id, customer: res.inline_customer, replacements: res.replacements ?? [] });
@@ -931,7 +1066,7 @@ export function ContractEditorPage() {
       }
     } catch (e) {
       // 写口整批回滚(合同、条目、派生档、IP、截原、新订阅、额度一起)⇒ 页面**保留**已录入内容:
-      // 只显示错误、把视口带到首个出错条目,用户可改后直接重提(已上传附件仍在孤儿清单里,⛔ 回收)。
+      // 只显示错误、把视口带到首个出错条目,用户可改后直接重提(⛔ 清空已录内容)。
       const message = e instanceof ApiError ? e.message : "保存失败,请稍后重试。";
       setError(message);
       focusFirstErrorItem(message);
@@ -959,46 +1094,24 @@ export function ContractEditorPage() {
   }
 
   /**
-   * 合同附件:选中即直传平台桶(同一两段式通路,前缀换成合同附件),成功才写进草稿;
-   * `attachment_url` 在提交时才随合同落库 ⇒ 上传成功但未保存=库里仍是旧附件。
-   *
-   * 孤儿回收(2026-11-16):上一份若也是**本页刚上传、还没落库**的,换掉的那一刻它就没人引用了
-   * ⇒ 立刻退回服务端(库里那份仍在引用,由写口的 `attachment_object_delete` 回收,⛔ 在这里删)。
+   * 合同附件:选中即直传平台对象存储(`klt/contract/attachment/` 前缀),成功后把对象键写进草稿。
+   * 附件**选填**;已有附件的合同在编辑态先回显库里的键,重传即覆盖(⛔ 追加成多份)。
    */
   async function pickAttachment(file: File | null) {
     if (!file) return;
     setAttachmentError("");
     setAttachmentBusy(true);
     try {
-      const previous = draft.attachmentUrl.trim();
       const uploaded = await uploadContractAttachment(file);
-      if (previous && previous !== record.data?.attachment_url) {
-        discardPendingAttachments([previous]);
-      }
-      pendingAttachmentKeys.current = [
-        ...pendingAttachmentKeys.current.filter((key) => key !== previous),
-        uploaded.object_key,
-      ];
+      setAttachmentObj(uploaded);
       set("attachmentUrl", uploaded.object_key);
-      setAttachmentName(uploaded.file_name);
     } catch (e) {
-      // 失败⛔ 清掉上一份:用户点的是「更换」,换失败时旧附件仍在库里,草稿也保持旧值。
-      setAttachmentError((e as Error)?.message || "合同附件上传失败。");
+      setAttachmentError((e as Error)?.message || "附件上传失败。");
     } finally {
       setAttachmentBusy(false);
     }
   }
 
-  /** 现签查看地址只在「库里那一条=草稿这一条」时有效(刚换过/未保存的还没签)。 */
-  const attachmentView = useMemo(() => {
-    const current = draft.attachmentUrl.trim();
-    if (!current) return "";
-    const row = record.data;
-    if (row && row.attachment_url === current) return row.attachment_view_url ?? "";
-    return /^https?:\/\//i.test(current) ? current : "";
-  }, [draft.attachmentUrl, record.data]);
-  const attachmentLabelText = attachmentName || contractAttachmentLabel(draft.attachmentUrl);
-
   if (created) {
     const c = created.customer;
     return <section className="ops-page ops-record-page">
@@ -1041,9 +1154,9 @@ export function ContractEditorPage() {
   return <section className="ops-page ops-record-page contract-editor">
     <header className="ops-page-head">
       <div>
-        <p className="ops-eyebrow"><span /> 合同管理 · {editing ? "编辑" : "新增"}</p>
-        <h1>{editing ? "编辑合同" : "新增合同"}</h1>
-        <p>{editing ? `合同 ${no}` : "录入合同与固定套餐式、自定义规格式两类服务构成。"}</p>
+        <p className="ops-eyebrow"><span /> 合同管理 · {editing ? "编辑" : "签订"}</p>
+        <h1>{editing ? "编辑合同" : "合同签订表单"}</h1>
+        <p>{editing ? `合同 ${no}` : "采集客户、商务、订购额度与合规信息,用于生成合同快照、资源额度和后续工单的授权依据。"}</p>
       </div>
       <div className="ops-head-actions">
         <Button variant="outline" size="sm" onClick={() => navigate("/contracts")}><ArrowLeft size={15} />返回合同台账</Button>
@@ -1127,14 +1240,17 @@ export function ContractEditorPage() {
             */}
           {!editing && (
             <div className="ops-form-grid ops-form-grid--business contract-customer-fields">
-              <label htmlFor="inline-region"><span className="ops-field-title">所属区域 <b title="必填">*</b><FieldHint label="所属区域说明">客户挂载的区域节点;「全网」是平台虚根,不允许选中。选定后才反查运营商、合伙人、运营团队与运维团队。</FieldHint></span>
+              <label htmlFor="inline-region"><span className="ops-field-title">所属区域 <b title="必填">*</b><FieldHint label="所属区域说明">客户挂载的区域节点,从省一级开始选(「全网」是平台虚根,不下拉)。选定后才反查运营商、合伙人、运营团队与运维团队。</FieldHint></span>
                 <TreeSelect treeData={regionTreeShown} value={inline.regionId} onChange={(value) => setInlineField("regionId", value)} ariaLabel="所属区域" placeholder={lockedCustomerFields ? "客户档案未挂载区域" : "请选择区域节点"} name="inline-region" disabled={lockedCustomerFields} />
               </label>
-              <label htmlFor="inline-operator"><span className="ops-field-title">运营商 <b title="必填">*</b><FieldHint label="运营商说明">{provinceId ? "候选=所挂区域省份下可见的运营商档案;唯一候选自动选中,录入人身份命中时自动选中并只读。" : "先选所属区域:运营商档案须与该区域同省,否则建档会被省份一致性校验拦下。"}</FieldHint></span>
-                <select id="inline-operator" disabled={lockedCustomerFields || Boolean(lockedOperatorId) || !inline.regionId} value={inline.operatorId} onChange={(event) => setInlineField("operatorId", event.target.value)}>
-                  <option value="">{inline.regionId ? "请选择运营商" : "请先选择所属区域"}</option>
-                  {operatorChoices.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
-                </select>
+              <label htmlFor="inline-operator">
+                <RegionGate gated={!inline.regionId}>
+                  <span className="ops-field-title">运营商 <b title="必填">*</b><FieldHint label="运营商说明">{provinceId ? "候选=所挂区域省份下可见的运营商档案;唯一候选自动选中,录入人身份命中时自动选中并只读。" : "先选所属区域:运营商档案须与该区域同省,否则建档会被省份一致性校验拦下。"}</FieldHint></span>
+                  <select id="inline-operator" disabled={lockedCustomerFields || Boolean(lockedOperatorId) || !inline.regionId} value={inline.operatorId} onChange={(event) => setInlineField("operatorId", event.target.value)}>
+                    <option value="">{inline.regionId ? "请选择运营商" : "请先选取所属区域"}</option>
+                    {operatorChoices.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
+                  </select>
+                </RegionGate>
               </label>
               <label htmlFor="inline-address"><span className="ops-field-title">客户地址</span><Input id="inline-address" disabled={lockedCustomerFields} placeholder={lockedCustomerFields ? "客户档案未登记地址" : "客户地址(含楼栋与房间号)"} value={inline.address} onChange={(event) => setInlineField("address", event.target.value)} /></label>
               <div className="contract-contact-field">
@@ -1158,35 +1274,77 @@ export function ContractEditorPage() {
                   <Input aria-label="财务联系人电话" inputMode="tel" disabled={lockedCustomerFields} placeholder={lockedCustomerFields ? "未登记" : "手机号"} value={inline.financePhone} onChange={(event) => setInlineField("financePhone", event.target.value)} />
                 </div>
               </div>
-              <label htmlFor="inline-partner"><span className="ops-field-title">合伙人 <FieldHint label="合伙人说明">候选=负责范围覆盖所挂区域的合伙人;唯一候选自动选中,录入人身份命中时自动选中并只读,多个候选需手选。</FieldHint></span>
-                <select id="inline-partner" disabled={lockedCustomerFields || Boolean(lockedPartnerId) || !inline.regionId} value={inline.partnerId} onChange={(event) => setInlineField("partnerId", event.target.value)}>
-                  <option value="">{inline.regionId ? "未匹配合伙人" : "请先选择所属区域"}</option>
-                  {partnerChoices.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
-                </select>
+              <label htmlFor="inline-partner">
+                <RegionGate gated={!inline.regionId}>
+                  <span className="ops-field-title">合伙人 <FieldHint label="合伙人说明">候选=负责范围覆盖所挂区域的合伙人;唯一候选自动选中,录入人身份命中时自动选中并只读,多个候选需手选。</FieldHint></span>
+                  <select id="inline-partner" disabled={lockedCustomerFields || Boolean(lockedPartnerId) || !inline.regionId} value={inline.partnerId} onChange={(event) => setInlineField("partnerId", event.target.value)}>
+                    <option value="">{inline.regionId ? "未匹配合伙人" : "请先选取所属区域"}</option>
+                    {partnerChoices.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
+                  </select>
+                </RegionGate>
               </label>
-              <label htmlFor="inline-operations-team"><span className="ops-field-title">运营团队 <FieldHint label="运营团队说明">按所挂区域实时反查,仅用于展示、不写入客户档案;唯一候选自动选中,录入人身份命中时自动选中并只读,多个候选需手选。</FieldHint></span>
-                <select id="inline-operations-team" disabled={lockedCustomerFields || Boolean(lockedOperationsTeamId) || !inline.regionId} value={inline.operationsTeamId} onChange={(event) => setInlineField("operationsTeamId", event.target.value)}>
-                  <option value="">{!inline.regionId ? "请先选择所属区域" : lockedCustomerFields ? (regionOptions.operationsTeams.length ? "按区域反查有多个候选" : "所挂区域未匹配运营团队") : "未匹配运营团队"}</option>
-                  {regionOptions.operationsTeams.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
-                </select>
+              <label htmlFor="inline-operations-team">
+                <RegionGate gated={!inline.regionId}>
+                  <span className="ops-field-title">运营团队 <FieldHint label="运营团队说明">按所挂区域实时反查,仅用于展示、不写入客户档案;唯一候选自动选中,录入人身份命中时自动选中并只读,多个候选需手选。</FieldHint></span>
+                  <select id="inline-operations-team" disabled={lockedCustomerFields || Boolean(lockedOperationsTeamId) || !inline.regionId} value={inline.operationsTeamId} onChange={(event) => setInlineField("operationsTeamId", event.target.value)}>
+                    <option value="">{!inline.regionId ? "请先选取所属区域" : lockedCustomerFields ? (regionOptions.operationsTeams.length ? "按区域反查有多个候选" : "所挂区域未匹配运营团队") : "未匹配运营团队"}</option>
+                    {regionOptions.operationsTeams.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
+                  </select>
+                </RegionGate>
               </label>
-              <div className="customer-team-field"><span className="ops-field-title">运维团队 <b title="必填">*</b><FieldHint label="运维团队说明">单支定案:一个客户同一时刻恰好挂 1 支运维团队;候选=负责范围覆盖所挂区域的团队,唯一候选自动选中,录入人身份命中时自动选中并只读。</FieldHint></span>
-                <CustomerTeamSelect disabled={lockedCustomerFields || Boolean(lockedTeamId) || !inline.regionId} options={teamChoices.map((item) => ({ id: item.id, name: item.name, hint: (org.maintenanceTeams.find((team) => team.id === item.id)?.ticketTypes ?? []).join("、") }))} value={inline.teamId} onChange={(id) => setInlineField("teamId", id)} />
+              <div className="customer-team-field">
+                <RegionGate gated={!inline.regionId}>
+                  <span className="ops-field-title">运维团队 <b title="必填">*</b><FieldHint label="运维团队说明">单支定案:一个客户同一时刻恰好挂 1 支运维团队;候选=负责范围覆盖所挂区域的团队,唯一候选自动选中,录入人身份命中时自动选中并只读。</FieldHint></span>
+                  <CustomerTeamSelect disabled={lockedCustomerFields || Boolean(lockedTeamId) || !inline.regionId} options={teamChoices.map((item) => ({ id: item.id, name: item.name, hint: (org.maintenanceTeams.find((team) => team.id === item.id)?.ticketTypes ?? []).join("、") }))} value={inline.teamId} onChange={(id) => setInlineField("teamId", id)} />
+                </RegionGate>
               </div>
               <label htmlFor="inline-remark" className="ops-form-span-full"><span className="ops-field-title">客户备注 <small>选填</small><FieldHint label="客户备注说明">多行文本,≤512 字;随客户建档写入客户档案的备注列。命中已有客户时显示档案里的备注(只读)。</FieldHint></span>
                 <textarea id="inline-remark" rows={3} maxLength={512} disabled={lockedCustomerFields} placeholder={lockedCustomerFields ? "客户档案未登记备注" : "补充说明(≤512 字)"} value={inline.remark} onChange={(event) => setInlineField("remark", event.target.value)} />
               </label>
               {inline.subject === "enterprise" ? (
-                <div className="ops-form-span-2 customer-document-picker">
-                  <div><strong>营业执照影像(选填)</strong>
-                    <label className="customer-upload-button" title="选择后立即直传平台对象存储(字节流不经过本系统)">
-                      <Upload size={15} />{licenseBusy ? "正在上传…" : licenseObj ? "重新选择" : "选择文件"}
-                      <input aria-label="上传营业执照影像" type="file" disabled={licenseBusy || submitting || lockedCustomerFields} onChange={(event) => { const file = event.target.files?.[0] ?? null; event.target.value = ""; void pickLicense(file); }} />
-                    </label>
+                /**
+                 * 营业执照影像(2026-11-19 定案):整块拖曳上传区,点击任意位置同样可选文件。
+                 * 文件输入铺满整块(透明覆盖层)⇒ 点哪儿都能选;「移除」按钮抬到覆盖层之上才点得到。
+                 * 拖曳高亮只认「拖进来的确实是文件」——拖文字/选区进框会被浏览器当成 drop,
+                 * 不加判据会让整块闪一下又把 URL 写进地址栏。
+                 */
+                <>
+                  <div
+                    className={`ops-form-span-full contract-license-drop${licenseDragging ? " is-dragging" : ""}${lockedCustomerFields ? " is-locked" : ""}`}
+                    onDragEnter={(event) => { if (!hasFiles(event.dataTransfer)) return; event.preventDefault(); if (!licenseBusy && !submitting && !lockedCustomerFields) setLicenseDragging(true); }}
+                    onDragOver={(event) => { if (!hasFiles(event.dataTransfer)) return; event.preventDefault(); event.dataTransfer.dropEffect = licenseBusy || submitting || lockedCustomerFields ? "none" : "copy"; }}
+                    onDragLeave={(event) => { if (event.currentTarget.contains(event.relatedTarget as Node | null)) return; setLicenseDragging(false); }}
+                    onDrop={(event) => {
+                      event.preventDefault();
+                      setLicenseDragging(false);
+                      if (licenseBusy || submitting || lockedCustomerFields) return;
+                      const file = event.dataTransfer.files?.[0] ?? null;
+                      if (file) void pickLicense(file);
+                    }}
+                  >
+                    <span className="contract-license-drop-body">
+                      <Upload size={22} />
+                      <strong>营业执照影像(选填)</strong>
+                      <span>{licenseObj
+                        ? `已上传:${licenseObj.file_name}`
+                        : licenseBusy
+                          ? "正在上传…"
+                          : lockedCustomerFields
+                            ? archivedLicenseText
+                            : "拖曳图片到此处,或点击选择文件"}</span>
+                    </span>
+                    {licenseObj && !lockedCustomerFields && <Button type="button" variant="ghost" size="sm" className="contract-license-drop-remove" disabled={licenseBusy || submitting} onClick={() => { setLicenseObj(null); setLicenseError(""); }}><X size={15} />移除</Button>}
+                    <input
+                      className="contract-license-drop-input"
+                      aria-label="上传营业执照影像"
+                      type="file"
+                      accept="image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp,.pdf"
+                      disabled={licenseBusy || submitting || lockedCustomerFields}
+                      onChange={(event) => { const file = event.target.files?.[0] ?? null; event.target.value = ""; void pickLicense(file); }}
+                    />
                   </div>
-                  <p>{licenseObj ? `已上传:${licenseObj.file_name}` : lockedCustomerFields ? archivedLicenseText : "留空=建档后到客户档案「登记材料」格补传;营业执照影像选填。"}</p>
-                  {licenseError && <small className="customer-field-error">{licenseError}</small>}
-                </div>
+                  {licenseError && <small className="ops-form-span-full customer-field-error">{licenseError}</small>}
+                </>
               ) : null}
               {/* 客户主账号只在建档时录入:命中已有客户时它已经存在,⛔ 显示成「沿用已有客户档案」的空输入框。 */}
               {!lockedCustomerFields && <>
@@ -1200,10 +1358,10 @@ export function ContractEditorPage() {
         </section>
 
         <section className="ops-record-card">
-          <div className="customer-form-section-title"><span>02</span><div><h2>合同基本要素</h2><p>必填。金额与付款周期确定期间,结束日由生效日自动推算、不可手改。</p></div></div>
+          <div className="customer-form-section-title"><span>02</span><div><h2>合同基本信息</h2><p>商务归档口径,用于对账、到期提醒与版本追溯</p></div></div>
           {!editing && customerId && (
             <div className="contract-renew-block">
-              <label htmlFor="renew-from"><span className="ops-field-title">续签自旧合同 <small>可选</small><FieldHint label="续签自旧合同说明">选中即带出旧合同的合同金额、付款周期、服务条目与运营商经办人三件套,并把<b>合同生效日自动推为旧合同结束日的次日</b>(该日已早于今天时取今天,结束日再按付款周期推算);合同编号/外部单号/附件/交接日期仍按本合同填写(交接日期默认录入当日)。续签按「新订阅开通」落库:不截原、不挂替换边、不出第七类工单;<b>服务条目与旧合同逐条一致(形式/档位/份数/席位/带宽/出口,价格不算)时视为无需施工,不出开通工单</b>,新订阅按续签开始日记为已交付。</FieldHint></span>
+              <label htmlFor="renew-from"><span className="ops-field-title">续签自旧合同 <small>可选</small><FieldHint label="续签自旧合同说明">选中即带出旧合同的合同金额、服务期(月)、服务条目与运营商经办人三件套,并把<b>合同生效日自动推为旧合同结束日的次日</b>(该日已早于今天时取今天,结束日再按服务期(月)推算);合同编号/外部单号/附件/签署日期仍按本合同填写(签署日期默认录入当日)。续签按「新订阅开通」落库:不截原、不挂替换边、不出第七类工单;<b>服务条目与旧合同逐条一致(形式/档位/份数/席位/带宽/出口,价格不算)时视为无需施工,不出开通工单</b>,新订阅按续签开始日记为已交付。</FieldHint></span>
                 <select id="renew-from" value={renewFrom} disabled={renewLoading || submitting} onChange={(event) => void pickRenewal(event.target.value)}>
                   <option value="">不续签(手工录入)</option>
                   {/* 深链续签源若不在客户合同列表里(已归档等),补一个同文案的选项,⛔ 让下拉空着。 */}
@@ -1220,36 +1378,91 @@ export function ContractEditorPage() {
           <div className="ops-form-grid ops-form-grid--business">
             <label htmlFor="contract-no"><span className="ops-field-title">合同编号 <small>{editing ? "服务端生成" : "可选"}</small></span><Input id="contract-no" placeholder={editing ? "" : "不填由服务端生成"} value={draft.contractNo} disabled={editing} onChange={(event) => set("contractNo", event.target.value)} /></label>
             <label htmlFor="external-no"><span className="ops-field-title">外部单号</span><Input id="external-no" placeholder="外部单号" value={draft.externalNo} onChange={(event) => set("externalNo", event.target.value)} /></label>
-            <label htmlFor="contract-amount"><span className="ops-field-title">合同金额(元) <b title="必填">*</b></span><Input id="contract-amount" inputMode="decimal" placeholder="0.00" aria-invalid={invalidOf("amount")} value={draft.amount} onChange={(event) => set("amount", event.target.value)} />{requiredErrorOf("amount")}</label>
-            <label htmlFor="pay-cycle"><span className="ops-field-title">付款周期 <b title="必填">*</b></span><select id="pay-cycle" aria-invalid={invalidOf("payCycle")} value={draft.payCycle} onChange={(event) => set("payCycle", event.target.value)}><option value="">未配置</option>{OPTIONS.pay_cycle.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</select>{requiredErrorOf("payCycle")}</label>
-            <label htmlFor="start-date"><span className="ops-field-title">合同生效日 <b title="必填">*</b></span><Input id="start-date" type="date" aria-invalid={invalidOf("start")} value={draft.start} onChange={(event) => set("start", event.target.value)} />{requiredErrorOf("start")}</label>
-            <label htmlFor="end-date"><span className="ops-field-title">合同结束日 <small>自动推算</small><FieldHint label="合同结束日说明">{draft.start && draft.payCycle ? <>=生效日+付款周期(年付 12/季付 3/月付 1 个月)再减一天,该月无对应日先取月末;<b>不可手改</b>,改生效日或付款周期即自动重算。</> : <>先填「合同生效日」与「付款周期」,结束日自动算出,<b>不可手改</b>。</>}</FieldHint></span><Input id="end-date" type="date" value={draft.end} readOnly aria-readonly="true" className="cursor-not-allowed bg-muted/40" /></label>
-            {/* 运营商经办人=交接单口径的三段,独占一行(机构/姓名/联系方式),⛔ 与上面六个商务格混排。 */}
-            <div className="ops-form-span-full contract-agent-block">
-              <span className="ops-field-title">运营商经办人</span>
-              <div className="ops-form-grid contract-agent-grid">
-                <label htmlFor="agent-org"><span className="ops-field-title">机构 <small>选填</small><FieldHint label="经办人机构说明">选填,不填也可提交;清空后保存即清除已记录的机构。</FieldHint></span><Input id="agent-org" placeholder="经办人所属机构" value={draft.agentOrg} onChange={(event) => set("agentOrg", event.target.value)} /></label>
-                <label htmlFor="agent-name"><span className="ops-field-title">姓名 <b title="必填">*</b></span><Input id="agent-name" aria-invalid={invalidOf("agent")} value={draft.agent} onChange={(event) => set("agent", event.target.value)} />{requiredErrorOf("agent")}</label>
-                <label htmlFor="agent-phone"><span className="ops-field-title">联系方式 <b title="必填">*</b><FieldHint label="经办人联系方式说明">必填。当前登录身份未提供手机号时留空,请手工录入经办人实际联系电话。</FieldHint></span><Input id="agent-phone" inputMode="numeric" aria-invalid={invalidOf("agentPhone")} value={draft.agentPhone} onChange={(event) => set("agentPhone", event.target.value)} />{requiredErrorOf("agentPhone")}</label>
-              </div>
-            </div>
+            <label htmlFor="contract-type"><span className="ops-field-title">合同类型 <b title="必填">*</b><FieldHint label="合同类型说明">新建=新签(可新开链路);续签=接在本客户某份旧合同之后,须选「续签自旧合同」;扩容补充协议=在既有链路上只叠加附加项(服务构成整批为增量条目);变更协议=可含逐条替换的变更。类型决定 03 服务构成的录入模式,建后不改。</FieldHint></span>
+              <select id="contract-type" value={draft.contractType} disabled={editing} onChange={(event) => pickContractType(event.target.value)}>
+                {CONTRACT_TYPES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
+              </select>
+            </label>
+
             {/*
-              * 录入经办人=界面录入账号,服务端从鉴权上下文写入(⛔ 入参、建后恒只读):
-              * 机构取账号绑定团队(运营/运维团队名,`hq` 回落「总运营」)、姓名取账号显示名、联系方式取绑定手机号(出参已掩码)。
-              * 新建态只在提交后才拿得到机构,故此处不给可编辑控件,⛔ 让前端「代填」一个值造成与后端不一致。
-              * 独占一行(`ops-form-span-full`),⛔ 与运营商经办人挤在同一行。
+              * 运营商经办人=姓名+联系电话(2026-11-19 三列排布):两项必填、成对录入。
+              * 机构不再采集(业主 2026-11-19 定案):`agentOrg` 仍随草稿原样回传,
+              * 存量合同已记录的机构⛔ 被本次保存清空,但本页不再提供录入格。
               */}
-            <div className="ops-form-span-full contract-agent-readonly">
-              <span className="ops-field-title">录入经办人 <small>=当前录入账号,提交时自动带入</small><FieldHint label="录入经办人说明">这三段由录入时账号自动带入,建后恒只读(KLT-L221),不得手工改。</FieldHint></span>
-              <div className="contract-inline-group">
-                <span className="contract-inline-seg"><small>机构</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_org || "未记录" : "取账号绑定团队"}</span></span>
-                <span className="contract-inline-seg"><small>姓名</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_name || record.data?.created_by || "未记录" : identity?.name || "未登录"}</span></span>
-                <span className="contract-inline-seg"><small>联系方式</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_mobile || "未绑定" : identity?.phone || "账号未绑手机号"}</span></span>
+            <div className="contract-agent-cell">
+              <span className="ops-field-title">运营商经办人 <b title="必填">*</b><FieldHint label="运营商经办人说明">运营商侧的对接人(<b>不是</b>录入账号,页面不预填):姓名与联系电话必填、成对录入。</FieldHint></span>
+              <div className="contract-agent-combo">
+                <Input id="agent-name" aria-label="运营商经办人姓名" placeholder="姓名" aria-invalid={invalidOf("agent")} value={draft.agent} onChange={(event) => set("agent", event.target.value)} />
+                <Input id="agent-phone" aria-label="运营商经办人电话" inputMode="numeric" placeholder="联系电话" aria-invalid={invalidOf("agentPhone")} value={draft.agentPhone} onChange={(event) => set("agentPhone", event.target.value)} />
               </div>
+              {requiredErrorOf("agent")}{requiredErrorOf("agentPhone")}
+            </div>
+            <label htmlFor="sign-date"><span className="ops-field-title">签署日期 <b title="必填">*</b><FieldHint label="签署日期说明">交接日期即签署日期(2026-11-19 定案),表单只留这一格;提交时同值写入合同的签署日期与交接日期两列。新建默认录入当日。</FieldHint></span><Input id="sign-date" type="date" aria-invalid={invalidOf("signDate")} value={draft.signDate} onChange={(event) => set("signDate", event.target.value)} />{requiredErrorOf("signDate")}</label>
+            <label htmlFor="contract-amount"><span className="ops-field-title">合同金额(元) <b title="必填">*</b></span><Input id="contract-amount" inputMode="decimal" placeholder="0.00" aria-invalid={invalidOf("amount")} value={draft.amount} onChange={(event) => set("amount", event.target.value)} />{requiredErrorOf("amount")}</label>
+
+            {/* 服务期(月):替代原「付款周期」,标题右侧挂月/季/年/3 年快捷档(点一下直接填月数)。 */}
+            <div className="contract-months-cell">
+              <span className="ops-field-title">服务期(月) <b title="必填">*</b>
+                <span className="contract-months-presets" role="group" aria-label="服务期快捷档">
+                  {SERVICE_MONTH_PRESETS.map((preset) => {
+                    const active = draft.serviceMonths.trim() === String(preset.months);
+                    return <button key={preset.months} type="button" className={active ? "is-active" : ""} aria-pressed={active} onClick={() => set("serviceMonths", String(preset.months))}>{preset.label}</button>;
+                  })}
+                </span>
+                <FieldHint label="服务期说明">可填 1~600 的整数月;也可点标题右侧的快捷档(月 1/季 3/年 12/3 年 36)。到期日期=生效日+服务期(月)−1 天,该月无对应日先取月末,不可手改。</FieldHint>
+              </span>
+              <Input id="service-months" type="number" min={1} max={600} step={1} inputMode="numeric" placeholder="1~600" aria-invalid={invalidOf("serviceMonths")} value={draft.serviceMonths} onChange={(event) => set("serviceMonths", event.target.value)} />
+              {requiredErrorOf("serviceMonths")}
             </div>
-            <label htmlFor="handover-on"><span className="ops-field-title">交接日期 <b title="必填">*</b></span><Input id="handover-on" type="date" aria-invalid={invalidOf("handoverOn")} value={draft.handoverOn} onChange={(event) => set("handoverOn", event.target.value)} />{requiredErrorOf("handoverOn")}</label>
+            <label htmlFor="start-date"><span className="ops-field-title">生效日期 <b title="必填">*</b></span><Input id="start-date" type="date" aria-invalid={invalidOf("start")} value={draft.start} onChange={(event) => set("start", event.target.value)} />{requiredErrorOf("start")}</label>
+            <label htmlFor="end-date"><span className="ops-field-title">到期日期 <small>自动推算</small><FieldHint label="到期日期说明">{draft.start && draft.serviceMonths ? <>=生效日+服务期(月)再减一天,该月无对应日先取月末;<b>不可手改</b>,改生效日或服务期即自动重算。</> : <>先填「生效日期」与「服务期(月)」,到期日期自动算出,<b>不可手改</b>。</>}</FieldHint></span><Input id="end-date" type="date" value={draft.end} readOnly aria-readonly="true" className="cursor-not-allowed bg-muted/40" /></label>
           </div>
-          {record.data?.source_label !== undefined && <p className="contract-form-summary">来源:{record.data.source_label === null ? WORD_UNCONFIGURED : record.data.source_label}{record.data.pay_cycle ? `;付款周期 ${record.data.pay_cycle} → ${label(PAY_CYCLE, record.data.pay_cycle)}` : ""}</p>}
+          {draft.contractType === "renew" && !renewFrom && !editing && <p className="ops-field-note contract-type-hint">合同类型为「续签」:请在上方「续签自旧合同」选定旧合同,否则提交会被类型校验拦下。</p>}
+          {draft.contractType === "expand" && <p className="ops-field-note contract-type-hint">合同类型为「扩容补充协议」:03 服务构成须全部为增量附加项(引用本客户既有跨境链路订阅,不新开链路)。</p>}
+          {/*
+            * 「录入经办人」块已下线(业主 2026-11-19):录入账号由服务端从鉴权上下文写入
+            * (`created_by*` 三列、建后恒只读 KLT-L221),合同表单不必再回显一遍——
+            * 它在合同详情页仍是独立只读行,需要核对时到详情页看。
+            */}
+          {/**
+            * 合同附件(业主 2026-11-19 定案):样式与「营业执照影像」同一块拖曳卡片,位置固定在 02 最下面。
+            * 选填;单值覆盖(重传即替换),提交时把一个对象键交给 `attachment_url`。
+            */}
+          <div
+            className={`contract-license-drop contract-attachment-drop${attachmentDragging ? " is-dragging" : ""}${attachmentBusy || submitting ? " is-locked" : ""}`}
+            onDragEnter={(event) => { if (!hasFiles(event.dataTransfer)) return; event.preventDefault(); if (!attachmentBusy && !submitting) setAttachmentDragging(true); }}
+            onDragOver={(event) => { if (!hasFiles(event.dataTransfer)) return; event.preventDefault(); event.dataTransfer.dropEffect = attachmentBusy || submitting ? "none" : "copy"; }}
+            onDragLeave={(event) => { if (event.currentTarget.contains(event.relatedTarget as Node | null)) return; setAttachmentDragging(false); }}
+            onDrop={(event) => {
+              event.preventDefault();
+              setAttachmentDragging(false);
+              if (attachmentBusy || submitting) return;
+              const file = event.dataTransfer.files?.[0] ?? null;
+              if (file) void pickAttachment(file);
+            }}
+          >
+            <span className="contract-license-drop-body">
+              <Upload size={22} />
+              <strong>合同附件(选填)</strong>
+              <span>{attachmentObj
+                ? `已上传:${attachmentObj.file_name}`
+                : attachmentBusy
+                  ? "正在上传…"
+                  : draft.attachmentUrl
+                    ? `已登记:${draft.attachmentUrl.split("/").slice(-1)[0]}`
+                    : "拖曳合同扫描件(PDF/图片)到此处,或点击选择文件"}</span>
+            </span>
+            {(attachmentObj || draft.attachmentUrl) && <Button type="button" variant="ghost" size="sm" className="contract-license-drop-remove" disabled={attachmentBusy || submitting} onClick={() => { setAttachmentObj(null); setAttachmentError(""); set("attachmentUrl", ""); }}><X size={15} />移除</Button>}
+            <input
+              className="contract-license-drop-input"
+              aria-label="上传合同附件"
+              type="file"
+              accept="image/png,image/jpeg,image/webp,application/pdf,.png,.jpg,.jpeg,.webp,.pdf"
+              disabled={attachmentBusy || submitting}
+              onChange={(event) => { const file = event.target.files?.[0] ?? null; event.target.value = ""; void pickAttachment(file); }}
+            />
+          </div>
+          {attachmentError && <small className="customer-field-error">{attachmentError}</small>}
         </section>
 
         <section className="ops-record-card">
@@ -1260,15 +1473,8 @@ export function ContractEditorPage() {
               * P1(D-9)增量合同:树的第一层是**被引用的既有链路订阅**(本合同没有链路条目),
               * 整行只读(灰底+锁标),本合同的附加项只能挂在这条引用下面。
               */}
-            {!editing && (
-              <div className="ops-form-span-full contract-increment-mode">
-                <label className="ops-field-title">合同类型<FieldHint label="合同类型说明">{draft.increment ? "增量合同⛔ 新建链路:只能引用本客户一条在期跨境链路订阅(可跨合同),并在其下叠加附加项(D-9)。" : "普通合同可新建跨境链路,并在任意链路节点下挂附加项(D-7)。"}</FieldHint></label>
-                <div className="contract-increment-switch">
-                  <Button type="button" variant={draft.increment ? "default" : "outline"} size="sm" aria-pressed={!draft.increment} onClick={() => toggleIncrement(false)}>普通合同(新建链路)</Button>
-                  <Button type="button" variant={draft.increment ? "default" : "outline"} size="sm" aria-pressed={draft.increment} onClick={() => toggleIncrement(true)}>增量合同(链路已在用、只补附加项)</Button>
-                </div>
-              </div>
-            )}
+            {/* 合同类型已上移到 02 合同基本信息(2026-11-19):此处只按类型呈现录入模式,⛔ 再给一套并行的类型开关。 */}
+            {draft.increment && !editing && <p className="ops-form-span-full contract-form-summary">合同类型为「扩容补充协议」:不新建链路,只引用本客户一条在期跨境链路订阅并叠加附加项(D-9)。</p>}
             {draft.increment && !editing && (
               <div className="ops-form-span-full">
                 <label htmlFor="increment-link"><span className="ops-field-title">引用既有跨境链路订阅 <b title="必填">*</b><FieldHint label="引用既有跨境链路订阅说明">只列本客户 status=active、未到期、plan_family=link 的订阅;引用后该节点只读,要换链路请另开一份增量合同,⛔ 在原合同上改引。</FieldHint></span></label>
@@ -1397,61 +1603,36 @@ export function ContractEditorPage() {
           </div>
         </section>
 
-        <div className="ops-record-pair">
-          <section className="ops-record-card">
-            <div className="customer-form-section-title"><span>04</span><div><h2>境外 IP</h2><p>随服务构成核定。</p></div></div>
-            <p className="contract-form-summary">固定 IP 条目已下线(2026-11-17):境外 IP 不再在合同上单独登记「线路出口+带宽档位+IP 数量」三元组,改由<strong>上方服务构成里选「叠加增值」档位并填份数</strong>表达(例:单独境外 IP 选 2 份=2 个 IP;不可叠加档份数恒 1)。</p>
-            <p className="contract-form-summary">存量 IP 条目保留在库里仅供追溯,本页不再展示、也不再随合同提交;后端读口同样不再下发 `ip_entries`。</p>
-          </section>
-          <section className="ops-record-card">
-            <div className="customer-form-section-title"><span>05</span><div><h2>合同附件</h2><p>可选 · 单份。</p></div></div>
-            <div className="ops-contract-upload-list">
-              {draft.attachmentUrl.trim()
-                ? <div><span>{attachmentLabelText} · 已上传</span></div>
-                : <div><Tri tone="missing" text={WORD_UNCONFIGURED} title="尚未选择附件文件" /></div>}
-            </div>
-            <input
-              ref={attachmentInput}
-              type="file"
-              accept=".pdf,.ofd,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx"
-              hidden
-              aria-label="选择合同附件文件"
-              onChange={(event) => { void pickAttachment(event.target.files?.[0] ?? null); event.target.value = ""; }}
-            />
-            <div className="ops-contract-item-actions">
-              <Button variant="outline" size="sm" disabled={attachmentBusy || submitting} onClick={() => attachmentInput.current?.click()}>
-                <Upload size={15} />{attachmentBusy ? "正在上传…" : draft.attachmentUrl.trim() ? "更换附件" : "选择并上传附件"}
-              </Button>
-              {attachmentView && <Button variant="ghost" size="sm" onClick={() => window.open(attachmentView, "_blank", "noopener,noreferrer")}>查看附件</Button>}
-              {draft.attachmentUrl.trim() && <Button variant="ghost" size="sm" disabled={attachmentBusy || submitting} onClick={() => {
-                // 移除的若是「本页刚上传、还没落库」的那一份 ⇒ 它当场失去引用,立即退回;
-                // 库里那份仍被合同引用(保存后才由写口回收),这里⛔ 提前删。
-                const current = draft.attachmentUrl.trim();
-                if (current && current !== record.data?.attachment_url) discardPendingAttachments([current]);
-                set("attachmentUrl", ""); setAttachmentName(""); setAttachmentError("");
-              }}><X size={15} />移除</Button>}
-            </div>
-            {attachmentError && <p className="ops-form-error" role="alert">{attachmentError}</p>}
-            <p className="contract-form-summary">文件选中即直传平台对象存储(字节流与上传凭证都不经本服务),成功后随合同保存对象键;单份,重传即替换,保存前不影响库里已有附件。查看地址由详情读口按需现签。</p>
-          </section>
-        </div>
       </div>
 
       <aside className="ops-record-side">
+        {/* 业务口径摘要(原型同款):随所选档位×份数实时汇总,⛔ 手填。 */}
+        <section className="ops-record-card">
+          <h2>业务口径摘要</h2>
+          <div className="ops-contract-summary contract-side-kv">
+            <div><span>订购项</span><strong>{sideMetrics.items} 条</strong></div>
+            <div><span>带宽合计</span><strong>{sideMetrics.bandwidth}</strong></div>
+            <div><span>境外固定 IP</span><strong>{sideMetrics.ip}</strong></div>
+            <div><span>账号上限</span><strong>{sideMetrics.quota}</strong></div>
+            <div><span>月度费用合计</span><strong>{sideMetrics.fee}</strong></div>
+          </div>
+        </section>
+
         <section className="ops-record-card">
-          <h2>提交校验</h2>
-          <div className="ops-contract-summary">
-            <div><span>客户</span><strong>{editing ? customerLabel : (customerId ? (candidates.find((item) => item.customer_id === customerId)?.customer_name || customerTerm.trim() || WORD_UNCONFIGURED) : freeText ? `${customerTerm.trim()}(自由录入)` : "待填写")}</strong></div>
-            <div><span>合同编号</span><strong>{draft.contractNo || "服务端生成"}</strong></div>
-            <div><span>合同金额</span><strong>{/^\d+(?:\.\d{1,2})?$/.test(draft.amount.trim()) ? `¥${Number(draft.amount).toLocaleString("zh-CN")}` : "待填写"}</strong></div>
-            <div><span>付款周期</span><strong>{draft.payCycle ? label(PAY_CYCLE, draft.payCycle) : WORD_UNCONFIGURED}</strong></div>
-            <div><span>合同期间</span><strong>{draft.start && draft.end ? `${draft.start} 至 ${draft.end}` : "待填写"}</strong></div>
-            <div><span>构成条目</span><strong>{draft.items.length} 个</strong></div>
-            <div><span>替换原订阅</span><strong>{renewFrom ? "续签(按新订阅开通,不替换原订阅)" : (() => { const picked = draft.items.filter((item) => item.replacesSubscriptionId); return picked.length ? `${picked.length} 条(升降配)` : "无(按新订阅开通)"; })()}</strong></div>
-            <div><span>附件</span><strong>{draft.attachmentUrl.trim() ? (attachmentBusy ? "上传中…" : attachmentLabelText) : "无附件"}</strong></div>
+          <h2>必填完成度</h2>
+          <div className="contract-progress" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={requiredProgress.pct} aria-label="必填完成度"><i style={{ width: `${requiredProgress.pct}%` }} /></div>
+          <div className="ops-contract-summary contract-side-kv">
+            <div><span>已填 / 必填</span><strong>{requiredProgress.done} / {requiredProgress.total}</strong></div>
           </div>
+        </section>
+
+        {/* 动作区(2026-11-19):不再列「提交后系统生成」说明,只留提交与取消。 */}
+        <section className="ops-record-card">
           {error && <p className="ops-form-error" role="alert">{error}</p>}
-          <div className="ops-form-actions"><Button size="sm" variant="outline" onClick={() => navigate(-1)}>取消</Button><Button size="sm" disabled={submitting || attachmentBusy || replacementBusy || (editing && record.loading)} onClick={save}>{submitting ? "正在提交…" : replacementBusy ? "正在比对替换候选…" : editing ? "保存修改" : "提交合同"}</Button></div>
+          <div className="ops-form-actions">
+            <Button size="sm" disabled={submitting || replacementBusy || (editing && record.loading)} onClick={save}>{submitting ? "正在提交…" : replacementBusy ? "正在比对替换候选…" : editing ? "保存修改" : "校验并提交"}</Button>
+            <Button size="sm" variant="outline" onClick={() => navigate(-1)}>取消</Button>
+          </div>
         </section>
       </aside>
     </div>}

+ 4 - 4
web-scaffold/src/pages/ContractManagementPage.tsx

@@ -109,7 +109,7 @@ export function ContractManagementPage() {
         <FilterSelect icon="source" aria-label="来源筛选" value={source} onChange={(event) => { setSource(event.target.value); paging.resetPage(); }}><option>全部来源</option>{[...new Set(["运营商同步", "界面录入", "批量导入", ...sources])].map((item) => <option key={item}>{item}</option>)}</FilterSelect>
         {hasFilter && <Button variant="ghost" size="sm" onClick={reset}>重置筛选</Button>}
       </div>
-      <div ref={tableOverflow.ref} tabIndex={0} role="region" aria-label="合同台账,可横向滚动查看字段" className={`measured-table-scroll ops-table-wrap contract-table-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}><table className="ops-table ops-clickable-table contract-ledger"><OpsTableColumns widths={columnWidths} /><thead><tr><th>合同 / 客户</th><th>外部单号</th><th>状态 / 期间</th><th>是否已开通</th><th>总额 / 周期</th><th>经办人</th><th>操作</th></tr></thead><tbody>{pageRows.map((item) => {
+      <div ref={tableOverflow.ref} tabIndex={0} role="region" aria-label="合同台账,可横向滚动查看字段" className={`measured-table-scroll ops-table-wrap contract-table-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}><table className="ops-table ops-clickable-table contract-ledger"><OpsTableColumns widths={columnWidths} /><thead><tr><th>合同 / 客户</th><th>外部单号</th><th>状态 / 期间</th><th>是否已开通</th><th>总额 / 服务期</th><th>经办人</th><th>操作</th></tr></thead><tbody>{pageRows.map((item) => {
         const state = statusOf(item);
         const link = encodeURIComponent(item.contractId || item.no);
         /**
@@ -119,14 +119,14 @@ export function ContractManagementPage() {
         const expiringRow = isExpiringSoon(item.end);
         const renewContractId = item.contractId ?? "";
         return <tr key={item.contractId || item.no} tabIndex={0} aria-label={`查看合同 ${item.no}`} onClick={() => navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } })} onKeyDown={(event) => { if (event.key === "Enter" && event.target === event.currentTarget) navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } }); }}>
-          <td><strong title={item.no}>{item.no || WORD_UNCONFIGURED}</strong><small title={`${item.customer} · ${item.source ?? ""}`}>{item.customer || WORD_UNCONFIGURED} · {item.source === undefined ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端合同读口未返回 source 列(服务版本落后于 20261115000002 迁移)——如实标未下发,不填 manual 冒充" /> : textCell(item.source)}</small></td>
+          <td><strong title={item.no}>{item.no || WORD_UNCONFIGURED}</strong><small title={`${item.customer} · ${item.source ?? ""}`}>{item.customer || WORD_UNCONFIGURED} · {item.contractType || "新建"} · {item.source === undefined ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端合同读口未返回 source 列(服务版本落后于 20261115000002 迁移)——如实标未下发,不填 manual 冒充" /> : textCell(item.source)}</small></td>
           <td title={item.extNo || undefined}>{item.extNo ? <span className="ops-mono">{item.extNo}</span> : "—"}</td>
           <td>{state ? <OpsStatus tone={contractStatusTone[state]}>{state}</OpsStatus> : <Tri tone={item.periodState === "fail" ? "fail" : "missing"} text={item.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="缺少生效日或结束日,状态不可判" />}{expiringRow && <OpsStatus tone="warning">快到期 · {expiringLabel(item.end)}</OpsStatus>}<small>{item.periodState === "val" ? `${d(item.start)} 至 ${d(item.end)}` : <Tri tone={item.periodState === "fail" ? "fail" : "missing"} text={item.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
           <td>{item.opened === undefined || item.opened === null ? <Tri tone={item.opened === undefined ? "fail" : "missing"} text={item.opened === undefined ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="是否已开通取关联工单回填,取数失败只坏本列" /> : <OpsStatus tone={item.opened ? "success" : "warning"}>{item.opened ? "已开通" : "未开通"}</OpsStatus>}<small>实际开通日 {item.openedOn ? d(item.openedOn) : "未回填"}</small></td>
-          <td>{item.amountState === "val" ? <span className="ops-money">¥{item.amount.toLocaleString("zh-CN")}</span> : <Tri tone={item.amountState === "fail" ? "fail" : "missing"} text={item.amountState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}<small>{item.payCycleState === "val" ? item.payCycle : <Tri tone={item.payCycleState === "fail" ? "fail" : "missing"} text={item.payCycleState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
+          <td>{item.amountState === "val" ? <span className="ops-money">¥{item.amount.toLocaleString("zh-CN")}</span> : <Tri tone={item.amountState === "fail" ? "fail" : "missing"} text={item.amountState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}<small>{item.serviceMonthsState === "val" ? `服务期 ${item.serviceMonths} 个月` : <Tri tone={item.serviceMonthsState === "fail" ? "fail" : "missing"} text={item.serviceMonthsState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
           <td><strong>{item.agent || WORD_UNCONFIGURED}</strong><small>{item.agentPhone || WORD_UNCONFIGURED}</small></td>
 <td><div className="ops-inline-actions"><button type="button" onClick={(event) => { event.stopPropagation(); navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } }); }}>详情</button>{!view.readOnly && <OpsResponsiveActions expanded={expandedActions} items={[
-            ...(expiringRow && renewContractId ? [{ label: "续签合同", shortLabel: "续签", icon: <CalendarClock size={15} />, title: "按旧合同带入金额、付款周期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅", onSelect: () => navigate(`/contracts/new?renew=${encodeURIComponent(renewContractId)}`) }] : []),
+            ...(expiringRow && renewContractId ? [{ label: "续签合同", shortLabel: "续签", icon: <CalendarClock size={15} />, title: "按旧合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅", onSelect: () => navigate(`/contracts/new?renew=${encodeURIComponent(renewContractId)}`) }] : []),
             { label: "删除合同", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, title: "引用拦截由服务端判定,删除后不可恢复", onSelect: () => setDeleteId(item.contractId ?? item.no) },
           ]} />}</div></td>
         </tr>;

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 15 - 13
web-scaffold/src/pages/ContractRecordPage.tsx


+ 4 - 1
web-scaffold/src/pages/PartyViewPages.tsx

@@ -27,6 +27,7 @@ import { Input } from "../components/ui/input";
 import { FilterSelect } from "../components/ui/filter-select";
 import { OpsNotice, OpsStatus, OpsTableEmpty, OpsTag } from "../components/OperationsKit";
 import { Tri } from "../components/triState";
+import { CONTRACT_TYPE_LABEL } from "../domain/contract-draft";
 import { hasBizCode } from "../lib/api/http";
 import {
   billGetDetail,
@@ -925,7 +926,9 @@ export function PartyContractDetailPage({ kind }: { kind: "partner" | "operator"
               <tr><th>客户名称</th><td>{data.customer_name ?? "—"}</td></tr>
               <tr><th>合同期间</th><td>{data.start_date ?? "—"} ~ {data.end_date ?? "—"}</td></tr>
               <tr><th>状态</th><td>{data.status}</td></tr>
-              <tr><th>付款周期</th><td>{data.pay_cycle ?? "—"}</td></tr>
+              <tr><th>合同类型</th><td>{data.contract_type ? (CONTRACT_TYPE_LABEL[data.contract_type] ?? data.contract_type) : "—"}</td></tr>
+              <tr><th>签署日期</th><td>{data.sign_date ?? "—"}</td></tr>
+              <tr><th>服务期(月)</th><td>{data.service_months ?? "—"}</td></tr>
               <tr><th>合同金额</th><td>{moneyFromCents(data.contract_amount_cents)}</td></tr>
             </tbody>
           </table>

+ 51 - 5
web-scaffold/src/styles/operations.css

@@ -455,8 +455,6 @@ button.ops-contract-exit.is-active svg { opacity: .7; }
 .order-record-inline-link:hover { text-decoration:underline; }
 .ops-contract-upload { display:inline-flex;align-items:center;gap:10px;padding:9px 13px;border:1px solid var(--border);border-radius:7px;color:var(--primary);font-weight:650;cursor:pointer; }
 .ops-contract-upload input { max-width:230px;font-size:var(--type-support); }
-.ops-contract-upload-list { display:grid;gap:7px;margin-top:12px; }
-.ops-contract-upload-list>div { display:flex;align-items:center;justify-content:space-between;gap:10px;padding:7px 10px;border:1px solid var(--border);border-radius:6px;font-size:var(--type-body); }
 .ops-form-grid--business { grid-template-columns:repeat(3,minmax(0,1fr)); }
 @media(max-width:1100px){.ops-form-grid--business{grid-template-columns:repeat(2,minmax(0,1fr))}}
 @media(max-width:600px){.ops-form-grid--business{grid-template-columns:1fr}}
@@ -676,6 +674,49 @@ button.ops-contract-exit.is-active svg { opacity: .7; }
 .contract-contact-field { display: grid; gap: 7px; min-width: 0; color: var(--field-label); font-size: var(--type-support); font-weight: 400; }
 .contract-contact-field > .ops-field-title { display: inline-flex; align-items: baseline; gap: 3px; white-space: nowrap; }
 .contract-contact-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); gap: 6px; }
+/* 合同基本信息三列排布(2026-11-19):运营商经办人=姓名/电话并排+机构一行;
+   服务期(月)标题右侧挂「月/季/年/3 年」快捷档,点一下直接填月数。 */
+.contract-agent-cell { display: flex; flex-direction: column; gap: 6px; min-width: 0; color: var(--field-label); font-size: var(--type-support); font-weight: 400; }
+.contract-agent-cell > .ops-field-title { display: inline-flex; align-items: baseline; gap: 3px; white-space: nowrap; }
+.contract-agent-combo { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; }
+.contract-months-cell { display: flex; flex-direction: column; gap: 6px; min-width: 0; color: var(--field-label); font-size: var(--type-support); font-weight: 400; }
+.contract-months-cell > .ops-field-title { display: flex; align-items: center; flex-wrap: wrap; gap: 3px 6px; min-height: 19px; }
+.contract-months-presets { display: inline-flex; gap: 4px; margin-left: auto; }
+.contract-months-presets > button { padding: 1px 7px; border: 1px solid var(--border); border-radius: 999px; background: var(--card); color: var(--text-secondary); font: inherit; font-size: var(--type-meta); line-height: 1.5; cursor: pointer; }
+.contract-months-presets > button:hover { border-color: var(--primary-border); color: var(--primary); }
+.contract-months-presets > button.is-active { border-color: var(--primary); background: var(--primary-soft); color: var(--primary); font-weight: 600; }
+.contract-type-hint { margin-top: 10px; }
+/*
+ * 营业执照影像=整块拖曳上传区(2026-11-19):虚线边框+图标+一行提示,点哪儿都能选文件。
+ * 文件输入铺满整块(透明)⇒ 点击与拖入同一入口;「移除」按钮抬到覆盖层之上。
+ * 拖曳悬停高亮(is-dragging)、只读态置灰(is-locked)。
+ */
+.contract-license-drop { position: relative; display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; padding: 16px 18px; border: 1.5px dashed var(--border); border-radius: 9px; background: var(--surface-subtle); transition: border-color .15s ease, background .15s ease; }
+.contract-license-drop.is-dragging { border-color: var(--primary); background: var(--primary-soft); }
+.contract-license-drop.is-locked { opacity: .72; }
+/* 聚焦环由覆盖层文件输入自带的 `:focus` 轮廓给出(卡片边框即整块轮廓),⛔ 再叠一层。 */
+.contract-license-drop-body { display: flex; flex: 1 1 260px; align-items: center; gap: 10px; min-width: 0; color: var(--text-secondary); }
+.contract-license-drop-body > svg { flex: none; color: var(--primary); }
+.contract-license-drop-body > strong { flex: none; color: var(--field-label); font-size: var(--type-body); font-weight: 400; }
+.contract-license-drop-body > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--type-support); }
+.contract-license-drop > input.contract-license-drop-input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; padding: 0; opacity: 0; cursor: pointer; }
+.contract-license-drop > input.contract-license-drop-input:disabled { cursor: not-allowed; }
+.contract-license-drop-remove { position: relative; z-index: 1; flex: none; }
+/* 合同附件(2026-11-19):沿用营业执照影像那块拖曳卡片,位置固定在 02 合同基本信息最下面。 */
+.contract-attachment-drop { margin-top: 14px; }
+/* 右侧卡片:业务口径摘要/必填完成度(标题在左、值在右)+动作区。 */
+.contract-progress { height: 8px; margin: 2px 0 14px; border-radius: 999px; background: var(--muted); overflow: hidden; }
+/* 右侧卡片改用「标题在左、值在右」的横向行(2026-11-19):一屏放下更多口径,⛔ 标题/值上下堆叠白占高度。 */
+.ops-contract-summary.contract-side-kv { gap: 0; }
+.ops-contract-summary.contract-side-kv > div { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; padding: 7px 0; }
+.ops-contract-summary.contract-side-kv > div:first-child { padding-top: 0; }
+.ops-contract-summary.contract-side-kv > div:last-child { padding-bottom: 0; }
+.ops-contract-summary.contract-side-kv > div > span { flex: none; white-space: nowrap; }
+.ops-contract-summary.contract-side-kv > div > strong { min-width: 0; text-align: right; font-variant-numeric: tabular-nums; }
+.contract-progress > i { display: block; height: 100%; border-radius: inherit; background: var(--primary); transition: width .2s ease; }
+@media (max-width: 1100px) {
+  .contract-months-presets { margin-left: 0; }
+}
 .ops-form-grid textarea { width: 100%; min-height: 76px; padding: 9px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--card); color: var(--foreground); font: inherit; font-size: var(--type-body); line-height: 1.55; resize: vertical; }
 .ops-form-grid textarea:focus { outline: 2px solid var(--ring); outline-offset: 1px; }
 .contract-inline-account-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding-top: 4px; border-top: 1px dashed var(--border); color: var(--text-secondary); font-size: var(--type-support); }
@@ -965,9 +1006,14 @@ button.ops-contract-exit.is-active svg { opacity: .7; }
 .contract-agent-grid { grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px 16px; }
 @media(max-width:1100px){ .contract-agent-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
 @media(max-width:600px){ .contract-agent-grid { grid-template-columns:1fr; } }
-/* 合同表单的「录入经办人」:同样独占一行,三段只读(账号自动带入)。 */
-.contract-agent-readonly { display:flex; flex-wrap:wrap; align-items:baseline; gap:4px 8px; padding:10px 12px; border:1px dashed var(--border); border-radius:8px; }
-.contract-agent-readonly > .ops-field-note { flex:0 0 100%; }
+/* 「录入经办人」只读块已于 2026-11-19 从合同表单下线(账号派生列只在详情页呈现)。 */
+/* 区域门禁(2026-11-19):「所属区域」未选时,运营商/合伙人/运营团队/运维团队只读。
+   原生 disabled 控件点不动也不冒泡 ⇒ 包装层接管点击并就地弹提示(标题区点击同样冒泡到这里)。
+   只让控件不吃指针事件,`FieldHint` 的说明仍可悬停;布局按宿主单元格「标题+控件」竖排。 */
+.contract-region-gate { position:relative; display:flex; flex-direction:column; gap:6px; min-width:0; cursor:not-allowed; }
+.customer-team-field > .contract-region-gate { gap:7px; }
+.contract-region-gate > select, .contract-region-gate > .customer-team-multi { pointer-events:none; }
+.contract-region-gate-tip { position:absolute; top:calc(100% + 6px); left:0; z-index:40; padding:6px 10px; border:1px solid var(--warning-border); border-radius:6px; background:var(--warning-soft); color:var(--text-secondary); font-size:var(--type-meta); line-height:1.4; white-space:nowrap; box-shadow:0 6px 16px rgba(0,0,0,.14); }
 .contract-inline-field.is-locked { color:var(--text-secondary); }
 .contract-inline-field .contract-inline-lock { display:inline-flex; align-items:center; flex:none; color:var(--warning); }
 .contract-lock-note { display:flex; align-items:center; gap:8px; margin:0 0 14px; padding:10px 14px; border:1px solid var(--warning-border); border-radius:8px; background:var(--warning-soft); color:var(--text-secondary); font-size:var(--type-support); line-height:1.55; }

+ 98 - 28
web-scaffold/tests/domain-foundation.test.mjs

@@ -140,32 +140,34 @@ test("合同金额走整数分:元⇄分⛔ 浮点误差,0 元与非法格
 });
 
 test("新建合同必填 6 项按后端短路顺序逐字段拦人,提示语照抄 `60004` 原话", () => {
-  const filled = { payCycle: "yearly", amount: "1920.00", start: "2026-11-14", agent: "临港联通 · 张工", agentPhone: "13900000101", handoverOn: "2026-11-14" };
-  assert.deepEqual(CONTRACT_REQUIRED_FIELDS.map((field) => field.key), ["payCycle", "amount", "start", "agent", "agentPhone", "handoverOn"]);
+  /** 2026-11-19:交接日期并入签署日期 ⇒ 必填第 6 项由「交接日期」改为「签署日期」(写口仍送 agent_handover_on)。 */
+  const filled = { serviceMonths: "12", amount: "1920.00", start: "2026-11-14", agent: "临港联通 · 张工", agentPhone: "13900000101", signDate: "2026-11-14" };
+  assert.deepEqual(CONTRACT_REQUIRED_FIELDS.map((field) => field.key), ["serviceMonths", "amount", "start", "agent", "agentPhone", "signDate"]);
   assert.deepEqual(CONTRACT_REQUIRED_FIELDS.map((field) => field.message), [
-    "请选择付款周期",
+    "请填写服务期(月)",
     "请填写合同金额",
     "请选择生效日",
     "请填写运营商经办人姓名",
     "请填写经办人联系电话",
-    "请选择交接日期",
+    "请选择签署日期",
   ]);
   assert.equal(checkContractRequired(filled), null);
-  /** 全空时只能报出后端第一个短路的字段(付款周期),⛔ 一句话把六项混在一起。 */
-  const allEmpty = { payCycle: "", amount: "", start: "", agent: "", agentPhone: "", handoverOn: "" };
-  assert.deepEqual(checkContractRequired(allEmpty), { key: "payCycle", message: "请选择付款周期" });
-  assert.deepEqual(checkContractRequired({ ...allEmpty, payCycle: "monthly" }), { key: "amount", message: "请填写合同金额" });
-  assert.deepEqual(checkContractRequired({ ...allEmpty, payCycle: "monthly", amount: "1" }), { key: "start", message: "请选择生效日" });
-  assert.deepEqual(checkContractRequired({ ...allEmpty, payCycle: "monthly", amount: "1", start: "2026-11-14" }), { key: "agent", message: "请填写运营商经办人姓名" });
-  assert.deepEqual(checkContractRequired({ ...allEmpty, payCycle: "monthly", amount: "1", start: "2026-11-14", agent: "张工" }), { key: "agentPhone", message: "请填写经办人联系电话" });
-  assert.deepEqual(checkContractRequired({ ...allEmpty, payCycle: "monthly", amount: "1", start: "2026-11-14", agent: "张工", agentPhone: "13900000101" }), { key: "handoverOn", message: "请选择交接日期" });
+  /** 全空时只能报出后端第一个短路的字段(服务期),⛔ 一句话把六项混在一起。 */
+  const allEmpty = { serviceMonths: "", amount: "", start: "", agent: "", agentPhone: "", signDate: "" };
+  assert.deepEqual(checkContractRequired(allEmpty), { key: "serviceMonths", message: "请填写服务期(月)" });
+  assert.deepEqual(checkContractRequired({ ...allEmpty, serviceMonths: "12" }), { key: "amount", message: "请填写合同金额" });
+  assert.deepEqual(checkContractRequired({ ...allEmpty, serviceMonths: "12", amount: "1" }), { key: "start", message: "请选择生效日" });
+  assert.deepEqual(checkContractRequired({ ...allEmpty, serviceMonths: "12", amount: "1", start: "2026-11-14" }), { key: "agent", message: "请填写运营商经办人姓名" });
+  assert.deepEqual(checkContractRequired({ ...allEmpty, serviceMonths: "12", amount: "1", start: "2026-11-14", agent: "张工" }), { key: "agentPhone", message: "请填写经办人联系电话" });
+  assert.deepEqual(checkContractRequired({ ...allEmpty, serviceMonths: "12", amount: "1", start: "2026-11-14", agent: "张工", agentPhone: "13900000101" }), { key: "signDate", message: "请选择签署日期" });
+  /** 服务期只收 1~600 的整数月(月/季/年等快捷档最终都落成月数)。 */
+  const monthsOk = { ...allEmpty, serviceMonths: "12" };
+  assert.deepEqual(checkContractRequired({ ...monthsOk, serviceMonths: "0" }), { key: "serviceMonths", message: "服务期须为 1~600 的整数(月)" });
+  assert.deepEqual(checkContractRequired({ ...monthsOk, serviceMonths: "601" }), { key: "serviceMonths", message: "服务期须为 1~600 的整数(月)" });
+  assert.deepEqual(checkContractRequired({ ...monthsOk, serviceMonths: "1.5" }), { key: "serviceMonths", message: "服务期须为 1~600 的整数(月)" });
   /** 金额非空但非法 ⇒ 同一字段换成更具体的口径(0 元不是合法合同金额)。 */
-  const payCycleOk = { ...allEmpty, payCycle: "quarterly" };
-  assert.deepEqual(checkContractRequired({ ...payCycleOk, amount: "0" }), { key: "amount", message: "合同金额须大于 0(0 元不是合法合同金额)" });
-  assert.match(checkContractRequired({ ...payCycleOk, amount: "1.999" })?.message ?? "", /格式不对/);
-  /** `agent_org`(经办人机构)实测选填 ⇒ ⛔ 出现在必填清单里。 */
-  assert.equal(Object.keys(allEmpty).includes("agentOrg"), false);
-  assert.equal(CONTRACT_REQUIRED_FIELDS.some((field) => field.key === "agentOrg" || field.label.includes("机构")), false);
+  assert.deepEqual(checkContractRequired({ ...monthsOk, amount: "0" }), { key: "amount", message: "合同金额须大于 0(0 元不是合法合同金额)" });
+  assert.match(checkContractRequired({ ...monthsOk, amount: "1.999" })?.message ?? "", /格式不对/);
 });
 
 test("合同页载荷补齐后端必填键,命中的必填项红显该字段", () => {
@@ -174,13 +176,17 @@ test("合同页载荷补齐后端必填键,命中的必填项红显该字段",
   const draft = readFileSync(new URL("../src/domain/contract-draft.ts", import.meta.url), "utf8");
   /** 写入口径已抽到 `domain/contract-draft`:新建与详情内联编辑共用同一份校验与载荷。 */
   assert.match(draft, /contractAmountCents: yuanTextToCents\(draft\.amount\) \?\? 0,/);
-  assert.match(draft, /payCycle: draft\.payCycle,/);
+  assert.match(draft, /contractType: draft\.contractType,/);
+  assert.match(draft, /signDate: draft\.signDate,/);
+  assert.match(draft, /serviceMonths: Number\(draft\.serviceMonths\.trim\(\)\),/);
   assert.match(draft, /agentMobile: draft\.agentPhone\.trim\(\),/);
   assert.match(draft, /agentName: draft\.agent\.trim\(\),/);
-  assert.match(draft, /agentHandoverOn: draft\.handoverOn,/);
+  /** 交接日期=签署日期:写口 `agent_handover_on` 取签署日期同值,⛔ 再留一个独立草稿键。 */
+  assert.match(draft, /agentHandoverOn: draft\.signDate,/);
+  assert.equal(/handoverOn/.test(draft), false, "草稿不应再有 handoverOn 键");
   assert.match(draft, /agentOrg: draft\.agentOrg\.trim\(\),/);
   assert.match(draft, /const missing = checkContractRequired\(\{[\s\S]{0,200}\}\);[\s\S]{0,100}fieldError: missing/);
-  for (const key of ["payCycle", "amount", "agent", "agentPhone", "handoverOn"]) {
+  for (const key of ["serviceMonths", "amount", "agent", "agentPhone", "signDate"]) {
     assert.match(contract, new RegExp(`aria-invalid=\\{invalidOf\\("${key}"\\)\\}`));
     assert.ok(contract.includes(`{requiredErrorOf("${key}")}`), `字段 ${key} 缺原话红显`);
     assert.match(detail, new RegExp(`invalidOf\\("${key}"\\)`));
@@ -200,7 +206,7 @@ test("合同页载荷补齐后端必填键,命中的必填项红显该字段",
   assert.equal(/checkContractRequired\([\s\S]{0,200}agentOrg/.test(`${contract}\n${draft}`), false);
 });
 
-test("合同详情与录入表单:两枚经办人都按机构/姓名/联系方式三段呈现", () => {
+test("合同详情两枚经办人都按机构/姓名/联系方式三段呈现,录入表单只留运营商经办人", () => {
   const contract = readFileSync(new URL("../src/pages/ContractDetailPages.tsx", import.meta.url), "utf8");
   const detail = readFileSync(new URL("../src/pages/ContractRecordPage.tsx", import.meta.url), "utf8");
   /** 运营商经办人:三段各自一枚 `contract-inline-seg`,顺序=机构 → 姓名 → 联系方式。 */
@@ -213,13 +219,77 @@ test("合同详情与录入表单:两枚经办人都按机构/姓名/联
   const createdRow = /<dt>录入经办人<\/dt>([\s\S]*?)<\/dd><\/div>/.exec(detail);
   assert.ok(createdRow, "详情页缺「录入经办人」行");
   assert.equal(/<InlineField/.test(createdRow[1]), false, "录入经办人 ⛔ 内联编辑");
-  /** 录入表单:同一份三段只读回显(新建态姓名/联系方式取当前登录身份,机构待服务端按账号带入)。 */
-  assert.match(contract, /录入经办人[\s\S]{0,600}?created_by_org[\s\S]{0,300}?created_by_name[\s\S]{0,300}?created_by_mobile/);
-  assert.match(contract, /提交时自动带入/);
+  /** 录入表单不再回显「录入经办人」块(2026-11-19 下线):账号派生列只在详情页只读呈现。 */
+  assert.equal(/录入经办人 <small>/.test(contract), false, "录入表单 ⛔ 再回显录入经办人块");
   /** 两枚经办人各占一整行:详情 facts 是两列网格 ⇒ 必须跨满两列,⛔ 与邻项并排。 */
   assert.match(detail, /<div className="contract-facts-row-full"><dt>运营商经办人<\/dt>/);
   assert.match(detail, /<div className="contract-facts-row-full"><dt>录入经办人<\/dt>/);
-  /** 录入表单:运营商经办人三段装在同一块三列栅格里(`contract-agent-grid`),录入经办人随后的整块另起一行。 */
-  assert.match(contract, /contract-agent-block[\s\S]{0,900}?contract-agent-grid[\s\S]{0,1200}?id="agent-org"[\s\S]{0,900}?id="agent-name"[\s\S]{0,900}?id="agent-phone"/);
-  assert.match(contract, /ops-form-span-full contract-agent-readonly/);
+  /** 录入表单:运营商经办人三段装在同一格里(姓名/电话并排+机构),录入经办人随后的整块另起一行。 */
+  /** 运营商经办人=姓名+联系电话两项(机构 2026-11-19 起不再采集):`agentOrg` 只随草稿原样回传。 */
+  assert.match(contract, /contract-agent-cell[\s\S]{0,900}?contract-agent-combo[\s\S]{0,600}?id="agent-name"[\s\S]{0,300}?id="agent-phone"/);
+  assert.equal(/id="agent-org"/.test(contract), false, "运营商经办人不再有机构录入格");
+  assert.match(contract, /agent_org: w\.agentOrg,/);
+  assert.equal(/contract-agent-readonly/.test(contract), false, "录入经办人只读块已下线");
+  /** 02 合同基本信息(2026-11-19):一行三列=编号/外部单号/类型、经办人/签署日期/金额、服务期/生效日/到期日。 */
+  assert.match(contract, /合同基本信息[\s\S]{0,4000}?id="contract-no"[\s\S]{0,400}?id="external-no"[\s\S]{0,400}?id="contract-type"/);
+  assert.match(contract, /contract-agent-cell[\s\S]{0,4000}?id="sign-date"[\s\S]{0,400}?id="contract-amount"/);
+  assert.match(contract, /contract-months-cell[\s\S]{0,1200}?contract-months-presets[\s\S]{0,1600}?id="start-date"[\s\S]{0,600}?id="end-date"/);
+  /** 服务期月数是唯一人工入口;到期日锁定为推算值(readOnly)。 */
+  assert.match(contract, /id="service-months"[^>]*type="number"/);
+  assert.match(contract, /id="end-date"[^>]*readOnly/);
+});
+
+test("所属区域未选时,四类反查项点击就地提示「请先选取所属区域」(2026-11-19)", () => {
+  const contract = readFileSync(new URL("../src/pages/ContractDetailPages.tsx", import.meta.url), "utf8");
+  const css = readFileSync(new URL("../src/styles/operations.css", import.meta.url), "utf8");
+  /** 门禁只认「所属区域为空」:运营商/合伙人/运营团队三枚下拉都套 RegionGate。 */
+  for (const id of ["inline-operator", "inline-partner", "inline-operations-team"]) {
+    assert.match(contract, new RegExp(`RegionGate gated=\\{!inline\\.regionId\\}[\\s\\S]{0,700}?id="${id}"`), `${id} 未套区域门禁`);
+  }
+  /** 运维团队走自绘下拉,同样由门禁接管点击。 */
+  assert.match(contract, /customer-team-field[\s\S]{0,400}?RegionGate gated=\{!inline\.regionId\}[\s\S]{0,700}?CustomerTeamSelect/);
+  /** 提示语统一「请先选取所属区域」;原生 disabled 控件不冒泡 ⇒ 控件必须让出指针事件,点击才落到包装层。 */
+  assert.match(contract, /contract-region-gate-tip[\s\S]{0,120}?请先选取所属区域/);
+  assert.match(css, /\.contract-region-gate > select, \.contract-region-gate > \.customer-team-multi \{ pointer-events:none; \}/);
+});
+
+test("交接日期并入签署日期;合同附件沿用营业执照影像的拖曳卡片,落在 02 卡片最下面(2026-11-19)", () => {
+  const contract = readFileSync(new URL("../src/pages/ContractDetailPages.tsx", import.meta.url), "utf8");
+  const detail = readFileSync(new URL("../src/pages/ContractRecordPage.tsx", import.meta.url), "utf8");
+  const draft = readFileSync(new URL("../src/domain/contract-draft.ts", import.meta.url), "utf8");
+  /** ⛔ 表单里再留「交接日期」录入格:一个日期只出现一次,且是必填。 */
+  assert.equal(/id="handover-on"/.test(contract), false, "新建/编辑表单不应再有交接日期格");
+  assert.equal(/id="contract-handover-on"/.test(detail), false, "详情页不应再有交接日期行");
+  assert.match(contract, /id="sign-date"[^>]*aria-invalid=\{invalidOf\("signDate"\)\}/);
+  assert.match(detail, /id="contract-sign-date"[\s\S]{0,900}?invalid=\{invalidOf\("signDate"\)\}/);
+  /** 写口仍按 `agent_handover_on` 收,值取签署日期(同值落两列)。 */
+  assert.match(draft, /agentHandoverOn: draft\.signDate,/);
+  /** 附件卡片与营业执照影像同一套类名(整块拖曳+点击上传+透明覆盖层),并挂在 02 卡片里。 */
+  assert.match(contract, /contract-license-drop contract-attachment-drop/);
+  assert.match(contract, /aria-label="上传合同附件"[\s\S]{0,400}?void pickAttachment\(file\)/);
+  assert.match(contract, /uploadContractAttachment\(file\)/);
+  assert.match(contract, /set\("attachmentUrl", uploaded\.object_key\)/);
+  /** 附件块必须在 02 卡片内、且位于三行业务字段之后(⛔ 跑到 03 服务构成里)。 */
+  const endAt = contract.indexOf('id="end-date"');
+  const dropAt = contract.indexOf("contract-attachment-drop");
+  const section03 = contract.indexOf("<span>03</span>");
+  assert.ok(endAt > 0 && dropAt > endAt && section03 > dropAt, "附件块应排在到期日期之后、03 服务构成之前");
+});
+
+test("新增合同的所属区域下拉整层去掉「全网」,直接以省一级为根(2026-11-19)", async () => {
+  const contract = readFileSync(new URL("../src/pages/ContractDetailPages.tsx", import.meta.url), "utf8");
+  const { regionTreeNodes } = await import("../src/lib/region-tree.ts");
+  /** 页面把「全网」从建树集合里摘掉,再把省节点当根渲染(⛔ 另写 re-root 分支)。 */
+  assert.match(contract, /const visible = org\.regions\.filter\(\(item\) => !blocked\.has\(item\.id\)\);/);
+  assert.match(contract, /return regionTreeNodes\(visible, visible\.map\(\(item\) => item\.id\)\);/);
+  assert.equal(/regionTreeNodes\(org\.regions,/.test(contract), false, "仍把含「全网」的全量集合交给建树");
+  const regions = [
+    { id: "root", name: "全网", parent: null, level: null, pathName: "全网" },
+    { id: "sh", name: "上海市", parent: "root", level: 0, pathName: "全网 / 上海市" },
+    { id: "js", name: "江苏省", parent: "root", level: 0, pathName: "全网 / 江苏省" },
+    { id: "pd", name: "浦东新区", parent: "sh", level: 2, pathName: "全网 / 上海市 / 浦东新区" },
+  ];
+  const tree = regionTreeNodes(regions.filter((item) => item.name !== "全网"), ["sh", "js", "pd"]);
+  assert.deepEqual(tree.map((node) => [node.label, node.hint]), [["上海市", "省"], ["江苏省", "省"]]);
+  assert.deepEqual(tree[0].children.map((node) => node.label), ["浦东新区"]);
 });

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä