|
@@ -31,6 +31,7 @@ use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
|
|
|
use bos_api::AppState;
|
|
use bos_api::AppState;
|
|
|
use bos_core::{ApiResponse, BosError, ErrorCode, KltCode, PageQuery, RoleCode};
|
|
use bos_core::{ApiResponse, BosError, ErrorCode, KltCode, PageQuery, RoleCode};
|
|
|
use bos_invariant::{check_plan_deletable, CrossRead, MAX_AMOUNT_CENTS};
|
|
use bos_invariant::{check_plan_deletable, CrossRead, MAX_AMOUNT_CENTS};
|
|
|
|
|
+use bos_platform::audit::AuditEvent;
|
|
|
use bos_platform::clients::uds::{de, DmlStatement, UdsClient};
|
|
use bos_platform::clients::uds::{de, DmlStatement, UdsClient};
|
|
|
use chrono::Local;
|
|
use chrono::Local;
|
|
|
use serde::Deserialize;
|
|
use serde::Deserialize;
|
|
@@ -58,9 +59,17 @@ const BW_MIN: i64 = 1;
|
|
|
const BW_MAX: i64 = 1000;
|
|
const BW_MAX: i64 = 1000;
|
|
|
/// 下属分账号额度上界(§3.2:非负整数、**允许 0**、上界 9999)。
|
|
/// 下属分账号额度上界(§3.2:非负整数、**允许 0**、上界 9999)。
|
|
|
const QUOTA_MAX: i64 = 9999;
|
|
const QUOTA_MAX: i64 = 9999;
|
|
|
|
|
+/// 成本项主键(`PCI-{6位}`)里的序号段取数表达式——发号基线用,**字面量**(⛔ 拼用户输入)。
|
|
|
|
|
+///
|
|
|
|
|
+/// ⚠️ ⛔ 写成 `SUBSTRING(item_id FROM 5)`:UDS 的 `qualify()` 认 `FROM` 关键字后的第一个
|
|
|
|
|
+/// 标识符并改写表名,会把这里的 `5` 当表名改写成 `uds.<schema>..5` ⇒ 整条 SQL 解析失败
|
|
|
|
|
+/// (实测 13001 `Expected: ), found: .5`)。逗号形式 `SUBSTRING(x, n)` 不带 `FROM`,安全。
|
|
|
|
|
+const COST_ITEM_SEQ_MAX: &str = "CAST(SUBSTRING(item_id, 5) AS BIGINT)";
|
|
|
/// 成本项名称/备注长度上限(对齐 `item_name VARCHAR(128)`/`remark VARCHAR(512)`)。
|
|
/// 成本项名称/备注长度上限(对齐 `item_name VARCHAR(128)`/`remark VARCHAR(512)`)。
|
|
|
const COST_NAME_MAX: usize = 128;
|
|
const COST_NAME_MAX: usize = 128;
|
|
|
const COST_REMARK_MAX: usize = 512;
|
|
const COST_REMARK_MAX: usize = 512;
|
|
|
|
|
+/// 套餐说明长度上限(对齐 `catalog_plan.plan_desc VARCHAR(512)`)。
|
|
|
|
|
+const DESC_MAX: usize = 512;
|
|
|
/// 计费单位三值(§3.5 表;与 `cost_item.billing_unit` 同一字典)。
|
|
/// 计费单位三值(§3.5 表;与 `cost_item.billing_unit` 同一字典)。
|
|
|
const COST_BILLING_UNITS: &[&str] = &["per_customer", "per_account", "per_copy"];
|
|
const COST_BILLING_UNITS: &[&str] = &["per_customer", "per_account", "per_copy"];
|
|
|
/// 成本项类别三值(对齐 `cost_item.category` 注释)。
|
|
/// 成本项类别三值(对齐 `cost_item.category` 注释)。
|
|
@@ -90,11 +99,16 @@ const LOCKED_FROZEN: &[&str] = &[
|
|
|
"bandwidth_down_mbps",
|
|
"bandwidth_down_mbps",
|
|
|
"customer_id",
|
|
"customer_id",
|
|
|
];
|
|
];
|
|
|
-/// 任何时候都可改(§3.6:仅名称+成本项)。
|
|
|
|
|
-const EDITABLE_ALWAYS: &[&str] = &["plan_name", "cost_items"];
|
|
|
|
|
|
|
+/// 任何时候都可改:名称+**说明**+成本项。
|
|
|
|
|
+///
|
|
|
|
|
+/// §3.6 的冻结清单只点名「年价、月结算标准金额、额度、总带宽、归属客户」,`plan_desc` 不在
|
|
|
|
|
+/// 其列;用例说明 05 引用冻结规则正面写「仍可修改的只有三项:套餐名称、**套餐说明**、随附
|
|
|
|
|
+/// 成本项」⇒ 说明与名称同档,冻结后仍可改。
|
|
|
|
|
+const EDITABLE_ALWAYS: &[&str] = &["plan_name", "plan_desc", "cost_items"];
|
|
|
/// 未冻结时的可改集(`monthly_settle_cents`/`sub_mode` 是派生值,⛔ 进不了这一栏)。
|
|
/// 未冻结时的可改集(`monthly_settle_cents`/`sub_mode` 是派生值,⛔ 进不了这一栏)。
|
|
|
const EDITABLE_THAWED: &[&str] = &[
|
|
const EDITABLE_THAWED: &[&str] = &[
|
|
|
"plan_name",
|
|
"plan_name",
|
|
|
|
|
+ "plan_desc",
|
|
|
"cost_items",
|
|
"cost_items",
|
|
|
"annual_price_cents",
|
|
"annual_price_cents",
|
|
|
"sub_account_quota",
|
|
"sub_account_quota",
|
|
@@ -111,7 +125,7 @@ const PLAN_COST_NOTE: &str =
|
|
|
"一期月成本取数口 plan_cost_amount 未接线 ⇒ plan_cost_state=unconfigured、plan_cost_cents=null(⛔ 按 0 显示)";
|
|
"一期月成本取数口 plan_cost_amount 未接线 ⇒ plan_cost_state=unconfigured、plan_cost_cents=null(⛔ 按 0 显示)";
|
|
|
|
|
|
|
|
/// 读侧列集(`p` = `catalog_plan`,`c` = `customer`)。
|
|
/// 读侧列集(`p` = `catalog_plan`,`c` = `customer`)。
|
|
|
-const PLAN_COLS: &str = "p.plan_id, p.plan_name, p.plan_kind, p.annual_price_cents, p.status, \
|
|
|
|
|
|
|
+const PLAN_COLS: &str = "p.plan_id, p.plan_name, p.plan_desc, p.plan_kind, p.annual_price_cents, p.status, \
|
|
|
p.created_at, p.use_category, p.sub_account_quota, p.bandwidth_committed, p.bandwidth_up_mbps, \
|
|
p.created_at, p.use_category, p.sub_account_quota, p.bandwidth_committed, p.bandwidth_up_mbps, \
|
|
|
p.bandwidth_down_mbps, p.customer_id, p.row_version, p.line_exits, p.line_exit_key, \
|
|
p.bandwidth_down_mbps, p.customer_id, p.row_version, p.line_exits, p.line_exit_key, \
|
|
|
p.monthly_settle_cents, p.first_referred_at, p.derived_from_contract_item_id, p.sort_no, \
|
|
p.monthly_settle_cents, p.first_referred_at, p.derived_from_contract_item_id, p.sort_no, \
|
|
@@ -159,6 +173,7 @@ pub struct CustomerOptionsReq {
|
|
|
pub struct CatalogCreateReq {
|
|
pub struct CatalogCreateReq {
|
|
|
pub plan_kind: Option<String>,
|
|
pub plan_kind: Option<String>,
|
|
|
pub plan_name: Option<String>,
|
|
pub plan_name: Option<String>,
|
|
|
|
|
+ pub plan_desc: Option<String>,
|
|
|
pub use_category: Option<String>,
|
|
pub use_category: Option<String>,
|
|
|
pub annual_price_cents: Option<i64>,
|
|
pub annual_price_cents: Option<i64>,
|
|
|
pub sub_account_quota: Option<i64>,
|
|
pub sub_account_quota: Option<i64>,
|
|
@@ -179,6 +194,7 @@ pub struct CatalogCreateReq {
|
|
|
pub struct CatalogUpdateReq {
|
|
pub struct CatalogUpdateReq {
|
|
|
pub plan_id: Option<String>,
|
|
pub plan_id: Option<String>,
|
|
|
pub plan_name: Option<String>,
|
|
pub plan_name: Option<String>,
|
|
|
|
|
+ pub plan_desc: Option<String>,
|
|
|
pub annual_price_cents: Option<i64>,
|
|
pub annual_price_cents: Option<i64>,
|
|
|
pub sub_account_quota: Option<i64>,
|
|
pub sub_account_quota: Option<i64>,
|
|
|
pub bandwidth_committed: Option<bool>,
|
|
pub bandwidth_committed: Option<bool>,
|
|
@@ -229,6 +245,8 @@ struct PlanRow {
|
|
|
plan_id: String,
|
|
plan_id: String,
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
|
plan_name: String,
|
|
plan_name: String,
|
|
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
|
|
+ plan_desc: Option<String>,
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
|
plan_kind: String,
|
|
plan_kind: String,
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
@@ -578,6 +596,21 @@ fn check_name(raw: Option<&str>) -> Result<String, BosError> {
|
|
|
Ok(n)
|
|
Ok(n)
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+/// 套餐说明(可空:⛔ 落库或空串 ⇒ 记 `NULL`)。
|
|
|
|
|
+///
|
|
|
|
|
+/// §3.2 没有为它单列校验行,唯一硬约束来自列宽 `VARCHAR(512)`:超长⛔ 静默截断(截断=悄悄
|
|
|
|
|
+/// 改掉运营写下的报价口径),直接 `11103`。
|
|
|
|
|
+fn check_desc(raw: Option<&str>) -> Result<Option<String>, BosError> {
|
|
|
|
|
+ let d = raw.unwrap_or_default().trim();
|
|
|
|
|
+ let len = d.chars().count();
|
|
|
|
|
+ if len > DESC_MAX {
|
|
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
|
|
+ "套餐说明最长 {DESC_MAX} 字符(收到 {len})"
|
|
|
|
|
+ )));
|
|
|
|
|
+ }
|
|
|
|
|
+ Ok(if d.is_empty() { None } else { Some(d.to_string()) })
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
/// 年订阅价格(§3.2:`> 0`;上限 `10^10` 分=[`MAX_AMOUNT_CENTS`])。
|
|
/// 年订阅价格(§3.2:`> 0`;上限 `10^10` 分=[`MAX_AMOUNT_CENTS`])。
|
|
|
fn check_price(v: Option<i64>) -> Result<i64, BosError> {
|
|
fn check_price(v: Option<i64>) -> Result<i64, BosError> {
|
|
|
let p = v.ok_or_else(|| BosError::bad_params("请填写大于 0 的年订阅价格"))?;
|
|
let p = v.ok_or_else(|| BosError::bad_params("请填写大于 0 的年订阅价格"))?;
|
|
@@ -766,6 +799,7 @@ fn plan_json(r: PlanRow, referred: i64) -> Value {
|
|
|
let mut v = json!({
|
|
let mut v = json!({
|
|
|
"plan_id": r.plan_id,
|
|
"plan_id": r.plan_id,
|
|
|
"plan_name": r.plan_name,
|
|
"plan_name": r.plan_name,
|
|
|
|
|
+ "plan_desc": r.plan_desc,
|
|
|
"plan_kind": r.plan_kind,
|
|
"plan_kind": r.plan_kind,
|
|
|
"annual_price_cents": as_num(&r.annual_price_cents),
|
|
"annual_price_cents": as_num(&r.annual_price_cents),
|
|
|
"monthly_settle_cents": Value::from(monthly_settle),
|
|
"monthly_settle_cents": Value::from(monthly_settle),
|
|
@@ -821,6 +855,61 @@ fn with_pending(mut v: Value) -> Value {
|
|
|
v
|
|
v
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+/// 审计前后快照(只取会变的业务字段,⛔ 把整行出参塞进 `before/after`)。
|
|
|
|
|
+fn plan_snapshot(r: &PlanRow) -> Value {
|
|
|
|
|
+ json!({
|
|
|
|
|
+ "plan_name": r.plan_name.clone(),
|
|
|
|
|
+ "plan_desc": r.plan_desc.clone(),
|
|
|
|
|
+ "plan_kind": r.plan_kind.clone(),
|
|
|
|
|
+ "use_category": r.use_category.clone(),
|
|
|
|
|
+ "annual_price_cents": as_num(&r.annual_price_cents),
|
|
|
|
|
+ "sub_account_quota": as_opt_num(r.sub_account_quota.as_deref()),
|
|
|
|
|
+ "bandwidth_committed": as_bool(r.bandwidth_committed.as_deref()),
|
|
|
|
|
+ "bandwidth_up_mbps": as_opt_num(r.bandwidth_up_mbps.as_deref()),
|
|
|
|
|
+ "bandwidth_down_mbps": as_opt_num(r.bandwidth_down_mbps.as_deref()),
|
|
|
|
|
+ "customer_id": r.customer_id.clone(),
|
|
|
|
|
+ "row_version": as_opt_num(r.row_version.as_deref()),
|
|
|
|
|
+ })
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// 写一条套餐目录审计(`bos_audit_log` 唯一写入口)。
|
|
|
|
|
+///
|
|
|
|
|
+/// 与 `account.rs`/`customer.rs` 同口径:审计不阻塞主流程——主写已落库时写审计失败只回
|
|
|
|
|
+/// `audit_written=false`,⛔ 因审计失败把已成功的业务写当成失败(那会让前端重试造成重复写)。
|
|
|
|
|
+#[allow(clippy::too_many_arguments)]
|
|
|
|
|
+async fn write_catalog_audit(
|
|
|
|
|
+ state: &AppState,
|
|
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
|
|
+ action: &str,
|
|
|
|
|
+ resource_type: &str,
|
|
|
|
|
+ resource_id: &str,
|
|
|
|
|
+ before: Option<Value>,
|
|
|
|
|
+ after: Option<Value>,
|
|
|
|
|
+ detail: Option<Value>,
|
|
|
|
|
+) -> bool {
|
|
|
|
|
+ state
|
|
|
|
|
+ .db
|
|
|
|
|
+ .write_audit(&AuditEvent {
|
|
|
|
|
+ actor_user_id: auth.user_id.clone(),
|
|
|
|
|
+ action: action.to_string(),
|
|
|
|
|
+ resource_type: resource_type.to_string(),
|
|
|
|
|
+ resource_id: resource_id.to_string(),
|
|
|
|
|
+ before,
|
|
|
|
|
+ after,
|
|
|
|
|
+ detail,
|
|
|
|
|
+ })
|
|
|
|
|
+ .await
|
|
|
|
|
+ .is_ok()
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// 成本项清单的审计视图(03 章 §8:只记名称,⛔ 记金额)。
|
|
|
|
|
+fn cost_items_audit_view(items: &[Value]) -> Vec<Value> {
|
|
|
|
|
+ items
|
|
|
|
|
+ .iter()
|
|
|
|
|
+ .map(|it| it.get("item_name").cloned().unwrap_or(Value::Null))
|
|
|
|
|
+ .collect()
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
// ══════════════════════════════ 取数 ══════════════════════════════
|
|
// ══════════════════════════════ 取数 ══════════════════════════════
|
|
|
|
|
|
|
|
async fn fetch_row(db: &UdsClient, plan_id: &str) -> Result<Option<PlanRow>, BosError> {
|
|
async fn fetch_row(db: &UdsClient, plan_id: &str) -> Result<Option<PlanRow>, BosError> {
|
|
@@ -1056,6 +1145,16 @@ async fn load_writable_plan(
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// ══════════════════════════════ 写侧 ══════════════════════════════
|
|
// ══════════════════════════════ 写侧 ══════════════════════════════
|
|
|
|
|
+//
|
|
|
|
|
+// **DML 的参数一律裸 `$n`,⛔ 写 `$n::type`**——类型由目标列/谓词列推断,这也是
|
|
|
|
|
+// `uds-gateway.md` §9.5.5 `/dml/batch@v1` 官方示例的写法(`VALUES ($1, $2, $3)`)。
|
|
|
|
|
+// 自写显式 cast 会踩平台绑参缺陷:建档那条 12 列 INSERT(`text`×6+`bigint`+`int`×4
|
|
|
|
|
+// +`boolean`,每枚都带 `$n::type`)稳定让 UDS 送出含 NUL 的字节流,PG 在**绑定期**报
|
|
|
|
|
+// `invalid byte sequence for encoding "UTF8": 0x00`(取证:`temp/uds_cast_grid.py`
|
|
|
|
|
+// ⑤⑥=摘掉任意一枚 cast 即通过、11 列全 cast 通过而 12 列全 cast 炸;
|
|
|
|
|
+// `temp/uds_mix_probe.py` ②③=把这套类型名换成 `int4`/`int8` 即正常,说明炸点
|
|
|
|
|
+// 在 UDS 对 cast 类型名的处理,⛔ 我方靠"换个写法"赌它不炸)。读侧(DataFusion
|
|
|
|
|
+// 方言)不受影响,仍按需要给列写显式类型。
|
|
|
|
|
|
|
|
fn year_now() -> Result<i32, BosError> {
|
|
fn year_now() -> Result<i32, BosError> {
|
|
|
Local::now()
|
|
Local::now()
|
|
@@ -1065,9 +1164,16 @@ fn year_now() -> Result<i32, BosError> {
|
|
|
.map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))
|
|
.map_err(|e| BosError::internal(format!("发号年份不可解析:{e}")))
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-/// `Params` 追加可空值(`None` ⇒ `NULL`),返回占位符。
|
|
|
|
|
|
|
+/// DML 里追加可空值:`None` ⇒ 直接写 SQL 的 `NULL` 关键字(**不占参数位**)。
|
|
|
|
|
+///
|
|
|
|
|
+/// ⛔ 把 JSON `null` 当参数绑上去:UDS 无从推断它的类型,按 `text` 送进协议级 bind,
|
|
|
|
|
+/// PG 在赋值期拒收(实测 `column "bandwidth_up_mbps" is of type integer but
|
|
|
|
|
+/// expression is of type text`)。`NULL` 是 SQL 关键字、不是外部输入值,⛔ 触碰注入面。
|
|
|
fn push_opt(p: &mut Params, v: Option<Value>) -> String {
|
|
fn push_opt(p: &mut Params, v: Option<Value>) -> String {
|
|
|
- p.push(v.unwrap_or(Value::Null))
|
|
|
|
|
|
|
+ match v {
|
|
|
|
|
+ Some(v) => p.push(v),
|
|
|
|
|
+ None => "NULL".to_string(),
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
fn push_opt_i64(p: &mut Params, v: Option<i64>) -> String {
|
|
fn push_opt_i64(p: &mut Params, v: Option<i64>) -> String {
|
|
@@ -1078,24 +1184,31 @@ fn push_opt_str(p: &mut Params, v: Option<String>) -> String {
|
|
|
push_opt(p, v.map(Value::String))
|
|
push_opt(p, v.map(Value::String))
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-/// 把「占位符 + 显式 cast」拼成 `VALUES` 列表(数值/布尔列⛔ `::text`,一律点名类型)。
|
|
|
|
|
-fn values_list(phs: &[String], casts: &[&str]) -> String {
|
|
|
|
|
- phs.iter()
|
|
|
|
|
- .zip(casts.iter())
|
|
|
|
|
- .map(|(ph, ty)| format!("{ph}::{ty}"))
|
|
|
|
|
- .collect::<Vec<_>>()
|
|
|
|
|
- .join(", ")
|
|
|
|
|
|
|
+/// 为 `n` 条成本项**一次性**预留主键号段,返回首号(`n` 须 ≥ 1)。
|
|
|
|
|
+///
|
|
|
|
|
+/// ⛔ 逐条 `next_seq` 后再拼接:号段长度必须与真实插入条数一致,否则计数器与实际插入脱钩。
|
|
|
|
|
+async fn cost_item_seq_first(db: &UdsClient, n: usize) -> Result<i64, BosError> {
|
|
|
|
|
+ listq::next_seq_n(
|
|
|
|
|
+ db,
|
|
|
|
|
+ "plan_cost_item",
|
|
|
|
|
+ "plan_cost_item",
|
|
|
|
|
+ COST_ITEM_SEQ_MAX,
|
|
|
|
|
+ year_now()?,
|
|
|
|
|
+ n as i64,
|
|
|
|
|
+ )
|
|
|
|
|
+ .await
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-const COST_CASTS: [&str; 8] = ["text", "text", "text", "bigint", "text", "text", "text", "int"];
|
|
|
|
|
-
|
|
|
|
|
-/// 成本项逐条插入语句(`base`=调用方本轮取到的发号基线,同一批内连续取号⛔ 重发)。
|
|
|
|
|
-fn cost_insert_statements(items: &[CleanCostItem], plan_id: &str, base: i64) -> Vec<DmlStatement> {
|
|
|
|
|
|
|
+/// 成本项逐条插入语句(`first`=调用方**一次预留**的号段首号,本批第 `idx` 条=`first+idx`)。
|
|
|
|
|
+///
|
|
|
|
|
+/// ⛔ 在这里自己"再加一个号":号段的长度由 [`listq::next_seq_n`] 一次性从 `bos_seq_year`
|
|
|
|
|
+/// 扣走,本函数只在已属于本批的号段内排布。
|
|
|
|
|
+fn cost_insert_statements(items: &[CleanCostItem], plan_id: &str, first: i64) -> Vec<DmlStatement> {
|
|
|
items
|
|
items
|
|
|
.iter()
|
|
.iter()
|
|
|
.enumerate()
|
|
.enumerate()
|
|
|
.map(|(idx, it)| {
|
|
.map(|(idx, it)| {
|
|
|
- let item_id = format!("PCI-{:06}", base + idx as i64 + 1);
|
|
|
|
|
|
|
+ let item_id = format!("PCI-{:06}", first + idx as i64);
|
|
|
let mut p = Params::default();
|
|
let mut p = Params::default();
|
|
|
let phs = vec![
|
|
let phs = vec![
|
|
|
p.push(Value::String(item_id)),
|
|
p.push(Value::String(item_id)),
|
|
@@ -1111,7 +1224,7 @@ fn cost_insert_statements(items: &[CleanCostItem], plan_id: &str, base: i64) ->
|
|
|
format!(
|
|
format!(
|
|
|
"INSERT INTO plan_cost_item (item_id, plan_id, item_name, amount_cents, \
|
|
"INSERT INTO plan_cost_item (item_id, plan_id, item_name, amount_cents, \
|
|
|
billing_unit, category, remark, sort_no) VALUES ({})",
|
|
billing_unit, category, remark, sort_no) VALUES ({})",
|
|
|
- values_list(&phs, &COST_CASTS)
|
|
|
|
|
|
|
+ phs.join(", ")
|
|
|
),
|
|
),
|
|
|
p.values().to_vec(),
|
|
p.values().to_vec(),
|
|
|
)
|
|
)
|
|
@@ -1130,12 +1243,12 @@ async fn replace_cost_items(
|
|
|
let mut pd = Params::default();
|
|
let mut pd = Params::default();
|
|
|
let pid = pd.push(Value::String(plan_id.to_string()));
|
|
let pid = pd.push(Value::String(plan_id.to_string()));
|
|
|
let mut stmts = vec![DmlStatement::new(
|
|
let mut stmts = vec![DmlStatement::new(
|
|
|
- format!("DELETE FROM plan_cost_item WHERE plan_id = {pid}::text"),
|
|
|
|
|
|
|
+ format!("DELETE FROM plan_cost_item WHERE plan_id = {pid}"),
|
|
|
pd.values().to_vec(),
|
|
pd.values().to_vec(),
|
|
|
)];
|
|
)];
|
|
|
if !items.is_empty() {
|
|
if !items.is_empty() {
|
|
|
- let base = listq::next_seq(db, "plan_cost_item", "plan_cost_item", year_now()?).await?;
|
|
|
|
|
- stmts.extend(cost_insert_statements(items, plan_id, base));
|
|
|
|
|
|
|
+ let first = cost_item_seq_first(db, items.len()).await?;
|
|
|
|
|
+ stmts.extend(cost_insert_statements(items, plan_id, first));
|
|
|
}
|
|
}
|
|
|
let results = db.dml_batch(&stmts).await?;
|
|
let results = db.dml_batch(&stmts).await?;
|
|
|
for (idx, r) in results.iter().enumerate().skip(1) {
|
|
for (idx, r) in results.iter().enumerate().skip(1) {
|
|
@@ -1165,16 +1278,16 @@ fn rename_sync_statement(
|
|
|
let pid = p.push(Value::String(plan_id.to_string()));
|
|
let pid = p.push(Value::String(plan_id.to_string()));
|
|
|
let st = p.push(Value::String("expired".to_string()));
|
|
let st = p.push(Value::String("expired".to_string()));
|
|
|
let gnm = p.push(Value::String(new_name.to_string()));
|
|
let gnm = p.push(Value::String(new_name.to_string()));
|
|
|
- let mut guard = format!("cp.plan_name = {gnm}::text");
|
|
|
|
|
|
|
+ let mut guard = format!("cp.plan_name = {gnm}");
|
|
|
if let Some(rv) = version_after_write {
|
|
if let Some(rv) = version_after_write {
|
|
|
let grv = p.push(Value::from(rv));
|
|
let grv = p.push(Value::from(rv));
|
|
|
- guard.push_str(&format!(" AND cp.row_version = {grv}::int"));
|
|
|
|
|
|
|
+ guard.push_str(&format!(" AND cp.row_version = {grv}"));
|
|
|
}
|
|
}
|
|
|
DmlStatement::new(
|
|
DmlStatement::new(
|
|
|
format!(
|
|
format!(
|
|
|
- "UPDATE subscription SET plan_name = {v}::text WHERE plan_id = {pid}::text \
|
|
|
|
|
- AND status <> {st}::text AND EXISTS (SELECT 1 FROM catalog_plan cp \
|
|
|
|
|
- WHERE cp.plan_id = {pid}::text AND {guard})"
|
|
|
|
|
|
|
+ "UPDATE subscription SET plan_name = {v} WHERE plan_id = {pid} \
|
|
|
|
|
+ AND status <> {st} AND EXISTS (SELECT 1 FROM catalog_plan cp \
|
|
|
|
|
+ WHERE cp.plan_id = {pid} AND {guard})"
|
|
|
),
|
|
),
|
|
|
p.values().to_vec(),
|
|
p.values().to_vec(),
|
|
|
)
|
|
)
|
|
@@ -1205,6 +1318,7 @@ async fn do_create(
|
|
|
reject_readonly_keys(&b.extra)?;
|
|
reject_readonly_keys(&b.extra)?;
|
|
|
|
|
|
|
|
let name = check_name(b.plan_name.as_deref())?;
|
|
let name = check_name(b.plan_name.as_deref())?;
|
|
|
|
|
+ let desc = check_desc(b.plan_desc.as_deref())?;
|
|
|
let cat = norm(b.use_category.as_deref());
|
|
let cat = norm(b.use_category.as_deref());
|
|
|
let cat = match cat.as_deref() {
|
|
let cat = match cat.as_deref() {
|
|
|
Some(c) if USE_CATEGORIES.contains(&c) => c.to_string(),
|
|
Some(c) if USE_CATEGORIES.contains(&c) => c.to_string(),
|
|
@@ -1266,14 +1380,11 @@ async fn do_create(
|
|
|
let plan_id = format!("P-{seq:06}");
|
|
let plan_id = format!("P-{seq:06}");
|
|
|
let operator = auth.subject.subject_id.clone();
|
|
let operator = auth.subject.subject_id.clone();
|
|
|
|
|
|
|
|
- const CASTS: [&str; 12] = [
|
|
|
|
|
- "text", "text", "text", "bigint", "text", "int", "boolean", "int", "int", "text", "int",
|
|
|
|
|
- "text",
|
|
|
|
|
- ];
|
|
|
|
|
let mut p = Params::default();
|
|
let mut p = Params::default();
|
|
|
let phs = vec![
|
|
let phs = vec![
|
|
|
p.push(Value::String(plan_id.clone())),
|
|
p.push(Value::String(plan_id.clone())),
|
|
|
p.push(Value::String(name.clone())),
|
|
p.push(Value::String(name.clone())),
|
|
|
|
|
+ push_opt_str(&mut p, desc),
|
|
|
p.push(Value::String(kind.clone())),
|
|
p.push(Value::String(kind.clone())),
|
|
|
p.push(Value::from(price)),
|
|
p.push(Value::from(price)),
|
|
|
p.push(Value::String(cat.clone())),
|
|
p.push(Value::String(cat.clone())),
|
|
@@ -1287,21 +1398,19 @@ async fn do_create(
|
|
|
];
|
|
];
|
|
|
let mut stmts = vec![DmlStatement::new(
|
|
let mut stmts = vec![DmlStatement::new(
|
|
|
format!(
|
|
format!(
|
|
|
- "INSERT INTO catalog_plan (plan_id, plan_name, plan_kind, annual_price_cents, \
|
|
|
|
|
|
|
+ "INSERT INTO catalog_plan (plan_id, plan_name, plan_desc, plan_kind, annual_price_cents, \
|
|
|
use_category, sub_account_quota, bandwidth_committed, bandwidth_up_mbps, \
|
|
use_category, sub_account_quota, bandwidth_committed, bandwidth_up_mbps, \
|
|
|
bandwidth_down_mbps, customer_id, row_version, created_by) VALUES ({})",
|
|
bandwidth_down_mbps, customer_id, row_version, created_by) VALUES ({})",
|
|
|
- values_list(&phs, &CASTS)
|
|
|
|
|
|
|
+ phs.join(", ")
|
|
|
),
|
|
),
|
|
|
p.values().to_vec(),
|
|
p.values().to_vec(),
|
|
|
)];
|
|
)];
|
|
|
|
|
|
|
|
// 新增态的成本项⛔ 另发一批:本批内「建档 + 挂成本项」要么一起成、要么一起滚回去
|
|
// 新增态的成本项⛔ 另发一批:本批内「建档 + 挂成本项」要么一起成、要么一起滚回去
|
|
|
- // (新档位⛔ 存量行 ⇒ 无需 DELETE)。
|
|
|
|
|
- if let Some(items) = cost_items.as_deref() {
|
|
|
|
|
- let base =
|
|
|
|
|
- listq::next_seq(state.db.as_ref(), "plan_cost_item", "plan_cost_item", year_now()?)
|
|
|
|
|
- .await?;
|
|
|
|
|
- stmts.extend(cost_insert_statements(items, &plan_id, base));
|
|
|
|
|
|
|
+ // (新档位⛔ 存量行 ⇒ 无需 DELETE)。`[]`=本批不挂成本项 ⇒ ⛔ 空跑一次发号。
|
|
|
|
|
+ if let Some(items) = cost_items.as_deref().filter(|v| !v.is_empty()) {
|
|
|
|
|
+ let first = cost_item_seq_first(state.db.as_ref(), items.len()).await?;
|
|
|
|
|
+ stmts.extend(cost_insert_statements(items, &plan_id, first));
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
let results = state.db.dml_batch(&stmts).await?;
|
|
let results = state.db.dml_batch(&stmts).await?;
|
|
@@ -1319,11 +1428,29 @@ async fn do_create(
|
|
|
let row = fetch_row(state.db.as_ref(), &plan_id)
|
|
let row = fetch_row(state.db.as_ref(), &plan_id)
|
|
|
.await?
|
|
.await?
|
|
|
.ok_or_else(|| BosError::internal(format!("新建档位写入后回读失败:plan_id={plan_id}")))?;
|
|
.ok_or_else(|| BosError::internal(format!("新建档位写入后回读失败:plan_id={plan_id}")))?;
|
|
|
|
|
+ let audit_after = plan_snapshot(&row);
|
|
|
let mut v = plan_json(row, 0);
|
|
let mut v = plan_json(row, 0);
|
|
|
// 回读真值再应答(`/dml/batch@v1` ⛔ 回 `RETURNING`)
|
|
// 回读真值再应答(`/dml/batch@v1` ⛔ 回 `RETURNING`)
|
|
|
let list = cost_items_of(state.db.as_ref(), &plan_id).await?;
|
|
let list = cost_items_of(state.db.as_ref(), &plan_id).await?;
|
|
|
- v["saved_count"] = json!(list.len());
|
|
|
|
|
|
|
+ let saved_count = list.len();
|
|
|
|
|
+ v["saved_count"] = json!(saved_count);
|
|
|
v["cost_items"] = json!(list);
|
|
v["cost_items"] = json!(list);
|
|
|
|
|
+ // 套餐档位建档审计(03 章 §8:`plan`/`plan.create`;固定档 `customer_id` 为空=平台级资产)
|
|
|
|
|
+ let mut after = audit_after;
|
|
|
|
|
+ after["cost_item_count"] = json!(saved_count);
|
|
|
|
|
+ v["audit_written"] = json!(
|
|
|
|
|
+ write_catalog_audit(
|
|
|
|
|
+ state,
|
|
|
|
|
+ auth,
|
|
|
|
|
+ "plan.create",
|
|
|
|
|
+ "plan",
|
|
|
|
|
+ &plan_id,
|
|
|
|
|
+ None,
|
|
|
|
|
+ Some(after),
|
|
|
|
|
+ None,
|
|
|
|
|
+ )
|
|
|
|
|
+ .await
|
|
|
|
|
+ );
|
|
|
Ok(v)
|
|
Ok(v)
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -1417,11 +1544,24 @@ async fn do_update(
|
|
|
Some(c) => c,
|
|
Some(c) => c,
|
|
|
None => is_true(cur.bandwidth_committed.as_deref()).unwrap_or(true),
|
|
None => is_true(cur.bandwidth_committed.as_deref()).unwrap_or(true),
|
|
|
};
|
|
};
|
|
|
- let (bw_up, bw_down) = check_bandwidth(
|
|
|
|
|
- committed_eff,
|
|
|
|
|
- b.bandwidth_up_mbps,
|
|
|
|
|
- b.bandwidth_down_mbps,
|
|
|
|
|
- )?;
|
|
|
|
|
|
|
+ // 部分更新:载荷未带带宽三键 ⇒ **不校验带宽**。
|
|
|
|
|
+ // 历史/种子档存在 `committed=true` 而上下行为 NULL 的存量行(见 18 册 CU-D4),整表校验会让
|
|
|
|
|
+ // 「引用冻结后只改名称/说明」被带宽必填拦死,直接违背 03 章 §3.6。带键才做三键完整校验,
|
|
|
|
|
+ // 缺的那一向回落库里现值再校验。
|
|
|
|
|
+ let bw_present = b.bandwidth_committed.is_some()
|
|
|
|
|
+ || b.bandwidth_up_mbps.is_some()
|
|
|
|
|
+ || b.bandwidth_down_mbps.is_some();
|
|
|
|
|
+ let (bw_up, bw_down) = if bw_present {
|
|
|
|
|
+ let up_eff = b
|
|
|
|
|
+ .bandwidth_up_mbps
|
|
|
|
|
+ .or_else(|| as_i64(cur.bandwidth_up_mbps.as_deref()));
|
|
|
|
|
+ let down_eff = b
|
|
|
|
|
+ .bandwidth_down_mbps
|
|
|
|
|
+ .or_else(|| as_i64(cur.bandwidth_down_mbps.as_deref()));
|
|
|
|
|
+ check_bandwidth(committed_eff, up_eff, down_eff)?
|
|
|
|
|
+ } else {
|
|
|
|
|
+ (None, None)
|
|
|
|
|
+ };
|
|
|
if let Some(c) = patch.use_category.as_deref() {
|
|
if let Some(c) = patch.use_category.as_deref() {
|
|
|
if !USE_CATEGORIES.contains(&c) {
|
|
if !USE_CATEGORIES.contains(&c) {
|
|
|
return Err(BosError::bad_params(format!(
|
|
return Err(BosError::bad_params(format!(
|
|
@@ -1474,10 +1614,28 @@ async fn do_update(
|
|
|
if let Some(q) = b.sub_account_quota {
|
|
if let Some(q) = b.sub_account_quota {
|
|
|
let used = active_seat_demand(state.db.as_ref(), &plan_id).await?;
|
|
let used = active_seat_demand(state.db.as_ref(), &plan_id).await?;
|
|
|
if q < used {
|
|
if q < used {
|
|
|
- return Err(BosError::bad_params(format!(
|
|
|
|
|
- "sub_account_quota ⛔ 改小于该档位活跃订阅已占席位数:已占 {used},请求={q}"
|
|
|
|
|
- ))
|
|
|
|
|
- .into());
|
|
|
|
|
|
|
+ // 契约 `KLT-K204`/60205:这是**引用/占用锁定**,⛔ 走参数校验码 `60004`
|
|
|
|
|
+ // (前端要按码分支提示「改额度请新建档位/升降配」)。文案同 03 章 §3.6。
|
|
|
|
|
+ let n = referred_count(state.db.as_ref(), &plan_id).await?;
|
|
|
|
|
+ let (locked, editable) = locked_editable(frozen, false);
|
|
|
|
|
+ return Err(CatalogErr::WithData(
|
|
|
|
|
+ BosError::klt(
|
|
|
|
|
+ KltCode::K204,
|
|
|
|
|
+ format!(
|
|
|
|
|
+ "分账号额度不能小于该档位活跃订阅已占席位数:已占 {used},请求={q}(referred_count={n})"
|
|
|
|
|
+ ),
|
|
|
|
|
+ ),
|
|
|
|
|
+ json!({
|
|
|
|
|
+ "frozen": frozen,
|
|
|
|
|
+ "referred_count": Value::from(n),
|
|
|
|
|
+ "active_seats": Value::from(used),
|
|
|
|
|
+ "requested_quota": Value::from(q),
|
|
|
|
|
+ "hit_fields": ["sub_account_quota"],
|
|
|
|
|
+ "locked_fields": locked,
|
|
|
|
|
+ "editable_fields": editable,
|
|
|
|
|
+ "hint": "调整额度请新建档位并在订阅中办理升级(03 章 §3.6)",
|
|
|
|
|
+ }),
|
|
|
|
|
+ ));
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -1499,27 +1657,33 @@ async fn do_update(
|
|
|
let by = p.push(Value::String(auth.subject.subject_id.clone()));
|
|
let by = p.push(Value::String(auth.subject.subject_id.clone()));
|
|
|
let mut sets: Vec<String> = vec![
|
|
let mut sets: Vec<String> = vec![
|
|
|
"updated_at = NOW()".to_string(),
|
|
"updated_at = NOW()".to_string(),
|
|
|
- format!("updated_by = {by}::text"),
|
|
|
|
|
|
|
+ format!("updated_by = {by}"),
|
|
|
];
|
|
];
|
|
|
let mut dirty = false;
|
|
let mut dirty = false;
|
|
|
if let Some(n) = name.as_deref() {
|
|
if let Some(n) = name.as_deref() {
|
|
|
let v = p.push(Value::String(n.to_string()));
|
|
let v = p.push(Value::String(n.to_string()));
|
|
|
- sets.push(format!("plan_name = {v}::text"));
|
|
|
|
|
|
|
+ sets.push(format!("plan_name = {v}"));
|
|
|
|
|
+ dirty = true;
|
|
|
|
|
+ }
|
|
|
|
|
+ // 说明与名称同档:引用冻结后仍可改(用例说明 05),空串=清空成 `NULL`。
|
|
|
|
|
+ if b.plan_desc.is_some() {
|
|
|
|
|
+ let v = push_opt_str(&mut p, check_desc(b.plan_desc.as_deref())?);
|
|
|
|
|
+ sets.push(format!("plan_desc = {v}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
if let Some(v) = b.annual_price_cents {
|
|
if let Some(v) = b.annual_price_cents {
|
|
|
let ph = p.push(Value::from(v));
|
|
let ph = p.push(Value::from(v));
|
|
|
- sets.push(format!("annual_price_cents = {ph}::bigint"));
|
|
|
|
|
|
|
+ sets.push(format!("annual_price_cents = {ph}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
if let Some(v) = b.sub_account_quota {
|
|
if let Some(v) = b.sub_account_quota {
|
|
|
let ph = p.push(Value::from(v));
|
|
let ph = p.push(Value::from(v));
|
|
|
- sets.push(format!("sub_account_quota = {ph}::int"));
|
|
|
|
|
|
|
+ sets.push(format!("sub_account_quota = {ph}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
if let Some(c) = b.bandwidth_committed {
|
|
if let Some(c) = b.bandwidth_committed {
|
|
|
let ph = p.push(Value::from(c));
|
|
let ph = p.push(Value::from(c));
|
|
|
- sets.push(format!("bandwidth_committed = {ph}::boolean"));
|
|
|
|
|
|
|
+ sets.push(format!("bandwidth_committed = {ph}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
// §3.2:不承诺带宽 ⇒ 上下行两列一律置空(库里残留值必须清掉);承诺 ⇒ 载荷带值才写。
|
|
// §3.2:不承诺带宽 ⇒ 上下行两列一律置空(库里残留值必须清掉);承诺 ⇒ 载荷带值才写。
|
|
@@ -1530,25 +1694,25 @@ async fn do_update(
|
|
|
if stale {
|
|
if stale {
|
|
|
let nu = push_opt(&mut p, None);
|
|
let nu = push_opt(&mut p, None);
|
|
|
let nd = push_opt(&mut p, None);
|
|
let nd = push_opt(&mut p, None);
|
|
|
- sets.push(format!("bandwidth_up_mbps = {nu}::int"));
|
|
|
|
|
- sets.push(format!("bandwidth_down_mbps = {nd}::int"));
|
|
|
|
|
|
|
+ sets.push(format!("bandwidth_up_mbps = {nu}"));
|
|
|
|
|
+ sets.push(format!("bandwidth_down_mbps = {nd}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
} else {
|
|
} else {
|
|
|
if let Some(v) = bw_up {
|
|
if let Some(v) = bw_up {
|
|
|
let ph = p.push(Value::from(v));
|
|
let ph = p.push(Value::from(v));
|
|
|
- sets.push(format!("bandwidth_up_mbps = {ph}::int"));
|
|
|
|
|
|
|
+ sets.push(format!("bandwidth_up_mbps = {ph}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
if let Some(v) = bw_down {
|
|
if let Some(v) = bw_down {
|
|
|
let ph = p.push(Value::from(v));
|
|
let ph = p.push(Value::from(v));
|
|
|
- sets.push(format!("bandwidth_down_mbps = {ph}::int"));
|
|
|
|
|
|
|
+ sets.push(format!("bandwidth_down_mbps = {ph}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
if let Some(cid) = patch.customer_id.as_deref().filter(|_| diff.customer_change) {
|
|
if let Some(cid) = patch.customer_id.as_deref().filter(|_| diff.customer_change) {
|
|
|
let v = p.push(Value::String(cid.to_string()));
|
|
let v = p.push(Value::String(cid.to_string()));
|
|
|
- sets.push(format!("customer_id = {v}::text"));
|
|
|
|
|
|
|
+ sets.push(format!("customer_id = {v}"));
|
|
|
dirty = true;
|
|
dirty = true;
|
|
|
}
|
|
}
|
|
|
if !dirty && cost_items.is_none() {
|
|
if !dirty && cost_items.is_none() {
|
|
@@ -1557,9 +1721,9 @@ async fn do_update(
|
|
|
|
|
|
|
|
if dirty {
|
|
if dirty {
|
|
|
sets.push("row_version = row_version + 1".to_string());
|
|
sets.push("row_version = row_version + 1".to_string());
|
|
|
- let mut preds = vec![format!("plan_id = {pid}::text")];
|
|
|
|
|
|
|
+ let mut preds = vec![format!("plan_id = {pid}")];
|
|
|
if let Some(ph) = expect_rv.map(|rv| p.push(Value::from(rv))) {
|
|
if let Some(ph) = expect_rv.map(|rv| p.push(Value::from(rv))) {
|
|
|
- preds.push(format!("row_version = {ph}::int"));
|
|
|
|
|
|
|
+ preds.push(format!("row_version = {ph}"));
|
|
|
}
|
|
}
|
|
|
let mut stmts = vec![DmlStatement::new(
|
|
let mut stmts = vec![DmlStatement::new(
|
|
|
format!(
|
|
format!(
|
|
@@ -1604,12 +1768,42 @@ async fn do_update(
|
|
|
.await?
|
|
.await?
|
|
|
.ok_or_else(|| BosError::internal(format!("档位更新后回读失败:plan_id={plan_id}")))?;
|
|
.ok_or_else(|| BosError::internal(format!("档位更新后回读失败:plan_id={plan_id}")))?;
|
|
|
let n = referred_count(state.db.as_ref(), &plan_id).await?;
|
|
let n = referred_count(state.db.as_ref(), &plan_id).await?;
|
|
|
|
|
+ let audit_after = plan_snapshot(&row);
|
|
|
let mut v = plan_json(row, n);
|
|
let mut v = plan_json(row, n);
|
|
|
if cost_items.is_some() {
|
|
if cost_items.is_some() {
|
|
|
let list = cost_items_of(state.db.as_ref(), &plan_id).await?;
|
|
let list = cost_items_of(state.db.as_ref(), &plan_id).await?;
|
|
|
v["saved_count"] = json!(list.len());
|
|
v["saved_count"] = json!(list.len());
|
|
|
v["cost_items"] = json!(list);
|
|
v["cost_items"] = json!(list);
|
|
|
}
|
|
}
|
|
|
|
|
+ // 套餐档位编辑审计(03 章 §8:`plan`/`plan.update`,`diff`+同步行数)
|
|
|
|
|
+ let mut changed: Vec<String> = diff.hits.clone();
|
|
|
|
|
+ if diff.rename.is_some() {
|
|
|
|
|
+ changed.push("plan_name".to_string());
|
|
|
|
|
+ }
|
|
|
|
|
+ if b.plan_desc.is_some() {
|
|
|
|
|
+ changed.push("plan_desc".to_string());
|
|
|
|
|
+ }
|
|
|
|
|
+ if cost_items.is_some() {
|
|
|
|
|
+ changed.push("cost_items".to_string());
|
|
|
|
|
+ }
|
|
|
|
|
+ v["audit_written"] = json!(
|
|
|
|
|
+ write_catalog_audit(
|
|
|
|
|
+ state,
|
|
|
|
|
+ auth,
|
|
|
|
|
+ "plan.update",
|
|
|
|
|
+ "plan",
|
|
|
|
|
+ &plan_id,
|
|
|
|
|
+ Some(plan_snapshot(&cur)),
|
|
|
|
|
+ Some(audit_after),
|
|
|
|
|
+ Some(json!({
|
|
|
|
|
+ "changed_fields": changed,
|
|
|
|
|
+ "referred_count": n,
|
|
|
|
|
+ "frozen": frozen,
|
|
|
|
|
+ "row_version": v["row_version"].clone(),
|
|
|
|
|
+ })),
|
|
|
|
|
+ )
|
|
|
|
|
+ .await
|
|
|
|
|
+ );
|
|
|
Ok(v)
|
|
Ok(v)
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -1648,13 +1842,13 @@ async fn do_delete(
|
|
|
let pid2 = p2.push(Value::String(plan_id.to_string()));
|
|
let pid2 = p2.push(Value::String(plan_id.to_string()));
|
|
|
let stmts = vec![
|
|
let stmts = vec![
|
|
|
DmlStatement::new(
|
|
DmlStatement::new(
|
|
|
- format!("DELETE FROM plan_cost_item WHERE plan_id = {pid1}::text"),
|
|
|
|
|
|
|
+ format!("DELETE FROM plan_cost_item WHERE plan_id = {pid1}"),
|
|
|
p1.values().to_vec(),
|
|
p1.values().to_vec(),
|
|
|
),
|
|
),
|
|
|
DmlStatement::new(
|
|
DmlStatement::new(
|
|
|
format!(
|
|
format!(
|
|
|
- "DELETE FROM catalog_plan p WHERE p.plan_id = {pid2}::text \
|
|
|
|
|
- AND NOT EXISTS (SELECT 1 FROM subscription s WHERE s.plan_id = {pid2}::text)"
|
|
|
|
|
|
|
+ "DELETE FROM catalog_plan p WHERE p.plan_id = {pid2} \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM subscription s WHERE s.plan_id = {pid2})"
|
|
|
),
|
|
),
|
|
|
p2.values().to_vec(),
|
|
p2.values().to_vec(),
|
|
|
),
|
|
),
|
|
@@ -1667,7 +1861,10 @@ async fn do_delete(
|
|
|
return Err(CatalogErr::WithData(
|
|
return Err(CatalogErr::WithData(
|
|
|
BosError::klt(
|
|
BosError::klt(
|
|
|
KltCode::K205,
|
|
KltCode::K205,
|
|
|
- format!("档位在用不能删除(referred_count={})", subs.len()),
|
|
|
|
|
|
|
+ format!(
|
|
|
|
|
+ "该套餐档位已被订阅引用,不能删除(引用 {} 份)",
|
|
|
|
|
+ subs.len()
|
|
|
|
|
+ ),
|
|
|
),
|
|
),
|
|
|
json!({
|
|
json!({
|
|
|
"deleted": false,
|
|
"deleted": false,
|
|
@@ -1685,6 +1882,18 @@ async fn do_delete(
|
|
|
))
|
|
))
|
|
|
.into());
|
|
.into());
|
|
|
}
|
|
}
|
|
|
|
|
+ // 套餐档位删除审计(03 章 §8:`plan`/`plan.delete`,`before` 存整档快照便于回溯)
|
|
|
|
|
+ let audit_ok = write_catalog_audit(
|
|
|
|
|
+ state,
|
|
|
|
|
+ auth,
|
|
|
|
|
+ "plan.delete",
|
|
|
|
|
+ "plan",
|
|
|
|
|
+ plan_id,
|
|
|
|
|
+ Some(plan_snapshot(&row)),
|
|
|
|
|
+ None,
|
|
|
|
|
+ Some(json!({ "referred_count": 0, "deleted": true })),
|
|
|
|
|
+ )
|
|
|
|
|
+ .await;
|
|
|
Ok(json!({
|
|
Ok(json!({
|
|
|
"deleted": true,
|
|
"deleted": true,
|
|
|
"plan_id": plan_id,
|
|
"plan_id": plan_id,
|
|
@@ -1693,7 +1902,7 @@ async fn do_delete(
|
|
|
"blocks": { "subscriptions": [], "items": [] },
|
|
"blocks": { "subscriptions": [], "items": [] },
|
|
|
"suggest": Value::Null,
|
|
"suggest": Value::Null,
|
|
|
"cost_items": [],
|
|
"cost_items": [],
|
|
|
- "audit_written": false,
|
|
|
|
|
|
|
+ "audit_written": audit_ok,
|
|
|
}))
|
|
}))
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -1742,14 +1951,28 @@ async fn do_plan_cost_save(
|
|
|
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 items = validate_cost_items(&items_in)?;
|
|
|
|
|
|
|
|
|
|
+ let before = cost_items_of(state.db.as_ref(), &b.plan_id).await?;
|
|
|
replace_cost_items(state.db.as_ref(), &b.plan_id, &items).await?;
|
|
replace_cost_items(state.db.as_ref(), &b.plan_id, &items).await?;
|
|
|
let list = cost_items_of(state.db.as_ref(), &b.plan_id).await?;
|
|
let list = cost_items_of(state.db.as_ref(), &b.plan_id).await?;
|
|
|
|
|
+ // 成本项审计(03 章 §8:`plan_cost`/`plan_cost.save`,只记名称 ⛔ 记金额)
|
|
|
|
|
+ let audit_ok = write_catalog_audit(
|
|
|
|
|
+ state,
|
|
|
|
|
+ auth,
|
|
|
|
|
+ "plan_cost.save",
|
|
|
|
|
+ "plan_cost",
|
|
|
|
|
+ &b.plan_id,
|
|
|
|
|
+ Some(json!(cost_items_audit_view(&before))),
|
|
|
|
|
+ Some(json!(cost_items_audit_view(&list))),
|
|
|
|
|
+ Some(json!({ "saved_count": list.len() })),
|
|
|
|
|
+ )
|
|
|
|
|
+ .await;
|
|
|
Ok(json!({
|
|
Ok(json!({
|
|
|
"plan_id": b.plan_id,
|
|
"plan_id": b.plan_id,
|
|
|
"items": list,
|
|
"items": list,
|
|
|
"saved_count": json!(list.len()),
|
|
"saved_count": json!(list.len()),
|
|
|
"frozen": frozen_of(row.first_referred_at.as_deref()),
|
|
"frozen": frozen_of(row.first_referred_at.as_deref()),
|
|
|
"frozen_note": "成本项⛔ 受引用冻结(03 章 §3.5):本接口不看也⛔ bump first_referred_at",
|
|
"frozen_note": "成本项⛔ 受引用冻结(03 章 §3.5):本接口不看也⛔ bump first_referred_at",
|
|
|
|
|
+ "audit_written": audit_ok,
|
|
|
}))
|
|
}))
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -1973,6 +2196,7 @@ mod tests {
|
|
|
PlanRow {
|
|
PlanRow {
|
|
|
plan_id: "P-000001".to_string(),
|
|
plan_id: "P-000001".to_string(),
|
|
|
plan_name: "通用办公标准档".to_string(),
|
|
plan_name: "通用办公标准档".to_string(),
|
|
|
|
|
+ plan_desc: None,
|
|
|
plan_kind: "fixed".to_string(),
|
|
plan_kind: "fixed".to_string(),
|
|
|
annual_price_cents: "120000".to_string(),
|
|
annual_price_cents: "120000".to_string(),
|
|
|
status: "active".to_string(),
|
|
status: "active".to_string(),
|
|
@@ -2096,6 +2320,24 @@ mod tests {
|
|
|
assert!(d.hits.contains(&"bandwidth_down_mbps".to_string()));
|
|
assert!(d.hits.contains(&"bandwidth_down_mbps".to_string()));
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ #[test]
|
|
|
|
|
+ fn 说明长度上限与冻结后仍可改() {
|
|
|
|
|
+ // §3.2 没有为说明单列校验行 ⇒ 唯一硬约束=列宽 512:超长拒(⛔ 静默截断),空/空白记 `NULL`。
|
|
|
|
|
+ assert!(check_desc(Some(&"说".repeat(DESC_MAX + 1))).is_err());
|
|
|
|
|
+ assert_eq!(
|
|
|
|
|
+ check_desc(Some(&"说".repeat(DESC_MAX))).unwrap().unwrap().chars().count(),
|
|
|
|
|
+ DESC_MAX
|
|
|
|
|
+ );
|
|
|
|
|
+ assert_eq!(check_desc(None).unwrap(), None::<String>);
|
|
|
|
|
+ assert_eq!(check_desc(Some(" ")).unwrap(), None::<String>);
|
|
|
|
|
+ assert_eq!(check_desc(Some(" 报价口径 ")).unwrap().unwrap(), "报价口径");
|
|
|
|
|
+ // 用例说明 05 的冻结口径=「仍可修改的只有三项:套餐名称、套餐说明、随附成本项」。
|
|
|
|
|
+ let (locked, editable) = locked_editable(true, false);
|
|
|
|
|
+ assert_eq!(editable, vec!["plan_name", "plan_desc", "cost_items"]);
|
|
|
|
|
+ assert!(!locked.contains(&"plan_desc"), "说明⛔ 进 §3.6 冻结清单");
|
|
|
|
|
+ assert!(locked.contains(&"annual_price_cents"));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
#[test]
|
|
#[test]
|
|
|
fn 字段校验矩阵() {
|
|
fn 字段校验矩阵() {
|
|
|
assert!(check_name(Some(" 通 ")).is_err());
|
|
assert!(check_name(Some(" 通 ")).is_err());
|
|
@@ -2206,12 +2448,15 @@ mod tests {
|
|
|
#[test]
|
|
#[test]
|
|
|
fn 改名同步语句自带参数集与落库守卫() {
|
|
fn 改名同步语句自带参数集与落库守卫() {
|
|
|
let s = rename_sync_statement("P-000007", "新名称", Some(4));
|
|
let s = rename_sync_statement("P-000007", "新名称", Some(4));
|
|
|
- assert!(s.sql.contains("UPDATE subscription SET plan_name = $1::text"));
|
|
|
|
|
- assert!(s.sql.contains("status <> $3::text"));
|
|
|
|
|
|
|
+ // ⚠️ 写侧占位符一律**裸** `$n`(⛔ `$n::type`):显式 cast 会让 UDS 送出含 `0x00` 的
|
|
|
|
|
+ // 字节流 ⇒ PG 绑定期 `invalid byte sequence for encoding "UTF8"`(2026-11-11 实测)。
|
|
|
|
|
+ assert!(s.sql.contains("UPDATE subscription SET plan_name = $1 "));
|
|
|
|
|
+ assert!(s.sql.contains("status <> $3"));
|
|
|
assert!(s.sql.contains("EXISTS (SELECT 1 FROM catalog_plan cp"));
|
|
assert!(s.sql.contains("EXISTS (SELECT 1 FROM catalog_plan cp"));
|
|
|
- assert!(s.sql.contains("cp.plan_id = $2::text"));
|
|
|
|
|
- assert!(s.sql.contains("cp.plan_name = $4::text"));
|
|
|
|
|
- assert!(s.sql.contains("cp.row_version = $5::int"));
|
|
|
|
|
|
|
+ assert!(s.sql.contains("cp.plan_id = $2"));
|
|
|
|
|
+ assert!(s.sql.contains("cp.plan_name = $4"));
|
|
|
|
|
+ assert!(s.sql.contains("cp.row_version = $5"));
|
|
|
|
|
+ assert!(!s.sql.contains("::"), "DML ⛔ 出现显式 cast:{}", s.sql);
|
|
|
// 占位符⛔ 跨语句复用:本条自带 5 个参数
|
|
// 占位符⛔ 跨语句复用:本条自带 5 个参数
|
|
|
assert_eq!(s.params.len(), 5);
|
|
assert_eq!(s.params.len(), 5);
|
|
|
let no_rv = rename_sync_statement("P-000007", "新名称", None);
|
|
let no_rv = rename_sync_statement("P-000007", "新名称", None);
|