ソースを参照

fix(bill): 修复账单明细搜索、返回筛选与详情观察项

对齐 placeholder 扩 keyword 命中列、详情返回保留 listSearch;顺带修非法 period/holder_type 校验、其他分成方单号链、零分成与空区间文案,以及 11104 归一文案与 account_days_failed 只坏一格。

Co-authored-by: Cursor <cursoragent@cursor.com>
cg 2 時間 前
親
コミット
5dc00a6e16

+ 43 - 16
src/modules/account/src/handlers/billing.rs

@@ -2375,11 +2375,22 @@ pub async fn bill_list(
     if let Err(e) = can_view(&auth) { return json_err(e); }
     // 期次缺省=「全部期次」(页面下拉的空值选项),⛔ 回落最近已结束月——
     // 否则空值选项与文案语义不符,且会静默丢掉其它期次的明细。
-    let period = req
-        .period
-        .as_deref()
-        .map(normalize_period)
-        .filter(|p| !p.is_empty());
+    // 非空但非 YYYY-MM(含长度≠7、月份越界)⇒ 60004,⛔ 静默忽略成全量(O-7)。
+    let period = match req.period.as_deref().map(str::trim).filter(|x| !x.is_empty()) {
+        None => None,
+        Some(raw) => {
+            let norm = normalize_period(raw);
+            if norm.is_empty() {
+                return json_err(BosError::bad_params(format!(
+                    "period 须为 YYYY-MM(11103):{raw}"
+                )));
+            }
+            if let Err(e) = parse_period(&norm) {
+                return json_err(e);
+            }
+            Some(norm)
+        }
+    };
     let page = req.page.unwrap_or(0).max(0);
     let size = req.page_size.unwrap_or(20).clamp(1, 100);
     let offset = page * size;
@@ -2393,6 +2404,10 @@ pub async fn bill_list(
         w.push(format!("d.period = {}", p.push(json!(pd))));
     }
     if let Some(t) = req.holder_type.as_deref().filter(|x| !x.is_empty()) {
+        // 与 recon/get_list 同口径:非法枚举 ⇒ 60004,⛔ 静默空集(O-6)。
+        if holder_table(t).is_none() {
+            return json_err(BosError::bad_params("holder_type 非法(11103)"));
+        }
         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()) {
@@ -2401,9 +2416,14 @@ pub async fn bill_list(
     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())))));
     }
+    // keyword 单框与列表 placeholder「分成方、客户、订阅或单号」对齐:并查 holder/客户/订阅/批次号(D-1)。
     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())))));
+        w.push(format!(
+            "(b.holder_name ILIKE {0} OR d.customer_name ILIKE {0} OR d.customer_id ILIKE {0} \
+              OR d.subscription_id ILIKE {0} OR COALESCE(d.subscription_label,'') ILIKE {0} \
+              OR d.batch_no ILIKE {0})",
+            p.push(json!(format!("%{}%", kw.trim())))
+        ));
     }
     // 主体收窄(对账§5.3 行集恒等于本方;✅ 2026-11-18 修复 D-4 追加区域轴):与上面的筛选取「且」,
     // ⛔ 用调用方传的 `holder_type` 替他决定行集(传别家类型只会与本谓词取交 ⇒ 空集)。
@@ -2511,7 +2531,10 @@ pub async fn bill_detail(
     }
     let period = s(r, "period");
     let sid = s(r, "subscription_id");
-    let accounts = match qry(&state.db, 
+    // 在期天数:取数失败只坏⑦格(account_days_failed=true + account_days=null),
+    // ⛔ 整页 60005/S406、⛔ 回落空数组冒充「无开停记录」(对账§14.3/O-5;同 ticket_gap_failed)。
+    let mut account_days_failed = false;
+    let account_days: Option<Vec<Value>> = 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 \
@@ -2519,15 +2542,17 @@ pub async fn bill_detail(
          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),
+        Ok(x) => Some(x.iter().map(|x| json!({
+            "sub_account_label": s(x, "sub_account_label"),
+            "in_period_days": i(x, "in_period_days"),
+        })).collect()),
+        Err(_) => {
+            account_days_failed = true;
+            None
+        }
     };
