|
|
@@ -60,7 +60,7 @@ use bos_invariant::{
|
|
|
check_contract_deletable, check_contract_items, contract_attachment_object_key,
|
|
|
contract_edit_scope, contracts_opened, normalize_line_exits,
|
|
|
replaced_attachment_object, resolve_contract_no, validate_contract_payload, AxisLock,
|
|
|
- ContractDraft, ContractEditScope, ContractItemRaw, ContractRaw, CrossRead, Opened,
|
|
|
+ ContractDraft, ContractEditScope, ContractItemRaw, ContractRaw, CrossRead, ItemMode, Opened,
|
|
|
OpenedProbe, PlanFamily, PlanRef, CONTRACT_ATTACHMENT_KEY_PREFIX,
|
|
|
};
|
|
|
|
|
|
@@ -75,7 +75,16 @@ const READONLY_KEYS: [&str; 3] = ["source", "opened", "first_referred_at"];
|
|
|
///
|
|
|
/// 其余曾入列的键(`item_kind`/账号数/上下行带宽/年价/月结算/`use_category`)已删列:
|
|
|
/// 它们落进 `extra` 后由 `fields_not_persisted` 逐键点名,⛔ 静默丢弃。
|
|
|
-const SERVICE_ITEM_FIELDS_PERSISTED: [&str; 4] = ["plan_id", "quantity", "item_family", "line_exits"];
|
|
|
+const SERVICE_ITEM_FIELDS_PERSISTED: [&str; 8] = [
|
|
|
+ "plan_id",
|
|
|
+ "quantity",
|
|
|
+ "item_family",
|
|
|
+ "line_exits",
|
|
|
+ "item_mode",
|
|
|
+ "serves_item_id",
|
|
|
+ "serves_item_index",
|
|
|
+ "ref_subscription_id",
|
|
|
+];
|
|
|
/// D-15:条目上⛔ 再出现的旧列/派生键(价格、带宽、席位只属档位,出现即拒)。
|
|
|
///
|
|
|
/// 与 [`SERVICE_ITEM_FIELDS_PERSISTED`] 的关系:这些键先落进 `extra`(openapi 已删列),
|
|
|
@@ -148,13 +157,15 @@ const CONTRACT_UPDATE_ALL: &str = "UPDATE contract SET external_no = $2::text, \
|
|
|
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";
|
|
|
|
|
|
-/// 条目新增的**全列**形态(D-15:五列=主键、合同、档位、份数、形态、出口)。
|
|
|
+/// 条目新增的**全列**形态(D-15:六列=主键、合同、档位、份数、形态、出口;
|
|
|
+/// P1 加三列=条目形态、父条目、增量引用订阅)。
|
|
|
///
|
|
|
/// `quantity` 走 `$n::text::int`,参数侧按文本下发([`num_text`])——原因见该函数的注释:
|
|
|
/// 同一段 SQL 的可空数值占位符混用 TEXT/INT8 会让 UDS 复用的预编译语句解码错位。
|
|
|
const ITEM_INSERT_FULL: &str = "INSERT INTO contract_service_item (item_id, contract_id, plan_id, \
|
|
|
- quantity, item_family, line_exits) \
|
|
|
- VALUES ($1::text, $2::text, $3::text, $4::text::int, $5::text, $6::text::jsonb)";
|
|
|
+ quantity, item_family, line_exits, item_mode, serves_item_id, ref_subscription_id) \
|
|
|
+ VALUES ($1::text, $2::text, $3::text, $4::text::int, $5::text, $6::text::jsonb, \
|
|
|
+ $7::text, $8::text, $9::text)";
|
|
|
|
|
|
/// 条目改写(`$1`=item_id、`$2`=contract_id、`$3..`=SET 列)。
|
|
|
///
|
|
|
@@ -162,6 +173,7 @@ const ITEM_INSERT_FULL: &str = "INSERT INTO contract_service_item (item_id, cont
|
|
|
/// `KLT-L213` 的引用面),删后重插=订阅挂到已消失的条目上,第 5 册 I12a 直接读空。
|
|
|
const ITEM_UPDATE: &str = "UPDATE contract_service_item SET plan_id = $3::text, \
|
|
|
quantity = $4::text::int, item_family = $5::text, line_exits = $6::text::jsonb, \
|
|
|
+ item_mode = $7::text, serves_item_id = $8::text, ref_subscription_id = $9::text, \
|
|
|
updated_at = NOW() \
|
|
|
WHERE item_id = $1::text AND contract_id = $2::text";
|
|
|
|
|
|
@@ -229,6 +241,15 @@ pub struct ServiceItemReq {
|
|
|
/// (`check_contract_items` 比对;⛔ 静默以档位为准=前后端两本账)。
|
|
|
pub item_family: Option<String>,
|
|
|
pub line_exits: Option<Value>,
|
|
|
+ /// 条目形态(D-9):`new`(缺省)/`increment`。
|
|
|
+ pub item_mode: Option<String>,
|
|
|
+ /// 附加项在**本合同内**的父条目主键(编辑态用;新建态还没有服务端主键)。
|
|
|
+ pub serves_item_id: Option<String>,
|
|
|
+ /// 附加项父条目在本载荷 `service_items` 里的 **0 基序号**(新建态用;编辑态也可用)。
|
|
|
+ /// ⚠️ 与 D-7 导入模板的「父条目序号」同一口径(0 基)。
|
|
|
+ pub serves_item_index: Option<Value>,
|
|
|
+ /// 增量条目引用的既有 `link` 订阅号(跨合同,D-9)。
|
|
|
+ pub ref_subscription_id: Option<String>,
|
|
|
/// 逐条替换(第 3 册 §5.3):仅新建合同受理;编辑态出现即拒。
|
|
|
pub succession: Option<super::succession::ReplaceReq>,
|
|
|
#[serde(flatten)]
|
|
|
@@ -375,6 +396,15 @@ struct ItemRow {
|
|
|
/// 交付形态(落库值=所引档位的 `plan_family`,D-15 后条目唯一形态来源)。
|
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
|
item_family: Option<String>,
|
|
|
+ /// 条目形态(D-9):`new`/`increment`。
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ item_mode: Option<String>,
|
|
|
+ /// 附加项在本合同内的父条目(D-7)。
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ serves_item_id: Option<String>,
|
|
|
+ /// 增量条目引用的既有链路订阅(D-9)。
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ ref_subscription_id: Option<String>,
|
|
|
/// JSONB:联合引擎可能整列回字符串(同 `audit.rs:79` 的坑)⇒ 解析不了就原样回,⛔ 吞。
|
|
|
#[serde(default)]
|
|
|
line_exits: Option<Value>,
|
|
|
@@ -436,6 +466,10 @@ fn item_json(r: ItemRow, plans: &HashMap<String, PlanName>) -> Value {
|
|
|
"sub_account_quota": own.and_then(|p| parse_i64(p.sub_account_quota.as_ref())),
|
|
|
"quantity": as_opt_num(r.quantity.as_deref()),
|
|
|
"item_family": item_family,
|
|
|
+ // D-9/D-7:形态与父引用原样出参,界面据此渲染父子缩进树。
|
|
|
+ "item_mode": blank(&r.item_mode).unwrap_or("new"),
|
|
|
+ "serves_item_id": blank(&r.serves_item_id),
|
|
|
+ "ref_subscription_id": blank(&r.ref_subscription_id),
|
|
|
"line_exits": json_cell(r.line_exits),
|
|
|
})
|
|
|
}
|
|
|
@@ -604,7 +638,8 @@ async fn load_children(db: &UdsClient, ids: &[String]) -> Result<Children, BosEr
|
|
|
let mut p = Params::default();
|
|
|
let in_pred = push_in(&mut p, "i.contract_id", ids, "text");
|
|
|
let sql = format!(
|
|
|
- "SELECT i.item_id, i.contract_id, i.plan_id, i.quantity, i.item_family, i.line_exits \
|
|
|
+ "SELECT i.item_id, i.contract_id, i.plan_id, i.quantity, i.item_family, \
|
|
|
+ i.item_mode, i.serves_item_id, i.ref_subscription_id, i.line_exits \
|
|
|
FROM contract_service_item i WHERE {in_pred} ORDER BY i.created_at, i.item_id"
|
|
|
);
|
|
|
let mut rows: Vec<ItemRow> = db.query_all::<ItemRow>(&sql, p.values()).await?;
|
|
|
@@ -843,6 +878,17 @@ fn want_pos(v: Option<&Value>, field: &str) -> Result<Option<i64>, BosError> {
|
|
|
Ok(n)
|
|
|
}
|
|
|
|
|
|
+/// 0 基序号(`serves_item_index`):⛔ 负数、⛔ 非整数。
|
|
|
+///
|
|
|
+/// 为什么单独一个函数而不是复用 `want_pos`:父条目序号**允许 0**,而 `want_pos` 把 0 判成
|
|
|
+/// 非法——两处用同一函数会让「第 1 条条目作父」永远报错,且报错文案指向「数量」很误导。
|
|
|
+fn want_index(v: Option<&Value>, field: &str) -> Result<Option<usize>, BosError> {
|
|
|
+ let Some(n) = want_int(v, field)? else { return Ok(None) };
|
|
|
+ usize::try_from(n)
|
|
|
+ .map(Some)
|
|
|
+ .map_err(|_| BosError::bad_params(format!("{field} 须为 ≥0 的整数(0 基序号),收到 {n}")))
|
|
|
+}
|
|
|
+
|
|
|
/// 库里已存的日期列(认不出来=当没有,⛔ 因脏数据卡住一次合法改写)。
|
|
|
fn stored_date(v: Option<&String>) -> Option<NaiveDate> {
|
|
|
v.as_deref()
|
|
|
@@ -869,6 +915,14 @@ struct ItemIns {
|
|
|
quantity: i64,
|
|
|
/// =所引档位的 `plan_family`(落库列 `item_family` 的唯一取值来源)。
|
|
|
plan_family: PlanFamily,
|
|
|
+ /// 条目形态(D-9):`new`/`increment`。
|
|
|
+ item_mode: ItemMode,
|
|
|
+ /// 附加项在本载荷里的父条目 **0 基序号**(发号后换成 `serves_item_id` 落库)。
|
|
|
+ parent_index: Option<usize>,
|
|
|
+ /// 落库父条目主键(发号后填;`increment` 与 `link` 恒 `None`)。
|
|
|
+ serves_item_id: Option<String>,
|
|
|
+ /// 增量条目引用的既有链路订阅(D-9)。
|
|
|
+ ref_subscription_id: Option<String>,
|
|
|
/// 归一化出口集合(JSONB 字符串数组=dev 在册列)
|
|
|
line_exits: Value,
|
|
|
/// I6 摘要键(I6 已停用;写侧照算作出口摘要,当前无读侧)
|
|
|
@@ -890,6 +944,10 @@ struct ItemRawOwned {
|
|
|
/// 交付形态确认位(原样保留,交给 `check_contract_items` 与档位比对)。
|
|
|
item_family: Option<String>,
|
|
|
line_exits: Vec<String>,
|
|
|
+ item_mode: Option<String>,
|
|
|
+ serves_item_id: Option<String>,
|
|
|
+ serves_item_index: Option<usize>,
|
|
|
+ ref_subscription_id: Option<String>,
|
|
|
succession: Option<super::succession::ReplaceReq>,
|
|
|
}
|
|
|
|
|
|
@@ -925,6 +983,10 @@ fn item_norm(raw: &[ServiceItemReq]) -> Result<(Vec<ItemRawOwned>, Vec<String>),
|
|
|
quantity: want_pos(it.quantity.as_ref(), &format!("{prefix}.quantity"))?,
|
|
|
item_family: trimmed(&it.item_family).map(|s| s.to_string()),
|
|
|
line_exits: exits,
|
|
|
+ item_mode: trimmed(&it.item_mode).map(|s| s.to_string()),
|
|
|
+ serves_item_id: trimmed(&it.serves_item_id).map(|s| s.to_string()),
|
|
|
+ serves_item_index: want_index(it.serves_item_index.as_ref(), &format!("{prefix}.serves_item_index"))?,
|
|
|
+ ref_subscription_id: trimmed(&it.ref_subscription_id).map(|s| s.to_string()),
|
|
|
succession: it.succession.clone(),
|
|
|
});
|
|
|
dropped.extend(it.extra.keys().cloned());
|
|
|
@@ -1014,6 +1076,22 @@ async fn resolve_items(
|
|
|
"服务构成至少一条(04 册 §4.3)",
|
|
|
));
|
|
|
}
|
|
|
+ // 父引用的两种形态只收一种:已有父用 `serves_item_id`,新建态父用 0 基序号
|
|
|
+ // (编成 `idx:{n}` 交给判据层,与 D-7 导入模板「父条目序号」同一口径)。
|
|
|
+ let mut parent_refs: Vec<Option<String>> = Vec::with_capacity(normed.len());
|
|
|
+ for (i, it) in normed.iter().enumerate() {
|
|
|
+ if it.serves_item_id.is_some() && it.serves_item_index.is_some() {
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "service_items[{i}] 同时给了 serves_item_id 与 serves_item_index:只给一个\
|
|
|
+ (已有父条目用 id,本次新建的父条目用 0 基序号)"
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ parent_refs.push(
|
|
|
+ it.serves_item_id
|
|
|
+ .clone()
|
|
|
+ .or_else(|| it.serves_item_index.map(|n| format!("idx:{n}"))),
|
|
|
+ );
|
|
|
+ }
|
|
|
let plan_ids: Vec<String> = normed
|
|
|
.iter()
|
|
|
.filter_map(|it| it.plan_id.clone())
|
|
|
@@ -1023,15 +1101,27 @@ async fn resolve_items(
|
|
|
let plans = load_plans(db, &plan_ids).await?;
|
|
|
let raws: Vec<ContractItemRaw<'_>> = normed
|
|
|
.iter()
|
|
|
- .map(|it| ContractItemRaw {
|
|
|
+ .enumerate()
|
|
|
+ .map(|(i, it)| ContractItemRaw {
|
|
|
item_id: it.item_id.as_deref(),
|
|
|
plan_id: it.plan_id.as_deref(),
|
|
|
quantity: it.quantity,
|
|
|
item_family: it.item_family.as_deref(),
|
|
|
line_exits: &it.line_exits,
|
|
|
+ item_mode: it.item_mode.as_deref(),
|
|
|
+ serves_ref: parent_refs[i].as_deref(),
|
|
|
+ ref_subscription_id: it.ref_subscription_id.as_deref(),
|
|
|
})
|
|
|
.collect();
|
|
|
let checked = check_contract_items(customer_id, &raws, &plans)?;
|
|
|
+ // D-9:增量条目引用的既有订阅必须属本客户 ∧ 为 `link` ∧ 在期。
|
|
|
+ // 「在期」是派生状态(随工单回填与日期翻转)⇒ 库层外键/CHECK 钉不住,只能写库前校验。
|
|
|
+ let refs: Vec<(usize, String)> = checked
|
|
|
+ .iter()
|
|
|
+ .enumerate()
|
|
|
+ .filter_map(|(i, c)| c.ref_subscription_id.clone().map(|r| (i, r)))
|
|
|
+ .collect();
|
|
|
+ check_increment_refs(db, customer_id, &refs).await?;
|
|
|
// 线路出口强校验(2026-11-15 裁定):条目上的每个出口都必须命中「套餐配置 → 线路出口」。
|
|
|
let mut uses: Vec<(String, String)> = Vec::new();
|
|
|
for (index, it) in normed.iter().enumerate() {
|
|
|
@@ -1043,17 +1133,31 @@ async fn resolve_items(
|
|
|
let out: Vec<ItemIns> = checked
|
|
|
.iter()
|
|
|
.zip(normed.iter())
|
|
|
- .map(|(c, n)| ItemIns {
|
|
|
- item_id: c.item_id.map(|s| s.to_string()),
|
|
|
- plan_id: c.plan.plan_id.clone(),
|
|
|
- // `check_contract_items` 已保证份数合法;缺省 1 与它的 `unwrap_or(1)` 同一式。
|
|
|
- quantity: n.quantity.unwrap_or(1),
|
|
|
- plan_family: c.plan_family,
|
|
|
- line_exits: Value::Array(
|
|
|
- c.line_exits.iter().map(|s| Value::String(s.clone())).collect(),
|
|
|
- ),
|
|
|
- line_exit_key: c.line_exit_key.clone(),
|
|
|
- succession: n.succession.clone(),
|
|
|
+ .map(|(c, n)| {
|
|
|
+ // `idx:{n}` 是本次新建的父条目 ⇒ 发号后再换成真正的主键(见调用方 `link_parents`)。
|
|
|
+ let (parent_index, serves_item_id) = match c.serves_ref.as_deref() {
|
|
|
+ Some(r) => match r.strip_prefix("idx:") {
|
|
|
+ Some(rest) => (rest.parse::<usize>().ok(), None),
|
|
|
+ None => (None, Some(r.to_string())),
|
|
|
+ },
|
|
|
+ None => (None, None),
|
|
|
+ };
|
|
|
+ ItemIns {
|
|
|
+ item_id: c.item_id.map(|s| s.to_string()),
|
|
|
+ plan_id: c.plan.plan_id.clone(),
|
|
|
+ // `check_contract_items` 已保证份数合法;缺省 1 与它的 `unwrap_or(1)` 同一式。
|
|
|
+ quantity: n.quantity.unwrap_or(1),
|
|
|
+ plan_family: c.plan_family,
|
|
|
+ item_mode: c.item_mode,
|
|
|
+ parent_index,
|
|
|
+ serves_item_id,
|
|
|
+ ref_subscription_id: c.ref_subscription_id.clone(),
|
|
|
+ line_exits: Value::Array(
|
|
|
+ c.line_exits.iter().map(|s| Value::String(s.clone())).collect(),
|
|
|
+ ),
|
|
|
+ line_exit_key: c.line_exit_key.clone(),
|
|
|
+ succession: n.succession.clone(),
|
|
|
+ }
|
|
|
})
|
|
|
.collect();
|
|
|
// 线路出口改**单选**(2026-11-17):新建/修改条目的出口集合必须恰好 1 个。
|
|
|
@@ -1075,6 +1179,110 @@ async fn resolve_items(
|
|
|
Ok((out, dropped))
|
|
|
}
|
|
|
|
|
|
+/// D-9:增量条目引用的既有链路订阅必须**属本客户 ∧ 为 `link` ∧ 在期**。
|
|
|
+///
|
|
|
+/// 为什么只能写库前校验:这三条里「在期」随工单回填与日期翻转而变(派生状态),
|
|
|
+/// 外键只保证「这条订阅存在」;⛔ 加的 CHECK 会把某一个瞬间的状态固化成数据不变量。
|
|
|
+async fn check_increment_refs(
|
|
|
+ db: &UdsClient,
|
|
|
+ customer_id: &str,
|
|
|
+ refs: &[(usize, String)],
|
|
|
+) -> Result<(), BosError> {
|
|
|
+ if refs.is_empty() {
|
|
|
+ return Ok(());
|
|
|
+ }
|
|
|
+ let ids: Vec<String> = refs.iter().map(|(_, r)| r.clone()).collect::<BTreeSet<_>>()
|
|
|
+ .into_iter()
|
|
|
+ .collect();
|
|
|
+ let mut p = Params::default();
|
|
|
+ let in_pred = push_in(&mut p, "s.subscription_id", &ids, "text");
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT s.subscription_id, s.customer_id, s.plan_family, s.status, s.end_date \
|
|
|
+ FROM subscription s WHERE {in_pred}"
|
|
|
+ );
|
|
|
+ let found: HashMap<String, RefSubRow> = db
|
|
|
+ .query_all::<RefSubRow>(&sql, p.values())
|
|
|
+ .await?
|
|
|
+ .into_iter()
|
|
|
+ .map(|r| (r.subscription_id.clone(), r))
|
|
|
+ .collect();
|
|
|
+ let today = Local::now().date_naive();
|
|
|
+ for (index, rid) in refs {
|
|
|
+ let at = format!("service_items[{index}].ref_subscription_id");
|
|
|
+ let row = found.get(rid).ok_or_else(|| {
|
|
|
+ BosError::klt(
|
|
|
+ KltCode::L216,
|
|
|
+ format!("{at}:订阅 {rid} 不存在(增量条目必须引用既有链路订阅)"),
|
|
|
+ )
|
|
|
+ })?;
|
|
|
+ if row.customer_id != customer_id {
|
|
|
+ return Err(BosError::klt(
|
|
|
+ KltCode::L216,
|
|
|
+ format!(
|
|
|
+ "{at}:订阅 {rid} 不属于本客户(增量合同的既有链路必须同客户,可跨合同)"
|
|
|
+ ),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ if row.plan_family.as_deref() != Some("link") {
|
|
|
+ return Err(BosError::klt(
|
|
|
+ KltCode::L216,
|
|
|
+ format!("{at}:订阅 {rid} 不是跨境链路订阅(increment 只能叠加在 link 上)"),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let expired = row
|
|
|
+ .end_date
|
|
|
+ .as_deref()
|
|
|
+ .and_then(|s| NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
|
|
|
+ .is_some_and(|d| d < today);
|
|
|
+ if row.status != "active" || expired {
|
|
|
+ return Err(BosError::klt(
|
|
|
+ KltCode::L216,
|
|
|
+ format!(
|
|
|
+ "{at}:订阅 {rid} 不在期(status={},到期 {})⇒ 不能再往上叠加附加项",
|
|
|
+ row.status,
|
|
|
+ row.end_date.as_deref().unwrap_or("—")
|
|
|
+ ),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Ok(())
|
|
|
+}
|
|
|
+
|
|
|
+/// 把 `parent_index`(本次载荷的 0 基序号)换成真正的主键 `serves_item_id`。
|
|
|
+///
|
|
|
+/// 为什么不在 `resolve_items` 里换:新建态条目主键在**发号之后**才有(服务端发号),
|
|
|
+/// 而判据层只看得到「第几条」;两件事分开后,'父是谁' 的判定与 '父叫什么' 的落值互不纠缠。
|
|
|
+fn link_parents(items: &mut [ItemIns]) -> Result<(), BosError> {
|
|
|
+ for i in 0..items.len() {
|
|
|
+ let Some(pi) = items[i].parent_index else { continue };
|
|
|
+ let pid = items.get(pi).and_then(|p| p.item_id.clone()).ok_or_else(|| {
|
|
|
+ BosError::klt(
|
|
|
+ KltCode::L216,
|
|
|
+ format!(
|
|
|
+ "service_items[{i}]:父条目序号 {pi} 无效或尚未发号(父条目必须也在本次载荷内)"
|
|
|
+ ),
|
|
|
+ )
|
|
|
+ })?;
|
|
|
+ items[i].serves_item_id = Some(pid);
|
|
|
+ items[i].parent_index = None;
|
|
|
+ }
|
|
|
+ Ok(())
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Deserialize)]
|
|
|
+struct RefSubRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ subscription_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ customer_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_family: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ status: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ end_date: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
// ─────────────── 派生自定义档(04 册 §4.3 末段,与合同保存同一条批) ───────────────
|
|
|
|
|
|
/// 载荷里出现过的只读/派生键(顶层 `extra` + 条目的 `extra`)。
|
|
|
@@ -1204,7 +1412,8 @@ fn num_text(v: Option<i64>) -> Value {
|
|
|
v.map(|n| Value::String(n.to_string())).unwrap_or(Value::Null)
|
|
|
}
|
|
|
|
|
|
-/// `service_items` 的参数位([`ITEM_INSERT_FULL`] 六列:D-15 后条目只剩「档位 × 份数」)。
|
|
|
+/// `service_items` 的参数位([`ITEM_INSERT_FULL`] 九列:D-15 后条目只剩「档位 × 份数」,
|
|
|
+/// P1 另加条目形态、父条目、增量引用订阅)。
|
|
|
///
|
|
|
/// 份数走 [`num_text`](可空列的统一纪律),形态=档位的 `plan_family`。
|
|
|
fn item_params(contract_id: &str, item_id: &str, it: &ItemIns) -> Vec<Value> {
|
|
|
@@ -1215,6 +1424,9 @@ fn item_params(contract_id: &str, item_id: &str, it: &ItemIns) -> Vec<Value> {
|
|
|
num_text(Some(it.quantity)),
|
|
|
Value::String(it.plan_family.as_str().to_string()),
|
|
|
Value::String(it.line_exits.to_string()),
|
|
|
+ Value::String(it.item_mode.as_str().to_string()),
|
|
|
+ text_param(it.serves_item_id.as_deref()),
|
|
|
+ text_param(it.ref_subscription_id.as_deref()),
|
|
|
]
|
|
|
}
|
|
|
|
|
|
@@ -1729,6 +1941,8 @@ async fn do_create_for_customer(
|
|
|
{
|
|
|
it.item_id = Some(id);
|
|
|
}
|
|
|
+ // 父条目序号 ⇒ 主键(发号后才有 id;D-7 只允许两级树)。
|
|
|
+ link_parents(&mut items)?;
|
|
|
// ⑥ 契约内逐条替换(§5.3):**前置全部校验完**才组装语句,与合同写入同一条批。
|
|
|
// 失败=整批回滚(合同、条目、派生档、IP、截原、新订阅、额度一起回滚),
|
|
|
// 前端保留已录入的合同、条目、替换选择与附件,改完可原样重提。
|
|
|
@@ -1858,6 +2072,11 @@ async fn do_create_for_customer(
|
|
|
&p.orig.subscription_id,
|
|
|
&p.new.subscription_id,
|
|
|
));
|
|
|
+ // D-2「父替换 ⇒ 子改挂」:只改父指针,子订阅自身不参与替换。
|
|
|
+ stmts.push(succession::reparent_children_stmt(
|
|
|
+ &p.orig.subscription_id,
|
|
|
+ &p.new.subscription_id,
|
|
|
+ ));
|
|
|
}
|
|
|
|
|
|
let results = db.dml_batch(&stmts).await?;
|
|
|
@@ -2032,8 +2251,12 @@ async fn do_create_for_customer(
|
|
|
quota_slots: p.new.quota_slots,
|
|
|
actor_user_id: a,
|
|
|
original: Some(succession::original_sub(state, &p.orig).await),
|
|
|
+ // 替换只承接 link 订阅 ⇒ 无父。
|
|
|
+ parent_subscription_id: p.new.parent_subscription_id.clone(),
|
|
|
// 替换=服务内容变了(第七类工单或开通单照旧)。
|
|
|
service_unchanged: false,
|
|
|
+ // D-11:号随**新合同**(旧合同号冻结在旧订阅上)。
|
|
|
+ carrier_order_no: draft.external_no.clone(),
|
|
|
},
|
|
|
)
|
|
|
.await
|
|
|
@@ -2109,7 +2332,10 @@ async fn do_create_for_customer(
|
|
|
quota_slots: p.new.quota_slots,
|
|
|
actor_user_id: a,
|
|
|
original: None,
|
|
|
+ parent_subscription_id: p.new.parent_subscription_id.clone(),
|
|
|
service_unchanged: renewal_unchanged,
|
|
|
+ // D-11:增量/续签新开都取**本单合同**的运营商订单号。
|
|
|
+ carrier_order_no: draft.external_no.clone(),
|
|
|
},
|
|
|
)
|
|
|
.await
|
|
|
@@ -2306,7 +2532,10 @@ async fn plan_contract_subs(
|
|
|
renew_from: Option<&str>,
|
|
|
) -> Result<PlannedSubs, BosError> {
|
|
|
let mut out = PlannedSubs { replaced: Vec::new(), fresh: Vec::new() };
|
|
|
- if renew_from.is_none() && !items.iter().any(|it| it.succession.is_some()) {
|
|
|
+ // D-9:增量条目是**本单交付物**(父链路早已交付)⇒ 合同签订即建附加订阅并出
|
|
|
+ // `service_open`,⛔ 沿用「合同登记≠订阅」把增量项晾在那里。
|
|
|
+ let has_increment = items.iter().any(|it| it.item_mode == ItemMode::Increment);
|
|
|
+ if renew_from.is_none() && !items.iter().any(|it| it.succession.is_some()) && !has_increment {
|
|
|
return Ok(out);
|
|
|
}
|
|
|
let existing = super::subscription::subs_of_customer(state, customer_id).await?;
|
|
|
@@ -2314,12 +2543,35 @@ async fn plan_contract_subs(
|
|
|
// 订阅开始日=**合同开始日**(2026-11-17 定案:订阅跟着合同起算,⛔ 一律从业务当天起)。
|
|
|
let start_owned = contract_start.to_string();
|
|
|
let mut seen: HashSet<String> = HashSet::new();
|
|
|
- for (idx, it) in items.iter().enumerate() {
|
|
|
+ // 两阶段(G-5/D-7):先 link 后 addon——附加条目的父订阅必须先有落点,否则
|
|
|
+ // `ck_sub_parent` 会在批内拒绝。`sort_no` 允许附加排在父之前,故顺序只按 `family` 重排,
|
|
|
+ // ⛔ 读 `sort_no` 推断归属。
|
|
|
+ let mut order: Vec<usize> = (0..items.len()).collect();
|
|
|
+ order.sort_by_key(|&i| usize::from(items[i].plan_family != PlanFamily::Link));
|
|
|
+ // 本次批内落成的「条目主键 → 新订阅号」:附加条目在父订阅还没落库时靠它解析父。
|
|
|
+ let mut planned_subs: HashMap<String, String> = HashMap::new();
|
|
|
+ for idx in order {
|
|
|
+ let it = &items[idx];
|
|
|
let prefix = format!("service_items[{idx}]");
|
|
|
let (plan, item_row) = item_plan(state, contract_id, it, &prefix).await?;
|
|
|
let new_id = super::subscription::new_subscription_id(state).await?;
|
|
|
+ // 父订阅(D-2/D-9):`addon` 必填、`link` 恒空。`increment` 条目引用既有链路订阅
|
|
|
+ // (可属另一份合同);普通附加条目走本合同父条目 → 父条目落成的 `link` 订阅。
|
|
|
+ let parent_id: Option<String> = if items[idx].plan_family == PlanFamily::Addon {
|
|
|
+ Some(resolve_contract_parent(
|
|
|
+ &prefix,
|
|
|
+ it,
|
|
|
+ &items,
|
|
|
+ &existing,
|
|
|
+ &planned_subs,
|
|
|
+ &today,
|
|
|
+ )?)
|
|
|
+ } else {
|
|
|
+ None
|
|
|
+ };
|
|
|
let Some(req) = it.succession.as_ref() else {
|
|
|
- if renew_from.is_some() {
|
|
|
+ // 续签整批带出,或增量条目(D-9:本合同要交付的那部分)⇒ 建订阅。
|
|
|
+ if renew_from.is_some() || it.item_mode == ItemMode::Increment {
|
|
|
let pin = succession::PlanInput {
|
|
|
plan: &plan,
|
|
|
item: Some(&item_row),
|
|
|
@@ -2330,6 +2582,7 @@ async fn plan_contract_subs(
|
|
|
trial_months: None,
|
|
|
discount_monthly_cents: None,
|
|
|
row_version: None,
|
|
|
+ parent_subscription_id: parent_id.as_deref(),
|
|
|
mode: succession::MatchMode::SameCategoryAndExit,
|
|
|
};
|
|
|
let planned = succession::plan_fresh(
|
|
|
@@ -2341,6 +2594,7 @@ async fn plan_contract_subs(
|
|
|
)?;
|
|
|
// 额度随档位(`addon` 额度恒 0)——份数只进 `subscription.quantity`,
|
|
|
// ⛔ 在这里再乘一次(D-15:link 恒 1 份,乘积只会重复计额度)。
|
|
|
+ planned_subs.insert(item_row.item_id.clone(), new_id.clone());
|
|
|
out.fresh.push((idx, planned));
|
|
|
}
|
|
|
continue;
|
|
|
@@ -2385,10 +2639,12 @@ async fn plan_contract_subs(
|
|
|
trial_months: None,
|
|
|
discount_monthly_cents: None,
|
|
|
row_version: None,
|
|
|
+ parent_subscription_id: parent_id.as_deref(),
|
|
|
mode: succession::MatchMode::SameCategoryAndExit,
|
|
|
};
|
|
|
let planned =
|
|
|
succession::plan_fresh(customer_id, &new_id, &pin, &today, &format!("{prefix}:"))?;
|
|
|
+ planned_subs.insert(item_row.item_id.clone(), new_id.clone());
|
|
|
out.fresh.push((idx, planned));
|
|
|
continue;
|
|
|
}
|
|
|
@@ -2403,16 +2659,90 @@ async fn plan_contract_subs(
|
|
|
trial_months: None,
|
|
|
discount_monthly_cents: None,
|
|
|
row_version: None,
|
|
|
+ parent_subscription_id: parent_id.as_deref(),
|
|
|
mode: succession::MatchMode::SameCategoryAndExit,
|
|
|
};
|
|
|
let planned =
|
|
|
succession::plan_change(state, customer_id, orig, &new_id, &pin, &today, &format!("{prefix}:"))
|
|
|
.await?;
|
|
|
+ planned_subs.insert(item_row.item_id.clone(), new_id.clone());
|
|
|
out.replaced.push((idx, planned));
|
|
|
}
|
|
|
Ok(out)
|
|
|
}
|
|
|
|
|
|
+/// 附加条目的父订阅解析(D-2/D-9,**写入事务前**的预演阶段)。
|
|
|
+///
|
|
|
+/// 与订阅台账 [`super::subscription::create`] 的父解析同口径,但多一条"批内先行":
|
|
|
+/// 父条目也在本次合同里且已预演成新订阅时,直接用那条**尚未落库**的订阅号(两阶段建单的前提)。
|
|
|
+fn resolve_contract_parent(
|
|
|
+ prefix: &str,
|
|
|
+ it: &ItemIns,
|
|
|
+ items: &[ItemIns],
|
|
|
+ existing: &[super::subscription::SubRow],
|
|
|
+ planned_subs: &HashMap<String, String>,
|
|
|
+ today: &str,
|
|
|
+) -> Result<String, BosError> {
|
|
|
+ let bad = |msg: String| BosError::klt(KltCode::L222, format!("{prefix}:{msg}"));
|
|
|
+ // ① 增量条目:引用既有链路订阅(跨合同允许)。
|
|
|
+ if it.item_mode == ItemMode::Increment {
|
|
|
+ let rid = it
|
|
|
+ .ref_subscription_id
|
|
|
+ .as_deref()
|
|
|
+ .map(str::trim)
|
|
|
+ .filter(|s| !s.is_empty())
|
|
|
+ .ok_or_else(|| bad("增量条目必须填引用订阅号(D-9)".to_string()))?;
|
|
|
+ let row = existing
|
|
|
+ .iter()
|
|
|
+ .find(|r| r.subscription_id == rid)
|
|
|
+ .ok_or_else(|| bad(format!("引用订阅 {rid} 不属于本客户(D-9)")))?;
|
|
|
+ if row.plan_family.as_deref() != Some(PlanFamily::Link.as_str()) {
|
|
|
+ return Err(bad(format!("引用订阅 {rid} 不是跨境链路(link)订阅(D-9)")));
|
|
|
+ }
|
|
|
+ let st = row.status.trim();
|
|
|
+ if st != "pending" && st != "active" {
|
|
|
+ return Err(bad(format!("引用订阅 {rid} 状态「{st}」,不在期(D-9)")));
|
|
|
+ }
|
|
|
+ if row
|
|
|
+ .end_date
|
|
|
+ .as_deref()
|
|
|
+ .is_some_and(|d| !d.is_empty() && d < today)
|
|
|
+ {
|
|
|
+ return Err(bad(format!("引用订阅 {rid} 已过结束日,不在期(D-9)")));
|
|
|
+ }
|
|
|
+ return Ok(rid.to_string());
|
|
|
+ }
|
|
|
+ // ② 普通附加条目:父条目必须在本合同内(库层 `fk_item_serves` 已兜,这里给出可读错因)。
|
|
|
+ let pid = it
|
|
|
+ .serves_item_id
|
|
|
+ .as_deref()
|
|
|
+ .map(str::trim)
|
|
|
+ .filter(|s| !s.is_empty())
|
|
|
+ .ok_or_else(|| bad("附加条目未选父条目(D-7)".to_string()))?;
|
|
|
+ if !items.iter().any(|i| {
|
|
|
+ i.plan_family == PlanFamily::Link && i.item_id.as_deref() == Some(pid)
|
|
|
+ }) {
|
|
|
+ // 父条目在本次载荷里不是 `link`(或根本不在本合同)⇒ 应用层可读错因;
|
|
|
+ // 「父必须同合同」由库层复合外键 `fk_item_serves` 兜底。
|
|
|
+ return Err(bad(format!(
|
|
|
+ "父条目 {pid} 不是本合同里的跨境链路(link)条目(D-7)"
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ if let Some(new_id) = planned_subs.get(pid) {
|
|
|
+ return Ok(new_id.clone());
|
|
|
+ }
|
|
|
+ if let Some(row) = existing.iter().find(|r| {
|
|
|
+ r.contract_item_id.as_deref() == Some(pid)
|
|
|
+ && r.plan_family.as_deref() == Some(PlanFamily::Link.as_str())
|
|
|
+ && matches!(r.status.trim(), "pending" | "active")
|
|
|
+ }) {
|
|
|
+ return Ok(row.subscription_id.clone());
|
|
|
+ }
|
|
|
+ Err(bad(format!(
|
|
|
+ "父条目 {pid} 还没有对应的跨境链路订阅:请先建父链路订阅,再录附加条目(D-2)"
|
|
|
+ )))
|
|
|
+}
|
|
|
+
|
|
|
/// 条目 → 「替换/续签用的档位行 + 条目行」(合同页两条去向共用同一次查库)。
|
|
|
///
|
|
|
/// D-15 后条目只引用目录里已存在的档位(`catalog_plan`)——自定义档也走目录建档(D-16),
|
|
|
@@ -2441,6 +2771,9 @@ async fn item_plan(
|
|
|
plan_id: Some(pid.to_string()),
|
|
|
quantity: Some(it.quantity.to_string()),
|
|
|
item_family: Some(it.plan_family.as_str().to_string()),
|
|
|
+ item_mode: Some(it.item_mode.as_str().to_string()),
|
|
|
+ serves_item_id: it.serves_item_id.clone(),
|
|
|
+ ref_subscription_id: it.ref_subscription_id.clone(),
|
|
|
line_exits: Some(it.line_exits.clone()),
|
|
|
};
|
|
|
Ok((plan, item_row))
|
|
|
@@ -2451,7 +2784,8 @@ async fn item_plan(
|
|
|
/// 为什么不再是「主键+形态」两列:修改日志要回答「这条到底改了什么」,
|
|
|
/// 只有 id 与形态时只能报「改了一条」,内容级变化说不出来。
|
|
|
async fn stored_items(db: &UdsClient, contract_id: &str) -> Result<Vec<ItemRow>, BosError> {
|
|
|
- let sql = "SELECT item_id, contract_id, plan_id, quantity, item_family, line_exits \
|
|
|
+ let sql = "SELECT item_id, contract_id, plan_id, quantity, item_family, item_mode, \
|
|
|
+ serves_item_id, ref_subscription_id, line_exits \
|
|
|
FROM contract_service_item WHERE contract_id = $1::text ORDER BY item_id";
|
|
|
db.query_all::<ItemRow>(sql, &[Value::String(contract_id.to_string())])
|
|
|
.await
|
|
|
@@ -2795,6 +3129,8 @@ async fn do_update(
|
|
|
for (id, it) in new_ids.into_iter().zip(items.iter_mut().filter(|i| i.item_id.is_none())) {
|
|
|
it.item_id = Some(id);
|
|
|
}
|
|
|
+ // 父条目序号 ⇒ 主键(编辑态:父可能是载荷里的既有条目或本次新增条目)。
|
|
|
+ link_parents(&mut items)?;
|
|
|
let mut upd: Vec<DmlStatement> = Vec::new();
|
|
|
let mut ins: Vec<DmlStatement> = Vec::new();
|
|
|
for it in items.iter() {
|
|
|
@@ -3015,6 +3351,9 @@ struct SubBrief {
|
|
|
/// 订阅份数(2026-11-17):可叠加档可 > 1(例:境外 IP 按个),其余恒 1。
|
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
|
quantity: Option<String>,
|
|
|
+ /// P1(D-2/D-7):附加订阅的父订阅;非空即页面上平铺标「附加于 SUB-xxx」。
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ parent_subscription_id: Option<String>,
|
|
|
}
|
|
|
|
|
|
/// 工单侧只读口一期未接线 ⇒ `opened_state` 恒 `unconfigured`。
|
|
|
@@ -3190,6 +3529,9 @@ fn item_changed(row: &ItemRow, it: &ItemIns) -> bool {
|
|
|
row.plan_id.trim() != it.plan_id.trim()
|
|
|
|| num(row.quantity.as_deref()) != Some(it.quantity)
|
|
|
|| row.item_family.as_deref().map(str::trim) != Some(it.plan_family.as_str())
|
|
|
+ || blank(&row.item_mode).unwrap_or("new") != it.item_mode.as_str()
|
|
|
+ || blank(&row.serves_item_id).map(str::to_string) != it.serves_item_id
|
|
|
+ || blank(&row.ref_subscription_id).map(str::to_string) != it.ref_subscription_id
|
|
|
|| exits_sig(row.line_exits.clone().unwrap_or(Value::Null)) != exits_sig(it.line_exits.clone())
|
|
|
}
|
|
|
|
|
|
@@ -3220,7 +3562,7 @@ fn with_opened(mut v: Value, r: &ContractRow, flags: &HashMap<String, Opened>) -
|
|
|
async fn subscriptions_of(db: &UdsClient, contract_id: &str) -> Result<Vec<Value>, BosError> {
|
|
|
let sql = "SELECT subscription_id, plan_name, status, start_date, end_date, actual_opened_at, \
|
|
|
sub_mode, plan_family, annual_price_cents, monthly_settle_cents, order_no, \
|
|
|
- contract_item_id, replaces_subscription_id, quantity \
|
|
|
+ contract_item_id, replaces_subscription_id, quantity, parent_subscription_id \
|
|
|
FROM subscription WHERE contract_id = $1::text ORDER BY subscription_id";
|
|
|
Ok(db
|
|
|
.query_all::<SubBrief>(sql, &[Value::String(contract_id.to_string())])
|
|
|
@@ -3242,6 +3584,8 @@ async fn subscriptions_of(db: &UdsClient, contract_id: &str) -> Result<Vec<Value
|
|
|
"contract_item_id": s.contract_item_id,
|
|
|
"replaces_subscription_id": s.replaces_subscription_id,
|
|
|
"quantity": s.quantity,
|
|
|
+ // P1(D-7):附加订阅的父;界面据此平铺标「附加于 SUB-xxx」。
|
|
|
+ "parent_subscription_id": s.parent_subscription_id,
|
|
|
})
|
|
|
})
|
|
|
.collect())
|
|
|
@@ -4111,6 +4455,10 @@ mod tests {
|
|
|
plan_id: "P-000001".to_string(),
|
|
|
quantity: 1,
|
|
|
plan_family: PlanFamily::Link,
|
|
|
+ item_mode: ItemMode::New,
|
|
|
+ parent_index: None,
|
|
|
+ serves_item_id: None,
|
|
|
+ ref_subscription_id: None,
|
|
|
line_exits: json!(["CMNET-1"]),
|
|
|
line_exit_key: "k".to_string(),
|
|
|
succession: None,
|
|
|
@@ -4189,6 +4537,9 @@ mod tests {
|
|
|
plan_id: Some("P-000001"),
|
|
|
quantity: Some(1),
|
|
|
item_family: Some("addon"),
|
|
|
+ item_mode: None,
|
|
|
+ serves_ref: None,
|
|
|
+ ref_subscription_id: None,
|
|
|
line_exits: &["CMNET-1".to_string()],
|
|
|
}];
|
|
|
let e = check_contract_items("KL-2026-1", &raw, &plans)
|
|
|
@@ -4205,6 +4556,9 @@ mod tests {
|
|
|
plan_id: Some("P-000001"),
|
|
|
quantity: Some(2),
|
|
|
item_family: None,
|
|
|
+ item_mode: None,
|
|
|
+ serves_ref: None,
|
|
|
+ ref_subscription_id: None,
|
|
|
line_exits: &["CMNET-1".to_string()],
|
|
|
}];
|
|
|
let e = check_contract_items("KL-2026-1", &raw, &plans)
|
|
|
@@ -4234,8 +4588,11 @@ mod tests {
|
|
|
json!("1"),
|
|
|
json!("link"),
|
|
|
Value::String(it.line_exits.to_string()),
|
|
|
+ json!("new"),
|
|
|
+ Value::Null,
|
|
|
+ Value::Null,
|
|
|
],
|
|
|
- "D-15:条目参数位=item_id/contract_id/plan_id/quantity/item_family/line_exits"
|
|
|
+ "P1:条目参数位=D-15 的六列 + item_mode/serves_item_id/ref_subscription_id"
|
|
|
);
|
|
|
// 改写走同一套参数位(`item_update_params` 复用 `item_params` 的 `$3..`)
|
|
|
let u = item_update_params("CT-1", "SI-000036", &it);
|
|
|
@@ -4454,6 +4811,9 @@ mod tests {
|
|
|
plan_id: "P-000001".to_string(),
|
|
|
quantity: Some("1".to_string()),
|
|
|
item_family: Some("link".to_string()),
|
|
|
+ item_mode: Some("new".to_string()),
|
|
|
+ serves_item_id: None,
|
|
|
+ ref_subscription_id: None,
|
|
|
line_exits: Some(json!(["CMNET-1"])),
|
|
|
};
|
|
|
let new = service_shape_of_item(&it);
|