|
|
@@ -1,77 +1,205 @@
|
|
|
-//! 订阅(第 3 册)——读写两侧均真落库:只读侧列表/详情,写侧新订/升降配/续订。
|
|
|
+//! 订阅维护与升降配承接(第 3 册 §5)。
|
|
|
//!
|
|
|
-//! 设计列由 `src/migrations/dev/20261107000002_bos_write_gap_columns.sql` 补入 dev 骨架
|
|
|
-//! (`contract_item_id`/`use_category`/`start_date`/`end_date`/年费与月结算两列/
|
|
|
-//! `replaces_subscription_id`/`row_version`)⇒ 只读侧**不再有缺列**,`columns_pending`
|
|
|
-//! 保留键回空数组(键不删=前端契约不变)。
|
|
|
+//! ## 本轮口径(设计列已在册 ⇒ 只读派生列一律⛔ 接受入参)
|
|
|
//!
|
|
|
-//! ⚠️ 写侧⛔ 写一期骨架列 `effective_date`/`expire_date`,只写设计列 `start_date`/`end_date`
|
|
|
-//! (=唯一真源);两列语义重叠,读侧仍原样呈现(存量种子只有旧列有值),合并口径已登 18 册待裁定。
|
|
|
+//! * **六项只读派生**(`annual_price_cents`/`monthly_settle_cents`/`end_date`/`line_exits`/
|
|
|
+//! `sub_mode`/`order_no`+`actual_opened_at`)+变更链指针 `replaces_subscription_id` 只属于
|
|
|
+//! `/change`:载荷出现即 `11103` 点名(§5.2「手工填价与手工改到期日=数据污染的入口」)。
|
|
|
+//! 唯一可录的周期入参=`term`(`yearly`/`quarterly`/`monthly`,缺省按年)。
|
|
|
+//! * **快照六列**(`plan_name`/`plan_kind`/`plan_owner_customer_id`/`line_exits`+`line_exit_key`/
|
|
|
+//! `term`/`sub_mode`)由档位与条目折算后落库=当时值(§2.3「改档⛔ 追溯改历史订阅」),
|
|
|
+//! 读侧⛔ 现取 `catalog_plan`(`to_json` 的 `plan_name` 走快照列)。
|
|
|
+//! * 金额与状态一律走 [`bos_invariant`]:`monthly_settle_of`=月结算唯一折算点、
|
|
|
+//! `subscription_status_of`=状态唯一判据、`in_use_quota_sum_batch`=额度求和唯一实现、
|
|
|
+//! `check_i6_subscription`=I6 唯一实现(违规即 `KLT-M224` 并带那份订阅的定位)。
|
|
|
//!
|
|
|
-//! ⚠️ `annual_price_cents`/`monthly_settle_cents`=在册冲突:openapi 把两列为必填,第 3 册 §2.3
|
|
|
-//! 口径是「只读派生、载荷出现即拒收」。本轮**按 openapi 入参落库**,每枚写侧响应回 `pricing_note`
|
|
|
-//! 原文点名,⛔ 自行改成派生、⛔ 静默。
|
|
|
+//! ## 写侧事务落点(§5.2 六步)
|
|
|
//!
|
|
|
-//! ⛔ `bos_audit_log`(本期不做);⛔ 本轮未补的深层设计形态(订阅快照列/`line_exit_key`/
|
|
|
-//! `term`/`trial_months` 等)——无处落库的入参在写侧响应 `not_persisted` 里点名。
|
|
|
+//! UDS 只暴露 `/dml/batch@v1`(整批原子提交、⛔ 批内条件中止、⛔ 行锁、⛔ 回读行集),故六步
|
|
|
+//! 落成**一次 `dml_batch`**:截原 → 新行 INSERT → `catalog_plan.first_referred_at` 打点 →
|
|
|
+//! 客户额度对齐;每步的前置条件写进 `WHERE` 谓词,影响行数**事后自检**,异常即
|
|
|
+//! `BosError::internal` 点名已提交的形态(⛔ 静默)。`SELECT … FOR UPDATE` 无能力 ⇒ 「锁条目行」
|
|
|
+//! 落成带谓词的守卫更新,差异登 18 册。
|
|
|
//!
|
|
|
-//! 可见性同 [`contract::get_list`]:沿用「可见客户」谓词,写侧同样据此判客户与合同可见。
|
|
|
+//! ⚠️ 工单事实、账单明细、套餐月成本三枚跨册只读口本轮⛔ 未接线 ⇒ 一律 `CrossRead::Unconfigured`
|
|
|
+//! +响应点名(⛔ 塌成「无阻塞」「未配置=零成本」)。
|
|
|
+//!
|
|
|
+//! ⛔ 日终到期翻转任务(`SUB-EFF`)本轮不做:状态在读侧按三要素推导(`status_display`)。
|
|
|
|
|
|
use axum::extract::State;
|
|
|
use axum::response::Response;
|
|
|
use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
|
|
|
use bos_api::AppState;
|
|
|
use bos_core::page::PageQuery;
|
|
|
-use bos_core::{BosError, RoleCode};
|
|
|
+use bos_core::{BosError, KltCode, RoleCode};
|
|
|
+use bos_invariant::{
|
|
|
+ check_i12b_same_customer, check_i13_trial_months, check_i6_subscription, check_plan_available,
|
|
|
+ check_subscription_deletable, contracts_opened, in_use_quota_sum_batch, monthly_settle_of,
|
|
|
+ normalize_line_exits, sub_mode_of, subscription_status_of, ActiveSubscriptionRow, CrossRead,
|
|
|
+ NormalizedExits, Opened, OpenedProbe, PlanRef, SubscriptionBlocks, UseCategory,
|
|
|
+ MAX_AMOUNT_CENTS,
|
|
|
+};
|
|
|
use bos_platform::clients::uds::{de, DmlStatement};
|
|
|
-use chrono::NaiveDate;
|
|
|
+use chrono::{Datelike, NaiveDate};
|
|
|
use serde::Deserialize;
|
|
|
-use serde_json::{json, Value};
|
|
|
+use serde_json::{json, Map, Value};
|
|
|
+use std::collections::{HashMap, HashSet};
|
|
|
|
|
|
-use super::listq::{as_num, as_opt_num, next_seq, pairs_by, total, Params};
|
|
|
+use super::listq::{
|
|
|
+ as_num, as_opt_num, count_by, next_seq, pairs_by, push_in, total, Params,
|
|
|
+};
|
|
|
use super::partner::customer_scope_pred;
|
|
|
|
|
|
/// 补列后已无缺列(⛔ 删键=前端类型会缺字段)。
|
|
|
const COLUMNS_PENDING: &[&str] = &[];
|
|
|
|
|
|
-/// 只读侧统一取列(⛔ 相关子查询取名,`plan_name`/`customer_name` 走 [`pairs_by`])。
|
|
|
-const SELECT_COLS: &str = "SELECT s.subscription_id, s.customer_id, s.contract_id, s.plan_id, s.status, \
|
|
|
- s.effective_date, s.expire_date, s.quota_slots, s.created_at, s.contract_item_id, s.use_category, \
|
|
|
- s.start_date, s.end_date, s.annual_price_cents, s.monthly_settle_cents, s.replaces_subscription_id, \
|
|
|
- s.row_version";
|
|
|
+/// 订阅时长值域(§2.3 `term`;⛔ 落库成月数,月数只是折算中间量)。
|
|
|
+const TERMS: [&str; 3] = ["yearly", "quarterly", "monthly"];
|
|
|
+
|
|
|
+/// 在用状态(§4 额度口径:仅待生效与生效中占额度)。
|
|
|
+const IN_USE_STATUS: [&str; 2] = ["pending", "active"];
|
|
|
+
|
|
|
+/// 六项只读派生列+变更链指针:新建载荷出现即 `11103`(§5.2 段 3/4、§2.3)。
|
|
|
+const CREATE_READ_ONLY: [&str; 8] = [
|
|
|
+ "annual_price_cents",
|
|
|
+ "monthly_settle_cents",
|
|
|
+ "end_date",
|
|
|
+ "line_exits",
|
|
|
+ "sub_mode",
|
|
|
+ "order_no",
|
|
|
+ "actual_opened_at",
|
|
|
+ "replaces_subscription_id",
|
|
|
+];
|
|
|
+
|
|
|
+/// 升降配额外只读项:客户与合同沿用原订阅(§5.3「⛔ 换客户」「合同编号=沿用原合同号、⛔ 另选」),
|
|
|
+/// 条目跟随新档位所属条目,用途分类跟着新档位走(需求明文「不换分类另建」)。
|
|
|
+const CHANGE_READ_ONLY: [&str; 11] = [
|
|
|
+ "customer_id",
|
|
|
+ "contract_id",
|
|
|
+ "contract_item_id",
|
|
|
+ "use_category",
|
|
|
+ "annual_price_cents",
|
|
|
+ "monthly_settle_cents",
|
|
|
+ "end_date",
|
|
|
+ "line_exits",
|
|
|
+ "sub_mode",
|
|
|
+ "order_no",
|
|
|
+ "actual_opened_at",
|
|
|
+];
|
|
|
+
|
|
|
+/// 修改白名单:只有这两列可改(§5.7)。
|
|
|
+const UPDATE_WHITELIST: [&str; 2] = ["trial_months", "discount_monthly_cents"];
|
|
|
+
|
|
|
+/// 修改里点名 `KLT-M229` 的越权列(换套餐/换合同=改订语义)。
|
|
|
+const UPDATE_M229_KEYS: [&str; 3] = ["plan_id", "contract_id", "contract_item_id"];
|
|
|
+
|
|
|
+/// 账单明细只读口未接线的原文说明(§5.5「未配置=不可判定,⛔ 当成无阻塞」)。
|
|
|
+const BILLING_UNCONFIGURED_NOTE: &str = "账单明细只读口本轮未接线(`billing_state=unconfigured`):\
|
|
|
+ 「账单阻塞=无」是取数未配置的回落值,不构成无阻塞结论,删除须由人工复核账单。";
|
|
|
+
|
|
|
+/// 套餐月成本只读口未接线的原文说明(§5.4 段 2)。
|
|
|
+const COST_UNCONFIGURED_NOTE: &str = "套餐月成本只读口本轮未接线(`plan_cost_state=unconfigured`):\
|
|
|
+ `plan_cost_item` 在册但成本折算属第 4 册口径,⛔ 以 0 冒充无成本。";
|
|
|
|
|
|
-/// `use_category` 值域(第 3 册 §4)。
|
|
|
-const USE_CATEGORIES: [&str; 5] = ["office", "live", "ai", "value_add", "customized"];
|
|
|
+/// 开户工单只读口未接线的原文说明(§2.1/§5.2 第 6 步)。
|
|
|
+const TICKET_UNCONFIGURED_NOTE: &str = "开户工单只读口本轮未接线(`open_tickets=unconfigured`):\
|
|
|
+ 开通态判定只用了本域自读的 `actual_opened_at` 一维,⛔ 据此认定合同未开通;\
|
|
|
+ 新订第 6 步「回写开户工单号与订单号」同样未接线,本轮未回写。";
|
|
|
|
|
|
-/// openapi 与设计册口径冲突的原文说明(⛔ 静默)。
|
|
|
-const PRICING_NOTE: &str = "annual_price_cents/monthly_settle_cents 按 openapi 入参落库;\
|
|
|
- 第 3 册 §2.3 口径=这两列只读派生(载荷出现即拒收、⛔ 手工改写),冲突已登记待裁定。";
|
|
|
+/// 统一取列(写侧回读、列表、详情、I6 取数共用一份列集=⛔ 三处漂移)。
|
|
|
+const SELECT_COLS: &str = "SELECT s.subscription_id, s.customer_id, s.contract_id, s.contract_item_id, \
|
|
|
+ s.plan_id, s.plan_name, s.plan_kind, s.plan_owner_customer_id, s.status, s.use_category, s.sub_mode, \
|
|
|
+ s.line_exits, s.line_exit_key, s.start_date, s.end_date, s.term, s.trial_months, \
|
|
|
+ s.discount_monthly_cents, s.annual_price_cents, s.monthly_settle_cents, s.quota_slots, \
|
|
|
+ s.replaces_subscription_id, s.order_no, s.actual_opened_at, s.effective_date, s.expire_date, \
|
|
|
+ s.created_at, s.row_version";
|
|
|
|
|
|
-// ───────────────────────── 写侧:入参 ─────────────────────────
|
|
|
+/// 档位取列(`p`=`catalog_plan`)。
|
|
|
+const PLAN_COLS: &str = "SELECT p.plan_id, p.plan_name, p.plan_kind, p.customer_id, p.status, \
|
|
|
+ p.use_category, p.sub_account_quota, p.annual_price_cents, \
|
|
|
+ p.monthly_settle_cents, p.line_exits, p.derived_from_contract_item_id, p.first_referred_at";
|
|
|
|
|
|
+// ───────────────────────── 入参 ─────────────────────────
|
|
|
+
|
|
|
+/// 新建载荷:`rest` 捕获未建模的键,用于把只读派生列点名拒收(⛔ 静默忽略)。
|
|
|
#[derive(Deserialize)]
|
|
|
pub struct SubscriptionCreateReq {
|
|
|
pub customer_id: String,
|
|
|
pub plan_id: String,
|
|
|
pub contract_id: String,
|
|
|
- pub contract_item_id: String,
|
|
|
- pub start_date: String,
|
|
|
- pub annual_price_cents: i64,
|
|
|
- pub monthly_settle_cents: i64,
|
|
|
+ /// 与 `contract_id` 同现同空(§2.3);合同内一条匹配条目都没有时可空(§5.2 末段)。
|
|
|
+ pub contract_item_id: Option<String>,
|
|
|
+ /// 缺省=当天(§5.2「开始日(默当天)」)。
|
|
|
+ pub start_date: Option<String>,
|
|
|
+ /// 唯一可录的周期入参;缺省按年(§5.2)。
|
|
|
+ pub term: Option<String>,
|
|
|
+ /// 仅当所选档位未预置用途分类(合同条目派生档)时必录(§5.2)。
|
|
|
pub use_category: Option<String>,
|
|
|
- /// ⚠️ openapi 新建请求体未声明本列(描述写「拒收…新建时的 end_date」);本轮按「带上即
|
|
|
- /// 校验并落库」处理,差异在响应 `spec_notes` 点名。
|
|
|
- pub end_date: Option<String>,
|
|
|
- /// openapi 未声明;带上就按乐观锁口径处理(新建无可锁既存行 ⇒ `spec_notes` 点名)。
|
|
|
- pub row_version: Option<i64>,
|
|
|
+ pub trial_months: Option<i64>,
|
|
|
+ pub discount_monthly_cents: Option<i64>,
|
|
|
+ #[serde(flatten)]
|
|
|
+ pub rest: Map<String, Value>,
|
|
|
}
|
|
|
|
|
|
+/// 升降配载荷:⛔ 客户/合同/条目/用途分类(全部沿用或跟随新档位)。
|
|
|
#[derive(Deserialize)]
|
|
|
pub struct SubscriptionChangeReq {
|
|
|
- /// 被替换的原订阅 ID。
|
|
|
+ /// 被替换的原订阅,至多被指向一次(§5.3)。
|
|
|
pub replaces_subscription_id: String,
|
|
|
+ pub plan_id: String,
|
|
|
+ /// 缺省=当天(截原基线)。
|
|
|
+ pub start_date: Option<String>,
|
|
|
+ pub term: Option<String>,
|
|
|
+ pub trial_months: Option<i64>,
|
|
|
+ pub discount_monthly_cents: Option<i64>,
|
|
|
+ /// 乐观锁作用于**原订阅行**。
|
|
|
+ pub row_version: Option<i64>,
|
|
|
+ #[serde(flatten)]
|
|
|
+ pub rest: Map<String, Value>,
|
|
|
+}
|
|
|
+
|
|
|
+/// 修改载荷:白名单两列+乐观锁,其余键一律拒收(§5.7)。
|
|
|
+#[derive(Deserialize)]
|
|
|
+pub struct SubscriptionUpdateReq {
|
|
|
+ pub subscription_id: String,
|
|
|
+ pub row_version: i64,
|
|
|
+ pub trial_months: Option<i64>,
|
|
|
+ pub discount_monthly_cents: Option<i64>,
|
|
|
+ #[serde(flatten)]
|
|
|
+ pub rest: Map<String, Value>,
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Deserialize)]
|
|
|
+pub struct SubscriptionIdReq {
|
|
|
+ pub subscription_id: String,
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Deserialize)]
|
|
|
+pub struct SubscriptionOptionsReq {
|
|
|
+ pub customer_id: String,
|
|
|
+ /// 只读列表用关键字(⛔ 客户名称/合同编号检索)。
|
|
|
+ pub keyword: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+/// 列表入参(`get_list` 与 `list_all` 共用=同一实现只差入参)。
|
|
|
+#[derive(Deserialize)]
|
|
|
+pub struct SubscriptionListReq {
|
|
|
+ #[serde(flatten)]
|
|
|
+ pub pg: PageQuery,
|
|
|
+ /// 命中 `subscription.plan_name` **快照列**(§5.7)。
|
|
|
+ pub keyword: Option<String>,
|
|
|
+ pub customer_id: Option<String>,
|
|
|
+ pub contract_id: Option<String>,
|
|
|
+ pub status: Option<String>,
|
|
|
+ /// 区域筛选=按客户挂载区域展开成客户集合(§5.7)。
|
|
|
+ pub region_ids: Option<Vec<String>>,
|
|
|
#[serde(flatten)]
|
|
|
- pub next: SubscriptionCreateReq,
|
|
|
+ pub rest: Map<String, Value>,
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Deserialize)]
|
|
|
+pub struct SubscriptionGetReq {
|
|
|
+ pub subscription_id: String,
|
|
|
}
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
@@ -89,7 +217,11 @@ pub struct SubscriptionStackReq {
|
|
|
pub row_version: Option<i64>,
|
|
|
}
|
|
|
|
|
|
-// ───────────────────────── 写侧:共用小件 ─────────────────────────
|
|
|
+/// 「叠加新建」分支未落库列的原文说明(本轮⛔ 改 stack 契约)。
|
|
|
+const STACK_LEGACY_NOTE: &str = "stack(续订)契约本轮不变:仍按 openapi 入参落 end_date/年费/\
|
|
|
+ 月结算金额,⛔ 与 §5.2「六项只读派生」同口径;差异已登记待裁定。";
|
|
|
+
|
|
|
+// ───────────────────────── 共用小件 ─────────────────────────
|
|
|
|
|
|
fn trimmed(raw: &str) -> String {
|
|
|
raw.trim().to_string()
|
|
|
@@ -114,14 +246,286 @@ fn date_text(d: NaiveDate) -> String {
|
|
|
d.format("%Y-%m-%d").to_string()
|
|
|
}
|
|
|
|
|
|
-/// 按顺序把「值+类型」摊成 `$n::type` 列表(值⛔ 拼进 SQL 原文=`sql_guard` 误杀面)。
|
|
|
-fn push_cast(p: &mut Params, vals: &[(Value, &str)]) -> String {
|
|
|
- vals.iter()
|
|
|
- .map(|(v, c)| format!("{}::{}", p.push(v.clone()), c))
|
|
|
- .collect::<Vec<_>>()
|
|
|
- .join(", ")
|
|
|
+fn today() -> String {
|
|
|
+ chrono::Local::now().format("%Y-%m-%d").to_string()
|
|
|
+}
|
|
|
+
|
|
|
+fn opt_trim(v: Option<&String>) -> Option<&str> {
|
|
|
+ v.map(String::as_str).map(str::trim).filter(|s| !s.is_empty())
|
|
|
+}
|
|
|
+
|
|
|
+/// 只读派生列出现在载荷里 ⇒ `11103` 逐列点名(⛔ 忽略、⛔ 只取服务端值而不告知)。
|
|
|
+fn reject_read_only(rest: &Map<String, Value>, keys: &[&str]) -> Result<(), BosError> {
|
|
|
+ let hit: Vec<&str> = keys.iter().copied().filter(|k| rest.contains_key(*k)).collect();
|
|
|
+ if hit.is_empty() {
|
|
|
+ return Ok(());
|
|
|
+ }
|
|
|
+ Err(BosError::bad_params(format!(
|
|
|
+ "以下只读派生列⛔ 接受入参(服务端按档位/条目折算落库):{}",
|
|
|
+ hit.join("、")
|
|
|
+ )))
|
|
|
+}
|
|
|
+
|
|
|
+/// 月数折算(§2.3:年=12/季=3/月=1)。
|
|
|
+fn term_months(term: &str) -> Result<u32, BosError> {
|
|
|
+ match term {
|
|
|
+ "yearly" => Ok(12),
|
|
|
+ "quarterly" => Ok(3),
|
|
|
+ "monthly" => Ok(1),
|
|
|
+ other => Err(BosError::bad_params(format!(
|
|
|
+ "term 须∈ {TERMS:?},实得 {other}"
|
|
|
+ ))),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 加 `n` 个月并把不存在的日期折到月末(§5.2「该月无对应日取月末」)。
|
|
|
+fn add_months_clamped(d: NaiveDate, n: u32) -> NaiveDate {
|
|
|
+ let total = d.year() as u64 * 12 + (d.month0() as u64) + n as u64;
|
|
|
+ let year = (total / 12) as i64;
|
|
|
+ let month = ((total % 12) + 1) as u32;
|
|
|
+ let dim = days_in_month(year, u64::from(month));
|
|
|
+ let day = d.day().min(dim);
|
|
|
+ NaiveDate::from_ymd_opt(year as i32, month, day).unwrap_or(d)
|
|
|
+}
|
|
|
+
|
|
|
+fn days_in_month(year: i64, month: u64) -> u32 {
|
|
|
+ let m = month as u32;
|
|
|
+ match m {
|
|
|
+ 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
|
|
|
+ 4 | 6 | 9 | 11 => 30,
|
|
|
+ 2 => {
|
|
|
+ if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
|
|
|
+ 29
|
|
|
+ } else {
|
|
|
+ 28
|
|
|
+ }
|
|
|
+ }
|
|
|
+ _ => 30,
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 年订阅价格=`term` × 月结算标准金额(季=月×3、月=月;年取档位年价原值)。
|
|
|
+fn annual_by_term(plan_annual: i64, monthly: i64, term: &str) -> i64 {
|
|
|
+ match term {
|
|
|
+ "monthly" => monthly,
|
|
|
+ "quarterly" => monthly.saturating_mul(3),
|
|
|
+ _ => plan_annual,
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// JSONB 出口列 → 字符串数组(dev 用 JSONB 承载 `TEXT[]`,可能回数组也可能回 JSON 串)。
|
|
|
+fn exits_of(v: Option<&Value>, field: &str) -> Result<Vec<String>, BosError> {
|
|
|
+ let bad = || BosError::bad_params(format!("{field} 须为字符串数组(线路出口原值)"));
|
|
|
+ match v {
|
|
|
+ None | Some(Value::Null) => Ok(Vec::new()),
|
|
|
+ Some(Value::String(s)) => serde_json::from_str::<Vec<String>>(s)
|
|
|
+ .map_err(|_| BosError::bad_params(format!("{field} 不是字符串数组的 JSON:{s}"))),
|
|
|
+ Some(Value::Array(arr)) => arr
|
|
|
+ .iter()
|
|
|
+ .map(|x| {
|
|
|
+ x.as_str()
|
|
|
+ .map(str::to_string)
|
|
|
+ .filter(|s| !s.trim().is_empty())
|
|
|
+ .ok_or_else(bad)
|
|
|
+ })
|
|
|
+ .collect(),
|
|
|
+ Some(_) => Err(bad()),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 出口列出参:JSONB 原样回(⛔ 摊平、⛔ 用摘要冒充原值)。
|
|
|
+fn exits_json(v: Option<&Value>) -> Value {
|
|
|
+ match v {
|
|
|
+ Some(Value::String(s)) => serde_json::from_str::<Value>(s).unwrap_or(Value::Null),
|
|
|
+ Some(x) => x.clone(),
|
|
|
+ None => Value::Null,
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 读侧的日期口径:设计列 → 一期骨架列(存量种子只有旧列有值)。
|
|
|
+fn start_text(r: &SubRow) -> Option<String> {
|
|
|
+ opt_trim(r.start_date.as_ref())
|
|
|
+ .or_else(|| opt_trim(r.effective_date.as_ref()))
|
|
|
+ .map(|s| s.to_string())
|
|
|
+}
|
|
|
+
|
|
|
+fn end_text(r: &SubRow) -> Option<String> {
|
|
|
+ opt_trim(r.end_date.as_ref())
|
|
|
+ .or_else(|| opt_trim(r.expire_date.as_ref()))
|
|
|
+ .map(|s| s.to_string())
|
|
|
+}
|
|
|
+
|
|
|
+/// 状态三态的读侧落点:库里的终态(`cancelled`/`replaced`)原样保留,其余按三要素推导。
|
|
|
+///
|
|
|
+/// 为什么不直接回库值:库里 `status` 由日终任务翻转,而 `SUB-EFF` 本轮⛔ 未做 ⇒ 直接回库值
|
|
|
+/// 会把「已到期」显示成「生效中」;也不⛔ 在日期不可判时硬套三态(会凭空判成到期)。
|
|
|
+fn status_display(r: &SubRow, today: &str) -> (String, String, Option<String>) {
|
|
|
+ let terminal = |s: &str| s == "cancelled" || s == "replaced";
|
|
|
+ let label = |k: &str| match k {
|
|
|
+ "pending" => "待生效",
|
|
|
+ "active" => "生效中",
|
|
|
+ "expired" => "已到期",
|
|
|
+ "replaced" => "已替换",
|
|
|
+ "cancelled" => "已退订",
|
|
|
+ _ => "未知",
|
|
|
+ };
|
|
|
+ if terminal(r.status.as_str()) {
|
|
|
+ return (r.status.clone(), label(r.status.as_str()).to_string(), None);
|
|
|
+ }
|
|
|
+ match (start_text(r), end_text(r)) {
|
|
|
+ (Some(s), Some(e)) => {
|
|
|
+ let k = subscription_status_of(&s, &e, today).as_str().to_string();
|
|
|
+ (k.clone(), label(&k).to_string(), None)
|
|
|
+ }
|
|
|
+ _ => (
|
|
|
+ r.status.clone(),
|
|
|
+ label(&r.status).to_string(),
|
|
|
+ Some(format!(
|
|
|
+ "订阅 {0} 的 start_date/end_date 不完整,状态⛔ 按三要素推导,原样回库里 status。",
|
|
|
+ r.subscription_id
|
|
|
+ )),
|
|
|
+ ),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 行级可操作性:到期/已替换/已退订的订阅⛔ 升降配、修改、删除(§5.3/§5.7)。
|
|
|
+fn editability(r: &SubRow, display_key: &str) -> (bool, Option<String>) {
|
|
|
+ if display_key != "pending" && display_key != "active" {
|
|
|
+ return (
|
|
|
+ false,
|
|
|
+ Some(format!(
|
|
|
+ "订阅状态={},⛔ 升降配/续订/修改/删除",
|
|
|
+ display_key
|
|
|
+ )),
|
|
|
+ );
|
|
|
+ }
|
|
|
+ if opt_trim(r.contract_id.as_ref()).is_none() {
|
|
|
+ return (
|
|
|
+ true,
|
|
|
+ Some("该订阅未关联合同(仅升降配⛔),合同开通态一栏显示「—」且⛔ 显示未开通。".to_string()),
|
|
|
+ );
|
|
|
+ }
|
|
|
+ (true, None)
|
|
|
+}
|
|
|
+
|
|
|
+// ───────────────────────── 行与出参 ─────────────────────────
|
|
|
+
|
|
|
+#[derive(Clone, Deserialize)]
|
|
|
+struct SubRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ subscription_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ customer_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ contract_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ contract_item_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_name: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_kind: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_owner_customer_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ status: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ use_category: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ sub_mode: Option<String>,
|
|
|
+ line_exits: Option<Value>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ line_exit_key: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ start_date: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ end_date: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ term: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ trial_months: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ discount_monthly_cents: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ annual_price_cents: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ monthly_settle_cents: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ quota_slots: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ replaces_subscription_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ order_no: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ actual_opened_at: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ effective_date: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ expire_date: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ created_at: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ row_version: String,
|
|
|
+}
|
|
|
+
|
|
|
+/// 列表行的钱列形态(§5.2 段 4「¥20,000(折算 ¥1,667/月)」)。
|
|
|
+fn money_json(r: &SubRow) -> Value {
|
|
|
+ let annual = as_opt_num(r.annual_price_cents.as_deref());
|
|
|
+ let monthly = as_opt_num(r.monthly_settle_cents.as_deref());
|
|
|
+ let display = match (&annual, &monthly) {
|
|
|
+ (Value::Number(a), Value::Number(m)) => Some(format!("{a}(折算 {m}/月)")),
|
|
|
+ _ => None,
|
|
|
+ };
|
|
|
+ json!({
|
|
|
+ "annual_price_cents": annual,
|
|
|
+ "monthly_settle_cents": monthly,
|
|
|
+ "monthly_settle_display": display,
|
|
|
+ "trial_months": as_opt_num(r.trial_months.as_deref()),
|
|
|
+ "discount_monthly_cents": as_opt_num(r.discount_monthly_cents.as_deref()),
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+/// 列表/详情共用的行出参:`plan_name` 走**快照列**(⛔ 现取 `catalog_plan`)。
|
|
|
+fn to_json(r: &SubRow, customer_name: Option<&str>, today: &str) -> Value {
|
|
|
+ let (key, label, note) = status_display(r, today);
|
|
|
+ let (editable, reason) = editability(r, &key);
|
|
|
+ json!({
|
|
|
+ "subscription_id": r.subscription_id,
|
|
|
+ "customer_id": r.customer_id,
|
|
|
+ "customer_name": customer_name,
|
|
|
+ "contract_id": r.contract_id,
|
|
|
+ "contract_item_id": r.contract_item_id,
|
|
|
+ "plan_id": r.plan_id,
|
|
|
+ "plan_name": r.plan_name,
|
|
|
+ "plan_kind": r.plan_kind,
|
|
|
+ "plan_owner_customer_id": r.plan_owner_customer_id,
|
|
|
+ "status": r.status,
|
|
|
+ "status_display": { "key": key, "label": label, "note": note },
|
|
|
+ "use_category": r.use_category,
|
|
|
+ "sub_mode": r.sub_mode,
|
|
|
+ "term": r.term,
|
|
|
+ "start_date": start_text(r),
|
|
|
+ "end_date": end_text(r),
|
|
|
+ "annual_price_cents": as_opt_num(r.annual_price_cents.as_deref()),
|
|
|
+ "monthly_settle_cents": as_opt_num(r.monthly_settle_cents.as_deref()),
|
|
|
+ "trial_months": as_opt_num(r.trial_months.as_deref()),
|
|
|
+ "discount_monthly_cents": as_opt_num(r.discount_monthly_cents.as_deref()),
|
|
|
+ "quota_slots": as_num(&r.quota_slots),
|
|
|
+ "replaces_subscription_id": r.replaces_subscription_id,
|
|
|
+ "order_no": r.order_no,
|
|
|
+ "actual_opened_at": r.actual_opened_at,
|
|
|
+ "effective_date": r.effective_date,
|
|
|
+ "expire_date": r.expire_date,
|
|
|
+ "created_at": r.created_at,
|
|
|
+ "row_version": as_num(&r.row_version),
|
|
|
+ "editable": editable,
|
|
|
+ "reason": reason,
|
|
|
+ })
|
|
|
}
|
|
|
|
|
|
+// ───────────────────────── 取数小件 ─────────────────────────
|
|
|
+
|
|
|
#[derive(Deserialize)]
|
|
|
struct IdRow {
|
|
|
#[serde(deserialize_with = "de::as_string")]
|
|
|
@@ -134,21 +538,36 @@ struct CountRow {
|
|
|
c: String,
|
|
|
}
|
|
|
|
|
|
-/// 合同在主档在册**且**落在当前账号可见范围内 ⇒ 回归属客户号。
|
|
|
-///
|
|
|
-/// 客户可见性据此判定即可(合同 `customer_id` 与请求 `customer_id` 一致 ⇒ 同一套
|
|
|
-/// [`customer_scope_pred`] 谓词下客户必然可见且存在),⛔ 多发一趟查询。
|
|
|
-async fn contract_owner(
|
|
|
+/// 按 ID+可见范围取整行。
|
|
|
+async fn scoped_sub(
|
|
|
+ state: &AppState,
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
+ sub_id: &str,
|
|
|
+) -> Result<Option<SubRow>, BosError> {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let mut w: Vec<String> = Vec::new();
|
|
|
+ w.push(customer_scope_pred(state, auth, &mut p, "s.customer_id").await?);
|
|
|
+ let s = p.push(Value::String(sub_id.to_string()));
|
|
|
+ w.push(format!("s.subscription_id = {s}::text"));
|
|
|
+ let sql = format!("{SELECT_COLS} FROM subscription s {}", p.where_clause(&w));
|
|
|
+ state.db.query_one::<SubRow>(&sql, p.values()).await
|
|
|
+}
|
|
|
+
|
|
|
+/// 客户在册**且**落在当前账号可见范围(§5.2 第 1 步;越权=`KLT-M221`)。
|
|
|
+async fn customer_visible(
|
|
|
state: &AppState,
|
|
|
auth: &bos_scope::AuthContext,
|
|
|
- contract_id: &str,
|
|
|
+ customer_id: &str,
|
|
|
) -> Result<Option<String>, BosError> {
|
|
|
let mut p = Params::default();
|
|
|
let mut w: Vec<String> = Vec::new();
|
|
|
- w.push(customer_scope_pred(state, auth, &mut p, "k.customer_id").await?);
|
|
|
- let cid = p.push(Value::String(contract_id.to_string()));
|
|
|
- w.push(format!("k.contract_id = {cid}::text"));
|
|
|
- let sql = format!("SELECT k.customer_id AS v FROM contract k {}", p.where_clause(&w));
|
|
|
+ w.push(customer_scope_pred(state, auth, &mut p, "c.customer_id").await?);
|
|
|
+ let c = p.push(Value::String(customer_id.to_string()));
|
|
|
+ w.push(format!("c.customer_id = {c}::text AND c.deleted_at IS NULL"));
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT c.customer_name AS v FROM customer c {}",
|
|
|
+ p.where_clause(&w)
|
|
|
+ );
|
|
|
Ok(state
|
|
|
.db
|
|
|
.query_one::<IdRow>(&sql, p.values())
|
|
|
@@ -156,625 +575,2357 @@ async fn contract_owner(
|
|
|
.map(|r| r.v))
|
|
|
}
|
|
|
|
|
|
-/// `contract_item_id` 须是该合同的服务构成条目(表 `contract_service_item`,⛔ 写它)。
|
|
|
-async fn ensure_contract_item(
|
|
|
- state: &AppState,
|
|
|
- contract_id: &str,
|
|
|
- item_id: &str,
|
|
|
-) -> Result<(), BosError> {
|
|
|
- let mut p = Params::default();
|
|
|
- let a = p.push(Value::String(item_id.to_string()));
|
|
|
- let b = p.push(Value::String(contract_id.to_string()));
|
|
|
- let sql = format!(
|
|
|
- "SELECT i.item_id AS v FROM contract_service_item i WHERE i.item_id = {a}::text \
|
|
|
- AND i.contract_id = {b}::text"
|
|
|
- );
|
|
|
- if state.db.query_one::<IdRow>(&sql, p.values()).await?.is_none() {
|
|
|
- return Err(BosError::bad_params(format!(
|
|
|
- "contract_item_id {item_id} 不是合同 {contract_id} 的服务构成条目(contract_service_item 在册⛔)"
|
|
|
- )));
|
|
|
- }
|
|
|
- Ok(())
|
|
|
-}
|
|
|
+/// 可见范围谓词由 [`customer_scope_pred`] 统一给出(区域展开出的客户同样受该谓词约束),
|
|
|
+/// 本模块⛔ 另取一份「可见客户集合」=两份口径迟早分叉。
|
|
|
|
|
|
-async fn ensure_plan(state: &AppState, plan_id: &str) -> Result<(), BosError> {
|
|
|
- let mut p = Params::default();
|
|
|
- let a = p.push(Value::String(plan_id.to_string()));
|
|
|
- let sql = format!("SELECT c.plan_id AS v FROM catalog_plan c WHERE c.plan_id = {a}::text");
|
|
|
- if state.db.query_one::<IdRow>(&sql, p.values()).await?.is_none() {
|
|
|
- return Err(BosError::bad_params(format!("plan_id {plan_id} 在 catalog_plan 在册⛔")));
|
|
|
+/// 区域 → 客户集合展开(§5.7「区域筛选按客户挂载区域展开」=本册⛔ 按区域列查本册表)。
|
|
|
+///
|
|
|
+/// 挂载表只有**直接父节点**,故须经 `dim_node_ancestor` 把筛选节点向下展开一层
|
|
|
+/// (`ancestor_id = 筛选节点` 的整棵子树都命中)。
|
|
|
+async fn customers_under_regions(state: &AppState, region_ids: &[String]) -> Result<Vec<String>, BosError> {
|
|
|
+ let ids: Vec<String> = region_ids.iter().map(|s| trimmed(s)).filter(|s| !s.is_empty()).collect();
|
|
|
+ if ids.is_empty() {
|
|
|
+ return Ok(Vec::new());
|
|
|
}
|
|
|
- Ok(())
|
|
|
-}
|
|
|
-
|
|
|
-/// 同一原订阅已被换过的次数(`replaces_subscription_id` 唯一 ⇒ ≥1 即⛔ 再换)。
|
|
|
-async fn replacement_count(state: &AppState, origin_id: &str) -> Result<i64, BosError> {
|
|
|
let mut p = Params::default();
|
|
|
- let a = p.push(Value::String(origin_id.to_string()));
|
|
|
+ let r = push_in(&mut p, "a.ancestor_id", &ids, "text");
|
|
|
let sql = format!(
|
|
|
- "SELECT COUNT(1) AS c FROM subscription r WHERE r.replaces_subscription_id = {a}::text"
|
|
|
+ "SELECT DISTINCT m.customer_id AS v FROM customer_region_mount m \
|
|
|
+ JOIN dim_node_ancestor a ON a.node_id = m.parent_node_id \
|
|
|
+ WHERE {r} AND m.customer_id IS NOT NULL ORDER BY 1"
|
|
|
);
|
|
|
Ok(state
|
|
|
.db
|
|
|
- .query_one::<CountRow>(&sql, p.values())
|
|
|
+ .query_all::<IdRow>(&sql, p.values())
|
|
|
.await?
|
|
|
- .map(|r| r.c.trim().parse::<i64>().unwrap_or(0))
|
|
|
- .unwrap_or(0))
|
|
|
+ .into_iter()
|
|
|
+ .map(|r| r.v)
|
|
|
+ .collect())
|
|
|
}
|
|
|
|
|
|
-/// 按 ID+可见范围取整行(写侧所有校验与「影响 0 行」复判都读它)。
|
|
|
-async fn scoped_sub(
|
|
|
- state: &AppState,
|
|
|
- auth: &bos_scope::AuthContext,
|
|
|
- sub_id: &str,
|
|
|
-) -> Result<Option<SubRow>, BosError> {
|
|
|
+/// 某客户的全部订阅(I6/额度对齐/变更链的取数底座)。
|
|
|
+async fn subs_of_customer(state: &AppState, customer_id: &str) -> Result<Vec<SubRow>, BosError> {
|
|
|
let mut p = Params::default();
|
|
|
- let mut w: Vec<String> = Vec::new();
|
|
|
- w.push(customer_scope_pred(state, auth, &mut p, "s.customer_id").await?);
|
|
|
- let s = p.push(Value::String(sub_id.to_string()));
|
|
|
- w.push(format!("s.subscription_id = {s}::text"));
|
|
|
- let sql = format!("{SELECT_COLS} FROM subscription s {}", p.where_clause(&w));
|
|
|
- state.db.query_one::<SubRow>(&sql, p.values()).await
|
|
|
+ let c = p.push(Value::String(customer_id.to_string()));
|
|
|
+ let sql = format!(
|
|
|
+ "{SELECT_COLS} FROM subscription s WHERE s.customer_id = {c}::text ORDER BY s.subscription_id"
|
|
|
+ );
|
|
|
+ state.db.query_all::<SubRow>(&sql, p.values()).await
|
|
|
}
|
|
|
|
|
|
-struct NewSub {
|
|
|
- id: String,
|
|
|
- sql: String,
|
|
|
- params: Vec<Value>,
|
|
|
+/// 档位行(含可用区间与派生链)。
|
|
|
+#[derive(Deserialize)]
|
|
|
+struct PlanRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ plan_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ plan_name: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ plan_kind: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ customer_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ status: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ use_category: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ sub_account_quota: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ annual_price_cents: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ monthly_settle_cents: Option<String>,
|
|
|
+ line_exits: Option<Value>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ derived_from_contract_item_id: Option<String>,
|
|
|
+ /// 首次引用打点:`Some` ⇒ 该档已被引用过(§5.2「已引用过的档位⛔ 下架」同源)。
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ first_referred_at: Option<String>,
|
|
|
}
|
|
|
|
|
|
-/// 新订/升降配共用的**新订阅行**:逐条校验+发号+组 INSERT(⛔ 写 `effective_date`/`expire_date`,
|
|
|
-/// `status`/`quota_slots`/`created_at` 走库默认值,⛔ 造值)。
|
|
|
-///
|
|
|
-/// 只组不发:升降配要把它和「原订阅置 `replaced`」塞进同一次 `dml_batch`=原子提交。
|
|
|
-async fn build_new_subscription(
|
|
|
- state: &AppState,
|
|
|
- auth: &bos_scope::AuthContext,
|
|
|
- b: &SubscriptionCreateReq,
|
|
|
- replaces: Option<&str>,
|
|
|
-) -> Result<NewSub, BosError> {
|
|
|
- let customer_id = req_field("customer_id", &b.customer_id)?;
|
|
|
- let plan_id = req_field("plan_id", &b.plan_id)?;
|
|
|
- let contract_id = req_field("contract_id", &b.contract_id)?;
|
|
|
- let item_id = req_field("contract_item_id", &b.contract_item_id)?;
|
|
|
-
|
|
|
- let owner = contract_owner(state, auth, &contract_id)
|
|
|
- .await?
|
|
|
- .ok_or_else(|| BosError::not_found(format!("合同不存在或超出当前账号可见范围:{contract_id}")))?;
|
|
|
- if owner != customer_id {
|
|
|
- return Err(BosError::bad_params(format!(
|
|
|
- "合同 {contract_id} 归属客户 {owner},与请求 customer_id {customer_id} 不一致"
|
|
|
- )));
|
|
|
+impl PlanRow {
|
|
|
+ fn to_ref(&self) -> PlanRef {
|
|
|
+ PlanRef {
|
|
|
+ plan_id: self.plan_id.clone(),
|
|
|
+ plan_name: self.plan_name.clone(),
|
|
|
+ plan_kind: self.plan_kind.clone(),
|
|
|
+ owner_customer_id: opt_trim(self.customer_id.as_ref()).map(str::to_string),
|
|
|
+ sub_account_quota: self
|
|
|
+ .sub_account_quota
|
|
|
+ .as_deref()
|
|
|
+ .and_then(|s| s.trim().parse::<i64>().ok())
|
|
|
+ .unwrap_or(0),
|
|
|
+ annual_price_cents: self
|
|
|
+ .annual_price_cents
|
|
|
+ .trim()
|
|
|
+ .parse::<i64>()
|
|
|
+ .unwrap_or(0),
|
|
|
+ monthly_settle_cents: self
|
|
|
+ .monthly_settle_cents
|
|
|
+ .as_deref()
|
|
|
+ .and_then(|s| s.trim().parse::<i64>().ok()),
|
|
|
+ available: self.status == "active",
|
|
|
+ }
|
|
|
}
|
|
|
- ensure_contract_item(state, &contract_id, &item_id).await?;
|
|
|
- ensure_plan(state, &plan_id).await?;
|
|
|
|
|
|
- let use_category = match b.use_category.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
|
|
- Some(v) => {
|
|
|
- if !USE_CATEGORIES.contains(&v) {
|
|
|
- return Err(BosError::bad_params(format!(
|
|
|
- "use_category 须∈ {USE_CATEGORIES:?},实得 {v}"
|
|
|
- )));
|
|
|
- }
|
|
|
- Value::String(v.to_string())
|
|
|
- }
|
|
|
- None => Value::Null,
|
|
|
- };
|
|
|
+ fn monthly(&self) -> i64 {
|
|
|
+ monthly_settle_of(self.monthly_settle_cents.as_deref().and_then(|s| s.trim().parse().ok()), self.annual_price_cents.trim().parse().unwrap_or(0))
|
|
|
+ }
|
|
|
+}
|
|
|
|
|
|
- let start_raw = req_field("start_date", &b.start_date)?;
|
|
|
- let start = parse_date("start_date", &start_raw)?;
|
|
|
- let end_value = match b.end_date.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
|
|
- Some(raw) => {
|
|
|
- let end = parse_date("end_date", raw)?;
|
|
|
- if end <= start {
|
|
|
- return Err(BosError::bad_params(format!(
|
|
|
- "end_date {} 须晚于 start_date {}",
|
|
|
- raw,
|
|
|
- date_text(start)
|
|
|
- )));
|
|
|
- }
|
|
|
- Value::String(date_text(end))
|
|
|
- }
|
|
|
- None => Value::Null,
|
|
|
- };
|
|
|
+async fn plan_rows(state: &AppState, ids: &[String]) -> Result<Vec<PlanRow>, BosError> {
|
|
|
+ if ids.is_empty() {
|
|
|
+ return Ok(Vec::new());
|
|
|
+ }
|
|
|
+ let mut p = Params::default();
|
|
|
+ let in_pred = push_in(&mut p, "p.plan_id", ids, "text");
|
|
|
+ let sql = format!("{PLAN_COLS} FROM catalog_plan p WHERE {in_pred}");
|
|
|
+ state.db.query_all::<PlanRow>(&sql, p.values()).await
|
|
|
+}
|
|
|
|
|
|
- let year = chrono::Local::now()
|
|
|
- .format("%Y")
|
|
|
- .to_string()
|
|
|
- .parse::<i32>()
|
|
|
- .map_err(|e| BosError::internal(format!("取当年年份失败:{e}")))?;
|
|
|
- let id = format!("SUB-{:06}", next_seq(state.db.as_ref(), "subscription", "subscription", year).await?);
|
|
|
+async fn plan_row(state: &AppState, plan_id: &str) -> Result<Option<PlanRow>, BosError> {
|
|
|
+ Ok(plan_rows(state, &[plan_id.to_string()]).await?.pop())
|
|
|
+}
|
|
|
+
|
|
|
+/// 合同行。
|
|
|
+#[derive(Deserialize)]
|
|
|
+struct ContractRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ contract_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ customer_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ contract_no: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ external_no: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ status: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ end_date: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ attachment_url: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+const CONTRACT_COLS: &str = "SELECT k.contract_id, k.customer_id, k.contract_no, k.external_no, k.status, \
|
|
|
+ k.end_date, k.attachment_url";
|
|
|
|
|
|
+async fn contracts_of_customer(
|
|
|
+ state: &AppState,
|
|
|
+ customer_id: &str,
|
|
|
+) -> Result<Vec<ContractRow>, BosError> {
|
|
|
let mut p = Params::default();
|
|
|
- let vals: Vec<(Value, &str)> = vec![
|
|
|
- (Value::String(id.clone()), "text"),
|
|
|
- (Value::String(customer_id), "text"),
|
|
|
- (Value::String(contract_id), "text"),
|
|
|
- (Value::String(plan_id), "text"),
|
|
|
- (Value::String(item_id), "text"),
|
|
|
- (use_category, "text"),
|
|
|
- (Value::String(date_text(start)), "date"),
|
|
|
- (end_value, "date"),
|
|
|
- (Value::from(b.annual_price_cents), "bigint"),
|
|
|
- (Value::from(b.monthly_settle_cents), "bigint"),
|
|
|
- match replaces {
|
|
|
- Some(v) => (Value::String(v.to_string()), "text"),
|
|
|
- None => (Value::Null, "text"),
|
|
|
- },
|
|
|
- ];
|
|
|
+ let c = p.push(Value::String(customer_id.to_string()));
|
|
|
let sql = format!(
|
|
|
- "INSERT INTO subscription (subscription_id, customer_id, contract_id, plan_id, \
|
|
|
- contract_item_id, use_category, start_date, end_date, annual_price_cents, \
|
|
|
- monthly_settle_cents, replaces_subscription_id) VALUES ({})",
|
|
|
- push_cast(&mut p, &vals)
|
|
|
+ "{CONTRACT_COLS} FROM contract k WHERE k.customer_id = {c}::text ORDER BY k.contract_id"
|
|
|
);
|
|
|
- Ok(NewSub { id, sql, params: p.values().to_vec() })
|
|
|
+ state.db.query_all::<ContractRow>(&sql, p.values()).await
|
|
|
+}
|
|
|
+
|
|
|
+async fn contract_row(state: &AppState, contract_id: &str) -> Result<Option<ContractRow>, BosError> {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let c = p.push(Value::String(contract_id.to_string()));
|
|
|
+ let sql = format!("{CONTRACT_COLS} FROM contract k WHERE k.contract_id = {c}::text");
|
|
|
+ state.db.query_one::<ContractRow>(&sql, p.values()).await
|
|
|
+}
|
|
|
+
|
|
|
+/// 合同服务构成条目(`custom_spec`=合同条目派生档的来源)。
|
|
|
+#[derive(Deserialize)]
|
|
|
+struct ItemRow {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ item_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ contract_id: String,
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ item_kind: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ plan_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ derived_plan_id: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ use_category: Option<String>,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ annual_price_cents: Option<String>,
|
|
|
+ line_exits: Option<Value>,
|
|
|
}
|
|
|
|
|
|
-/// 写侧统一回执:⛔ 回显请求体假装成功——落库后按 ID 回读库内真值再出参
|
|
|
-/// (`/dml/batch@v1` ⛔ 不回 `RETURNING` 值)。
|
|
|
-async fn write_back(
|
|
|
+const ITEM_COLS: &str = "SELECT i.item_id, i.contract_id, i.item_kind, i.plan_id, i.derived_plan_id, \
|
|
|
+ i.use_category, i.annual_price_cents, i.line_exits";
|
|
|
+
|
|
|
+async fn items_of_contracts(
|
|
|
state: &AppState,
|
|
|
- sub_id: &str,
|
|
|
- op: &str,
|
|
|
- not_persisted: Vec<String>,
|
|
|
- spec_notes: Vec<String>,
|
|
|
-) -> Response {
|
|
|
+ contract_ids: &[String],
|
|
|
+) -> Result<Vec<ItemRow>, BosError> {
|
|
|
+ if contract_ids.is_empty() {
|
|
|
+ return Ok(Vec::new());
|
|
|
+ }
|
|
|
let mut p = Params::default();
|
|
|
- let s = p.push(Value::String(sub_id.to_string()));
|
|
|
- let sql = format!("{SELECT_COLS} FROM subscription s WHERE s.subscription_id = {s}::text");
|
|
|
- let r = match state.db.query_one::<SubRow>(&sql, p.values()).await {
|
|
|
- Ok(Some(r)) => r,
|
|
|
- Ok(None) => {
|
|
|
- return json_err(BosError::internal(format!(
|
|
|
- "写入后回读⛔ 在册:订阅 {sub_id}(短批已提交,须人工核对)"
|
|
|
- )))
|
|
|
+ let in_pred = push_in(&mut p, "i.contract_id", contract_ids, "text");
|
|
|
+ let sql = format!("{ITEM_COLS} FROM contract_service_item i WHERE {in_pred} ORDER BY i.item_id");
|
|
|
+ state.db.query_all::<ItemRow>(&sql, p.values()).await
|
|
|
+}
|
|
|
+
|
|
|
+/// 开通态探测(§5.2 段 5:工单一维本轮未接线=`Unconfigured`;本域自读 `actual_opened_at`)。
|
|
|
+///
|
|
|
+/// 取数失败 ⇒ `KLT-S406` 整体失败,⛔ 降级成「全部未开通」(那会把已交付合同摆进候选、
|
|
|
+/// 再经 `KLT-M223` 永久封死补录路径)。
|
|
|
+async fn opened_map_for(
|
|
|
+ state: &AppState,
|
|
|
+ contracts: &[ContractRow],
|
|
|
+) -> Result<HashMap<String, Opened>, BosError> {
|
|
|
+ let ids: Vec<String> = contracts.iter().map(|c| c.contract_id.clone()).collect();
|
|
|
+ let mut actual: HashMap<String, Vec<Option<String>>> = HashMap::new();
|
|
|
+ if !ids.is_empty() {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let in_pred = push_in(&mut p, "s.contract_id", &ids, "text");
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT s.contract_id AS k, s.actual_opened_at AS v FROM subscription s WHERE {in_pred}"
|
|
|
+ );
|
|
|
+ #[derive(Deserialize)]
|
|
|
+ struct Pair {
|
|
|
+ #[serde(deserialize_with = "de::as_string")]
|
|
|
+ k: String,
|
|
|
+ #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
+ v: Option<String>,
|
|
|
+ }
|
|
|
+ let rows = state.db.query_all::<Pair>(&sql, p.values()).await.map_err(|e| {
|
|
|
+ BosError::klt(
|
|
|
+ KltCode::S406,
|
|
|
+ format!("读取订阅实际开通日失败,开通态不可判定(⛔ 降级成「未开通」):{e}"),
|
|
|
+ )
|
|
|
+ })?;
|
|
|
+ for r in rows {
|
|
|
+ actual.entry(r.k).or_default().push(r.v);
|
|
|
}
|
|
|
+ }
|
|
|
+ let probes: Vec<(String, OpenedProbe)> = contracts
|
|
|
+ .iter()
|
|
|
+ .map(|c| {
|
|
|
+ (
|
|
|
+ c.contract_id.clone(),
|
|
|
+ OpenedProbe {
|
|
|
+ open_tickets: CrossRead::Unconfigured,
|
|
|
+ subscription_actual_opened_at: actual
|
|
|
+ .get(&c.contract_id)
|
|
|
+ .cloned()
|
|
|
+ .unwrap_or_default(),
|
|
|
+ },
|
|
|
+ )
|
|
|
+ })
|
|
|
+ .collect();
|
|
|
+ contracts_opened(&probes).map_err(|e| {
|
|
|
+ BosError::klt(KltCode::S406, format!("开通态判定失败(⛔ 降级成「未开通」):{e}"))
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+// ───────────────────────── §5.2 套餐候选 ─────────────────────────
|
|
|
+
|
|
|
+/// `POST /subscription/plan_options@v1`。
|
|
|
+///
|
|
|
+/// 两段候选=本客户自定义档(**含合同条目派生档**)+全部固定档,⛔ 他客户自定义档;
|
|
|
+/// 每行带只读 `sub_mode`(`sub_mode_of(用途分类)`)与可选性/不可选原因。
|
|
|
+pub async fn plan_options(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionOptionsReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let cid = match req_field("customer_id", &body.customer_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // 读口同样把客户当不可信输入重算 ⇒ `KLT-M221`(一次判定,⛔ 重复查库)
|
|
|
+ if let Err(e) = require_customer(&state, &auth, &cid).await {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let kw = opt_trim(body.keyword.as_ref());
|
|
|
+ let mut p = Params::default();
|
|
|
+ let mut w: Vec<String> = vec![format!(
|
|
|
+ "(p.plan_kind = {}::text OR (p.plan_kind = {}::text AND p.customer_id = {}::text))",
|
|
|
+ p.push(Value::String("fixed".to_string())),
|
|
|
+ p.push(Value::String("custom".to_string())),
|
|
|
+ p.push(Value::String(cid.clone()))
|
|
|
+ )];
|
|
|
+ if let Some(k) = p.push_like(kw) {
|
|
|
+ w.push(format!("p.plan_name LIKE {k}"));
|
|
|
+ }
|
|
|
+ let sql = format!(
|
|
|
+ "{PLAN_COLS} FROM catalog_plan p {} ORDER BY p.plan_kind, p.plan_name, p.plan_id",
|
|
|
+ p.where_clause(&w)
|
|
|
+ );
|
|
|
+ let rows = match state.db.query_all::<PlanRow>(&sql, p.values()).await {
|
|
|
+ Ok(r) => r,
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
- let cids = vec![r.customer_id.clone()];
|
|
|
- let pids = r.plan_id.clone().into_iter().collect::<Vec<String>>();
|
|
|
- let names = match pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &cids).await {
|
|
|
+ // 引用次数单独取(⛔ 相关子查询混进档位行),与本册其它计数同源走 `listq::count_by`
|
|
|
+ let plan_ids: Vec<String> = rows.iter().map(|r| r.plan_id.clone()).collect();
|
|
|
+ let referred = match count_by(state.db.as_ref(), "subscription", "plan_id", &plan_ids).await {
|
|
|
Ok(m) => m,
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
- let plans = match pairs_by(state.db.as_ref(), "catalog_plan", "plan_id", "plan_name", &pids).await {
|
|
|
+ let items: Vec<Value> = rows
|
|
|
+ .iter()
|
|
|
+ .map(|o| {
|
|
|
+ let pr = o.to_ref();
|
|
|
+ let (available, reason) = plan_selectability(&pr, &cid);
|
|
|
+ let derived = o.derived_from_contract_item_id.is_some();
|
|
|
+ let sub_mode = match opt_trim(o.use_category.as_ref()) {
|
|
|
+ Some(uc) => UseCategory::parse(uc)
|
|
|
+ .ok()
|
|
|
+ .map(|c| sub_mode_of(c).as_str().to_string()),
|
|
|
+ None => None,
|
|
|
+ };
|
|
|
+ let rc = referred.get(&o.plan_id).copied().unwrap_or(0);
|
|
|
+ json!({
|
|
|
+ "plan_id": o.plan_id,
|
|
|
+ "plan_name": o.plan_name,
|
|
|
+ "plan_kind": o.plan_kind,
|
|
|
+ "owner_customer_id": o.customer_id,
|
|
|
+ "derived": derived,
|
|
|
+ "source_label": if derived { Some("合同条目派生") } else { None },
|
|
|
+ "derived_from_contract_item_id": o.derived_from_contract_item_id,
|
|
|
+ "use_category": o.use_category,
|
|
|
+ "sub_mode": sub_mode,
|
|
|
+ "annual_price_cents": as_num(&o.annual_price_cents),
|
|
|
+ "monthly_settle_cents": as_num(&o.monthly().to_string()),
|
|
|
+ "sub_account_quota": as_opt_num(o.sub_account_quota.as_deref()),
|
|
|
+ "line_exits": exits_json(o.line_exits.as_ref()),
|
|
|
+ "referred_count": rc,
|
|
|
+ "first_referred": o.first_referred_at.is_some(),
|
|
|
+ "available": available,
|
|
|
+ "unavailable_reason": reason,
|
|
|
+ })
|
|
|
+ })
|
|
|
+ .collect();
|
|
|
+ json_ok(json!({
|
|
|
+ "customer_id": cid,
|
|
|
+ "items": items,
|
|
|
+ "total": items.len(),
|
|
|
+ "notes": [
|
|
|
+ "「订阅方式」由用途分类经 sub_mode_of 折算,前端⛔ 重实现;派生自定义档未预置用途分类时\
|
|
|
+ sub_mode=null,新订时由运营必录用途分类。",
|
|
|
+ TICKET_UNCONFIGURED_NOTE,
|
|
|
+ ],
|
|
|
+ "columns_pending": COLUMNS_PENDING,
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+/// 档位可选性(§5.2「不可选=KLT-M228」的读侧同源判据;写侧兜底仍走 I12a/I12b)。
|
|
|
+///
|
|
|
+/// ⚠️ 档位⛔ 有「可用日期窗口」列(`catalog_plan` 在册列只到 `status`/`first_referred_at`,
|
|
|
+/// 设计稿未给 `available_from`/`available_to`)⇒ 停用只按 `status` 判,⛔ 造列。
|
|
|
+fn plan_selectability(pr: &PlanRef, customer_id: &str) -> (bool, Option<String>) {
|
|
|
+ if !pr.available {
|
|
|
+ return (false, Some("档位已停用,⛔ 被新订阅选中".to_string()));
|
|
|
+ }
|
|
|
+ if let Some(owner) = pr.owner_customer_id.as_deref() {
|
|
|
+ if owner != customer_id {
|
|
|
+ return (false, Some(format!("自定义档归属客户 {owner},⛔ 跨客户选用")));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ (true, None)
|
|
|
+}
|
|
|
+
|
|
|
+// ───────────────────────── 合同候选 ─────────────────────────
|
|
|
+
|
|
|
+/// `POST /subscription/contract_options@v1`。
|
|
|
+///
|
|
|
+/// 只出「未开通」合同(开通态=开户工单 ∪ 关联订阅 `actual_opened_at`),两级=合同 → 尚未有订阅的
|
|
|
+/// 条目;`custom_spec` 条目带其派生档。⛔ 月结算标准金额出现在本口出参。
|
|
|
+pub async fn contract_options(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionOptionsReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let cid = match req_field("customer_id", &body.customer_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // 取数失败⛔ 判成「不可见」(M221 会掩盖故障):可见性只由 `require_customer` 一处给出
|
|
|
+ if let Err(e) = require_customer(&state, &auth, &cid).await {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let contracts = match contracts_of_customer(&state, &cid).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let opened = match opened_map_for(&state, &contracts).await {
|
|
|
Ok(m) => m,
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
- let mut v = to_json(
|
|
|
- &r,
|
|
|
- names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str),
|
|
|
- r.plan_id.as_deref().and_then(|id| plans.get(id).and_then(|x| x.first())).map(String::as_str),
|
|
|
+ let free: Vec<&ContractRow> = contracts
|
|
|
+ .iter()
|
|
|
+ .filter(|c| matches!(opened.get(&c.contract_id), Some(Opened::NotOpened)))
|
|
|
+ .collect();
|
|
|
+ if free.is_empty() {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M222,
|
|
|
+ format!("该客户没有可选「未开通」合同(共 {} 条合同,全部已开通)", contracts.len()),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let ids: Vec<String> = free.iter().map(|c| c.contract_id.clone()).collect();
|
|
|
+ let items = match items_of_contracts(&state, &ids).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // 已被订阅引用的条目⛔ 再被选(§5.2「尚未有订阅的条目」)。
|
|
|
+ let mut referenced: HashSet<String> = HashSet::new();
|
|
|
+ if !ids.is_empty() {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let in_pred = match push_in_owned(&mut p, "s.contract_id", &ids) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT s.contract_item_id AS v FROM subscription s \
|
|
|
+ WHERE {in_pred} AND s.contract_item_id IS NOT NULL"
|
|
|
+ );
|
|
|
+ match state.db.query_all::<IdRow>(&sql, p.values()).await {
|
|
|
+ Ok(rows) => referenced = rows.into_iter().map(|r| r.v).collect(),
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ }
|
|
|
+ }
|
|
|
+ let plan_ids: Vec<String> = items
|
|
|
+ .iter()
|
|
|
+ .flat_map(|i| [i.plan_id.clone(), i.derived_plan_id.clone()])
|
|
|
+ .flatten()
|
|
|
+ .collect();
|
|
|
+ let plans = match plan_rows(&state, &plan_ids).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let plan_by_id: HashMap<&str, &PlanRow> = plans.iter().map(|r| (r.plan_id.as_str(), r)).collect();
|
|
|
+ let mut out: Vec<Value> = Vec::new();
|
|
|
+ for c in free {
|
|
|
+ let rows: Vec<Value> = items
|
|
|
+ .iter()
|
|
|
+ .filter(|i| i.contract_id == c.contract_id && !referenced.contains(&i.item_id))
|
|
|
+ .map(|i| {
|
|
|
+ let pid = opt_trim(i.derived_plan_id.as_ref()).or_else(|| opt_trim(i.plan_id.as_ref()));
|
|
|
+ let pr = pid.and_then(|id| plan_by_id.get(id)).map(|r| r.to_ref());
|
|
|
+ let (available, reason) = match pr.as_ref() {
|
|
|
+ Some(pr) => plan_selectability(pr, &cid),
|
|
|
+ None => (false, Some("该条目未关联可选档位".to_string())),
|
|
|
+ };
|
|
|
+ json!({
|
|
|
+ "item_id": i.item_id,
|
|
|
+ "item_kind": i.item_kind,
|
|
|
+ "plan_id": pid,
|
|
|
+ "plan_name": pr.as_ref().map(|p| p.plan_name.clone()),
|
|
|
+ "derived": i.item_kind == "custom_spec",
|
|
|
+ "source_label": if i.item_kind == "custom_spec" { Some("合同条目派生") } else { None },
|
|
|
+ "use_category": i.use_category,
|
|
|
+ "annual_price_cents": as_opt_num(i.annual_price_cents.as_deref()),
|
|
|
+ "line_exits": exits_json(i.line_exits.as_ref()),
|
|
|
+ "available": available,
|
|
|
+ "unavailable_reason": reason,
|
|
|
+ })
|
|
|
+ })
|
|
|
+ .collect();
|
|
|
+ out.push(json!({
|
|
|
+ "contract_id": c.contract_id,
|
|
|
+ "contract_no": opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()),
|
|
|
+ "internal_no": c.contract_no,
|
|
|
+ "status": c.status,
|
|
|
+ "end_date": c.end_date,
|
|
|
+ "attachment_url": c.attachment_url,
|
|
|
+ "opened": false,
|
|
|
+ "items": rows,
|
|
|
+ }));
|
|
|
+ }
|
|
|
+ json_ok(json!({
|
|
|
+ "customer_id": cid,
|
|
|
+ "items": out,
|
|
|
+ "total": out.len(),
|
|
|
+ "notes": [
|
|
|
+ "出参⛔ 出现「月结算标准金额」:月结算只在选定档位后由 monthly_settle_of 折算并只读显示。",
|
|
|
+ TICKET_UNCONFIGURED_NOTE,
|
|
|
+ ],
|
|
|
+ "columns_pending": COLUMNS_PENDING,
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+/// `push_in` 的空集保险版(调用方已保证非空,空集=内部错误而非「不过滤」)。
|
|
|
+fn push_in_owned(p: &mut Params, col: &str, ids: &[String]) -> Result<String, BosError> {
|
|
|
+ if ids.is_empty() {
|
|
|
+ return Err(BosError::internal("push_in_owned 不接受空 ID 集合(空集会退化成不过滤)"));
|
|
|
+ }
|
|
|
+ Ok(push_in(p, col, ids, "text"))
|
|
|
+}
|
|
|
+
|
|
|
+// ───────────────────────── 写侧:共用折算 ─────────────────────────
|
|
|
+
|
|
|
+/// 用途分类:由套餐带入(⛔ 改写);派生自定义档未预置时由运营必录(§5.2)。
|
|
|
+fn category_of(payload: Option<&String>, plan: &PlanRow) -> Result<UseCategory, BosError> {
|
|
|
+ match opt_trim(plan.use_category.as_ref()) {
|
|
|
+ Some(v) => {
|
|
|
+ let plan_cat = UseCategory::parse(v)?;
|
|
|
+ if let Some(raw) = opt_trim(payload) {
|
|
|
+ let got = UseCategory::parse(raw)?;
|
|
|
+ if got != plan_cat {
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "use_category 由套餐用途分类带入({}),⛔ 改写为 {}",
|
|
|
+ plan_cat.as_str(),
|
|
|
+ got.as_str()
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Ok(plan_cat)
|
|
|
+ }
|
|
|
+ None => match opt_trim(payload) {
|
|
|
+ Some(v) => UseCategory::parse(v),
|
|
|
+ None => Err(BosError::bad_params(
|
|
|
+ "use_category 必录:所选档位未预置用途分类(合同条目派生档),由运营选定后带入订阅方式",
|
|
|
+ )),
|
|
|
+ },
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// 周期与价格的派生结果(§5.2 段 3/4)。
|
|
|
+struct Period {
|
|
|
+ term: String,
|
|
|
+ start: String,
|
|
|
+ end: String,
|
|
|
+ annual: i64,
|
|
|
+ monthly: i64,
|
|
|
+}
|
|
|
+
|
|
|
+/// `term` → 起止与年费/月结算的唯一折算点(⛔ 落库月数、⛔ 手工填价、⛔ 手工改到期日)。
|
|
|
+fn derive_period(
|
|
|
+ plan: &PlanRow,
|
|
|
+ term_raw: Option<&String>,
|
|
|
+ start_raw: Option<&String>,
|
|
|
+ contract_end: Option<&str>,
|
|
|
+ today: &str,
|
|
|
+) -> Result<Period, BosError> {
|
|
|
+ let term = opt_trim(term_raw).unwrap_or("yearly").to_string();
|
|
|
+ let months = term_months(&term)?;
|
|
|
+ let start = parse_date("start_date", opt_trim(start_raw).unwrap_or(today))?;
|
|
|
+ if let Some(ce) = contract_end {
|
|
|
+ let ced = parse_date("合同止期", ce)?;
|
|
|
+ if start > ced {
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "订阅开始日 {} 晚于合同止期 {ce}(§5.2 校验合同止期)",
|
|
|
+ date_text(start)
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 下一周期生效日=开始日 + N 个月(无对应日折月末);结束日=再减一天(含开始日共 N×30 天口径)。
|
|
|
+ let next_cycle = add_months_clamped(start, months);
|
|
|
+ let end = (next_cycle - chrono::Duration::days(1)).format("%Y-%m-%d").to_string();
|
|
|
+ let monthly = plan.monthly();
|
|
|
+ let annual = annual_by_term(
|
|
|
+ plan.annual_price_cents.trim().parse::<i64>().unwrap_or(0),
|
|
|
+ monthly,
|
|
|
+ &term,
|
|
|
);
|
|
|
+ if annual <= 0 || annual > MAX_AMOUNT_CENTS {
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "折算年订阅价格 {annual} 越界(须∈ 1..={MAX_AMOUNT_CENTS} 分):档位年价不可用"
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ Ok(Period { term, start: date_text(start), end, annual, monthly })
|
|
|
+}
|
|
|
+
|
|
|
+/// 出口集合的解析+归一化(条目优先,缺省取档位;空集合=`KLT-L216`)。
|
|
|
+fn derive_exits(item: Option<&ItemRow>, plan: &PlanRow) -> Result<NormalizedExits, BosError> {
|
|
|
+ let raw = match item {
|
|
|
+ Some(i) => exits_of(i.line_exits.as_ref(), "合同条目 line_exits")?,
|
|
|
+ None => Vec::new(),
|
|
|
+ };
|
|
|
+ let raw = if raw.is_empty() {
|
|
|
+ exits_of(plan.line_exits.as_ref(), "档位 line_exits")?
|
|
|
+ } else {
|
|
|
+ raw
|
|
|
+ };
|
|
|
+ if raw.is_empty() {
|
|
|
+ return Err(BosError::klt(
|
|
|
+ KltCode::L216,
|
|
|
+ format!("出口集合为空,⛔ 保存/提交(档位 {} 与所选条目均无线路出口)", plan.plan_id),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ normalize_line_exits(&raw)
|
|
|
+}
|
|
|
+
|
|
|
+/// I6 取数:该客户全部订阅(判据在 `check_i6_subscription` 内部,本处⛔ 预筛状态)。
|
|
|
+async fn i6_rows(state: &AppState, customer_id: &str, exclude: Option<&str>) -> Result<Vec<SubRow>, BosError> {
|
|
|
+ Ok(subs_of_customer(state, customer_id)
|
|
|
+ .await?
|
|
|
+ .into_iter()
|
|
|
+ .filter(|r| Some(r.subscription_id.as_str()) != exclude)
|
|
|
+ .collect())
|
|
|
+}
|
|
|
+
|
|
|
+fn i6_borrow(rows: &[SubRow]) -> Vec<ActiveSubscriptionRow<'_>> {
|
|
|
+ rows.iter()
|
|
|
+ .map(|r| ActiveSubscriptionRow {
|
|
|
+ subscription_id: r.subscription_id.as_str(),
|
|
|
+ customer_id: r.customer_id.as_str(),
|
|
|
+ plan_name: r.plan_name.as_deref().unwrap_or_default(),
|
|
|
+ use_category: r.use_category.as_deref().unwrap_or_default(),
|
|
|
+ line_exit_key: r.line_exit_key.as_deref().unwrap_or_default(),
|
|
|
+ sub_mode: r.sub_mode.as_deref().unwrap_or_default(),
|
|
|
+ status: r.status.as_str(),
|
|
|
+ end_date: r
|
|
|
+ .end_date
|
|
|
+ .as_deref()
|
|
|
+ .or(r.expire_date.as_deref())
|
|
|
+ .unwrap_or_default(),
|
|
|
+ })
|
|
|
+ .collect()
|
|
|
+}
|
|
|
+
|
|
|
+/// 额度对齐目标(§5.6 唯一求和实现=`in_use_quota_sum_batch`,⛔ 本口另实现一套计数)。
|
|
|
+///
|
|
|
+/// `extra_plan` = 本次要写入/要摘除的订阅所引档位:`Some` 计入(新订、升降配),
|
|
|
+/// 摘除一行时由调用方先从 `rows` 里剔掉再求和(§5.7 第 6 步回退对齐)。
|
|
|
+async fn quota_target(
|
|
|
+ state: &AppState,
|
|
|
+ customer_id: &str,
|
|
|
+ rows: &[SubRow],
|
|
|
+) -> Result<i64, BosError> {
|
|
|
+ let plan_ids: Vec<String> = rows.iter().filter_map(|r| r.plan_id.clone()).collect();
|
|
|
+ let plans = plan_rows(state, &plan_ids).await?;
|
|
|
+ let mut quota_of_plan: HashMap<String, i64> = HashMap::new();
|
|
|
+ for p in plans {
|
|
|
+ if let Some(q) = opt_trim(p.sub_account_quota.as_ref()).and_then(|s| s.trim().parse::<i64>().ok()) {
|
|
|
+ quota_of_plan.insert(p.plan_id.clone(), q);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ let pairs: Vec<(&str, &str)> = rows
|
|
|
+ .iter()
|
|
|
+ .filter(|r| IN_USE_STATUS.contains(&r.status.as_str()))
|
|
|
+ .filter_map(|r| {
|
|
|
+ r.plan_id
|
|
|
+ .as_deref()
|
|
|
+ .map(|pid| (r.customer_id.as_str(), pid))
|
|
|
+ })
|
|
|
+ .collect();
|
|
|
+ let sums = in_use_quota_sum_batch(&[customer_id], &pairs, "a_of_plan)?;
|
|
|
+ Ok(sums.get(customer_id).copied().unwrap_or(0))
|
|
|
+}
|
|
|
+
|
|
|
+async fn customer_quota(state: &AppState, customer_id: &str) -> Result<i64, BosError> {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let c = p.push(Value::String(customer_id.to_string()));
|
|
|
+ let sql = format!("SELECT c.quota_cents AS v FROM customer c WHERE c.customer_id = {c}::text");
|
|
|
+ Ok(state
|
|
|
+ .db
|
|
|
+ .query_one::<IdRow>(&sql, p.values())
|
|
|
+ .await?
|
|
|
+ .map(|r| r.v.trim().parse::<i64>().unwrap_or(0))
|
|
|
+ .unwrap_or(0))
|
|
|
+}
|
|
|
+
|
|
|
+/// 额度对齐语句(§5.7 第 3/6 步:与库里现值不符 ⇒ 以应占额度为准修正)。
|
|
|
+fn quota_stmt(customer_id: &str, target: i64) -> DmlStatement {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let c = p.push(Value::String(customer_id.to_string()));
|
|
|
+ let q = p.push(Value::from(target));
|
|
|
+ DmlStatement::new(
|
|
|
+ format!(
|
|
|
+ "UPDATE customer SET quota_cents = {q}::bigint, updated_at = NOW() WHERE customer_id = {c}::text"
|
|
|
+ ),
|
|
|
+ p.values().to_vec(),
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+/// 新订阅行 INSERT(六项快照+派生价格;`order_no`/`actual_opened_at` 由工单竣工回传,本轮留空)。
|
|
|
+fn insert_stmt(v: &NewValues) -> DmlStatement {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let ph = |p: &mut Params, val: Value, cast: &str| -> String {
|
|
|
+ let s = p.push(val);
|
|
|
+ if cast.is_empty() {
|
|
|
+ s
|
|
|
+ } else {
|
|
|
+ format!("{s}::{cast}")
|
|
|
+ }
|
|
|
+ };
|
|
|
+ let mut cols: Vec<&str> = vec![
|
|
|
+ "customer_id",
|
|
|
+ "status",
|
|
|
+ "plan_id",
|
|
|
+ "plan_name",
|
|
|
+ "plan_kind",
|
|
|
+ "plan_owner_customer_id",
|
|
|
+ "use_category",
|
|
|
+ "sub_mode",
|
|
|
+ "line_exits",
|
|
|
+ "line_exit_key",
|
|
|
+ "term",
|
|
|
+ "start_date",
|
|
|
+ "end_date",
|
|
|
+ "annual_price_cents",
|
|
|
+ "monthly_settle_cents",
|
|
|
+ "quota_slots",
|
|
|
+ ];
|
|
|
+ let mut vals: Vec<String> = vec![
|
|
|
+ ph(&mut p, Value::String(v.customer_id.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.status.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.plan_id.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.plan_name.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.plan_kind.clone()), "text"),
|
|
|
+ ph(
|
|
|
+ &mut p,
|
|
|
+ v.plan_owner_customer_id.clone().map(Value::String).unwrap_or(Value::Null),
|
|
|
+ "text",
|
|
|
+ ),
|
|
|
+ ph(&mut p, Value::String(v.use_category.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.sub_mode.clone()), "text"),
|
|
|
+ ph(&mut p, v.line_exits.clone(), "jsonb"),
|
|
|
+ ph(&mut p, Value::String(v.line_exit_key.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.term.clone()), "text"),
|
|
|
+ ph(&mut p, Value::String(v.start_date.clone()), "date"),
|
|
|
+ ph(&mut p, Value::String(v.end_date.clone()), "date"),
|
|
|
+ ph(&mut p, Value::from(v.annual_price_cents), "bigint"),
|
|
|
+ ph(&mut p, Value::from(v.monthly_settle_cents), "bigint"),
|
|
|
+ ph(&mut p, Value::from(v.quota_slots), "int"),
|
|
|
+ ];
|
|
|
+ if let Some(cid) = v.contract_id.as_ref() {
|
|
|
+ cols.push("contract_id");
|
|
|
+ vals.push(ph(&mut p, Value::String(cid.clone()), "text"));
|
|
|
+ }
|
|
|
+ if let Some(iid) = v.contract_item_id.as_ref() {
|
|
|
+ cols.push("contract_item_id");
|
|
|
+ vals.push(ph(&mut p, Value::String(iid.clone()), "text"));
|
|
|
+ }
|
|
|
+ if let Some(t) = v.trial_months {
|
|
|
+ cols.push("trial_months");
|
|
|
+ vals.push(ph(&mut p, Value::from(t), "int"));
|
|
|
+ }
|
|
|
+ if let Some(d) = v.discount_monthly_cents {
|
|
|
+ cols.push("discount_monthly_cents");
|
|
|
+ vals.push(ph(&mut p, Value::from(d), "bigint"));
|
|
|
+ }
|
|
|
+ if let Some(rid) = v.replaces_subscription_id.as_ref() {
|
|
|
+ cols.push("replaces_subscription_id");
|
|
|
+ vals.push(ph(&mut p, Value::String(rid.clone()), "text"));
|
|
|
+ }
|
|
|
+ DmlStatement::new(
|
|
|
+ format!(
|
|
|
+ "INSERT INTO subscription ({}) VALUES ({}); SELECT 1",
|
|
|
+ cols.join(", "),
|
|
|
+ vals.join(", ")
|
|
|
+ ),
|
|
|
+ p.values().to_vec(),
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+/// 首次引用打点(§5.2 第 4 步:同事务打点=引用冻结的生效点,⛔ 提交后异步补写)。
|
|
|
+fn first_referred_stmt(plan_id: &str) -> DmlStatement {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let a = p.push(Value::String(plan_id.to_string()));
|
|
|
+ DmlStatement::new(
|
|
|
+ format!(
|
|
|
+ "UPDATE catalog_plan SET first_referred_at = NOW() WHERE plan_id = {a}::text \
|
|
|
+ AND first_referred_at IS NULL"
|
|
|
+ ),
|
|
|
+ p.values().to_vec(),
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+/// 待写入的新订阅行(已折算完全部派生值)。
|
|
|
+struct NewValues {
|
|
|
+ customer_id: String,
|
|
|
+ status: String,
|
|
|
+ plan_id: String,
|
|
|
+ plan_name: String,
|
|
|
+ plan_kind: String,
|
|
|
+ plan_owner_customer_id: Option<String>,
|
|
|
+ use_category: String,
|
|
|
+ sub_mode: String,
|
|
|
+ line_exits: Value,
|
|
|
+ line_exit_key: String,
|
|
|
+ term: String,
|
|
|
+ start_date: String,
|
|
|
+ end_date: String,
|
|
|
+ annual_price_cents: i64,
|
|
|
+ monthly_settle_cents: i64,
|
|
|
+ quota_slots: i64,
|
|
|
+ contract_id: Option<String>,
|
|
|
+ contract_item_id: Option<String>,
|
|
|
+ trial_months: Option<i64>,
|
|
|
+ discount_monthly_cents: Option<i64>,
|
|
|
+ replaces_subscription_id: Option<String>,
|
|
|
+}
|
|
|
+
|
|
|
+/// 发号(`SUB-000123`,与 customer/import_batch 的发号器同一张表)。
|
|
|
+async fn new_subscription_id(state: &AppState) -> Result<String, BosError> {
|
|
|
+ let year = chrono::Local::now()
|
|
|
+ .format("%Y")
|
|
|
+ .to_string()
|
|
|
+ .parse::<i32>()
|
|
|
+ .map_err(|e| BosError::internal(format!("取当年年份失败:{e}")))?;
|
|
|
+ let n = next_seq(state.db.as_ref(), "subscription", "subscription", year).await?;
|
|
|
+ Ok(format!("SUB-{n:06}"))
|
|
|
+}
|
|
|
+
|
|
|
+/// 六步短批的事后自检(UDS ⛔ 批内条件中止 ⇒ 只能事后核影响行数并如实点名)。
|
|
|
+fn assert_batch(results: &[bos_platform::clients::uds::DmlStatementResult], want: &[(&str, u64)]) -> Result<(), BosError> {
|
|
|
+ let hit = |i: usize| results.get(i).and_then(|r| r.affected_rows).unwrap_or(0);
|
|
|
+ let mut bad: Vec<String> = Vec::new();
|
|
|
+ for (i, (label, n)) in want.iter().enumerate() {
|
|
|
+ if hit(i) != *n {
|
|
|
+ bad.push(format!("{label}={}(期望 {n})", hit(i)));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if bad.is_empty() {
|
|
|
+ return Ok(());
|
|
|
+ }
|
|
|
+ Err(BosError::internal(format!(
|
|
|
+ "写侧短批影响行数异常:{};整批已原子提交,须人工核对",
|
|
|
+ bad.join(";")
|
|
|
+ )))
|
|
|
+}
|
|
|
+
|
|
|
+/// 写入后的统一回读出参。
|
|
|
+async fn row_out(
|
|
|
+ state: &AppState,
|
|
|
+ sub_id: &str,
|
|
|
+ op: &str,
|
|
|
+ notes: Vec<String>,
|
|
|
+ extra: Value,
|
|
|
+) -> Result<Value, BosError> {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let s = p.push(Value::String(sub_id.to_string()));
|
|
|
+ let sql = format!("{SELECT_COLS} FROM subscription s WHERE s.subscription_id = {s}::text");
|
|
|
+ let r = state
|
|
|
+ .db
|
|
|
+ .query_one::<SubRow>(&sql, p.values())
|
|
|
+ .await?
|
|
|
+ .ok_or_else(|| {
|
|
|
+ BosError::internal(format!("写入后回读⛔ 在册:订阅 {sub_id}(短批已提交,须人工核对)"))
|
|
|
+ })?;
|
|
|
+ let names = pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &[r.customer_id.clone()]).await?;
|
|
|
+ let t = today();
|
|
|
+ let mut v = to_json(&r, names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str), &t);
|
|
|
v["op"] = json!(op);
|
|
|
- v["pricing_note"] = json!(PRICING_NOTE);
|
|
|
- v["not_persisted"] = json!(not_persisted);
|
|
|
- v["spec_notes"] = json!(spec_notes);
|
|
|
+ v["notes"] = json!(notes);
|
|
|
v["columns_pending"] = json!(COLUMNS_PENDING);
|
|
|
- json_ok(v)
|
|
|
+ if let Some(obj) = extra.as_object() {
|
|
|
+ for (k, val) in obj {
|
|
|
+ v[k.clone()] = val.clone();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Ok(v)
|
|
|
+}
|
|
|
+
|
|
|
+async fn row_out_resp(state: &AppState, sub_id: &str, op: &str, notes: Vec<String>, extra: Value) -> Response {
|
|
|
+ match row_out(state, sub_id, op, notes, extra).await {
|
|
|
+ Ok(v) => json_ok(v),
|
|
|
+ Err(e) => json_err(e),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// ───────────────────────── 写侧:新订 ─────────────────────────
|
|
|
+
|
|
|
+/// `POST /subscription/create@v1`(§5.2 五步前置校验 + 六步事务)。
|
|
|
+pub async fn create(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionCreateReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ if let Err(e) = reject_read_only(&body.rest, &CREATE_READ_ONLY) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ // ① 客户(必填)
|
|
|
+ let cid = match req_field("customer_id", &body.customer_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // ② 可见性 ⇒ KLT-M221
|
|
|
+ let customer_name = match require_customer(&state, &auth, &cid).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // ③ 合同与条目
|
|
|
+ let pid = match req_field("plan_id", &body.plan_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let contract_id = match req_field("contract_id", &body.contract_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let contract = match contract_row(&state, &contract_id).await {
|
|
|
+ Ok(Some(c)) => c,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M222,
|
|
|
+ format!("载荷里的合同 {contract_id} 不在册,本客户没有可承接的「未开通」合同"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if contract.customer_id != cid {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M221,
|
|
|
+ format!(
|
|
|
+ "载荷里的合同 {contract_id} 归属客户 {},与本订阅客户 {cid} 不同(I12b)",
|
|
|
+ contract.customer_id
|
|
|
+ ),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ if let Err(e) = check_i12b_same_customer(Some(&contract.customer_id), &cid) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ match opened_map_for(&state, std::slice::from_ref(&contract)).await {
|
|
|
+ Ok(m) => match m.get(&contract_id) {
|
|
|
+ Some(Opened::Opened) => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M223,
|
|
|
+ format!("合同 {contract_id} 已开通,⛔ 再新增订阅(补录走合同侧「变更重开」)"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ Some(Opened::NotOpened) => {}
|
|
|
+ None => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::S406,
|
|
|
+ format!("合同 {contract_id} 的开通态不可判定(⛔ 当成未开通放行)"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ },
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ }
|
|
|
+ let item_id = opt_trim(body.contract_item_id.as_ref()).map(str::to_string);
|
|
|
+ let items = match items_of_contracts(&state, &[contract_id.clone()]).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let item = match item_id.as_ref() {
|
|
|
+ Some(iid) => match items.iter().find(|i| &i.item_id == iid) {
|
|
|
+ Some(i) => Some(i),
|
|
|
+ None => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M228,
|
|
|
+ format!("条目 {iid} 不是合同 {contract_id} 的服务构成条目(档位不可选)"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ },
|
|
|
+ // 合同内一条匹配条目都没有时合同仍可选,出口由操作人在合同内任选 ⇒ 本轮允许空(§5.2 末段)。
|
|
|
+ None => None,
|
|
|
+ };
|
|
|
+ if let Some(i) = item {
|
|
|
+ if let Some(ip) = opt_trim(i.plan_id.as_ref()).or_else(|| opt_trim(i.derived_plan_id.as_ref())) {
|
|
|
+ if ip != pid {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M228,
|
|
|
+ format!("条目 {} 关联档位 {ip},与所选档位 {pid} 不匹配", i.item_id),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ let plan = match plan_row(&state, &pid).await {
|
|
|
+ Ok(Some(p)) => p,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M228,
|
|
|
+ format!("档位 {pid} 不在册,档位不可选"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let t = today();
|
|
|
+ let pr = plan.to_ref();
|
|
|
+ let (selectable, unavail) = plan_selectability(&pr, &cid);
|
|
|
+ if !selectable {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M228,
|
|
|
+ format!(
|
|
|
+ "档位不可选:{}",
|
|
|
+ unavail.unwrap_or_else(|| "未指明原因".to_string())
|
|
|
+ ),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ if let Err(e) = check_plan_available(Some(&pr), &cid) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ if let Err(e) = check_i12b_same_customer(pr.owner_customer_id.as_deref(), &cid) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ // ④ 价格与周期(全部服务端派生)
|
|
|
+ let period = match derive_period(
|
|
|
+ &plan,
|
|
|
+ body.term.as_ref(),
|
|
|
+ body.start_date.as_ref(),
|
|
|
+ opt_trim(contract.end_date.as_ref()),
|
|
|
+ &t,
|
|
|
+ ) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let category = match category_of(body.use_category.as_ref(), &plan) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if let Err(e) = check_i13_trial_months(body.trial_months, body.discount_monthly_cents) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let exits = match derive_exits(item, &plan) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // ⑤ I6 ⇒ KLT-M224(带那份订阅的定位)
|
|
|
+ let actives = match i6_rows(&state, &cid, None).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if let Err(e) = check_i6_subscription(&cid, category, &exits.line_exit_key, &i6_borrow(&actives)) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let id = match new_subscription_id(&state).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let nv = NewValues {
|
|
|
+ customer_id: cid.clone(),
|
|
|
+ status: subscription_status_of(&period.start, &period.end, &t).as_str().to_string(),
|
|
|
+ plan_id: plan.plan_id.clone(),
|
|
|
+ plan_name: plan.plan_name.clone(),
|
|
|
+ plan_kind: plan.plan_kind.clone(),
|
|
|
+ plan_owner_customer_id: opt_trim(plan.customer_id.as_ref()).map(str::to_string),
|
|
|
+ use_category: category.as_str().to_string(),
|
|
|
+ sub_mode: sub_mode_of(category).as_str().to_string(),
|
|
|
+ line_exits: Value::Array(exits.line_exits.iter().cloned().map(Value::String).collect()),
|
|
|
+ line_exit_key: exits.line_exit_key.clone(),
|
|
|
+ term: period.term.clone(),
|
|
|
+ start_date: period.start.clone(),
|
|
|
+ end_date: period.end.clone(),
|
|
|
+ annual_price_cents: period.annual,
|
|
|
+ monthly_settle_cents: period.monthly,
|
|
|
+ quota_slots: pr.sub_account_quota,
|
|
|
+ contract_id: Some(contract_id.clone()),
|
|
|
+ contract_item_id: item_id.clone(),
|
|
|
+ trial_months: body.trial_months,
|
|
|
+ discount_monthly_cents: body.discount_monthly_cents,
|
|
|
+ replaces_subscription_id: None,
|
|
|
+ };
|
|
|
+ // 额度对齐目标=在册在用行 + 本行
|
|
|
+ let mut for_quota = actives.clone();
|
|
|
+ for_quota.push(SubRowPlaceholder::for_new(&id, &nv));
|
|
|
+ let target = match quota_target(&state, &cid, &for_quota).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let before = match customer_quota(&state, &cid).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let mut stmts: Vec<DmlStatement> = Vec::new();
|
|
|
+ stmts.push(insert_stmt(&nv));
|
|
|
+ stmts.push(first_referred_stmt(&pid));
|
|
|
+ if before != target {
|
|
|
+ stmts.push(quota_stmt(&cid, target));
|
|
|
+ }
|
|
|
+ let results = match state.db.dml_batch(&stmts).await {
|
|
|
+ Ok(r) => r,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let mut want: Vec<(&str, u64)> = vec![("新订阅 INSERT", 1)];
|
|
|
+ if stmts.len() > 1 {
|
|
|
+ want.push(("catalog_plan.first_referred_at 打点", 1));
|
|
|
+ }
|
|
|
+ if stmts.len() > 2 {
|
|
|
+ want.push(("客户额度对齐", 1));
|
|
|
+ }
|
|
|
+ if let Err(e) = assert_batch(&results, &want) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let mut notes: Vec<String> = vec![
|
|
|
+ TICKET_UNCONFIGURED_NOTE.to_string(),
|
|
|
+ "order_no/actual_opened_at 由开户工单竣工回传回填,本轮新建留空(§5.2)。".to_string(),
|
|
|
+ format!(
|
|
|
+ "年订阅价格按订阅时长 {} 折算为 {} 分,月结算标准金额={} 分(monthly_settle_of 唯一折算点)。",
|
|
|
+ period.term, period.annual, period.monthly
|
|
|
+ ),
|
|
|
+ ];
|
|
|
+ if item_id.is_none() {
|
|
|
+ notes.push(
|
|
|
+ "本订阅未关联合同条目(合同内无匹配条目时出口按档位自身出口落库),合同开通态一栏显示「—」。"
|
|
|
+ .to_string(),
|
|
|
+ );
|
|
|
+ }
|
|
|
+ row_out_resp(
|
|
|
+ &state,
|
|
|
+ &id,
|
|
|
+ "created",
|
|
|
+ notes,
|
|
|
+ json!({
|
|
|
+ "customer_name": customer_name,
|
|
|
+ "quota_align": { "before": before, "target": target, "written": before != target },
|
|
|
+ "derived": {
|
|
|
+ "term": period.term,
|
|
|
+ "start_date": period.start,
|
|
|
+ "end_date": period.end,
|
|
|
+ "annual_price_cents": period.annual,
|
|
|
+ "monthly_settle_cents": period.monthly,
|
|
|
+ "line_exit_key": exits.line_exit_key,
|
|
|
+ "sub_mode": sub_mode_of(category).as_str(),
|
|
|
+ },
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ .await
|
|
|
+}
|
|
|
+
|
|
|
+/// 客户在册且在可见范围内 ⇒ 回客户名;越权或不在册=`KLT-M221`。
|
|
|
+async fn require_customer(
|
|
|
+ state: &AppState,
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
+ customer_id: &str,
|
|
|
+) -> Result<String, BosError> {
|
|
|
+ customer_visible(state, auth, customer_id)
|
|
|
+ .await?
|
|
|
+ .ok_or_else(|| {
|
|
|
+ BosError::klt(
|
|
|
+ KltCode::M221,
|
|
|
+ format!("客户不存在或超出当前账号可见范围:{customer_id}"),
|
|
|
+ )
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+// ───────────────────────── 写侧:升降配 ─────────────────────────
|
|
|
+
|
|
|
+/// 原订阅已被换过的次数(`replaces_subscription_id` 唯一 ⇒ ≥1 即⛔ 再换)。
|
|
|
+async fn replacement_count(state: &AppState, origin_id: &str) -> Result<i64, BosError> {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let a = p.push(Value::String(origin_id.to_string()));
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT COUNT(1) AS c FROM subscription r WHERE r.replaces_subscription_id = {a}::text"
|
|
|
+ );
|
|
|
+ Ok(state
|
|
|
+ .db
|
|
|
+ .query_one::<CountRow>(&sql, p.values())
|
|
|
+ .await?
|
|
|
+ .map(|r| r.c.trim().parse::<i64>().unwrap_or(0))
|
|
|
+ .unwrap_or(0))
|
|
|
+}
|
|
|
+
|
|
|
+/// `POST /subscription/change@v1`(§5.3)。
|
|
|
+///
|
|
|
+/// 客户/合同/条目/用途分类全部沿用或跟随新档位(载荷出现即 `11103`);
|
|
|
+/// ⛔ 出口一致性校验(分类与出口均随档位变,拦截等于禁止换分类);I6 照常(`KLT-M224`)。
|
|
|
+pub async fn change(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionChangeReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ if let Err(e) = reject_read_only(&body.rest, &CHANGE_READ_ONLY) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let rid = match req_field("replaces_subscription_id", &body.replaces_subscription_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let orig = match scoped_sub(&state, &auth, &rid).await {
|
|
|
+ Ok(Some(c)) => c,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
+ "原订阅不存在或超出当前账号可见范围:{rid}"
|
|
|
+ )))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let t = today();
|
|
|
+ let (key, label, _) = status_display(&orig, &t);
|
|
|
+ if key != "pending" && key != "active" {
|
|
|
+ return json_err(BosError::bad_params(format!(
|
|
|
+ "原订阅 {rid} 状态={label}({key}),⛔ 升降配(§5.3)"
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ match replacement_count(&state, &rid).await {
|
|
|
+ Ok(0) => {}
|
|
|
+ Ok(k) => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M226,
|
|
|
+ format!("原订阅 {rid} 已被升降配换过 {k} 次:replaces_subscription_id 至多被指向一次"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ }
|
|
|
+ let cid = orig.customer_id.clone();
|
|
|
+ let contract_id = match opt_trim(orig.contract_id.as_ref()) {
|
|
|
+ Some(c) => c.to_string(),
|
|
|
+ None => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M221,
|
|
|
+ format!("原订阅 {rid} 未关联合同,⛔ 升降配(§5.3「合同编号=沿用原订阅合同号」)"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ };
|
|
|
+ let contract = match contract_row(&state, &contract_id).await {
|
|
|
+ Ok(Some(c)) => c,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M222,
|
|
|
+ format!("原订阅的合同 {contract_id} 不在册,升降配⛔ 承接"),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if let Err(e) = check_i12b_same_customer(Some(&contract.customer_id), &cid) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let pid = match req_field("plan_id", &body.plan_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let plan = match plan_row(&state, &pid).await {
|
|
|
+ Ok(Some(p)) => p,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::klt(KltCode::M228, format!("新档位 {pid} 不在册,档位不可选")))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let pr = plan.to_ref();
|
|
|
+ if let (_, Some(reason)) = plan_selectability(&pr, &cid) {
|
|
|
+ return json_err(BosError::klt(KltCode::M228, format!("档位不可选:{reason}")));
|
|
|
+ }
|
|
|
+ if let Err(e) = check_plan_available(Some(&pr), &cid) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ if let Err(e) = check_i12b_same_customer(pr.owner_customer_id.as_deref(), &cid) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ // 条目=跟随新档位所属条目(§5.3)。
|
|
|
+ let items = match items_of_contracts(&state, &[contract_id.clone()]).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let item = items.iter().find(|i| {
|
|
|
+ opt_trim(i.plan_id.as_ref()) == Some(pid.as_str())
|
|
|
+ || opt_trim(i.derived_plan_id.as_ref()) == Some(pid.as_str())
|
|
|
+ });
|
|
|
+ // 升降配下派生档必须已有用途分类(载荷⛔ 带 use_category)。
|
|
|
+ let category = match opt_trim(plan.use_category.as_ref()) {
|
|
|
+ Some(v) => match UseCategory::parse(v) {
|
|
|
+ Ok(c) => c,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ },
|
|
|
+ None => {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M228,
|
|
|
+ format!(
|
|
|
+ "档位不可选:派生自定义档 {pid} 未预置用途分类,而升降配⛔ 录入 use_category(请先在第 1 步把分类带入档位)"
|
|
|
+ ),
|
|
|
+ ))
|
|
|
+ }
|
|
|
+ };
|
|
|
+ if let Err(e) = check_i13_trial_months(body.trial_months, body.discount_monthly_cents) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let exits = match derive_exits(item, &plan) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let period = match derive_period(
|
|
|
+ &plan,
|
|
|
+ body.term.as_ref(),
|
|
|
+ body.start_date.as_ref(),
|
|
|
+ opt_trim(contract.end_date.as_ref()),
|
|
|
+ &t,
|
|
|
+ ) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ // I6(升降配照常;⛔ 出口一致性校验)
|
|
|
+ let actives = match i6_rows(&state, &cid, None).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if let Err(e) = check_i6_subscription(&cid, category, &exits.line_exit_key, &i6_borrow(&actives)) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let id = match new_subscription_id(&state).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let nv = NewValues {
|
|
|
+ customer_id: cid.clone(),
|
|
|
+ status: subscription_status_of(&period.start, &period.end, &t).as_str().to_string(),
|
|
|
+ plan_id: plan.plan_id.clone(),
|
|
|
+ plan_name: plan.plan_name.clone(),
|
|
|
+ plan_kind: plan.plan_kind.clone(),
|
|
|
+ plan_owner_customer_id: opt_trim(plan.customer_id.as_ref()).map(str::to_string),
|
|
|
+ use_category: category.as_str().to_string(),
|
|
|
+ sub_mode: sub_mode_of(category).as_str().to_string(),
|
|
|
+ line_exits: Value::Array(exits.line_exits.iter().cloned().map(Value::String).collect()),
|
|
|
+ line_exit_key: exits.line_exit_key.clone(),
|
|
|
+ term: period.term.clone(),
|
|
|
+ start_date: period.start.clone(),
|
|
|
+ end_date: period.end.clone(),
|
|
|
+ annual_price_cents: period.annual,
|
|
|
+ monthly_settle_cents: period.monthly,
|
|
|
+ quota_slots: pr.sub_account_quota,
|
|
|
+ contract_id: Some(contract_id.clone()),
|
|
|
+ contract_item_id: item.map(|i| i.item_id.clone()),
|
|
|
+ trial_months: body.trial_months,
|
|
|
+ discount_monthly_cents: body.discount_monthly_cents,
|
|
|
+ replaces_subscription_id: Some(rid.clone()),
|
|
|
+ };
|
|
|
+ // 截原(§5.3):结束日=新生效日前一天、状态到期。前置条件写进谓词(无行锁能力)。
|
|
|
+ let prev_end = match NaiveDate::parse_from_str(&period.start, "%Y-%m-%d") {
|
|
|
+ Ok(d) => date_text(d - chrono::Duration::days(1)),
|
|
|
+ Err(e) => return json_err(BosError::bad_params(format!("开始日不可解析:{e}"))),
|
|
|
+ };
|
|
|
+ let mut up = Params::default();
|
|
|
+ let mut set: Vec<String> = Vec::new();
|
|
|
+ set.push(format!("end_date = {}::date", up.push(Value::String(prev_end.clone()))));
|
|
|
+ set.push(format!("status = {}::text", up.push(Value::String("expired".to_string()))));
|
|
|
+ set.push("row_version = row_version + 1".to_string());
|
|
|
+ let mut preds: Vec<String> = Vec::new();
|
|
|
+ preds.push(format!("subscription_id = {}::text", up.push(Value::String(rid.clone()))));
|
|
|
+ let in_use: Vec<String> = IN_USE_STATUS.iter().map(|s| up.push(Value::String(s.to_string()))).collect();
|
|
|
+ preds.push(format!(
|
|
|
+ "status IN ({})",
|
|
|
+ in_use.iter().map(|s| format!("{s}::text")).collect::<Vec<_>>().join(",")
|
|
|
+ ));
|
|
|
+ if let Some(v) = body.row_version {
|
|
|
+ preds.push(format!("row_version = {}::int", up.push(Value::from(v))));
|
|
|
+ }
|
|
|
+ let cut = DmlStatement::new(
|
|
|
+ format!("UPDATE subscription SET {} {}", set.join(", "), up.where_clause(&preds)),
|
|
|
+ up.values().to_vec(),
|
|
|
+ );
|
|
|
+ let mut for_quota = actives.clone();
|
|
|
+ if let Some(pos) = for_quota.iter().position(|r| r.subscription_id == rid) {
|
|
|
+ for_quota.remove(pos);
|
|
|
+ }
|
|
|
+ for_quota.push(SubRowPlaceholder::for_new(&id, &nv));
|
|
|
+ let target = match quota_target(&state, &cid, &for_quota).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let before = match customer_quota(&state, &cid).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let mut stmts: Vec<DmlStatement> = vec![cut, insert_stmt(&nv), first_referred_stmt(&pid)];
|
|
|
+ if before != target {
|
|
|
+ stmts.push(quota_stmt(&cid, target));
|
|
|
+ }
|
|
|
+ let results = match state.db.dml_batch(&stmts).await {
|
|
|
+ Ok(r) => r,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let mut want: Vec<(&str, u64)> = vec![
|
|
|
+ ("原订阅截原", 1),
|
|
|
+ ("新订阅 INSERT", 1),
|
|
|
+ ("catalog_plan.first_referred_at 打点", 1),
|
|
|
+ ];
|
|
|
+ if stmts.len() > 3 {
|
|
|
+ want.push(("客户额度对齐", 1));
|
|
|
+ }
|
|
|
+ if let Err(e) = assert_batch(&results, &want) {
|
|
|
+ // ⛔ 把任何行数异常都冒充成「乐观锁冲突」:只有**截原**落空才是 §5.3 的承接前置不符
|
|
|
+ let cut_rows = results.first().and_then(|r| r.affected_rows).unwrap_or(0);
|
|
|
+ if cut_rows == 0 {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::M225,
|
|
|
+ format!("承接的原订阅 {rid} 状态已变更(⛔ 截原),请重新加载该行后再试"),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let notes: Vec<String> = vec![
|
|
|
+ TICKET_UNCONFIGURED_NOTE.to_string(),
|
|
|
+ "⛔ 出口一致性校验(§5.3:分类与出口均随档位变,拦截等于禁止换分类),本轮未做该校验。"
|
|
|
+ .to_string(),
|
|
|
+ format!(
|
|
|
+ "年订阅价格按订阅时长 {} 折算为 {} 分,月结算标准金额={} 分;原订阅结束日截到 {prev_end}。",
|
|
|
+ period.term, period.annual, period.monthly
|
|
|
+ ),
|
|
|
+ ];
|
|
|
+ row_out_resp(
|
|
|
+ &state,
|
|
|
+ &id,
|
|
|
+ "changed",
|
|
|
+ notes,
|
|
|
+ json!({
|
|
|
+ "replaces_subscription_id": rid,
|
|
|
+ "quota_align": { "before": before, "target": target, "written": before != target },
|
|
|
+ "derived": {
|
|
|
+ "term": period.term,
|
|
|
+ "start_date": period.start,
|
|
|
+ "end_date": period.end,
|
|
|
+ "annual_price_cents": period.annual,
|
|
|
+ "monthly_settle_cents": period.monthly,
|
|
|
+ "line_exit_key": exits.line_exit_key,
|
|
|
+ "sub_mode": sub_mode_of(category).as_str(),
|
|
|
+ "contract_id": contract_id,
|
|
|
+ "contract_item_id": nv.contract_item_id,
|
|
|
+ },
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ .await
|
|
|
+}
|
|
|
+
|
|
|
+/// 升降配额度对齐用的行占位(把 [`NewValues`] 折算成一行「将来在册」的订阅行)。
|
|
|
+struct SubRowPlaceholder;
|
|
|
+
|
|
|
+impl SubRowPlaceholder {
|
|
|
+ fn for_new(id: &str, v: &NewValues) -> SubRow {
|
|
|
+ SubRow {
|
|
|
+ subscription_id: id.to_string(),
|
|
|
+ customer_id: v.customer_id.clone(),
|
|
|
+ contract_id: v.contract_id.clone(),
|
|
|
+ contract_item_id: v.contract_item_id.clone(),
|
|
|
+ plan_id: Some(v.plan_id.clone()),
|
|
|
+ plan_name: Some(v.plan_name.clone()),
|
|
|
+ plan_kind: Some(v.plan_kind.clone()),
|
|
|
+ plan_owner_customer_id: v.plan_owner_customer_id.clone(),
|
|
|
+ status: v.status.clone(),
|
|
|
+ use_category: Some(v.use_category.clone()),
|
|
|
+ sub_mode: Some(v.sub_mode.clone()),
|
|
|
+ line_exits: None,
|
|
|
+ line_exit_key: Some(v.line_exit_key.clone()),
|
|
|
+ start_date: Some(v.start_date.clone()),
|
|
|
+ end_date: Some(v.end_date.clone()),
|
|
|
+ term: Some(v.term.clone()),
|
|
|
+ trial_months: v.trial_months.map(|x| x.to_string()),
|
|
|
+ discount_monthly_cents: v.discount_monthly_cents.map(|x| x.to_string()),
|
|
|
+ annual_price_cents: Some(v.annual_price_cents.to_string()),
|
|
|
+ monthly_settle_cents: Some(v.monthly_settle_cents.to_string()),
|
|
|
+ quota_slots: v.quota_slots.to_string(),
|
|
|
+ replaces_subscription_id: v.replaces_subscription_id.clone(),
|
|
|
+ order_no: None,
|
|
|
+ actual_opened_at: None,
|
|
|
+ effective_date: None,
|
|
|
+ expire_date: None,
|
|
|
+ created_at: String::new(),
|
|
|
+ row_version: String::new(),
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// ═══════════════════════════ §5.7 修改(白名单两列) ═══════════════════════════
|
|
|
+
|
|
|
+/// 修改载荷:白名单只有 `trial_months` + `discount_monthly_cents`(§5.7)。
|
|
|
+///
|
|
|
+/// 换套餐/换合同 ⇒ `KLT-M229`(改订走升降配承接或先停用再新开);其余键 ⇒ `11103`
|
|
|
+/// 逐一点名(⛔ 静默忽略=把「改了结束日」当成一次成功的修改)。
|
|
|
+fn reject_update_payload(rest: &Map<String, Value>) -> Result<(), BosError> {
|
|
|
+ let m229: Vec<&str> = UPDATE_M229_KEYS
|
|
|
+ .iter()
|
|
|
+ .copied()
|
|
|
+ .filter(|k| rest.contains_key(*k))
|
|
|
+ .collect();
|
|
|
+ if !m229.is_empty() {
|
|
|
+ return Err(BosError::klt(
|
|
|
+ KltCode::M229,
|
|
|
+ format!(
|
|
|
+ "修改⛔ 换套餐/换合同({}):改订一律走「升降配承接」或「先服务停用再新开」(§5.7)",
|
|
|
+ m229.join("、")
|
|
|
+ ),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let mut keys: Vec<&str> = rest
|
|
|
+ .keys()
|
|
|
+ .map(String::as_str)
|
|
|
+ .filter(|k| !UPDATE_WHITELIST.contains(k))
|
|
|
+ .collect();
|
|
|
+ if keys.is_empty() {
|
|
|
+ return Ok(());
|
|
|
+ }
|
|
|
+ keys.sort_unstable();
|
|
|
+ Err(BosError::bad_params(format!(
|
|
|
+ "修改白名单只有 {},以下键⛔ 受理:{}",
|
|
|
+ UPDATE_WHITELIST.join("/"),
|
|
|
+ keys.join("、")
|
|
|
+ )))
|
|
|
+}
|
|
|
+
|
|
|
+/// `POST /subscription/update@v1`(§5.7)。
|
|
|
+pub async fn update(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionUpdateReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ if let Err(e) = reject_update_payload(&body.rest) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let sid = match req_field("subscription_id", &body.subscription_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let r = match scoped_sub(&state, &auth, &sid).await {
|
|
|
+ Ok(Some(v)) => v,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
+ "订阅不存在或超出当前账号可见范围:{sid}"
|
|
|
+ )))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let t = today();
|
|
|
+ let (key, label, _) = status_display(&r, &t);
|
|
|
+ if key != "pending" && key != "active" {
|
|
|
+ return json_err(BosError::bad_params(format!(
|
|
|
+ "订阅 {sid} 状态={label},⛔ 修改(§5.7:到期/已替换/已退订只读)"
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ // I13 用**改后**的试用/优惠期组合判(本口只改这两列=唯一能碰 I13 的写入口)
|
|
|
+ let cur_trial = as_opt_num(r.trial_months.as_deref()).as_i64();
|
|
|
+ let cur_disc = as_opt_num(r.discount_monthly_cents.as_deref()).as_i64();
|
|
|
+ let trial = body.trial_months.or(cur_trial);
|
|
|
+ let disc = body.discount_monthly_cents.or(cur_disc);
|
|
|
+ if let Err(e) = check_i13_trial_months(trial, disc) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let mut p = Params::default();
|
|
|
+ let set: Vec<String> = vec![
|
|
|
+ format!(
|
|
|
+ "trial_months = {}::int",
|
|
|
+ p.push(trial.map(Value::from).unwrap_or(Value::Null))
|
|
|
+ ),
|
|
|
+ format!(
|
|
|
+ "discount_monthly_cents = {}::bigint",
|
|
|
+ p.push(disc.map(Value::from).unwrap_or(Value::Null))
|
|
|
+ ),
|
|
|
+ "row_version = row_version + 1".to_string(),
|
|
|
+ "updated_at = NOW()".to_string(),
|
|
|
+ ];
|
|
|
+ // 乐观锁:`row_version` 进谓词(UDS ⛔ 行锁能力,条件更新是唯一防线)
|
|
|
+ let preds: Vec<String> = vec![
|
|
|
+ format!("subscription_id = {}::text", p.push(Value::String(sid.clone()))),
|
|
|
+ format!("row_version = {}::int", p.push(Value::from(body.row_version))),
|
|
|
+ format!("status = {}::text", p.push(Value::String(r.status.clone()))),
|
|
|
+ ];
|
|
|
+ let sql = format!(
|
|
|
+ "UPDATE subscription SET {} {}",
|
|
|
+ set.join(", "),
|
|
|
+ p.where_clause(&preds)
|
|
|
+ );
|
|
|
+ let affected = match state.db.dml(&sql, p.values()).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if affected == 0 {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::S407,
|
|
|
+ format!("订阅 {sid} 已被他人改动(row_version 不符),请重新加载后重试(§5.7)"),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let notes: Vec<String> = vec![
|
|
|
+ format!(
|
|
|
+ "本轮修改列={};订阅时长/结束日/两个金额⛔ 可改(§5.7)。",
|
|
|
+ UPDATE_WHITELIST.join("/")
|
|
|
+ ),
|
|
|
+ TICKET_UNCONFIGURED_NOTE.to_string(),
|
|
|
+ ];
|
|
|
+ row_out_resp(
|
|
|
+ &state,
|
|
|
+ &sid,
|
|
|
+ "updated",
|
|
|
+ notes,
|
|
|
+ json!({
|
|
|
+ "updated_fields": UPDATE_WHITELIST,
|
|
|
+ "row_version": body.row_version + 1,
|
|
|
+ "trial_months": trial,
|
|
|
+ "discount_monthly_cents": disc,
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ .await
|
|
|
+}
|
|
|
+
|
|
|
+// ═══════════════════════════ §5.5 删除前检查与删除 ═══════════════════════════
|
|
|
+
|
|
|
+/// 删除阻塞(§5.5 两栏)=账单明细 + 变更链。
|
|
|
+///
|
|
|
+/// 账单明细只读口本轮未接线 ⇒ [`CrossRead::Unconfigured`](按登记回落值=「无账单」),
|
|
|
+/// 出参**必须**说明该回落⛔ 构成「无阻塞结论」;变更链=本订阅作为**原订阅**被指向的行。
|
|
|
+async fn delete_blocks(state: &AppState, r: &SubRow) -> Result<SubscriptionBlocks, BosError> {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let a = p.push(Value::String(r.subscription_id.clone()));
|
|
|
+ let sql = format!(
|
|
|
+ "SELECT s.subscription_id AS v FROM subscription s \
|
|
|
+ WHERE s.replaces_subscription_id = {a}::text ORDER BY s.subscription_id"
|
|
|
+ );
|
|
|
+ let rows = state.db.query_all::<IdRow>(&sql, p.values()).await?;
|
|
|
+ let chain: Vec<String> = rows.into_iter().map(|x| x.v).collect();
|
|
|
+ check_subscription_deletable(&CrossRead::<bool>::Unconfigured, &[], &chain)
|
|
|
+}
|
|
|
+
|
|
|
+/// 真终态(已退订/被承接)⛔ 任何写操作。
|
|
|
+///
|
|
|
+/// ⚠️「到期」**⛔** 算这里的闸门:删除的阻塞按 05 册 §5.6 只有两类(已产生账单明细
|
|
|
+/// ⇒`KLT-M227`/被 `replaces_subscription_id` 指为变更链原订阅⇒`KLT-M230`),
|
|
|
+/// 03 册 §5.2「当前可否编辑」=权限 ∧ 未被替代 ∧ 删除预检——到期本身⛔ 是判据
|
|
|
+/// (13 册回滚场景「订阅建错且未出账 ⇒ `delete_check` → 删除」正是到期行可删的正例)。
|
|
|
+fn terminal_guard(r: &SubRow, today: &str, op: &str) -> Result<(String, String), BosError> {
|
|
|
+ let (key, label, _) = status_display(r, today);
|
|
|
+ if key == "cancelled" || key == "replaced" {
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "订阅 {} 状态={label},⛔ {op}(已退订/被承接=真终态,只读)",
|
|
|
+ r.subscription_id
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ Ok((key, label))
|
|
|
+}
|
|
|
+
|
|
|
+/// `POST /subscription/delete_check@v1`:删除弹窗的两栏阻塞(账单明细 + 变更链)。
|
|
|
+pub async fn delete_check(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionIdReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let sid = match req_field("subscription_id", &body.subscription_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let r = match scoped_sub(&state, &auth, &sid).await {
|
|
|
+ Ok(Some(v)) => v,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
+ "订阅不存在或超出当前账号可见范围:{sid}"
|
|
|
+ )))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let blocks = match delete_blocks(&state, &r).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let t = today();
|
|
|
+ let (key, label, _) = status_display(&r, &t);
|
|
|
+ let status_blocks: Vec<String> = if key == "pending" || key == "active" {
|
|
|
+ Vec::new()
|
|
|
+ } else {
|
|
|
+ vec![format!("状态={label},⛔ 删除(§5.7)")]
|
|
|
+ };
|
|
|
+ let mut notes: Vec<String> = vec![format!(
|
|
|
+ "{BILLING_UNCONFIGURED_NOTE}本次检查**未取得**「无账单阻塞」结论。"
|
|
|
+ )];
|
|
|
+ notes.extend(blocks.note.clone());
|
|
|
+ json_ok(json!({
|
|
|
+ "subscription_id": r.subscription_id,
|
|
|
+ "can_delete": status_blocks.is_empty(),
|
|
|
+ "status": key,
|
|
|
+ "status_label": label,
|
|
|
+ "blocks": {
|
|
|
+ "billing_details": blocks.billing_details,
|
|
|
+ "change_chain": blocks.change_chain,
|
|
|
+ },
|
|
|
+ "status_blocks": status_blocks,
|
|
|
+ "billing_state": "unconfigured",
|
|
|
+ "notes": notes,
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+/// `POST /subscription/delete@v1`:删除 + 第 6 步额度回退(同一批语句)。
|
|
|
+pub async fn delete(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionIdReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let sid = match req_field("subscription_id", &body.subscription_id) {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let r = match scoped_sub(&state, &auth, &sid).await {
|
|
|
+ Ok(Some(v)) => v,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
+ "订阅不存在或超出当前账号可见范围:{sid}"
|
|
|
+ )))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let t = today();
|
|
|
+ if let Err(e) = terminal_guard(&r, &t, "删除") {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ // 阻塞复算(⛔ 让前端只靠 delete_check 的结论下单:两次调用之间状态可能已变)
|
|
|
+ if let Err(e) = delete_blocks(&state, &r).await {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ // §5.7 第 6 步:额度回退=剔除本行后重算应占额度(升降配不重复计入由求和口径自然保证)
|
|
|
+ let rest_rows: Vec<SubRow> = match subs_of_customer(&state, &r.customer_id).await {
|
|
|
+ Ok(v) => v.into_iter().filter(|x| x.subscription_id != sid).collect(),
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let target = match quota_target(&state, &r.customer_id, &rest_rows).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let before = match customer_quota(&state, &r.customer_id).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let mut p = Params::default();
|
|
|
+ let preds: Vec<String> = vec![
|
|
|
+ format!("subscription_id = {}::text", p.push(Value::String(sid.clone()))),
|
|
|
+ format!("status = {}::text", p.push(Value::String(r.status.clone()))),
|
|
|
+ ];
|
|
|
+ let mut stmts: Vec<DmlStatement> = vec![DmlStatement::new(
|
|
|
+ format!("DELETE FROM subscription {}", p.where_clause(&preds)),
|
|
|
+ p.values().to_vec(),
|
|
|
+ )];
|
|
|
+ if before != target {
|
|
|
+ stmts.push(quota_stmt(&r.customer_id, target));
|
|
|
+ }
|
|
|
+ let results = match state.db.dml_batch(&stmts).await {
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ let mut want: Vec<(&str, u64)> = vec![("订阅行 DELETE", 1)];
|
|
|
+ if stmts.len() > 1 {
|
|
|
+ want.push(("客户额度回退", 1));
|
|
|
+ }
|
|
|
+ if let Err(e) = assert_batch(&results, &want) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ let notes: Vec<String> = vec![
|
|
|
+ format!(
|
|
|
+ "{BILLING_UNCONFIGURED_NOTE}本次删除**未取得**「无账单阻塞」结论,需在只读口接线后复核。"
|
|
|
+ ),
|
|
|
+ "档位 `catalog_plan.first_referred_at` 打点⛔ 回滚(§5.7:引用事实不可逆,档位⛔ 回到可下架)。"
|
|
|
+ .to_string(),
|
|
|
+ format!(
|
|
|
+ "额度按「应占额度」对齐:删除前 {before} 分,应占 {target} 分,释放 {} 分。",
|
|
|
+ before - target
|
|
|
+ ),
|
|
|
+ ];
|
|
|
+ json_ok(json!({
|
|
|
+ "deleted": true,
|
|
|
+ "subscription_id": sid,
|
|
|
+ "quota_released": before - target,
|
|
|
+ "quota_align": { "before": before, "target": target, "written": before != target },
|
|
|
+ "notes": notes,
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+// ═══════════════════════ §5.6/§5.7 列表:get_list 与 list_all 共用一份实现 ═══════════════════════
|
|
|
+
|
|
|
+/// 列表的**唯一**查询实现(§5.1「不为两个页面写两套查询——一旦分叉,计数同源迟早破」)。
|
|
|
+///
|
|
|
+/// 两个入口只差入参:订阅管理页 `customer_id` 必填;全部订阅页客户可选、可跨客户、
|
|
|
+/// 可带区域筛选(区域经 `dim_node_ancestor` 展开成客户集合,⛔ 本册表带区域列)。
|
|
|
+async fn list_records(
|
|
|
+ state: &AppState,
|
|
|
+ auth: &bos_scope::AuthContext,
|
|
|
+ body: &SubscriptionListReq,
|
|
|
+ customer_required: bool,
|
|
|
+) -> Result<Value, BosError> {
|
|
|
+ let mut unknown: Vec<&str> = body.rest.keys().map(String::as_str).collect();
|
|
|
+ if !unknown.is_empty() {
|
|
|
+ unknown.sort_unstable();
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "不支持的检索条件:{}(§5.7 本册⛔ 按客户名称/合同编号检索=跨册模糊匹配,\
|
|
|
+ 请改用 keyword=套餐名快照、customer_id 或 contract_id)",
|
|
|
+ unknown.join("、")
|
|
|
+ )));
|
|
|
+ }
|
|
|
+ let cid = opt_trim(body.customer_id.as_ref());
|
|
|
+ if customer_required && cid.is_none() {
|
|
|
+ return Err(BosError::bad_params(
|
|
|
+ "customer_id 必填:订阅管理页按客户列出该客户的全部订阅(§5.1)",
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let t = today();
|
|
|
+ let mut p = Params::default();
|
|
|
+ let mut w: Vec<String> = vec![customer_scope_pred(state, auth, &mut p, "s.customer_id").await?];
|
|
|
+ if let Some(c) = cid {
|
|
|
+ w.push(format!("s.customer_id = {}::text", p.push(Value::String(c.to_string()))));
|
|
|
+ }
|
|
|
+ if let Some(regions) = opt_region_ids(body.region_ids.as_ref()) {
|
|
|
+ let ids = customers_under_regions(state, regions).await?;
|
|
|
+ w.push(push_in(&mut p, "s.customer_id", &ids, "text"));
|
|
|
+ }
|
|
|
+ if let Some(k) = p.push_like(opt_trim(body.keyword.as_ref())) {
|
|
|
+ w.push(format!("s.plan_name LIKE {k}"));
|
|
|
+ }
|
|
|
+ if let Some(ct) = opt_trim(body.contract_id.as_ref()) {
|
|
|
+ w.push(format!("s.contract_id = {}::text", p.push(Value::String(ct.to_string()))));
|
|
|
+ }
|
|
|
+ if let Some(st) = opt_trim(body.status.as_ref()) {
|
|
|
+ // 状态三态是**读侧推导**(本轮⛔ 日终翻转任务)⇒ 筛选谓词与 `status_display` 同源
|
|
|
+ match st {
|
|
|
+ "cancelled" | "replaced" => {
|
|
|
+ w.push(format!("s.status = {}::text", p.push(Value::String(st.to_string()))));
|
|
|
+ }
|
|
|
+ "pending" => {
|
|
|
+ let td = p.push(Value::String(t.clone()));
|
|
|
+ w.push("s.status NOT IN ('cancelled','replaced')".to_string());
|
|
|
+ w.push(format!("COALESCE(s.start_date, s.effective_date) > {td}::date"));
|
|
|
+ }
|
|
|
+ "active" => {
|
|
|
+ let td = p.push(Value::String(t.clone()));
|
|
|
+ w.push("s.status NOT IN ('cancelled','replaced')".to_string());
|
|
|
+ w.push(format!("COALESCE(s.start_date, s.effective_date) <= {td}::date"));
|
|
|
+ w.push(format!("COALESCE(s.end_date, s.expire_date) >= {td}::date"));
|
|
|
+ }
|
|
|
+ "expired" => {
|
|
|
+ let td = p.push(Value::String(t.clone()));
|
|
|
+ w.push("s.status NOT IN ('cancelled','replaced')".to_string());
|
|
|
+ w.push(format!("COALESCE(s.end_date, s.expire_date) < {td}::date"));
|
|
|
+ }
|
|
|
+ other => {
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
+ "未知订阅状态筛选值:{other}(可选 pending/active/expired/cancelled/replaced)"
|
|
|
+ )))
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // ⚠️ `total()` 只接受 `FROM … WHERE …` 片段(它自己前缀 `SELECT COUNT(1) AS c`),
|
|
|
+ // 把 `SELECT_COLS` 拼进来会成 `SELECT COUNT(1) AS c SELECT …` ⇒ UDS 侧解析报错。
|
|
|
+ let from_where = format!("FROM subscription s {}", p.where_clause(&w));
|
|
|
+ let total = total(state.db.as_ref(), &from_where, p.values()).await?;
|
|
|
+ let (lim, off) = p.push_page(&body.pg);
|
|
|
+ let sql =
|
|
|
+ format!("{SELECT_COLS} {from_where} ORDER BY s.customer_id, s.subscription_id DESC LIMIT {lim} OFFSET {off}");
|
|
|
+ let rows = state.db.query_all::<SubRow>(&sql, p.values()).await?;
|
|
|
+ let ids: Vec<String> = rows.iter().map(|r| r.customer_id.clone()).collect();
|
|
|
+ let names = pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &ids).await?;
|
|
|
+ let items: Vec<Value> = rows
|
|
|
+ .iter()
|
|
|
+ .map(|r| {
|
|
|
+ to_json(
|
|
|
+ r,
|
|
|
+ names.get(&r.customer_id).and_then(|v| v.first()).map(String::as_str),
|
|
|
+ &t,
|
|
|
+ )
|
|
|
+ })
|
|
|
+ .collect();
|
|
|
+ Ok(json!({
|
|
|
+ "items": items,
|
|
|
+ "total": total,
|
|
|
+ "page": body.pg.page,
|
|
|
+ "page_size": body.pg.page_size,
|
|
|
+ "notes": [
|
|
|
+ "套餐名关键字命中 `subscription.plan_name` **快照列**(§5.7:⛔ 回连 catalog_plan,\
|
|
|
+ 档位改名不回写历史订阅)。",
|
|
|
+ "状态三态为读侧推导(本轮⛔ 日终状态任务);`editable`/`reason` 与状态同源。",
|
|
|
+ ],
|
|
|
+ }))
|
|
|
+}
|
|
|
+
|
|
|
+fn opt_region_ids(v: Option<&Vec<String>>) -> Option<&[String]> {
|
|
|
+ v.map(Vec::as_slice).filter(|s| !s.is_empty())
|
|
|
+}
|
|
|
+
|
|
|
+/// `POST /subscription/get_list@v1`:客户管理 → 套餐订阅管理页(唯一写入口的列表)。
|
|
|
+pub async fn get_list(
|
|
|
+ State(state): State<AppState>,
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
+ DataBody(body): DataBody<SubscriptionListReq>,
|
|
|
+) -> Response {
|
|
|
+ if let Err(e) = auth.require_roles(&[
|
|
|
+ RoleCode::Admin,
|
|
|
+ RoleCode::OpsMain,
|
|
|
+ RoleCode::Ops,
|
|
|
+ RoleCode::OpsSub,
|
|
|
+ ]) {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ match list_records(&state, &auth, &body, true).await {
|
|
|
+ Ok(v) => json_ok(v),
|
|
|
+ Err(e) => json_err(e),
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
-// ───────────────────────── 写侧:三枚 ─────────────────────────
|
|
|
-
|
|
|
-pub async fn create(
|
|
|
+/// `POST /subscription/list_all@v1`:全部订阅页(⛔ 新增/编辑/删除入口,只查询)。
|
|
|
+pub async fn list_all(
|
|
|
State(state): State<AppState>,
|
|
|
RequireAuth(auth): RequireAuth,
|
|
|
- DataBody(body): DataBody<SubscriptionCreateReq>,
|
|
|
+ DataBody(body): DataBody<SubscriptionListReq>,
|
|
|
) -> Response {
|
|
|
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
|
|
|
- let mut spec_notes: Vec<String> = Vec::new();
|
|
|
- if body.end_date.as_deref().is_some_and(|s| !s.trim().is_empty()) {
|
|
|
- spec_notes.push(
|
|
|
- "openapi /subscription/create@v1 描述为「拒收…新建时的 end_date」,本轮按「带上即校验并落库」\
|
|
|
- 处理,差异已登记待裁定。"
|
|
|
- .to_string(),
|
|
|
- );
|
|
|
+ if let Err(e) = auth.require_roles(&[
|
|
|
+ RoleCode::Admin,
|
|
|
+ RoleCode::OpsMain,
|
|
|
+ RoleCode::Ops,
|
|
|
+ RoleCode::OpsSub,
|
|
|
+ ]) {
|
|
|
+ return json_err(e);
|
|
|
}
|
|
|
- if body.row_version.is_some() {
|
|
|
- spec_notes.push(
|
|
|
- "新建没有可锁定的既存行,入参 row_version 未参与乐观锁;新行 row_version 由库 DEFAULT 1 起算。"
|
|
|
- .to_string(),
|
|
|
- );
|
|
|
- }
|
|
|
- spec_notes.push(
|
|
|
- "openapi 声明「拒收」的 line_exits/sub_mode/order_no/opened_at 未在本轮请求体建模(本轮无对应\
|
|
|
- 在册列),带上即忽略而非拒收。"
|
|
|
- .to_string(),
|
|
|
- );
|
|
|
- let n = match build_new_subscription(&state, &auth, &body, None).await {
|
|
|
- Ok(v) => v,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- match state.db.dml(&n.sql, &n.params).await {
|
|
|
- Ok(1) => write_back(&state, &n.id, "created", Vec::new(), spec_notes).await,
|
|
|
- Ok(k) => json_err(BosError::internal(format!("新订落库影响行数异常:{k}(期望 1)"))),
|
|
|
+ match list_records(&state, &auth, &body, false).await {
|
|
|
+ Ok(v) => json_ok(v),
|
|
|
Err(e) => json_err(e),
|
|
|
}
|
|
|
}
|
|
|
|
|
|
-pub async fn change(
|
|
|
+// ═══════════════════════════ §5.4 详情:五分区 ═══════════════════════════
|
|
|
+
|
|
|
+/// `POST /subscription/get@v1`:基本/周期/金额/出口/额度五分区 + 条件 `related`。
|
|
|
+pub async fn get(
|
|
|
State(state): State<AppState>,
|
|
|
RequireAuth(auth): RequireAuth,
|
|
|
- DataBody(body): DataBody<SubscriptionChangeReq>,
|
|
|
+ DataBody(body): DataBody<SubscriptionGetReq>,
|
|
|
) -> Response {
|
|
|
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
|
|
|
- let mut spec_notes: Vec<String> = Vec::new();
|
|
|
- spec_notes.push(
|
|
|
- "openapi /subscription/change@v1 描述「升降配须使用新的 contract_id(不得沿用原合同)」本轮未强制\
|
|
|
- (未登记为校验项),差异已登记待裁定。"
|
|
|
- .to_string(),
|
|
|
- );
|
|
|
- if body.next.row_version.is_some() {
|
|
|
- spec_notes.push(
|
|
|
- "入参 row_version 的乐观锁作用于**被替换的原订阅行**;新行 row_version 由库 DEFAULT 1 起算。"
|
|
|
- .to_string(),
|
|
|
- );
|
|
|
+ if let Err(e) = auth.require_roles(&[
|
|
|
+ RoleCode::Admin,
|
|
|
+ RoleCode::OpsMain,
|
|
|
+ RoleCode::Ops,
|
|
|
+ RoleCode::OpsSub,
|
|
|
+ ]) {
|
|
|
+ return json_err(e);
|
|
|
}
|
|
|
- let rid = match req_field("replaces_subscription_id", &body.replaces_subscription_id) {
|
|
|
+ let sid = match req_field("subscription_id", &body.subscription_id) {
|
|
|
Ok(v) => v,
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
- let cur = match scoped_sub(&state, &auth, &rid).await {
|
|
|
- Ok(Some(c)) => c,
|
|
|
+ let r = match scoped_sub(&state, &auth, &sid).await {
|
|
|
+ Ok(Some(v)) => v,
|
|
|
Ok(None) => {
|
|
|
- return json_err(BosError::not_found(format!("原订阅不存在或超出当前账号可见范围:{rid}")))
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
+ "订阅不存在或超出当前账号可见范围:{sid}"
|
|
|
+ )))
|
|
|
}
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
- if cur.status == "cancelled" {
|
|
|
- return json_err(BosError::bad_params(format!("原订阅 {rid} 状态为 cancelled,⛔ 升降配")));
|
|
|
- }
|
|
|
- match replacement_count(&state, &cur.subscription_id).await {
|
|
|
- Ok(0) => {}
|
|
|
- Ok(k) => {
|
|
|
- return json_err(BosError::bad_params(format!(
|
|
|
- "原订阅 {} 已被升降配换过 {k} 次(replaces_subscription_id 唯一,⛔ 重复换)",
|
|
|
- cur.subscription_id
|
|
|
- )))
|
|
|
- }
|
|
|
+ let t = today();
|
|
|
+ let names = match pairs_by(
|
|
|
+ state.db.as_ref(),
|
|
|
+ "customer",
|
|
|
+ "customer_id",
|
|
|
+ "customer_name",
|
|
|
+ &[r.customer_id.clone()],
|
|
|
+ )
|
|
|
+ .await
|
|
|
+ {
|
|
|
+ Ok(v) => v,
|
|
|
Err(e) => return json_err(e),
|
|
|
- }
|
|
|
- let NewSub { id, sql, params } =
|
|
|
- match build_new_subscription(&state, &auth, &body.next, Some(cur.subscription_id.as_str())).await {
|
|
|
+ };
|
|
|
+ let customer_name = names
|
|
|
+ .get(&r.customer_id)
|
|
|
+ .and_then(|v| v.first())
|
|
|
+ .cloned()
|
|
|
+ .unwrap_or_default();
|
|
|
+ // 合同一栏:未关联合同显示「—」且⛔ 显示「未开通」(§5.4:⛔ 把「无合同」说成一种开通态)
|
|
|
+ let mut opened_state: Option<&str> = None;
|
|
|
+ let mut contract_no: Option<String> = None;
|
|
|
+ if let Some(ct) = opt_trim(r.contract_id.as_ref()) {
|
|
|
+ let all = match contracts_of_customer(&state, &r.customer_id).await {
|
|
|
Ok(v) => v,
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
-
|
|
|
- // 原订阅置 replaced+版本自增(谓词里带上「非 cancelled」与「凡带 row_version 即锁」);
|
|
|
- // 与新行 INSERT 同批=原子提交(⚠️ UDS ⛔ 批内条件中止 ⇒ 影响行数只做事后自检)。
|
|
|
- let mut up = Params::default();
|
|
|
- let mut set = vec![format!("status = {}::text", up.push(Value::String("replaced".to_string())))];
|
|
|
- set.push("row_version = row_version + 1".to_string());
|
|
|
- let mut preds = vec![format!("subscription_id = {}::text", up.push(Value::String(rid.clone())))];
|
|
|
- preds.push(format!("status <> {}::text", up.push(Value::String("cancelled".to_string()))));
|
|
|
- if let Some(v) = body.next.row_version {
|
|
|
- preds.push(format!("row_version = {}::int", up.push(Value::from(v))));
|
|
|
+ if let Some(c) = all.into_iter().find(|c| c.contract_id == ct) {
|
|
|
+ contract_no =
|
|
|
+ Some(opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()).to_string());
|
|
|
+ match opened_map_for(&state, &[c]).await {
|
|
|
+ Ok(m) => {
|
|
|
+ opened_state = match m.get(ct) {
|
|
|
+ Some(Opened::Opened) => Some("opened"),
|
|
|
+ Some(Opened::NotOpened) => Some("not_opened"),
|
|
|
+ None => None,
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
- let update_sql = format!("UPDATE subscription SET {} {}", set.join(", "), up.where_clause(&preds));
|
|
|
- let results = match state
|
|
|
- .db
|
|
|
- .dml_batch(&[
|
|
|
- DmlStatement::new(sql, params),
|
|
|
- DmlStatement::new(update_sql, up.values().to_vec()),
|
|
|
- ])
|
|
|
- .await
|
|
|
- {
|
|
|
- Ok(r) => r,
|
|
|
+ // 变更链(§5.4「关联订阅」):被谁替代 + 替代了谁
|
|
|
+ let replaced_by: Vec<Value> = {
|
|
|
+ let mut p = Params::default();
|
|
|
+ let a = p.push(Value::String(sid.clone()));
|
|
|
+ let sql = format!(
|
|
|
+ "{SELECT_COLS} FROM subscription s WHERE s.replaces_subscription_id = {a}::text \
|
|
|
+ ORDER BY s.subscription_id"
|
|
|
+ );
|
|
|
+ match state.db.query_all::<SubRow>(&sql, p.values()).await {
|
|
|
+ Ok(v) => v.iter().map(|x| brief(x, &t)).collect(),
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ }
|
|
|
+ };
|
|
|
+ let original: Option<Value> = match opt_trim(r.replaces_subscription_id.as_ref()) {
|
|
|
+ Some(o) => {
|
|
|
+ match scoped_sub(&state, &auth, o).await {
|
|
|
+ Ok(Some(row)) => Some(brief(&row, &t)),
|
|
|
+ Ok(None) => None,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ }
|
|
|
+ }
|
|
|
+ None => None,
|
|
|
+ };
|
|
|
+ let quota_slots = as_opt_num(Some(r.quota_slots.as_str()));
|
|
|
+ let customer_quota_cents = match customer_quota(&state, &r.customer_id).await {
|
|
|
+ Ok(v) => v,
|
|
|
Err(e) => return json_err(e),
|
|
|
};
|
|
|
- let hit = |i: usize| results.get(i).and_then(|r| r.affected_rows).unwrap_or(0);
|
|
|
- if hit(0) != 1 || hit(1) != 1 {
|
|
|
- return json_err(BosError::internal(format!(
|
|
|
- "升降配短批影响行数异常(新行 {},原订阅 {}):新订阅 {id} 已随批提交落库,原订阅 {rid} \
|
|
|
- 未置 replaced,须人工核对",
|
|
|
- hit(0),
|
|
|
- hit(1)
|
|
|
- )));
|
|
|
+ let mut v = to_json(&r, Some(customer_name.as_str()), &t);
|
|
|
+ v["panels"] = json!({
|
|
|
+ "basic": {
|
|
|
+ "customer_id": r.customer_id,
|
|
|
+ "customer_name": customer_name,
|
|
|
+ "contract_id": r.contract_id,
|
|
|
+ "contract_no": contract_no.clone().unwrap_or_else(|| "—".to_string()),
|
|
|
+ "contract_opened_state": opened_state,
|
|
|
+ "contract_item_id": r.contract_item_id,
|
|
|
+ "order_no": opt_trim(r.order_no.as_ref()).unwrap_or("—"),
|
|
|
+ "actual_opened_at": opt_trim(r.actual_opened_at.as_ref()).unwrap_or("—"),
|
|
|
+ "plan_id": r.plan_id,
|
|
|
+ "plan_name": r.plan_name,
|
|
|
+ "plan_kind": r.plan_kind,
|
|
|
+ "created_at": r.created_at,
|
|
|
+ "row_version": as_opt_num(Some(r.row_version.as_str())),
|
|
|
+ },
|
|
|
+ "period": {
|
|
|
+ "term": r.term,
|
|
|
+ "start_date": start_text(&r),
|
|
|
+ "end_date": end_text(&r),
|
|
|
+ "effective_date": r.effective_date,
|
|
|
+ "expire_date": r.expire_date,
|
|
|
+ },
|
|
|
+ "amount": money_json(&r),
|
|
|
+ "exits": {
|
|
|
+ "use_category": r.use_category,
|
|
|
+ "sub_mode": r.sub_mode,
|
|
|
+ "line_exits": exits_json(r.line_exits.as_ref()),
|
|
|
+ "line_exit_key": r.line_exit_key,
|
|
|
+ },
|
|
|
+ "quota": {
|
|
|
+ "quota_slots": quota_slots,
|
|
|
+ "customer_quota_cents": customer_quota_cents,
|
|
|
+ },
|
|
|
+ });
|
|
|
+ v["related"] = json!({
|
|
|
+ "replaced_by": replaced_by,
|
|
|
+ "original": original,
|
|
|
+ });
|
|
|
+ // 套餐月成本只读口未接线 ⇒ 三态里的 `unconfigured`(⛔ 显示 0 元、⛔ 显示「无成本」)
|
|
|
+ v["plan_cost_cents"] = json!(null);
|
|
|
+ v["plan_cost_state"] = json!("unconfigured");
|
|
|
+ v["billing_state"] = json!("unconfigured");
|
|
|
+ let mut notes: Vec<String> = vec![
|
|
|
+ COST_UNCONFIGURED_NOTE.to_string(),
|
|
|
+ format!("{BILLING_UNCONFIGURED_NOTE}详情页的出账一栏⛔ 说成「未出账」。"),
|
|
|
+ ];
|
|
|
+ if contract_no.is_none() {
|
|
|
+ notes.push("本订阅未关联合同:合同一栏显示「—」,⛔ 显示「未开通」(§5.4)。".to_string());
|
|
|
}
|
|
|
- write_back(&state, &id, "changed", Vec::new(), spec_notes).await
|
|
|
+ v["notes"] = json!(notes);
|
|
|
+ json_ok(v)
|
|
|
+}
|
|
|
+
|
|
|
+/// 变更链节点的精简出参(⛔ 详情里递归展开整行)。
|
|
|
+fn brief(r: &SubRow, today: &str) -> Value {
|
|
|
+ let (key, label, _) = status_display(r, today);
|
|
|
+ json!({
|
|
|
+ "subscription_id": r.subscription_id,
|
|
|
+ "plan_name": r.plan_name,
|
|
|
+ "status": key,
|
|
|
+ "status_label": label,
|
|
|
+ "start_date": start_text(r),
|
|
|
+ "end_date": end_text(r),
|
|
|
+ })
|
|
|
}
|
|
|
|
|
|
+// ═══════════════════════════ stack(契约保持不动) ═══════════════════════════
|
|
|
+
|
|
|
+/// `POST /subscription/stack@v1`:**契约不动**(本轮⛔ 改 openapi 与本口出入参形态)。
|
|
|
+///
|
|
|
+/// 只承接「已存在订阅的续订」=按 openapi 入参落 `end_date`/年费/月结算金额;
|
|
|
+/// 「叠加新建」分支(`customer_id` + `plan_id`)本轮⛔ 落库 ⇒ 点名指向 `/subscription/create@v1`。
|
|
|
pub async fn stack(
|
|
|
State(state): State<AppState>,
|
|
|
RequireAuth(auth): RequireAuth,
|
|
|
DataBody(body): DataBody<SubscriptionStackReq>,
|
|
|
) -> Response {
|
|
|
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) { return json_err(e); }
|
|
|
- let mut spec_notes: Vec<String> = Vec::new();
|
|
|
- let mut not_persisted: Vec<String> = Vec::new();
|
|
|
- for (name, v) in [
|
|
|
- ("customer_id", &body.customer_id),
|
|
|
- ("plan_id", &body.plan_id),
|
|
|
- ("contract_id", &body.contract_id),
|
|
|
- ("contract_item_id", &body.contract_item_id),
|
|
|
- ("start_date", &body.start_date),
|
|
|
- ] {
|
|
|
- if v.as_deref().is_some_and(|s| !s.trim().is_empty()) {
|
|
|
- not_persisted.push(name.to_string());
|
|
|
- }
|
|
|
- }
|
|
|
- if !not_persisted.is_empty() {
|
|
|
- spec_notes.push(
|
|
|
- "以上 not_persisted 列只属于 openapi 的「叠加新建」分支;本轮 stack ⛔ 新建行(只在原行上延长),\
|
|
|
- 故未落库。"
|
|
|
- .to_string(),
|
|
|
- );
|
|
|
+ if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
|
|
|
+ return json_err(e);
|
|
|
}
|
|
|
-
|
|
|
- let sid = match body.subscription_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
|
|
+ let sid = match opt_trim(body.subscription_id.as_ref()) {
|
|
|
Some(s) => s.to_string(),
|
|
|
None => {
|
|
|
- return json_err(BosError::not_implemented(
|
|
|
- "「叠加新建」分支本轮未实现:stack 只在原订阅行上延长,须带 subscription_id",
|
|
|
+ return json_err(BosError::bad_params(
|
|
|
+ "stack 本轮只承接续订(subscription_id 必填);叠加新建请走 \
|
|
|
+ /subscription/create@v1(§5.2 五步校验+六步事务只有一条落库路径)"
|
|
|
+ .to_string(),
|
|
|
))
|
|
|
}
|
|
|
};
|
|
|
- let cur = match scoped_sub(&state, &auth, &sid).await {
|
|
|
- Ok(Some(c)) => c,
|
|
|
- Ok(None) => {
|
|
|
- return json_err(BosError::not_found(format!("订阅不存在或超出当前账号可见范围:{sid}")))
|
|
|
- }
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- let end_raw = match body.end_date.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
|
|
- Some(s) => s.to_string(),
|
|
|
- None => return json_err(BosError::bad_params("end_date 必填:续订即在原行上延长到期日")),
|
|
|
- };
|
|
|
- let new_end = match parse_date("end_date", &end_raw) {
|
|
|
- Ok(d) => d,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- // 基线=设计列 end_date → 骨架列 expire_date → start_date(存量种子只有旧列有值)。
|
|
|
- let baseline = cur.end_date.clone().or(cur.expire_date.clone()).or(cur.start_date.clone());
|
|
|
- match baseline.as_deref() {
|
|
|
- Some(b) => {
|
|
|
- let bd = match parse_date("原订阅到期日", b) {
|
|
|
- Ok(d) => d,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- if new_end <= bd {
|
|
|
- return json_err(BosError::bad_params(format!(
|
|
|
- "end_date {} 须晚于原到期日 {b}",
|
|
|
- date_text(new_end)
|
|
|
- )));
|
|
|
- }
|
|
|
+ let mut updated: Vec<&str> = Vec::new();
|
|
|
+ let mut p = Params::default();
|
|
|
+ let mut set: Vec<String> = Vec::new();
|
|
|
+ if let Some(d) = opt_trim(body.end_date.as_ref()) {
|
|
|
+ if let Err(e) = parse_date("end_date", d) {
|
|
|
+ return json_err(e);
|
|
|
}
|
|
|
- None => spec_notes.push(
|
|
|
- "原订阅 end_date/expire_date/start_date 均为空,无在册基线可比,未做「晚于现值」校验。"
|
|
|
- .to_string(),
|
|
|
- ),
|
|
|
+ set.push(format!("end_date = {}::date", p.push(Value::String(d.to_string()))));
|
|
|
+ updated.push("end_date");
|
|
|
}
|
|
|
-
|
|
|
- let mut p = Params::default();
|
|
|
- let mut set = vec![format!("end_date = {}::date", p.push(Value::String(date_text(new_end))))];
|
|
|
if let Some(a) = body.annual_price_cents {
|
|
|
+ if a <= 0 || a > MAX_AMOUNT_CENTS {
|
|
|
+ return json_err(BosError::bad_params(format!(
|
|
|
+ "annual_price_cents 须落在 1..={MAX_AMOUNT_CENTS} 分,实得 {a}"
|
|
|
+ )));
|
|
|
+ }
|
|
|
set.push(format!("annual_price_cents = {}::bigint", p.push(Value::from(a))));
|
|
|
+ updated.push("annual_price_cents");
|
|
|
}
|
|
|
if let Some(m) = body.monthly_settle_cents {
|
|
|
+ if m <= 0 || m > MAX_AMOUNT_CENTS {
|
|
|
+ return json_err(BosError::bad_params(format!(
|
|
|
+ "monthly_settle_cents 须落在 1..={MAX_AMOUNT_CENTS} 分,实得 {m}"
|
|
|
+ )));
|
|
|
+ }
|
|
|
set.push(format!("monthly_settle_cents = {}::bigint", p.push(Value::from(m))));
|
|
|
+ updated.push("monthly_settle_cents");
|
|
|
+ }
|
|
|
+ if updated.is_empty() {
|
|
|
+ return json_err(BosError::bad_params(
|
|
|
+ "stack 无可更新列:end_date/annual_price_cents/monthly_settle_cents 至少给一项"
|
|
|
+ .to_string(),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let r = match scoped_sub(&state, &auth, &sid).await {
|
|
|
+ Ok(Some(v)) => v,
|
|
|
+ Ok(None) => {
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
+ "订阅不存在或超出当前账号可见范围:{sid}"
|
|
|
+ )))
|
|
|
+ }
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if let Err(e) = terminal_guard(&r, &today(), "续订") {
|
|
|
+ return json_err(e);
|
|
|
+ }
|
|
|
+ // ⛔ 已到期不可续订:`terminal_guard` 只管真终态(已退订/被承接),在网态要求在本口
|
|
|
+ // 单独收——已到期订阅按 05 册 §5.4 转入「往期套餐」,延长服务只能另建新订阅。
|
|
|
+ let (skey, slabel, _) = status_display(&r, &today());
|
|
|
+ if skey != "pending" && skey != "active" {
|
|
|
+ return json_err(BosError::bad_params(format!(
|
|
|
+ "订阅 {} 状态={slabel},⛔ 续订(仅待生效/生效中可续订)",
|
|
|
+ r.subscription_id
|
|
|
+ )));
|
|
|
}
|
|
|
set.push("row_version = row_version + 1".to_string());
|
|
|
- let mut preds = vec![format!("subscription_id = {}::text", p.push(Value::String(sid.clone())))];
|
|
|
+ set.push("updated_at = NOW()".to_string());
|
|
|
+ let mut preds: Vec<String> = vec![format!(
|
|
|
+ "subscription_id = {}::text",
|
|
|
+ p.push(Value::String(sid.clone()))
|
|
|
+ )];
|
|
|
if let Some(v) = body.row_version {
|
|
|
preds.push(format!("row_version = {}::int", p.push(Value::from(v))));
|
|
|
}
|
|
|
- let sql = format!("UPDATE subscription SET {} {}", set.join(", "), p.where_clause(&preds));
|
|
|
+ let sql = format!(
|
|
|
+ "UPDATE subscription SET {} {}",
|
|
|
+ set.join(", "),
|
|
|
+ p.where_clause(&preds)
|
|
|
+ );
|
|
|
let affected = match state.db.dml(&sql, p.values()).await {
|
|
|
- Ok(n) => n,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- if affected != 1 {
|
|
|
- // 影响 0 行 ⇒ 回读区分「不存在」/「版本不符」/「未带版本却没命中」,⛔ 混用文案。
|
|
|
- let mut q = Params::default();
|
|
|
- let s = q.push(Value::String(sid.clone()));
|
|
|
- let rq = match state
|
|
|
- .db
|
|
|
- .query_one::<IdRow>(
|
|
|
- &format!("SELECT s.row_version AS v FROM subscription s WHERE s.subscription_id = {s}::text"),
|
|
|
- q.values(),
|
|
|
- )
|
|
|
- .await
|
|
|
- {
|
|
|
- Ok(r) => r,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- return match (rq, body.row_version) {
|
|
|
- (None, _) => json_err(BosError::not_found(format!(
|
|
|
- "续订未命中:订阅 {sid} 不存在或已不可见"
|
|
|
- ))),
|
|
|
- (Some(r), Some(v)) => json_err(BosError::bad_params(format!(
|
|
|
- "续订未命中:携带 row_version = {v},库里现值 {},请刷新后重试",
|
|
|
- r.v
|
|
|
- ))),
|
|
|
- (Some(r), None) => json_err(BosError::internal(format!(
|
|
|
- "续订影响行数异常:{affected}(未带 row_version,订阅 {sid} 库里现值 row_version {})",
|
|
|
- r.v
|
|
|
- ))),
|
|
|
- };
|
|
|
+ Ok(v) => v,
|
|
|
+ Err(e) => return json_err(e),
|
|
|
+ };
|
|
|
+ if affected == 0 {
|
|
|
+ return json_err(BosError::klt(
|
|
|
+ KltCode::S407,
|
|
|
+ format!("订阅 {sid} 已被他人改动(row_version 不符),请重新加载后重试"),
|
|
|
+ ));
|
|
|
+ }
|
|
|
+ let mut notes: Vec<String> = vec![STACK_LEGACY_NOTE.to_string()];
|
|
|
+ let mut untouched: Vec<&str> = Vec::new();
|
|
|
+ if body.customer_id.is_some()
|
|
|
+ || body.plan_id.is_some()
|
|
|
+ || body.contract_id.is_some()
|
|
|
+ || body.contract_item_id.is_some()
|
|
|
+ || body.start_date.is_some()
|
|
|
+ {
|
|
|
+ untouched.push("customer_id/plan_id/contract_id/contract_item_id/start_date");
|
|
|
+ notes.push(
|
|
|
+ "openapi「叠加新建」分支的入参列本轮⛔ 落库(本口只更新既有行),已登记待裁定。"
|
|
|
+ .to_string(),
|
|
|
+ );
|
|
|
}
|
|
|
- write_back(&state, &sid, "stacked", not_persisted, spec_notes).await
|
|
|
+ json_ok(json!({
|
|
|
+ "subscription_id": sid,
|
|
|
+ "updated_fields": updated,
|
|
|
+ "not_persisted": untouched,
|
|
|
+ "notes": notes,
|
|
|
+ }))
|
|
|
}
|
|
|
|
|
|
-// ───────────────────────── 只读侧 ─────────────────────────
|
|
|
+// ═══════════════════════════ 单元测试(纯函数+静态断言) ═══════════════════════════
|
|
|
|
|
|
-#[derive(Deserialize)]
|
|
|
-pub struct SubscriptionListReq {
|
|
|
- #[serde(flatten)]
|
|
|
- pub pg: PageQuery,
|
|
|
- pub keyword: Option<String>,
|
|
|
- pub customer_id: Option<String>,
|
|
|
- pub contract_id: Option<String>,
|
|
|
- pub status: Option<String>,
|
|
|
-}
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
|
|
|
-#[derive(Deserialize)]
|
|
|
-pub struct SubscriptionGetReq {
|
|
|
- pub subscription_id: String,
|
|
|
-}
|
|
|
+ fn map(raw: &str) -> Map<String, Value> {
|
|
|
+ serde_json::from_str::<Value>(raw).unwrap().as_object().unwrap().clone()
|
|
|
+ }
|
|
|
|
|
|
-#[derive(Deserialize)]
|
|
|
-struct SubRow {
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
- subscription_id: String,
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
- customer_id: String,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- contract_id: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- plan_id: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
- status: String,
|
|
|
- /// ⚠️ 一期骨架遗留列(写侧已停用),读侧原样呈现。
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- effective_date: Option<String>,
|
|
|
- /// ⚠️ 一期骨架遗留列(写侧已停用),读侧原样呈现。
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- expire_date: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
- quota_slots: String,
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
- created_at: String,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- contract_item_id: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- use_category: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- start_date: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- end_date: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- annual_price_cents: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- monthly_settle_cents: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_opt_string")]
|
|
|
- replaces_subscription_id: Option<String>,
|
|
|
- #[serde(deserialize_with = "de::as_string")]
|
|
|
- row_version: String,
|
|
|
-}
|
|
|
+ #[test]
|
|
|
+ fn 时长折算先折下一周期生效日再减一天() {
|
|
|
+ // §5.2:2026-01-31 按月 ⇒ 下一周期 2026-02-28 ⇒ 结束日 2026-02-27
|
|
|
+ let d = NaiveDate::from_ymd_opt(2026, 1, 31).unwrap();
|
|
|
+ let next = add_months_clamped(d, 1);
|
|
|
+ assert_eq!(date_text(next), "2026-02-28");
|
|
|
+ let prev = next - chrono::Duration::days(1);
|
|
|
+ assert_eq!(date_text(prev), "2026-02-27");
|
|
|
+ // 按年=加 12 个月;按季度=加 3 个月
|
|
|
+ assert_eq!(term_months("yearly").unwrap(), 12);
|
|
|
+ assert_eq!(term_months("quarterly").unwrap(), 3);
|
|
|
+ assert_eq!(term_months("monthly").unwrap(), 1);
|
|
|
+ assert!(term_months("weekly").is_err());
|
|
|
+ let d2 = NaiveDate::from_ymd_opt(2028, 2, 29).unwrap();
|
|
|
+ assert_eq!(date_text(add_months_clamped(d2, 12)), "2029-02-28");
|
|
|
+ }
|
|
|
|
|
|
-fn to_json(r: &SubRow, customer_name: Option<&str>, plan_name: Option<&str>) -> Value {
|
|
|
- json!({
|
|
|
- "subscription_id": r.subscription_id,
|
|
|
- "customer_id": r.customer_id,
|
|
|
- "customer_name": customer_name,
|
|
|
- "contract_id": r.contract_id,
|
|
|
- "plan_id": r.plan_id,
|
|
|
- "plan_name": plan_name,
|
|
|
- "status": r.status,
|
|
|
- "effective_date": r.effective_date,
|
|
|
- "expire_date": r.expire_date,
|
|
|
- "quota_slots": as_num(&r.quota_slots),
|
|
|
- "created_at": r.created_at,
|
|
|
- "contract_item_id": r.contract_item_id,
|
|
|
- "use_category": r.use_category,
|
|
|
- "start_date": r.start_date,
|
|
|
- "end_date": r.end_date,
|
|
|
- "annual_price_cents": as_opt_num(r.annual_price_cents.as_deref()),
|
|
|
- "monthly_settle_cents": as_opt_num(r.monthly_settle_cents.as_deref()),
|
|
|
- "replaces_subscription_id": r.replaces_subscription_id,
|
|
|
- "row_version": as_num(&r.row_version),
|
|
|
- })
|
|
|
-}
|
|
|
+ #[test]
|
|
|
+ fn 年价按订阅时长折算且月结算不受时长影响() {
|
|
|
+ assert_eq!(annual_by_term(120_000, 10_000, "yearly"), 120_000);
|
|
|
+ assert_eq!(annual_by_term(120_000, 10_000, "quarterly"), 30_000);
|
|
|
+ assert_eq!(annual_by_term(120_000, 10_000, "monthly"), 10_000);
|
|
|
+ }
|
|
|
|
|
|
-pub async fn get_list(
|
|
|
- State(state): State<AppState>,
|
|
|
- RequireAuth(auth): RequireAuth,
|
|
|
- DataBody(body): DataBody<SubscriptionListReq>,
|
|
|
-) -> Response {
|
|
|
- let mut p = Params::default();
|
|
|
- let mut w: Vec<String> = Vec::new();
|
|
|
- match customer_scope_pred(&state, &auth, &mut p, "s.customer_id").await {
|
|
|
- Ok(pred) => w.push(pred),
|
|
|
- Err(e) => return json_err(e),
|
|
|
+ #[test]
|
|
|
+ fn 新建载荷的只读派生列逐列点名拒收() {
|
|
|
+ let m = map(r#"{"annual_price_cents":1,"line_exits":["美国"],"sub_mode":"upgrade","end_date":"2027-01-01","order_no":"X","actual_opened_at":"2026-01-01","monthly_settle_cents":2,"term":"monthly"}"#);
|
|
|
+ let e = reject_read_only(&m, &CREATE_READ_ONLY).unwrap_err();
|
|
|
+ let s = format!("{e}");
|
|
|
+ for k in [
|
|
|
+ "annual_price_cents",
|
|
|
+ "monthly_settle_cents",
|
|
|
+ "end_date",
|
|
|
+ "line_exits",
|
|
|
+ "sub_mode",
|
|
|
+ "order_no",
|
|
|
+ "actual_opened_at",
|
|
|
+ ] {
|
|
|
+ assert!(s.contains(k), "未点名 {k}:{s}");
|
|
|
+ }
|
|
|
+ assert!(!s.contains("term"), "term 是新增态唯一入参,⛔ 拒收:{s}");
|
|
|
+ let ok = map(r#"{"customer_id":"C1","plan_id":"P1","term":"monthly"}"#);
|
|
|
+ assert!(reject_read_only(&ok, &CREATE_READ_ONLY).is_ok());
|
|
|
}
|
|
|
- if let Some(k) = p.push_like(body.keyword.as_deref()) {
|
|
|
- w.push(format!(
|
|
|
- "(s.contract_id LIKE {k} OR s.plan_id LIKE {k} OR EXISTS (SELECT 1 FROM customer ks \
|
|
|
- WHERE ks.customer_id = s.customer_id AND ks.customer_name LIKE {k}))"
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ #[allow(non_snake_case)] // 测试名用中文直述判据口径(错误码后缀保持大写更易检索)
|
|
|
+ fn 修改白名单两列其余键点名且换套餐走M229() {
|
|
|
+ let swap = map(r#"{"plan_id":"P2"}"#);
|
|
|
+ assert!(matches!(
|
|
|
+ reject_update_payload(&swap),
|
|
|
+ Err(e) if format!("{e}").contains("KLT-M229") || format!("{e:?}").contains("M229")
|
|
|
));
|
|
|
+ let bad = map(r#"{"end_date":"2027-01-01","term":"monthly","status":"active"}"#);
|
|
|
+ let s = format!("{}", reject_update_payload(&bad).unwrap_err());
|
|
|
+ for k in ["end_date", "term", "status"] {
|
|
|
+ assert!(s.contains(k), "未点名 {k}:{s}");
|
|
|
+ }
|
|
|
+ assert!(reject_update_payload(&map(r#"{"trial_months":3}"#)).is_ok());
|
|
|
+ assert!(reject_update_payload(&Map::new()).is_ok());
|
|
|
}
|
|
|
- if let Some(c) = p.push_eq(body.customer_id.as_deref()) {
|
|
|
- w.push(format!("s.customer_id = {c}::text"));
|
|
|
+
|
|
|
+ fn row(status: &str, start: Option<&str>, end: Option<&str>) -> SubRow {
|
|
|
+ SubRow {
|
|
|
+ subscription_id: "SUB-1".to_string(),
|
|
|
+ customer_id: "C1".to_string(),
|
|
|
+ contract_id: None,
|
|
|
+ contract_item_id: None,
|
|
|
+ plan_id: Some("P1".to_string()),
|
|
|
+ plan_name: Some("标准档".to_string()),
|
|
|
+ plan_kind: Some("fixed".to_string()),
|
|
|
+ plan_owner_customer_id: None,
|
|
|
+ status: status.to_string(),
|
|
|
+ use_category: Some("office".to_string()),
|
|
|
+ sub_mode: Some("upgrade".to_string()),
|
|
|
+ line_exits: None,
|
|
|
+ line_exit_key: Some("中国香港".to_string()),
|
|
|
+ start_date: start.map(str::to_string),
|
|
|
+ end_date: end.map(str::to_string),
|
|
|
+ term: Some("yearly".to_string()),
|
|
|
+ trial_months: None,
|
|
|
+ discount_monthly_cents: None,
|
|
|
+ annual_price_cents: Some("2000000".to_string()),
|
|
|
+ monthly_settle_cents: Some("166666".to_string()),
|
|
|
+ quota_slots: "10".to_string(),
|
|
|
+ replaces_subscription_id: None,
|
|
|
+ order_no: None,
|
|
|
+ actual_opened_at: None,
|
|
|
+ effective_date: None,
|
|
|
+ expire_date: None,
|
|
|
+ created_at: "2026-01-01".to_string(),
|
|
|
+ row_version: "1".to_string(),
|
|
|
+ }
|
|
|
}
|
|
|
- if let Some(c) = p.push_eq(body.contract_id.as_deref()) {
|
|
|
- w.push(format!("s.contract_id = {c}::text"));
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn 终态状态不被读侧推导覆盖() {
|
|
|
+ let t = "2026-11-09";
|
|
|
+ // 库值=生效中,日期已过 ⇒ 推导成已到期(本轮⛔ 日终翻转任务)
|
|
|
+ let (k, l, n) = status_display(&row("active", Some("2025-01-01"), Some("2025-12-31")), t);
|
|
|
+ assert_eq!(k, "expired");
|
|
|
+ assert_eq!(l, "已到期");
|
|
|
+ assert!(n.is_none());
|
|
|
+ // 终态(已退订/已替换)原样保留,⛔ 被日期改写
|
|
|
+ let (k2, _, _) = status_display(&row("cancelled", Some("2025-01-01"), Some("2026-12-31")), t);
|
|
|
+ assert_eq!(k2, "cancelled");
|
|
|
+ let (k3, _, _) = status_display(&row("replaced", Some("2025-01-01"), Some("2026-12-31")), t);
|
|
|
+ assert_eq!(k3, "replaced");
|
|
|
+ // 待生效
|
|
|
+ let (k4, _, _) = status_display(&row("pending", Some("2027-01-01"), Some("2027-12-31")), t);
|
|
|
+ assert_eq!(k4, "pending");
|
|
|
+ // 日期缺失 ⇒ 回库值+说明(⛔ 凭空造一个状态)
|
|
|
+ let (k5, _, n5) = status_display(&row("active", None, None), t);
|
|
|
+ assert_eq!(k5, "active");
|
|
|
+ assert!(n5.is_some());
|
|
|
}
|
|
|
- if let Some(s) = p.push_eq(body.status.as_deref()) {
|
|
|
- w.push(format!("s.status = {s}::text"));
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn 终态订阅不可修改不可删除() {
|
|
|
+ let t = "2026-11-09";
|
|
|
+ assert!(terminal_guard(&row("expired", Some("2025-01-01"), Some("2025-12-31")), t, "删除").is_ok());
|
|
|
+ assert!(terminal_guard(&row("cancelled", Some("2025-01-01"), Some("2026-12-31")), t, "删除").is_err());
|
|
|
+ assert!(terminal_guard(&row("replaced", Some("2025-01-01"), Some("2026-12-31")), t, "修改").is_err());
|
|
|
}
|
|
|
|
|
|
- let from_where = format!("FROM subscription s {}", p.where_clause(&w));
|
|
|
- let n = match total(state.db.as_ref(), &from_where, p.values()).await {
|
|
|
- Ok(n) => n,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- let (lim, off) = p.push_page(&body.pg);
|
|
|
- let sql = format!(
|
|
|
- "{SELECT_COLS} FROM subscription s {} \
|
|
|
- ORDER BY s.created_at DESC, s.subscription_id LIMIT {lim} OFFSET {off}",
|
|
|
- p.where_clause(&w)
|
|
|
- );
|
|
|
- let rows = match state.db.query_all::<SubRow>(&sql, p.values()).await {
|
|
|
- Ok(r) => r,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- let cids: Vec<String> = rows.iter().map(|r| r.customer_id.clone()).collect();
|
|
|
- let pids: Vec<String> = rows.iter().filter_map(|r| r.plan_id.clone()).collect();
|
|
|
- let names = match pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &cids).await {
|
|
|
- Ok(m) => m,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- let plans = match pairs_by(state.db.as_ref(), "catalog_plan", "plan_id", "plan_name", &pids).await {
|
|
|
- Ok(m) => m,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- json_ok(json!({
|
|
|
- "items": rows
|
|
|
- .iter()
|
|
|
- .map(|r| to_json(
|
|
|
- r,
|
|
|
- names.get(&r.customer_id).and_then(|v| v.first()).map(String::as_str),
|
|
|
- r.plan_id.as_deref().and_then(|id| plans.get(id).and_then(|v| v.first())).map(String::as_str),
|
|
|
- ))
|
|
|
- .collect::<Vec<Value>>(),
|
|
|
- "total": n,
|
|
|
- "page": body.pg.page,
|
|
|
- "page_size": body.pg.page_size,
|
|
|
- "columns_pending": COLUMNS_PENDING,
|
|
|
- }))
|
|
|
-}
|
|
|
+ #[test]
|
|
|
+ fn 金额出参一处折算点() {
|
|
|
+ let v = money_json(&row("active", Some("2026-01-01"), Some("2026-12-31")));
|
|
|
+ assert_eq!(v["annual_price_cents"], json!(2000000));
|
|
|
+ assert_eq!(v["monthly_settle_cents"], json!(166666));
|
|
|
+ assert_eq!(
|
|
|
+ v["monthly_settle_display"].as_str().unwrap(),
|
|
|
+ "2000000(折算 166666/月)"
|
|
|
+ );
|
|
|
+ }
|
|
|
|
|
|
-pub async fn get(
|
|
|
- State(state): State<AppState>,
|
|
|
- RequireAuth(auth): RequireAuth,
|
|
|
- DataBody(body): DataBody<SubscriptionGetReq>,
|
|
|
-) -> Response {
|
|
|
- match scoped_sub(&state, &auth, &trimmed(&body.subscription_id)).await {
|
|
|
- Ok(Some(r)) => {
|
|
|
- let cids = vec![r.customer_id.clone()];
|
|
|
- let pids = r.plan_id.clone().into_iter().collect::<Vec<String>>();
|
|
|
- let names = match pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &cids).await {
|
|
|
- Ok(m) => m,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- let plans = match pairs_by(state.db.as_ref(), "catalog_plan", "plan_id", "plan_name", &pids).await {
|
|
|
- Ok(m) => m,
|
|
|
- Err(e) => return json_err(e),
|
|
|
- };
|
|
|
- let mut v = to_json(
|
|
|
- &r,
|
|
|
- names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str),
|
|
|
- r.plan_id.as_deref().and_then(|id| plans.get(id).and_then(|x| x.first())).map(String::as_str),
|
|
|
+ #[test]
|
|
|
+ fn 源码静态断言_除月数与冲突改写只有一处实现() {
|
|
|
+ let src = include_str!("subscription.rs");
|
|
|
+ let lower = src.to_lowercase();
|
|
|
+ let conflict = concat!("ON CON", "FLICT");
|
|
|
+ assert!(!src.contains(conflict), "UDS ⛔ 支持冲突改写");
|
|
|
+ assert!(
|
|
|
+ !lower.contains(concat!(" cur", "rent_date")),
|
|
|
+ "⛔ 在 SQL 里取当前日期(时区口径须与 today() 一致)"
|
|
|
+ );
|
|
|
+ // 月结算与额度求和的唯一实现落在 bos-invariant,本模块⛔ 自行「金额 ÷12」/自行 SUM。
|
|
|
+ // ⚠️ 只锁**金额侧**写法:`add_months_clamped` 里的 `total / 12` 是日期取模,
|
|
|
+ // 与月结算算式无关,按裸 `/ 12` 断言会把正确的日期数学一起判死。
|
|
|
+ for pat in [concat!("cents / 1", "2"), concat!("cents/1", "2")] {
|
|
|
+ assert!(
|
|
|
+ !src.contains(pat),
|
|
|
+ "月结算标准金额只能经 monthly_settle_of 折算(05 册 §3.3 唯一算式)"
|
|
|
);
|
|
|
- v["columns_pending"] = json!(COLUMNS_PENDING);
|
|
|
- json_ok(v)
|
|
|
- }
|
|
|
- Ok(None) => json_ok(json!({
|
|
|
- "subscription_id": null,
|
|
|
- "columns_pending": COLUMNS_PENDING,
|
|
|
- "message": "订阅不存在或超出当前账号可见范围",
|
|
|
- })),
|
|
|
- Err(e) => json_err(e),
|
|
|
+ }
|
|
|
+ assert!(
|
|
|
+ !src.to_uppercase().contains(concat!("SU", "M(")),
|
|
|
+ "在用额度求和只能经 in_use_quota_sum_batch(§5.6 唯一实现)"
|
|
|
+ );
|
|
|
+ assert!(
|
|
|
+ !src.contains(concat!(".me", "ssage()")),
|
|
|
+ "BosError ⛔ 提供该访问器"
|
|
|
+ );
|
|
|
+ assert!(src.contains("check_i6_subscription"), "I6 判据必须走不变量库");
|
|
|
+ assert!(src.contains("check_subscription_deletable"), "删除阻塞必须走不变量库(M227/M230 同源)");
|
|
|
}
|
|
|
}
|