Ver Fonte

fix(recon): 落地份数/档位成本与档案分成,补 bill/detail 成本出参

按对账金额偏差缺陷收敛:quantity 进应收与 per_copy;plan_cost_item 组合价优先档位补漏;分成快照去 share_rule;bill/detail 补实扣/应扣与月天数单价。G-4 分账号按天折算仍待开停列。

Co-authored-by: Cursor <cursoragent@cursor.com>
cg há 1 dia atrás
pai
commit
781fe9c3c7
1 ficheiros alterados com 571 adições e 24 exclusões
  1. 571 24
      src/modules/account/src/handlers/billing.rs

+ 571 - 24
src/modules/account/src/handlers/billing.rs

@@ -6,9 +6,14 @@
 //! 一期取数口径(与设计册的差异,均已在交付说明中登记):
 //! 1. 第 5 册工单/开停未实现 ⇒ 无 `open_stop_facts`,分账号按现有 `sub_account`
 //!    且 `status <> 'not_opened'` 视为本期在期,天数取订阅本期计费天数(整月计)。
-//! 2. 成本明细未落到客户/省份/运营商维度 ⇒ 应收的成本抵扣为 0、`cost_snapshot=[]`,
-//!    对账清单「总成本」如实为 0(⛔ 不按客户摊派)。
+//!    账号级开通/停机日折算待 `sub_account` 加列+开停域落地(G-4)。
+//! 2. 成本按「客户省份 × 期初归属运营商」组合取数(`billing_snapshot_cost_price` 期初
+//!    冻结 ⇒ 事后改价⛔ 回改已出账期次);组合无定价的成本项按 0 计并在 `cost_snapshot`
+//!    标 `configured:false`。`per_copy` 乘数取订阅 `quantity`;档位随附成本项
+//!    (`plan_cost_item`)按「组合价优先、档位补漏」并入明细;`billing_receivable`
+//!    没有设计册的 `cost_cents` 两列 ⇒ 取数组合与单价由 `cost_snapshot` JSON 承载。
 //! 3. 客户归属区域 = 客户所属运营商/合作伙伴的区域;两者皆空时落空串(表列 NOT NULL)。
+//! 4. 分成快照只取档案两列(U-100/2026-11-04),⛔ 再读客户级 `share_rule`。
 
 use axum::extract::{Query, State};
 use axum::response::Response;
@@ -17,7 +22,7 @@ use bos_api::AppState;
 use bos_core::error::KltCode;
 use bos_core::{BosError, RoleCode};
 use bos_platform::audit::AuditEvent;
-use bos_platform::clients::uds::UdsClient;
+use bos_platform::clients::uds::{DmlStatement, UdsClient};
 use bos_scope::{AuthContext, ScopedSelect};
 use chrono::{Datelike, Duration, NaiveDate, Utc};
 use serde::Deserialize;
@@ -1730,6 +1735,50 @@ pub async fn recon_detail(
         "zero_note": os(r, "zero_note"),
     })).collect();
 
+    // 「成本未配」清单:本批明细的 `billing_receivable.cost_snapshot` 里 `configured:false`
+    // 的成本项(去重)——组合齐备但该组合未配金额 ⇒ 按 0 计,页面据此提示(04 册 04 §4.1 ⑤)。
+    // 取数失败只坏这一格(回空数组),⛔ 整页报错。
+    let cost_unconfigured: Vec<Value> = match qry(&state.db,
+        "SELECT COALESCE(r.cost_snapshot, '[]') AS cs \
+           FROM bill_detail d \
+           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'",
+        &[json!(batch_no)],
+    )
+    .await
+    {
+        Ok(rows) => {
+            let mut seen: HashSet<String> = HashSet::new();
+            let mut out: Vec<Value> = Vec::new();
+            for r in rows {
+                let raw = {
+                    let t = s(&r, "cs");
+                    if t.is_empty() { "[]".to_string() } else { t }
+                };
+                let Ok(entries) = serde_json::from_str::<Value>(&raw) else { continue };
+                let Some(arr) = entries.as_array() else { continue };
+                for e in arr {
+                    if e["configured"].as_bool() != Some(false) {
+                        continue;
+                    }
+                    let id = e["item_id"].as_str().unwrap_or_default().to_string();
+                    if id.is_empty() || !seen.insert(id.clone()) {
+                        continue;
+                    }
+                    out.push(json!({
+                        "item_id": id,
+                        "item_name": e["item_name"].as_str().unwrap_or_default(),
+                    }));
+                }
+            }
+            out
+        }
+        Err(e) => {
+            tracing::warn!(err = %err_text(&e), "成本未配清单取数失败(批次详情 cost_unconfigured 回空)");
+            Vec::new()
+        }
+    };
+
     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();
