|
|
@@ -0,0 +1,886 @@
|
|
|
+//! 「交付现状」读侧(讨论稿 §7.7/§7.8)。
|
|
|
+//!
|
|
|
+//! 三处消费同一份取数:
|
|
|
+//! * 运营侧客户详情「交付现状」页签(本文件 `list`);
|
|
|
+//! * 订阅详情「当前资源」区块(同一接口,传 `subscription_id`);
|
|
|
+//! * 客户门户套餐详情摘要([`ip_counts_by_subscription`],本模块是台账**唯一**读口)。
|
|
|
+//!
|
|
|
+//! 三条口径(§7.7「三类字段三个来源」,混读即误导):
|
|
|
+//! 1. **在册资源**(境外 IP/IP 出口/申报带宽)只认台账 `subscription_ip_assignment`
|
|
|
+//! 的 `released_at IS NULL` 行——⛔ 用「最新一单」当在册数据源(并单后一单只含部分账号,
|
|
|
+//! `service_open` 又是增量交付);
|
|
|
+//! 2. **实测参数**(内网 IP/实测上下行/实测出口)只认「该账号**最近一次**成功开通回填」的
|
|
|
+//! `ticket_backfill_route` 行——它记录的是那一刻的测值,列头必须带测值日期;
|
|
|
+//! 3. **合同口径**(合同出口 `subscription.line_exits`)与实测出口**两列并排**,不一致时
|
|
|
+//! 两值同时显示并标红(⛔ 用实测覆盖合同,也⛔ 用合同盖掉实测)。
|
|
|
+//!
|
|
|
+//! ⚠️ **端口段本轮不显示也不下发**(D-6):`port_start`/`port_end` 恒 `NULL`,
|
|
|
+//! 显示它只能是整列「—」,反而让运营以为该填。列位与取数口径登记在讨论稿 §5.2
|
|
|
+//! 启用清单第 4 步,启用时再与端口输入框一起上。
|
|
|
+//!
|
|
|
+//! ⚠️ **导出不另立判据**(§6.3 第 7 条既有纪律):[`export`] 与 [`list`] 共用同一段谓词
|
|
|
+//! ([`filter_preds`])与同一列集,⛔ 各写一份 SQL。
|
|
|
+
|
|
|
+use std::collections::{BTreeSet, HashMap};
|
|
|
+
|
|
|
+use axum::extract::State;
|
|
|
+use axum::response::Response;
|
|
|
+use bos_api::extract::{json_err, json_err_data, json_ok, DataBody, RequireAuth};
|
|
|
+use bos_api::AppState;
|
|
|
+use bos_core::error::ErrorCode;
|
|
|
+use bos_core::{BosError, RoleCode};
|
|
|
+use bos_core::page::PageQuery;
|
|
|
+use bos_platform::audit::AuditEvent;
|
|
|
+use bos_platform::clients::uds::de;
|
|
|
+use serde::Deserialize;
|
|
|
+use serde_json::{json, Value};
|
|
|
+
|
|
|
+use super::listq::{as_opt_num, push_in, total, Params};
|
|
|
+use super::partner::customer_scope_pred;
|
|
|
+
|
|
|
+/// 单次导出行上限(与审计导出同族口径:平台单次批量上限 `S10`,⛔ 可调大)。
|
|
|
+///
|
|
|
+/// 超限 ⇒ `KLT-R20903`,三件事都不发生:不产文件、不写审计、不落 OSS 半成品。
|
|
|
+const DELIVERY_EXPORT_ROW_LIMIT: i64 = 20_000;
|
|
|
+
|
|
|
+fn export_row_limit() -> i64 {
|
|
|
+ std::env::var("BOS_DELIVERY_EXPORT_ROW_LIMIT")
|
|
|
+ .ok()
|
|
|
+ .and_then(|v| v.trim().parse::<i64>().ok())
|
|
|
+ .filter(|n| *n > 0)
|
|
|
+ .unwrap_or(DELIVERY_EXPORT_ROW_LIMIT)
|
|
|
+ .min(DELIVERY_EXPORT_ROW_LIMIT)
|
|
|
+}
|
|
|
+
|
|
|
+/// 业务日(东八区):与第 3 册订阅读侧同一口径([`super::subscription::today`])。
|
|
|
+fn today() -> String {
|
|
|
+ super::subscription::today()
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 请求形态 ══════════════════════════
|
|
|
+
|
|
|
+#[derive(Debug, Clone, Deserialize)]
|
|
|
+pub struct DeliveryListReq {
|
|
|
+ #[serde(flatten)]
|
|
|
+ pub pg: PageQuery,
|
|
|
+ pub customer_id: Option<String>,
|
|
|
+ pub subscription_id: Option<String>,
|
|
|
+ pub sub_account_id: Option<String>,
|
|
|
+ /// 关键字:账号登录名/使用人/网络侧账号名/境外 IP/档位名。
|
|
|
+ pub keyword: Option<String>,
|
|
|
+ /// 三态精确过滤:`in_use`/`pending_release`/`released`/`all`;缺省=前两态。
|
|
|
+ pub state: Option<String>,
|
|
|
+ /// 勾选后把「已回收」一并返回(§7.7:第三态需勾选,⛔ 默认显示)。
|
|
|
+ #[serde(default)]
|
|
|
+ pub include_released: bool,
|
|
|
+}
|
|
|
+
|
|
|
+/// 三态(§7.7 表:在用/已到期待回收/已回收)。
|
|
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
|
+enum StatePick {
|
|
|
+ /// 默认视图:在用 + 已到期待回收(=台账未释放)。
|
|
|
+ LiveOnly,
|
|
|
+ InUse,
|
|
|
+ PendingRelease,
|
|
|
+ Released,
|
|
|
+ All,
|
|
|
+}
|
|
|
+
|
|
|
+impl StatePick {
|
|
|
+ fn parse(state: Option<&str>, include_released: bool) -> Result<Self, BosError> {
|
|
|
+ let Some(raw) = state.map(str::trim).filter(|s| !s.is_empty()) else {
|
|
|
+ return Ok(if include_released {
|
|
|
+ StatePick::All
|
|
|
+ } else {
|
|
|
+ StatePick::LiveOnly
|
|
|
+ });
|
|
|
+ };
|
|
|
+ match raw {
|
|
|
+ "in_use" => Ok(StatePick::InUse),
|
|
|
+ "pending_release" => Ok(StatePick::PendingRelease),
|
|
|
+ "released" => Ok(StatePick::Released),
|
|
|
+ "all" => Ok(StatePick::All),
|
|
|
+ other => Err(BosError::bad_params(format!(
|
|
|
+ "state 取值非法:{other}(只接受 in_use/pending_release/released/all)"
|
|
|
+ ))),
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ fn as_str(self) -> &'static str {
|
|
|
+ match self {
|
|
|
+ StatePick::LiveOnly | StatePick::InUse => "in_use",
|
|
|
+ StatePick::PendingRelease => "pending_release",
|
|
|
+ StatePick::Released => "released",
|
|
|
+ StatePick::All => "all",
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 读侧列与 FROM ══════════════════════════
|
|
|
+
|
|
|
+/// 台账行+账号资料+订阅快照+合同出口(+来源工单号)。`p` = `catalog_plan`(档位带宽,
|
|
|
+/// 供「申报带宽」按跨境账号取档位上下行)。
|
|
|
+const SELECT_COLS: &str = "a.id::text AS assign_id, a.subscription_id, a.sub_account_id, \
|
|
|
+ a.overseas_ip, a.egress AS ip_egress, a.ip_type, a.bandwidth_mbps, \
|
|
|
+ a.activated_at::text AS activated_at, a.released_at::text AS released_at, a.release_reason, \
|
|
|
+ sa.customer_id, sa.display_name, sa.net_account, sa.status AS account_status, \
|
|
|
+ u.username, c.customer_name, \
|
|
|
+ sub.plan_name, sub.plan_family, sub.parent_subscription_id, \
|
|
|
+ sub.start_date::text AS sub_start_date, sub.end_date::text AS sub_end_date, \
|
|
|
+ sub.actual_opened_at::text AS actual_opened_at, sub.line_exits, \
|
|
|
+ p.bandwidth_committed, p.bandwidth_up_mbps, p.bandwidth_down_mbps, \
|
|
|
+ tk.ticket_no AS source_ticket_no";
|
|
|
+
|
|
|
+/// `FROM`:三个 JOIN 都是主键/外键一一对应(不产生行膨胀,可安全用于 `COUNT`),
|
|
|
+/// 两个 LEFT JOIN 只为带出「来源回填单号」与「档位带宽」。
|
|
|
+const FROM: &str = "FROM subscription_ip_assignment a \
|
|
|
+ JOIN sub_account sa ON sa.sub_account_id = a.sub_account_id \
|
|
|
+ JOIN subscription sub ON sub.subscription_id = a.subscription_id \
|
|
|
+ LEFT JOIN customer c ON c.customer_id = sa.customer_id \
|
|
|
+ LEFT JOIN bos_user_binding u ON u.user_id = sa.user_id \
|
|
|
+ LEFT JOIN ticket_backfill bf ON bf.backfill_id = a.source_backfill_id \
|
|
|
+ LEFT JOIN ticket tk ON tk.ticket_id = bf.ticket_id \
|
|
|
+ LEFT JOIN catalog_plan p ON p.plan_id = sub.plan_id";
|
|
|
+
|
|
|
+#[derive(Debug, Deserialize)]
|
|
|
+struct DeliveryRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ assign_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ subscription_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ sub_account_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ overseas_ip: String,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ ip_egress: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ ip_type: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ bandwidth_mbps: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ activated_at: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ released_at: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ release_reason: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ customer_id: String,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ display_name: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ net_account: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ account_status: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ username: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ customer_name: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_name: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_family: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ parent_subscription_id: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ sub_start_date: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ sub_end_date: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ actual_opened_at: Option<String>,
|
|
|
+ #[serde(default)]
|
|
|
+ line_exits: Option<Value>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ bandwidth_committed: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ bandwidth_up_mbps: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ bandwidth_down_mbps: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ source_ticket_no: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+/// 实测参数:该账号**最近一次**成功开通回填的那一行 `ticket_backfill_route`。
|
|
|
+#[derive(Debug, Deserialize)]
|
|
|
+struct MeasuredRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ sub_account_id: String,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ intranet_ip: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ egress_pop: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ down_mbps: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ up_mbps: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ measured_at: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+/// 一行交付现状的实测侧(无成功回填 ⇒ `None`,出参逐列回 `null`,⛔ 以空串冒充)。
|
|
|
+#[derive(Debug, Default, Clone)]
|
|
|
+struct Measured {
|
|
|
+ intranet_ip: Option<String>,
|
|
|
+ egress_pop: Option<String>,
|
|
|
+ down_mbps: Option<String>,
|
|
|
+ up_mbps: Option<String>,
|
|
|
+ measured_at: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 谓词(list/export 共用) ══════════════════════════
|
|
|
+
|
|
|
+/// 组装筛选谓词:**列表与导出共用这一份**(⛔ 各自再写一段"近似"SQL)。
|
|
|
+///
|
|
|
+/// 顺序固定(占位符 `$n` 与 `p` 的追加顺序绑定):三态 → 可见范围 → 客户/订阅/分账号 → 关键字。
|
|
|
+async fn filter_preds(
|
|
|
+ state: &AppState,
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
+ p: &mut Params,
|
|
|
+ body: &DeliveryListReq,
|
|
|
+ pick: StatePick,
|
|
|
+) -> Result<Vec<String>, BosError> {
|
|
|
+ let mut preds: Vec<String> = Vec::new();
|
|
|
+ // 三态(§7.7):`released_at` 是台账「当前态」的唯一开关;「已到期待回收」=
|
|
|
+ // 台账未释放 ∧ 订阅 `end_date` 已过(计费按 `end_date` 截断,资源还挂着)。
|
|
|
+ match pick {
|
|
|
+ StatePick::LiveOnly => preds.push("a.released_at IS NULL".to_string()),
|
|
|
+ StatePick::InUse => {
|
|
|
+ let d = p.push(Value::String(today()));
|
|
|
+ preds.push(format!(
|
|
|
+ "a.released_at IS NULL AND (sub.end_date IS NULL OR sub.end_date >= {d}::date)"
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ StatePick::PendingRelease => {
|
|
|
+ let d = p.push(Value::String(today()));
|
|
|
+ preds.push(format!(
|
|
|
+ "a.released_at IS NULL AND sub.end_date IS NOT NULL AND sub.end_date < {d}::date"
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ StatePick::Released => preds.push("a.released_at IS NOT NULL".to_string()),
|
|
|
+ StatePick::All => {}
|
|
|
+ }
|
|
|
+ // 可见范围:复用既有 `customer_scope_pred`(⛔ 新造一套可见性判据)。
|
|
|
+ preds.push(customer_scope_pred(state, auth, p, "sa.customer_id").await?);
|
|
|
+ if let Some(c) = p.push_eq(body.customer_id.as_deref()) {
|
|
|
+ preds.push(format!("sa.customer_id = {c}::text"));
|
|
|
+ }
|
|
|
+ if let Some(s) = p.push_eq(body.subscription_id.as_deref()) {
|
|
|
+ preds.push(format!("a.subscription_id = {s}::text"));
|
|
|
+ }
|
|
|
+ if let Some(s) = p.push_eq(body.sub_account_id.as_deref()) {
|
|
|
+ preds.push(format!("a.sub_account_id = {s}::text"));
|
|
|
+ }
|
|
|
+ if let Some(k) = p.push_like(body.keyword.as_deref()) {
|
|
|
+ preds.push(format!(
|
|
|
+ "(u.username LIKE {k} OR sa.display_name LIKE {k} OR sa.net_account LIKE {k} \
|
|
|
+ OR a.overseas_ip LIKE {k} OR sub.plan_name LIKE {k})"
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ Ok(preds)
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 行整形 ══════════════════════════
|
|
|
+
|
|
|
+/// jsonb 经联邦引擎可能回字符串,取值处⛔ 假定单一形态。
|
|
|
+fn cell(v: Option<Value>) -> Value {
|
|
|
+ match v {
|
|
|
+ Some(Value::String(s)) => serde_json::from_str(&s).unwrap_or(Value::String(s)),
|
|
|
+ Some(v) => v,
|
|
|
+ None => Value::Null,
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+fn opt_trim(v: Option<&String>) -> Option<&str> {
|
|
|
+ v.map(String::as_str).map(str::trim).filter(|s| !s.is_empty())
|
|
|
+}
|
|
|
+
|
|
|
+/// 出口归一化(与 `bos_invariant::normalize_line_exits` 同一算式:去空白+小写)。
|
|
|
+///
|
|
|
+/// 这里只用于**展示口**的「实测出口是否落在合同出口集合内」,⛔ 参与任何写入判据。
|
|
|
+fn exit_key(s: &str) -> String {
|
|
|
+ s.chars()
|
|
|
+ .filter(|c| !c.is_whitespace())
|
|
|
+ .flat_map(char::to_lowercase)
|
|
|
+ .collect()
|
|
|
+}
|
|
|
+
|
|
|
+fn contract_exit_set(raw: &Value) -> Option<BTreeSet<String>> {
|
|
|
+ let arr = raw.as_array()?;
|
|
|
+ let list: Vec<String> = arr
|
|
|
+ .iter()
|
|
|
+ .filter_map(|v| v.as_str())
|
|
|
+ .map(str::to_string)
|
|
|
+ .collect();
|
|
|
+ match bos_invariant::normalize_line_exits(&list) {
|
|
|
+ Ok(n) => Some(n.line_exits.into_iter().collect()),
|
|
|
+ // 空集/超长 ⇒ 无从比对(出参 `exit_mismatch = null`,⛔ 当作「一致」)。
|
|
|
+ Err(_) => None,
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 三态判据(与 [`filter_preds`] 同一段语义,读侧逐行复算)。
|
|
|
+fn three_state(released_at: Option<&str>, end_date: Option<&str>, today: &str) -> &'static str {
|
|
|
+ if released_at.is_some() {
|
|
|
+ return "released";
|
|
|
+ }
|
|
|
+ match end_date {
|
|
|
+ Some(e) if !e.trim().is_empty() && e < today => "pending_release",
|
|
|
+ _ => "in_use",
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+fn row_json(r: &DeliveryRow, m: Option<&Measured>, today: &str) -> Value {
|
|
|
+ let exits = cell(r.line_exits.clone());
|
|
|
+ let exits_json = if exits.is_null() { Value::Null } else { exits.clone() };
|
|
|
+ let measured_exit = m.and_then(|x| x.egress_pop.clone());
|
|
|
+ // 合同出口 vs 实测出口:两者都有才判;实测出口归一后不在合同集合内 ⇒ `true`(前端标红)。
|
|
|
+ let exit_mismatch = match (contract_exit_set(&exits), measured_exit.as_deref()) {
|
|
|
+ (Some(set), Some(me)) if !me.trim().is_empty() => {
|
|
|
+ Value::Bool(!set.contains(&exit_key(me)))
|
|
|
+ }
|
|
|
+ _ => Value::Null,
|
|
|
+ };
|
|
|
+ json!({
|
|
|
+ "assign_id": r.assign_id,
|
|
|
+ "state": three_state(r.released_at.as_deref(), r.sub_end_date.as_deref(), today),
|
|
|
+ "customer_id": r.customer_id,
|
|
|
+ "customer_name": r.customer_name,
|
|
|
+ "subscription_id": r.subscription_id,
|
|
|
+ "plan_name": r.plan_name,
|
|
|
+ "plan_family": r.plan_family,
|
|
|
+ // 附加订阅平铺呈现,只标注「附加于 ⟨父单号⟩」(D-7 第 6 条:⛔ 折叠嵌套)。
|
|
|
+ "parent_subscription_id": r.parent_subscription_id,
|
|
|
+ "sub_start_date": r.sub_start_date,
|
|
|
+ "sub_end_date": r.sub_end_date,
|
|
|
+ "opened_at": r.actual_opened_at,
|
|
|
+ "sub_account_id": r.sub_account_id,
|
|
|
+ "username": r.username,
|
|
|
+ "display_name": r.display_name,
|
|
|
+ "net_account": r.net_account,
|
|
|
+ "account_status": r.account_status,
|
|
|
+ // 在册资源(台账)
|
|
|
+ "overseas_ip": if r.overseas_ip.trim().is_empty() { Value::Null } else { json!(r.overseas_ip) },
|
|
|
+ "ip_egress": r.ip_egress,
|
|
|
+ "ip_type": r.ip_type,
|
|
|
+ "declared_bandwidth_mbps": as_opt_num(r.bandwidth_mbps.as_deref()),
|
|
|
+ "activated_at": r.activated_at,
|
|
|
+ "released_at": r.released_at,
|
|
|
+ "release_reason": r.release_reason,
|
|
|
+ "source_ticket_no": r.source_ticket_no,
|
|
|
+ // 档位规格(跨境账号的「申报带宽」按档位上下行取,见前端列口径)
|
|
|
+ "plan_bandwidth_committed": match r.bandwidth_committed.as_deref() {
|
|
|
+ Some("true") => Value::Bool(true),
|
|
|
+ Some("false") => Value::Bool(false),
|
|
|
+ _ => Value::Null,
|
|
|
+ },
|
|
|
+ "plan_bandwidth_up_mbps": as_opt_num(r.bandwidth_up_mbps.as_deref()),
|
|
|
+ "plan_bandwidth_down_mbps": as_opt_num(r.bandwidth_down_mbps.as_deref()),
|
|
|
+ // 合同口径 vs 实测(§7.7 第 2/3 条:两列并排,⛔ 互相覆盖)
|
|
|
+ "contract_exits": exits_json,
|
|
|
+ "measured_egress": measured_exit,
|
|
|
+ "exit_mismatch": exit_mismatch,
|
|
|
+ // 实测参数(最近一次成功开通回填;`measured_at` 是列头日期)
|
|
|
+ "intranet_ip": m.and_then(|x| x.intranet_ip.clone()),
|
|
|
+ "measured_down_mbps": as_opt_num(m.and_then(|x| x.down_mbps.as_deref())),
|
|
|
+ "measured_up_mbps": as_opt_num(m.and_then(|x| x.up_mbps.as_deref())),
|
|
|
+ "measured_at": m.and_then(|x| x.measured_at.clone()),
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+/// 批量取「该账号最近一次成功开通回填」的实测参数。
|
|
|
+///
|
|
|
+/// ⚠️ 不用 `LATERAL`/`DISTINCT ON`(联邦引擎不支持),也不用相关子查询(`EXISTS` 在派生表上
|
|
|
+/// 会被执行计划拒)⇒ 先按账号取全量候选、在内存里**按排序取第一条**。
|
|
|
+/// `ORDER BY` 必须写全三级(`actual_opened_date` → `updated_at` → `route.id`),否则同日两版
|
|
|
+/// 回填取到哪一版不确定。
|
|
|
+async fn measured_by_account(
|
|
|
+ state: &AppState,
|
|
|
+ accounts: &[String],
|
|
|
+) -> Result<HashMap<String, Measured>, BosError> {
|
|
|
+ let mut out: HashMap<String, Measured> = HashMap::new();
|
|
|
+ // 分片:导出可能一次 2 万行,一次性 `IN (...)` 会撞平台参数上限。
|
|
|
+ for chunk in accounts.chunks(500) {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let in_pred = push_in(&mut p, "r.sub_account_id", chunk, "text");
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT r.sub_account_id, r.intranet_ip, r.egress_pop, r.down_mbps, r.up_mbps, \
|
|
|
+ b.actual_opened_date::text AS measured_at \
|
|
|
+ FROM ticket_backfill_route r \
|
|
|
+ JOIN ticket_backfill b ON b.backfill_id = r.backfill_id \
|
|
|
+ WHERE {in_pred} AND b.exec_conclusion = 'success' \
|
|
|
+ AND b.actual_opened_date IS NOT NULL \
|
|
|
+ ORDER BY r.sub_account_id, b.actual_opened_date DESC, b.updated_at DESC, r.id DESC"
|
|
|
+ );
|
|
|
+ for r in state.db.query_all::<MeasuredRow>(&sql, p.values()).await? {
|
|
|
+ out.entry(r.sub_account_id.clone()).or_insert(Measured {
|
|
|
+ intranet_ip: opt_trim(r.intranet_ip.as_ref()).map(str::to_string),
|
|
|
+ egress_pop: opt_trim(r.egress_pop.as_ref()).map(str::to_string),
|
|
|
+ down_mbps: r.down_mbps.clone(),
|
|
|
+ up_mbps: r.up_mbps.clone(),
|
|
|
+ measured_at: r.measured_at.clone(),
|
|
|
+ });
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Ok(out)
|
|
|
+}
|
|
|
+
|
|
|
+fn page_rows(
|
|
|
+ rows: &[DeliveryRow],
|
|
|
+ measured: &HashMap<String, Measured>,
|
|
|
+ today: &str,
|
|
|
+) -> Vec<Value> {
|
|
|
+ rows.iter()
|
|
|
+ .map(|r| row_json(r, measured.get(&r.sub_account_id), today))
|
|
|
+ .collect()
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 列表 ══════════════════════════
|
|
|
+
|
|
|
+/// `POST /delivery/list@v1`:交付现状(运营侧客户详情页签/订阅详情「当前资源」)。
|
|
|
+///
|
|
|
+/// 角色:`admin`/`opsMain`/`opsSub`/`teamLead`(团队主账号按客户可见范围看本团队客户)。
|
|
|
+/// 可见范围**只**由 [`customer_scope_pred`] 给出,⛔ 另起判据。
|
|
|
+pub async fn list(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<DeliveryListReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[
|
|
|
+ RoleCode::Admin,
|
|
|
+ RoleCode::OpsMain,
|
|
|
+ RoleCode::OpsSub,
|
|
|
+ RoleCode::TeamLead,
|
|
|
+ ]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ match do_list(&state, &auth, &body).await {
|
|
|
+ Ok(v) => json_ok(v),
|
|
|
+ Err(e) => json_err(e),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+async fn do_list(
|
|
|
+ state: &AppState,
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
+ body: &DeliveryListReq,
|
|
|
+) -> Result<Value, BosError> {
|
|
|
+ let pick = StatePick::parse(body.state.as_deref(), body.include_released)?;
|
|
|
+ let today = today();
|
|
|
+ let mut p = Params::default();
|
|
|
+ let preds = filter_preds(state, auth, &mut p, body, pick).await?;
|
|
|
+ let where_sql = p.where_clause(&preds);
|
|
|
+ let n = total(state.db.as_ref(), &format!("{FROM} {where_sql}"), p.values()).await?;
|
|
|
+ let (lim, off) = p.push_page(&body.pg);
|
|
|
+ // 末级 tie-breaker 是台账主键:并单后同一账号常有两行同日、排序不稳定会翻出重复行。
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT {SELECT_COLS} {FROM} {where_sql} \
|
|
|
+ ORDER BY sub.customer_id, a.subscription_id, a.sub_account_id, a.id DESC \
|
|
|
+ LIMIT {lim} OFFSET {off}"
|
|
|
+ );
|
|
|
+ let rows = state.db.query_all::<DeliveryRow>(&sql, p.values()).await?;
|
|
|
+ let accounts: Vec<String> = rows
|
|
|
+ .iter()
|
|
|
+ .map(|r| r.sub_account_id.clone())
|
|
|
+ .collect::<BTreeSet<_>>()
|
|
|
+ .into_iter()
|
|
|
+ .collect();
|
|
|
+ let measured = measured_by_account(state, &accounts).await?;
|
|
|
+ let items = page_rows(&rows, &measured, &today);
|
|
|
+ Ok(json!({
|
|
|
+ "items": items,
|
|
|
+ "total": n,
|
|
|
+ "page": body.pg.page,
|
|
|
+ "page_size": body.pg.page_size,
|
|
|
+ "state": pick.as_str(),
|
|
|
+ "include_released": body.include_released,
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 导出 ══════════════════════════
|
|
|
+
|
|
|
+/// 导出失败的两类形态:普通错误;需随错误下发 `detail` 的业务错误
|
|
|
+/// (`KLT-R20903` 的 `row_count` + `limit`)。
|
|
|
+enum ExportFailure {
|
|
|
+ Plain(BosError),
|
|
|
+ WithDetail(BosError, Value),
|
|
|
+}
|
|
|
+
|
|
|
+impl From<BosError> for ExportFailure {
|
|
|
+ fn from(e: BosError) -> Self {
|
|
|
+ Self::Plain(e)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// `POST /delivery/export@v1`:交付现状导出(CSV)。
|
|
|
+///
|
|
|
+/// 与 [`list`] **同谓词、同列**(§6.3 第 7 条:导出不另立判据);行数上限
|
|
|
+/// [`export_row_limit`](超出 ⇒ `KLT-R20903`,不产文件、不写审计、不落 OSS)。
|
|
|
+/// 产出成功写一条 `object_type='delivery_export'` 留痕(`after_json` 只写筛选条件与
|
|
|
+/// 文件元数据,⛔ 写被导出行的内容);留痕失败 ⇒ `KLT-S405`(文件不回滚、不重试)。
|
|
|
+pub async fn export(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<DeliveryListReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[
|
|
|
+ RoleCode::Admin,
|
|
|
+ RoleCode::OpsMain,
|
|
|
+ RoleCode::OpsSub,
|
|
|
+ RoleCode::TeamLead,
|
|
|
+ ]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ match export_csv(&state, &auth, &body).await {
|
|
|
+ Ok(v) => json_ok(v),
|
|
|
+ Err(ExportFailure::Plain(e)) => json_err(e),
|
|
|
+ Err(ExportFailure::WithDetail(e, d)) => json_err_data(e, d),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+async fn export_csv(
|
|
|
+ state: &AppState,
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
+ body: &DeliveryListReq,
|
|
|
+) -> Result<Value, ExportFailure> {
|
|
|
+ let limit = export_row_limit();
|
|
|
+ let pick = StatePick::parse(body.state.as_deref(), body.include_released)?;
|
|
|
+ let today = today();
|
|
|
+ let mut p = Params::default();
|
|
|
+ let preds = filter_preds(state, auth, &mut p, body, pick).await?;
|
|
|
+ let where_sql = p.where_clause(&preds);
|
|
|
+ let n = total(state.db.as_ref(), &format!("{FROM} {where_sql}"), p.values()).await?;
|
|
|
+ if n > limit {
|
|
|
+ return Err(ExportFailure::WithDetail(
|
|
|
+ BosError::biz(
|
|
|
+ ErrorCode::Business(60903),
|
|
|
+ format!("KLT-R20903 本次可导出行数 {n} 超过上限 {limit},请收窄筛选条件后重试"),
|
|
|
+ ),
|
|
|
+ json!({ "row_count": n, "limit": limit }),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let lim = p.push(Value::from(limit));
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT {SELECT_COLS} {FROM} {where_sql} \
|
|
|
+ ORDER BY sub.customer_id, a.subscription_id, a.sub_account_id, a.id DESC LIMIT {lim}::bigint"
|
|
|
+ );
|
|
|
+ let rows = state.db.query_all::<DeliveryRow>(&sql, p.values()).await?;
|
|
|
+ let accounts: Vec<String> = rows
|
|
|
+ .iter()
|
|
|
+ .map(|r| r.sub_account_id.clone())
|
|
|
+ .collect::<BTreeSet<_>>()
|
|
|
+ .into_iter()
|
|
|
+ .collect();
|
|
|
+ let measured = measured_by_account(state, &accounts).await?;
|
|
|
+
|
|
|
+ let stamp = export_stamp();
|
|
|
+ let file_name = format!("交付现状-{}.csv", stamp.key);
|
|
|
+ let mut csv = String::new();
|
|
|
+ // 第 1 行说明行(`#` 起头,⛔ 与数据表头混用):导出时刻+条件逐项回显+
|
|
|
+ // 文件行数/命中总数+范围裁剪声明(与审计导出同一纪律)。
|
|
|
+ csv.push_str(&format!(
|
|
|
+ "# 导出时刻:{};筛选条件:{};文件行数={};同一谓词命中总数={};\
|
|
|
+ 本文件仅包含导出账号当时可见范围内的记录,范围按当前归属计算,范围调整后重新导出结果会不同\n",
|
|
|
+ stamp.display,
|
|
|
+ filters_echo(body, pick),
|
|
|
+ rows.len(),
|
|
|
+ n
|
|
|
+ ));
|
|
|
+ csv.push_str(
|
|
|
+ "账号,网络账户名,所属订阅,账号状态,开通日,到期日,合同出口,实测出口,内网 IP,\
|
|
|
+ 申报带宽,实测下行,实测上行,实测日期,境外 IP,IP 出口,IP 类型,来源回填单号,\
|
|
|
+ 状态,释放日,释放原因\n",
|
|
|
+ );
|
|
|
+ for r in &rows {
|
|
|
+ let v = row_json(r, measured.get(&r.sub_account_id), &today);
|
|
|
+ // 账号列:使用人显示名优先,缺省回落登录名(⛔ 空列当成"该账号不存在")。
|
|
|
+ let account = opt_trim(r.display_name.as_ref())
|
|
|
+ .or_else(|| opt_trim(r.username.as_ref()))
|
|
|
+ .unwrap_or("");
|
|
|
+ let exits = v["contract_exits"]
|
|
|
+ .as_array()
|
|
|
+ .map(|a| a.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join("、"))
|
|
|
+ .unwrap_or_default();
|
|
|
+ // 申报带宽:跨境账号取档位上下行,IP 侧取台账(D-18 后附加档不带带宽)。
|
|
|
+ let bandwidth = match (
|
|
|
+ v["plan_bandwidth_down_mbps"].as_i64(),
|
|
|
+ v["plan_bandwidth_up_mbps"].as_i64(),
|
|
|
+ v["declared_bandwidth_mbps"].as_i64(),
|
|
|
+ ) {
|
|
|
+ (Some(d), Some(u), _) => format!("档位 下行 {d} / 上行 {u} Mbps"),
|
|
|
+ (_, _, Some(b)) => format!("{b} Mbps"),
|
|
|
+ _ => String::new(),
|
|
|
+ };
|
|
|
+ csv.push_str(&format!(
|
|
|
+ "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n",
|
|
|
+ csv_field(account),
|
|
|
+ csv_field(opt_trim(r.net_account.as_ref()).unwrap_or("")),
|
|
|
+ csv_field(opt_trim(r.plan_name.as_ref()).unwrap_or("")),
|
|
|
+ csv_field(opt_trim(r.account_status.as_ref()).unwrap_or("")),
|
|
|
+ csv_field(opt_trim(r.actual_opened_at.as_ref()).unwrap_or("")),
|
|
|
+ csv_field(opt_trim(r.sub_end_date.as_ref()).unwrap_or("")),
|
|
|
+ csv_field(&exits),
|
|
|
+ csv_field(v["measured_egress"].as_str().unwrap_or("")),
|
|
|
+ csv_field(v["intranet_ip"].as_str().unwrap_or("")),
|
|
|
+ csv_field(&bandwidth),
|
|
|
+ csv_field(&num_text(v["measured_down_mbps"].clone())),
|
|
|
+ csv_field(&num_text(v["measured_up_mbps"].clone())),
|
|
|
+ csv_field(v["measured_at"].as_str().unwrap_or("")),
|
|
|
+ csv_field(v["overseas_ip"].as_str().unwrap_or("")),
|
|
|
+ csv_field(v["ip_egress"].as_str().unwrap_or("")),
|
|
|
+ csv_field(v["ip_type"].as_str().unwrap_or("")),
|
|
|
+ csv_field(v["source_ticket_no"].as_str().unwrap_or("")),
|
|
|
+ csv_field(state_label(v["state"].as_str().unwrap_or(""))),
|
|
|
+ csv_field(v["released_at"].as_str().unwrap_or("")),
|
|
|
+ csv_field(release_reason_label(v["release_reason"].as_str())),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+
|
|
|
+ // 对象键⛔ 走受孤儿巡检管理的两个前缀(`klt/customer/license/`、`klt/contract/attachment/`),
|
|
|
+ // 否则导出文件会被「库内无引用」判据当孤儿删掉。
|
|
|
+ let oss_key = format!("klt/delivery/export/{}/{}", stamp.day, stamp.key);
|
|
|
+ let mut bytes: Vec<u8> = Vec::with_capacity(csv.len() + 3);
|
|
|
+ // UTF-8 BOM:Excel 打开中文列不乱码。
|
|
|
+ bytes.extend_from_slice("\u{feff}".as_bytes());
|
|
|
+ bytes.extend_from_slice(csv.as_bytes());
|
|
|
+ state
|
|
|
+ .platform
|
|
|
+ .oss_upload_object(
|
|
|
+ &state.tenant_id,
|
|
|
+ &state.project_id,
|
|
|
+ &oss_key,
|
|
|
+ "text/csv",
|
|
|
+ bytes,
|
|
|
+ )
|
|
|
+ .await?;
|
|
|
+
|
|
|
+ let after = json!({
|
|
|
+ "filters": {
|
|
|
+ "customer_id": body.customer_id,
|
|
|
+ "subscription_id": body.subscription_id,
|
|
|
+ "sub_account_id": body.sub_account_id,
|
|
|
+ "keyword": body.keyword,
|
|
|
+ "state": pick.as_str(),
|
|
|
+ "include_released": body.include_released,
|
|
|
+ },
|
|
|
+ "row_count": rows.len(),
|
|
|
+ "file_name": file_name,
|
|
|
+ "oss_key": oss_key,
|
|
|
+ "limit": limit,
|
|
|
+ "actor": { "user_id": auth.user_id, "role": auth.role.as_str() },
|
|
|
+ });
|
|
|
+ let ev = AuditEvent {
|
|
|
+ actor_user_id: auth.user_id.clone(),
|
|
|
+ action: "delivery_export".to_string(),
|
|
|
+ resource_type: "delivery_export".to_string(),
|
|
|
+ resource_id: "筛选条件".to_string(),
|
|
|
+ before: None,
|
|
|
+ after: Some(after),
|
|
|
+ detail: None,
|
|
|
+ };
|
|
|
+ if state.db.write_audit(&ev).await.is_err() {
|
|
|
+ tracing::error!(
|
|
|
+ target: "bos_delivery_export_audit_fail_total",
|
|
|
+ file = %file_name,
|
|
|
+ rows = rows.len(),
|
|
|
+ "交付现状导出已完成但未留痕(KLT-S405)"
|
|
|
+ );
|
|
|
+ return Err(ExportFailure::Plain(BosError::biz(
|
|
|
+ ErrorCode::Business(60905),
|
|
|
+ "KLT-S405 导出已完成,但本次未留痕,请联系管理员",
|
|
|
+ )));
|
|
|
+ }
|
|
|
+
|
|
|
+ Ok(json!({
|
|
|
+ "file_name": file_name,
|
|
|
+ "oss_key": oss_key,
|
|
|
+ "row_count": rows.len(),
|
|
|
+ "limit": limit,
|
|
|
+ "truncated": false,
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+fn state_label(code: &str) -> &'static str {
|
|
|
+ match code {
|
|
|
+ "in_use" => "在用",
|
|
|
+ "pending_release" => "已到期待回收",
|
|
|
+ "released" => "已回收",
|
|
|
+ _ => "—",
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+fn release_reason_label(code: Option<&str>) -> &'static str {
|
|
|
+ match code.map(str::trim) {
|
|
|
+ Some("expiry_stop") => "到期停机",
|
|
|
+ Some("service_stop") => "服务停用",
|
|
|
+ Some("updown") => "升降配替换",
|
|
|
+ Some("rebind") => "换绑",
|
|
|
+ Some("manual") => "人工销账",
|
|
|
+ _ => "",
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 导出时刻(东八区)+文件名用的日期/唯一尾巴。
|
|
|
+struct ExportStamp {
|
|
|
+ display: String,
|
|
|
+ day: String,
|
|
|
+ key: String,
|
|
|
+}
|
|
|
+
|
|
|
+fn export_stamp() -> ExportStamp {
|
|
|
+ let now = chrono::Utc::now() + chrono::Duration::hours(8);
|
|
|
+ ExportStamp {
|
|
|
+ display: now.format("%Y-%m-%d %H:%M:%S +08:00").to_string(),
|
|
|
+ day: now.format("%Y%m%d").to_string(),
|
|
|
+ key: now.format("%Y%m%d-%H%M%S-%f").to_string(),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 筛选条件逐项回显(写进说明行;⛔ 写入被导出行的内容)。
|
|
|
+fn filters_echo(b: &DeliveryListReq, pick: StatePick) -> String {
|
|
|
+ let mut parts: Vec<String> = Vec::new();
|
|
|
+ parts.push(format!(
|
|
|
+ "客户={}",
|
|
|
+ b.customer_id.as_deref().unwrap_or("全部可见")
|
|
|
+ ));
|
|
|
+ parts.push(format!(
|
|
|
+ "订阅={}",
|
|
|
+ b.subscription_id.as_deref().unwrap_or("全部")
|
|
|
+ ));
|
|
|
+ parts.push(format!(
|
|
|
+ "分账号={}",
|
|
|
+ b.sub_account_id.as_deref().unwrap_or("全部")
|
|
|
+ ));
|
|
|
+ parts.push(format!("状态={}", state_label(pick.as_str())));
|
|
|
+ parts.push(format!(
|
|
|
+ "关键字={}",
|
|
|
+ b.keyword.as_deref().unwrap_or("无")
|
|
|
+ ));
|
|
|
+ parts.join("、")
|
|
|
+}
|
|
|
+
|
|
|
+/// JSON 数值 → CSV 单元格:`null` ⇒ 空串(⛔ 写出字面 `null` 让 Excel 当文本)。
|
|
|
+fn num_text(v: Value) -> String {
|
|
|
+ match v {
|
|
|
+ Value::Null => String::new(),
|
|
|
+ Value::Number(n) => n.to_string(),
|
|
|
+ Value::String(s) => s.trim().to_string(),
|
|
|
+ other => other.to_string(),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// CSV 字段转义(RFC4180:含逗号/引号/换行时整体加引号,内部引号翻倍)。
|
|
|
+fn csv_field(s: &str) -> String {
|
|
|
+ if s.chars().any(|c| matches!(c, ',' | '"' | '\n' | '\r')) {
|
|
|
+ format!("\"{}\"", s.replace('"', "\"\""))
|
|
|
+ } else {
|
|
|
+ s.to_string()
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// ══════════════════════════ 门户摘要(第 9 册) ══════════════════════════
|
|
|
+
|
|
|
+/// 单条订阅的在册/已回收 IP 计数(门户「套餐详情」只读摘要用)。
|
|
|
+#[derive(Debug, Clone, Copy, Default)]
|
|
|
+pub(crate) struct IpCounts {
|
|
|
+ pub live: i64,
|
|
|
+ pub released: i64,
|
|
|
+ pub live_accounts: i64,
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Debug, Deserialize)]
|
|
|
+struct SubCountRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ subscription_id: String,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ live: Option<String>,
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
+ released: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Debug, Deserialize)]
|
|
|
+struct SubAccountCountRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ subscription_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ n: String,
|
|
|
+}
|
|
|
+
|
|
|
+/// 按订阅聚合「该客户」的在册 IP 数与在用账号数。
|
|
|
+///
|
|
|
+/// ⚠️ 这是台账的**第二个读口**(第一个是 [`list`]),也是第 9 册门户唯一允许的台账取数:
|
|
|
+/// `portal.rs` 内⛔ 再写台账 SQL(该册 A54「零扩张」),一律经本函数。
|
|
|
+pub(crate) async fn ip_counts_by_subscription(
|
|
|
+ state: &AppState,
|
|
|
+ customer_id: &str,
|
|
|
+) -> Result<HashMap<String, IpCounts>, BosError> {
|
|
|
+ let mut out: HashMap<String, IpCounts> = HashMap::new();
|
|
|
+ if customer_id.trim().is_empty() {
|
|
|
+ return Ok(out);
|
|
|
+ }
|
|
|
+ let mut p = Params::default();
|
|
|
+ let c = p.push(Value::String(customer_id.to_string()));
|
|
|
+ // 计数用 `SUM(CASE …)` 而非 `FILTER`/`COUNT(DISTINCT CASE …)`:联邦引擎对后两者支持有边界。
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT a.subscription_id, \
|
|
|
+ SUM(CASE WHEN a.released_at IS NULL THEN 1 ELSE 0 END) AS live, \
|
|
|
+ SUM(CASE WHEN a.released_at IS NOT NULL THEN 1 ELSE 0 END) AS released \
|
|
|
+ FROM subscription_ip_assignment a \
|
|
|
+ JOIN subscription sub ON sub.subscription_id = a.subscription_id \
|
|
|
+ WHERE sub.customer_id = {c}::text GROUP BY a.subscription_id"
|
|
|
+ );
|
|
|
+ for r in state.db.query_all::<SubCountRow>(&sql, p.values()).await? {
|
|
|
+ let e = out.entry(r.subscription_id).or_default();
|
|
|
+ e.live = r.live.as_deref().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
|
|
|
+ e.released = r
|
|
|
+ .released
|
|
|
+ .as_deref()
|
|
|
+ .and_then(|s| s.trim().parse().ok())
|
|
|
+ .unwrap_or(0);
|
|
|
+ }
|
|
|
+ // 在用账号数:派生表先 `DISTINCT (订阅, 账号)` 再按订阅计数(⛔ 用 COUNT(DISTINCT CASE …))。
|
|
|
+ let mut q = Params::default();
|
|
|
+ let c2 = q.push(Value::String(customer_id.to_string()));
|
|
|
+ let sql2 = format!(
|
|
|
+ "SELECT z.subscription_id, COUNT(1) AS n FROM (\
|
|
|
+ SELECT DISTINCT a.subscription_id, a.sub_account_id \
|
|
|
+ FROM subscription_ip_assignment a \
|
|
|
+ JOIN subscription sub ON sub.subscription_id = a.subscription_id \
|
|
|
+ WHERE a.released_at IS NULL AND sub.customer_id = {c2}::text\
|
|
|
+ ) z GROUP BY z.subscription_id"
|
|
|
+ );
|
|
|
+ for r in state.db.query_all::<SubAccountCountRow>(&sql2, q.values()).await? {
|
|
|
+ let e = out.entry(r.subscription_id).or_default();
|
|
|
+ e.live_accounts = r.n.trim().parse().unwrap_or(0);
|
|
|
+ }
|
|
|
+ Ok(out)
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn three_state_judgement() {
|
|
|
+ assert_eq!(three_state(Some("2026-11-01"), Some("2026-12-31"), "2026-11-19"), "released");
|
|
|
+ assert_eq!(three_state(None, Some("2026-11-18"), "2026-11-19"), "pending_release");
|
|
|
+ assert_eq!(three_state(None, Some("2026-11-19"), "2026-11-19"), "in_use");
|
|
|
+ // 无到期日=长期有效 ⇒ 在用(⛔ 判成已到期)。
|
|
|
+ assert_eq!(three_state(None, None, "2026-11-19"), "in_use");
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn state_pick_default_and_parse() {
|
|
|
+ assert_eq!(StatePick::parse(None, false).unwrap(), StatePick::LiveOnly);
|
|
|
+ assert_eq!(StatePick::parse(None, true).unwrap(), StatePick::All);
|
|
|
+ assert_eq!(StatePick::parse(Some("released"), false).unwrap(), StatePick::Released);
|
|
|
+ assert!(StatePick::parse(Some("bogus"), false).is_err());
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn exit_mismatch_is_set_based_not_string_equal() {
|
|
|
+ // 合同出口 `["美国","日本"]` vs 实测 `日本 ` ⇒ 归一后命中,⛔ 判成不一致。
|
|
|
+ let set = contract_exit_set(&json!(["美国", "日本"])).unwrap();
|
|
|
+ assert!(set.contains(&exit_key(" 日本 ")));
|
|
|
+ assert!(!set.contains(&exit_key("新加坡")));
|
|
|
+ }
|
|
|
+}
|