|
@@ -0,0 +1,1938 @@
|
|
|
|
|
+//! 第 6 册:计费与对账出账(RECON 两阶段 + 对账清单/批次详情/账单明细/出账更正/出账配置)。
|
|
|
|
|
+//!
|
|
|
|
|
+//! 数据面一律经 SEOH UDS(`bos.` 项目库),DDL 由开发者空间 DM 通道发布,见
|
|
|
|
|
+//! `temp/dm_recon_models.py`。金额一律整数分;业务日口径 Asia/Shanghai。
|
|
|
|
|
+//!
|
|
|
|
|
+//! 一期取数口径(与设计册的差异,均已在交付说明中登记):
|
|
|
|
|
+//! 1. 第 5 册工单/开停未实现 ⇒ 无 `open_stop_facts`,分账号按现有 `sub_account`
|
|
|
|
|
+//! 且 `status <> 'not_opened'` 视为本期在期,天数取订阅本期计费天数(整月计)。
|
|
|
|
|
+//! 2. 成本明细未落到客户/省份/运营商维度 ⇒ 应收的成本抵扣为 0、`cost_snapshot=[]`,
|
|
|
|
|
+//! 对账清单「总成本」如实为 0(⛔ 不按客户摊派)。
|
|
|
|
|
+//! 3. 客户归属区域 = 客户所属运营商/合作伙伴的区域;两者皆空时落空串(表列 NOT NULL)。
|
|
|
|
|
+
|
|
|
|
|
+use axum::extract::{Query, State};
|
|
|
|
|
+use axum::response::Response;
|
|
|
|
|
+use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
|
|
|
|
|
+use bos_api::AppState;
|
|
|
|
|
+use bos_core::error::KltCode;
|
|
|
|
|
+use bos_core::{BosError, RoleCode};
|
|
|
|
|
+use bos_platform::clients::uds::UdsClient;
|
|
|
|
|
+use bos_scope::AuthContext;
|
|
|
|
|
+use chrono::{Datelike, Duration, NaiveDate, Utc};
|
|
|
|
|
+use serde::Deserialize;
|
|
|
|
|
+use serde_json::{json, Value};
|
|
|
|
|
+
|
|
|
|
|
+use super::listq::{next_seq, Params};
|
|
|
|
|
+
|
|
|
|
|
+// ───────────────────────────── 通用小工具 ─────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+fn s(v: &Value, k: &str) -> String {
|
|
|
|
|
+ match v.get(k) {
|
|
|
|
|
+ Some(Value::String(x)) => x.clone(),
|
|
|
|
|
+ Some(Value::Number(n)) => n.to_string(),
|
|
|
|
|
+ Some(Value::Bool(b)) => b.to_string(),
|
|
|
|
|
+ Some(Value::Null) | None => String::new(),
|
|
|
|
|
+ Some(other) => other.to_string(),
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn os(v: &Value, k: &str) -> Option<String> {
|
|
|
|
|
+ let x = s(v, k);
|
|
|
|
|
+ if x.is_empty() { None } else { Some(x) }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn i(v: &Value, k: &str) -> i64 {
|
|
|
|
|
+ s(v, k).parse().unwrap_or(0)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn oi(v: &Value, k: &str) -> Option<i64> {
|
|
|
|
|
+ s(v, k).parse().ok()
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn f(v: &Value, k: &str) -> f64 {
|
|
|
|
|
+ s(v, k).parse().unwrap_or(0.0)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn b(v: &Value, k: &str) -> bool {
|
|
|
|
|
+ matches!(s(v, k).as_str(), "true" | "t" | "1")
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// UDS 查询:统一剥 `QueryData` 壳,取 `rows`(列值多为字符串,按 `s()`/`i()` 读取)。
|
|
|
|
|
+async fn qry(db: &UdsClient, sql: &str, ps: &[Value]) -> Result<Vec<Value>, BosError> {
|
|
|
|
|
+ Ok(db.query(sql, ps).await?.rows)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// DML 带步骤标签(失败时日志能直接读出卡在哪一步)。
|
|
|
|
|
+async fn dmlx(db: &UdsClient, tag: &str, sql: &str, ps: &[Value]) -> Result<u64, BosError> {
|
|
|
|
|
+ db.dml(sql, ps).await.map_err(|e| {
|
|
|
|
|
+ tracing::warn!(step = tag, err = %err_text(&e), "对账引擎 DML 失败");
|
|
|
|
|
+ BosError::internal(format!("{}: {}", tag, err_text(&e)))
|
|
|
|
|
+ })
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn ok(data: Value) -> Response {
|
|
|
|
|
+ json_ok(data)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// 错误原文(`BosError` 只有 `Biz{message}` 一支带文案,其余交给 `Display`)。
|
|
|
|
|
+fn err_text(e: &BosError) -> String {
|
|
|
|
|
+ match e {
|
|
|
|
|
+ BosError::Biz { message, .. } => message.clone(),
|
|
|
|
|
+ other => other.to_string(),
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn can_view(auth: &AuthContext) -> Result<(), BosError> {
|
|
|
|
|
+ auth.require_roles(&[
|
|
|
|
|
+ RoleCode::Admin,
|
|
|
|
|
+ RoleCode::OpsMain,
|
|
|
|
|
+ RoleCode::OpsSub,
|
|
|
|
|
+ RoleCode::Operator,
|
|
|
|
|
+ RoleCode::Partner,
|
|
|
|
|
+ RoleCode::TeamLead,
|
|
|
|
|
+ ])
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn can_admin(auth: &AuthContext) -> Result<(), BosError> {
|
|
|
|
|
+ auth.require_roles(&[RoleCode::Admin])
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn today() -> NaiveDate {
|
|
|
|
|
+ // 业务日 = Asia/Shanghai(UTC+8)。
|
|
|
|
|
+ (Utc::now() + Duration::hours(8)).date_naive()
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn period_of(d: NaiveDate) -> String {
|
|
|
|
|
+ format!("{:04}-{:02}", d.year(), d.month())
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn parse_period(p: &str) -> Result<NaiveDate, BosError> {
|
|
|
|
|
+ let bytes = p.as_bytes();
|
|
|
|
|
+ let shape_ok = bytes.len() == 7 && bytes[4] == b'-'
|
|
|
|
|
+ && bytes[..4].iter().all(u8::is_ascii_digit)
|
|
|
|
|
+ && bytes[5..].iter().all(u8::is_ascii_digit);
|
|
|
|
|
+ if !shape_ok {
|
|
|
|
|
+ return Err(BosError::bad_params(format!(
|
|
|
|
|
+ "period 须为 YYYY-MM(11103):{p}"
|
|
|
|
|
+ )));
|
|
|
|
|
+ }
|
|
|
|
|
+ NaiveDate::from_ymd_opt(
|
|
|
|
|
+ p[..4].parse().unwrap_or(0),
|
|
|
|
|
+ p[5..].parse().unwrap_or(0),
|
|
|
|
|
+ 1,
|
|
|
|
|
+ )
|
|
|
|
|
+ .ok_or_else(|| BosError::bad_params(format!("period 非法(11103):{p}")))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn month_end(first: NaiveDate) -> NaiveDate {
|
|
|
|
|
+ let (y, m) = (first.year(), first.month());
|
|
|
|
|
+ let next = if m == 12 {
|
|
|
|
|
+ NaiveDate::from_ymd_opt(y + 1, 1, 1)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ NaiveDate::from_ymd_opt(y, m + 1, 1)
|
|
|
|
|
+ }
|
|
|
|
|
+ .unwrap_or(first);
|
|
|
|
|
+ next - Duration::days(1)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn last_closed_period() -> String {
|
|
|
|
|
+ let t = today();
|
|
|
|
|
+ let first = NaiveDate::from_ymd_opt(t.year(), t.month(), 1).unwrap_or(t);
|
|
|
|
|
+ period_of(first - Duration::days(1))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn add_months(d: NaiveDate, n: i32) -> NaiveDate {
|
|
|
|
|
+ let m0 = d.year() * 12 + d.month() as i32 - 1 + n;
|
|
|
|
|
+ let (y, m) = (m0 / 12, (m0 % 12 + 1) as u32);
|
|
|
|
|
+ let day = d.day().min(month_end(NaiveDate::from_ymd_opt(y, m, 1).unwrap()).day());
|
|
|
|
|
+ NaiveDate::from_ymd_opt(y, m, day).unwrap_or(d)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn normalize_period(v: &str) -> String {
|
|
|
|
|
+ let t = v.trim();
|
|
|
|
|
+ if t.len() == 7 { t.to_string() } else { String::new() }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// 舍入:四舍五入(正数;比例/折算与 PostgreSQL round(numeric) 同口径)。
|
|
|
|
|
+fn round_half_up(n: i128, d: i128) -> i64 {
|
|
|
|
|
+ if d == 0 { return 0; }
|
|
|
|
|
+ let r = (n * 2 + d) / (d * 2);
|
|
|
|
|
+ r as i64
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn holder_table(t: &str) -> Option<(&'static str, &'static str)> {
|
|
|
|
|
+ match t {
|
|
|
|
|
+ "operator" => Some(("operator", "operator_id")),
|
|
|
|
|
+ "partner" => Some(("partner", "partner_id")),
|
|
|
|
|
+ "ops_team" => Some(("ops_team", "team_id")),
|
|
|
|
|
+ _ => None,
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn derive_status(status: &str) -> &'static str {
|
|
|
|
|
+ match status {
|
|
|
|
|
+ "executed" => "settled",
|
|
|
|
|
+ "failed" => "abnormal",
|
|
|
|
|
+ _ => "unsettled",
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────── 1. 分成参数摘要(分成管理页) ───────────────────────
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct ShareParamSummaryReq {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub holders: Vec<ShareParamRef>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize, Clone)]
|
|
|
|
|
+pub struct ShareParamRef {
|
|
|
|
|
+ pub holder_type: String,
|
|
|
|
|
+ pub holder_id: String,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn share_param_summary(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(body): DataBody<ShareParamSummaryReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ if body.holders.len() > 500 {
|
|
|
|
|
+ return json_err(BosError::bad_params("holders 最多 500 项(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ let mut out = Vec::with_capacity(body.holders.len());
|
|
|
|
|
+ for h in &body.holders {
|
|
|
|
|
+ let Some((table, idcol)) = holder_table(&h.holder_type) else {
|
|
|
|
|
+ return json_err(BosError::bad_params(format!(
|
|
|
|
|
+ "holder_type 非法(11103):{}", h.holder_type
|
|
|
|
|
+ )));
|
|
|
|
|
+ };
|
|
|
|
|
+ let sql = format!(
|
|
|
|
|
+ "SELECT {idcol} AS id, COALESCE(settle_mode,'') AS settle_mode, \
|
|
|
|
|
+ CAST(settle_value AS TEXT) AS settle_value FROM {table} WHERE {idcol} = $1"
|
|
|
|
|
+ );
|
|
|
|
|
+ let rows = match qry(&state.db, &sql, &[Value::String(h.holder_id.clone())]).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let Some(row) = rows.first() else {
|
|
|
|
|
+ return json_err(BosError::not_found(format!(
|
|
|
|
|
+ "分成方不存在(11104):{} {}", h.holder_type, h.holder_id
|
|
|
|
|
+ )));
|
|
|
|
|
+ };
|
|
|
|
|
+ let mode = s(row, "settle_mode");
|
|
|
|
|
+ let cnt_sql = match h.holder_type.as_str() {
|
|
|
|
|
+ "operator" => {
|
|
|
|
|
+ "SELECT COUNT(*) AS n FROM customer WHERE operator_id = $1 AND deleted_at IS NULL"
|
|
|
|
|
+ .to_string()
|
|
|
|
|
+ }
|
|
|
|
|
+ "partner" => {
|
|
|
|
|
+ "SELECT COUNT(*) AS n FROM customer WHERE partner_id = $1 AND deleted_at IS NULL"
|
|
|
|
|
+ .to_string()
|
|
|
|
|
+ }
|
|
|
|
|
+ _ => "SELECT COUNT(DISTINCT customer_id) AS n FROM customer_team_belong \
|
|
|
|
|
+ WHERE team_id = $1 AND is_current = true"
|
|
|
|
|
+ .to_string(),
|
|
|
|
|
+ };
|
|
|
|
|
+ let cnt_rows = match qry(&state.db, &cnt_sql, &[Value::String(h.holder_id.clone())]).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let customer_count = cnt_rows.first().map(|r| i(r, "n")).unwrap_or(0);
|
|
|
|
|
+ let configured = !mode.is_empty();
|
|
|
|
|
+ out.push(json!({
|
|
|
|
|
+ "holder_type": h.holder_type,
|
|
|
|
|
+ "holder_id": h.holder_id,
|
|
|
|
|
+ "configured": configured,
|
|
|
|
|
+ "share_mode": if configured { Value::String(mode) } else { Value::Null },
|
|
|
|
|
+ "share_value": if configured {
|
|
|
|
|
+ Value::from(f(row, "settle_value"))
|
|
|
|
|
+ } else {
|
|
|
|
|
+ Value::Null
|
|
|
|
|
+ },
|
|
|
|
|
+ "customer_count": customer_count,
|
|
|
|
|
+ }));
|
|
|
|
|
+ }
|
|
|
|
|
+ ok(json!({ "items": out }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 2. 出账配置 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+async fn ensure_config(db: &UdsClient) -> Result<Value, BosError> {
|
|
|
|
|
+ let rows = qry(db,
|
|
|
|
|
+ "SELECT id, default_recon_day, effective_mode, row_version, \
|
|
|
|
|
+ COALESCE(updated_by,'') AS updated_by, CAST(updated_at AS TEXT) AS updated_at \
|
|
|
|
|
+ FROM billing_config WHERE id = 1",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ if let Some(r) = rows.first() {
|
|
|
|
|
+ return Ok(r.clone());
|
|
|
|
|
+ }
|
|
|
|
|
+ db.dml(
|
|
|
|
|
+ "INSERT INTO billing_config (id, default_recon_day, effective_mode, row_version) \
|
|
|
|
|
+ SELECT 1, 5, 'period_snapshot', 1 WHERE NOT EXISTS (SELECT 1 FROM billing_config WHERE id = 1)",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ let rows = qry(db,
|
|
|
|
|
+ "SELECT id, default_recon_day, effective_mode, row_version, \
|
|
|
|
|
+ COALESCE(updated_by,'') AS updated_by, CAST(updated_at AS TEXT) AS updated_at \
|
|
|
|
|
+ FROM billing_config WHERE id = 1",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ rows.into_iter().next().ok_or_else(|| BosError::internal("billing_config 初始化失败"))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn billing_config_get(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let cfg = match ensure_config(&state.db).await {
|
|
|
|
|
+ Ok(c) => c,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let ops = match qry(&state.db,
|
|
|
|
|
+ "SELECT operator_id, COALESCE(name,'') AS name, COALESCE(brand,'') AS brand, \
|
|
|
|
|
+ COALESCE(region_node_id,'') AS region_node_id, recon_day, COALESCE(pay_cycle,'') AS pay_cycle \
|
|
|
|
|
+ FROM operator ORDER BY operator_id",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let operators: Vec<Value> = ops.iter().map(|r| json!({
|
|
|
|
|
+ "operator_id": s(r, "operator_id"),
|
|
|
|
|
+ "name": s(r, "name"),
|
|
|
|
|
+ "brand": s(r, "brand"),
|
|
|
|
|
+ "region_node_id": s(r, "region_node_id"),
|
|
|
|
|
+ "region_label": Value::Null,
|
|
|
|
|
+ "recon_day": oi(r, "recon_day"),
|
|
|
|
|
+ "pay_cycle": os(r, "pay_cycle"),
|
|
|
|
|
+ "editable": true,
|
|
|
|
|
+ })).collect();
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "default_recon_day": oi(&cfg, "default_recon_day").unwrap_or(5),
|
|
|
|
|
+ "effective_mode": s(&cfg, "effective_mode"),
|
|
|
|
|
+ "row_version": oi(&cfg, "row_version").unwrap_or(1),
|
|
|
|
|
+ "updated_by": s(&cfg, "updated_by"),
|
|
|
|
|
+ "updated_at": s(&cfg, "updated_at"),
|
|
|
|
|
+ "operators": operators,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct BillingConfigUpdateReq {
|
|
|
|
|
+ pub default_recon_day: i64,
|
|
|
|
|
+ pub effective_mode: String,
|
|
|
|
|
+ pub row_version: i64,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub operators: Option<Value>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub confirm_reset: Option<bool>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn billing_config_update(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(body): DataBody<BillingConfigUpdateReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_admin(&auth) { return json_err(e); }
|
|
|
|
|
+ if body.operators.is_some() {
|
|
|
|
|
+ return json_err(BosError::bad_params(
|
|
|
|
|
+ "运营商对账日与付款周期由 operator/update 写(11103):config_update 禁传 operators",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ if !(1..=28).contains(&body.default_recon_day) {
|
|
|
|
|
+ return json_err(BosError::bad_params("default_recon_day 取值域 1–28(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if !matches!(body.effective_mode.as_str(), "period_snapshot" | "live_at_billing") {
|
|
|
|
|
+ return json_err(BosError::bad_params(
|
|
|
|
|
+ "effective_mode 仅 period_snapshot / live_at_billing(11103)",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ if body.row_version < 1 {
|
|
|
|
|
+ return json_err(BosError::bad_params("row_version 必填(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ let cfg = match ensure_config(&state.db).await { Ok(c) => c, Err(e) => return json_err(e) };
|
|
|
|
|
+ // 提交同值 ⇒ changed=0、不动 row_version(不写审计)。
|
|
|
|
|
+ if oi(&cfg, "default_recon_day") == Some(body.default_recon_day)
|
|
|
|
|
+ && s(&cfg, "effective_mode") == body.effective_mode
|
|
|
|
|
+ {
|
|
|
|
|
+ return ok(json!({
|
|
|
|
|
+ "changed": 0,
|
|
|
|
|
+ "row_version": oi(&cfg, "row_version").unwrap_or(1),
|
|
|
|
|
+ "default_recon_day": body.default_recon_day,
|
|
|
|
|
+ "effective_mode": body.effective_mode,
|
|
|
|
|
+ }));
|
|
|
|
|
+ }
|
|
|
|
|
+ let uid = auth.user_id.clone();
|
|
|
|
|
+ let sql = "UPDATE billing_config SET default_recon_day = $1, effective_mode = $2, \
|
|
|
|
|
+ row_version = row_version + 1, updated_by = $3, updated_at = now() \
|
|
|
|
|
+ WHERE id = 1 AND row_version = $4";
|
|
|
|
|
+ let affected = match state.db.dml(sql, &[
|
|
|
|
|
+ json!(body.default_recon_day),
|
|
|
|
|
+ json!(body.effective_mode),
|
|
|
|
|
+ json!(uid),
|
|
|
|
|
+ json!(body.row_version),
|
|
|
|
|
+ ]).await {
|
|
|
|
|
+ Ok(n) => n,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if affected == 0 {
|
|
|
|
|
+ return json_err(BosError::klt(
|
|
|
|
|
+ KltCode::S407,
|
|
|
|
|
+ "出账配置已被他人修改,请刷新后重试(KLT-S407)",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "changed": 1,
|
|
|
|
|
+ "row_version": body.row_version + 1,
|
|
|
|
|
+ "default_recon_day": body.default_recon_day,
|
|
|
|
|
+ "effective_mode": body.effective_mode,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 3. 期次下拉 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+pub async fn recon_periods(State(state): State<AppState>, RequireAuth(auth): RequireAuth) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT period FROM ( \
|
|
|
|
|
+ SELECT period FROM billing_receivable \
|
|
|
|
|
+ UNION SELECT period FROM reconcile_batch \
|
|
|
|
|
+ UNION SELECT period FROM bill_detail WHERE status = 'active' \
|
|
|
|
|
+ ) p ORDER BY period DESC LIMIT 36",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let items: Vec<String> = rows.iter().map(|r| s(r, "period")).filter(|p| !p.is_empty()).collect();
|
|
|
|
|
+ // 契约 14.1 ②:`{periods: string[]}`(倒序;⚠️ 与 list 行集不同,⛔ 合并两行源)。
|
|
|
|
|
+ ok(json!({ "periods": items }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 4. 对账清单 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct ReconListReq {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub period: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub holder_type: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub holder_kw: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub reconcile_status: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub status: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub include_zero_lines: Option<bool>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub keyword: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub page: Option<i64>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub page_size: Option<i64>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn recon_list(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(req): DataBody<ReconListReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let period = match req.period.as_deref().map(normalize_period) {
|
|
|
|
|
+ Some(p) if !p.is_empty() => p,
|
|
|
|
|
+ _ => last_closed_period(),
|
|
|
|
|
+ };
|
|
|
|
|
+ let page = req.page.unwrap_or(0).max(0);
|
|
|
|
|
+ let size = req.page_size.unwrap_or(20).clamp(1, 100);
|
|
|
|
|
+ let offset = page * size;
|
|
|
|
|
+ // 出账状态是派生筛选项(executed→settled/failed→abnormal/其余 unsettled),
|
|
|
|
|
+ // 必须在 SQL 内判定:分页后再筛会少行、且 total 与页脚对不上。
|
|
|
|
|
+ let reconcile = req.reconcile_status.as_deref().filter(|x| !x.is_empty());
|
|
|
|
|
+ if let Some(rs) = reconcile {
|
|
|
|
|
+ if !matches!(rs, "settled" | "abnormal" | "unsettled") {
|
|
|
|
|
+ return json_err(BosError::bad_params("reconcile_status 非法(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ let reconcile_pred = |alias: &str| -> String {
|
|
|
|
|
+ match reconcile {
|
|
|
|
|
+ Some("settled") => format!("{alias}.status = 'executed'"),
|
|
|
|
|
+ Some("abnormal") => format!("{alias}.status = 'failed'"),
|
|
|
|
|
+ Some(_) => format!("{alias}.status NOT IN ('executed','failed')"),
|
|
|
|
|
+ None => String::new(),
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ let mut p = Params::default();
|
|
|
|
|
+ let mut where_parts = vec![format!("b.period = {}", p.push(json!(period)))];
|
|
|
|
|
+ if let Some(t) = req.holder_type.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ if holder_table(t).is_none() {
|
|
|
|
|
+ return json_err(BosError::bad_params("holder_type 非法(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ where_parts.push(format!("b.holder_type = {}", p.push(json!(t))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.holder_kw.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ where_parts.push(format!("b.holder_name ILIKE {}", p.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(st) = req.status.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ if !matches!(st, "pending" | "executed" | "failed" | "voided") {
|
|
|
|
|
+ return json_err(BosError::bad_params("status 非法(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ where_parts.push(format!("b.status = {}", p.push(json!(st))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if !reconcile_pred("b").is_empty() {
|
|
|
|
|
+ where_parts.push(reconcile_pred("b"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(new_batch) = req.keyword.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ where_parts.push(format!("b.batch_no ILIKE {}", p.push(json!(format!("%{}%", new_batch.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ let include_zero = req.include_zero_lines.unwrap_or(false);
|
|
|
|
|
+ if !include_zero {
|
|
|
|
|
+ where_parts.push("COALESCE(d.cnt, 0) > 0".to_string());
|
|
|
|
|
+ }
|
|
|
|
|
+ let where_sql = where_parts.join(" AND ");
|
|
|
|
|
+
|
|
|
|
|
+ let base = format!(
|
|
|
|
|
+ "FROM reconcile_batch b \
|
|
|
|
|
+ LEFT JOIN (SELECT batch_no, COUNT(*) AS cnt, \
|
|
|
|
|
+ COALESCE(SUM(share_base_cents),0) AS base, \
|
|
|
|
|
+ COALESCE(SUM(share_amount_cents),0) AS share \
|
|
|
|
|
+ FROM bill_detail WHERE status = 'active' GROUP BY batch_no) d \
|
|
|
|
|
+ ON d.batch_no = b.batch_no \
|
|
|
|
|
+ WHERE {where_sql}"
|
|
|
|
|
+ );
|
|
|
|
|
+
|
|
|
|
|
+ // 出账状态三态在 SQL 外派生,避免与前端枚举漂移。
|
|
|
|
|
+ let rows_sql = format!(
|
|
|
|
|
+ "SELECT b.batch_no, b.period, b.holder_type, b.holder_id, b.holder_name, \
|
|
|
|
|
+ CAST(b.recon_date AS TEXT) AS recon_date, b.trigger_type, b.status, \
|
|
|
|
|
+ COALESCE(d.cnt,0) AS detail_count, COALESCE(d.base,0) AS base_cents, \
|
|
|
|
|
+ COALESCE(d.share,0) AS share_cents, b.operator_user_id, \
|
|
|
|
|
+ CAST(b.executed_at AS TEXT) AS executed_at, COALESCE(b.fail_reason,'') AS fail_reason \
|
|
|
|
|
+ {base} ORDER BY b.batch_no DESC LIMIT {size} OFFSET {offset}"
|
|
|
|
|
+ );
|
|
|
|
|
+ let rows = match qry(&state.db, &rows_sql, p.values()).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let total_rows = match qry(&state.db, &format!("SELECT COUNT(*) AS n {base}"), p.values()).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let total = total_rows.first().map(|r| i(r, "n")).unwrap_or(0);
|
|
|
|
|
+
|
|
|
|
|
+ let mut items = Vec::new();
|
|
|
|
|
+ for r in &rows {
|
|
|
|
|
+ let status = s(r, "status");
|
|
|
|
|
+ let derived = derive_status(&status);
|
|
|
|
|
+ items.push(json!({
|
|
|
|
|
+ "batch_no": s(r, "batch_no"),
|
|
|
|
|
+ "period": s(r, "period"),
|
|
|
|
|
+ "holder_type": s(r, "holder_type"),
|
|
|
|
|
+ "holder_id": s(r, "holder_id"),
|
|
|
|
|
+ "holder_name": s(r, "holder_name"),
|
|
|
|
|
+ "recon_date": s(r, "recon_date"),
|
|
|
|
|
+ "trigger_type": s(r, "trigger_type"),
|
|
|
|
|
+ "status": status,
|
|
|
|
|
+ "reconcile_status": derived,
|
|
|
|
|
+ "detail_count": i(r, "detail_count"),
|
|
|
|
|
+ "base_cents": i(r, "base_cents"),
|
|
|
|
|
+ "share_cents": i(r, "share_cents"),
|
|
|
|
|
+ "operator_user_id": os(r, "operator_user_id"),
|
|
|
|
|
+ "fail_reason": os(r, "fail_reason"),
|
|
|
|
|
+ }));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 统计卡:与列表同一行集(期 × 类型 × 分成方 × 批次状态 × 出账状态 × 单号关键字)。
|
|
|
|
|
+ // 基数/成本按应收去重(period × subscription_id);分成按(应收 × 分成方)且只认 executed。
|
|
|
|
|
+ let mut sp = Params::default();
|
|
|
|
|
+ let mut sw = vec![format!("b.period = {}", sp.push(json!(period)))];
|
|
|
|
|
+ if let Some(t) = req.holder_type.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ sw.push(format!("b.holder_type = {}", sp.push(json!(t))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.holder_kw.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ sw.push(format!("b.holder_name ILIKE {}", sp.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(st) = req.status.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ sw.push(format!("b.status = {}", sp.push(json!(st))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if !reconcile_pred("b").is_empty() {
|
|
|
|
|
+ sw.push(reconcile_pred("b"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.keyword.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ sw.push(format!("b.batch_no ILIKE {}", sp.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ let shared_join = format!(
|
|
|
|
|
+ "FROM bill_detail d JOIN reconcile_batch b ON b.batch_no = d.batch_no \
|
|
|
|
|
+ WHERE d.status = 'active' AND b.status = 'executed' AND {}",
|
|
|
|
|
+ sw.join(" AND ")
|
|
|
|
|
+ );
|
|
|
|
|
+ let share_rows = match qry(&state.db,
|
|
|
|
|
+ &format!("SELECT COALESCE(SUM(d.share_amount_cents),0) AS share {shared_join}"),
|
|
|
|
|
+ sp.values(),
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let total_share = share_rows.first().map(|r| i(r, "share")).unwrap_or(0);
|
|
|
|
|
+
|
|
|
|
|
+ let mut qp = Params::default();
|
|
|
|
|
+ let mut qw = vec![format!("r.period = {}", qp.push(json!(period)))];
|
|
|
|
|
+ if let Some(t) = req.holder_type.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ qw.push(format!("b2.holder_type = {}", qp.push(json!(t))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.holder_kw.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ qw.push(format!("b2.holder_name ILIKE {}", qp.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(st) = req.status.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ qw.push(format!("b2.status = {}", qp.push(json!(st))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if !reconcile_pred("b2").is_empty() {
|
|
|
|
|
+ qw.push(reconcile_pred("b2"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.keyword.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ qw.push(format!("b2.batch_no ILIKE {}", qp.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ // 除期次外无筛选时不能留空条件(否则 SQL 尾巴是 `AND )`),用 TRUE 占位。
|
|
|
|
|
+ let inner_pred = if qw.len() > 1 { qw[1..].join(" AND ") } else { "TRUE".to_string() };
|
|
|
|
|
+ let rec_rows = match qry(&state.db,
|
|
|
|
|
+ &format!(
|
|
|
|
|
+ "SELECT COALESCE(SUM(r.share_base_cents),0) AS base, \
|
|
|
|
|
+ COALESCE(SUM(r.cost_deduct_cents),0) AS cost \
|
|
|
|
|
+ FROM billing_receivable r \
|
|
|
|
|
+ WHERE r.period = $1 AND EXISTS ( \
|
|
|
|
|
+ SELECT 1 FROM bill_detail d2 JOIN reconcile_batch b2 ON b2.batch_no = d2.batch_no \
|
|
|
|
|
+ WHERE d2.period = r.period AND d2.subscription_id = r.subscription_id \
|
|
|
|
|
+ AND d2.status = 'active' AND b2.status = 'executed' AND {inner_pred})"
|
|
|
|
|
+ ),
|
|
|
|
|
+ qp.values(),
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let (total_base, total_cost) = rec_rows.first()
|
|
|
|
|
+ .map(|r| (i(r, "base"), i(r, "cost")))
|
|
|
|
|
+ .unwrap_or((0, 0));
|
|
|
|
|
+
|
|
|
|
|
+ let sum_rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT COUNT(DISTINCT period) AS n, COALESCE(MAX(period),'') AS latest \
|
|
|
|
|
+ FROM reconcile_batch WHERE status = 'executed'",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let reconciled_summary = match sum_rows.first() {
|
|
|
|
|
+ Some(r) if i(r, "n") > 0 => json!({
|
|
|
|
|
+ "count": i(r, "n"),
|
|
|
|
|
+ "latest": s(r, "latest"),
|
|
|
|
|
+ }),
|
|
|
|
|
+ _ => Value::Null,
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ let progress = match period_progress(&state.db, &period).await {
|
|
|
|
|
+ Ok(p) => p,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "items": items,
|
|
|
|
|
+ "total": total,
|
|
|
|
|
+ "page": page,
|
|
|
|
|
+ "page_size": size,
|
|
|
|
|
+ "stats": {
|
|
|
|
|
+ "total_base_cents": total_base,
|
|
|
|
|
+ "total_cost_cents": total_cost,
|
|
|
|
|
+ "total_share_cents": total_share,
|
|
|
|
|
+ },
|
|
|
|
|
+ "reconciled_summary": reconciled_summary,
|
|
|
|
|
+ "progress": progress,
|
|
|
|
|
+ "self_config": Value::Null,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// ③-1 期次出账进度:只随自然月变化(⛔ 随其余筛选变)。
|
|
|
|
|
+/// 口径:分成方集合=该期分成快照里的去重 (holder_type, holder_id);应出账日=该方对账日(无档案列则取默认对账日)。
|
|
|
|
|
+async fn period_progress(db: &UdsClient, period: &str) -> Result<Value, BosError> {
|
|
|
|
|
+ let default_day = qry(db,
|
|
|
|
|
+ "SELECT default_recon_day FROM billing_config WHERE id = 1",
|
|
|
|
|
+ &[],
|
|
|
|
|
+ ).await?.first().and_then(|r| oi(r, "default_recon_day")).unwrap_or(5);
|
|
|
|
|
+
|
|
|
|
|
+ let holders = qry(db,
|
|
|
|
|
+ "SELECT DISTINCT v.holder_type, v.holder_id, v.holder_name \
|
|
|
|
|
+ FROM billing_snapshot_share v WHERE v.period = $1 \
|
|
|
|
|
+ ORDER BY v.holder_type, v.holder_id",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ let batches = qry(db,
|
|
|
|
|
+ "SELECT batch_no, holder_type, holder_id, status FROM reconcile_batch \
|
|
|
|
|
+ WHERE period = $1 AND status IN ('pending','executed','failed')",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ let first = parse_period(period)?;
|
|
|
|
|
+ let today_d = today();
|
|
|
|
|
+
|
|
|
|
|
+ let mut items = Vec::new();
|
|
|
|
|
+ let (mut generated, mut not_due, mut overdue) = (0i64, 0i64, 0i64);
|
|
|
|
|
+ for h in &holders {
|
|
|
|
|
+ let ht = s(h, "holder_type");
|
|
|
|
|
+ let hid = s(h, "holder_id");
|
|
|
|
|
+ let day = if ht == "operator" {
|
|
|
|
|
+ qry(db, "SELECT recon_day FROM operator WHERE operator_id = $1", &[json!(hid)])
|
|
|
|
|
+ .await?
|
|
|
|
|
+ .first()
|
|
|
|
|
+ .and_then(|r| oi(r, "recon_day"))
|
|
|
|
|
+ .filter(|d| (1..=28).contains(d))
|
|
|
|
|
+ .unwrap_or(default_day)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ default_day
|
|
|
|
|
+ };
|
|
|
|
|
+ let expected = NaiveDate::from_ymd_opt(first.year(), first.month(), day.clamp(1, 28) as u32)
|
|
|
|
|
+ .unwrap_or(today_d);
|
|
|
|
|
+ let batch = batches.iter().find(|b| s(b, "holder_type") == ht && s(b, "holder_id") == hid);
|
|
|
|
|
+ let (status, batch_no) = match batch {
|
|
|
|
|
+ Some(b) => {
|
|
|
|
|
+ let st = s(b, "status");
|
|
|
|
|
+ let label = match st.as_str() {
|
|
|
|
|
+ "executed" => "已出账",
|
|
|
|
|
+ "failed" => "出账异常",
|
|
|
|
|
+ _ => "执行中",
|
|
|
|
|
+ };
|
|
|
|
|
+ if st == "executed" { generated += 1; }
|
|
|
|
|
+ (label.to_string(), Some(s(b, "batch_no")))
|
|
|
|
|
+ }
|
|
|
|
|
+ None => {
|
|
|
|
|
+ if expected <= today_d {
|
|
|
|
|
+ overdue += 1;
|
|
|
|
|
+ ("逾期未出账".to_string(), None)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ not_due += 1;
|
|
|
|
|
+ ("未到对账日".to_string(), None)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+ items.push(json!({
|
|
|
|
|
+ "holder_type": ht,
|
|
|
|
|
+ "holder_id": hid,
|
|
|
|
|
+ "holder_name": s(h, "holder_name"),
|
|
|
|
|
+ "region_label": Value::Null,
|
|
|
|
|
+ "recon_day": day,
|
|
|
|
|
+ "expected_date": expected.to_string(),
|
|
|
|
|
+ "status": status,
|
|
|
|
|
+ "batch_no": batch_no,
|
|
|
|
|
+ }));
|
|
|
|
|
+ }
|
|
|
|
|
+ Ok(json!({
|
|
|
|
|
+ "period": period,
|
|
|
|
|
+ "expected": holders.len() as i64,
|
|
|
|
|
+ "generated": generated,
|
|
|
|
|
+ "not_due": not_due,
|
|
|
|
|
+ "overdue": overdue,
|
|
|
|
|
+ "items": items,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 5. 批次详情 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize, Default)]
|
|
|
|
|
+pub struct BatchQuery {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub batch_no: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub batch_id: Option<String>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn recon_detail(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ Query(q): Query<BatchQuery>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let batch_no = q.batch_no.or(q.batch_id).unwrap_or_default();
|
|
|
|
|
+ if batch_no.is_empty() {
|
|
|
|
|
+ return json_err(BosError::bad_params("batch_no 必填(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT batch_no, period, holder_type, holder_id, holder_name, \
|
|
|
|
|
+ CAST(recon_date AS TEXT) AS recon_date, trigger_type, status, \
|
|
|
|
|
+ operator_user_id, CAST(executed_at AS TEXT) AS executed_at, \
|
|
|
|
|
+ COALESCE(fail_reason,'') AS fail_reason, COALESCE(replaced_by_batch_no,'') AS replaced_by \
|
|
|
|
|
+ FROM reconcile_batch WHERE batch_no = $1",
|
|
|
|
|
+ &[json!(batch_no)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let Some(b) = rows.first() else {
|
|
|
|
|
+ return json_err(BosError::not_found(format!("批次不存在(11104):{batch_no}")));
|
|
|
|
|
+ };
|
|
|
|
|
+ let period = s(b, "period");
|
|
|
|
|
+ let status = s(b, "status");
|
|
|
|
|
+
|
|
|
|
|
+ let items = match qry(&state.db,
|
|
|
|
|
+ "SELECT d.bill_detail_id, d.customer_id, d.customer_name, d.subscription_id, \
|
|
|
|
|
+ COALESCE(d.subscription_label,'') AS subscription_label, d.share_mode, \
|
|
|
|
|
+ CAST(d.share_value AS TEXT) AS share_value, d.share_base_cents, \
|
|
|
|
|
+ d.share_amount_cents, d.billing_days, COALESCE(d.zero_note,'') AS zero_note, \
|
|
|
|
|
+ COALESCE(r.receivable_cents, 0) AS receivable_cents \
|
|
|
|
|
+ FROM bill_detail d \
|
|
|
|
|
+ LEFT JOIN billing_receivable r ON r.period = d.period AND r.subscription_id = d.subscription_id \
|
|
|
|
|
+ WHERE d.batch_no = $1 AND d.status = 'active' ORDER BY d.customer_id, d.subscription_id",
|
|
|
|
|
+ &[json!(batch_no)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let detail_items: Vec<Value> = items.iter().map(|r| json!({
|
|
|
|
|
+ "bill_detail_id": s(r, "bill_detail_id"),
|
|
|
|
|
+ "customer_id": s(r, "customer_id"),
|
|
|
|
|
+ "customer_name": s(r, "customer_name"),
|
|
|
|
|
+ "subscription_id": s(r, "subscription_id"),
|
|
|
|
|
+ "subscription_label": s(r, "subscription_label"),
|
|
|
|
|
+ "share_mode": s(r, "share_mode"),
|
|
|
|
|
+ "share_value": f(r, "share_value"),
|
|
|
|
|
+ "share_base_cents": i(r, "share_base_cents"),
|
|
|
|
|
+ "share_amount_cents": i(r, "share_amount_cents"),
|
|
|
|
|
+ "receivable_cents": i(r, "receivable_cents"),
|
|
|
|
|
+ "billing_days": i(r, "billing_days"),
|
|
|
|
|
+ "zero_note": os(r, "zero_note"),
|
|
|
|
|
+ })).collect();
|
|
|
|
|
+
|
|
|
|
|
+ let closed = period < period_of(today());
|
|
|
|
|
+ let can_rerun = auth.role == RoleCode::Admin && closed && status == "failed";
|
|
|
|
|
+ let can_export = status == "executed" && !detail_items.is_empty();
|
|
|
|
|
+ let base_cents: i64 = detail_items.iter().map(|x| x["share_base_cents"].as_i64().unwrap_or(0)).sum();
|
|
|
|
|
+ let share_cents: i64 = detail_items.iter().map(|x| x["share_amount_cents"].as_i64().unwrap_or(0)).sum();
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "batch_no": s(b, "batch_no"),
|
|
|
|
|
+ "period": period,
|
|
|
|
|
+ "holder_type": s(b, "holder_type"),
|
|
|
|
|
+ "holder_id": s(b, "holder_id"),
|
|
|
|
|
+ "holder_name": s(b, "holder_name"),
|
|
|
|
|
+ "recon_date": s(b, "recon_date"),
|
|
|
|
|
+ "trigger_type": s(b, "trigger_type"),
|
|
|
|
|
+ "status": status,
|
|
|
|
|
+ "operator_user_id": os(b, "operator_user_id"),
|
|
|
|
|
+ "executed_at": os(b, "executed_at"),
|
|
|
|
|
+ "fail_reason": os(b, "fail_reason"),
|
|
|
|
|
+ "voided_by_batch_no": if status == "voided" { os(b, "replaced_by") } else { None },
|
|
|
|
|
+ "detail_count": detail_items.len(),
|
|
|
|
|
+ "base_cents": base_cents,
|
|
|
|
|
+ "share_cents": share_cents,
|
|
|
|
|
+ "can_rerun": can_rerun,
|
|
|
|
|
+ "can_export": can_export,
|
|
|
|
|
+ "can_correct": status == "executed",
|
|
|
|
|
+ "ticket_gap_count": Value::Null,
|
|
|
|
|
+ "ticket_gap_failed": false,
|
|
|
|
|
+ "cost_unconfigured": [],
|
|
|
|
|
+ "items": detail_items,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 6. RECON 两阶段引擎 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+/// 期首次冻结:客户归属快照 + 分成规则快照。返回 (是否已冻结, 分账号快照已有行数)。
|
|
|
|
|
+async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool, BosError> {
|
|
|
|
|
+ let first = parse_period(period)?;
|
|
|
|
|
+ let pstart = first.to_string();
|
|
|
|
|
+ let pend = month_end(first).to_string();
|
|
|
|
|
+
|
|
|
|
|
+ let state_rows = qry(db,
|
|
|
|
|
+ "SELECT CAST(receivable_generated_at AS TEXT) AS generated, \
|
|
|
|
|
+ CAST(share_frozen_at AS TEXT) AS share_frozen \
|
|
|
|
|
+ FROM billing_period_state WHERE period = $1",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ if state_rows.first().map(|r| !s(r, "generated").is_empty()).unwrap_or(false) {
|
|
|
|
|
+ return Ok(true);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ① 归属快照(客户未被冻结过才写)。
|
|
|
|
|
+ dmlx(db, "snapshot_customer", "INSERT INTO billing_snapshot_customer \
|
|
|
|
|
+ (period, customer_id, region_node_id, region_path, operator_id, partner_id, frozen_at) \
|
|
|
|
|
+ SELECT $1, c.customer_id, \
|
|
|
|
|
+ COALESCE(NULLIF(op.region_node_id,''), NULLIF(pt.region_node_id,''), ''), '', \
|
|
|
|
|
+ COALESCE(c.operator_id,''), COALESCE(c.partner_id,''), now() \
|
|
|
|
|
+ FROM customer c \
|
|
|
|
|
+ LEFT JOIN operator op ON op.operator_id = c.operator_id \
|
|
|
|
|
+ LEFT JOIN partner pt ON pt.partner_id = c.partner_id \
|
|
|
|
|
+ WHERE c.deleted_at IS NULL \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM billing_snapshot_customer s \
|
|
|
|
|
+ WHERE s.period = $1 AND s.customer_id = c.customer_id)",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+
|
|
|
|
|
+ // ② 分成规则快照:档案值,客户级 share_rule 覆盖(仅 active)。
|
|
|
|
|
+ dmlx(db, "snapshot_share_operator", "INSERT INTO billing_snapshot_share \
|
|
|
|
|
+ (period, customer_id, holder_type, holder_id, holder_name, share_mode, share_value, frozen_at) \
|
|
|
|
|
+ SELECT $1, c.customer_id, 'operator', o.operator_id, COALESCE(o.name,''), \
|
|
|
|
|
+ COALESCE(r.settle_mode, o.settle_mode), COALESCE(r.settle_value, o.settle_value), now() \
|
|
|
|
|
+ FROM customer c \
|
|
|
|
|
+ JOIN operator o ON o.operator_id = c.operator_id \
|
|
|
|
|
+ LEFT JOIN share_rule r ON r.holder_type = 'operator' AND r.holder_id = o.operator_id \
|
|
|
|
|
+ AND r.customer_id = c.customer_id AND r.status = 'active' \
|
|
|
|
|
+ WHERE c.deleted_at IS NULL AND COALESCE(r.settle_mode, o.settle_mode) IS NOT NULL \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM billing_snapshot_share s WHERE s.period=$1 \
|
|
|
|
|
+ AND s.customer_id=c.customer_id AND s.holder_type='operator' AND s.holder_id=o.operator_id)",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ dmlx(db, "snapshot_share_partner", "INSERT INTO billing_snapshot_share \
|
|
|
|
|
+ (period, customer_id, holder_type, holder_id, holder_name, share_mode, share_value, frozen_at) \
|
|
|
|
|
+ SELECT $1, c.customer_id, 'partner', pt.partner_id, COALESCE(pt.name,''), \
|
|
|
|
|
+ COALESCE(r.settle_mode, pt.settle_mode), COALESCE(r.settle_value, pt.settle_value), now() \
|
|
|
|
|
+ FROM customer c \
|
|
|
|
|
+ JOIN partner pt ON pt.partner_id = c.partner_id \
|
|
|
|
|
+ LEFT JOIN share_rule r ON r.holder_type = 'partner' AND r.holder_id = pt.partner_id \
|
|
|
|
|
+ AND r.customer_id = c.customer_id AND r.status = 'active' \
|
|
|
|
|
+ WHERE c.deleted_at IS NULL AND COALESCE(r.settle_mode, pt.settle_mode) IS NOT NULL \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM billing_snapshot_share s WHERE s.period=$1 \
|
|
|
|
|
+ AND s.customer_id=c.customer_id AND s.holder_type='partner' AND s.holder_id=pt.partner_id)",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ dmlx(db, "snapshot_share_ops_team", "INSERT INTO billing_snapshot_share \
|
|
|
|
|
+ (period, customer_id, holder_type, holder_id, holder_name, share_mode, share_value, frozen_at) \
|
|
|
|
|
+ SELECT DISTINCT $1, b.customer_id, 'ops_team', t.team_id, COALESCE(t.team_name,''), \
|
|
|
|
|
+ COALESCE(r.settle_mode, t.settle_mode), COALESCE(r.settle_value, t.settle_value), now() \
|
|
|
|
|
+ FROM customer_team_belong b \
|
|
|
|
|
+ JOIN ops_team t ON t.team_id = b.team_id \
|
|
|
|
|
+ LEFT JOIN share_rule r ON r.holder_type = 'ops_team' AND r.holder_id = t.team_id \
|
|
|
|
|
+ AND r.customer_id = b.customer_id AND r.status = 'active' \
|
|
|
|
|
+ WHERE COALESCE(r.settle_mode, t.settle_mode) IS NOT NULL \
|
|
|
|
|
+ AND (b.valid_from IS NULL OR b.valid_from::text = '' OR b.valid_from <= $2::timestamptz) \
|
|
|
|
|
+ AND (b.valid_to IS NULL OR b.valid_to::text = '' OR b.valid_to >= $3::timestamptz) \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM billing_snapshot_share s WHERE s.period=$1 \
|
|
|
|
|
+ AND s.customer_id=b.customer_id AND s.holder_type='ops_team' AND s.holder_id=t.team_id)",
|
|
|
|
|
+ &[json!(period), json!(pstart), json!(pend)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+
|
|
|
|
|
+ // ③ 应收生成(按订阅在本期的实际计费区间)。
|
|
|
|
|
+ let subs = qry(db,
|
|
|
|
|
+ "SELECT subscription_id, customer_id, COALESCE(monthly_settle_cents,0) AS monthly, \
|
|
|
|
|
+ COALESCE(annual_price_cents,0) AS annual, COALESCE(trial_months,0) AS trial, \
|
|
|
|
|
+ CAST(start_date AS TEXT) AS start_date, CAST(end_date AS TEXT) AS end_date, \
|
|
|
|
|
+ COALESCE(plan_id,'') AS plan_id \
|
|
|
|
|
+ FROM subscription \
|
|
|
|
|
+ WHERE start_date <= $2::date \
|
|
|
|
|
+ AND (end_date IS NULL OR end_date >= $1::date)",
|
|
|
|
|
+ &[json!(pstart), json!(pend)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+
|
|
|
|
|
+ let month_days = month_end(first).day() as i64;
|
|
|
|
|
+ for row in &subs {
|
|
|
|
|
+ let sid = s(row, "subscription_id");
|
|
|
|
|
+ let cid = s(row, "customer_id");
|
|
|
|
|
+ let start = NaiveDate::parse_from_str(&s(row, "start_date"), "%Y-%m-%d").ok();
|
|
|
|
|
+ let end = NaiveDate::parse_from_str(&s(row, "end_date"), "%Y-%m-%d").ok();
|
|
|
|
|
+ let Some(st) = start else { continue; };
|
|
|
|
|
+ let from = st.max(first);
|
|
|
|
|
+ let to = end.map(|e| e.min(month_end(first))).unwrap_or(month_end(first));
|
|
|
|
|
+ if to < from { continue; }
|
|
|
|
|
+ let days = (to - from).num_days() + 1;
|
|
|
|
|
+ if days <= 0 { continue; }
|
|
|
|
|
+ let std = {
|
|
|
|
|
+ let m = i(row, "monthly");
|
|
|
|
|
+ if m > 0 { m } else { round_half_up(i(row, "annual") as i128, 12) }
|
|
|
|
|
+ };
|
|
|
|
|
+ // 试用窗口:计费起点起 trial_months 个自然月内不计费(整期按试用处理)。
|
|
|
|
|
+ let trial_until = add_months(st, i(row, "trial") as i32);
|
|
|
|
|
+ let in_trial = i(row, "trial") > 0 && from < trial_until;
|
|
|
|
|
+ let pre_align = if in_trial { 0 } else { round_half_up(std as i128 * days as i128, month_days as i128) };
|
|
|
|
|
+ let receivable = pre_align;
|
|
|
|
|
+ let cost = 0i64;
|
|
|
|
|
+ let share_base = (receivable - cost).max(0);
|
|
|
|
|
+ let plan = s(row, "plan_id");
|
|
|
|
|
+ let _ = plan;
|
|
|
|
|
+ dmlx(db, "receivable", "INSERT INTO billing_receivable \
|
|
|
|
|
+ (period, subscription_id, customer_id, settle_std_cents, billing_days, month_days, \
|
|
|
|
|
+ is_partial, pre_align_cents, receivable_cents, cost_deduct_cents, share_base_cents, \
|
|
|
|
|
+ cost_snapshot, effective_mode, bill_from, bill_to, created_at) \
|
|
|
|
|
+ SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,'[]'::jsonb,$12,$13::date,$14::date,now() \
|
|
|
|
|
+ WHERE NOT EXISTS (SELECT 1 FROM billing_receivable WHERE period=$1 AND subscription_id=$2)",
|
|
|
|
|
+ &[
|
|
|
|
|
+ json!(period), json!(sid), json!(cid), json!(std), json!(days), json!(month_days),
|
|
|
|
|
+ json!(days < month_days), json!(pre_align), json!(receivable), json!(cost),
|
|
|
|
|
+ json!(share_base), json!("period_snapshot"), json!(from.to_string()), json!(to.to_string()),
|
|
|
|
|
+ ],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ // 在期账号(一期口径:客户现存分账号,未开通不计;天数取本期计费天数)。
|
|
|
|
|
+ dmlx(db, "receivable", "INSERT INTO billing_receivable_account (period, subscription_id, sub_account_id, in_period_days, created_at) \
|
|
|
|
|
+ SELECT $1, $2, a.sub_account_id, $3, now() FROM sub_account a \
|
|
|
|
|
+ WHERE a.customer_id = $4 AND COALESCE(a.status,'') <> 'not_opened' \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM billing_receivable_account x \
|
|
|
|
|
+ WHERE x.period=$1 AND x.subscription_id=$2 AND x.sub_account_id=a.sub_account_id)",
|
|
|
|
|
+ &[json!(period), json!(sid), json!(days), json!(cid)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ dmlx(db, "period_state", "INSERT INTO billing_period_state (period, customer_frozen_at, share_frozen_at, receivable_generated_at) \
|
|
|
|
|
+ SELECT $1, now(), now(), now() WHERE NOT EXISTS (SELECT 1 FROM billing_period_state WHERE period=$1)",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ dmlx(db, "period_state_touch", "UPDATE billing_period_state SET customer_frozen_at = COALESCE(customer_frozen_at, now()), \
|
|
|
|
|
+ share_frozen_at = COALESCE(share_frozen_at, now()), receivable_generated_at = now() \
|
|
|
|
|
+ WHERE period = $1",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ Ok(false)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// 有效批次是否存在(与部分唯一索引同一谓词)。
|
|
|
|
|
+async fn active_batch(db: &UdsClient, period: &str, ht: &str, hid: &str) -> Result<Option<(String, String)>, BosError> {
|
|
|
|
|
+ let rows = qry(db,
|
|
|
|
|
+ "SELECT batch_no, status FROM reconcile_batch WHERE period=$1 AND holder_type=$2 \
|
|
|
|
|
+ AND holder_id=$3 AND status IN ('pending','executed')",
|
|
|
|
|
+ &[json!(period), json!(ht), json!(hid)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ Ok(rows.first().map(|r| (s(r, "batch_no"), s(r, "status"))))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+async fn allocate_batch_no(db: &UdsClient, rerun: bool, period: &str) -> Result<String, BosError> {
|
|
|
|
|
+ let today_s = today().format("%Y%m%d").to_string();
|
|
|
|
|
+ let kind = if rerun {
|
|
|
|
|
+ format!("recon_rg_{today_s}")
|
|
|
|
|
+ } else {
|
|
|
|
|
+ format!("recon_bt_{today_s}")
|
|
|
|
|
+ };
|
|
|
|
|
+ let seq = next_seq(db, &kind, "reconcile_batch", today().year()).await?;
|
|
|
|
|
+ let _ = period;
|
|
|
|
|
+ if rerun {
|
|
|
|
|
+ Ok(format!("DZD-{}-RG{:02}", today_s, seq % 100))
|
|
|
|
|
+ } else {
|
|
|
|
|
+ Ok(format!("DZD-{}-{:02}", today_s, seq % 100))
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// 执行一个分成方的出账(阶段二)。`rerun=true` 时要求已存在 failed 批次。
|
|
|
|
|
+async fn execute_holder(
|
|
|
|
|
+ db: &UdsClient,
|
|
|
|
|
+ period: &str,
|
|
|
|
|
+ ht: &str,
|
|
|
|
|
+ hid: &str,
|
|
|
|
|
+ trigger: &str,
|
|
|
|
|
+ user_id: &str,
|
|
|
|
|
+ rerun: bool,
|
|
|
|
|
+) -> Result<Option<String>, BosError> {
|
|
|
|
|
+ // 前置②:有效批次(补跑在调用方已判 60503)。
|
|
|
|
|
+ if let Some((no, st)) = active_batch(db, period, ht, hid).await? {
|
|
|
|
|
+ if !rerun {
|
|
|
|
|
+ return Ok(Some(no)); // 作业路径:已出账/执行中 ⇒ 幂等跳过
|
|
|
|
|
+ }
|
|
|
|
|
+ if st == "executed" {
|
|
|
|
|
+ return Err(BosError::klt(KltCode::H20503, "该期已出账,无需补跑"));
|
|
|
|
|
+ }
|
|
|
|
|
+ return Err(BosError::klt(KltCode::H20503, "该期出账正在执行,请稍后查看结果"));
|
|
|
|
|
+ }
|
|
|
|
|
+ // 前置④:可展开应收(补跑才报码;作业路径无明细不建批)。
|
|
|
|
|
+ let recips = qry(db,
|
|
|
|
|
+ "SELECT r.period, r.subscription_id, r.customer_id, r.receivable_cents, r.share_base_cents, \
|
|
|
|
|
+ r.billing_days, COALESCE(c.customer_name,'') AS customer_name, \
|
|
|
|
|
+ COALESCE(p.plan_name,'') AS plan_name \
|
|
|
|
|
+ FROM billing_receivable r \
|
|
|
|
|
+ JOIN billing_snapshot_share v ON v.period=r.period AND v.customer_id=r.customer_id \
|
|
|
|
|
+ AND v.holder_type=$2 AND v.holder_id=$3 \
|
|
|
|
|
+ LEFT JOIN customer c ON c.customer_id=r.customer_id \
|
|
|
|
|
+ LEFT JOIN subscription s ON s.subscription_id=r.subscription_id \
|
|
|
|
|
+ LEFT JOIN catalog_plan p ON p.plan_id=s.plan_id \
|
|
|
|
|
+ WHERE r.period=$1",
|
|
|
|
|
+ &[json!(period), json!(ht), json!(hid)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ if recips.is_empty() {
|
|
|
|
|
+ if rerun {
|
|
|
|
|
+ return Err(BosError::klt(KltCode::H20506, "该分成方该期无任何可展开应收"));
|
|
|
|
|
+ }
|
|
|
|
|
+ return Ok(None);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let batch_no = allocate_batch_no(db, rerun, period).await?;
|
|
|
|
|
+ let holder_name = {
|
|
|
|
|
+ let (table, idcol) = holder_table(ht).unwrap();
|
|
|
|
|
+ let name_col = if ht == "ops_team" { "team_name" } else { "name" };
|
|
|
|
|
+ let sql = format!("SELECT COALESCE({name_col},'') AS nm FROM {table} WHERE {idcol}=$1");
|
|
|
|
|
+ let rows = qry(db, &sql, &[json!(hid)]).await?;
|
|
|
|
|
+ rows.first().map(|r| s(r, "nm")).unwrap_or_default()
|
|
|
|
|
+ };
|
|
|
|
|
+ let due = {
|
|
|
|
|
+ let rows = qry(db,
|
|
|
|
|
+ "SELECT recon_day FROM operator WHERE operator_id = $1",
|
|
|
|
|
+ &[json!(hid)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ rows.first().and_then(|r| oi(r, "recon_day")).unwrap_or(5)
|
|
|
|
|
+ };
|
|
|
|
|
+ let recon_date = if trigger == "manual" {
|
|
|
|
|
+ today()
|
|
|
|
|
+ } else {
|
|
|
|
|
+ let first = parse_period(period)?;
|
|
|
|
|
+ let day = due.clamp(1, 28) as u32;
|
|
|
|
|
+ NaiveDate::from_ymd_opt(first.year(), first.month(), day).unwrap_or(today())
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ // 事务 A:先落 pending 批次(部分唯一索引兜底并发)。
|
|
|
|
|
+ db.dml(
|
|
|
|
|
+ "INSERT INTO reconcile_batch \
|
|
|
|
|
+ (batch_no, period, holder_type, holder_id, holder_name, recon_date, trigger_type, status, \
|
|
|
|
|
+ operator_user_id, created_at) \
|
|
|
|
|
+ VALUES ($1,$2,$3,$4,$5,$6::date,$7,'pending',$8,now())",
|
|
|
|
|
+ &[json!(batch_no), json!(period), json!(ht), json!(hid), json!(holder_name),
|
|
|
|
|
+ json!(recon_date.to_string()), json!(trigger), json!(user_id)],
|
|
|
|
|
+ ).await.map_err(|e| {
|
|
|
|
|
+ // 预检查放过、写入那一刻撞部分唯一索引 ⇒ KLT-S407(与 60503 的分界=时机)。
|
|
|
|
|
+ let msg = err_text(&e).to_lowercase();
|
|
|
|
|
+ if msg.contains("duplicate") || msg.contains("unique") {
|
|
|
|
|
+ BosError::klt(KltCode::S407, "该分成方该期批次已存在,请刷新后重试(KLT-S407)")
|
|
|
|
|
+ } else { e }
|
|
|
|
|
+ })?;
|
|
|
|
|
+
|
|
|
|
|
+ // 事务 B:明细展开(比例四舍五入;固定金额原样(元→分);按账号 × 账号数)。
|
|
|
|
|
+ let insert = db.dml(
|
|
|
|
|
+ "INSERT INTO bill_detail \
|
|
|
|
|
+ (bill_detail_id, batch_no, period, customer_id, customer_name, subscription_id, \
|
|
|
|
|
+ subscription_label, holder_type, holder_id, share_mode, share_value, share_base_cents, \
|
|
|
|
|
+ share_amount_cents, billing_days, zero_note, status, created_at) \
|
|
|
|
|
+ SELECT 'BD-' || $1 || '-' || r.subscription_id, $1, r.period, r.customer_id, \
|
|
|
|
|
+ COALESCE(c.customer_name,''), r.subscription_id, COALESCE(p.plan_name, r.subscription_id), \
|
|
|
|
|
+ $2, $3, v.share_mode, v.share_value, r.share_base_cents, \
|
|
|
|
|
+ CASE v.share_mode \
|
|
|
|
|
+ WHEN 'ratio' THEN round(r.share_base_cents * v.share_value)::bigint \
|
|
|
|
|
+ WHEN 'amount' THEN round(v.share_value * 100)::bigint \
|
|
|
|
|
+ ELSE round(v.share_value * 100)::bigint * \
|
|
|
|
|
+ (SELECT COUNT(*) FROM billing_receivable_account a \
|
|
|
|
|
+ WHERE a.period=r.period AND a.subscription_id=r.subscription_id) \
|
|
|
|
|
+ END, \
|
|
|
|
|
+ r.billing_days, \
|
|
|
|
|
+ CASE WHEN v.share_mode='ratio' AND r.share_base_cents=0 THEN 'base_zero' \
|
|
|
|
|
+ WHEN v.share_mode='per_account' AND NOT EXISTS ( \
|
|
|
|
|
+ SELECT 1 FROM billing_receivable_account a \
|
|
|
|
|
+ WHERE a.period=r.period AND a.subscription_id=r.subscription_id) \
|
|
|
|
|
+ THEN 'no_in_period_account' ELSE NULL END, \
|
|
|
|
|
+ 'active', now() \
|
|
|
|
|
+ FROM billing_receivable r \
|
|
|
|
|
+ JOIN billing_snapshot_share v ON v.period=r.period AND v.customer_id=r.customer_id \
|
|
|
|
|
+ AND v.holder_type=$2 AND v.holder_id=$3 \
|
|
|
|
|
+ LEFT JOIN customer c ON c.customer_id=r.customer_id \
|
|
|
|
|
+ LEFT JOIN subscription s ON s.subscription_id=r.subscription_id \
|
|
|
|
|
+ LEFT JOIN catalog_plan p ON p.plan_id=s.plan_id \
|
|
|
|
|
+ WHERE r.period=$1 \
|
|
|
|
|
+ AND NOT EXISTS (SELECT 1 FROM bill_detail x WHERE x.batch_no=$1 AND x.subscription_id=r.subscription_id)",
|
|
|
|
|
+ &[json!(batch_no), json!(ht), json!(hid)],
|
|
|
|
|
+ ).await;
|
|
|
|
|
+
|
|
|
|
|
+ if let Err(e) = insert {
|
|
|
|
|
+ db.dml(
|
|
|
|
|
+ "UPDATE reconcile_batch SET status='failed', fail_reason=$2 WHERE batch_no=$1",
|
|
|
|
|
+ &[json!(batch_no), json!(format!("DETAIL_FAILED: {}", err_text(&e)))],
|
|
|
|
|
+ ).await.ok();
|
|
|
|
|
+ return Err(e);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 汇总回填 + 置 executed。
|
|
|
|
|
+ db.dml(
|
|
|
|
|
+ "UPDATE reconcile_batch SET status='executed', executed_at=now(), \
|
|
|
|
|
+ detail_count=(SELECT COUNT(*) FROM bill_detail WHERE batch_no=$1 AND status='active'), \
|
|
|
|
|
+ base_cents=(SELECT COALESCE(SUM(share_base_cents),0) FROM bill_detail WHERE batch_no=$1 AND status='active'), \
|
|
|
|
|
+ share_cents=(SELECT COALESCE(SUM(share_amount_cents),0) FROM bill_detail WHERE batch_no=$1 AND status='active') \
|
|
|
|
|
+ WHERE batch_no=$1",
|
|
|
|
|
+ &[json!(batch_no)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ if rerun {
|
|
|
|
|
+ db.dml(
|
|
|
|
|
+ "UPDATE reconcile_batch SET status='voided', replaced_by_batch_no=$2 \
|
|
|
|
|
+ WHERE period=$1 AND holder_type=$3 AND holder_id=$4 AND status='failed'",
|
|
|
|
|
+ &[json!(period), json!(batch_no), json!(ht), json!(hid)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ }
|
|
|
|
|
+ Ok(Some(batch_no))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct ReconRerunReq {
|
|
|
|
|
+ pub period: String,
|
|
|
|
|
+ pub holder_type: String,
|
|
|
|
|
+ pub holder_id: String,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn recon_rerun(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(body): DataBody<ReconRerunReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_admin(&auth) { return json_err(e); }
|
|
|
|
|
+ let period = match parse_period(&body.period) {
|
|
|
|
|
+ Ok(_) => normalize_period(&body.period),
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if holder_table(&body.holder_type).is_none() {
|
|
|
|
|
+ return json_err(BosError::bad_params("holder_type 非法(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ // 前置①:期已结束。
|
|
|
|
|
+ if period >= period_of(today()) {
|
|
|
|
|
+ return json_err(BosError::klt(
|
|
|
|
|
+ KltCode::H20502,
|
|
|
|
|
+ format!(
|
|
|
|
|
+ "补跑指定的自然月尚未结束(KLT-H20502),可选期上界:{}",
|
|
|
|
|
+ last_closed_period()
|
|
|
|
|
+ ),
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ // 前置③:快照已冻结。
|
|
|
|
|
+ let frozen = match qry(&state.db,
|
|
|
|
|
+ "SELECT CAST(receivable_generated_at AS TEXT) AS generated FROM billing_period_state WHERE period=$1",
|
|
|
|
|
+ &[json!(period)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r.first().map(|x| !s(x, "generated").is_empty()).unwrap_or(false),
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if !frozen {
|
|
|
|
|
+ return json_err(BosError::klt(
|
|
|
|
|
+ KltCode::H20504,
|
|
|
|
|
+ "该期归属与规则快照未冻结完成(KLT-H20504),请等待本轮作业完成或联系总运营",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ // 前置②:有效批次。
|
|
|
|
|
+ match active_batch(&state.db, &period, &body.holder_type, &body.holder_id).await {
|
|
|
|
|
+ Ok(Some((_, st))) => {
|
|
|
|
|
+ let msg = if st == "executed" {
|
|
|
|
|
+ "该期已出账,无需补跑(KLT-H20503)"
|
|
|
|
|
+ } else {
|
|
|
|
|
+ "该期出账正在执行,请稍后查看结果(KLT-H20503)"
|
|
|
|
|
+ };
|
|
|
|
|
+ return json_err(BosError::klt(KltCode::H20503, msg));
|
|
|
|
|
+ }
|
|
|
|
|
+ Ok(None) => {}
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ }
|
|
|
|
|
+ match execute_holder(&state.db, &period, &body.holder_type, &body.holder_id, "manual", &auth.user_id, true).await {
|
|
|
|
|
+ Ok(Some(no)) => ok(json!({
|
|
|
|
|
+ "batch_id": no,
|
|
|
|
|
+ "batch_no": no,
|
|
|
|
|
+ "period": period,
|
|
|
|
|
+ "holder_type": body.holder_type,
|
|
|
|
|
+ "holder_id": body.holder_id,
|
|
|
|
|
+ "status": "executed",
|
|
|
|
|
+ "status_label": "已出账",
|
|
|
|
|
+ })),
|
|
|
|
|
+ Ok(None) => json_err(BosError::klt(KltCode::H20506, "该分成方该期无任何可展开应收(KLT-H20506)")),
|
|
|
|
|
+ Err(e) => json_err(e),
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// RECON 作业入口:`period == Some` ⇒ 指定已结束月回填(补跑口径,admin 触发);
|
|
|
|
|
+/// `None` ⇒ 调度口径:每月 1 日生成上一个已结束月的应收;当日按各分成方对账日出账。
|
|
|
|
|
+pub async fn run_recon_job(
|
|
|
|
|
+ db: &UdsClient,
|
|
|
|
|
+ biz_date: NaiveDate,
|
|
|
|
|
+ period: Option<String>,
|
|
|
|
|
+ user_id: &str,
|
|
|
|
|
+) -> Result<Value, BosError> {
|
|
|
|
|
+ let is_rerun_context = period.is_some();
|
|
|
|
|
+ let target = match period {
|
|
|
|
|
+ Some(p) => {
|
|
|
|
|
+ if p >= period_of(biz_date) {
|
|
|
|
|
+ return Err(BosError::klt(KltCode::H20502, "补跑指定的自然月尚未结束(KLT-H20502)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ p
|
|
|
|
|
+ }
|
|
|
|
|
+ None => period_of(biz_date - Duration::days(1)),
|
|
|
|
|
+ };
|
|
|
|
|
+ let already = freeze_period(db, &target).await?;
|
|
|
|
|
+ let mut created = Vec::new();
|
|
|
|
|
+ let mut skipped = 0usize;
|
|
|
|
|
+ let holders = qry(db,
|
|
|
|
|
+ "SELECT DISTINCT v.holder_type, v.holder_id FROM billing_snapshot_share v \
|
|
|
|
|
+ JOIN billing_receivable r ON r.period=v.period AND r.customer_id=v.customer_id \
|
|
|
|
|
+ WHERE v.period=$1 ORDER BY v.holder_type, v.holder_id",
|
|
|
|
|
+ &[json!(target)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ for h in &holders {
|
|
|
|
|
+ let ht = s(h, "holder_type");
|
|
|
|
|
+ let hid = s(h, "holder_id");
|
|
|
|
|
+ if !is_rerun_context {
|
|
|
|
|
+ // 调度口径:只处理今天到对账日的分成方。
|
|
|
|
|
+ let rows = qry(db, "SELECT recon_day FROM operator WHERE operator_id=$1", &[json!(hid)]).await?;
|
|
|
|
|
+ let due = rows.first().and_then(|r| oi(r, "recon_day")).unwrap_or(5);
|
|
|
|
|
+ if due != biz_date.day() as i64 {
|
|
|
|
|
+ continue;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ match execute_holder(db, &target, &ht, &hid, if is_rerun_context { "manual" } else { "auto" }, user_id, false).await {
|
|
|
|
|
+ Ok(Some(no)) => created.push(no),
|
|
|
|
|
+ Ok(None) => skipped += 1,
|
|
|
|
|
+ Err(e) => {
|
|
|
|
|
+ return Err(BosError::internal(format!(
|
|
|
|
|
+ "RECON {target} {ht}:{hid} 失败:{}",
|
|
|
|
|
+ err_text(&e)
|
|
|
|
|
+ )))
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ Ok(json!({
|
|
|
|
|
+ "period": target,
|
|
|
|
|
+ "already_generated": already,
|
|
|
|
|
+ "created": created,
|
|
|
|
|
+ "skipped": skipped,
|
|
|
|
|
+ "holders": holders.len(),
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 7. 账单明细 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct BillListReq {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub period: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub holder_type: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub holder_kw: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub customer_kw: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub keyword: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub page: Option<i64>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub page_size: Option<i64>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn bill_list(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(req): DataBody<BillListReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let period = match req.period.as_deref().map(normalize_period) {
|
|
|
|
|
+ Some(p) if !p.is_empty() => p,
|
|
|
|
|
+ _ => last_closed_period(),
|
|
|
|
|
+ };
|
|
|
|
|
+ let page = req.page.unwrap_or(0).max(0);
|
|
|
|
|
+ let size = req.page_size.unwrap_or(20).clamp(1, 100);
|
|
|
|
|
+ let offset = page * size;
|
|
|
|
|
+
|
|
|
|
|
+ let mut p = Params::default();
|
|
|
|
|
+ let mut w = vec![
|
|
|
|
|
+ format!("d.period = {}", p.push(json!(period))),
|
|
|
|
|
+ "d.status = 'active'".to_string(),
|
|
|
|
|
+ "b.status = 'executed'".to_string(),
|
|
|
|
|
+ ];
|
|
|
|
|
+ if let Some(t) = req.holder_type.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ w.push(format!("d.holder_type = {}", p.push(json!(t))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.holder_kw.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ w.push(format!("b.holder_name ILIKE {}", p.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.customer_kw.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ w.push(format!("(d.customer_name ILIKE {0} OR d.customer_id ILIKE {0})", p.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.keyword.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ w.push(format!("(d.subscription_id ILIKE {0} OR COALESCE(d.subscription_label,'') ILIKE {0} OR d.batch_no ILIKE {0})",
|
|
|
|
|
+ p.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ let from = format!(
|
|
|
|
|
+ "FROM bill_detail d JOIN reconcile_batch b ON b.batch_no = d.batch_no \
|
|
|
|
|
+ LEFT JOIN billing_receivable r ON r.period=d.period AND r.subscription_id=d.subscription_id \
|
|
|
|
|
+ WHERE {}",
|
|
|
|
|
+ w.join(" AND ")
|
|
|
|
|
+ );
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ &format!(
|
|
|
|
|
+ "SELECT d.bill_detail_id, d.batch_no, d.period, d.customer_id, d.customer_name, \
|
|
|
|
|
+ d.subscription_id, COALESCE(d.subscription_label,'') AS subscription_label, \
|
|
|
|
|
+ d.holder_type, d.holder_id, b.holder_name, d.share_mode, \
|
|
|
|
|
+ CAST(d.share_value AS TEXT) AS share_value, d.share_base_cents, \
|
|
|
|
|
+ d.share_amount_cents, d.billing_days, COALESCE(d.zero_note,'') AS zero_note \
|
|
|
|
|
+ {from} ORDER BY d.bill_detail_id DESC LIMIT {size} OFFSET {offset}"
|
|
|
|
|
+ ),
|
|
|
|
|
+ p.values(),
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let total = match qry(&state.db, &format!("SELECT COUNT(*) AS n {from}"), p.values()).await {
|
|
|
|
|
+ Ok(r) => r.first().map(|x| i(x, "n")).unwrap_or(0),
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let items: Vec<Value> = rows.iter().map(|r| json!({
|
|
|
|
|
+ "bill_detail_id": s(r, "bill_detail_id"),
|
|
|
|
|
+ "batch_id": s(r, "batch_no"),
|
|
|
|
|
+ "batch_no": s(r, "batch_no"),
|
|
|
|
|
+ "period": s(r, "period"),
|
|
|
|
|
+ "customer_id": s(r, "customer_id"),
|
|
|
|
|
+ "customer_name": s(r, "customer_name"),
|
|
|
|
|
+ "subscription_id": s(r, "subscription_id"),
|
|
|
|
|
+ "subscription_label": s(r, "subscription_label"),
|
|
|
|
|
+ "holder_type": s(r, "holder_type"),
|
|
|
|
|
+ "holder_id": s(r, "holder_id"),
|
|
|
|
|
+ "holder_name": s(r, "holder_name"),
|
|
|
|
|
+ "share_mode": s(r, "share_mode"),
|
|
|
|
|
+ "share_value": f(r, "share_value"),
|
|
|
|
|
+ "share_base_cents": i(r, "share_base_cents"),
|
|
|
|
|
+ "share_amount_cents": i(r, "share_amount_cents"),
|
|
|
|
|
+ "billing_days": i(r, "billing_days"),
|
|
|
|
|
+ "zero_note": os(r, "zero_note"),
|
|
|
|
|
+ })).collect();
|
|
|
|
|
+ ok(json!({ "items": items, "total": total, "page": page, "page_size": size }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize, Default)]
|
|
|
|
|
+pub struct BillDetailQuery {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub bill_detail_id: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub detail_id: Option<String>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn bill_detail(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ Query(q): Query<BillDetailQuery>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let id = q.bill_detail_id.or(q.detail_id).unwrap_or_default();
|
|
|
|
|
+ if id.is_empty() {
|
|
|
|
|
+ return json_err(BosError::bad_params("bill_detail_id 必填(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT d.bill_detail_id, d.batch_no, d.period, d.customer_id, d.customer_name, \
|
|
|
|
|
+ d.subscription_id, COALESCE(d.subscription_label,'') AS subscription_label, \
|
|
|
|
|
+ d.holder_type, d.holder_id, b.holder_name, d.share_mode, \
|
|
|
|
|
+ CAST(d.share_value AS TEXT) AS share_value, d.share_base_cents, \
|
|
|
|
|
+ d.share_amount_cents, d.billing_days, COALESCE(d.zero_note,'') AS zero_note, \
|
|
|
|
|
+ b.status AS batch_status, COALESCE(r.receivable_cents,0) AS receivable_cents, \
|
|
|
|
|
+ COALESCE(r.pre_align_cents,0) AS pre_align_cents, \
|
|
|
|
|
+ COALESCE(r.cost_deduct_cents,0) AS cost_deduct_cents, \
|
|
|
|
|
+ CAST(r.bill_from AS TEXT) AS bill_from, CAST(r.bill_to AS TEXT) AS bill_to, \
|
|
|
|
|
+ COALESCE(r.is_partial,false) AS is_partial, COALESCE(r.cost_snapshot,'[]') AS cost_snapshot \
|
|
|
|
|
+ FROM bill_detail d JOIN reconcile_batch b ON b.batch_no=d.batch_no \
|
|
|
|
|
+ LEFT JOIN billing_receivable r ON r.period=d.period AND r.subscription_id=d.subscription_id \
|
|
|
|
|
+ WHERE d.bill_detail_id=$1 AND d.status='active' AND b.status='executed'",
|
|
|
|
|
+ &[json!(id)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let Some(r) = rows.first() else {
|
|
|
|
|
+ return json_err(BosError::not_found(format!("账单明细不存在或未出账(11104):{id}")));
|
|
|
|
|
+ };
|
|
|
|
|
+ let period = s(r, "period");
|
|
|
|
|
+ let sid = s(r, "subscription_id");
|
|
|
|
|
+ let accounts = match qry(&state.db,
|
|
|
|
|
+ "SELECT COALESCE(NULLIF(sa.display_name,''), a.sub_account_id) AS sub_account_label, \
|
|
|
|
|
+ a.in_period_days \
|
|
|
|
|
+ FROM billing_receivable_account a \
|
|
|
|
|
+ LEFT JOIN sub_account sa ON sa.sub_account_id=a.sub_account_id \
|
|
|
|
|
+ WHERE a.period=$1 AND a.subscription_id=$2 ORDER BY a.sub_account_id",
|
|
|
|
|
+ &[json!(period), json!(sid)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(x) => x,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let account_days: Vec<Value> = accounts.iter().map(|x| json!({
|
|
|
|
|
+ "sub_account_label": s(x, "sub_account_label"),
|
|
|
|
|
+ "in_period_days": i(x, "in_period_days"),
|
|
|
|
|
+ })).collect();
|
|
|
|
|
+ let others = match qry(&state.db,
|
|
|
|
|
+ "SELECT d.bill_detail_id, d.batch_no, d.holder_type, b.holder_name, d.share_amount_cents \
|
|
|
|
|
+ FROM bill_detail d JOIN reconcile_batch b ON b.batch_no=d.batch_no \
|
|
|
|
|
+ WHERE d.period=$1 AND d.subscription_id=$2 AND d.status='active' AND b.status='executed' \
|
|
|
|
|
+ AND NOT (d.holder_type=$3 AND d.holder_id=$4) ORDER BY d.holder_type, d.holder_id",
|
|
|
|
|
+ &[json!(period), json!(sid), json!(s(r, "holder_type")), json!(s(r, "holder_id"))],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(x) => x,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let other_parties: Vec<Value> = others.iter().map(|x| json!({
|
|
|
|
|
+ "holder_type": s(x, "holder_type"),
|
|
|
|
|
+ "holder_name": s(x, "holder_name"),
|
|
|
|
|
+ "share_amount_cents": i(x, "share_amount_cents"),
|
|
|
|
|
+ "batch_no": s(x, "batch_no"),
|
|
|
|
|
+ })).collect();
|
|
|
|
|
+
|
|
|
|
|
+ let receivable = i(r, "receivable_cents");
|
|
|
|
|
+ let base = i(r, "share_base_cents");
|
|
|
|
|
+ // 成本快照:一期无客户级成本归属 ⇒ 冻结数组为空(如实为空,⛔ 按客户摊派)。
|
|
|
|
|
+ let costs: Value = serde_json::from_str(&{
|
|
|
|
|
+ let raw = s(r, "cost_snapshot");
|
|
|
|
|
+ if raw.is_empty() { "[]".to_string() } else { raw }
|
|
|
|
|
+ }).unwrap_or_else(|_| json!([]));
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "bill_detail_id": s(r, "bill_detail_id"),
|
|
|
|
|
+ "batch_no": s(r, "batch_no"),
|
|
|
|
|
+ "period": period,
|
|
|
|
|
+ "customer_id": s(r, "customer_id"),
|
|
|
|
|
+ "customer_name": s(r, "customer_name"),
|
|
|
|
|
+ "subscription_id": sid,
|
|
|
|
|
+ "subscription_label": s(r, "subscription_label"),
|
|
|
|
|
+ "holder_type": s(r, "holder_type"),
|
|
|
|
|
+ "holder_id": s(r, "holder_id"),
|
|
|
|
|
+ "holder_name": s(r, "holder_name"),
|
|
|
|
|
+ "share_mode": s(r, "share_mode"),
|
|
|
|
|
+ "share_value": f(r, "share_value"),
|
|
|
|
|
+ "pre_align_cents": i(r, "pre_align_cents"),
|
|
|
|
|
+ "receivable_cents": receivable,
|
|
|
|
|
+ "bill_from": os(r, "bill_from"),
|
|
|
|
|
+ "bill_to": os(r, "bill_to"),
|
|
|
|
|
+ "billing_days": i(r, "billing_days"),
|
|
|
|
|
+ "partial_month": b(r, "is_partial"),
|
|
|
|
|
+ "costs": costs,
|
|
|
|
|
+ "share_base_cents": base,
|
|
|
|
|
+ "base_floor_protected": receivable > 0 && base == 0,
|
|
|
|
|
+ "share_amount_cents": i(r, "share_amount_cents"),
|
|
|
|
|
+ "zero_note": os(r, "zero_note"),
|
|
|
|
|
+ "other_parties": other_parties,
|
|
|
|
|
+ "account_days": account_days,
|
|
|
|
|
+ "account_days_failed": false,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─────────────────────────── 8. 出账更正 ───────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct CorrectionCreateReq {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub bill_detail_id: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub ref_: Option<String>,
|
|
|
|
|
+ #[serde(rename = "ref", default)]
|
|
|
|
|
+ pub reference: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub raw_ref: Option<String>,
|
|
|
|
|
+ pub error_text: String,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+async fn customer_region(db: &UdsClient, customer_id: &str, period: &str) -> Result<(String, String), BosError> {
|
|
|
|
|
+ let rows = qry(db,
|
|
|
|
|
+ "SELECT COALESCE(op.name,'') AS operator_name, \
|
|
|
|
|
+ COALESCE(NULLIF(s.region_node_id,''), NULLIF(op.region_node_id,''), \
|
|
|
|
|
+ NULLIF(pt.region_node_id,''), '') AS region_node_id \
|
|
|
|
|
+ FROM customer c \
|
|
|
|
|
+ LEFT JOIN operator op ON op.operator_id=c.operator_id \
|
|
|
|
|
+ LEFT JOIN partner pt ON pt.partner_id=c.partner_id \
|
|
|
|
|
+ LEFT JOIN billing_snapshot_customer s ON s.period=$2 AND s.customer_id=c.customer_id \
|
|
|
|
|
+ WHERE c.customer_id=$1",
|
|
|
|
|
+ &[json!(customer_id), json!(period)],
|
|
|
|
|
+ ).await?;
|
|
|
|
|
+ Ok(rows.first().map(|r| (s(r, "operator_name"), s(r, "region_node_id"))).unwrap_or_default())
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn correction_create(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(body): DataBody<CorrectionCreateReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let raw_ref = body.ref_
|
|
|
|
|
+ .or(body.reference)
|
|
|
|
|
+ .or(body.raw_ref)
|
|
|
|
|
+ .unwrap_or_default()
|
|
|
|
|
+ .trim()
|
|
|
|
|
+ .to_string();
|
|
|
|
|
+ let detail_id = body.bill_detail_id.unwrap_or_default().trim().to_string();
|
|
|
|
|
+ if raw_ref.chars().count() > 64 {
|
|
|
|
|
+ return json_err(BosError::bad_params("raw_ref 超 64 字符(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if body.error_text.trim().is_empty() || body.error_text.chars().count() > 4000 {
|
|
|
|
|
+ return json_err(BosError::bad_params("error_text 必填且 ≤4000 字符(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if detail_id.is_empty() && raw_ref.is_empty() {
|
|
|
|
|
+ return json_err(BosError::bad_params("关联账单必填(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let mut matched_batch = String::new();
|
|
|
|
|
+ let mut matched_detail = String::new();
|
|
|
|
|
+ let mut matched_customer = String::new();
|
|
|
|
|
+ let mut matched_holder = String::new();
|
|
|
|
|
+ let mut period = String::new();
|
|
|
|
|
+
|
|
|
|
|
+ if !detail_id.is_empty() {
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT d.bill_detail_id, d.batch_no, d.customer_id, d.period, d.holder_id, b.status \
|
|
|
|
|
+ FROM bill_detail d JOIN reconcile_batch b ON b.batch_no=d.batch_no \
|
|
|
|
|
+ WHERE d.bill_detail_id=$1 AND d.status='active'",
|
|
|
|
|
+ &[json!(detail_id)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let Some(r) = rows.first() else {
|
|
|
|
|
+ return json_err(BosError::klt(KltCode::H20507, "关联的账单未出账(KLT-H20507)"));
|
|
|
|
|
+ };
|
|
|
|
|
+ if s(r, "status") != "executed" {
|
|
|
|
|
+ return json_err(BosError::klt(KltCode::H20507, "关联的账单未出账(KLT-H20507)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ matched_detail = s(r, "bill_detail_id");
|
|
|
|
|
+ matched_batch = s(r, "batch_no");
|
|
|
|
|
+ matched_customer = s(r, "customer_id");
|
|
|
|
|
+ matched_holder = s(r, "holder_id");
|
|
|
|
|
+ period = s(r, "period");
|
|
|
|
|
+ } else {
|
|
|
|
|
+ // 认批次号。
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT batch_no, period, holder_type, holder_id FROM reconcile_batch WHERE batch_no=$1",
|
|
|
|
|
+ &[json!(raw_ref)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if let Some(r) = rows.first() {
|
|
|
|
|
+ matched_batch = s(r, "batch_no");
|
|
|
|
|
+ matched_holder = s(r, "holder_id");
|
|
|
|
|
+ period = s(r, "period");
|
|
|
|
|
+ let cust = match qry(&state.db,
|
|
|
|
|
+ "SELECT customer_id FROM bill_detail WHERE batch_no=$1 AND status='active' LIMIT 1",
|
|
|
|
|
+ &[json!(raw_ref)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(x) => x,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if let Some(c) = cust.first() { matched_customer = s(c, "customer_id"); }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ // 认「客户名 + 自然月」或纯客户名。
|
|
|
|
|
+ let cust = match qry(&state.db,
|
|
|
|
|
+ "SELECT customer_id FROM customer WHERE customer_name=$1 AND deleted_at IS NULL LIMIT 1",
|
|
|
|
|
+ &[json!(raw_ref)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let mut found = cust.first().map(|r| s(r, "customer_id")).unwrap_or_default();
|
|
|
|
|
+ let mut maybe_period = String::new();
|
|
|
|
|
+ if found.is_empty() {
|
|
|
|
|
+ // 尝试剥离末尾的 YYYY-MM。
|
|
|
|
|
+ for cut in [8usize, 7usize] {
|
|
|
|
|
+ if raw_ref.chars().count() > cut {
|
|
|
|
|
+ let chars: Vec<char> = raw_ref.chars().collect();
|
|
|
|
|
+ let (name, tail) = chars.split_at(chars.len() - cut);
|
|
|
|
|
+ let tail_s: String = tail.iter().collect();
|
|
|
|
|
+ if tail_s.len() == 7 && tail_s.as_bytes()[4] == b'-' {
|
|
|
|
|
+ let nm: String = name.iter().collect::<String>().trim().to_string();
|
|
|
|
|
+ let r = match qry(&state.db,
|
|
|
|
|
+ "SELECT customer_id FROM customer WHERE customer_name=$1 AND deleted_at IS NULL LIMIT 1",
|
|
|
|
|
+ &[json!(nm)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if let Some(x) = r.first() {
|
|
|
|
|
+ found = s(x, "customer_id");
|
|
|
|
|
+ maybe_period = tail_s;
|
|
|
|
|
+ period = maybe_period.clone();
|
|
|
|
|
+ break;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if found.is_empty() {
|
|
|
|
|
+ return json_err(BosError::klt(
|
|
|
|
|
+ KltCode::H20501,
|
|
|
|
|
+ "无法识别归属区域(KLT-H20501):请改选客户账单/批次,或先补客户归属",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ matched_customer = found;
|
|
|
|
|
+ if !maybe_period.is_empty() {
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT d.bill_detail_id, d.batch_no FROM bill_detail d \
|
|
|
|
|
+ JOIN reconcile_batch b ON b.batch_no=d.batch_no \
|
|
|
|
|
+ WHERE d.customer_id=$1 AND d.period=$2 AND d.status='active' AND b.status='executed' \
|
|
|
|
|
+ ORDER BY d.bill_detail_id DESC LIMIT 1",
|
|
|
|
|
+ &[json!(matched_customer), json!(maybe_period)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if let Some(x) = rows.first() {
|
|
|
|
|
+ matched_detail = s(x, "bill_detail_id");
|
|
|
|
|
+ matched_batch = s(x, "batch_no");
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if matched_customer.is_empty() && matched_batch.is_empty() {
|
|
|
|
|
+ return json_err(BosError::klt(
|
|
|
|
|
+ KltCode::H20501,
|
|
|
|
|
+ "无法识别归属区域(KLT-H20501):请改选客户账单/批次,或先补客户归属",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ let (operator_name, region_node_id) = if matched_customer.is_empty() {
|
|
|
|
|
+ ("".to_string(), "".to_string())
|
|
|
|
|
+ } else {
|
|
|
|
|
+ match customer_region(&state.db, &matched_customer, &period).await {
|
|
|
|
|
+ Ok(x) => x,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+ if region_node_id.is_empty() {
|
|
|
|
|
+ return json_err(BosError::klt(
|
|
|
|
|
+ KltCode::H20501,
|
|
|
|
|
+ "无法识别归属区域(KLT-H20501):请先补客户归属",
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ let cid = format!(
|
|
|
|
|
+ "COR-{}-{}",
|
|
|
|
|
+ today().format("%Y%m%d"),
|
|
|
|
|
+ uuid_like()
|
|
|
|
|
+ );
|
|
|
|
|
+ if let Err(e) = state.db.dml(
|
|
|
|
|
+ "INSERT INTO billing_correction \
|
|
|
|
|
+ (correction_id, scope, raw_ref, matched_batch_no, matched_bill_detail_id, \
|
|
|
|
|
+ matched_holder_id, matched_customer_id, error_text, period, region_node_id, \
|
|
|
|
|
+ region_label, operator_name, severity, created_by, created_at) \
|
|
|
|
|
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,NULL,$11,'severe',$12,now())",
|
|
|
|
|
+ &[
|
|
|
|
|
+ json!(cid),
|
|
|
|
|
+ json!(if matched_batch.is_empty() { "customer" } else { "batch" }),
|
|
|
|
|
+ json!(raw_ref),
|
|
|
|
|
+ json!(if matched_batch.is_empty() { Value::Null } else { json!(matched_batch) }),
|
|
|
|
|
+ json!(if matched_detail.is_empty() { Value::Null } else { json!(matched_detail) }),
|
|
|
|
|
+ json!(if matched_holder.is_empty() { Value::Null } else { json!(matched_holder) }),
|
|
|
|
|
+ json!(if matched_customer.is_empty() { Value::Null } else { json!(matched_customer) }),
|
|
|
|
|
+ json!(body.error_text.trim()),
|
|
|
|
|
+ json!(if period.is_empty() { Value::Null } else { json!(period) }),
|
|
|
|
|
+ json!(region_node_id),
|
|
|
|
|
+ json!(operator_name),
|
|
|
|
|
+ json!(auth.user_id.clone()),
|
|
|
|
|
+ ],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ return json_err(e);
|
|
|
|
|
+ }
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "correction_id": cid,
|
|
|
|
|
+ "matched": !matched_batch.is_empty(),
|
|
|
|
|
+ "period": if period.is_empty() { Value::Null } else { json!(period) },
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+fn uuid_like() -> String {
|
|
|
|
|
+ use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
|
+ let n = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
|
|
|
|
|
+ format!("{:06}", n % 1_000_000)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct CorrectionListReq {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub period: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub region_node_id: Option<String>,
|
|
|
|
|
+ #[serde(default, rename = "operator_keyword")]
|
|
|
|
|
+ pub operator_kw: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub keyword: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub scope: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub page: Option<i64>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub page_size: Option<i64>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn correction_list(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(req): DataBody<CorrectionListReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let page = req.page.unwrap_or(0).max(0);
|
|
|
|
|
+ let size = req.page_size.unwrap_or(20).clamp(1, 100);
|
|
|
|
|
+ let offset = page * size;
|
|
|
|
|
+ let mut p = Params::default();
|
|
|
|
|
+ let mut w: Vec<String> = vec!["1=1".to_string()];
|
|
|
|
|
+ if let Some(pd) = req.period.as_deref().map(normalize_period).filter(|x| !x.is_empty()) {
|
|
|
|
|
+ w.push(format!("c.period = {}", p.push(json!(pd))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(rg) = req.region_node_id.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ w.push(format!("c.region_node_id = {}", p.push(json!(rg))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.operator_kw.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ w.push(format!("COALESCE(c.operator_name,'') ILIKE {}", p.push(json!(format!("%{}%", kw.trim())))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(sc) = req.scope.as_deref().filter(|x| !x.is_empty()) {
|
|
|
|
|
+ if !matches!(sc, "batch" | "customer" | "period") {
|
|
|
|
|
+ return json_err(BosError::bad_params("scope 非法(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ w.push(format!("c.scope = {}", p.push(json!(sc))));
|
|
|
|
|
+ }
|
|
|
|
|
+ if let Some(kw) = req.keyword.as_deref().filter(|x| !x.trim().is_empty()) {
|
|
|
|
|
+ let idx = p.push(json!(format!("%{}%", kw.trim())));
|
|
|
|
|
+ w.push(format!(
|
|
|
|
|
+ "(c.raw_ref ILIKE {idx} OR c.error_text ILIKE {idx} OR COALESCE(c.matched_batch_no,'') ILIKE {idx})"
|
|
|
|
|
+ ));
|
|
|
|
|
+ }
|
|
|
|
|
+ let where_sql = w.join(" AND ");
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ &format!(
|
|
|
|
|
+ "SELECT c.correction_id, c.scope, c.raw_ref, COALESCE(c.matched_batch_no,'') AS matched_batch_no, \
|
|
|
|
|
+ COALESCE(c.matched_customer_id,'') AS matched_customer_id, c.error_text, \
|
|
|
|
|
+ COALESCE(c.period,'') AS period, COALESCE(c.region_node_id,'') AS region_node_id, \
|
|
|
|
|
+ COALESCE(c.region_label,'') AS region_label, COALESCE(c.operator_name,'') AS operator_name, \
|
|
|
|
|
+ c.severity, c.created_by, CAST(c.created_at AS TEXT) AS created_at \
|
|
|
|
|
+ FROM billing_correction c WHERE {where_sql} \
|
|
|
|
|
+ ORDER BY c.created_at DESC, c.correction_id DESC LIMIT {size} OFFSET {offset}"
|
|
|
|
|
+ ),
|
|
|
|
|
+ p.values(),
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let total = match qry(&state.db,
|
|
|
|
|
+ &format!("SELECT COUNT(*) AS n FROM billing_correction c WHERE {where_sql}"),
|
|
|
|
|
+ p.values(),
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r.first().map(|x| i(x, "n")).unwrap_or(0),
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let items: Vec<Value> = rows.iter().map(|r| {
|
|
|
|
|
+ let batch = s(r, "matched_batch_no");
|
|
|
|
|
+ let cust = s(r, "matched_customer_id");
|
|
|
|
|
+ let text = s(r, "error_text");
|
|
|
|
|
+ let excerpt: String = text.chars().take(100).collect();
|
|
|
|
|
+ json!({
|
|
|
|
|
+ "correction_id": s(r, "correction_id"),
|
|
|
|
|
+ "created_at": s(r, "created_at"),
|
|
|
|
|
+ "period": os(r, "period"),
|
|
|
|
|
+ "region_node_id": s(r, "region_node_id"),
|
|
|
|
|
+ "region_label": os(r, "region_label"),
|
|
|
|
|
+ "holder_type": Value::Null,
|
|
|
|
|
+ "holder_id": Value::Null,
|
|
|
|
|
+ "holder_name": Value::Null,
|
|
|
|
|
+ "operator_key": Value::Null,
|
|
|
|
|
+ "operator_name": os(r, "operator_name"),
|
|
|
|
|
+ "scope": s(r, "scope"),
|
|
|
|
|
+ "raw_ref": s(r, "raw_ref"),
|
|
|
|
|
+ "matched": !batch.is_empty(),
|
|
|
|
|
+ "matched_batch_no": os(r, "matched_batch_no"),
|
|
|
|
|
+ "matched_customer_id": os(r, "matched_customer_id"),
|
|
|
|
|
+ "matched_customer_name": if cust.is_empty() { Value::Null } else { json!(cust) },
|
|
|
|
|
+ "ref_label": s(r, "raw_ref"),
|
|
|
|
|
+ "error_excerpt": excerpt,
|
|
|
|
|
+ "severity": s(r, "severity"),
|
|
|
|
|
+ "created_by": s(r, "created_by"),
|
|
|
|
|
+ })
|
|
|
|
|
+ }).collect();
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "items": items,
|
|
|
|
|
+ "total": total,
|
|
|
|
|
+ "page": page,
|
|
|
|
|
+ "page_size": size,
|
|
|
|
|
+ "period_progress": Value::Null,
|
|
|
|
|
+ "self_config": Value::Null,
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize, Default)]
|
|
|
|
|
+pub struct CorrectionQuery {
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub correction_id: Option<String>,
|
|
|
|
|
+ #[serde(default)]
|
|
|
|
|
+ pub id: Option<String>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn correction_detail(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ Query(q): Query<CorrectionQuery>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let id = q.correction_id.or(q.id).unwrap_or_default();
|
|
|
|
|
+ if id.is_empty() {
|
|
|
|
|
+ return json_err(BosError::bad_params("correction_id 必填(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT c.correction_id, c.scope, c.raw_ref, COALESCE(c.matched_batch_no,'') AS matched_batch_no, \
|
|
|
|
|
+ COALESCE(c.matched_bill_detail_id,'') AS matched_bill_detail_id, \
|
|
|
|
|
+ COALESCE(c.matched_customer_id,'') AS matched_customer_id, \
|
|
|
|
|
+ COALESCE(c.matched_holder_id,'') AS matched_holder_id, c.error_text, \
|
|
|
|
|
+ COALESCE(c.period,'') AS period, COALESCE(c.region_node_id,'') AS region_node_id, \
|
|
|
|
|
+ COALESCE(c.region_label,'') AS region_label, COALESCE(c.operator_name,'') AS operator_name, \
|
|
|
|
|
+ c.severity, c.created_by, CAST(c.created_at AS TEXT) AS created_at \
|
|
|
|
|
+ FROM billing_correction c WHERE c.correction_id=$1",
|
|
|
|
|
+ &[json!(id)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let Some(r) = rows.first() else {
|
|
|
|
|
+ return json_err(BosError::not_found(format!("更正记录不存在(11104):{id}")));
|
|
|
|
|
+ };
|
|
|
|
|
+ ok(json!({
|
|
|
|
|
+ "correction_id": s(r, "correction_id"),
|
|
|
|
|
+ "created_at": s(r, "created_at"),
|
|
|
|
|
+ "period": os(r, "period"),
|
|
|
|
|
+ "region_node_id": s(r, "region_node_id"),
|
|
|
|
|
+ "region_label": os(r, "region_label"),
|
|
|
|
|
+ "holder_type": Value::Null,
|
|
|
|
|
+ "holder_id": Value::Null,
|
|
|
|
|
+ "holder_name": Value::Null,
|
|
|
|
|
+ "matched_holder_id": os(r, "matched_holder_id"),
|
|
|
|
|
+ "operator_key": Value::Null,
|
|
|
|
|
+ "operator_name": os(r, "operator_name"),
|
|
|
|
|
+ "scope": s(r, "scope"),
|
|
|
|
|
+ "raw_ref": s(r, "raw_ref"),
|
|
|
|
|
+ "ref_label": s(r, "raw_ref"),
|
|
|
|
|
+ "matched": !s(r, "matched_batch_no").is_empty(),
|
|
|
|
|
+ "matched_batch_no": os(r, "matched_batch_no"),
|
|
|
|
|
+ "matched_bill_detail_id": os(r, "matched_bill_detail_id"),
|
|
|
|
|
+ "matched_customer_id": os(r, "matched_customer_id"),
|
|
|
|
|
+ "matched_customer_name": Value::Null,
|
|
|
|
|
+ "error_text": s(r, "error_text"),
|
|
|
|
|
+ "severity": s(r, "severity"),
|
|
|
|
|
+ "created_by": s(r, "created_by"),
|
|
|
|
|
+ }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[derive(Deserialize)]
|
|
|
|
|
+pub struct DraftSaveReq {
|
|
|
|
|
+ pub form: Value,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn correction_draft_save(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+ DataBody(body): DataBody<DraftSaveReq>,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let text = body.form.to_string();
|
|
|
|
|
+ if text.len() > 64 * 1024 {
|
|
|
|
|
+ return json_err(BosError::bad_params("草稿表单整体超 64 KB(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ if body.form.get("user_id").is_some() {
|
|
|
|
|
+ return json_err(BosError::bad_params("user_id 由系统带出,不接受录入(11103)"));
|
|
|
|
|
+ }
|
|
|
|
|
+ let uid = auth.user_id.clone();
|
|
|
|
|
+ let n = match state.db.dml(
|
|
|
|
|
+ "UPDATE billing_correction_draft SET form=$2::text::jsonb, updated_at=now() WHERE user_id=$1",
|
|
|
|
|
+ &[json!(uid), json!(body.form)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(n) => n,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ if n == 0 {
|
|
|
|
|
+ if let Err(e) = state.db.dml(
|
|
|
|
|
+ "INSERT INTO billing_correction_draft (user_id, form, updated_at) VALUES ($1,$2::text::jsonb,now())",
|
|
|
|
|
+ &[json!(uid), json!(body.form)],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ return json_err(e);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ ok(json!({ "saved": true }))
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn correction_draft_get(
|
|
|
|
|
+ State(state): State<AppState>,
|
|
|
|
|
+ RequireAuth(auth): RequireAuth,
|
|
|
|
|
+) -> Response {
|
|
|
|
|
+ if let Err(e) = can_view(&auth) { return json_err(e); }
|
|
|
|
|
+ let rows = match qry(&state.db,
|
|
|
|
|
+ "SELECT form FROM billing_correction_draft WHERE user_id=$1",
|
|
|
|
|
+ &[json!(auth.user_id.clone())],
|
|
|
|
|
+ ).await {
|
|
|
|
|
+ Ok(r) => r,
|
|
|
|
|
+ Err(e) => return json_err(e),
|
|
|
|
|
+ };
|
|
|
|
|
+ let form = rows.first().map(|r| r.get("form").cloned().unwrap_or(json!({}))).unwrap_or(json!({}));
|
|
|
|
|
+ ok(json!({ "form": form }))
|
|
|
|
|
+}
|
|
|
|
|
+
|