@@ -1790,11 +1839,406 @@ pub async fn recon_detail(
         "can_correct": can_correct,
         "ticket_gap_count": ticket_gap_count,
         "ticket_gap_failed": ticket_gap_failed,
-        "cost_unconfigured": [],
+        "cost_unconfigured": cost_unconfigured,
         "items": detail_items,
     }))
 }
 
+// ─────────────────── 成本:期初快照与取数(04 册 02 §2.4/06 册 04 §2 第 7、8 步) ───────────────────
+//
+// 口径(04 册 04 §4.1/§6.3、06 册 02 §1.2):
+// * 取数组合=「客户省份 × 期初归属运营商」,省份是 `billing_snapshot_customer.region_node_id`
+//   的**省级祖先**(层级真源=业务侧自持的 `bos_region_meta.level`,⛔ 由平台 `depth` 推导),
+//   运营商取**期初快照**(期中换运营商 ⇒ 整月按变更前,TC-FN-60);
+// * `effective_mode='period_snapshot'`(默认)金额与定义读 `billing_snapshot_cost_price`
+//   (期初冻结 ⇒ 事后改价/改定义⛔ 回改已出账期次,TC-FN-06/67);
+//   `'live_at_billing'` 金额与定义读活表,组合键仍取期初快照(TC-FN-66/67 的第二档);
+// * 金额=`cost_amount.amount_cents`(单位=分/月,⛔ 再 ×100),乘数按 `billing_unit`
+//   取一/人天/份数,`per_account` 按「在期人天 ÷ 当月天数」折算,按分四舍五入;
+// * 未配金额=该组合无行 ⇒ 按 0 计并在 `cost_snapshot` 里标 `configured:false`(§4.1 ⑤);
+// * 只有 `deduct_from_base=true` 的条目进 `cost_deduct_cents`(先收回成本再分成)。
+
+/// 成本价格行(快照表与活表的同形投影)。
+#[derive(Debug, Clone)]
+struct CostPrice {
+    item_id: String,
+    item_name: String,
+    category: String,
+    billing_unit: String,
+    deduct_from_base: bool,
+    amount_cents: i64,
+}
+
+/// 账期成本取数索引:`(省份节点, 运营商) → 成本条目`。
+///
+/// 一次性整表取回内存建索引(06 册 04 §2 第 7 步「批量预取,⛔ 逐订阅发查询」)。
+async fn load_cost_prices(
+    db: &UdsClient,
+    period: &str,
+    effective_mode: &str,
+) -> Result<HashMap<(String, String), Vec<CostPrice>>, BosError> {
+    let live = effective_mode == "live_at_billing";
+    let sql = if live {
+        "SELECT ca.province_node_id, ca.operator_id, ci.item_id, ci.item_name, ci.category, \
+                ci.billing_unit, ci.deduct_from_base, ca.amount_cents \
+           FROM cost_amount ca JOIN cost_item ci ON ci.item_id = ca.item_id \
+          WHERE ca.period IS NULL"
+    } else {
+        "SELECT province_node_id, operator_id, cost_item_id AS item_id, item_name, category, \
+                billing_unit, deduct_from_base, amount_cents \
+           FROM billing_snapshot_cost_price WHERE period = $1::text"
+    };
+    let ps: Vec<Value> = if live { vec![] } else { vec![json!(period)] };
+    let rows = qry(db, sql, &ps).await?;
+    let mut idx: HashMap<(String, String), Vec<CostPrice>> = HashMap::new();
+    for r in rows {
+        let key = (s(&r, "province_node_id"), s(&r, "operator_id"));
+        if key.0.is_empty() || key.1.is_empty() {
+            continue;
+        }
+        idx.entry(key).or_default().push(CostPrice {
+            item_id: s(&r, "item_id"),
+            item_name: s(&r, "item_name"),
+            category: s(&r, "category"),
+            billing_unit: s(&r, "billing_unit"),
+            deduct_from_base: b(&r, "deduct_from_base"),
+            amount_cents: oi(&r, "amount_cents").unwrap_or(0),
+        });
+    }
+    Ok(idx)
+}
+
+/// 成本项目录(全局定义,用于把「该组合未配金额」的条目如实标 `configured:false`)。
+async fn load_cost_catalog(db: &UdsClient) -> Result<Vec<CostPrice>, BosError> {
+    let rows = qry(
+        db,
+        "SELECT item_id, item_name, category, billing_unit, deduct_from_base FROM cost_item",
+        &[],
+    )
+    .await?;
+    Ok(rows
+        .into_iter()
+        .map(|r| CostPrice {
+            item_id: s(&r, "item_id"),
+            item_name: s(&r, "item_name"),
+            category: s(&r, "category"),
+            billing_unit: s(&r, "billing_unit"),
+            deduct_from_base: b(&r, "deduct_from_base"),
+            amount_cents: 0,
+        })
+        .collect())
+}
+
+/// 节点 → 省级祖先(`dim_node_ancestor × bos_region_meta.level`;闭包表含自身行 ⇒ 省节点命中自身)。
+async fn province_map(db: &UdsClient) -> HashMap<String, String> {
+    let sql = "SELECT a.node_id, a.ancestor_id, CAST(a.depth AS BIGINT) AS depth \
+                 FROM dim_node_ancestor a JOIN bos_region_meta m ON m.node_id = a.ancestor_id \
+                WHERE m.level IN ('省','province') ORDER BY CAST(a.depth AS BIGINT) ASC";
+    match qry(db, sql, &[]).await {
+        Ok(rows) => {
+            let mut m: HashMap<String, String> = HashMap::new();
+            for r in rows {
+                // 已按 depth 升序 ⇒ 首个即最近省级祖先,更远的祖先⛔ 覆盖它。
+                m.entry(s(&r, "node_id"))
+                    .or_insert_with(|| s(&r, "ancestor_id"));
+            }
+            m
+        }
+        Err(e) => {
+            tracing::warn!(err = %err_text(&e), "省级祖先读失败,成本组合按无省份处理(成本按 0 计)");
+            HashMap::new()
+        }
+    }
+}
+
+/// 运营商档案品牌(只为在 `cost_snapshot` 里如实记下取数组合,04 册 04 §8.5)。
+async fn operator_brand_map(db: &UdsClient) -> HashMap<String, String> {
+    match qry(db, "SELECT operator_id, brand FROM operator", &[]).await {
+        Ok(rows) => rows
+            .into_iter()
+            .map(|r| (s(&r, "operator_id"), s(&r, "brand")))
+            .collect(),
+        Err(_) => HashMap::new(),
+    }
+}
+
+/// 出账生效口径(`billing_config.effective_mode`):只认 `live_at_billing`,其余一律 `period_snapshot`。
+///
+/// 读不到配置(表未初始化/查询失败)⇒ 回落默认档 `period_snapshot`,⛔ 因配置读失败整期不出账。
+async fn billing_effective_mode(db: &UdsClient) -> String {
+    let m = qry(db, "SELECT effective_mode FROM billing_config WHERE id = 1", &[])
+        .await
+        .ok()
+        .and_then(|rows| rows.first().map(|r| s(r, "effective_mode")))
+        .unwrap_or_default();
+    if m == "live_at_billing" {
+        "live_at_billing".to_string()
+    } else {
+        "period_snapshot".to_string()
+    }
+}
+
+/// 期初成本快照冻结(04 册 02 §2.4:`billing_snapshot_cost_price`)。
+///
+/// 只冻结**组合齐备**(省份+运营商都非空)的差异行,定义取 `cost_item` 当时的值;
+/// `WHERE NOT EXISTS` ⇒ 同账期重复冻结/人工补跑沿用**首次**冻结值(事后改价/改定义
+/// ⛔ 回改已出账期次,TC-FN-06/67)。
+///
+/// ⚠️ 逐行单语句走 `dml/batch`(⛔ `INSERT … SELECT … JOIN`):跨表 SELECT 的写入形态
+/// 在本引擎尚未验证,先走本文件已验证的「`INSERT … SELECT` 常量 + `NOT EXISTS` 幂等」。
+async fn freeze_cost_snapshot(db: &UdsClient, period: &str) -> Result<(), BosError> {
+    let rows = qry(db,
+        "SELECT ca.province_node_id, ca.operator_id, COALESCE(op.brand,'') AS brand, \
+                ci.item_id, ci.item_name, ci.category, ci.billing_unit, \
+                CAST(ci.is_amortized AS TEXT) AS is_amortized, \
+                CAST(ci.amortization_months AS TEXT) AS amortization_months, \
+                CAST(ci.deduct_from_base AS TEXT) AS deduct_from_base, \
+                CAST(ca.amount_cents AS TEXT) AS amount_cents \
+           FROM cost_amount ca \
+           JOIN cost_item ci ON ci.item_id = ca.item_id \
+           LEFT JOIN operator op ON op.operator_id = ca.operator_id \
+          WHERE ca.period IS NULL \
+            AND COALESCE(ca.province_node_id,'') <> '' \
+            AND COALESCE(ca.operator_id,'') <> ''",
+        &[],
+    ).await?;
+    if rows.is_empty() {
+        return Ok(());
+    }
+    const INS: &str = "INSERT INTO billing_snapshot_cost_price \
+            (period, province_node_id, operator_id, brand, cost_item_id, item_name, category, \
+             billing_unit, is_amortized, amortization_months, deduct_from_base, amount_cents, frozen_at) \
+         SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,now() \
+         WHERE NOT EXISTS (SELECT 1 FROM billing_snapshot_cost_price \
+                WHERE period=$1 AND province_node_id=$2 AND operator_id=$3 AND cost_item_id=$5)";
+    // ⚠️ 参数⛔ 带显式类型转换:`$9::boolean` / `$10::integer` 会让服务端把绑定值按 text 解析,
+    //    布尔/整型的二进制值随即报 `invalid byte sequence for encoding "UTF8": 0x00`。
+    //    裸参数由 INSERT 目标列推导类型(与应收 INSERT 同一写法),实测通过。
+    // ⚠️ 但**裸参数绑 JSON `null`** 时 UDS 按 text 发送,目标列 `amortization_months` 是 integer
+    //    且无隐式 text→integer 转换 ⇒ `column "amortization_months" is of type integer but
+    //    expression is of type text`(2026-11-24 实测:目录中「不摊销」成本项=NULL,整批冻结
+    //    在 statements[0] 即失败,出账中断)。NULL 走字面量分支(实测 `SELECT … NULL …` 可行)。
+    const INS_NO_MONTHS: &str = "INSERT INTO billing_snapshot_cost_price \
+            (period, province_node_id, operator_id, brand, cost_item_id, item_name, category, \
+             billing_unit, is_amortized, amortization_months, deduct_from_base, amount_cents, frozen_at) \
+         SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,NULL,$10,$11,now() \
+         WHERE NOT EXISTS (SELECT 1 FROM billing_snapshot_cost_price \
+                WHERE period=$1 AND province_node_id=$2 AND operator_id=$3 AND cost_item_id=$5)";
+    let stmts: Vec<DmlStatement> = rows
+        .iter()
+        .map(|r| {
+            let head = vec![
+                json!(period),
+                json!(s(r, "province_node_id")),
+                json!(s(r, "operator_id")),
+                json!(s(r, "brand")),
+                json!(s(r, "item_id")),
+                json!(s(r, "item_name")),
+                json!(s(r, "category")),
+                json!(s(r, "billing_unit")),
+                json!(b(r, "is_amortized")),
+            ];
+            let deduct = json!(b(r, "deduct_from_base"));
+            let amount = json!(oi(r, "amount_cents").unwrap_or(0));
+            match oi(r, "amortization_months") {
+                Some(m) => {
+                    let mut ps = head;
+                    ps.extend([json!(m), deduct, amount]);
+                    DmlStatement::new(INS, ps)
+                }
+                None => {
+                    let mut ps = head;
+                    ps.extend([deduct, amount]);
+                    DmlStatement::new(INS_NO_MONTHS, ps)
+                }
+            }
+        })
+        .collect();
+    for chunk in stmts.chunks(100) {
+        let res = db.dml_batch(chunk).await.map_err(|e| {
+            BosError::internal(format!("成本快照冻结: {}", err_text(&e)))
+        })?;
+        if res.len() != chunk.len() {
+            return Err(BosError::internal(format!(
+                "成本快照冻结短批:期望 {},实得 {}",
+                chunk.len(),
+                res.len()
+            )));
+        }
+    }
+    tracing::info!(period, rows = stmts.len(), "成本期初快照已冻结");
+    Ok(())
+}
+
+/// 单订阅的成本明细与**应扣除合计**(06 册 04 §2 第 8 步)。
+///
+/// * 组合缺失(客户无省份或无期初归属运营商)⇒ 无条目、成本 0(⛔ 按客户摊派);
+/// * 组合齐备 ⇒ 该组合**有定价**的成本项逐条列出,目录里其余成本项按 0 计并标
+///   `configured:false`(04 册 04 §4.1 ⑤「未配金额」,页面据此给「成本未配」提示);
+/// * `per_account` 按「在期人天 ÷ 当月天数」折算(30000×3×21/31 → 60968),按分四舍五入;
+/// * `cost_deduct_cents` 只累加 `deduct_from_base=true`,并以应收为上限(恒等式
+///   `share_base = receivable − cost_deduct` 逐笔成立),超出部分只告警⛔ 静默吞掉。
+#[allow(clippy::too_many_arguments)]
+fn cost_breakdown(
+    combo: Option<(&str, &str)>,
+    priced: &[CostPrice],
+    catalog: &[CostPrice],
+    brands: &HashMap<String, String>,
+    source: &str,
+    accounts: i64,
+    days: i64,
+    month_days: i64,
+    copies: i64,
+    plan_item_ids: Option<&HashSet<String>>,
+) -> (i64, Vec<Value>) {
+    let Some((prov, op)) = combo else {
+        return (0, Vec::new());
+    };
+    let brand = brands.get(op).cloned().unwrap_or_default();
+    let combo_json = json!({
+        "province_node_id": prov,
+        "operator_id": op,
+        "brand": brand,
+    });
+    let md = month_days.max(1) as f64;
+    let copy_mult = copies.max(1) as f64;
+    let acct_mult = accounts.max(0) as f64 * days as f64 / md;
+    let mut entries: Vec<Value> = Vec::new();
+    let mut deduct = 0i64;
+    let mut priced_ids: HashSet<&str> = HashSet::new();
+    for p in priced {
+        priced_ids.insert(p.item_id.as_str());
+        let (mult, kind) = match p.billing_unit.as_str() {
+            "per_account" => (acct_mult, "in_period_accounts"),
+            "per_copy" => (copy_mult, "copies"),
+            _ => (1.0, "one"),
+        };
+        let cents = (p.amount_cents as f64 * mult).round() as i64;
+        if p.deduct_from_base {
+            deduct += cents;
+        }
+        let plan_attached = plan_item_ids
+            .map(|ids| ids.contains(&p.item_id))
+            .unwrap_or(false);
+        entries.push(json!({
+            "item_id": p.item_id,
+            "item_name": p.item_name,
+            "category": p.category,
+            "billing_unit": p.billing_unit,
+            "calc_basis": "monthly",
+            "multiplier": ((mult * 10000.0).round() / 10000.0),
+            "multiplier_kind": kind,
+            "price_cents": p.amount_cents,
+            "cost_cents": cents,
+            "deduct_from_base": p.deduct_from_base,
+            "configured": true,
+            "source": source,
+            "plan_attached": plan_attached,
+            "combo": combo_json,
+        }));
+    }
+    // 档位补漏:挂在 plan_cost_item、组合未配价的项 ⇒ configured:false、source=plan_cost_item。
+    let mut plan_filled: HashSet<&str> = HashSet::new();
+    if let Some(ids) = plan_item_ids {
+        for c in catalog {
+            if priced_ids.contains(c.item_id.as_str()) || !ids.contains(&c.item_id) {
+                continue;
+            }
+            plan_filled.insert(c.item_id.as_str());
+            let kind = match c.billing_unit.as_str() {
+                "per_account" => "in_period_accounts",
+                "per_copy" => "copies",
+                _ => "one",
+            };
+            let mult = match kind {
+                "in_period_accounts" => acct_mult,
+                "copies" => copy_mult,
+                _ => 1.0,
+            };
+            entries.push(json!({
+                "item_id": c.item_id,
+                "item_name": c.item_name,
+                "category": c.category,
+                "billing_unit": c.billing_unit,
+                "calc_basis": "monthly",
+                "multiplier": ((mult * 10000.0).round() / 10000.0),
+                "multiplier_kind": kind,
+                "price_cents": 0,
+                "cost_cents": 0,
+                "deduct_from_base": c.deduct_from_base,
+                "configured": false,
+                "source": "plan_cost_item",
+                "plan_attached": true,
+                "combo": combo_json,
+            }));
+        }
+    }
+    for c in catalog {
+        if priced_ids.contains(c.item_id.as_str()) || plan_filled.contains(c.item_id.as_str()) {
+            continue;
+        }
+        let kind = match c.billing_unit.as_str() {
+            "per_account" => "in_period_accounts",
+            "per_copy" => "copies",
+            _ => "one",
+        };
+        let mult = match kind {
+            "in_period_accounts" => acct_mult,
+            "copies" => copy_mult,
+            _ => 1.0,
+        };
+        entries.push(json!({
+            "item_id": c.item_id,
+            "item_name": c.item_name,
+            "category": c.category,
+            "billing_unit": c.billing_unit,
+            "calc_basis": "monthly",
+            "multiplier": ((mult * 10000.0).round() / 10000.0),
+            "multiplier_kind": kind,
+            "price_cents": 0,
+            "cost_cents": 0,
+            "deduct_from_base": c.deduct_from_base,
+            "configured": false,
+            "source": source,
+            "plan_attached": false,
+            "combo": combo_json,
+        }));
+    }
+    (deduct, entries)
+}
+
+/// 档位 → 随附成本项 id 集(活表现读;与成本索引同轮预取,⛔ 逐订阅往返)。
+async fn load_plan_cost_items(db: &UdsClient) -> HashMap<String, HashSet<String>> {
+    match qry(
+        db,
+        "SELECT plan_id, cost_item_id AS item_id FROM plan_cost_item \
+         WHERE cost_item_id IS NOT NULL AND CAST(cost_item_id AS TEXT) <> ''",
+        &[],
+    )
+    .await
+    {
+        Ok(rows) => {
+            let mut m: HashMap<String, HashSet<String>> = HashMap::new();
+            for r in rows {
+                let pid = s(&r, "plan_id");
+                let iid = s(&r, "item_id");
+                if pid.is_empty() || iid.is_empty() {
+                    continue;
+                }
+                m.entry(pid).or_default().insert(iid);
+            }
+            m
+        }
+        Err(e) => {
+            tracing::warn!(
+                err = %err_text(&e),
+                "plan_cost_item 预取失败 ⇒ 档位随附成本项本轮不并入"
+            );
+            HashMap::new()
+        }
+    }
+}
+
 // ─────────────────────────── 6. RECON 两阶段引擎 ───────────────────────────
 
 /// 期首次冻结:客户归属快照 + 分成规则快照。返回 (是否已冻结, 分账号快照已有行数)。
