Преглед на файлове

fix(web): 修复合伙人详情加载时页面闪动

sy преди 3 дни
родител
ревизия
c76a96ade2

+ 37 - 24
web-scaffold/src/pages/PartnerReadOnlyRecords.tsx

@@ -12,6 +12,12 @@ import { useDetailLinkState, type detailBack } from "../lib/detail-navigation";
 type RecordBack = ReturnType<typeof detailBack>;
 type RecordSection = { id: string; label: string; count?: number; content: ReactNode };
 type RecordMetric = { label: string; icon: ReactNode; value: ReactNode };
+type PartnerRecordState = { back: RecordBack; recordId: string; loading: boolean; fallback?: ReactNode };
+
+const recordTypes = {
+  CUSTOMER: { title: "客户详情", icon: Building2 },
+  CONTRACT: { title: "合同详情", icon: FileSignature },
+} as const;
 
 const empty = <span className="table-placeholder">—</span>;
 const money = (cents: number) => `¥${(cents / 100).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
@@ -22,44 +28,52 @@ function RecordFacts({ fields }: { fields: readonly (readonly [string, ReactNode
   </dl>;
 }
 
-function PartnerRecordLayout({ back, type, number, title, icon, context, metrics, sections }: {
-  back: RecordBack;
-  type: string;
-  number: string;
-  title: string;
-  icon: ReactNode;
-  context: ReactNode;
-  metrics: readonly RecordMetric[];
-  sections: readonly [RecordSection, ...RecordSection[]];
+function PartnerRecordLayout({ back, recordId, loading, fallback, type, number = recordId, title, context, metrics, sections }: PartnerRecordState & {
+  type: keyof typeof recordTypes;
+  number?: string;
+  title?: string;
+  context?: ReactNode;
+  metrics?: readonly RecordMetric[];
+  sections?: readonly [RecordSection, ...RecordSection[]];
 }) {
-  const [active, setActive] = useState(sections[0].id);
+  const [selected, setSelected] = useState<string>();
+  const active = selected ?? sections?.[0].id ?? "";
+  const recordType = recordTypes[type];
+  const Icon = recordType.icon;
+  const pending = loading && !sections;
   const prefix = `partner-${type.toLowerCase()}`;
   return <article className="ops-page ops-record-page record-detail">
     <Link className="ops-back-link" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label.replace(/^←\s*/, "")}</Link>
     <header className="customer-record-masthead">
-      <div className="customer-hero-symbol" aria-hidden="true">{icon}</div>
+      <div className="customer-hero-symbol" aria-hidden="true"><Icon size={26} /></div>
       <div className="customer-hero-copy">
         <p className="customer-record-id">{type} <span aria-hidden="true">·</span> <span>{number}</span></p>
-        <h1 className="customer-record-title">{title}</h1>
-        <div className="customer-record-tags">{context}</div>
+        <h1 className="customer-record-title">{pending ? <>
+          <span className="sr-only">{recordType.title}</span>
+          <span className="partner-record-title-placeholder" aria-hidden="true" />
+        </> : title || recordType.title}</h1>
+        <div className="customer-record-tags">{pending
+          ? <span className="partner-record-tags-placeholder" aria-hidden="true" />
+          : context}</div>
       </div>
     </header>
-    <dl className="customer-record-metrics partner-record-metrics" aria-label="业务摘要">
+    {metrics && <dl className="customer-record-metrics partner-record-metrics" aria-label="业务摘要">
       {metrics.map((metric) => <div key={metric.label}>
         <dt>{metric.icon}{metric.label}</dt><dd><strong>{metric.value}</strong></dd>
       </div>)}
-    </dl>
-    <div className="record-tabs-frame">
-      <RecordTabs prefix={prefix} label="详情视图" tabs={sections} active={active} onChange={setActive} />
+    </dl>}
+    {sections ? <div className="record-tabs-frame">
+      <RecordTabs prefix={prefix} label="详情视图" tabs={sections} active={active} onChange={setSelected} />
       {sections.map((section) => <section key={section.id} className="ops-record-card record-summary-panel record-tab-panel"
         id={`${prefix}-panel-${section.id}`} role="tabpanel" aria-labelledby={`${prefix}-tab-${section.id}`} hidden={active !== section.id} tabIndex={0}>
         {section.content}
       </section>)}
-    </div>
+    </div> : pending ? <div className="record-tabs-frame"><p className="partner-record-loading" role="status">正在读取{recordType.title}…</p></div> : fallback}
   </article>;
 }
 
-export function PartnerCustomerRecord({ data, back }: { data: CustomerDetail; back: RecordBack }) {
+export function PartnerCustomerRecord({ data, ...state }: PartnerRecordState & { data: CustomerDetail | null }) {
+  if (!data) return <PartnerRecordLayout {...state} type="CUSTOMER" />;
   const customer = data.customer;
   const region = data.region_mounts?.[0]?.path_name;
   const subject = customer.subject_type ? label(SUBJECT_TYPE, customer.subject_type) : null;
@@ -67,8 +81,7 @@ export function PartnerCustomerRecord({ data, back }: { data: CustomerDetail; ba
   const tone = status === "stopped" || status === "disabled" ? "danger"
     : ["active", "normal", "in_use"].includes(status) ? "success" : "neutral";
 
-  return <PartnerRecordLayout back={back} type="CUSTOMER" number={customer.customer_id} title={customer.customer_name}
-    icon={<Building2 size={26} />}
+  return <PartnerRecordLayout {...state} type="CUSTOMER" number={customer.customer_id} title={customer.customer_name}
     context={<>
       {subject && <OpsTag tone="brand">{subject}</OpsTag>}
       {status && <OpsStatus tone={tone}>{label(ACCT_STATUS, status)}</OpsStatus>}
@@ -99,8 +112,9 @@ function PartnerRecordTable({ caption, columns, children }: { caption: string; c
   </div>;
 }
 
-export function PartnerContractRecord({ data, back }: { data: ContractGetResult; back: RecordBack }) {
+export function PartnerContractRecord({ data, ...state }: PartnerRecordState & { data: ContractGetResult | null }) {
   const linkState = useDetailLinkState();
+  if (!data) return <PartnerRecordLayout {...state} type="CONTRACT" />;
   const profile = data.customer_profile;
   const items = data.service_items;
   const subscriptions = data.subscriptions;
@@ -111,8 +125,7 @@ export function PartnerContractRecord({ data, back }: { data: ContractGetResult;
   const customerLink = profile && data.customer_id && customerName
     ? <Link className="contract-ref-link" to={`/bos/pv/customer/${encodeURIComponent(data.customer_id)}`} state={linkState}>{customerName}</Link>
     : customerName;
-  return <PartnerRecordLayout back={back} type="CONTRACT" number={data.contract_id} title={data.contract_no}
-    icon={<FileSignature size={26} />}
+  return <PartnerRecordLayout {...state} type="CONTRACT" number={data.contract_id} title={data.contract_no}
     context={<>
       {status && <OpsStatus tone={contractStatusTone[status]}>{status}</OpsStatus>}
       {data.opened != null && <OpsStatus tone={data.opened ? "success" : "warning"}>{data.opened ? "已开通" : "未开通"}</OpsStatus>}

+ 12 - 8
web-scaffold/src/pages/PartyViewPages.tsx

@@ -829,6 +829,12 @@ function DetailHeader({ title, back }: { title: string; back: ReturnType<typeof
   );
 }
 
+function PartyRecordFailure({ fail, back, reload }: { fail: ViewFail | null; back: ReturnType<typeof detailBack>; reload: () => void }) {
+  if (!fail) return null;
+  if (fail.kind === "notfound") return <DetailNotFound back={back} />;
+  return <FullPageState text={fail.kind === "fail" ? fail.message : VIEW_WIRING_NOTE} retry={fail.kind === "fail" ? reload : undefined} />;
+}
+
 /** V9 客户详情(⛔「关联工单」卡片,14.5 白名单第 2 项)。 */
 export function PartyCustomerDetailPage({ kind }: { kind: "partner" | "operator" }) {
   const { id = "" } = useParams();
@@ -841,13 +847,12 @@ function PartyCustomerDetail({ kind, id }: { kind: "partner" | "operator"; id: s
   const back = detailBack(location.state, `${prefix}/customer`, BACK_TO_CUSTOMER_LIST);
   const fetchState = useViewFetch(() => customerGet({ customer_id: id }), [id]);
   const { data, fail } = fetchState;
-  if (kind === "partner" && data) return <PartnerCustomerRecord data={data} back={back} />;
+  const failure = <PartyRecordFailure fail={fail} back={back} reload={fetchState.reload} />;
+  if (kind === "partner") return <PartnerCustomerRecord data={data} back={back} recordId={id} loading={fetchState.loading} fallback={failure} />;
   return (
     <section className="ops-page reconcile-index">
       <DetailHeader title="客户详情" back={back} />
-      {kind === "partner" && fetchState.loading && <p role="status">正在读取客户详情…</p>}
-      {fail?.kind === "notfound" && <DetailNotFound back={back} />}
-      {fail && fail.kind !== "notfound" && <FullPageState text={fail.kind === "fail" ? fail.message : VIEW_WIRING_NOTE} retry={fail.kind === "fail" ? fetchState.reload : undefined} />}
+      {failure}
       {data && (
         <div className="ops-table-wrap">
           <table className="ops-table">
@@ -879,13 +884,12 @@ function PartyContractDetail({ kind, id }: { kind: "partner" | "operator"; id: s
   const back = detailBack(location.state, `${prefix}/contract`, BACK_TO_CONTRACT_LIST);
   const fetchState = useViewFetch(() => contractGet({ contract_id: id }), [id]);
   const { data, fail } = fetchState;
-  if (kind === "partner" && data) return <PartnerContractRecord data={data} back={back} />;
+  const failure = <PartyRecordFailure fail={fail} back={back} reload={fetchState.reload} />;
+  if (kind === "partner") return <PartnerContractRecord data={data} back={back} recordId={id} loading={fetchState.loading} fallback={failure} />;
   return (
     <section className="ops-page reconcile-index">
       <DetailHeader title="合同详情" back={back} />
-      {kind === "partner" && fetchState.loading && <p role="status">正在读取合同详情…</p>}
-      {fail?.kind === "notfound" && <DetailNotFound back={back} />}
-      {fail && fail.kind !== "notfound" && <FullPageState text={fail.kind === "fail" ? fail.message : VIEW_WIRING_NOTE} retry={fail.kind === "fail" ? fetchState.reload : undefined} />}
+      {failure}
       {data && (
         <div className="ops-table-wrap">
           <table className="ops-table">

+ 47 - 2
web-scaffold/src/pages/__tests__/party-ledger-navigation.test.tsx

@@ -1,13 +1,15 @@
 import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
 import { MemoryRouter, Route, Routes } from "react-router";
 import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { billGetList, contractGetList, customerGetList, reconGetList } from "../../lib/api/bos";
-import { OperatorBillDetailPage, OperatorReconPage, PartyContractListPage, PartyCustomerListPage } from "../PartyViewPages";
+import { billGetList, contractGet, contractGetList, customerGet, customerGetList, reconGetList } from "../../lib/api/bos";
+import { OperatorBillDetailPage, OperatorReconPage, PartyContractDetailPage, PartyContractListPage, PartyCustomerDetailPage, PartyCustomerListPage } from "../PartyViewPages";
 
 vi.mock("../../lib/api/bos", async (load) => ({
   ...await load<typeof import("../../lib/api/bos")>(),
   billGetList: vi.fn(),
+  contractGet: vi.fn(),
   contractGetList: vi.fn(),
+  customerGet: vi.fn(),
   customerGetList: vi.fn(),
   reconGetList: vi.fn(),
 }));
@@ -102,3 +104,46 @@ it("合同清单沿用运营侧的金额格式与服务期单元格", async () =
   expect(cell?.classList.contains("contract-ledger-amount")).toBe(true);
   expect(cell?.querySelector("small")?.textContent).toBe("服务期 12 个月");
 });
+
+it.each([
+  { path: "customer", label: "客户详情", title: "客户甲", tab: "主体资料", page: <PartyCustomerDetailPage kind="partner" /> },
+  { path: "contract", label: "合同详情", title: "CT-001", tab: "客户资料", page: <PartyContractDetailPage kind="partner" /> },
+])("合伙人$label读取前后共用同一个头部", async ({ path, label, title, tab, page }) => {
+  let finishRequest!: () => void;
+  const requestDelay = new Promise<void>((resolve) => { finishRequest = resolve; });
+  vi.mocked(customerGet).mockImplementation(async () => {
+    await requestDelay;
+    return {
+      customer: {
+        customer_id: "KL-001", customer_name: "客户甲", subject_type: "enterprise", acct_status: "in_use",
+        operator_id: null, operator_name: null, partner_id: "PT-01", partner_name: "合伙人甲", quota_cents: "10", created_at: null,
+      },
+      team_ids: [], sub_account_count: 1, region_mounts: [],
+    };
+  });
+  vi.mocked(contractGet).mockImplementation(async () => {
+    await requestDelay;
+    return {
+      contract_id: "CT-001", contract_no: "CT-001", customer_id: "KL-001", external_no: null,
+      status: "active", contract_amount_cents: 123450, service_months: 12, start_date: null, end_date: null,
+      agent_name: null, agent_mobile: null, agent_handover_on: null, agent_org: null,
+      attachment_url: null, created_at: "2026-10-01", row_version: "1",
+    };
+  });
+  const prefix = `/bos/pv/${path}`;
+  render(<MemoryRouter initialEntries={[`${prefix}/${path === "customer" ? "KL-001" : "CT-001"}`]}>
+    <Routes><Route path={`${prefix}/:id`} element={page} /></Routes>
+  </MemoryRouter>);
+
+  const pendingHeading = screen.getByRole("heading", { name: label });
+  const pendingHeader = pendingHeading.closest(".customer-record-masthead");
+  expect(pendingHeader).toBeTruthy();
+  expect(screen.getByRole("status").textContent).toContain(`正在读取${label}`);
+  expect(screen.queryByText("READONLY / 只读视图")).toBeNull();
+
+  finishRequest();
+  const loadedHeading = await screen.findByRole("heading", { name: title });
+  expect(loadedHeading).toBe(pendingHeading);
+  expect(loadedHeading.closest("header")).toBe(pendingHeader);
+  expect(screen.getByRole("tab", { name: tab }).getAttribute("aria-selected")).toBe("true");
+});

+ 16 - 0
web-scaffold/src/styles/record-detail.css

@@ -57,6 +57,22 @@
   gap: 6px;
 }
 
+.partner-record-title-placeholder,
+.partner-record-tags-placeholder {
+  border-radius: var(--radius-control);
+  background: var(--border-subtle);
+}
+
+.partner-record-title-placeholder { display: inline-block; width: min(15rem, 100%); height: .8em; }
+.partner-record-tags-placeholder { width: min(8rem, 100%); height: 24px; }
+
+.partner-record-loading {
+  margin: 0;
+  padding: 24px 22px;
+  color: var(--muted-foreground);
+  font-size: var(--type-support);
+}
+
 .customer-record-meta {
   display: inline-flex;
   align-items: center;