-    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 \
+        "SELECT d.bill_detail_id, d.batch_no, d.holder_type, d.holder_id, 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",
@@ -2536,8 +2561,10 @@ pub async fn bill_detail(
         Ok(x) => x,
         Err(e) => return json_err(e),
     };
+    // holder_id 一并下发:前端「其他分成方」子表对账单号可点进批次(与本方「所属对账单号」同形,O-1)。
     let other_parties: Vec<Value> = others.iter().map(|x| json!({
         "holder_type": s(x, "holder_type"),
+        "holder_id": s(x, "holder_id"),
         "holder_name": s(x, "holder_name"),
         "share_amount_cents": i(x, "share_amount_cents"),
         "batch_no": s(x, "batch_no"),
@@ -2576,7 +2603,7 @@ pub async fn bill_detail(
         "zero_note": os(r, "zero_note"),
         "other_parties": other_parties,
         "account_days": account_days,
-        "account_days_failed": false,
+        "account_days_failed": account_days_failed,
     });
     // 三类只读身份**字段不返回**(对账§5.3/06 册接口清单):旁人的分成金额是旁人的商业秘密,
     // ⛔ 置空——前端会把空值渲染成「0 元」,等于替对方否认分成。

+ 2 - 2
web-scaffold/src/lib/api/types.ts

@@ -3258,8 +3258,8 @@ export type BillDetailResult = {
   /** ⑥ 本方分成金额+恒 0 标注+所属对账单号 */
   share_amount_cents: number;
   zero_note: ZeroNote | null;
-  /** 其他分成方面板:三类只读身份的响应体不出现该字段(⛔ 值为空) ⇒ null */
-  other_parties: { holder_type: HolderType; holder_name: string; share_amount_cents: number; batch_no: string | null }[] | null;
+  /** 其他分成方面板:三类只读身份的响应体不出现该字段(⛔ 值为空) ⇒ null;holder_id 供对账单号链进批次 */
+  other_parties: { holder_type: HolderType; holder_id: string; holder_name: string; share_amount_cents: number; batch_no: string | null }[] | null;
   /** ⑦ 逐账号在期天数;KLT-S406 ⇒ null 且 account_days_failed=true(⛔ 回落「无开停记录」) */
   account_days: { sub_account_label: string; in_period_days: number }[] | null;
   account_days_failed: boolean;

+ 5 - 1
web-scaffold/src/lib/recon.ts

@@ -29,6 +29,7 @@ import {
 import type { BillingConfigResult } from "./api/types";
 import { WORD_FETCH_FAILED } from "./api/lockedCopy";
 import { PERMISSION_PENDING_NOTE, S404_DISCIPLINE } from "./copy-billing";
+import { VIEW_NOT_FOUND } from "./copy-views";
 
 /* ── 页面常量 ───────────────────────────────────────────────────── */
 
@@ -51,12 +52,15 @@ export interface ReconFail {
 }
 
 /** 统一失败分类:11001=权限待配置(本族路由已在 openapi 声明,未声明时网关回 404/50000);
- * S404=范围过大不渲卡;S406=取数失败;其余=原样 message。
+ * S404=范围过大不渲卡;S406=取数失败;11104=查无/越权同码 ⇒ 归一文案(与本方页 VIEW_NOT_FOUND 对齐,O-4);
+ * 其余=原样 message。
  * ⚠️ 11001 ⛔ 再当「未接线」渲染成占位分支(会让页面谎称接口没交付),也不⛔ 放宽判权装成有权限。 */
 export function classifyReconError(e: unknown): ReconFail {
   if (hasBizCode(e, "11001")) return { kind: "permission", message: PERMISSION_PENDING_NOTE };
   if (hasBizCode(e, "KLT-S404")) return { kind: "s404", message: S404_DISCIPLINE };
   if (hasBizCode(e, "KLT-S406")) return { kind: "s406", message: WORD_FETCH_FAILED };
+  // 越权与查无同码:⛔ 直出后端原文+字母码(会与本方页「数据不存在或归属已变更」分叉)。
+  if (hasBizCode(e, "11104")) return { kind: "other", message: VIEW_NOT_FOUND };
   return { kind: "other", message: e instanceof Error && e.message ? e.message : WORD_FETCH_FAILED };
 }
 

+ 1 - 1
web-scaffold/src/pages/PartyViewPages.tsx

@@ -981,7 +981,7 @@ export function PartyBillDetailPage({ kind }: { kind: ViewKind }) {
               <tr><th>尾月对齐前</th><td>{moneyFromCents(data.pre_align_cents)}</td></tr>
               <tr><th>应结金额(对齐后)</th><td><strong>{moneyFromCents(data.receivable_cents)}</strong></td></tr>
               {/* ② 计费区间与天数 */}
-              <tr><th>计费区间</th><td>{data.bill_from} ~ {data.bill_to}({data.billing_days} 天{data.partial_month ? ",不满月" : ""})</td></tr>
+              <tr><th>计费区间</th><td>{(data.bill_from || data.bill_to) ? `${data.bill_from || "—"} ~ ${data.bill_to || "—"}` : "—"}({data.billing_days} 天{data.partial_month ? ",不满月" : ""})</td></tr>
               {/* ④ 分成基数 */}
               <tr><th>分成基数</th><td>{moneyFromCents(data.share_base_cents)}{data.base_floor_protected ? "(已按下限保护取 0)" : ""}</td></tr>
               {/* ⑤ 当时冻结的分成方式与取值(⛔ 读档案现值,I22) */}

+ 21 - 9
web-scaffold/src/pages/SettlementRecordPages.tsx

@@ -523,13 +523,13 @@ export function SettlementStatementRecordPage() {
   const location = useLocation();
   const { no } = useParams();
   const state = (location.state ?? {}) as { from?: string; listSearch?: string };
-  // 返回恒回进来那一页(总则§16.11;⛔ history.back())。
+  // 返回恒回进来那一页(总则§16.11;⛔ history.back());账单明细来路带 listSearch 保留筛选。
   const back = state.from === "/correction-notes"
     ? { to: "/correction-notes", label: BACK_TO_CORRECTIONS }
     : state.from?.startsWith("/settlement-bills/")
       ? { to: state.from, label: BACK_TO_BILL_DETAIL }
       : state.from === "/settlement-bills"
-        ? { to: "/settlement-bills", label: BACK_TO_BILL_LIST }
+        ? { to: `/settlement-bills${state.listSearch ?? ""}`, label: BACK_TO_BILL_LIST }
         : { to: `/settlement-batches${state.listSearch ?? ""}`, label: BACK_TO_RECON_LIST };
 
   const detail = useReconDetail(no ?? null);
@@ -747,12 +747,15 @@ function BatchDetailBody({ d, isAdmin, onRerun, onExport, onCorrect, lineState }
 /* ── FN-08 账单明细(14.3 列表) ─────────────────────────────────── */
 
 export function SettlementBillListPage() {
+  const location = useLocation();
   const filters = useListFilters();
   const q = filters.get("q");
   const type = filters.get("type");
   const month = filters.get("month");
   const page = Number(filters.get("page") || "1") || 1;
   const hasFilter = Boolean(q || type || month);
+  // 详情/批次返回时拼回本串,保留筛选(D-2;对齐对账清单 listSearch)。
+  const listNavState = { from: "/settlement-bills" as const, listSearch: location.search };
 
   const periodsFetch = useReconPeriods();
   const periods = periodsFetch.data?.periods ?? null;
@@ -810,12 +813,12 @@ export function SettlementBillListPage() {
                   <td><span className="ops-money">{moneyFromCents(row.share_base_cents)}</span></td>
                   <td><strong className="reconcile-money">{moneyFromCents(row.share_amount_cents)}</strong></td>
                   <td>
-                    <Link className="reconcile-row-link" title={row.batch_no} to={batchPath(row.holder_id, row.batch_no)} state={{ from: "/settlement-bills" }}>
+                    <Link className="reconcile-row-link" title={row.batch_no} to={batchPath(row.holder_id, row.batch_no)} state={listNavState}>
                       {row.batch_no}<ArrowRight size={14} />
                     </Link>
                   </td>
                   <td>
-                    <Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(row.bill_detail_id)}`} state={{ from: "/settlement-bills" }}>
+                    <Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(row.bill_detail_id)}`} state={listNavState}>
                       详情
                     </Link>
                   </td>
@@ -848,12 +851,13 @@ export function SettlementBillListPage() {
 export function SettlementBillRecordPage() {
   const { index } = useParams();
   const location = useLocation();
-  const state = (location.state ?? {}) as { from?: string };
+  const state = (location.state ?? {}) as { from?: string; listSearch?: string };
+  // 来自列表时拼回 listSearch,保留筛选(D-2);其它来路仍回进来那一页。
   const back = state.from === "/correction-notes"
     ? { to: "/correction-notes", label: BACK_TO_CORRECTIONS }
     : state.from?.startsWith("/settlement-batches/")
       ? { to: state.from, label: BACK_TO_RECON_DETAIL }
-      : { to: "/settlement-bills", label: BACK_TO_BILL_LIST };
+      : { to: `/settlement-bills${state.from === "/settlement-bills" ? (state.listSearch ?? "") : ""}`, label: BACK_TO_BILL_LIST };
 
   const detail = useBillDetail(index ?? null);
   const d = detail.data;
@@ -901,7 +905,7 @@ export function SettlementBillRecordPage() {
           <section className="reconcile-record-section">
             <div className="reconcile-record-section-head"><span>02</span><div><h2>计费依据</h2><p>本期计费区间与天数。</p></div></div>
             <dl className="reconcile-record-facts">
-              <div><dt>计费区间</dt><dd>{d.bill_from} ~ {d.bill_to}</dd></div>
+              <div><dt>计费区间</dt><dd>{(d.bill_from || d.bill_to) ? `${d.bill_from || "—"} ~ ${d.bill_to || "—"}` : "—"}</dd></div>
               <div><dt>计费天数</dt><dd>{d.billing_days} 天</dd></div>
               <div><dt>是否不满月</dt><dd>{d.partial_month ? "是" : "否"}</dd></div>
             </dl>
@@ -952,7 +956,7 @@ export function SettlementBillRecordPage() {
           <section className="reconcile-record-section">
             <div className="reconcile-record-section-head"><span>06</span><div><h2>对账归属</h2><p>本方分成金额与所属批次。</p></div></div>
             <dl className="reconcile-record-facts">
-              <div><dt>本方分成金额</dt><dd>{moneyFromCents(d.share_amount_cents)}{d.zero_note ? `(${ZERO_NOTE_TEXT[d.zero_note]})` : ""}</dd></div>
+              <div><dt>本方分成金额</dt><dd>{moneyFromCents(d.share_amount_cents)}{d.zero_note ? ` · ${ZERO_NOTE_TEXT[d.zero_note]}` : ""}</dd></div>
               <div>
                 <dt>所属对账单号</dt>
                 <dd>
@@ -972,7 +976,15 @@ export function SettlementBillRecordPage() {
                       <tr key={`${p.holder_type}-${p.holder_name}-${i}`}>
                         <td><OpsTag tone={holderTone[p.holder_type]}>{HOLDER_TYPE_TEXT[p.holder_type]}</OpsTag> {p.holder_name}</td>
                         <td><span className="ops-money">{moneyFromCents(p.share_amount_cents)}</span></td>
-                        <td className="ops-mono">{p.batch_no ?? "—"}</td>
+                        <td>
+                          {p.batch_no && p.holder_id ? (
+                            <Link className="ops-table-action" to={batchPath(p.holder_id, p.batch_no)} state={{ from: location.pathname }}>
+                              {p.batch_no} <ArrowRight size={14} />
+                            </Link>
+                          ) : (
+                            <span className="ops-mono">{p.batch_no ?? "—"}</span>
+                          )}
+                        </td>
                       </tr>
                     ))}
                   </tbody>