@@ -1846,16 +2290,18 @@ pub(crate) async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool,
         &[json!(period)],
     ).await?;
 
-    // ② 分成规则快照:档案值,客户级 share_rule 覆盖(仅 active)。
+    // ①半 成本期初冻结(04 册 02 §2.4):读**活表**差异行落一期一份快照,
+    // 之后 `period_snapshot` 档只读快照 ⇒ 期中改价⛔ 回改本期(TC-FN-06/67)。
+    freeze_cost_snapshot(db, period).await?;
+
+    // ② 分成规则快照:档案两列统一生效(U-100/2026-11-04),⛔ 客户级 share_rule。
     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() \
+                o.settle_mode, 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 \
+         WHERE c.deleted_at IS NULL AND 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)],
@@ -1863,12 +2309,10 @@ pub(crate) async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool,
     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() \
+                pt.settle_mode, 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 \
+         WHERE c.deleted_at IS NULL AND 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)],
@@ -1876,12 +2320,10 @@ pub(crate) async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool,
     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() \
+                t.settle_mode, 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 \
+         WHERE 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 \
@@ -1906,6 +2348,7 @@ pub(crate) async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool,
     let subs_sql = format!(
         "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, \
+                COALESCE(quantity,1) AS quantity, \
                 CAST(start_date AS TEXT) AS start_date, \
                 CAST(({eff}) AS TEXT) AS end_date, \
                 COALESCE(plan_id,'') AS plan_id \
@@ -1917,7 +2360,55 @@ pub(crate) async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool,
     );
     let subs = qry(db, &subs_sql, &[json!(pstart), json!(pend)]).await?;
 
