Просмотр исходного кода

fix(web): 允许自然月筛选选择本月及更早月份

sy 2 дней назад
Родитель
Сommit
4fdeaccb66

+ 12 - 12
web-scaffold/src/components/ui/month-filter.tsx

@@ -1,27 +1,28 @@
 import { useId, useRef, useState } from "react";
 import { ChevronLeft, ChevronRight } from "lucide-react";
+import { businessToday } from "../../lib/business-date";
 import { cn } from "../../lib/utils";
 import { FilterIcon } from "./filter-select";
 import "../../styles/month-filter.css";
 
-export function MonthFilter({ value, onChange, maxMonth, allowAll = true, availableMonths }: {
+export function MonthFilter({ value, onChange, maxMonth, allowAll = true }: {
   value: string;
   onChange: (value: string) => void;
-  /** 可选上界(YYYY-MM):给了就⛔ 能选到比它更晚的自然月(补跑弹窗只能选已结束的月份)。 */
+  /** 可选上界(YYYY-MM),默认本月。人工补跑传最近一个已结束的自然月。 */
   maxMonth?: string;
   /** 是否给「全部自然月」这一项;必填期次的场景(人工补跑)传 false。 */
   allowAll?: boolean;
-  /** 可选账期按从新到旧排列,省略时可选择任意自然月。 */
-  availableMonths?: readonly string[];
 }) {
   const id = useId();
   const popup = useRef<HTMLDivElement>(null);
   const trigger = useRef<HTMLButtonElement>(null);
-  const preferredYear = Number((value || availableMonths?.[0] || "").slice(0, 4));
-  const initialYear = Number.isInteger(preferredYear) && preferredYear > 0 ? preferredYear : new Date().getFullYear();
+  const limit = maxMonth ?? businessToday().slice(0, 7);
+  const maxYear = Number(limit.slice(0, 4));
+  const selectedYear = Number(value.slice(0, 4));
+  const initialYear = selectedYear > 0 ? Math.min(selectedYear, maxYear) : maxYear;
   const [year, setYear] = useState(initialYear);
   const label = value || "全部自然月";
-  const maxYear = maxMonth ? Number(maxMonth.slice(0, 4)) : NaN;
+  const limitHint = maxMonth ? "只能选已结束的月份" : "只能选择本月及之前的月份";
 
   function choose(month: string) {
     popup.current?.hidePopover();
@@ -40,16 +41,15 @@ export function MonthFilter({ value, onChange, maxMonth, allowAll = true, availa
         <button type="button" aria-label="上一年" disabled={year === 1} onClick={() => setYear(year - 1)}><ChevronLeft size={16} aria-hidden="true" /></button>
         <strong aria-live="polite">{year} 年</strong>
         <button type="button" aria-label="下一年"
-          disabled={Number.isInteger(maxYear) ? year >= maxYear : year === 9999}
+          disabled={year >= maxYear}
           onClick={() => setYear(year + 1)}><ChevronRight size={16} aria-hidden="true" /></button>
       </div>
       <div className="month-filter-grid">
         {Array.from({ length: 12 }, (_, index) => {
           const month = `${String(year).padStart(4, "0")}-${String(index + 1).padStart(2, "0")}`;
-          const beyond = Number.isInteger(maxYear) && month > maxMonth!;
-          const unavailable = availableMonths?.includes(month) === false;
-          return <button type="button" key={month} aria-pressed={month === value} disabled={beyond || unavailable}
-            title={beyond ? "只能选已结束的月份" : undefined}
+          const beyond = month > limit;
+          return <button type="button" key={month} aria-pressed={month === value} disabled={beyond}
+            title={beyond ? limitHint : undefined}
             onClick={() => choose(month)}>{index + 1} 月</button>;
         })}
       </div>

+ 0 - 5
web-scaffold/src/lib/copy-billing.ts

@@ -28,8 +28,6 @@ export const STAT_CARDS = [
 export const S404_DISCIPLINE = "范围过大,请缩小条件后重试";
 /** KLT-S404 空态表句(触顶 ⇒ 不渲染三卡与列表,⚠️ 禁止静默截断)。 */
 export const S404_EMPTY_NOTE = "可见范围过大,请指定区域或自然月后重试";
-/** 预选月不在 periods 选项内时的显式说明(⛔ 把「本期还没有数据」静默成「筛选无结果」,C35)。 */
-export const MONTH_NO_BATCH_NOTE = "本范围该月还没有批次";
 /** 月份下拉首项空值项(⛔ 不得删除)。 */
 export const ALL_PERIODS_LABEL = "全部自然月";
 
@@ -197,9 +195,6 @@ export function saveReconExportCsv(r: ReconExportResult): boolean {
 export const TICKET_GAP_LABEL = "本批仍有未完成开户工单";
 export const ticketGapText = (n: number): string => `${n} 个`;
 
-/** periods 口 11104 ⇒ 自然月筛选不可用(⛔ 禁用整页筛选条)。 */
-export const PERIODS_UNAVAILABLE = "自然月筛选暂不可用。";
-
 /** ③-1 期次出账进度展开开关文案。 */
 export const PROGRESS_EXPAND = "展开各分成方明细";
 export const PROGRESS_COLLAPSE = "收起各分成方明细";

+ 0 - 6
web-scaffold/src/lib/recon.ts

@@ -23,7 +23,6 @@ import {
   correctionGetList,
   reconGetDetail,
   reconGetList,
-  reconGetPeriods,
   reconRerun,
 } from "./api/bos";
 import type { BillingConfigResult } from "./api/types";
@@ -103,11 +102,6 @@ function useFetch<T>(fn: () => Promise<T>, deps: readonly unknown[]): {
 
 /* ── FN-05 对账清单 ─────────────────────────────────────────────── */
 
-/** 自然月下拉行集(11104 ⇒ 下拉不可用,⛔ 禁用整页筛选条)。 */
-export function useReconPeriods() {
-  return useFetch(() => reconGetPeriods(), []);
-}
-
 export interface ReconListFilters {
   period: string;
   holderType: string;

+ 5 - 34
web-scaffold/src/pages/SettlementRecordPages.tsx

@@ -29,7 +29,7 @@ import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
 import { detailBack, detailLinkState, useDetailLinkState, type DetailLinkState } from "../lib/detail-navigation";
 import {
   lastClosedMonth, submitReconRerun,
-  useBillDetail, useBillList, useReconDetail, useReconList, useReconPeriods,
+  useBillDetail, useBillList, useReconDetail, useReconList,
 } from "../lib/recon";
 import {
   ACTION_FLAG_PENDING_NOTE,
@@ -44,8 +44,6 @@ import {
   EXPORT_EMPTY_NOTE,
   exportResultNote,
   HOLDER_TYPE_TEXT,
-  MONTH_NO_BATCH_NOTE,
-  PERIODS_UNAVAILABLE,
   periodProgressLine,
   PROGRESS_COLLAPSE,
   PROGRESS_EXPAND,
@@ -315,7 +313,6 @@ export function SettlementStatementListPage() {
   const canExportAll = !identity || identity.role === "admin" || identity.role === "regAdmin";
   const isAdmin = !identity || identity.role === "admin";
 
-  const lastClosedPeriod = lastClosedMonth();
   const monthParam = filters.get("month");
   // 无参数时显示全部自然月,同时兼容旧链接的 month=all。
   const month = monthParam === "all" ? "" : monthParam;
@@ -329,28 +326,6 @@ export function SettlementStatementListPage() {
   const page = Number(filters.get("page") || "1") || 1;
   const hasFilter = Boolean(month || type || party || reconcile || status || trigger || zero || q);
 
-  const periodsFetch = useReconPeriods();
-  // D-19:下拉选项=接口期次 ∪ 上一个已结束自然月(与人工补跑弹窗 `lastClosedMonth()` 同基准)。
-  // 仅有历史批、尚无「上月」批时,仍须能选上月(可能空表),⛔ 静默退到更早月造成「弹窗说 10 月、清单只到 9 月」。
-  const periods = (() => {
-    const raw = periodsFetch.data?.periods ?? null;
-    if (!raw) return null;
-    if (raw.includes(lastClosedPeriod)) return raw;
-    return [lastClosedPeriod, ...raw];
-  })();
-  // 仅纠正不在选项内的显式月份(例如旧书签中的月份)。
-  const [monthFallback, setMonthFallback] = useState(false);
-  useEffect(() => {
-    if (!periods?.length) return;
-    if (!month || periods.includes(month)) {
-      setMonthFallback(false);
-      return;
-    }
-    filters.set("month", periods[0], true);
-    setMonthFallback(true);
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, [periods, month]);
-
   const list = useReconList({
     period: month,
     holderType: type,
@@ -411,8 +386,6 @@ export function SettlementStatementListPage() {
 
       {/* 接线占位横幅(klt-bos recon/* 未交付;交付后本分支自然失效) */}
       {wiring && <p className="ops-import-note" role="status">{RECON_WIRING_NOTE}</p>}
-      {periodsFetch.fail && !wiring && <p className="ops-import-note" role="status">{PERIODS_UNAVAILABLE}</p>}
-      {monthFallback && !rows.length && <p className="ops-import-note" role="status">{MONTH_NO_BATCH_NOTE}</p>}
 
       {/* ② 三统计卡:与列表同一响应同一行集;S404 ⇒ 整体不渲染(不是显示 0);单格 null ⇒「取数失败」。 */}
       {!s404 && (wiring || data) && (
@@ -466,7 +439,7 @@ export function SettlementStatementListPage() {
 
       {/* ④ 批次清单 */}
       <div className="reconcile-ledger list-shell-fill">
-        {/* ③ 筛选条:自然月(periods 口)/分成方类型/分成方(可搜)/出账状态/批次状态/对账单号关键字/零明细开关/重置筛选。 */}
+        {/* ③ 筛选条:自然月/分成方类型/分成方(可搜)/出账状态/批次状态/对账单号关键字/零明细开关/重置筛选。 */}
         <div className="ops-toolbar reconcile-filters statement-filters" role="group" aria-label="对账清单筛选">
           <label className="ops-search">
             <Search size={17} aria-hidden="true" />
@@ -480,7 +453,7 @@ export function SettlementStatementListPage() {
               onCommit={(value) => filters.set("party", value, true)} />
             {party && <button type="button" aria-label="清空分成方" onClick={() => filters.set("party", "", true)}><X size={15} aria-hidden="true" /></button>}
           </label>
-          <MonthFilter value={month} availableMonths={periods ?? (month ? [month] : [])} onChange={(value) => filters.set("month", value, true)} />
+          <MonthFilter value={month} onChange={(value) => filters.set("month", value, true)} />
           <FilterSelect icon="type" aria-label="分成方类型" value={type} onChange={(event) => filters.set("type", event.target.value, true)}>
             <option value="">全部类型</option>
             <option value="operator">{HOLDER_TYPE_TEXT.operator}</option>
@@ -508,7 +481,7 @@ export function SettlementStatementListPage() {
           </FilterSelect>
           <Button variant={zero ? "default" : "outline"} size="sm" className="h-[38px] shrink-0" aria-pressed={zero}
             onClick={() => filters.set("zero", zero ? "" : "1", true)}><ListFilter size={15} aria-hidden="true" />零明细批次</Button>
-          {hasFilter && <Button variant="ghost" size="sm" onClick={() => { filters.reset(); setMonthFallback(false); }}>重置筛选</Button>}
+          {hasFilter && <Button variant="ghost" size="sm" onClick={filters.reset}>重置筛选</Button>}
         </div>
 
         {/* S404 触顶 ⇒ 不渲染三卡与列表(⚠️ 禁止静默截断)。 */}
@@ -806,8 +779,6 @@ export function SettlementBillListPage() {
   const page = Number(filters.get("page") || "1") || 1;
   const hasFilter = Boolean(q || type || month);
 
-  const periodsFetch = useReconPeriods();
-  const periods = periodsFetch.data?.periods ?? null;
   const list = useBillList({ period: month, holderType: type, keyword: q, page });
   const wiring = list.fail?.kind === "wiring";
   const rows = list.data?.items ?? [];
@@ -839,7 +810,7 @@ export function SettlementBillListPage() {
             <option value="partner">{HOLDER_TYPE_TEXT.partner}</option>
             <option value="ops_team">{HOLDER_TYPE_TEXT.ops_team}</option>
           </FilterSelect>
-          <MonthFilter value={month} availableMonths={periods ?? (month ? [month] : [])} onChange={(value) => filters.set("month", value, true)} />
+          <MonthFilter value={month} onChange={(value) => filters.set("month", value, true)} />
           {hasFilter && <Button variant="ghost" size="sm" onClick={filters.reset}>重置筛选</Button>}
         </div>
 

+ 21 - 8
web-scaffold/src/pages/__tests__/settlement-statement-list.test.tsx

@@ -4,6 +4,10 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
 import { reconExportList, reconGetList, reconRerun } from "../../lib/api/bos";
 import { SettlementStatementListPage } from "../SettlementRecordPages";
 
+vi.mock("../../lib/business-date", async (load) => ({
+  ...await load<typeof import("../../lib/business-date")>(),
+  businessToday: () => "2026-11-30",
+}));
 vi.mock("../../lib/recon", async (load) => ({
   ...await load<typeof import("../../lib/recon")>(),
   lastClosedMonth: () => "2026-10",
@@ -14,7 +18,6 @@ vi.mock("../../lib/demo-session", async (load) => ({
 }));
 vi.mock("../../lib/api/bos", async (load) => ({
   ...await load<typeof import("../../lib/api/bos")>(),
-  reconGetPeriods: vi.fn(async () => ({ periods: ["2026-10", "2026-09"] })),
   reconGetList: vi.fn(async () => ({
     total: 25,
     stats: { total_base_cents: 120000, total_cost_cents: null, total_share_cents: 19000 },
@@ -112,13 +115,22 @@ it.each(["", "?month=all"])("默认查询全部自然月并支持选月和重置
   fireEvent.click(monthTrigger);
   const calendar = within(screen.getByLabelText("选择自然月"));
   expect(calendar.getByText("2026 年")).toBeTruthy();
-  expect(calendar.getByText<HTMLButtonElement>("11 月").disabled).toBe(true);
-  const october = calendar.getByText<HTMLButtonElement>("10 月");
-  expect(october.disabled).toBe(false);
-  fireEvent.click(october);
-  await waitFor(() => expect(reconGetList).toHaveBeenLastCalledWith(expect.objectContaining({ period: "2026-10" })));
-  expect(screen.getByRole("button", { name: "自然月:2026-10" })).toBe(monthTrigger);
-  expect(within(monthTrigger).getByText("2026-10").classList.contains("is-placeholder")).toBe(false);
+  expect(calendar.getByText<HTMLButtonElement>("12 月").disabled).toBe(true);
+  expect(calendar.getByLabelText<HTMLButtonElement>("下一年").disabled).toBe(true);
+  const currentMonth = calendar.getByText<HTMLButtonElement>("11 月");
+  expect(currentMonth.disabled).toBe(false);
+  fireEvent.click(currentMonth);
+  await waitFor(() => expect(reconGetList).toHaveBeenLastCalledWith(expect.objectContaining({ period: "2026-11" })));
+  expect(screen.getByRole("button", { name: "自然月:2026-11" })).toBe(monthTrigger);
+  expect(within(monthTrigger).getByText("2026-11").classList.contains("is-placeholder")).toBe(false);
+
+  fireEvent.click(monthTrigger);
+  fireEvent.click(calendar.getByLabelText("上一年"));
+  expect(calendar.getByText("2025 年")).toBeTruthy();
+  const pastMonth = calendar.getByText<HTMLButtonElement>("12 月");
+  expect(pastMonth.disabled).toBe(false);
+  fireEvent.click(pastMonth);
+  await waitFor(() => expect(reconGetList).toHaveBeenLastCalledWith(expect.objectContaining({ period: "2025-12" })));
 
   fireEvent.click(screen.getByRole("button", { name: "重置筛选" }));
   expect(screen.getByRole("button", { name: "自然月:全部自然月" })).toBe(monthTrigger);
@@ -130,6 +142,7 @@ it("补跑对话框预览选择的分成方和账期,完成后进入新批次
   renderPage("?type=operator");
   fireEvent.click(screen.getByRole("button", { name: "人工补跑" }));
   const dialog = within(screen.getByRole("dialog", { name: "确认人工补跑" }));
+  expect(within(dialog.getByLabelText("选择自然月")).getByText<HTMLButtonElement>("11 月").disabled).toBe(true);
   expect(await dialog.findByText("补跑对象:华东运营商 · 2026-10。")).toBeTruthy();
   fireEvent.change(dialog.getByRole("combobox", { name: "分成方类型" }), { target: { value: "partner" } });
   expect(await dialog.findByText("补跑对象:渠道伙伴 · 2026-10。")).toBeTruthy();