|
@@ -166,9 +166,6 @@ const PLAN_FROM: &str = "FROM catalog_plan p \
|
|
|
LEFT JOIN bos_account_ext a ON a.user_id = u.user_id \
|
|
LEFT JOIN bos_account_ext a ON a.user_id = u.user_id \
|
|
|
LEFT JOIN ent_team et ON et.team_id = u.subject_id AND u.subject_type = 'ent_team' \
|
|
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'";
|
|
LEFT JOIN ops_team ot ON ot.team_id = u.subject_id AND u.subject_type = 'ops_team'";
|
|
|
-/// 成本项读侧列集。
|
|
|
|
|
-const COST_COLS: &str = "item_id, plan_id, item_name, amount_cents, billing_unit, category, \
|
|
|
|
|
- remark, sort_no, created_at";
|
|
|
|
|
|
|
|
|
|
// ══════════════════════════════ 请求形态 ══════════════════════════════
|
|
// ══════════════════════════════ 请求形态 ══════════════════════════════
|
|
|
|
|
|
|
@@ -275,9 +272,13 @@ pub struct PlanCostSaveReq {
|
|
|
pub extra: HashMap<String, Value>,
|
|
pub extra: HashMap<String, Value>,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-/// 成本项单条录入(§3.5:名称是弱引用,⛔ 校验是否在全局清单里)。
|
|
|
|
|
|
|
+/// 成本项单条录入(D-1:以 `cost_item_id` 强引用全局 `cost_item`,名称/类别/计费口径由
|
|
|
|
|
+/// 服务端快照全局现值;前端⛔ 自由文本录名,只能从全局清单按 id 选择)。
|
|
|
#[derive(Deserialize, Clone)]
|
|
#[derive(Deserialize, Clone)]
|
|
|
pub struct CostItemReq {
|
|
pub struct CostItemReq {
|
|
|
|
|
+ /// 全局成本项 id(必填,强引用)。
|
|
|
|
|
+ pub cost_item_id: Option<String>,
|
|
|
|
|
+ /// 名称仅作回显/兼容,保存时以全局现名快照覆盖。
|
|
|
pub item_name: Option<String>,
|
|
pub item_name: Option<String>,
|
|
|
pub amount_cents: Option<i64>,
|
|
pub amount_cents: Option<i64>,
|
|
|
pub billing_unit: Option<String>,
|
|
pub billing_unit: Option<String>,
|
|
@@ -346,6 +347,16 @@ struct PlanRow {
|
|
|
/// 建档团队可读名(`ent_team`/`ops_team` 现名;`hq` 账号回落「总运营」)。
|
|
/// 建档团队可读名(`ent_team`/`ops_team` 现名;`hq` 账号回落「总运营」)。
|
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
|
created_team_name: Option<String>,
|
|
created_team_name: Option<String>,
|
|
|
|
|
+ /// 列表页 CTE 回填:订阅引用数(其它读口缺省)。
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ sub_ref_count: Option<String>,
|
|
|
|
|
+ /// 列表页 CTE 回填:成本项条数/已配金额条数/金额合计(其它读口缺省)。
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ cost_item_count: Option<String>,
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ cost_configured_count: Option<String>,
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ cost_sum_cents: Option<String>,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
#[derive(Deserialize)]
|
|
@@ -354,6 +365,7 @@ struct CostRow {
|
|
|
item_id: String,
|
|
item_id: String,
|
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
|
plan_id: Option<String>,
|
|
plan_id: Option<String>,
|
|
|
|
|
+ /// 读时 JOIN 全局 `cost_item` 取现名(NULL 回落到 `pci.item_name` 快照)。
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
|
item_name: String,
|
|
item_name: String,
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
@@ -368,6 +380,8 @@ struct CostRow {
|
|
|
sort_no: Option<String>,
|
|
sort_no: Option<String>,
|
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
#[serde(deserialize_with = "de::as_opt_string")]
|
|
|
created_at: Option<String>,
|
|
created_at: Option<String>,
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ cost_item_id: Option<String>,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
#[derive(Deserialize)]
|
|
@@ -812,8 +826,11 @@ fn check_bandwidth(
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
/// 校验通过的成本项行(`sort_no` 缺省=载荷行号,保证读回顺序稳定)。
|
|
/// 校验通过的成本项行(`sort_no` 缺省=载荷行号,保证读回顺序稳定)。
|
|
|
|
|
+/// `cost_item_id`=全局强引用;`item_name`/`category`/`billing_unit`=保存时从全局项快照
|
|
|
|
|
+/// 的现值(读时仍以 JOIN 现名为准,快照仅兜底历史 NULL 行与全局项被删的极端情况)。
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
struct CleanCostItem {
|
|
struct CleanCostItem {
|
|
|
|
|
+ cost_item_id: String,
|
|
|
item_name: String,
|
|
item_name: String,
|
|
|
amount_cents: i64,
|
|
amount_cents: i64,
|
|
|
billing_unit: Option<String>,
|
|
billing_unit: Option<String>,
|
|
@@ -822,8 +839,10 @@ struct CleanCostItem {
|
|
|
sort_no: i64,
|
|
sort_no: i64,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-/// 成本项整段校验(§3.5):只校验非空与长度、⛔ 校验是否在全局清单里;
|
|
|
|
|
-/// 同档位重名 ⇒ `K206` + `fields[]`(前端行内红显要 `field`/`index`)。
|
|
|
|
|
|
|
+/// 成本项整段校验(D-1:以 `cost_item_id` 强引用全局 `cost_item`):
|
|
|
|
|
+/// - `cost_item_id` 必填且须在全局清单存在(存在性由 [`resolve_cost_item_refs`] 异步校验);
|
|
|
|
|
+/// - 同档位 `cost_item_id` 重复 ⇒ `K206` + `fields[]`(前端行内红显要 `field`/`index`);
|
|
|
|
|
+/// - 金额/长度/字典值仍在本同步函数内校验(便于单测)。
|
|
|
fn validate_cost_items(items: &[CostItemReq]) -> Result<Vec<CleanCostItem>, CatalogErr> {
|
|
fn validate_cost_items(items: &[CostItemReq]) -> Result<Vec<CleanCostItem>, CatalogErr> {
|
|
|
if items.len() > COST_ITEMS_MAX {
|
|
if items.len() > COST_ITEMS_MAX {
|
|
|
let msg = format!("成本项最多 {COST_ITEMS_MAX} 条(收到 {})", items.len());
|
|
let msg = format!("成本项最多 {COST_ITEMS_MAX} 条(收到 {})", items.len());
|
|
@@ -844,20 +863,31 @@ fn validate_cost_items(items: &[CostItemReq]) -> Result<Vec<CleanCostItem>, Cata
|
|
|
"一期 plan_cost_item 无 copies 列,份数语义未落库(差额登 18 册)",
|
|
"一期 plan_cost_item 无 copies 列,份数语义未落库(差额登 18 册)",
|
|
|
));
|
|
));
|
|
|
}
|
|
}
|
|
|
- let name = match norm(it.item_name.as_deref()) {
|
|
|
|
|
|
|
+ // D-1:以 cost_item_id 强引用全局项;名称不再是引用键,载荷里的 item_name 只做
|
|
|
|
|
+ // 长度兜底(空串留给 resolve 阶段用全局现名覆盖)。
|
|
|
|
|
+ let cid = match norm(it.cost_item_id.as_deref()) {
|
|
|
Some(n) => n,
|
|
Some(n) => n,
|
|
|
None => {
|
|
None => {
|
|
|
- fields.push(field_entry("items[].item_name", Some(i), "成本项名称不能为空"));
|
|
|
|
|
|
|
+ fields.push(field_entry(
|
|
|
|
|
+ "items[].cost_item_id",
|
|
|
|
|
+ Some(i),
|
|
|
|
|
+ "成本项不能为空(请从全局成本项清单中选择)",
|
|
|
|
|
+ ));
|
|
|
continue;
|
|
continue;
|
|
|
}
|
|
}
|
|
|
};
|
|
};
|
|
|
- if name.chars().count() > COST_NAME_MAX {
|
|
|
|
|
- fields.push(field_entry(
|
|
|
|
|
- "items[].item_name",
|
|
|
|
|
- Some(i),
|
|
|
|
|
- &format!("成本项名称超长(上限 {COST_NAME_MAX} 字符)"),
|
|
|
|
|
- ));
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ let name = match norm(it.item_name.as_deref()) {
|
|
|
|
|
+ Some(n) if n.chars().count() <= COST_NAME_MAX => n,
|
|
|
|
|
+ Some(_) => {
|
|
|
|
|
+ fields.push(field_entry(
|
|
|
|
|
+ "items[].item_name",
|
|
|
|
|
+ Some(i),
|
|
|
|
|
+ &format!("成本项名称超长(上限 {COST_NAME_MAX} 字符)"),
|
|
|
|
|
+ ));
|
|
|
|
|
+ continue;
|
|
|
|
|
+ }
|
|
|
|
|
+ None => String::new(),
|
|
|
|
|
+ };
|
|
|
let amount = match it.amount_cents {
|
|
let amount = match it.amount_cents {
|
|
|
Some(v) if v >= 0 && v <= MAX_AMOUNT_CENTS => v,
|
|
Some(v) if v >= 0 && v <= MAX_AMOUNT_CENTS => v,
|
|
|
Some(v) => {
|
|
Some(v) => {
|
|
@@ -904,6 +934,7 @@ fn validate_cost_items(items: &[CostItemReq]) -> Result<Vec<CleanCostItem>, Cata
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
clean.push(CleanCostItem {
|
|
clean.push(CleanCostItem {
|
|
|
|
|
+ cost_item_id: cid,
|
|
|
item_name: name,
|
|
item_name: name,
|
|
|
amount_cents: amount,
|
|
amount_cents: amount,
|
|
|
billing_unit: unit,
|
|
billing_unit: unit,
|
|
@@ -913,14 +944,14 @@ fn validate_cost_items(items: &[CostItemReq]) -> Result<Vec<CleanCostItem>, Cata
|
|
|
});
|
|
});
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // 同档位重名 ⇒ K206(`UNIQUE(plan_id,item_name)` 兜底未落库 ⇒ 应用层先查后判)。
|
|
|
|
|
|
|
+ // 同档位 cost_item_id 重复 ⇒ K206(DB 端 `uq_plan_cost_item_plan_cost_item` 部分唯一索引兜底)。
|
|
|
let mut dup_fields: Vec<Value> = Vec::new();
|
|
let mut dup_fields: Vec<Value> = Vec::new();
|
|
|
for (idx, c) in clean.iter().enumerate() {
|
|
for (idx, c) in clean.iter().enumerate() {
|
|
|
- if clean[..idx].iter().any(|p| p.item_name == c.item_name) {
|
|
|
|
|
|
|
+ if clean[..idx].iter().any(|p| p.cost_item_id == c.cost_item_id) {
|
|
|
dup_fields.push(field_entry(
|
|
dup_fields.push(field_entry(
|
|
|
- "items[].item_name",
|
|
|
|
|
|
|
+ "items[].cost_item_id",
|
|
|
Some(idx as i64),
|
|
Some(idx as i64),
|
|
|
- &format!("同一档位内成本项名称重复:{}", c.item_name),
|
|
|
|
|
|
|
+ &format!("同一档位内成本项重复:{}(cost_item_id={})", c.item_name, c.cost_item_id),
|
|
|
));
|
|
));
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
@@ -930,13 +961,67 @@ fn validate_cost_items(items: &[CostItemReq]) -> Result<Vec<CleanCostItem>, Cata
|
|
|
}
|
|
}
|
|
|
if !dup_fields.is_empty() {
|
|
if !dup_fields.is_empty() {
|
|
|
return Err(CatalogErr::WithData(
|
|
return Err(CatalogErr::WithData(
|
|
|
- BosError::klt(KltCode::K206, "同一档位内成本项名称重复"),
|
|
|
|
|
|
|
+ BosError::klt(KltCode::K206, "同一档位内成本项重复"),
|
|
|
json!({ "fields": dup_fields, "detail": { "fields": dup_fields } }),
|
|
json!({ "fields": dup_fields, "detail": { "fields": dup_fields } }),
|
|
|
));
|
|
));
|
|
|
}
|
|
}
|
|
|
Ok(clean)
|
|
Ok(clean)
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+/// D-1:按 `cost_item_id` 批量回查全局 `cost_item`,把当前 `item_name`/`category`/
|
|
|
|
|
+/// `billing_unit` 快照进 [`CleanCostItem`];任一 id 不存在 ⇒ `60005` 显式失败(⛔ 存一条悬空行,
|
|
|
|
|
+/// 改名弱引用时代已废)。
|
|
|
|
|
+async fn resolve_cost_item_refs(
|
|
|
|
|
+ db: &UdsClient,
|
|
|
|
|
+ clean: &mut Vec<CleanCostItem>,
|
|
|
|
|
+) -> Result<(), CatalogErr> {
|
|
|
|
|
+ if clean.is_empty() {
|
|
|
|
|
+ return Ok(());
|
|
|
|
|
+ }
|
|
|
|
|
+ let ids: Vec<String> = clean.iter().map(|c| c.cost_item_id.clone()).collect();
|
|
|
|
|
+ let mut p = Params::default();
|
|
|
|
|
+ let in_pred = listq::push_in(&mut p, "item_id", &ids, "text");
|
|
|
|
|
+ let sql = format!(
|
|
|
|
|
+ "SELECT item_id, item_name, category, billing_unit FROM cost_item WHERE {in_pred}"
|
|
|
|
|
+ );
|
|
|
|
|
+ #[derive(Deserialize)]
|
|
|
|
|
+ struct RefRow {
|
|
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
|
|
+ item_id: String,
|
|
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
|
|
+ item_name: String,
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ category: Option<String>,
|
|
|
|
|
+ #[serde(default, deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ billing_unit: Option<String>,
|
|
|
|
|
+ }
|
|
|
|
|
+ let found = db.query_all::<RefRow>(&sql, p.values()).await?;
|
|
|
|
|
+ let mut map: HashMap<String, RefRow> = HashMap::with_capacity(found.len());
|
|
|
|
|
+ for r in found {
|
|
|
|
|
+ map.insert(r.item_id.clone(), r);
|
|
|
|
|
+ }
|
|
|
|
|
+ let mut missing: Vec<String> = Vec::new();
|
|
|
|
|
+ for c in clean.iter_mut() {
|
|
|
|
|
+ match map.get(&c.cost_item_id) {
|
|
|
|
|
+ Some(r) => {
|
|
|
|
|
+ c.item_name = r.item_name.trim().to_string();
|
|
|
|
|
+ c.category = r.category.clone();
|
|
|
|
|
+ c.billing_unit = r.billing_unit.clone();
|
|
|
|
|
+ }
|
|
|
|
|
+ None => missing.push(c.cost_item_id.clone()),
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if !missing.is_empty() {
|
|
|
|
|
+ missing.sort();
|
|
|
|
|
+ missing.dedup();
|
|
|
|
|
+ return Err(CatalogErr::Plain(BosError::not_found(format!(
|
|
|
|
|
+ "成本项不存在:{}",
|
|
|
|
|
+ missing.join("、")
|
|
|
|
|
+ ))));
|
|
|
|
|
+ }
|
|
|
|
|
+ Ok(())
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
// ══════════════════════════════ 出参组装 ══════════════════════════════
|
|
// ══════════════════════════════ 出参组装 ══════════════════════════════
|
|
|
|
|
|
|
|
/// 在册列给真值,缺册列([`COLUMNS_PENDING`])给 `null`。
|
|
/// 在册列给真值,缺册列([`COLUMNS_PENDING`])给 `null`。
|
|
@@ -996,6 +1081,7 @@ fn cost_json(r: CostRow) -> Value {
|
|
|
json!({
|
|
json!({
|
|
|
"item_id": r.item_id,
|
|
"item_id": r.item_id,
|
|
|
"plan_id": r.plan_id,
|
|
"plan_id": r.plan_id,
|
|
|
|
|
+ "cost_item_id": r.cost_item_id,
|
|
|
"item_name": r.item_name,
|
|
"item_name": r.item_name,
|
|
|
"amount_cents": as_num(&r.amount_cents),
|
|
"amount_cents": as_num(&r.amount_cents),
|
|
|
"billing_unit": r.billing_unit,
|
|
"billing_unit": r.billing_unit,
|
|
@@ -1213,9 +1299,19 @@ async fn referred_count(db: &UdsClient, plan_id: &str) -> Result<i64, BosError>
|
|
|
async fn cost_items_of(db: &UdsClient, plan_id: &str) -> Result<Vec<Value>, BosError> {
|
|
async fn cost_items_of(db: &UdsClient, plan_id: &str) -> Result<Vec<Value>, BosError> {
|
|
|
let mut p = Params::default();
|
|
let mut p = Params::default();
|
|
|
let pid = p.push(Value::String(plan_id.to_string()));
|
|
let pid = p.push(Value::String(plan_id.to_string()));
|
|
|
|
|
+ // D-1:名称/类别/计费口径 JOIN 全局 `cost_item` 取现名(全局改名 ⇒ 套餐侧跟随);
|
|
|
|
|
+ // `cost_item_id` 为 NULL 的历史行回落到 `pci` 快照字段(COALESCE),保证读口不断裂。
|
|
|
let sql = format!(
|
|
let sql = format!(
|
|
|
- "SELECT {COST_COLS} FROM plan_cost_item WHERE plan_id = {pid}::text \
|
|
|
|
|
- ORDER BY sort_no, item_id"
|
|
|
|
|
|
|
+ "SELECT pci.item_id, pci.plan_id, \
|
|
|
|
|
+ COALESCE(ci.item_name, pci.item_name) AS item_name, \
|
|
|
|
|
+ pci.amount_cents, \
|
|
|
|
|
+ COALESCE(ci.billing_unit, pci.billing_unit) AS billing_unit, \
|
|
|
|
|
+ COALESCE(ci.category, pci.category) AS category, \
|
|
|
|
|
+ pci.remark, pci.sort_no, pci.created_at, pci.cost_item_id \
|
|
|
|
|
+ FROM plan_cost_item pci \
|
|
|
|
|
+ LEFT JOIN cost_item ci ON ci.item_id = pci.cost_item_id \
|
|
|
|
|
+ WHERE pci.plan_id = {pid}::text \
|
|
|
|
|
+ ORDER BY pci.sort_no, pci.item_id"
|
|
|
);
|
|
);
|
|
|
Ok(db
|
|
Ok(db
|
|
|
.query_all::<CostRow>(&sql, p.values())
|
|
.query_all::<CostRow>(&sql, p.values())
|
|
@@ -1473,6 +1569,7 @@ fn cost_insert_statements(items: &[CleanCostItem], plan_id: &str, first: i64) ->
|
|
|
let phs = [
|
|
let phs = [
|
|
|
p.push(Value::String(item_id)),
|
|
p.push(Value::String(item_id)),
|
|
|
p.push(Value::String(plan_id.to_string())),
|
|
p.push(Value::String(plan_id.to_string())),
|
|
|
|
|
+ p.push(Value::String(it.cost_item_id.clone())),
|
|
|
p.push(Value::String(it.item_name.clone())),
|
|
p.push(Value::String(it.item_name.clone())),
|
|
|
p.push(Value::from(it.amount_cents)),
|
|
p.push(Value::from(it.amount_cents)),
|
|
|
push_opt_str(&mut p, it.billing_unit.clone()),
|
|
push_opt_str(&mut p, it.billing_unit.clone()),
|
|
@@ -1484,7 +1581,7 @@ fn cost_insert_statements(items: &[CleanCostItem], plan_id: &str, first: i64) ->
|
|
|
}
|
|
}
|
|
|
vec![DmlStatement::new(
|
|
vec![DmlStatement::new(
|
|
|
format!(
|
|
format!(
|
|
|
- "INSERT INTO plan_cost_item (item_id, plan_id, item_name, amount_cents, \
|
|
|
|
|
|
|
+ "INSERT INTO plan_cost_item (item_id, plan_id, cost_item_id, item_name, amount_cents, \
|
|
|
billing_unit, category, remark, sort_no) VALUES {}",
|
|
billing_unit, category, remark, sort_no) VALUES {}",
|
|
|
value_rows.join(", ")
|
|
value_rows.join(", ")
|
|
|
),
|
|
),
|
|
@@ -1743,10 +1840,14 @@ async fn do_create(
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- let cost_items = match b.cost_items.as_deref() {
|
|
|
|
|
|
|
+ let mut cost_items = match b.cost_items.as_deref() {
|
|
|
Some(items) => Some(validate_cost_items(items)?),
|
|
Some(items) => Some(validate_cost_items(items)?),
|
|
|
None => None,
|
|
None => None,
|
|
|
};
|
|
};
|
|
|
|
|
+ // D-1:按 id 回查全局项,快照现名/类别/计费口径;id 不存在 ⇒ 60005 拒绝(⛔ 存悬空行)。
|
|
|
|
|
+ if let Some(items) = cost_items.as_mut() {
|
|
|
|
|
+ resolve_cost_item_refs(state.db.as_ref(), items).await?;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
let seq = listq::next_seq(state.db.as_ref(), "catalog_plan", "catalog_plan", year_now()?).await?;
|
|
let seq = listq::next_seq(state.db.as_ref(), "catalog_plan", "catalog_plan", year_now()?).await?;
|
|
|
let plan_id = format!("P-{seq:06}");
|
|
let plan_id = format!("P-{seq:06}");
|
|
@@ -2033,10 +2134,14 @@ async fn do_update(
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- let cost_items = match b.cost_items.as_deref() {
|
|
|
|
|
|
|
+ let mut cost_items = match b.cost_items.as_deref() {
|
|
|
Some(items) => Some(validate_cost_items(items)?),
|
|
Some(items) => Some(validate_cost_items(items)?),
|
|
|
None => None,
|
|
None => None,
|
|
|
};
|
|
};
|
|
|
|
|
+ // D-1:按 id 回查全局项,快照现名/类别/计费口径;id 不存在 ⇒ 60005 拒绝(⛔ 存悬空行)。
|
|
|
|
|
+ if let Some(items) = cost_items.as_mut() {
|
|
|
|
|
+ resolve_cost_item_refs(state.db.as_ref(), items).await?;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
// ④ 写。两段一批:① 「档位更新 + 改名同步未到期订阅」=**同一个 dml_batch**(§3.6 明文
|
|
// ④ 写。两段一批:① 「档位更新 + 改名同步未到期订阅」=**同一个 dml_batch**(§3.6 明文
|
|
|
// 同事务,改名那条带「主写确实落库」守卫);② 成本项整段替换=另一个 dml_batch(§3.5
|
|
// 同事务,改名那条带「主写确实落库」守卫);② 成本项整段替换=另一个 dml_batch(§3.5
|
|
@@ -2357,7 +2462,9 @@ async fn do_plan_cost_save(
|
|
|
})?;
|
|
})?;
|
|
|
let row = load_writable_plan(state, auth, &plan_id).await?;
|
|
let row = load_writable_plan(state, auth, &plan_id).await?;
|
|
|
let items_in = b.items.clone().unwrap_or_default();
|
|
let items_in = b.items.clone().unwrap_or_default();
|
|
|
- let items = validate_cost_items(&items_in)?;
|
|
|
|
|
|
|
+ let mut items = validate_cost_items(&items_in)?;
|
|
|
|
|
+ // D-1:按 id 回查全局项,快照现名/类别/计费口径;id 不存在 ⇒ 60005 拒绝(⛔ 存悬空行)。
|
|
|
|
|
+ resolve_cost_item_refs(state.db.as_ref(), &mut items).await?;
|
|
|
|
|
|
|
|
let before = cost_items_of(state.db.as_ref(), &plan_id).await?;
|
|
let before = cost_items_of(state.db.as_ref(), &plan_id).await?;
|
|
|
replace_cost_items(state.db.as_ref(), &plan_id, &items).await?;
|
|
replace_cost_items(state.db.as_ref(), &plan_id, &items).await?;
|
|
@@ -2470,18 +2577,22 @@ struct FacetRow {
|
|
|
cnt: Option<String>,
|
|
cnt: Option<String>,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-/// 台账 facets(R-14)+列表 total:同一套 params,单 UDS。
|
|
|
|
|
|
|
+/// 台账 facets(R-14)+列表 total+分档计数:同一套 params,单 UDS。
|
|
|
///
|
|
///
|
|
|
-/// * facets=**未追加**建档人/建档团队谓词的 base(含 plan_kind/scope)
|
|
|
|
|
|
|
+/// * facets=**未追加**建档人/建档团队谓词的 base(含 plan_kind/scope);`include_creator_facets=false`
|
|
|
|
|
+/// (固定档 tab)时跳过 team/by 两臂,砍掉无用 GROUP BY。
|
|
|
/// * total=base ∧ creator 谓词(与页数据 WHERE 同域)
|
|
/// * total=base ∧ creator 谓词(与页数据 WHERE 同域)
|
|
|
|
|
+/// * kind_totals=**未加** plan_kind/creator 的 scope(关键字+可见域),供 tab 角标
|
|
|
///
|
|
///
|
|
|
/// ⛔ 用当前页行凑选项:翻一页选项就变一批,且筛选后的行集根本凑不出「已选项」。
|
|
/// ⛔ 用当前页行凑选项:翻一页选项就变一批,且筛选后的行集根本凑不出「已选项」。
|
|
|
async fn facets_and_total(
|
|
async fn facets_and_total(
|
|
|
db: &UdsClient,
|
|
db: &UdsClient,
|
|
|
base: &[String],
|
|
base: &[String],
|
|
|
full: &[String],
|
|
full: &[String],
|
|
|
|
|
+ scope: &[String],
|
|
|
values: &[Value],
|
|
values: &[Value],
|
|
|
-) -> Result<(Value, i64), BosError> {
|
|
|
|
|
|
|
+ include_creator_facets: bool,
|
|
|
|
|
+) -> Result<(Value, i64, Value), BosError> {
|
|
|
let where_base = if base.is_empty() {
|
|
let where_base = if base.is_empty() {
|
|
|
String::new()
|
|
String::new()
|
|
|
} else {
|
|
} else {
|
|
@@ -2492,25 +2603,41 @@ async fn facets_and_total(
|
|
|
} else {
|
|
} else {
|
|
|
format!(" WHERE {}", full.join(" AND "))
|
|
format!(" WHERE {}", full.join(" AND "))
|
|
|
};
|
|
};
|
|
|
|
|
+ let where_scope = if scope.is_empty() {
|
|
|
|
|
+ String::new()
|
|
|
|
|
+ } else {
|
|
|
|
|
+ format!(" WHERE {}", scope.join(" AND "))
|
|
|
|
|
+ };
|
|
|
let by_where = if base.is_empty() {
|
|
let by_where = if base.is_empty() {
|
|
|
" WHERE p.created_by IS NOT NULL".to_string()
|
|
" WHERE p.created_by IS NOT NULL".to_string()
|
|
|
} else {
|
|
} else {
|
|
|
format!("{where_base} AND p.created_by IS NOT NULL")
|
|
format!("{where_base} AND p.created_by IS NOT NULL")
|
|
|
};
|
|
};
|
|
|
- // UDS 收拢:团队 facets + 建档人 facets + total 原 3 跳 → 1 条 UNION ALL。
|
|
|
|
|
- let sql = format!(
|
|
|
|
|
- "SELECT 'team' AS kind, COALESCE(p.created_team_id, '{CREATED_TEAM_HQ_SENTINEL}') AS id, \
|
|
|
|
|
- MAX({CREATED_TEAM_NAME_EXPR}) AS name, COUNT(1)::text AS cnt \
|
|
|
|
|
- {PLAN_FROM}{where_base} \
|
|
|
|
|
- GROUP BY COALESCE(p.created_team_id, '{CREATED_TEAM_HQ_SENTINEL}') \
|
|
|
|
|
- UNION ALL \
|
|
|
|
|
- SELECT 'by' AS kind, p.created_by AS id, MAX({CREATED_BY_NAME_EXPR}) AS name, COUNT(1)::text AS cnt \
|
|
|
|
|
- {PLAN_FROM}{by_where} \
|
|
|
|
|
- GROUP BY p.created_by \
|
|
|
|
|
- UNION ALL \
|
|
|
|
|
- SELECT 'total' AS kind, '' AS id, '' AS name, COUNT(1)::text AS cnt \
|
|
|
|
|
|
|
+ // UDS 收拢:team/by(可关)+ total + kind 分档 原多跳 → 1 条 UNION ALL。
|
|
|
|
|
+ let mut arms: Vec<String> = Vec::new();
|
|
|
|
|
+ if include_creator_facets {
|
|
|
|
|
+ arms.push(format!(
|
|
|
|
|
+ "SELECT 'team' AS kind, COALESCE(p.created_team_id, '{CREATED_TEAM_HQ_SENTINEL}') AS id, \
|
|
|
|
|
+ MAX({CREATED_TEAM_NAME_EXPR}) AS name, COUNT(1)::text AS cnt \
|
|
|
|
|
+ {PLAN_FROM}{where_base} \
|
|
|
|
|
+ GROUP BY COALESCE(p.created_team_id, '{CREATED_TEAM_HQ_SENTINEL}')"
|
|
|
|
|
+ ));
|
|
|
|
|
+ arms.push(format!(
|
|
|
|
|
+ "SELECT 'by' AS kind, p.created_by AS id, MAX({CREATED_BY_NAME_EXPR}) AS name, COUNT(1)::text AS cnt \
|
|
|
|
|
+ {PLAN_FROM}{by_where} \
|
|
|
|
|
+ GROUP BY p.created_by"
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ arms.push(format!(
|
|
|
|
|
+ "SELECT 'total' AS kind, '' AS id, '' AS name, COUNT(1)::text AS cnt \
|
|
|
{PLAN_FROM}{where_full}"
|
|
{PLAN_FROM}{where_full}"
|
|
|
- );
|
|
|
|
|
|
|
+ ));
|
|
|
|
|
+ arms.push(format!(
|
|
|
|
|
+ "SELECT 'kind' AS kind, p.plan_kind AS id, '' AS name, COUNT(1)::text AS cnt \
|
|
|
|
|
+ {PLAN_FROM}{where_scope} \
|
|
|
|
|
+ GROUP BY p.plan_kind"
|
|
|
|
|
+ ));
|
|
|
|
|
+ let sql = arms.join(" UNION ALL ");
|
|
|
#[derive(Deserialize)]
|
|
#[derive(Deserialize)]
|
|
|
struct FacetKindRow {
|
|
struct FacetKindRow {
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
@@ -2525,11 +2652,21 @@ async fn facets_and_total(
|
|
|
let mut teams: Vec<Value> = Vec::new();
|
|
let mut teams: Vec<Value> = Vec::new();
|
|
|
let mut creators: Vec<Value> = Vec::new();
|
|
let mut creators: Vec<Value> = Vec::new();
|
|
|
let mut n: i64 = 0;
|
|
let mut n: i64 = 0;
|
|
|
|
|
+ let mut fixed_n: i64 = 0;
|
|
|
|
|
+ let mut custom_n: i64 = 0;
|
|
|
for r in db.query_all::<FacetKindRow>(&sql, values).await? {
|
|
for r in db.query_all::<FacetKindRow>(&sql, values).await? {
|
|
|
match r.kind.as_str() {
|
|
match r.kind.as_str() {
|
|
|
"total" => {
|
|
"total" => {
|
|
|
n = r.cnt.and_then(|c| c.parse::<i64>().ok()).unwrap_or(0);
|
|
n = r.cnt.and_then(|c| c.parse::<i64>().ok()).unwrap_or(0);
|
|
|
}
|
|
}
|
|
|
|
|
+ "kind" => {
|
|
|
|
|
+ let c = r.cnt.and_then(|c| c.parse::<i64>().ok()).unwrap_or(0);
|
|
|
|
|
+ match r.id.as_str() {
|
|
|
|
|
+ "fixed" => fixed_n = c,
|
|
|
|
|
+ "custom" => custom_n = c,
|
|
|
|
|
+ _ => {}
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
"team" | "by" => {
|
|
"team" | "by" => {
|
|
|
let item = json!({
|
|
let item = json!({
|
|
|
"value": r.id,
|
|
"value": r.id,
|
|
@@ -2552,7 +2689,11 @@ async fn facets_and_total(
|
|
|
};
|
|
};
|
|
|
teams.sort_by_key(sort_key);
|
|
teams.sort_by_key(sort_key);
|
|
|
creators.sort_by_key(sort_key);
|
|
creators.sort_by_key(sort_key);
|
|
|
- Ok((json!({ "created_team": teams, "created_by": creators }), n))
|
|
|
|
|
|
|
+ Ok((
|
|
|
|
|
+ json!({ "created_team": teams, "created_by": creators }),
|
|
|
|
|
+ n,
|
|
|
|
|
+ json!({ "fixed": fixed_n, "custom": custom_n }),
|
|
|
|
|
+ ))
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_list(
|
|
pub async fn get_list(
|
|
@@ -2568,15 +2709,7 @@ pub async fn get_list(
|
|
|
return fail(fields_err(&msg, vec![field_entry("plan_kind", None, &detail)]));
|
|
return fail(fields_err(&msg, vec![field_entry("plan_kind", None, &detail)]));
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
- // §3.1:用途分类过滤**只对自定义档提供**
|
|
|
|
|
- if body.plan_kind.as_deref().map(str::trim) == Some("fixed")
|
|
|
|
|
- && norm(body.plan_family.as_deref()).is_some()
|
|
|
|
|
- {
|
|
|
|
|
- return fail(fields_err(
|
|
|
|
|
- "固定档列表不提供用途分类过滤(03 章 §3.1)",
|
|
|
|
|
- vec![field_entry("plan_family", None, "该检索项只对自定义套餐提供")],
|
|
|
|
|
- ));
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ // 交付形态(plan_family)固定/自定义档均可下推,供台账真分页(⛔ 再 wide=200 本地筛)。
|
|
|
// D-PKG-22:关键字先 trim 再匹配(push_like 也 trim;此处显式收口对外契约)。
|
|
// D-PKG-22:关键字先 trim 再匹配(push_like 也 trim;此处显式收口对外契约)。
|
|
|
let keyword = body
|
|
let keyword = body
|
|
|
.keyword
|
|
.keyword
|
|
@@ -2584,48 +2717,124 @@ pub async fn get_list(
|
|
|
.map(str::trim)
|
|
.map(str::trim)
|
|
|
.filter(|s| !s.is_empty());
|
|
.filter(|s| !s.is_empty());
|
|
|
let mut p = Params::default();
|
|
let mut p = Params::default();
|
|
|
- let mut w = preds(
|
|
|
|
|
|
|
+ // scope=关键字/状态/客户/用途+可见域(⛔ plan_kind/建档人);供 kind_totals 与 base 共用。
|
|
|
|
|
+ let mut scope_w = preds(
|
|
|
&mut p,
|
|
&mut p,
|
|
|
keyword,
|
|
keyword,
|
|
|
- body.plan_kind.as_deref(),
|
|
|
|
|
|
|
+ None,
|
|
|
body.status.as_deref(),
|
|
body.status.as_deref(),
|
|
|
body.customer_id.as_deref(),
|
|
body.customer_id.as_deref(),
|
|
|
body.plan_family.as_deref(),
|
|
body.plan_family.as_deref(),
|
|
|
);
|
|
);
|
|
|
// §3.1/§3.4:固定档⛔ 带客户谓词;自定义档必须带可见客户集合(越权的行**不出现**)
|
|
// §3.1/§3.4:固定档⛔ 带客户谓词;自定义档必须带可见客户集合(越权的行**不出现**)
|
|
|
match customer_scope_pred(&state, &auth, &mut p, "p.customer_id").await {
|
|
match customer_scope_pred(&state, &auth, &mut p, "p.customer_id").await {
|
|
|
- Ok(scope) => w.push(format!("(p.plan_kind = 'fixed'::text OR {scope})")),
|
|
|
|
|
|
|
+ Ok(scope) => scope_w.push(format!("(p.plan_kind = 'fixed'::text OR {scope})")),
|
|
|
Err(e) => return json_err(e),
|
|
Err(e) => return json_err(e),
|
|
|
}
|
|
}
|
|
|
- // facets=base∧scope;total/页数据=再叠建档人/建档团队。合并到同一 Params 后一次 UNION。
|
|
|
|
|
- let base_w = w.clone();
|
|
|
|
|
- w.extend(creator_preds(
|
|
|
|
|
|
|
+ let mut base_w = scope_w.clone();
|
|
|
|
|
+ if let Some(k) = p.push_eq(body.plan_kind.as_deref()) {
|
|
|
|
|
+ base_w.push(format!("p.plan_kind = {k}::text"));
|
|
|
|
|
+ }
|
|
|
|
|
+ // facets=base∧scope;total/页数据=再叠建档人/建档团队。
|
|
|
|
|
+ let mut full_w = base_w.clone();
|
|
|
|
|
+ full_w.extend(creator_preds(
|
|
|
&mut p,
|
|
&mut p,
|
|
|
body.created_by.as_deref(),
|
|
body.created_by.as_deref(),
|
|
|
body.created_team_id.as_deref(),
|
|
body.created_team_id.as_deref(),
|
|
|
body.created_team_name.as_deref(),
|
|
body.created_team_name.as_deref(),
|
|
|
));
|
|
));
|
|
|
- let (facets, n) = match facets_and_total(state.db.as_ref(), &base_w, &w, p.values()).await {
|
|
|
|
|
|
|
+ // 固定档 tab 不展示建档人/团队筛 ⇒ 跳过 team/by GROUP BY(省墙钟)。
|
|
|
|
|
+ let include_creator_facets = body.plan_kind.as_deref().map(str::trim) != Some("fixed");
|
|
|
|
|
+ let (facets, n, kind_totals) = match facets_and_total(
|
|
|
|
|
+ state.db.as_ref(),
|
|
|
|
|
+ &base_w,
|
|
|
|
|
+ &full_w,
|
|
|
|
|
+ &scope_w,
|
|
|
|
|
+ p.values(),
|
|
|
|
|
+ include_creator_facets,
|
|
|
|
|
+ )
|
|
|
|
|
+ .await
|
|
|
|
|
+ {
|
|
|
Ok(v) => v,
|
|
Ok(v) => v,
|
|
|
Err(e) => return json_err(e),
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
};
|
|
|
|
|
+ if std::env::var("KLT_BOS_INJECT_PLAN_COST_FAIL").ok().as_deref() == Some("1") {
|
|
|
|
|
+ return json_err(BosError::internal(
|
|
|
|
|
+ "注入:月成本取数失败(KLT_BOS_INJECT_PLAN_COST_FAIL=1)",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
let (lim, off) = p.push_page(&body.pg);
|
|
let (lim, off) = p.push_page(&body.pg);
|
|
|
|
|
+ // Wave C:页行 ∪ 订阅计数 ∪ 成本汇总 原 2 跳 → 1 条 CTE(改前=page + catalog_list_backfill)。
|
|
|
let sql = format!(
|
|
let sql = format!(
|
|
|
- "SELECT {} {PLAN_FROM} {} \
|
|
|
|
|
- ORDER BY p.plan_kind, p.annual_price_cents, p.plan_name LIMIT {lim} OFFSET {off}",
|
|
|
|
|
|
|
+ "WITH page AS ( \
|
|
|
|
|
+ SELECT {} {PLAN_FROM} {} \
|
|
|
|
|
+ ORDER BY p.plan_kind, p.annual_price_cents, p.plan_name LIMIT {lim} OFFSET {off} \
|
|
|
|
|
+ ), \
|
|
|
|
|
+ sub AS ( \
|
|
|
|
|
+ SELECT s.plan_id, COUNT(1)::text AS cnt \
|
|
|
|
|
+ FROM subscription s INNER JOIN page pg ON pg.plan_id = s.plan_id \
|
|
|
|
|
+ GROUP BY s.plan_id \
|
|
|
|
|
+ ), \
|
|
|
|
|
+ cost AS ( \
|
|
|
|
|
+ SELECT c.plan_id, COUNT(1)::text AS items, \
|
|
|
|
|
+ COUNT(c.amount_cents)::text AS configured, \
|
|
|
|
|
+ SUM(c.amount_cents)::text AS total \
|
|
|
|
|
+ FROM plan_cost_item c INNER JOIN page pg ON pg.plan_id = c.plan_id \
|
|
|
|
|
+ GROUP BY c.plan_id \
|
|
|
|
|
+ ) \
|
|
|
|
|
+ SELECT page.*, COALESCE(sub.cnt, '0') AS sub_ref_count, \
|
|
|
|
|
+ cost.items AS cost_item_count, \
|
|
|
|
|
+ cost.configured AS cost_configured_count, \
|
|
|
|
|
+ cost.total AS cost_sum_cents \
|
|
|
|
|
+ FROM page \
|
|
|
|
|
+ LEFT JOIN sub ON sub.plan_id = page.plan_id \
|
|
|
|
|
+ LEFT JOIN cost ON cost.plan_id = page.plan_id \
|
|
|
|
|
+ ORDER BY page.plan_kind, page.annual_price_cents, page.plan_name",
|
|
|
plan_cols(),
|
|
plan_cols(),
|
|
|
- p.where_clause(&w)
|
|
|
|
|
|
|
+ p.where_clause(&full_w)
|
|
|
);
|
|
);
|
|
|
let rows = match state.db.query_all::<PlanRow>(&sql, p.values()).await {
|
|
let rows = match state.db.query_all::<PlanRow>(&sql, p.values()).await {
|
|
|
Ok(r) => r,
|
|
Ok(r) => r,
|
|
|
Err(e) => return json_err(e),
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
};
|
|
|
- let ids: Vec<String> = rows.iter().map(|r| r.plan_id.clone()).collect();
|
|
|
|
|
- // UDS 收拢:subscription 计数 + plan_cost 汇总 原 2 跳 → 1 条 UNION ALL。
|
|
|
|
|
- let (counts, cost_raw) = match catalog_list_backfill(state.db.as_ref(), &ids).await {
|
|
|
|
|
- Ok(v) => v,
|
|
|
|
|
- Err(e) => return json_err(e),
|
|
|
|
|
- };
|
|
|
|
|
|
|
+ let mut cost_raw: HashMap<String, Result<Option<i64>, String>> = HashMap::new();
|
|
|
|
|
+ for r in &rows {
|
|
|
|
|
+ if r.plan_kind != "custom" {
|
|
|
|
|
+ continue;
|
|
|
|
|
+ }
|
|
|
|
|
+ let items = r
|
|
|
|
|
+ .cost_item_count
|
|
|
|
|
+ .as_deref()
|
|
|
|
|
+ .and_then(|s| s.trim().parse::<i64>().ok())
|
|
|
|
|
+ .unwrap_or(0);
|
|
|
|
|
+ let configured = r
|
|
|
|
|
+ .cost_configured_count
|
|
|
|
|
+ .as_deref()
|
|
|
|
|
+ .and_then(|s| s.trim().parse::<i64>().ok())
|
|
|
|
|
+ .unwrap_or(0);
|
|
|
|
|
+ if items <= 0 || configured != items {
|
|
|
|
|
+ cost_raw.insert(r.plan_id.clone(), Ok(None));
|
|
|
|
|
+ continue;
|
|
|
|
|
+ }
|
|
|
|
|
+ match r
|
|
|
|
|
+ .cost_sum_cents
|
|
|
|
|
+ .as_deref()
|
|
|
|
|
+ .and_then(|s| s.trim().parse::<i64>().ok())
|
|
|
|
|
+ {
|
|
|
|
|
+ Some(cents) => {
|
|
|
|
|
+ cost_raw.insert(r.plan_id.clone(), Ok(Some(cents)));
|
|
|
|
|
+ }
|
|
|
|
|
+ None => {
|
|
|
|
|
+ cost_raw.insert(
|
|
|
|
|
+ r.plan_id.clone(),
|
|
|
|
|
+ Err(format!(
|
|
|
|
|
+ "月成本汇总不可解析:plan_id={} total_cents={:?}",
|
|
|
|
|
+ r.plan_id, r.cost_sum_cents
|
|
|
|
|
+ )),
|
|
|
|
|
+ );
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
let custom_ids: Vec<String> = rows
|
|
let custom_ids: Vec<String> = rows
|
|
|
.iter()
|
|
.iter()
|
|
|
.filter(|r| r.plan_kind == "custom")
|
|
.filter(|r| r.plan_kind == "custom")
|
|
@@ -2635,9 +2844,13 @@ pub async fn get_list(
|
|
|
let items: Vec<Value> = rows
|
|
let items: Vec<Value> = rows
|
|
|
.into_iter()
|
|
.into_iter()
|
|
|
.map(|r| {
|
|
.map(|r| {
|
|
|
- let n = counts.get(&r.plan_id).copied().unwrap_or(0);
|
|
|
|
|
|
|
+ let referred = r
|
|
|
|
|
+ .sub_ref_count
|
|
|
|
|
+ .as_deref()
|
|
|
|
|
+ .and_then(|s| s.trim().parse::<i64>().ok())
|
|
|
|
|
+ .unwrap_or(0);
|
|
|
let cost = cost_readout_for(&r.plan_kind, &r.plan_id, &cost_sums);
|
|
let cost = cost_readout_for(&r.plan_kind, &r.plan_id, &cost_sums);
|
|
|
- plan_json(r, n, &cost)
|
|
|
|
|
|
|
+ plan_json(r, referred, &cost)
|
|
|
})
|
|
})
|
|
|
.collect();
|
|
.collect();
|
|
|
let fixed: Vec<Value> = items
|
|
let fixed: Vec<Value> = items
|
|
@@ -2656,6 +2869,8 @@ pub async fn get_list(
|
|
|
"custom": custom,
|
|
"custom": custom,
|
|
|
// R-14 台账筛选下拉项(服务端聚合,⛔ 从当前页行凑)
|
|
// R-14 台账筛选下拉项(服务端聚合,⛔ 从当前页行凑)
|
|
|
"facets": facets,
|
|
"facets": facets,
|
|
|
|
|
+ // tab 角标:关键字+可见域下的分档计数(⛔ plan_kind/建档人收窄)
|
|
|
|
|
+ "kind_totals": kind_totals,
|
|
|
"total": n,
|
|
"total": n,
|
|
|
// R-4:回显夹紧后的分页参数(与实际 LIMIT/OFFSET 一致),⛔ 原样回传越界入参。
|
|
// R-4:回显夹紧后的分页参数(与实际 LIMIT/OFFSET 一致),⛔ 原样回传越界入参。
|
|
|
"page": body.pg.effective_page(),
|
|
"page": body.pg.effective_page(),
|
|
@@ -2665,77 +2880,7 @@ pub async fn get_list(
|
|
|
}))
|
|
}))
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-/// 列表页回填:订阅引用数 + 自定义档月成本汇总(单 UDS)。
|
|
|
|
|
-async fn catalog_list_backfill(
|
|
|
|
|
- db: &UdsClient,
|
|
|
|
|
- plan_ids: &[String],
|
|
|
|
|
-) -> Result<(HashMap<String, i64>, HashMap<String, Result<Option<i64>, String>>), BosError> {
|
|
|
|
|
- let mut counts = HashMap::new();
|
|
|
|
|
- let mut costs: HashMap<String, Result<Option<i64>, String>> = HashMap::new();
|
|
|
|
|
- if plan_ids.is_empty() {
|
|
|
|
|
- return Ok((counts, costs));
|
|
|
|
|
- }
|
|
|
|
|
- if std::env::var("KLT_BOS_INJECT_PLAN_COST_FAIL").ok().as_deref() == Some("1") {
|
|
|
|
|
- return Err(BosError::internal(
|
|
|
|
|
- "注入:月成本取数失败(KLT_BOS_INJECT_PLAN_COST_FAIL=1)",
|
|
|
|
|
- ));
|
|
|
|
|
- }
|
|
|
|
|
- let mut p = Params::default();
|
|
|
|
|
- let in_sub = listq::push_in(&mut p, "plan_id", plan_ids, "text");
|
|
|
|
|
- let in_cost = listq::push_in(&mut p, "plan_id", plan_ids, "text");
|
|
|
|
|
- let sql = format!(
|
|
|
|
|
- "SELECT 'sub' AS kind, plan_id AS id, COUNT(1)::text AS a, '' AS b, '' AS c \
|
|
|
|
|
- FROM subscription WHERE {in_sub} GROUP BY plan_id \
|
|
|
|
|
- UNION ALL \
|
|
|
|
|
- SELECT 'cost' AS kind, plan_id AS id, COUNT(1)::text AS a, \
|
|
|
|
|
- COUNT(amount_cents)::text AS b, SUM(amount_cents)::text AS c \
|
|
|
|
|
- FROM plan_cost_item WHERE {in_cost} GROUP BY plan_id"
|
|
|
|
|
- );
|
|
|
|
|
- #[derive(Deserialize)]
|
|
|
|
|
- struct BackfillRow {
|
|
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
|
|
- kind: String,
|
|
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
|
|
- id: String,
|
|
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
|
|
- a: String,
|
|
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
|
|
- b: String,
|
|
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
|
|
- c: Option<String>,
|
|
|
|
|
- }
|
|
|
|
|
- for r in db.query_all::<BackfillRow>(&sql, p.values()).await? {
|
|
|
|
|
- match r.kind.as_str() {
|
|
|
|
|
- "sub" => {
|
|
|
|
|
- counts.insert(r.id, r.a.trim().parse().unwrap_or(0));
|
|
|
|
|
- }
|
|
|
|
|
- "cost" => {
|
|
|
|
|
- let items = r.a.trim().parse::<i64>().unwrap_or(0);
|
|
|
|
|
- let configured = r.b.trim().parse::<i64>().unwrap_or(0);
|
|
|
|
|
- if items <= 0 || configured != items {
|
|
|
|
|
- costs.insert(r.id, Ok(None));
|
|
|
|
|
- continue;
|
|
|
|
|
- }
|
|
|
|
|
- match r.c.as_deref().and_then(|s| s.trim().parse::<i64>().ok()) {
|
|
|
|
|
- Some(cents) => {
|
|
|
|
|
- costs.insert(r.id, Ok(Some(cents)));
|
|
|
|
|
- }
|
|
|
|
|
- None => {
|
|
|
|
|
- costs.insert(
|
|
|
|
|
- r.id.clone(),
|
|
|
|
|
- Err(format!(
|
|
|
|
|
- "月成本汇总不可解析:plan_id={} total_cents={:?}",
|
|
|
|
|
- r.id, r.c
|
|
|
|
|
- )),
|
|
|
|
|
- );
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- _ => {}
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- Ok((counts, costs))
|
|
|
|
|
-}
|
|
|
|
|
|
|
+// catalog_list_backfill 已并入 get_list 页 CTE(Wave C);勿再单独往返。
|
|
|
|
|
|
|
|
|
|
|
|
|
pub async fn get(
|
|
pub async fn get(
|
|
@@ -2878,11 +3023,19 @@ mod tests {
|
|
|
created_by_name: Some("总运营".to_string()),
|
|
created_by_name: Some("总运营".to_string()),
|
|
|
created_team_id: Some("OPS-000001".to_string()),
|
|
created_team_id: Some("OPS-000001".to_string()),
|
|
|
created_team_name: Some("平台运维一组".to_string()),
|
|
created_team_name: Some("平台运维一组".to_string()),
|
|
|
|
|
+ sub_ref_count: None,
|
|
|
|
|
+ cost_item_count: None,
|
|
|
|
|
+ cost_configured_count: None,
|
|
|
|
|
+ cost_sum_cents: None,
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
fn cost(name: &str, amount: i64) -> CostItemReq {
|
|
fn cost(name: &str, amount: i64) -> CostItemReq {
|
|
|
|
|
+ // 每次调用生成唯一 cost_item_id,避免多测例共享同一 id 触发同档去重(D-1)。
|
|
|
|
|
+ static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
|
|
|
|
+ let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
|
CostItemReq {
|
|
CostItemReq {
|
|
|
|
|
+ cost_item_id: Some(format!("CI-TEST-{n}")),
|
|
|
item_name: Some(name.to_string()),
|
|
item_name: Some(name.to_string()),
|
|
|
amount_cents: Some(amount),
|
|
amount_cents: Some(amount),
|
|
|
billing_unit: Some("per_customer".to_string()),
|
|
billing_unit: Some("per_customer".to_string()),
|
|
@@ -2985,6 +3138,7 @@ mod tests {
|
|
|
#[test]
|
|
#[test]
|
|
|
fn 成本项fields前缀与入参键items对齐() {
|
|
fn 成本项fields前缀与入参键items对齐() {
|
|
|
let err = validate_cost_items(&[CostItemReq {
|
|
let err = validate_cost_items(&[CostItemReq {
|
|
|
|
|
+ cost_item_id: Some("CI-TEST".into()),
|
|
|
item_name: Some("x".into()),
|
|
item_name: Some("x".into()),
|
|
|
amount_cents: None,
|
|
amount_cents: None,
|
|
|
billing_unit: None,
|
|
billing_unit: None,
|
|
@@ -3155,8 +3309,10 @@ mod tests {
|
|
|
#[test]
|
|
#[test]
|
|
|
fn 成本项校验与同档位重名() {
|
|
fn 成本项校验与同档位重名() {
|
|
|
assert!(validate_cost_items(&[cost("国际带宽", 100)]).is_ok());
|
|
assert!(validate_cost_items(&[cost("国际带宽", 100)]).is_ok());
|
|
|
- // 名称空白
|
|
|
|
|
- assert!(validate_cost_items(&[cost(" ", 100)]).is_err());
|
|
|
|
|
|
|
+ // D-1:cost_item_id 空白 ⇒ 拒(名称不再是引用键,空白名称由服务端快照全局现名覆盖)
|
|
|
|
|
+ let mut no_cid = cost("国际带宽", 100);
|
|
|
|
|
+ no_cid.cost_item_id = None;
|
|
|
|
|
+ assert!(validate_cost_items(&[no_cid]).is_err());
|
|
|
// 金额缺失/越界
|
|
// 金额缺失/越界
|
|
|
let mut bad = cost("国际带宽", -1);
|
|
let mut bad = cost("国际带宽", -1);
|
|
|
assert!(validate_cost_items(&[bad.clone()]).is_err());
|
|
assert!(validate_cost_items(&[bad.clone()]).is_err());
|
|
@@ -3169,8 +3325,14 @@ mod tests {
|
|
|
let mut c = cost("国际带宽", 100);
|
|
let mut c = cost("国际带宽", 100);
|
|
|
c.category = Some("other".to_string());
|
|
c.category = Some("other".to_string());
|
|
|
assert!(validate_cost_items(&[c]).is_err());
|
|
assert!(validate_cost_items(&[c]).is_err());
|
|
|
- // 同档位重名 ⇒ K206
|
|
|
|
|
- let dup = vec![cost("国际带宽", 100), cost("设备费", 200), cost(" 国际带宽 ", 300)];
|
|
|
|
|
|
|
+ // D-1:同档位 cost_item_id 重复 ⇒ K206(名称不同也拦,因为引用键是 id)
|
|
|
|
|
+ let mut a = cost("国际带宽", 100);
|
|
|
|
|
+ a.cost_item_id = Some("CI-01".to_string());
|
|
|
|
|
+ let mut b = cost("设备费", 200);
|
|
|
|
|
+ b.cost_item_id = Some("CI-02".to_string());
|
|
|
|
|
+ let mut d = cost(" 国际带宽 ", 300);
|
|
|
|
|
+ d.cost_item_id = Some("CI-01".to_string()); // 与 a 同 id
|
|
|
|
|
+ let dup = vec![a, b, d];
|
|
|
let err = validate_cost_items(&dup);
|
|
let err = validate_cost_items(&dup);
|
|
|
assert!(matches!(err, Err(CatalogErr::WithData(..))));
|
|
assert!(matches!(err, Err(CatalogErr::WithData(..))));
|
|
|
// 空整段=合法(清空该档位成本项)
|
|
// 空整段=合法(清空该档位成本项)
|
|
@@ -3185,8 +3347,9 @@ mod tests {
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
#[test]
|
|
|
- fn 成本项名称弱引用不校验全局清单() {
|
|
|
|
|
- // 名称不在任何字典里也应通过(§3.5:保存时只校验非空与长度)
|
|
|
|
|
|
|
+ fn 成本项同步校验不查全局清单存在性() {
|
|
|
|
|
+ // D-1:同步校验只看字段与同档 id 去重;全局存在性由 resolve_cost_item_refs 异步校验。
|
|
|
|
|
+ // 故「名称随手写」在同步层通过(名称由服务端快照覆盖),id 不存在留到异步层拦。
|
|
|
assert!(validate_cost_items(&[cost("随手写的名字", 0)]).is_ok());
|
|
assert!(validate_cost_items(&[cost("随手写的名字", 0)]).is_ok());
|
|
|
}
|
|
}
|
|
|
|
|
|