+    // ③半 成本预取(06 册 04 §2 第 7 步:一次性取回内存建索引,⛔ 逐订阅发查询)。
     let month_days = month_end(first).day() as i64;
+    let eff_mode = billing_effective_mode(db).await;
+    let cost_index = load_cost_prices(db, period, &eff_mode).await?;
+    let cost_catalog = load_cost_catalog(db).await?;
+    let plan_costs = load_plan_cost_items(db).await;
+    let provinces = province_map(db).await;
+    let brands = operator_brand_map(db).await;
+    let mut accounts: HashMap<String, i64> = HashMap::new();
+    let mut combos: HashMap<String, (String, String)> = HashMap::new();
+    if cost_index.is_empty() {
+        tracing::debug!(period, eff_mode = %eff_mode, "本期无成本定价(组合 0 个)⇒ 成本抵扣按 0 计");
+    } else {
+        // 在期账号数(`per_account` 乘数;未开通不计,与 `billing_receivable_account` 同判据)。
+        match qry(db, "SELECT subscription_id, COUNT(*)::text AS n FROM sub_account \
+                        WHERE COALESCE(status,'') <> 'not_opened' GROUP BY subscription_id", &[]).await {
+            Ok(rows) => {
+                for r in rows {
+                    accounts.insert(s(&r, "subscription_id"), oi(&r, "n").unwrap_or(0));
+                }
+            }
+            Err(e) => tracing::warn!(err = %err_text(&e), "在期账号数预取失败 ⇒ per_account 成本按 0 个账号计"),
+        }
+        // 客户 → 取数组合:省份=**期初归属区域**的省级祖先,运营商=**期初归属**(⛔ 读活表,TC-FN-60)。
+        match qry(db, "SELECT customer_id, region_node_id, operator_id \
+                         FROM billing_snapshot_customer WHERE period = $1", &[json!(period)]).await {
+            Ok(rows) => {
+                for r in rows {
+                    let op = s(&r, "operator_id");
+                    if op.is_empty() {
+                        continue;
+                    }
+                    if let Some(prov) = provinces.get(&s(&r, "region_node_id")) {
+                        combos.insert(s(&r, "customer_id"), (prov.clone(), op));
+                    }
+                }
+                if combos.is_empty() {
+                    tracing::warn!(
+                        period,
+                        priced_combos = cost_index.len(),
+                        "有成本定价但无客户命中「省份×运营商」组合 ⇒ 成本抵扣按 0 计\
+                         (检查 billing_snapshot_customer.region_node_id 与 bos_region_meta.level)"
+                    );
+                }
+            }
+            Err(e) => tracing::warn!(err = %err_text(&e), "期初归属快照读失败 ⇒ 成本抵扣按 0 计"),
+        }
+    }
+
     for row in &subs {
         let sid = s(row, "subscription_id");
         let cid = s(row, "customer_id");
@@ -1933,25 +2424,64 @@ pub(crate) async fn freeze_period(db: &UdsClient, period: &str) -> Result<bool,
             let m = i(row, "monthly");
             if m > 0 { m } else { round_half_up(i(row, "annual") as i128, 12) }
         };
+        // 份数:附加订阅 quantity≥1;link 恒 1。settle_std 仍落单价,应收再乘份数。
+        let qty = i(row, "quantity").max(1);
         // 试用窗口:计费起点起 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 pre_align = if in_trial {
+            0
+        } else {
+            round_half_up(std as i128 * qty as i128 * days as i128, month_days as i128)
+        };
         let receivable = pre_align;
-        let cost = 0i64;
-        let share_base = (receivable - cost).max(0);
+        // 成本抵扣(尾月对齐**之后**做减法,06 册 04 §2 第 8 步):组合缺失 ⇒ 无条目、0;
+        // 应扣大于应收 ⇒ 实扣以应收为上限(分成基数按 0),并留 warn(⛔ 静默吞掉)。
         let plan = s(row, "plan_id");
-        let _ = plan;
+        let plan_ids = plan_costs.get(&plan);
+        let combo = combos.get(&cid).cloned();
+        let (cost_should, cost_entries) = match &combo {
+            Some((prov, op)) => {
+                let none: Vec<CostPrice> = Vec::new();
+                cost_breakdown(
+                    Some((prov.as_str(), op.as_str())),
+                    cost_index.get(&(prov.clone(), op.clone())).unwrap_or(&none),
+                    &cost_catalog,
+                    &brands,
+                    &eff_mode,
+                    accounts.get(&sid).copied().unwrap_or(0),
+                    days,
+                    month_days,
+                    qty,
+                    plan_ids,
+                )
+            }
+            None => (0i64, Vec::new()),
+        };
+        let cost = cost_should.min(receivable.max(0));
+        if receivable > 0 && cost_should > receivable {
+            tracing::warn!(
+                period,
+                subscription_id = %sid,
+                receivable,
+                cost_should_deduct = cost_should,
+                cost_deducted = cost,
+                "成本应扣除大于应收 ⇒ 分成基数按 0,实扣以应收为上限"
+            );
+        }
+        let share_base = receivable - cost;
+        let cost_json = serde_json::to_string(&cost_entries).unwrap_or_else(|_| "[]".to_string());
         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() \
+                 effective_mode, bill_from, bill_to, cost_snapshot, created_at) \
+             SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13::date,$14::date,$15::text::jsonb,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()),
+                json!(share_base), json!(eff_mode), json!(from.to_string()), json!(to.to_string()),
+                json!(cost_json),
             ],
         ).await?;
         // 在期账号(M4:**按订阅**取账号——席位归属订阅,同一客户多份订阅各算各的;未开通不计;
@@ -2503,6 +3033,8 @@ pub async fn bill_detail(
                 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.settle_std_cents,0) AS settle_std_cents, \
+                COALESCE(r.month_days,0) AS month_days, \
                 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 \
@@ -2572,11 +3104,22 @@ pub async fn bill_detail(
 
     let receivable = i(r, "receivable_cents");
     let base = i(r, "share_base_cents");
+    let cost_deduct = i(r, "cost_deduct_cents");
     // 成本快照:一期无客户级成本归属 ⇒ 冻结数组为空(如实为空,⛔ 按客户摊派)。
+    // costs[].cost_cents=应扣(封顶前);顶层 cost_deduct_cents=实扣(O-12/O-13)。
     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!([]));
+    let cost_should_deduct: i64 = costs
+        .as_array()
+        .map(|arr| {
+            arr.iter()
+                .filter(|e| e.get("deduct_from_base").and_then(|v| v.as_bool()).unwrap_or(false))
+                .map(|e| e.get("cost_cents").and_then(|v| v.as_i64()).unwrap_or(0))
+                .sum()
+        })
+        .unwrap_or(0);
     let mut out = json!({
         "bill_detail_id": s(r, "bill_detail_id"),
         "batch_no": s(r, "batch_no"),
@@ -2590,13 +3133,17 @@ pub async fn bill_detail(
         "holder_name": s(r, "holder_name"),
         "share_mode": s(r, "share_mode"),
         "share_value": f(r, "share_value"),
+        "settle_std_cents": i(r, "settle_std_cents"),
         "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"),
+        "month_days": i(r, "month_days"),
         "partial_month": b(r, "is_partial"),
         "costs": costs,
+        "cost_should_deduct_cents": cost_should_deduct,
+        "cost_deduct_cents": cost_deduct,
         "share_base_cents": base,
         "base_floor_protected": receivable > 0 && base == 0,
         "share_amount_cents": i(r, "share_amount_cents"),