Ver Fonte

fix(web): 统一页面返回路径并保留来路状态

sy há 2 dias atrás
pai
commit
34ffb505c3
31 ficheiros alterados com 502 adições e 280 exclusões
  1. 3 1
      web-scaffold/src/components/CustomerServiceStopAction.tsx
  2. 13 15
      web-scaffold/src/components/ReferenceDrawer.tsx
  3. 7 2
      web-scaffold/src/components/layout/InboxPanel.tsx
  4. 7 8
      web-scaffold/src/components/work-order/WorkOrderLedgerList.tsx
  5. 95 34
      web-scaffold/src/lib/detail-navigation.ts
  6. 21 10
      web-scaffold/src/pages/ContractDetailPages.tsx
  7. 7 6
      web-scaffold/src/pages/ContractManagementPage.tsx
  8. 6 5
      web-scaffold/src/pages/ContractRecordPage.tsx
  9. 1 1
      web-scaffold/src/pages/CustomerOrdersPage.tsx
  10. 12 11
      web-scaffold/src/pages/CustomerRecordsPages.tsx
  11. 6 4
      web-scaffold/src/pages/CustomerTicketPages.tsx
  12. 6 4
      web-scaffold/src/pages/CustomerWorkspacePage.tsx
  13. 21 12
      web-scaffold/src/pages/FinanceReferencePages.tsx
  14. 3 1
      web-scaffold/src/pages/JobRunsDialog.tsx
  15. 12 6
      web-scaffold/src/pages/OrderManagementPage.tsx
  16. 3 3
      web-scaffold/src/pages/OrderRecordPage.tsx
  17. 55 25
      web-scaffold/src/pages/OrganizationPages.tsx
  18. 6 1
      web-scaffold/src/pages/PackageManagementPage.tsx
  19. 60 39
      web-scaffold/src/pages/PartyViewPages.tsx
  20. 19 12
      web-scaffold/src/pages/SettlementPages.tsx
  21. 29 41
      web-scaffold/src/pages/SettlementRecordPages.tsx
  22. 1 4
      web-scaffold/src/pages/TeamQueuePage.tsx
  23. 4 5
      web-scaffold/src/pages/WorkOrderDeliveryPage.tsx
  24. 11 4
      web-scaffold/src/pages/WorkOrderManagementPage.tsx
  25. 4 2
      web-scaffold/src/pages/WorkOrderMinePage.tsx
  26. 5 5
      web-scaffold/src/pages/WorkOrderOverviewPage.tsx
  27. 7 5
      web-scaffold/src/pages/WorkOrderRecordPage.tsx
  28. 32 3
      web-scaffold/src/pages/__tests__/settlement-bill-record.test.tsx
  29. 2 2
      web-scaffold/src/pages/__tests__/settlement-statement-list.test.tsx
  30. 15 8
      web-scaffold/src/pages/mobile/MobileWorkOrderPages.tsx
  31. 29 1
      web-scaffold/tests/detail-navigation.test.mjs

+ 3 - 1
web-scaffold/src/components/CustomerServiceStopAction.tsx

@@ -1,3 +1,4 @@
+import { useDetailLinkState } from "../lib/detail-navigation";
 import { useEffect, useId, useRef, useState } from "react";
 import { useNavigate } from "react-router";
 import { createPortal } from "react-dom";
@@ -39,6 +40,7 @@ type Props = {
  */
 export function CustomerServiceStopAction({ customerId, customerName, orderId, orderLabel }: Props) {
   const navigate = useNavigate();
+  const outgoingState = useDetailLinkState();
   const identity = useDemoIdentity();
   const canSubmit = !identity || ["admin", "regAdmin"].includes(identity.role);
   const subjectName = customerName || customerId;
@@ -74,7 +76,7 @@ export function CustomerServiceStopAction({ customerId, customerName, orderId, o
         confirm: true,
       });
       setOpen(false);
-      navigate(`/work-orders/${encodeURIComponent(created.ticket_id)}`, { state: { from: `/orders/${orderId}` } });
+      navigate(`/work-orders/${encodeURIComponent(created.ticket_id)}`, { state: outgoingState });
     } catch (cause) {
       setError(cause instanceof Error ? cause.message : "发起失败,请稍后重试。");
     } finally {

+ 13 - 15
web-scaffold/src/components/ReferenceDrawer.tsx

@@ -12,7 +12,7 @@
  * 本件始终渲染栈顶,栈深 > 1 时给出「返回上一级」,关闭则整栈清空。
  */
 import { useEffect, useRef, useState, type ReactNode } from "react";
-import { Link, useLocation } from "react-router";
+import { Link } from "react-router";
 import { ArrowLeft, ArrowRight, Building2, Package, Tag } from "lucide-react";
 import { FetchError } from "./fetchError";
 import { ListPager } from "./ListPager";
@@ -22,7 +22,7 @@ import { catalogGet, customerGet, orderGet, orderGetList } from "../lib/api/bos"
 import type { CatalogPlanRow, OrderGetResult, OrderListResult } from "../lib/api/types";
 import { ACCT_STATUS, PLAN_FAMILY, PLAN_KIND, ORDER_MODE, ORDER_STATUS, SUBJECT_TYPE, TERM, label } from "../lib/api/labels";
 import { bandwidthTextOfRow, moneyCell } from "../lib/package-catalog";
-import { detailLinkState } from "../lib/detail-navigation";
+import type { DetailLinkState } from "../lib/detail-navigation";
 import { LIST_PAGE_SIZE, clampPage } from "../lib/list-paging";
 import { fmtDate } from "../lib/ticket";
 import { useLoad } from "../lib/useLoad";
@@ -51,11 +51,12 @@ function period(start: string | null | undefined, end: string | null | undefined
   return `${start || "未登记"} 至 ${end || "未登记"}`;
 }
 
-export function ReferenceDrawer({ stack, onPush, onBack, onClose, presentation = "drawer" }: {
+export function ReferenceDrawer({ stack, onPush, onBack, onClose, linkState, presentation = "drawer" }: {
   stack: RefTarget[];
   onPush: (target: RefTarget) => void;
   onBack: () => void;
   onClose: () => void;
+  linkState: DetailLinkState;
   presentation?: "drawer" | "dialog";
 }) {
   const top = stack[stack.length - 1];
@@ -74,10 +75,10 @@ export function ReferenceDrawer({ stack, onPush, onBack, onClose, presentation =
     ? `${top.name} · ${top.id}`
     : top.kind === "customer" ? "客户主体参考信息" : top.kind === "plan" ? "套餐目录参考信息" : "订阅参考信息";
   const content = top.kind === "customer"
-    ? <CustomerPanel customerId={top.id} onOpenOrder={onPush} />
+    ? <CustomerPanel customerId={top.id} onOpenOrder={onPush} linkState={linkState} />
     : top.kind === "plan"
-      ? <PlanPanel planId={top.id} onOpenCustomer={onPush} />
-      : <OrderPanel orderId={top.id} onOpenCustomer={onPush} />;
+      ? <PlanPanel planId={top.id} onOpenCustomer={onPush} linkState={linkState} />
+      : <OrderPanel orderId={top.id} onOpenCustomer={onPush} linkState={linkState} />;
 
   if (presentation === "dialog") return <OpsDialog title={title} subtitle={top.id} onClose={onClose}
     className="work-order-action-dialog is-reference">
@@ -96,12 +97,11 @@ export function ReferenceDrawer({ stack, onPush, onBack, onClose, presentation =
   </OpsDrawer>;
 }
 
-function CustomerPanel({ customerId, onOpenOrder }: {
+function CustomerPanel({ customerId, onOpenOrder, linkState }: {
   customerId: string;
   onOpenOrder: (target: RefTarget) => void;
+  linkState: DetailLinkState;
 }) {
-  const location = useLocation();
-  const linkState = detailLinkState(location.pathname, location.state);
   const [orderPage, setOrderPage] = useState(0);
   const [orderPageSize, setOrderPageSize] = useState(LIST_PAGE_SIZE);
   const detail = useLoad(() => customerGet({ customer_id: customerId }), [customerId]);
@@ -190,12 +190,11 @@ function CustomerPanel({ customerId, onOpenOrder }: {
 }
 
 /** 套餐档位详情:合同条目的「套餐 / 配置」是外部引用,点开按 `plan_id` 现取目录档。 */
-function PlanPanel({ planId, onOpenCustomer }: {
+function PlanPanel({ planId, onOpenCustomer, linkState }: {
   planId: string;
   onOpenCustomer: (target: RefTarget) => void;
+  linkState: DetailLinkState;
 }) {
-  const location = useLocation();
-  const linkState = detailLinkState(location.pathname, location.state);
   const detail = useLoad(() => catalogGet({ plan_id: planId }), [planId]);
   if (detail.loading) return <p className="record-ref-status">正在读取套餐档位…</p>;
   if (detail.error) return <FetchError className="record-ref-status" message={`套餐档位取数失败:${detail.error.message}`} onRetry={detail.reload} />;
@@ -259,12 +258,11 @@ function PlanPanel({ planId, onOpenCustomer }: {
   </div>;
 }
 
-function OrderPanel({ orderId, onOpenCustomer }: {
+function OrderPanel({ orderId, onOpenCustomer, linkState }: {
   orderId: string;
   onOpenCustomer: (target: RefTarget) => void;
+  linkState: DetailLinkState;
 }) {
-  const location = useLocation();
-  const linkState = detailLinkState(location.pathname, location.state);
   const detail = useLoad(() => orderGet({ subscription_id: orderId }), [orderId]);
   if (detail.loading) return <p className="record-ref-status">正在读取订阅详情…</p>;
   if (detail.error) return <FetchError className="record-ref-status" message={`订阅详情取数失败:${detail.error.message}`} onRetry={detail.reload} />;

+ 7 - 2
web-scaffold/src/components/layout/InboxPanel.tsx

@@ -9,6 +9,7 @@ import { useNavigate } from "react-router";
 import { Bell, RefreshCw, X } from "lucide-react";
 import { Button } from "../ui/button";
 import { cn } from "../../lib/utils";
+import { useDetailLinkState } from "../../lib/detail-navigation";
 import {
   inboxList,
   inboxRead,
@@ -23,6 +24,10 @@ type LoadState = "idle" | "loading" | "ready" | "denied";
 
 export function InboxPanel({ onUnreadChange }: { onUnreadChange?: (n: number) => void }) {
   const navigate = useNavigate();
+  const outgoingState = useDetailLinkState();
+  const openPage = (path: string) => {
+    if (path !== outgoingState.from.split(/[?#]/, 1)[0]) navigate(path, { state: outgoingState });
+  };
   const [state, setState] = useState<LoadState>("idle");
   const [rows, setRows] = useState<InboxMessage[]>([]);
   const [unread, setUnread] = useState(0);
@@ -76,11 +81,11 @@ export function InboxPanel({ onUnreadChange }: { onUnreadChange?: (n: number) =>
       (msg.action === "open_ticket" || msg.action === "confirm_close" || msg.kind === "ticket_urge" || msg.kind === "completion_rejected" || msg.kind === "ticket_awaiting_confirm")
       && msg.payload?.ticket_id
     ) {
-      navigate(`/work-orders/${encodeURIComponent(String(msg.payload.ticket_id))}`);
+      openPage(`/work-orders/${encodeURIComponent(String(msg.payload.ticket_id))}`);
       return;
     }
     if ((msg.action === "open_customer" || msg.kind === "customer_region_transfer") && msg.payload?.customer_id) {
-      navigate(`/customers/${encodeURIComponent(String(msg.payload.customer_id))}`);
+      openPage(`/customers/${encodeURIComponent(String(msg.payload.customer_id))}`);
     }
   }
 

+ 7 - 8
web-scaffold/src/components/work-order/WorkOrderLedgerList.tsx

@@ -1,3 +1,4 @@
+import { useDetailLinkState, type DetailLinkState } from "../../lib/detail-navigation";
 import type { ReactNode } from "react";
 import { ArrowRight } from "lucide-react";
 import { Link } from "react-router";
@@ -13,9 +14,9 @@ type OwnerColumn = "assignee" | "team" | "none";
 type DateColumn = "created_at" | "completed_at";
 type LedgerItem = Omit<TicketListItem, "status"> & { status?: TicketListItem["status"] };
 
-function TicketLedgerRow({ item, from, ownerColumn, dateColumn, showNextStep, showStatus, extraAction, mobile = false }: {
+function TicketLedgerRow({ item, linkState, ownerColumn, dateColumn, showNextStep, showStatus, extraAction, mobile = false }: {
   item: LedgerItem;
-  from: string;
+  linkState: DetailLinkState;
   ownerColumn: OwnerColumn;
   dateColumn: DateColumn;
   showNextStep: boolean;
@@ -26,7 +27,6 @@ function TicketLedgerRow({ item, from, ownerColumn, dateColumn, showNextStep, sh
   const statusCode = item.status ?? "";
   const step = showNextStep ? nextStepOf({ ...item, status: statusCode }) : null;
   const href = `/work-orders/${encodeURIComponent(item.ticket_id)}`;
-  const state = { from };
   const due = todoRowDueOn(item);
   const number = item.ticket_no || item.ticket_id;
   const title = item.title?.trim();
@@ -40,9 +40,9 @@ function TicketLedgerRow({ item, from, ownerColumn, dateColumn, showNextStep, sh
   const status = showStatus && <TicketStatusTag status={statusCode} type={item.ticket_type} />;
   const type = <TicketTypeTag type={item.ticket_type} />;
   const action = step?.label
-    ? <Link className={`work-order-next-step tone-${step.tone}`} to={step.action ? `${href}?act=${step.action}` : href} state={state}>{step.label}</Link>
+    ? <Link className={`work-order-next-step tone-${step.tone}`} to={step.action ? `${href}?act=${step.action}` : href} state={linkState}>{step.label}</Link>
     : <span className="table-placeholder">—</span>;
-  const detail = <Link className="ops-table-action" to={href} state={state} aria-label={`查看工单 ${number} 详情`}>详情<ArrowRight size={14} aria-hidden="true" /></Link>;
+  const detail = <Link className="ops-table-action" to={href} state={linkState} aria-label={`查看工单 ${number} 详情`}>详情<ArrowRight size={14} aria-hidden="true" /></Link>;
 
   const actions = <div className="ops-inline-actions">{extraAction}{detail}</div>;
   const ownerLabel = ownerColumn === "team" ? "负责团队" : "责任人 / 团队";
@@ -90,7 +90,6 @@ function TicketLedgerRow({ item, from, ownerColumn, dateColumn, showNextStep, sh
 
 export function WorkOrderLedgerList<T extends LedgerItem>({
   rows,
-  from,
   label,
   fallback,
   clientView = false,
@@ -101,7 +100,6 @@ export function WorkOrderLedgerList<T extends LedgerItem>({
   renderRowAction,
 }: {
   rows: readonly T[];
-  from: string;
   label: string;
   fallback?: ReactNode;
   clientView?: boolean;
@@ -112,6 +110,7 @@ export function WorkOrderLedgerList<T extends LedgerItem>({
   renderRowAction?: (item: T) => ReactNode;
 }) {
   const tableOverflow = useHorizontalOverflow();
+  const linkState = useDetailLinkState();
   const infoColumns = [
     { label: "客户 / 工单编号", weight: 18 },
     { label: "工单标题 / 类型", weight: 24 },
@@ -127,7 +126,7 @@ export function WorkOrderLedgerList<T extends LedgerItem>({
   const bodyWidth = Math.max(minWidth, tableOverflow.width) - statusWidth - actionWidth;
   const totalWeight = infoColumns.reduce((sum, column) => sum + column.weight, 0);
   const columnWidths = [...infoColumns.map((column) => bodyWidth * column.weight / totalWeight), ...(showStatus ? [statusWidth] : []), actionWidth];
-  const rowOptions = { from, ownerColumn, dateColumn, showNextStep, showStatus };
+  const rowOptions = { linkState, ownerColumn, dateColumn, showNextStep, showStatus };
 
   return (
     <>

+ 95 - 34
web-scaffold/src/lib/detail-navigation.ts

@@ -1,36 +1,98 @@
-type DetailReturnState = { from?: unknown; previousState?: unknown };
+import { useLocation } from "react-router";
 
-const detailPath = /^\/(?:orders\/[^/]+|contracts\/[^/]+|customers\/[^/]+(?:\/orders)?|work-orders\/(?!overview$|mine$|queue$|delivery$)[^/]+)$/;
-/**
- * 可返回的列表路径。
- *
- * ⚠️ 工单组现有五个入口:`/work-orders`(台账)与 `/work-orders/{overview,mine,queue,delivery}`。
- * 这四条**不是详情**(详情是 `/work-orders/:id`),返回链必须能停在它们上面并保留筛选/页码;
- * `detailPath` 也已把四段排除,否则从总览进详情再「返回」会被当成「回工单详情」。
- */
-const listPath = /^\/(customers|contracts|orders|work-orders(?:\/(?:overview|mine|queue|delivery))?|workspace\/(?:progress|plan|queue))(?:\?[^#]*)?$/;
-const listLabels: Record<string, string> = { customers: "返回客户清单", contracts: "返回合同清单", orders: "返回全部订阅", "work-orders": "返回工单列表", "work-orders/overview": "返回工单总览", "work-orders/mine": "返回我的待办", "work-orders/queue": "返回待分派队列", "work-orders/delivery": "返回交付与回执", "workspace/progress": "返回工单进度", "workspace/plan": "返回我的套餐", "workspace/queue": "返回待分派队列" };
+type DetailReturnState = { from?: unknown; previousState?: unknown; listSearch?: unknown };
+export type DetailLinkState = { from: string; previousState: unknown };
+
+const pageLabels: Record<string, string> = {
+  "/": "返回概览",
+  "/profile": "返回个人资料",
+  "/organization/regions": "返回区域管理",
+  "/organization/operators": "返回运营商管理",
+  "/organization/partners": "返回合伙人管理",
+  "/organization/operations-teams": "返回运营团队",
+  "/organization/maintenance-teams": "返回运维团队",
+  "/packages": "返回套餐配置",
+  "/customers": "返回客户清单",
+  "/customers/new": "返回新增客户",
+  "/contracts": "返回合同清单",
+  "/contracts/new": "返回新增合同",
+  "/import-batches": "返回批量导入",
+  "/orders": "返回全部订阅",
+  "/share-rules": "返回分成管理",
+  "/costs": "返回成本管理",
+  "/correction-notes": "返回出账更正记录",
+  "/settlement-batches": "返回对账清单",
+  "/settlement-bills": "返回账单明细",
+  "/reconciliation-settings": "返回出账配置",
+  "/work-orders": "返回工单列表",
+  "/work-orders/overview": "返回工单总览",
+  "/work-orders/mine": "返回我的待办",
+  "/work-orders/queue": "返回待分派队列",
+  "/work-orders/delivery": "返回交付与回执",
+  "/work-order-settings": "返回工单配置",
+  "/m/work-orders/mine": "返回移动端待办",
+  "/workspace/progress": "返回工单进度",
+  "/workspace/plan": "返回我的套餐",
+  "/workspace/queue": "返回待分派队列",
+  "/workspace/submit": "返回提交工单",
+  "/workspace/members": "返回成员与负责范围",
+  "/workspace/dispatch-mode": "返回分派方式",
+  "/workspace/accounts": "返回下属分账号",
+  "/workspace/customer-changes": "返回归属变更",
+  "/daily-tasks": "返回定时任务",
+  "/audit-logs": "返回审计日志",
+  "/bos/pv/recon": "返回本运营区域对账",
+  "/bos/ov/recon": "返回本方对账清单",
+  "/bos/tv/recon": "返回本方对账",
+  "/bos/ov/bill-detail": "返回账单明细",
+};
+
+const detailPages: readonly (readonly [RegExp, string])[] = [
+  [/^\/orders\/[^/]+$/, "返回订阅详情"],
+  [/^\/contracts\/[^/]+(?:\/edit)?$/, "返回合同详情"],
+  [/^\/customers\/[^/]+(?:\/edit)?$/, "返回客户详情"],
+  [/^\/customers\/[^/]+\/orders$/, "返回套餐订阅管理"],
+  [/^\/work-orders\/[^/]+$/, "返回工单详情"],
+  [/^\/m\/work-orders\/[^/]+$/, "返回移动端工单详情"],
+  [/^\/m\/work-orders\/[^/]+\/backfill$/, "返回施工回填"],
+  [/^\/organization\/operations-teams\/[^/]+\/accounts$/, "返回运营团队账号"],
+  [/^\/organization\/maintenance-teams\/[^/]+\/accounts$/, "返回运维团队账号"],
+  [/^\/settlement-batches\/[^/]+\/[^/]+$/, "返回批次详情"],
+  [/^\/settlement-bills\/[^/]+$/, "返回账单明细详情"],
+  [/^\/bos\/(?:pv|ov)\/customer$/, "返回客户清单"],
+  [/^\/bos\/(?:pv|ov)\/customer\/[^/]+$/, "返回客户详情"],
+  [/^\/bos\/(?:pv|ov)\/contract$/, "返回合同清单"],
+  [/^\/bos\/(?:pv|ov)\/contract\/[^/]+$/, "返回合同详情"],
+  [/^\/bos\/(?:pv|ov|tv)\/bill-detail\/[^/]+$/, "返回账单明细详情"],
+  [/^\/bos\/(?:pv|ov|tv)\/n$/, "返回本方变更记录"],
+];
 
-export function detailLinkState(pathname: string, previousState: unknown) {
+const pathOf = (url: string) => url.split(/[?#]/, 1)[0].replace(/\/$/, "") || "/";
+
+export function detailLinkState(pathname: string, previousState: unknown): DetailLinkState {
   return { from: pathname, previousState: previousState ?? null };
 }
 
+export function useDetailLinkState(): DetailLinkState {
+  const location = useLocation();
+  return detailLinkState(location.pathname + location.search + location.hash, location.state);
+}
+
 export function detailBack(state: unknown, fallback: string, fallbackLabel: string) {
-  const { from, previousState } = (state && typeof state === "object" ? state : {}) as DetailReturnState;
-  const listMatch = typeof from === "string" ? from.match(listPath) : null;
-  if (listMatch) {
-    return { to: from as string, state: previousState ?? null, label: (from as string).split("?")[0] === fallback.split("?")[0] ? fallbackLabel : listLabels[listMatch[1]] };
-  }
-  if (typeof from !== "string" || !detailPath.test(from)) {
-    return { to: fallback, state: null, label: fallbackLabel };
-  }
+  const { from, previousState, listSearch } = (state && typeof state === "object" ? state : {}) as DetailReturnState;
+  const defaultTarget = { to: fallback, state: null, label: fallbackLabel };
+  if (typeof from !== "string" || !/^\/(?!\/)/.test(from) || /[\\\u0000-\u001f]/.test(from)) return defaultTarget;
+
+  const pathname = pathOf(from);
+  if (/(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i.test(pathname)) return defaultTarget;
+  const label = pageLabels[pathname] ?? detailPages.find(([pattern]) => pattern.test(pathname))?.[1];
+  if (!label) return defaultTarget;
 
-  const label = from.startsWith("/orders/") ? "返回订阅详情"
-    : from.startsWith("/contracts/") ? "返回合同详情"
-    : from.startsWith("/work-orders/") ? "返回工单详情"
-    : from.endsWith("/orders") ? "返回套餐订阅管理"
-    : "返回客户详情";
-  return { to: from, state: previousState ?? null, label };
+  // 兼容已打开的旧版对账页面,旧版本把筛选条件单独存在 listSearch。
+  const to = !/[?#]/.test(from) && typeof listSearch === "string" && /^\?[^#]*$/.test(listSearch)
+    ? from + listSearch
+    : from;
+  return { to, state: previousState ?? null, label: pathname === pathOf(fallback) ? fallbackLabel : label };
 }
 
 /**
@@ -46,8 +108,8 @@ export function detailBack(state: unknown, fallback: string, fallbackLabel: stri
  */
 export function customerTicketBack(state: unknown, list = "/workspace/progress", listLabel = "返回工单进度") {
   const back = detailBack(state, list, listLabel);
-  const opsTicketList = /^\/work-orders(?:\/(?:overview|mine|queue|delivery))?(?:\?|$)/;
-  return opsTicketList.test(back.to) ? { to: list, state: null, label: listLabel } : back;
+  const opsTicketList = /^\/work-orders(?:\/(?:overview|mine|queue|delivery))?$/;
+  return opsTicketList.test(pathOf(back.to)) ? { to: list, state: null, label: listLabel } : back;
 }
 
 /**
@@ -62,10 +124,9 @@ export function customerTicketBack(state: unknown, list = "/workspace/progress",
  * `<Link to={back.to} state={back.state}>`,⛔ 只看文案不看 state。
  */
 export function formBack({ state, detail, detailLabel, list, listLabel }: { state: unknown; detail: string; detailLabel: string; list: string; listLabel: string }) {
-  const { from, previousState } = (state && typeof state === "object" ? state : {}) as DetailReturnState;
-  if (typeof from === "string") {
-    if (listPath.test(from) && from.split("?")[0] === list.split("?")[0]) return { to: from, state: previousState ?? null, label: listLabel };
-    if (detailPath.test(from)) return { to: from, state: previousState ?? null, label: detailLabel };
-  }
-  return { to: detail, state: null, label: detailLabel };
+  const back = detailBack(state, detail, detailLabel);
+  const pathname = pathOf(back.to);
+  if (pathname === pathOf(list)) return { ...back, label: listLabel };
+  if (/^\/(?:customers\/[^/]+\/edit|customers\/new|contracts\/new)$/.test(pathname)) return { to: detail, state: null, label: detailLabel };
+  return pathname === pathOf(detail) ? { ...back, label: detailLabel } : back;
 }

+ 21 - 10
web-scaffold/src/pages/ContractDetailPages.tsx

@@ -1,3 +1,4 @@
+import { detailLinkState, formBack } from "../lib/detail-navigation";
 import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
 import { ArrowLeft, Lock, Plus, Trash2, Upload, X } from "lucide-react";
 import { FetchError } from "../components/fetchError";
@@ -136,6 +137,15 @@ export function ContractEditorPage() {
   const [searchParams] = useSearchParams();
   const identity = useDemoIdentity();
   const editing = Boolean(no);
+  const back = formBack({
+    state: location.state,
+    detail: no ? `/contracts/${encodeURIComponent(no)}` : "/contracts",
+    detailLabel: no ? "返回合同详情" : "返回合同台账",
+    list: "/contracts",
+    listLabel: "返回合同台账",
+  });
+  const returnToEntry = () => navigate(back.to, { state: back.state });
+  const entryState = detailLinkState(back.to, back.state);
   const catalog = useCatalogPlans();
   const plans = useMemo(() => rowsOf(catalog.data?.items), [catalog.data]);
   /** 线路出口目录(套餐配置统一维护):合同条目只从这里选(2026-11-15 裁定)。 */
@@ -429,7 +439,7 @@ export function ContractEditorPage() {
         // 清掉 ?renew= 防刷新重复带入;seed 放进 state,避免同路由 replace 时偶发丢草稿(D-CT-12)。
         navigate("/contracts/new", {
           replace: true,
-          state: { renewFrom: renewParam, renewSeed: nextDraft, renewLabel: renewalOptionLabel(row) },
+          state: { ...location.state, renewFrom: renewParam, renewSeed: nextDraft, renewLabel: renewalOptionLabel(row) },
         });
       } catch (e) {
         setRenewError(e instanceof ApiError ? e.message : "读取旧合同失败,请重试。");
@@ -1116,7 +1126,7 @@ export function ContractEditorPage() {
           row_version: version,
           ...shared,
         });
-        navigate(`/contracts/${encodeURIComponent(row.contract_id)}`);
+        returnToEntry();
       } else {
         /**
          * 命中已有客户(业主 2026-11-19 晚定案):先把可改的客户资料写回档案,再签合同。
@@ -1187,7 +1197,8 @@ export function ContractEditorPage() {
         }
         navigate(`/contracts/${encodeURIComponent(res?.contract_id ?? "")}`, {
           // 逐条替换的回执(订阅号/原订阅号/工单类型)带到详情页提示,⛔ 在本页静默丢弃。
-          state: { replacements: res?.replacements ?? [] },
+          replace: true,
+          state: { ...entryState, replacements: res?.replacements ?? [] },
         });
       }
     } catch (e) {
@@ -1271,14 +1282,14 @@ export function ContractEditorPage() {
         </div>}
         <p className="ops-form-note">激活码请用客户列表的「导出激活码」经平台凭证通道取;⛔ 本页不留存明文。</p>
         <div className="ops-form-actions">
-          <Button onClick={() => navigate(`/contracts/${encodeURIComponent(created.contractId)}`)}>查看合同详情</Button>
-          <Button variant="outline" onClick={() => navigate(`/customers/${encodeURIComponent(c.customer_id)}`)}>查看客户档案</Button>
+          <Button onClick={() => navigate(`/contracts/${encodeURIComponent(created.contractId)}`, { replace: true, state: { ...entryState, replacements: created.replacements } })}>查看合同详情</Button>
+          <Button variant="outline" onClick={() => navigate(`/customers/${encodeURIComponent(c.customer_id)}`, { replace: true, state: entryState })}>查看客户档案</Button>
         </div>
       </div>
     </section>;
   }
 
-  const backToLedger = <Link to="/contracts" className="ops-back-link"><ArrowLeft size={16} />返回合同台账</Link>;
+  const backLink = <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>;
   return <section className="ops-page ops-record-page contract-editor record-editor-fields">
     <header className="ops-page-head">
       <div>
@@ -1286,11 +1297,11 @@ export function ContractEditorPage() {
         <h1>{editing ? "编辑合同" : "合同签订表单"}</h1>
         <p>{editing ? `合同 ${no}` : "采集客户、商务、订购额度与合规信息,用于生成合同快照、资源额度和后续工单的授权依据。"}</p>
       </div>
-      {backToLedger}
+      {backLink}
     </header>
     {record.loading && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">正在从合同接口读取…</p></section></div>}
-    {record.error && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="ops-form-error" role="alert">{record.error.message}</p><div className="ops-form-actions">{backToLedger}</div></section></div>}
-    {!record.loading && !record.error && editing && !record.data && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">未找到合同 {no},可能已被删除。请从合同台账重新进入,或返回台账检索。</p><div className="ops-form-actions">{backToLedger}</div></section></div>}
+    {record.error && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="ops-form-error" role="alert">{record.error.message}</p><div className="ops-form-actions">{backLink}</div></section></div>}
+    {!record.loading && !record.error && editing && !record.data && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">未找到合同 {no},可能已被删除。请从合同台账重新进入,或返回台账检索。</p><div className="ops-form-actions">{backLink}</div></section></div>}
     {(!editing || record.data) && <div className="ops-record-layout">
       <div className="ops-record-stack">
         <section className="ops-record-card">
@@ -1808,7 +1819,7 @@ export function ContractEditorPage() {
           {error && <p className="ops-form-error" role="alert">{error}</p>}
           <div className="ops-form-actions">
             <Button size="sm" disabled={submitting || replacementBusy || (editing && record.loading)} onClick={save}>{submitting ? "正在提交…" : replacementBusy ? "正在比对替换候选…" : editing ? "保存修改" : "检查并签订"}</Button>
-            <Button size="sm" variant="outline" onClick={() => navigate(-1)}>取消</Button>
+            <Button size="sm" variant="outline" onClick={returnToEntry}>取消</Button>
           </div>
         </section>
       </aside>

+ 7 - 6
web-scaffold/src/pages/ContractManagementPage.tsx

@@ -1,8 +1,9 @@
+import { useDetailLinkState } from "../lib/detail-navigation";
 import { FilterSelect } from "../components/ui/filter-select";
 import { PageIntro } from "../components/PageIntro";
 import { useEffect, useMemo, useState } from "react";
 import { Plus, Search, Trash2, X, CalendarClock } from "lucide-react";
-import { useLocation, useNavigate, useSearchParams } from "react-router";
+import { useNavigate, useSearchParams } from "react-router";
 import { Button } from "../components/ui/button";
 import { SearchInput } from "../components/ui/search-input";
 import {
@@ -38,7 +39,7 @@ export function ContractManagementPage() {
   const flexibleWidth = Math.max(1080, tableOverflow.width) - actionWidth;
   const columnWidths = [.231, .179, .179, .154, .115, .142].map((weight) => flexibleWidth * weight).concat(actionWidth);
   const navigate = useNavigate();
-  const location = useLocation();
+  const linkState = useDetailLinkState();
   const view = useBusinessView([]);
   const [params, setParams] = useSearchParams();
   function filter(key: string, value: string) { setParams((current) => { const next = new URLSearchParams(current); if (value) next.set(key, value); else next.delete(key); return next; }, { replace: true }); }
@@ -120,7 +121,7 @@ export function ContractManagementPage() {
   const hasFilter = status !== "全部" || expiring || exit !== "" || source !== "全部来源" || search !== "" || pageFromUrl > 0;
   function reset() { setParams({}); }
   return <section className="ops-page ops-page--contracts page-fill page-fill-window">
-    <header className="ops-heading"><div><p className="ops-eyebrow"><span /> CONTRACTS / 客户与订阅</p><h1>{view.contractListTitle}</h1><PageIntro>{view.readOnly ? "按客户查找合同,核对服务何时开始、何时到期。" : "登记客户签约信息,跟进从服务开通到合同到期的进度。"}</PageIntro></div>{!view.readOnly && <Button onClick={() => navigate("/contracts/new")}><Plus size={16} />新增合同</Button>}</header>
+    <header className="ops-heading"><div><p className="ops-eyebrow"><span /> CONTRACTS / 客户与订阅</p><h1>{view.contractListTitle}</h1><PageIntro>{view.readOnly ? "按客户查找合同,核对服务何时开始、何时到期。" : "登记客户签约信息,跟进从服务开通到合同到期的进度。"}</PageIntro></div>{!view.readOnly && <Button onClick={() => navigate("/contracts/new", { state: linkState })}><Plus size={16} />新增合同</Button>}</header>
     <div className="ops-list-shell list-shell-fill">
       <div className="ops-toolbar">
         <label className="ops-search"><Search size={17} /><SearchInput aria-label="搜索合同" placeholder="搜索编号、客户、外部单号、经办人或套餐名" value={search} onCommit={(value) => { setSearch(value); resetPage(); }} />{search && <button type="button" aria-label="清空搜索" onClick={() => { setSearch(""); resetPage(); }}><X size={15} /></button>}</label>
@@ -153,15 +154,15 @@ export function ContractManagementPage() {
          */
         const expiringRow = isExpiringSoon(item.end);
         const renewContractId = item.contractId ?? "";
-        return <tr key={item.contractId || item.no} tabIndex={0} aria-label={`查看合同 ${item.no}`} onClick={() => navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } })} onKeyDown={(event) => { if (event.key === "Enter" && event.target === event.currentTarget) navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } }); }}>
+        return <tr key={item.contractId || item.no} tabIndex={0} aria-label={`查看合同 ${item.no}`} onClick={() => navigate(`/contracts/${link}`, { state: linkState })} onKeyDown={(event) => { if (event.key === "Enter" && event.target === event.currentTarget) navigate(`/contracts/${link}`, { state: linkState }); }}>
           <td><strong className="table-cell-title" title={item.no}><TableValueText>{item.no || WORD_UNCONFIGURED}</TableValueText></strong><small title={`${item.customer} · ${item.source ?? ""}`}><TableValueText>{item.customer || WORD_UNCONFIGURED}</TableValueText> · {item.contractType || "新建"} · {item.source === undefined ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端合同读口未返回 source 列(服务版本落后于 20261115000002 迁移)——如实标未下发,不填 manual 冒充" /> : textCell(item.source)}</small></td>
           <td title={item.extNo || undefined}>{item.extNo ? <span className="ops-mono">{item.extNo}</span> : <span className="table-placeholder">—</span>}</td>
           <td>{state ? <OpsStatus tone={contractStatusTone[state]}>{state}</OpsStatus> : <Tri tone={item.periodState === "fail" ? "fail" : "missing"} text={item.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="缺少生效日或结束日,状态不可判" />}{expiringRow && <OpsStatus tone="warning">快到期 · {expiringLabel(item.end)}</OpsStatus>}<small>{item.periodState === "val" ? `${d(item.start)} 至 ${d(item.end)}` : <Tri tone={item.periodState === "fail" ? "fail" : "missing"} text={item.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
           <td>{item.opened === undefined || item.opened === null ? <Tri tone={item.opened === undefined ? "fail" : "missing"} text={item.opened === undefined ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="是否已开通取关联工单回填,取数失败只坏本列" /> : <OpsStatus tone={item.opened ? "success" : "warning"}>{item.opened ? "已开通" : "未开通"}</OpsStatus>}<small>实际开通日 {item.openedOn ? d(item.openedOn) : <span className="table-placeholder">未回填</span>}</small></td>
           <td>{item.amountState === "val" ? <span className="ops-money">¥{item.amount.toLocaleString("zh-CN")}</span> : <Tri tone={item.amountState === "fail" ? "fail" : "missing"} text={item.amountState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}<small>{item.serviceMonthsState === "val" ? `服务期 ${item.serviceMonths} 个月` : <Tri tone={item.serviceMonthsState === "fail" ? "fail" : "missing"} text={item.serviceMonthsState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
           <td><strong><TableValueText>{item.agent || WORD_UNCONFIGURED}</TableValueText></strong><small><TableValueText>{item.agentPhone || WORD_UNCONFIGURED}</TableValueText></small></td>
-<td><div className="ops-inline-actions"><button type="button" onClick={(event) => { event.stopPropagation(); navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } }); }}>详情</button>{!view.readOnly && <OpsResponsiveActions expanded={expandedActions} items={[
-            ...(expiringRow && renewContractId ? [{ label: "续签合同", shortLabel: "续签", icon: <CalendarClock size={15} />, title: "按旧合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅", onSelect: () => navigate(`/contracts/new?renew=${encodeURIComponent(renewContractId)}`) }] : []),
+<td><div className="ops-inline-actions"><button type="button" onClick={(event) => { event.stopPropagation(); navigate(`/contracts/${link}`, { state: linkState }); }}>详情</button>{!view.readOnly && <OpsResponsiveActions expanded={expandedActions} items={[
+            ...(expiringRow && renewContractId ? [{ label: "续签合同", shortLabel: "续签", icon: <CalendarClock size={15} />, title: "按旧合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅", onSelect: () => navigate(`/contracts/new?renew=${encodeURIComponent(renewContractId)}`, { state: linkState }) }] : []),
             { label: "删除合同", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, title: "引用拦截由服务端判定,删除后不可恢复", onSelect: () => setDeleteId(item.contractId ?? item.no) },
           ]} />}</div></td>
         </tr>;

+ 6 - 5
web-scaffold/src/pages/ContractRecordPage.tsx

@@ -54,7 +54,6 @@ export function ContractRecordPage() {
   const view = useBusinessView(["regions", "operationsTeams"]);
   const location = useLocation();
   const back = detailBack(location.state, "/contracts", `返回${view.contractListTitle}`);
-  const outgoingState = detailLinkState(location.pathname, location.state);
   /** 新建合同随路由带来的逐条替换回执(升降配):只提示一次,刷新即消失。 */
   const replacements = (location.state as { replacements?: ContractReplacementResult[] } | null)?.replacements ?? [];
   const writable = !view.readOnly;
@@ -127,8 +126,10 @@ export function ContractRecordPage() {
   const [editingField, setEditingField] = useState<keyof ContractDraft | null>(null);
   const [editingItem, setEditingItem] = useState<number | null>(null);
   const defaultTab: ContractTab = useMatch("/contracts/:no/edit") ? "business" : "profile";
-  const [tab, setTab] = useState<ContractTab>(defaultTab);
-  useEffect(() => setTab(defaultTab), [param, defaultTab]);
+  const restoredTab = (location.state?.contractTab ?? defaultTab) as ContractTab;
+  const [tab, setTab] = useState<ContractTab>(restoredTab);
+  useEffect(() => setTab(restoredTab), [param, restoredTab]);
+  const outgoingState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, contractTab: tab });
   const [error, setError] = useState("");
   const [fieldError, setFieldError] = useState<ContractMissing | null>(null);
   const [saving, setSaving] = useState(false);
@@ -548,7 +549,7 @@ export function ContractRecordPage() {
         </div>
       </div>
       <div className="ops-hero-actions customer-record-actions">
-        {writable && record.data?.contract_id && isExpiringSoon(record.data?.end_date) ? <Button size="sm" title="按本合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅" onClick={() => navigate(`/contracts/new?renew=${encodeURIComponent(record.data?.contract_id ?? "")}`)}><CalendarClock size={15} />续签合同</Button> : null}
+        {writable && record.data?.contract_id && isExpiringSoon(record.data?.end_date) ? <Button size="sm" title="按本合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅" onClick={() => navigate(`/contracts/new?renew=${encodeURIComponent(record.data?.contract_id ?? "")}`, { state: outgoingState })}><CalendarClock size={15} />续签合同</Button> : null}
         <Button variant="outline" size="sm" onClick={record.reload}><RefreshCcw size={15} />刷新</Button>
       </div>
     </header>
@@ -793,6 +794,6 @@ export function ContractRecordPage() {
     </div>}
     {!dirty && error && <p className="ops-form-error" role="alert">{error}</p>}
     {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
-    {refStack.length > 0 && <ReferenceDrawer stack={refStack} onPush={openRef} onBack={() => setRefStack((stack) => stack.slice(0, -1))} onClose={() => setRefStack([])} />}
+    {refStack.length > 0 && <ReferenceDrawer stack={refStack} linkState={outgoingState} onPush={openRef} onBack={() => setRefStack((stack) => stack.slice(0, -1))} onClose={() => setRefStack([])} />}
   </section>;
 }

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

@@ -39,7 +39,7 @@ export function CustomerOrdersPage() {
   const { no } = useParams();
   const param = decodeURIComponent(no ?? "");
   const back = detailBack(location.state, param ? `/customers/${encodeURIComponent(param)}` : "/customers", "返回客户档案");
-  const outgoingState = detailLinkState(location.pathname, location.state);
+  const outgoingState = detailLinkState(location.pathname + location.search + location.hash, location.state);
   const tableOverflow = useHorizontalOverflow();
   /**
    * 客户档案改读真实接口(`/customer/get@v1`)。

+ 12 - 11
web-scaffold/src/pages/CustomerRecordsPages.tsx

@@ -12,8 +12,8 @@ import { FilterIcon, FilterSelect } from "../components/ui/filter-select";
 import { PageIntro } from "../components/PageIntro";
 import { FetchError } from "../components/fetchError";
 import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Download, Plus, Search, Trash2 } from "lucide-react";
-import { Navigate, useLocation, useNavigate, useParams, useSearchParams } from "react-router";
+import { ArrowLeft, Download, Plus, Search, Trash2 } from "lucide-react";
+import { Link, Navigate, useLocation, useNavigate, useParams, useSearchParams } from "react-router";
 import { Button } from "../components/ui/button";
 import { Input } from "../components/ui/input";
 import { SearchInput } from "../components/ui/search-input";
@@ -32,7 +32,7 @@ import { useOrganizationData } from "../lib/organization-demo";
 import { ACCT_STATUS, SUBJECT_TYPE } from "../lib/api/labels";
 import { ListPager } from "../components/ListPager";
 import { LIST_PAGE_SIZE, clampPage } from "../lib/list-paging";
-import { detailLinkState } from "../lib/detail-navigation";
+import { detailBack, detailLinkState } from "../lib/detail-navigation";
 import "../styles/operations.css";
 
 /** 台账主体类型筛(与后端 SUBJECT_TYPES 对齐)。 */
@@ -65,8 +65,9 @@ export function CustomerListPage() {
   const columnWidths = [.23, .19, .23, .10, .10, .15].map((weight) => flexibleWidth * weight).concat([96, actionWidth]);
   const navigate = useNavigate();
   const location = useLocation();
+  const back = detailBack(location.state, "/customers", "返回客户管理");
   /** 去详情/新增时带上「从清单哪一屏来」:返回与保存后回到同一组筛选,⛔ 退回没筛过的默认清单。 */
-  const listState = detailLinkState(`${location.pathname}${location.search}`, location.state);
+  const listState = detailLinkState(location.pathname + location.search + location.hash, location.state);
   const view = useBusinessView([]);
   const { ctx } = useSession();
   /** 与后端 `delete`/`delete_precheck` 允许集一致:仅 Admin/OpsMain(R-4);⛔ 运营子/运维走完预检才吃 60058。 */
@@ -105,7 +106,7 @@ export function CustomerListPage() {
       // 筛选变了页码必须回到第一页,⛔ 停在旧页码看空页。
       next.delete("page");
       return next;
-    }, { replace: true });
+    }, { replace: true, state: location.state });
   }
   const query = params.get("query") || "";
   const setQuery = (value: string) => filter("query", value);
@@ -141,7 +142,7 @@ export function CustomerListPage() {
       const next = new URLSearchParams(current);
       ["query", "identifier", "subject", "partner", "region", "region_node", "operator", "status", "page"].forEach((key) => next.delete(key));
       return next;
-    }, { replace: true });
+    }, { replace: true, state: location.state });
   }
   const [deleteId, setDeleteId] = useState<string | null>(null);
   const [deleteName, setDeleteName] = useState("");
@@ -228,22 +229,22 @@ export function CustomerListPage() {
    */
   const safePage = clampPage(pageZero, listTotal, LIST_PAGE_SIZE);
   useEffect(() => {
-    if (pageZero === safePage) return;
+    if (directory.loading || directory.error || pageZero === safePage) return;
     setParams((current) => {
       const updated = new URLSearchParams(current);
       if (safePage > 0) updated.set("page", String(safePage + 1)); else updated.delete("page");
       return updated;
-    }, { replace: true });
-  }, [pageZero, safePage, setParams]);
+    }, { replace: true, state: location.state });
+  }, [directory.loading, directory.error, pageZero, safePage, setParams, location.state]);
   const setPage = (next: number) => setParams((current) => {
     const updated = new URLSearchParams(current);
     if (next > 0) updated.set("page", String(next + 1)); else updated.delete("page");
     return updated;
-  }, { replace: true });
+  }, { replace: true, state: location.state });
   const pageRows = records;
   const missingCount = records.filter((item) => !item.name).length;
   const listFailed = Boolean(directory.error);
-  return <section className="ops-page ops-page--customers page-fill page-fill-window"><header className="ops-heading"><div><h1>{view.customerListTitle}</h1><PageIntro>{view.readOnly ? "从客户归属入手,查清负责范围内每家客户的服务情况。" : "登记客户主体和业务归属,后续可从客户档案追查合同和订阅。"}</PageIntro></div>{!view.readOnly && <div className="customer-list-actions"><Button variant="outline" onClick={() => setClaimExport(true)}><Download size={16} />导出激活码</Button><Button onClick={() => navigate("/customers/new", { state: listState })}><Plus size={16} />新增客户</Button></div>}</header>
+  return <section className="ops-page ops-page--customers page-fill page-fill-window">{back.to !== "/customers" && <Link className="ops-back-link self-start" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}<header className="ops-heading"><div><h1>{view.customerListTitle}</h1><PageIntro>{view.readOnly ? "从客户归属入手,查清负责范围内每家客户的服务情况。" : "登记客户主体和业务归属,后续可从客户档案追查合同和订阅。"}</PageIntro></div>{!view.readOnly && <div className="customer-list-actions"><Button variant="outline" onClick={() => setClaimExport(true)}><Download size={16} />导出激活码</Button><Button onClick={() => navigate("/customers/new", { state: listState })}><Plus size={16} />新增客户</Button></div>}</header>
     {listFailed && <FetchError message={directory.error?.message ?? FAILED} onRetry={directory.reload} />}
     {missingCount > 0 && <p className="ops-import-note">其中 {missingCount} 家客户在 <code>POST /customer/get_list@v1</code> 回执里客户名称为空,对应单元格标「{MISSING}」(本页不逐行补调 <code>/customer/get@v1</code>)。</p>}
     <div className="ops-list-shell list-shell-fill">

+ 6 - 4
web-scaffold/src/pages/CustomerTicketPages.tsx

@@ -33,13 +33,15 @@ import "../styles/operations.css";
 import "../styles/work-orders.css";
 
 export function CustomerSubmitPage() {
+  const location = useLocation();
   const identity = useDemoIdentity();
   const customer = readCustomers().find((item) => item.no === identity?.customerNo);
   const [type, setType] = useState<"fault" | "after_sale">("fault");
   const [title, setTitle] = useState("");
   const [description, setDescription] = useState("");
   const [errors, setErrors] = useState({ title: "", desc: "" });
-  const [done, setDone] = useState<{ id: string; no: string } | null>(null);
+  const [done, setDone] = useState<{ id: string; no: string } | null>(location.state?.submittedTicket ?? null);
+  const detailState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, submittedTicket: done });
   const submit = useSubmit();
   if (!identity || !["enterprise", "sub"].includes(identity.role)) return <WorkspaceEmpty title="请切换到客户账号" description="故障与售后提交入口面向客户侧账号;运维请在工单管理代办。" />;
 
@@ -72,7 +74,7 @@ export function CustomerSubmitPage() {
     <WorkspaceHeading title="提交故障或售后" description={`为 ${customer?.name ?? identity.customerNo ?? "本企业"} 提交服务请求,运维团队受理后可在工单中跟进。`} aside={<Link className="workspace-link" to="/workspace/progress">查看工单进度 <ArrowRight size={15} /></Link>} />
     <div className="workspace-split">
       <WorkspacePanel title="描述需要协助的事项" description="尽量说明发生时间、影响范围和具体表现,便于团队定位。">
-        {done && <div className="workspace-success" role="status"><Check size={18} /><span>{`工单 ${done.no} 已提交,运维团队将尽快与您联系。`} <Link className="workspace-link" to={`/work-orders/${encodeURIComponent(done.no ?? done.id)}`}>查看工单 <ArrowRight size={14} /></Link></span></div>}
+        {done && <div className="workspace-success" role="status"><Check size={18} /><span>{`工单 ${done.no} 已提交,运维团队将尽快与您联系。`} <Link className="workspace-link" to={`/work-orders/${encodeURIComponent(done.no ?? done.id)}`} state={detailState}>查看工单 <ArrowRight size={14} /></Link></span></div>}
         <form className="workspace-form !pt-0" noValidate onSubmit={onSubmit}>
           <label className="workspace-field"><span>事项类型 <em>*</em></span><select value={type} onChange={(event) => setType(event.target.value as "fault" | "after_sale")}><option value="fault">故障报修</option><option value="after_sale">售后服务</option></select></label>
           <label className="workspace-field"><span>事项标题 <em>*</em><FieldHint label="事项标题说明">受理方按标题快速识别事项,最长 128 字。</FieldHint></span><input maxLength={128} placeholder="一句话说明诉求" value={title} aria-invalid={titleInvalid || undefined} aria-describedby={titleInvalid ? "submit-title-error" : undefined} onChange={(event) => { setTitle(event.target.value); setErrors((prev) => (prev.title ? { ...prev, title: "" } : prev)); }} />{titleInvalid && <small id="submit-title-error" className="workspace-error" role="alert">{errors.title}</small>}</label>
@@ -158,7 +160,7 @@ export function CustomerTicketProgressPage() {
   const currentPage = Math.min(page, pages);
   const fail = list.error ? classifyTicketError(list.error) : null;
   /** 进详情的「来路」=本页当前 URL(含筛选与页码),返回时逐字复原。 */
-  const detailState = detailLinkState(`${location.pathname}${location.search}`, location.state);
+  const detailState = detailLinkState(location.pathname + location.search + location.hash, location.state);
 
   return <section className="work-order-page work-order-ledger-page page-fill">
     <header className="work-order-heading"><div><p className="work-order-eyebrow"><span /> CUSTOMER SUPPORT / 我的工单</p><h1>工单进度</h1></div><Link to="/workspace/submit"><Button><FileText size={17} />提交故障或售后</Button></Link></header>
@@ -239,7 +241,7 @@ function CustomerTicketActionSheet({ row, onClose, onResolved, onDone }: {
   const ref = useRef<HTMLDialogElement>(null);
   const head = detail.data?.ticket ?? null;
   /** 「查看完整记录」=从本弹框(仍在本列表页)进详情,返回目标就是这张列表。 */
-  const detailState = detailLinkState(`${location.pathname}${location.search}`, location.state);
+  const detailState = detailLinkState(location.pathname + location.search + location.hash, location.state);
 
   useEffect(() => {
     const el = ref.current;

+ 6 - 4
web-scaffold/src/pages/CustomerWorkspacePage.tsx

@@ -134,13 +134,15 @@ type ProfileDraft = {
 export function CustomerWorkspacePage() {
   const { no } = useParams();
   const location = useLocation();
-  const outgoingState = detailLinkState(location.pathname, location.state);
   const organization = useOrganizationData(["regions", "operators", "partners", "operationsTeams", "maintenanceTeams"]);
   /** 页签=本页唯一的浏览轴(讨论稿 §7.7);`#workspace-service` 仍落在「全部订阅」。 */
-  const [tab, setTab] = useState<WorkspaceTab>(() => (location.hash === "#workspace-service" ? "subscriptions" : "profile"));
+  const preferredTab = WORKSPACE_TABS.find(({ id }) => id === location.state?.customerTab)?.id;
+  const [tab, setTab] = useState<WorkspaceTab>(() => preferredTab ?? (location.hash === "#workspace-service" ? "subscriptions" : "profile"));
   useEffect(() => {
-    if (location.hash === "#workspace-service") setTab("subscriptions");
-  }, [location.hash]);
+    if (preferredTab) setTab(preferredTab);
+    else if (location.hash === "#workspace-service") setTab("subscriptions");
+  }, [location.hash, preferredTab]);
+  const outgoingState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, customerTab: tab });
 
   /** 详情侧栏列表:默认每页 20,page/page_size 下推服务端(⛔ 一次拉 200)。 */
   const [ordersPage, setOrdersPage] = useState(0);

+ 21 - 12
web-scaffold/src/pages/FinanceReferencePages.tsx

@@ -3,7 +3,7 @@ import { PageIntro } from "../components/PageIntro";
 import { FilterSelect } from "../components/ui/filter-select";
 import { MonthFilter } from "../components/ui/month-filter";
 import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { ArrowRight, PencilLine, Plus, Search, Trash2, X } from "lucide-react";
+import { ArrowLeft, ArrowRight, PencilLine, Plus, Search, Trash2, X } from "lucide-react";
 import { ListPager, ServerListPager } from "../components/ListPager";
 import { slicePage, useLocalPage, LIST_PAGE_SIZE } from "../lib/list-paging";
 import { Button } from "../components/ui/button";
@@ -13,6 +13,7 @@ import { OpsHint, OpsNotice, OpsResponsiveActions, OpsStatus, OpsTag, OpsTableEm
 import { TreeSelect } from "../components/ui/tree-select";
 import { regionTreeNodes } from "../lib/region-tree";
 import { Link, useLocation } from "react-router";
+import { detailBack, detailLinkState, type DetailLinkState } from "../lib/detail-navigation";
 
 import { Tri } from "../components/triState";
 import { ApiError, hasBizCode } from "../lib/api/http";
@@ -755,7 +756,11 @@ export function CorrectionNotesPage() {
   const { identity, organization, readOnly } = useBusinessView(["regions", "operationsTeams", "enterprises"]);
   const location = useLocation();
   /** 批次详情「登记更正」入口带来的预填关联对象(state.ref=对账单号,进页即开登记窗、一次性消费)。 */
-  const prefillRef = ((location.state ?? {}) as { ref?: string }).ref ?? "";
+  const { ref: prefillRef = "", correctionView } = (location.state ?? {}) as {
+    ref?: string;
+    correctionView?: { period: string; regionNodeId: string; operatorKeyword: string; keyword: string; page: number; detailId: string | null };
+  };
+  const back = detailBack(location.state, "/correction-notes", "返回出账更正记录");
   const allowed = useMemo(() => onboardingRegions(organization, identity), [organization, identity]);
   const tree = useMemo(() => regionTreeNodes(organization.regions, [...allowed]), [organization.regions, allowed]);
   /**
@@ -766,18 +771,21 @@ export function CorrectionNotesPage() {
   const regionNames = useMemo(() => new Map(organization.regions.map((r) => [r.id, r.name])), [organization.regions]);
 
   // 筛选四件:自然月(⛔ 预选——记录永久保留,预选会把「本期没有更正」看成「从没有过更正」)+归属区域+登记人+关键字(只查错误内容,⛔ 扩到关联对象)。
-  const [period, setPeriod] = useState("");
-  const [regionNodeId, setRegionNodeId] = useState("");
-  const [operatorKeyword, setOperatorKeyword] = useState("");
-  const [keyword, setKeyword] = useState("");
-  const [page, setPage] = useState(1);
+  const [period, setPeriod] = useState(correctionView?.period ?? "");
+  const [regionNodeId, setRegionNodeId] = useState(correctionView?.regionNodeId ?? "");
+  const [operatorKeyword, setOperatorKeyword] = useState(correctionView?.operatorKeyword ?? "");
+  const [keyword, setKeyword] = useState(correctionView?.keyword ?? "");
+  const [page, setPage] = useState(correctionView?.page ?? 1);
   const list = useCorrectionList({ period, regionNodeId, operatorKeyword, keyword, page });
   const wiring = list.fail?.kind === "wiring";
   const total = list.data?.total ?? 0;
   const pageSize = list.data?.page_size ?? 20;
 
   const [creating, setCreating] = useState(false);
-  const [detailId, setDetailId] = useState<string | null>(null);
+  const [detailId, setDetailId] = useState<string | null>(correctionView?.detailId ?? null);
+  const outgoingState = detailLinkState(location.pathname + location.search + location.hash, {
+    ...location.state, ref: "", correctionView: { period, regionNodeId, operatorKeyword, keyword, page, detailId },
+  });
   const [notice, setNotice] = useState("");
   useEffect(() => { if (prefillRef) setCreating(true); }, [prefillRef]);
 
@@ -788,6 +796,7 @@ export function CorrectionNotesPage() {
   // 不授键角色(只读三类+运维团队三类)整页不开放;regAdmin 可登记,范围由服务端收窄(越权 KLT-C007 直读 message)。
   if (readOnly) return <div className="ops-empty">当前身份无权查看出账更正记录。</div>;
   return <section className="ops-page ops-page--corrections page-fill page-fill-window">
+    {back.to !== "/correction-notes" && <Link className="ops-back-link self-start" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
     <header className="ops-heading">
       <div><h1>出账更正记录</h1><PageIntro>发现已出账的差错时,在这里登记问题、关联账单,便于日后核查。</PageIntro></div>
       <Button onClick={() => setCreating(true)}><Plus size={16} />登记更正</Button>
@@ -835,7 +844,7 @@ export function CorrectionNotesPage() {
     {creating && <CorrectionCreateDialog userKey={identity?.login ?? "anonymous"} initialRef={prefillRef}
       onClose={() => setCreating(false)}
       onCreated={() => { setCreating(false); setNotice(CORRECTION_CREATED_FEEDBACK); list.reload(); }} />}
-    {detailId && <CorrectionDetailDialog id={detailId} regionNames={regionNames} refLabel={(list.data?.items ?? []).find((item) => item.correction_id === detailId)?.ref_label ?? "更正记录"} onClose={() => setDetailId(null)} />}
+    {detailId && <CorrectionDetailDialog id={detailId} regionNames={regionNames} linkState={outgoingState} refLabel={(list.data?.items ?? []).find((item) => item.correction_id === detailId)?.ref_label ?? "更正记录"} onClose={() => setDetailId(null)} />}
     {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
   </section>;
 }
@@ -937,7 +946,7 @@ function CorrectionCreateDialog({ userKey, initialRef, onClose, onCreated }: {
 }
 
 /** FN-11 详情窗:命中/未命中两种展示同源一个接口;能进列表就能进详情(11104 越权与查无同码 ⇒ fail 分支)。 */
-function CorrectionDetailDialog({ id, refLabel, regionNames, onClose }: { id: string; refLabel: string; regionNames: Map<string, string>; onClose: () => void }) {
+function CorrectionDetailDialog({ id, refLabel, regionNames, linkState, onClose }: { id: string; refLabel: string; regionNames: Map<string, string>; linkState: DetailLinkState; onClose: () => void }) {
   const detail = useCorrectionDetail(id);
   const d = detail.data;
   const wiring = detail.fail?.kind === "wiring";
@@ -960,9 +969,9 @@ function CorrectionDetailDialog({ id, refLabel, regionNames, onClose }: { id: st
         <section className="correction-notes-detail-section"><h3>关联对象</h3>
           {d.matched ? (
             <ul>
-              {d.matched_bill_detail_id && <li><Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(d.matched_bill_detail_id)}`} state={{ from: "/correction-notes" }}>进入账单明细({d.matched_bill_detail_id}) <ArrowRight size={14} /></Link></li>}
+              {d.matched_bill_detail_id && <li><Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(d.matched_bill_detail_id)}`} state={linkState}>进入账单明细({d.matched_bill_detail_id}) <ArrowRight size={14} /></Link></li>}
               {d.matched_batch_no && <li>{d.matched_holder_id
-                ? <Link className="ops-table-action" to={`/settlement-batches/${encodeURIComponent(d.matched_holder_id)}/${encodeURIComponent(d.matched_batch_no)}`} state={{ from: "/correction-notes" }}>进入对账批次({d.matched_batch_no}) <ArrowRight size={14} /></Link>
+                ? <Link className="ops-table-action" to={`/settlement-batches/${encodeURIComponent(d.matched_holder_id)}/${encodeURIComponent(d.matched_batch_no)}`} state={linkState}>进入对账批次({d.matched_batch_no}) <ArrowRight size={14} /></Link>
                 : <span>对账批次 {d.matched_batch_no} <small title="批次持有方未随详情下发,批次入口暂不可用(已登记缺口清单)">(批次入口{BACKEND_NOT_WIRED})</small></span>}</li>}
             </ul>
           ) : (

+ 3 - 1
web-scaffold/src/pages/JobRunsDialog.tsx

@@ -48,6 +48,7 @@ import {
 } from "../lib/copy-jobs";
 import type { JobRunRow } from "../lib/api/types";
 import { useNavigate } from "react-router";
+import { useDetailLinkState } from "../lib/detail-navigation";
 
 export interface JobRunsPreset {
   jobKey: string;
@@ -56,6 +57,7 @@ export interface JobRunsPreset {
 
 export function JobRunsDialog({ preset, rows, onClose }: { preset: JobRunsPreset; rows: JobListRow[]; onClose: () => void }) {
   const navigate = useNavigate();
+  const linkState = useDetailLinkState();
   const [filter, setFilter] = useState<RunsFilter>({ ...EMPTY_RUNS_FILTER, jobKey: preset.jobKey });
   const [applied, setApplied] = useState<RunsFilter>({ ...EMPTY_RUNS_FILTER, jobKey: preset.jobKey });
   const [detail, setDetail] = useState<JobRunRow | null>(null);
@@ -175,7 +177,7 @@ export function JobRunsDialog({ preset, rows, onClose }: { preset: JobRunsPreset
                 </thead>
                 <tbody role="rowgroup">
                   {state.runs.map((run) => (
-                    <RunRow key={run.run_id} run={run} rows={rows} onDetail={() => setDetail(run)} onGoto={(page) => { onClose(); navigate(page); }} />
+                    <RunRow key={run.run_id} run={run} rows={rows} onDetail={() => setDetail(run)} onGoto={(page) => { onClose(); navigate(page, { state: linkState }); }} />
                   ))}
                 </tbody>
               </table>

+ 12 - 6
web-scaffold/src/pages/OrderManagementPage.tsx

@@ -4,11 +4,12 @@ import { OpsStatus, OpsTableColumns, OpsTableEmpty } from "../components/Operati
 import { FilterSelect } from "../components/ui/filter-select";
 import { useEffect, useMemo, useState } from "react";
 import {
-  CalendarClock, CalendarDays, ChevronRight, Clock3,
+  ArrowLeft, CalendarClock, CalendarDays, ChevronRight, Clock3,
   Search, Signal, X,
 } from "lucide-react";
 import { Button } from "../components/ui/button";
-import { useNavigate, useSearchParams } from "react-router";
+import { Link, useLocation, useNavigate, useSearchParams } from "react-router";
+import { detailBack, useDetailLinkState } from "../lib/detail-navigation";
 import { Input } from "../components/ui/input";
 import { orderStatuses, statusPresentation, type OrderStatus } from "../domain/statuses";
 import {
@@ -66,6 +67,10 @@ export function OrderManagementPage() {
   /** 操作列只余「详情」一颗按钮(写入口已按需求 5.2 移出本页)⇒ 末两列 = 状态 104 + 操作 96。 */
   const columnWidths = [.21, .23, .14, .09, .12, .10, .11].map((weight) => contentWidth * weight).concat([104, 96]);
   const navigate = useNavigate();
+  const { state } = useLocation();
+  const back = detailBack(state, "/orders", "返回全部订阅");
+  const outgoingState = useDetailLinkState();
+  const openOrder = (number: string) => navigate(`/orders/${encodeURIComponent(number)}`, { state: outgoingState });
   const [params, setParams] = useSearchParams();
   function updateQuery(key: string, value: string) {
     setParams((current) => {
@@ -74,7 +79,7 @@ export function OrderManagementPage() {
       else next.delete(key);
       if (key !== "page") next.delete("page");
       return next;
-    }, { replace: true });
+    }, { replace: true, state });
   }
   const status = (params.get("status") as StatusFilter) || "全部状态";
   const planKind = (params.get("plan") as PlanFilter) || "全部类型";
@@ -122,7 +127,7 @@ export function OrderManagementPage() {
     [exitsLoad.data],
   );
   function resetFilters() {
-    setParams({});
+    setParams({}, { state });
   }
   const statuses: StatusFilter[] = ["全部状态", ...orderStatuses];
   const tabCount = (item: StatusFilter) => {
@@ -156,6 +161,7 @@ export function OrderManagementPage() {
     : !records.length ? <span role="status">{emptyMessage}</span>
     : null;
   return <section className="order-page page-fill page-fill-window">
+    {back.to !== "/orders" && <Link className="ops-back-link self-start" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
     <header className="order-heading">
       <div><p className="order-eyebrow"><span /> CONTRACT OPERATIONS <b>/</b> 产品与订阅</p><h1>全部订阅</h1><PageIntro>本页仅供查询。新增订阅、升降配或叠加的{SUBS_READONLY_ENTRY}。</PageIntro></div>
     </header>
@@ -183,12 +189,12 @@ export function OrderManagementPage() {
           <td><strong className="order-date">{dateCell(item.openedOn, WORD_NOT_OPENED)}</strong><small>{item.openedOn ? "计费取较晚日期" : <span className="table-placeholder">暂无计费起点</span>}</small></td>
           <td><StatusPill record={item} /></td>
           <td><div className="ops-inline-actions">
-            <button type="button" className="ops-table-action" onClick={() => navigate(`/orders/${encodeURIComponent(item.no)}`)} aria-label={`查看${item.customer}订阅详情`}>详情</button>
+            <button type="button" className="ops-table-action" onClick={() => openOrder(item.no)} aria-label={`查看${item.customer}订阅详情`}>详情</button>
           </div></td>
         </tr>;
         })}
       </tbody></table></div>
-      <div className="order-mobile-list">{listState ? <div className="order-mobile-state">{listState}</div> : records.map((item) => <article key={item.no} className="order-mobile-card"><div><small>{item.no}</small><StatusPill record={item} /></div><h3>{item.customer}</h3><p>{item.planName ?? WORD_UNCONFIGURED} <span>·</span> {item.termLabel || WORD_UNCONFIGURED}</p><dl><div><dt>年订阅价格</dt><dd>{moneyCell(item.annual)}</dd></div><div><dt>合同周期</dt><dd>{dateCell(item.start)} — {dateCell(item.end)}</dd></div></dl><button type="button" onClick={() => navigate(`/orders/${encodeURIComponent(item.no)}`)}>查看订阅详情</button></article>)}</div>
+      <div className="order-mobile-list">{listState ? <div className="order-mobile-state">{listState}</div> : records.map((item) => <article key={item.no} className="order-mobile-card"><div><small>{item.no}</small><StatusPill record={item} /></div><h3>{item.customer}</h3><p>{item.planName ?? WORD_UNCONFIGURED} <span>·</span> {item.termLabel || WORD_UNCONFIGURED}</p><dl><div><dt>年订阅价格</dt><dd>{moneyCell(item.annual)}</dd></div><div><dt>合同周期</dt><dd>{dateCell(item.start)} — {dateCell(item.end)}</dd></div></dl><button type="button" onClick={() => openOrder(item.no)}>查看订阅详情</button></article>)}</div>
       <ListPager total={serverTotal} page={paging.safePage} pageSize={paging.pageSize} onPageChange={setPage} unit="条" className="list-pager" />
       <details className="order-rule-strip is-footer"><summary><CalendarDays size={16} />订阅计费规则<span>合同生效 → 实际开通 → 自然月核算</span><ChevronRight size={16} /></summary><div className="order-rule-content">
         <div><CalendarDays size={18} /><span><strong>合同生效</strong><small>确定年度订阅周期</small></span></div><ChevronRight size={15} />

+ 3 - 3
web-scaffold/src/pages/OrderRecordPage.tsx

@@ -43,7 +43,7 @@ export function OrderRecordPage() {
   const param = decodeURIComponent(id ?? "");
   const location = useLocation();
   const back = detailBack(location.state, view.customerView ? "/workspace/plan" : view.readOnly ? "/customers" : "/orders", view.customerView ? "返回我的套餐" : view.readOnly ? `返回${view.customerListTitle}` : "返回全部订阅");
-  const outgoingState = detailLinkState(location.pathname, location.state);
+  const outgoingState = detailLinkState(location.pathname + location.search + location.hash, location.state);
   /** Wave B:详情走 `subscription/get`(含 billing 四卡),⛔ 再靠 list_all 凑行。 */
   const orders = useOrderRecord(param || undefined);
   const item = orders.data ?? undefined;
@@ -221,7 +221,7 @@ export function OrderRecordPage() {
         {item.trialMonths ? <tr><th scope="row">试用优惠</th><td>{item.trialMonths} 个月 · {item.trialDiscount === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.trialDiscount === null ? <span className="table-placeholder">优惠金额未填写</span> : `${moneyCell(item.trialDiscount).text} / 月`}</td></tr> : null}
         <tr><th scope="row">线路出口</th><td>{item.exits === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.exits === null ? <Tri tone="missing" text={WORD_UNCONFIGURED} /> : item.exits.length ? item.exits.join("、") : <Tri tone="missing" text={WORD_UNCONFIGURED} />}<span className="order-record-inline-note"> · 随合同服务构成条目带出,保存时冻结</span></td></tr>
         <tr><th scope="row">合同编号</th><td>{cell(item.contractNo)}{contract.error ? <span className="order-record-inline-note">(合同记录取数失败:{contract.error.message})</span> : contract.loading ? <span className="order-record-inline-note">(正在读取合同…)</span> : contractRow ? <> · <TableValueText>{contractRow.start_date ?? WORD_UNCONFIGURED}</TableValueText> 至 <TableValueText>{contractRow.end_date ?? WORD_UNCONFIGURED}</TableValueText> · 合同状态 <TableValueText>{contractState ?? WORD_UNCONFIGURED}</TableValueText> · 合同总额 {moneyCell(contractRow.amount_cents).text} <Link to={`/contracts/${encodeURIComponent(contractRow.contract_id)}`} state={outgoingState}>查看合同 <ArrowRight size={14} /></Link></> : <span className="order-record-inline-note">(合同记录不存在或未下发 contract_id)</span>}</td></tr>
-        <tr><th scope="row">订单号</th><td>{cell(item.orderNo, "无运营商订单号")}<span className="order-record-inline-note"> · 保存时从合同外部单号冻结;订阅写入方在第4册{!view.readOnly && item.orderNo && <> · <Link to={`/orders?order=${encodeURIComponent(item.orderNo)}`}>按该单查询</Link></>}</span></td></tr>
+        <tr><th scope="row">订单号</th><td>{cell(item.orderNo, "无运营商订单号")}<span className="order-record-inline-note"> · 保存时从合同外部单号冻结;订阅写入方在第4册{!view.readOnly && item.orderNo && <> · <Link to={`/orders?q=${encodeURIComponent(item.orderNo)}`} state={outgoingState}>按该单查询</Link></>}</span></td></tr>
         <tr><th scope="row">实际开通日</th><td>{item.openedOn === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.openedOn ? item.openedOn : <Tri tone="missing" text="未开通" />}<span className="order-record-inline-note"> · 由运维回填,本册只读</span></td></tr>
         <tr><th scope="row">提前停机日</th><td>{item.earlyStoppedOn ? item.earlyStoppedOn : <Tri tone="missing" text="—" />}<span className="order-record-inline-note"> · 提前停机回填生效后写入;起止日不变</span></td></tr>
         <tr><th scope="row">可否编辑</th><td><OpsStatus tone={item.editable === undefined ? "neutral" : editable ? "success" : "neutral"}>{item.editable === undefined ? "未知" : editable ? "可编辑" : "只读"}</OpsStatus><span className="order-record-inline-note"> · {editReason}</span>{editable && <> · <Link to={`/customers/${encodeURIComponent(item.customerId)}/orders`} state={outgoingState}>前往办理 <ArrowRight size={14} /></Link></>}</td></tr>
@@ -290,7 +290,7 @@ export function OrderRecordPage() {
       </div>
       {relatedTickets.loading ? <p className="order-record-empty-note">正在按订单号读取工单台账…</p>
         : relatedTickets.error ? <p className="order-record-empty-note"><Tri tone="fail" text={WORD_FETCH_FAILED} title={relatedTickets.error.message} /> 工单台账取数失败,不得把「查不了」渲染成「0 张」。</p>
-        : ticketRows.length ? <div className="order-record-table-wrap"><table><thead><tr><th>我方工单号</th><th>类型</th><th>状态</th><th>创建日</th><th>完成日</th></tr></thead><tbody>{ticketRows.map((ticket) => <tr key={ticket.ticket_id}><td><Link to={`/work-orders/${encodeURIComponent(ticket.ticket_id)}`} state={{ from: `/orders/${encodeURIComponent(item.no)}` }}>{ticket.ticket_no ?? ticket.ticket_id}<ArrowRight size={14} /></Link></td><td>{typeLabel(ticket.ticket_type)}</td><td><OpsStatus tone={ticket.status === "completed" || ticket.status === "settled" ? "success" : ticket.status === "processing" || ticket.status === "pending" ? "warning" : "neutral"}>{statusLabel(ticket.status, ticket.ticket_type)}</OpsStatus></td><td>{fmtDate(ticket.created_at)}</td><td>{fmtDate(ticket.completed_at)}</td></tr>)}</tbody></table></div> : <p className="order-record-empty-note">本条订阅暂无关联工单(按订单号现查 <code>/ticket/list@v1</code>,服务端可见范围内为空)。历史漏单可点「补发交付工单」。</p>}
+        : ticketRows.length ? <div className="order-record-table-wrap"><table><thead><tr><th>我方工单号</th><th>类型</th><th>状态</th><th>创建日</th><th>完成日</th></tr></thead><tbody>{ticketRows.map((ticket) => <tr key={ticket.ticket_id}><td><Link to={`/work-orders/${encodeURIComponent(ticket.ticket_id)}`} state={outgoingState}>{ticket.ticket_no ?? ticket.ticket_id}<ArrowRight size={14} /></Link></td><td>{typeLabel(ticket.ticket_type)}</td><td><OpsStatus tone={ticket.status === "completed" || ticket.status === "settled" ? "success" : ticket.status === "processing" || ticket.status === "pending" ? "warning" : "neutral"}>{statusLabel(ticket.status, ticket.ticket_type)}</OpsStatus></td><td>{fmtDate(ticket.created_at)}</td><td>{fmtDate(ticket.completed_at)}</td></tr>)}</tbody></table></div> : <p className="order-record-empty-note">本条订阅暂无关联工单(按订单号现查 <code>/ticket/list@v1</code>,服务端可见范围内为空)。历史漏单可点「补发交付工单」。</p>}
       <ListPager total={ticketTotal} page={ticketPage} pageSize={LIST_PAGE_SIZE} onPageChange={setTicketPage} unit="张" />
       <p className="order-record-note">订阅保存后,未开户走开户工单,已在用走服务开通工单;运维回填的实际开通日写回本条订阅。点击工单号查看详情。工单列表服务端分页(默认每页 {LIST_PAGE_SIZE},页码 1 基)。</p>
     </section>}

+ 55 - 25
web-scaffold/src/pages/OrganizationPages.tsx

@@ -10,7 +10,8 @@ import { FilterIcon, FilterSelect } from "../components/ui/filter-select";
 import { useLayoutEffect, useEffect, useMemo, useRef, useState, type CSSProperties, type FormEvent, type ReactNode } from "react";
 import { createPortal } from "react-dom";
 import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, ArrowUpDown, Building2, ChevronDown, ChevronRight, Download, Info, MapPinned, PencilLine, Plus, Search, Trash2, UserRound, Users, Wrench, X } from "lucide-react";
-import { Link, useParams, useSearchParams } from "react-router";
+import { Link, useLocation, useParams, useSearchParams } from "react-router";
+import { detailBack, detailLinkState } from "../lib/detail-navigation";
 import { Button as UiButton } from "../components/ui/button";
 import { TreeSelect } from "../components/ui/tree-select";
 import { FieldHint } from "../components/ui/field-hint";
@@ -834,9 +835,10 @@ function RegionTree({ data, parent, selected, expanded, menu, canAdmin, select,
 
 /** 名录区域筛与概况下钻共用 `?region=`(节点 ID);改筛/重置同步写回 URL。非法 id 回落为空并提示。 */
 function useRegionQueryFilter(knownIds?: Set<string>) {
+  const { state } = useLocation();
   const [params, setParams] = useSearchParams();
   const raw = params.get("region") || "";
-  const invalid = Boolean(raw && knownIds && !knownIds.has(raw));
+  const invalid = Boolean(raw && knownIds?.size && !knownIds.has(raw));
   const region = invalid ? "" : raw;
   useEffect(() => {
     if (!invalid) return;
@@ -844,15 +846,15 @@ function useRegionQueryFilter(knownIds?: Set<string>) {
       const next = new URLSearchParams(current);
       next.delete("region");
       return next;
-    }, { replace: true });
-  }, [invalid, setParams]);
+    }, { replace: true, state });
+  }, [invalid, setParams, state]);
   const setRegion = (value: string) => {
     setParams((current) => {
       const next = new URLSearchParams(current);
       if (value) next.set("region", value);
       else next.delete("region");
       return next;
-    }, { replace: true });
+    }, { replace: true, state });
   };
   return [region, setRegion, invalid ? raw : ""] as const;
 }
@@ -869,6 +871,7 @@ function regionDrillPath(base: string, nodeId: string) {
  * (`replace`,刷新不再重复弹出);记录已删/不在可见范围时参数留着不动,也不弹空表。
  */
 function useEditorDeepLink(kind: EditorKind, exists: (id: string) => boolean, editor: Editor | null, setEditor: (next: Editor | null) => void) {
+  const { state } = useLocation();
   const [params, setParams] = useSearchParams();
   const wanted = params.get("edit") ?? "";
   useEffect(() => {
@@ -878,13 +881,22 @@ function useEditorDeepLink(kind: EditorKind, exists: (id: string) => boolean, ed
       const next = new URLSearchParams(current);
       next.delete("edit");
       return next;
-    }, { replace: true });
-  }, [wanted, editor, kind, exists, setEditor, setParams]);
+    }, { replace: true, state });
+  }, [wanted, editor, kind, exists, setEditor, setParams, state]);
+}
+
+function OrganizationEntryBack({ fallback }: { fallback: string }) {
+  const { state } = useLocation();
+  const back = detailBack(state, fallback, "返回档案列表");
+  if (back.to === fallback) return null;
+  return <Link className="org-back-link self-start" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>;
 }
 
 function RegionOverview({ data, node, canAdmin, onOpenInfo, onSelect, onDelete }: {
   data: OrganizationData; node: Region; canAdmin: boolean; onOpenInfo: () => void; onSelect: (id: string) => void; onDelete: (id: string) => void;
 }) {
+  const location = useLocation();
+  const linkState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, regionSelected: node.id });
   const loaded = useOrganizationLoaded();
   const status = useOrganizationStatus();
   const visibleIds = useMemo(() => new Set(data.regions.map((item) => item.id)), [data.regions]);
@@ -916,7 +928,7 @@ function RegionOverview({ data, node, canAdmin, onOpenInfo, onSelect, onDelete }
     <div className="org-overview-grid">{cards.map((card) => {
       const enabled = Boolean(card.href || card.onClick);
       if (card.href) {
-        return <Link className={`org-overview-card${enabled ? "" : " is-disabled"}`} key={card.title} to={card.href} aria-disabled={!enabled} onClick={(e) => { if (!enabled) e.preventDefault(); }}><span className="org-overview-card-title">{card.title}{enabled ? <ArrowRight aria-hidden="true" size={16} /> : null}</span><strong>{card.value}</strong><small>{card.detail}</small></Link>;
+        return <Link className={`org-overview-card${enabled ? "" : " is-disabled"}`} key={card.title} to={card.href} state={linkState} aria-disabled={!enabled} onClick={(e) => { if (!enabled) e.preventDefault(); }}><span className="org-overview-card-title">{card.title}{enabled ? <ArrowRight aria-hidden="true" size={16} /> : null}</span><strong>{card.value}</strong><small>{card.detail}</small></Link>;
       }
       return <button className="org-overview-card" key={card.title} onClick={card.onClick} type="button" disabled={!enabled}><span className="org-overview-card-title">{card.title}{enabled ? <ArrowRight aria-hidden="true" size={16} /> : null}</span><strong>{card.value}</strong><small>{card.detail}</small></button>;
     })}</div>
@@ -925,6 +937,7 @@ function RegionOverview({ data, node, canAdmin, onOpenInfo, onSelect, onDelete }
 }
 
 export function RegionManagementPage() {
+  const location = useLocation();
   // 首屏只拉区域树(counters 已内联):墙钟曾被并行的 ops_team/ent_team 拖到 2~4s。
   // 概况卡片的团队名录计数延后补取——未就绪时卡片已回「尚未就绪」,⛔ 挡树渲染。
   const data = useOrganizationData(["regions"]);
@@ -936,7 +949,7 @@ export function RegionManagementPage() {
   const regionScoped = identity?.role === "regAdmin";
   const visible = data.regions.filter((r) => r.id !== V_ROOT);
   const visibleIds = useMemo(() => new Set(data.regions.map((r) => r.id)), [data.regions]);
-  const [selected, setSelected] = useState("");
+  const [selected, setSelected] = useState<string>(location.state?.regionSelected ?? "");
   const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
   const [tab, setTab] = useState<"overview" | "info">("overview");
   const [menu, setMenu] = useState<RegionTreeMenuState>(null);
@@ -1115,6 +1128,7 @@ export function OperatorManagementPage() {
     return <DirectorySortHeader label={label} direction={sortKey === key ? sortDir : undefined} onSort={() => toggleSort(key)} />;
   }
   return <div className="org-page org-operator-page page-fill">
+    <OrganizationEntryBack fallback="/organization/operators" />
     <PageHead eyebrow="组织与区域 / 02" title="运营商管理" exportCsv={{ onClick: exportRows, disabled: !rows.length }} description="按所属区域建立结算对手方档案,集中核对对账口径。" action={<Button onClick={() => setEditor({ kind: "operator" })}><Plus size={16} /> 新增运营商</Button>} />
     <OrgFetchState status={status} collections={["operators"]} />
     <CollectionFailed status={status} collection="operators" title="运营商" />
@@ -1236,7 +1250,7 @@ export function PartnerManagementPage() {
   function sortHeader(key: PtSort, label: string) {
     return <DirectorySortHeader label={label} direction={sortKey === key ? sortDir : undefined} onSort={() => toggleSort(key)} />;
   }
-  return <div className="org-page org-partner-page page-fill"><PageHead eyebrow="组织与区域 / 03" title="合伙人管理" exportCsv={{ onClick: exportRows, disabled: !rows.length }} description="为渠道合伙人建档,明确客户覆盖范围和分成约定。" action={<Button onClick={() => setEditor({ kind: "partner" })}><Plus size={16} /> 新建合伙人</Button>} />
+  return <div className="org-page org-partner-page page-fill"><OrganizationEntryBack fallback="/organization/partners" /><PageHead eyebrow="组织与区域 / 03" title="合伙人管理" exportCsv={{ onClick: exportRows, disabled: !rows.length }} description="为渠道合伙人建档,明确客户覆盖范围和分成约定。" action={<Button onClick={() => setEditor({ kind: "partner" })}><Plus size={16} /> 新建合伙人</Button>} />
     <OrgFetchState status={status} collections={["partners"]} />
     <CollectionFailed status={status} collection="partners" title="合伙人" />
     {invalidRegion && <p className="org-form-error" role="status">区域参数无效({invalidRegion}),已回落为全部区域。</p>}
@@ -1318,7 +1332,9 @@ export function OperationsTeamManagementPage() {
   const actionWidth = expandedActions ? 280 : 148;
   const remaining = Math.max(1100, tableOverflow.width) - 200 - actionWidth;
   const columnWidths = [remaining * .30, remaining * .23, remaining * .16, remaining * .31, 90, 110, actionWidth];
-  const [query, setQuery] = useState("");
+  const location = useLocation();
+  const savedView = location.state?.teamList as { query: string; mode?: string; sortKey: EntSort | null; sortDir: SortDir; page: number; pageSize: number } | undefined;
+  const [query, setQuery] = useState(savedView?.query ?? "");
   const regionIds = useMemo(() => new Set(data.regions.map((item) => item.id)), [data.regions]);
   const [regionFilter, setRegionFilter, invalidRegion] = useRegionQueryFilter(regionIds);
   const [editor, setEditor] = useState<Editor | null>(null);
@@ -1332,8 +1348,8 @@ export function OperationsTeamManagementPage() {
   // 总部内置在任意区域筛选下仍可见(「全网/某省」=不把总部藏掉)。
   const filtered = data.operationsTeams.filter((team) => (!regionFilter || team.hq || descendants(data, regionFilter).includes(team.region)) && `${team.name} ${team.desc} ${scopeSummary(data, team.scope)}`.toLowerCase().includes(query.trim().toLowerCase()));
   type EntSort = "name" | "region" | "coverage" | "members";
-  const [sortKey, setSortKey] = useState<EntSort | null>("name");
-  const [sortDir, setSortDir] = useState<SortDir>("asc");
+  const [sortKey, setSortKey] = useState<EntSort | null>(savedView ? savedView.sortKey : "name");
+  const [sortDir, setSortDir] = useState<SortDir>(savedView?.sortDir ?? "asc");
   const teams = useMemo(() => {
     const list = [...filtered];
     if (!sortKey) return list;
@@ -1345,7 +1361,10 @@ export function OperationsTeamManagementPage() {
     });
     return list;
   }, [filtered, sortKey, sortDir, data]);
-  const paging = useLocalPage(teams.length);
+  const paging = useLocalPage(teams.length, savedView?.pageSize, savedView?.page);
+  const linkState = detailLinkState(location.pathname + location.search + location.hash, {
+    ...location.state, teamList: { query, sortKey, sortDir, page: paging.safePage, pageSize: paging.pageSize },
+  });
   const pageTeams = slicePage(teams, paging.safePage, paging.pageSize);
   function toggleSort(key: EntSort) {
     const next = nextSort(sortKey, sortDir, key);
@@ -1359,6 +1378,7 @@ export function OperationsTeamManagementPage() {
   }
   const sortAria = (key: EntSort) => sortKey === key ? (sortDir === "asc" ? "ascending" : "descending") : "none";
   return <div className="org-page org-operations-ledger-page page-fill">
+    <OrganizationEntryBack fallback="/organization/operations-teams" />
     <PageHead eyebrow="组织与区域 / 04" title="运营团队" exportCsv={{ onClick: exportRows, disabled: !teams.length }} description="理清各运营团队负责的区域、客户和成员。" action={teamReadOnly ? <span className="org-helper">档案只读,不能新建团队;本团队成员账号可管理</span> : <Button onClick={() => setEditor({ kind: "operations" })}><Plus size={16} /> 新建运营团队</Button>} />
     <OrgFetchState status={status} collections={["operationsTeams"]} />
     <CollectionFailed status={status} collection="operationsTeams" title="运营团队" />
@@ -1366,7 +1386,7 @@ export function OperationsTeamManagementPage() {
     <div className="org-maintenance-ledger-shell list-shell-fill">
       <div className="ops-toolbar"><SearchBox onChange={(value) => { setQuery(value); paging.resetPage(); }} placeholder="搜索团队名称、说明或负责范围" value={query} /><RegionSelect all data={data} onChange={(value) => { setRegionFilter(value); paging.resetPage(); }} value={regionFilter} />{(query || regionFilter) && <UiButton variant="ghost" size="sm" onClick={() => { setQuery(""); setRegionFilter(""); paging.resetPage(); }}>重置筛选</UiButton>}</div>
       <div ref={tableOverflow.ref} tabIndex={0} role="region" aria-label="运营团队台账,可横向滚动查看字段" className={`measured-table-scroll org-table-wrap org-team-table-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}><table className="org-table org-operations-ledger-table org-team-ledger"><OpsTableColumns widths={columnWidths} /><thead><tr><th className="sortable" aria-sort={sortAria("name")} onClick={() => toggleSort("name")}>团队 / 说明</th><th className="sortable" aria-sort={sortAria("region")} onClick={() => toggleSort("region")}>所属区域</th><th>分成规则</th><th>负责范围</th><th className="sortable" aria-sort={sortAria("coverage")} onClick={() => toggleSort("coverage")}>覆盖客户</th><th className="sortable" aria-sort={sortAria("members")} onClick={() => toggleSort("members")}>成员账号</th><th className="org-table-actions-heading">操作</th></tr></thead><tbody>{pageTeams.map((team) => {
-        return <tr key={team.id}><td><div className="org-operations-team-name"><strong className="table-cell-title" title={team.name}>{team.name}</strong>{team.hq && <OpsTag tone="brand">总部内置</OpsTag>}</div><small title={team.desc || "尚未填写团队说明"}>{team.desc || <span className="table-placeholder">尚未填写团队说明</span>}</small></td><td>{team.hq ? "总部 · 不限区域" : operationsRegionLabel(data, team.region)}</td><td className="org-maintenance-share"><strong>{shareText(team)}</strong><small>{team.shareMode}</small></td><td className="org-maintenance-scope-cell" title={scopeSummary(data, team.scope)}><TableValueText>{scopeSummary(data, team.scope)}</TableValueText></td><td className="org-directory-customer-count"><Count v={team.coverageCustomers} />{typeof team.coverageCustomers === "number" ? " 家" : null}</td><td className="org-directory-customer-count">{team.members.length || (team.memberCount ?? 0) > 0 ? <span className="org-member-count" title={team.membersPending || undefined}><span><Count v={team.memberCount} />{typeof team.memberCount === "number" ? " 个" : null}</span>{team.membersPending ? <span aria-label={team.membersPending} className="org-member-count-hint" role="img" title={team.membersPending}><Info aria-hidden="true" size={13} /></span> : null}</span> : <OrganizationAccountStatus status="未开通" />}</td><td className="org-table-actions-cell"><div className="org-table-actions is-icons"><Link className="org-maintenance-account-link" to={`/organization/operations-teams/${encodeURIComponent(team.id)}/accounts`}><UserRound size={15} />账号</Link>{!teamReadOnly && <OpsResponsiveActions expanded={expandedActions} items={[
+        return <tr key={team.id}><td><div className="org-operations-team-name"><strong className="table-cell-title" title={team.name}>{team.name}</strong>{team.hq && <OpsTag tone="brand">总部内置</OpsTag>}</div><small title={team.desc || "尚未填写团队说明"}>{team.desc || <span className="table-placeholder">尚未填写团队说明</span>}</small></td><td>{team.hq ? "总部 · 不限区域" : operationsRegionLabel(data, team.region)}</td><td className="org-maintenance-share"><strong>{shareText(team)}</strong><small>{team.shareMode}</small></td><td className="org-maintenance-scope-cell" title={scopeSummary(data, team.scope)}><TableValueText>{scopeSummary(data, team.scope)}</TableValueText></td><td className="org-directory-customer-count"><Count v={team.coverageCustomers} />{typeof team.coverageCustomers === "number" ? " 家" : null}</td><td className="org-directory-customer-count">{team.members.length || (team.memberCount ?? 0) > 0 ? <span className="org-member-count" title={team.membersPending || undefined}><span><Count v={team.memberCount} />{typeof team.memberCount === "number" ? " 个" : null}</span>{team.membersPending ? <span aria-label={team.membersPending} className="org-member-count-hint" role="img" title={team.membersPending}><Info aria-hidden="true" size={13} /></span> : null}</span> : <OrganizationAccountStatus status="未开通" />}</td><td className="org-table-actions-cell"><div className="org-table-actions is-icons"><Link className="org-maintenance-account-link" to={`/organization/operations-teams/${encodeURIComponent(team.id)}/accounts`} state={linkState}><UserRound size={15} />账号</Link>{!teamReadOnly && <OpsResponsiveActions expanded={expandedActions} items={[
           { label: "编辑团队", shortLabel: "编辑", icon: <PencilLine size={15} />, onSelect: () => setEditor({ kind: "operations", id: team.id }) },
           ...(!team.hq ? [{ label: "删除团队", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, onSelect: () => setDeleteId(team.id) }] : []),
         ]} />}</div></td></tr>;
@@ -1420,12 +1440,14 @@ function TeamAccountsSummary({ name, kind, icon, details, memberCount, coverage,
 
 export function OperationsTeamAccountsPage() {
   const { id } = useParams();
+  const location = useLocation();
+  const back = detailBack(location.state, "/organization/operations-teams", "返回运营团队");
   const data = useOrganizationData(["regions", "operationsTeams", "enterprises"]);
   const team = data.operationsTeams.find((item) => item.id === id);
-  if (!team) return <div className="org-page"><Link className="org-back-link" to="/organization/operations-teams"><ArrowLeft size={16} />返回运营团队</Link><Empty>团队不存在或已被删除</Empty></div>;
+  if (!team) return <div className="org-page"><Link className="org-back-link" to={back.to} state={back.state}><ArrowLeft size={16} />{back.label}</Link><Empty>团队不存在或已被删除</Empty></div>;
   const covered = scopeEnterpriseIndexes(data, team.scope);
   return <div className="org-page org-team-accounts-page">
-    <Link className="org-back-link" to="/organization/operations-teams"><ArrowLeft size={16} />返回运营团队</Link>
+    <Link className="org-back-link" to={back.to} state={back.state}><ArrowLeft size={16} />{back.label}</Link>
     <TeamAccountsSummary
       name={team.name}
       kind="OPERATIONS / ACCOUNTS"
@@ -1453,10 +1475,12 @@ export function MaintenanceTeamLedgerPage() {
   const remaining = Math.max(1520, tableOverflow.width) - ticketTypeWidth - 372 - actionWidth;
   const columnUnit = remaining / 78;
   const columnWidths = [columnUnit * 22, columnUnit * 22, ticketTypeWidth, columnUnit * 13, columnUnit * 21, 90, 90, 112, 80, actionWidth];
-  const [query, setQuery] = useState("");
+  const location = useLocation();
+  const savedView = location.state?.teamList as { query: string; mode?: string; sortKey: OpsSort | null; sortDir: SortDir; page: number; pageSize: number } | undefined;
+  const [query, setQuery] = useState(savedView?.query ?? "");
   const regionIds = useMemo(() => new Set(data.regions.map((item) => item.id)), [data.regions]);
   const [regionFilter, setRegionFilter, invalidRegion] = useRegionQueryFilter(regionIds);
-  const [modeFilter, setModeFilter] = useState("");
+  const [modeFilter, setModeFilter] = useState(savedView?.mode ?? "");
   const [editor, setEditor] = useState<Editor | null>(null);
   useEditorDeepLink("maintenance", (id) => data.maintenanceTeams.some((item) => item.id === id), editor, setEditor);
   const saveNotice = useSaveNotice();
@@ -1464,8 +1488,8 @@ export function MaintenanceTeamLedgerPage() {
   const status = useOrganizationStatus();
   const filtered = data.maintenanceTeams.filter((team) => (!regionFilter || descendants(data, regionFilter).includes(team.region)) && (!modeFilter || team.mode === modeFilter) && `${team.name} ${regionPath(data, team.region)} ${scopeSummary(data, team.scope)} ${team.mode} ${team.shareMode} ${team.lead} ${teamTicketTypes(team).map(typeLabel).join(" ")} ${team.members.map((member) => member.name).join(" ")}`.toLowerCase().includes(query.trim().toLowerCase()));
   type OpsSort = "name" | "region" | "coverage" | "open" | "members";
-  const [sortKey, setSortKey] = useState<OpsSort | null>("name");
-  const [sortDir, setSortDir] = useState<SortDir>("asc");
+  const [sortKey, setSortKey] = useState<OpsSort | null>(savedView ? savedView.sortKey : "name");
+  const [sortDir, setSortDir] = useState<SortDir>(savedView?.sortDir ?? "asc");
   const teams = useMemo(() => {
     const list = [...filtered];
     if (!sortKey) return list;
@@ -1478,7 +1502,10 @@ export function MaintenanceTeamLedgerPage() {
     });
     return list;
   }, [filtered, sortKey, sortDir, data]);
-  const paging = useLocalPage(teams.length);
+  const paging = useLocalPage(teams.length, savedView?.pageSize, savedView?.page);
+  const linkState = detailLinkState(location.pathname + location.search + location.hash, {
+    ...location.state, teamList: { query, mode: modeFilter, sortKey, sortDir, page: paging.safePage, pageSize: paging.pageSize },
+  });
   const pageTeams = slicePage(teams, paging.safePage, paging.pageSize);
   function toggleSort(key: OpsSort) {
     const next = nextSort(sortKey, sortDir, key);
@@ -1511,6 +1538,7 @@ export function MaintenanceTeamLedgerPage() {
     return () => observer.disconnect();
   }, [tableRef, data, query, regionFilter, modeFilter, paging.safePage]);
   return <div className="org-page org-maintenance-ledger-page page-fill">
+    <OrganizationEntryBack fallback="/organization/maintenance-teams" />
     <OrgFetchState status={status} collections={["maintenanceTeams"]} />
     <CollectionFailed status={status} collection="maintenanceTeams" title="运维团队" />
     {invalidRegion && <p className="org-form-error" role="status">区域参数无效({invalidRegion}),已回落为全部区域。</p>}
@@ -1518,7 +1546,7 @@ export function MaintenanceTeamLedgerPage() {
     <div className="org-maintenance-ledger-shell list-shell-fill">
       <div className="ops-toolbar"><SearchBox onChange={(value) => { setQuery(value); paging.resetPage(); }} placeholder="搜索团队名称、区域路径、说明或成员" value={query} /><RegionSelect all data={data} onChange={(value) => { setRegionFilter(value); paging.resetPage(); }} value={regionFilter} /><FilterSelect icon="assignment" aria-label="分派方式" onChange={(event) => { setModeFilter(event.target.value); paging.resetPage(); }} value={modeFilter}><option value="">全部分派方式</option><option value="手工">手工</option><option value="自动平均">自动平均</option></FilterSelect>{(query || regionFilter || modeFilter) && <UiButton variant="ghost" size="sm" onClick={() => { setQuery(""); setRegionFilter(""); setModeFilter(""); paging.resetPage(); }}>重置筛选</UiButton>}</div>
       <div ref={tableRef} tabIndex={0} role="region" aria-label="运维团队台账,可横向滚动查看字段" className={`measured-table-scroll org-table-wrap org-team-table-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}><table className="org-table org-maintenance-ledger-table org-team-ledger"><OpsTableColumns widths={columnWidths} /><thead><tr><th className="sortable" aria-sort={sortAria("name")} onClick={() => toggleSort("name")}>团队 / 分派</th><th className="sortable" aria-sort={sortAria("region")} onClick={() => toggleSort("region")}>所属区域</th><th className="org-maintenance-ticket-types"><span>可分配工单类型</span></th><th>分成规则</th><th>负责范围</th><th className="sortable" aria-sort={sortAria("coverage")} onClick={() => toggleSort("coverage")}>覆盖客户</th><th className="sortable" aria-sort={sortAria("open")} onClick={() => toggleSort("open")}>未完成</th><th>超期未完成</th><th className="sortable" aria-sort={sortAria("members")} onClick={() => toggleSort("members")}>成员账号</th><th className="org-table-actions-heading">操作</th></tr></thead><tbody>{pageTeams.map((team) => {
-        return <tr key={team.id}><td><strong className="table-cell-title" title={team.name}>{team.name}</strong><small>{team.mode}分派</small></td><td title={regionPath(data, team.region)}>{regionPath(data, team.region)}</td><td className="org-maintenance-ticket-types"><TeamTicketTypes types={teamTicketTypes(team)} /></td><td className="org-maintenance-share"><strong>{shareText(team)}</strong><small>{team.shareMode}</small></td><td className="org-maintenance-scope-cell" title={scopeSummary(data, team.scope)}><TableValueText>{scopeSummary(data, team.scope)}</TableValueText></td><td className="org-number"><Count v={team.coverageCustomers} /></td><td className="org-number"><Count v={team.openTickets} /></td><td>{team.overdueOpenTickets === undefined || team.overdueOpenTickets === null ? <Tri tone="missing" text={FIELD_UNAVAILABLE} title={team.loadPending} /> : team.overdueOpenTickets > 0 ? <OpsStatus tone="danger">超期 {team.overdueOpenTickets}</OpsStatus> : <OpsStatus tone="brand">正常</OpsStatus>}</td><td><strong><Count v={team.memberCount} /></strong><small>{team.membersPending ?? `成员 ${team.members.length} 人`}</small></td><td className="org-table-actions-cell"><div className="org-table-actions is-icons"><Link className="org-maintenance-account-link" to={`/organization/maintenance-teams/${encodeURIComponent(team.id)}/accounts`}><UserRound size={15} />账号</Link><OpsResponsiveActions expanded={expandedActions} items={[
+        return <tr key={team.id}><td><strong className="table-cell-title" title={team.name}>{team.name}</strong><small>{team.mode}分派</small></td><td title={regionPath(data, team.region)}>{regionPath(data, team.region)}</td><td className="org-maintenance-ticket-types"><TeamTicketTypes types={teamTicketTypes(team)} /></td><td className="org-maintenance-share"><strong>{shareText(team)}</strong><small>{team.shareMode}</small></td><td className="org-maintenance-scope-cell" title={scopeSummary(data, team.scope)}><TableValueText>{scopeSummary(data, team.scope)}</TableValueText></td><td className="org-number"><Count v={team.coverageCustomers} /></td><td className="org-number"><Count v={team.openTickets} /></td><td>{team.overdueOpenTickets === undefined || team.overdueOpenTickets === null ? <Tri tone="missing" text={FIELD_UNAVAILABLE} title={team.loadPending} /> : team.overdueOpenTickets > 0 ? <OpsStatus tone="danger">超期 {team.overdueOpenTickets}</OpsStatus> : <OpsStatus tone="brand">正常</OpsStatus>}</td><td><strong><Count v={team.memberCount} /></strong><small>{team.membersPending ?? `成员 ${team.members.length} 人`}</small></td><td className="org-table-actions-cell"><div className="org-table-actions is-icons"><Link className="org-maintenance-account-link" to={`/organization/maintenance-teams/${encodeURIComponent(team.id)}/accounts`} state={linkState}><UserRound size={15} />账号</Link><OpsResponsiveActions expanded={expandedActions} items={[
           // 负责范围已并入「编辑团队」弹窗(2026-11-16 业主指示),⛔ 再单列一条动作。
           { label: "编辑团队", shortLabel: "编辑", icon: <PencilLine size={15} />, onSelect: () => setEditor({ kind: "maintenance", id: team.id }) },
           { label: "删除团队", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, onSelect: () => setDeleteId(team.id) },
@@ -1533,12 +1561,14 @@ export function MaintenanceTeamLedgerPage() {
 
 export function MaintenanceTeamAccountsPage() {
   const { id } = useParams();
+  const location = useLocation();
+  const back = detailBack(location.state, "/organization/maintenance-teams", "返回运维团队");
   const data = useOrganizationData(["regions", "maintenanceTeams", "enterprises"]);
   const team = data.maintenanceTeams.find((item) => item.id === id);
-  if (!team) return <div className="org-page"><Link className="org-back-link" to="/organization/maintenance-teams"><ArrowLeft size={16} />返回运维团队</Link><Empty>团队不存在或已被删除</Empty></div>;
+  if (!team) return <div className="org-page"><Link className="org-back-link" to={back.to} state={back.state}><ArrowLeft size={16} />{back.label}</Link><Empty>团队不存在或已被删除</Empty></div>;
   const covered = scopeEnterpriseIndexes(data, team.scope).filter((index) => enterpriseTeamIds(data.enterprises[index]).includes(team.id));
   return <div className="org-page org-team-accounts-page">
-    <Link className="org-back-link" to="/organization/maintenance-teams"><ArrowLeft size={16} />返回运维团队</Link>
+    <Link className="org-back-link" to={back.to} state={back.state}><ArrowLeft size={16} />{back.label}</Link>
     <TeamAccountsSummary
       name={team.name}
       kind="MAINTENANCE / ACCOUNTS"

+ 6 - 1
web-scaffold/src/pages/PackageManagementPage.tsx

@@ -2,7 +2,9 @@ import { FilterSelect } from "../components/ui/filter-select";
 import { PageIntro } from "../components/PageIntro";
 import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, Fragment, type ReactNode } from "react";
 import { createPortal } from "react-dom";
-import { CircleHelp, Globe2, Layers3, LockKeyhole, PencilLine, Plus, Search, SlidersHorizontal, Trash2, X } from "lucide-react";
+import { ArrowLeft, CircleHelp, Globe2, Layers3, LockKeyhole, PencilLine, Plus, Search, SlidersHorizontal, Trash2, X } from "lucide-react";
+import { Link, useLocation } from "react-router";
+import { detailBack } from "../lib/detail-navigation";
 import { Button } from "../components/ui/button";
 import { Input } from "../components/ui/input";
 import { TableValueText, Tri } from "../components/triState";
@@ -556,6 +558,8 @@ function BandwidthTierPanel({ writable, tiers, onNotice }: { writable: boolean;
 }
 
 export function PackageManagementPage() {
+  const { state } = useLocation();
+  const back = detailBack(state, "/packages", "返回套餐配置");
   /** 03 章 §3.4 权限三档:固定档写入口=总运营专属;运营主账号只配客户专属档;其余角色只读且不出入口。
    *  `opsMain`/`opsSub` 在 session 均映成 `regAdmin`,差异只由 `primary` 承载(D-PKG-16)⇒
    *  自定义档写入口必须与 `canWriteExits` 同式,⛔ 把子账号放成可点的写按钮。 */
@@ -736,6 +740,7 @@ export function PackageManagementPage() {
         ? "没有符合筛选条件的套餐档,可重置筛选后再看。"
         : tab === "custom" ? "目录里还没有自定义套餐档。" : "目录里还没有固定套餐档。";
   return <section className="ops-page ops-page--packages package-catalog">
+    {back.to !== "/packages" && <Link className="ops-back-link" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
     <header className="catalog-page-head">
       <h1>套餐配置</h1>
       <PageIntro>管理签约可选的套餐、订阅价格和交付配置。</PageIntro>

+ 60 - 39
web-scaffold/src/pages/PartyViewPages.tsx

@@ -21,7 +21,8 @@
 import { useCallback, useEffect, useRef, useState } from "react";
 import { PageIntro } from "../components/PageIntro";
 import { Download, Search, X } from "lucide-react";
-import { Link, useParams } from "react-router";
+import { Link, useLocation, useParams } from "react-router";
+import { detailBack, detailLinkState } from "../lib/detail-navigation";
 import { ServerListPager } from "../components/ListPager";
 import { Button } from "../components/ui/button";
 import { Input } from "../components/ui/input";
@@ -177,12 +178,23 @@ function FullPageState({ text, retry }: { text: string; retry?: () => void }) {
 
 /* ── V-P1/V-P1b 合并页(六段一次请求,⛔ 分段懒加载) ────────────────────── */
 
+type PartyListView = { page: number; month?: string; keyword?: string; batchKw?: string; customerKw?: string };
+
+function usePartyListReturn() {
+  const location = useLocation();
+  const saved = location.state?.partyList as PartyListView | undefined;
+  const stateFor = (partyList: PartyListView) => detailLinkState(location.pathname + location.search + location.hash, { ...location.state, partyList });
+  return { location, saved, stateFor };
+}
+
 function PartyReconMergedPage({ kind }: { kind: "partner" | "team" }) {
   const title = kind === "partner" ? "本运营区域对账" : "本方对账";
   const prefix = kindPrefix(kind);
-  const [month, setMonth] = useState(lastClosedMonth());
-  const [keyword, setKeyword] = useState("");
-  const [page, setPage] = useState(1);
+  const { saved, stateFor } = usePartyListReturn();
+  const [month, setMonth] = useState(saved?.month ?? lastClosedMonth());
+  const [keyword, setKeyword] = useState(saved?.keyword ?? "");
+  const [page, setPage] = useState(saved?.page ?? 1);
+  const linkState = stateFor({ month, keyword, page });
   const [notice, setNotice] = useState("");
   const detailRef = useRef<HTMLDivElement>(null);
   const exportBatch = useExportBatch(setNotice);
@@ -395,7 +407,7 @@ function PartyReconMergedPage({ kind }: { kind: "partner" | "team" }) {
                         <td>
                           {/* C76:当前归属≠我 ⇒ 纯文本无链接+「归属已变更」;teamLead 无客户详情页 ⇒ 恒纯文本。 */}
                           {kind === "partner" && row.customer_visible ? (
-                            <Link className="workspace-link" to={`${prefix}/customer/${encodeURIComponent(row.customer_id)}`}>{row.customer_name}</Link>
+                            <Link className="workspace-link" to={`${prefix}/customer/${encodeURIComponent(row.customer_id)}`} state={linkState}>{row.customer_name}</Link>
                           ) : (
                             <span>{row.customer_name}{!row.customer_visible && <OpsTag tone="neutral">{OWNERSHIP_CHANGED}</OpsTag>}</span>
                           )}
@@ -405,7 +417,7 @@ function PartyReconMergedPage({ kind }: { kind: "partner" | "team" }) {
                         <td><strong className="table-number">{moneyFromCents(row.receivable_cents)}</strong></td>
                         {/* 批次详情宿主路由未在 14.1 路由表声明(仅 14.6 返回链路提及)⇒ 纯文本,缺口已登记。 */}
                         <td className="ops-mono">{row.batch_no}</td>
-                        <td><Link className="workspace-link" to={`${prefix}/bill-detail/${encodeURIComponent(row.bill_detail_id)}`}>查看详情</Link></td>
+                        <td><Link className="workspace-link" to={`${prefix}/bill-detail/${encodeURIComponent(row.bill_detail_id)}`} state={linkState}>查看详情</Link></td>
                       </tr>
                     ))
                   )}
@@ -442,9 +454,11 @@ export function TeamReconPage() {
 /* ── V-P5 运营商「本方对账清单」(⚠️ 独立组件,⛔ 与 V-P1 合并靠 props 抹平,A51) ── */
 
 export function OperatorReconPage() {
-  const [month, setMonth] = useState(lastClosedMonth());
-  const [keyword, setKeyword] = useState("");
-  const [page, setPage] = useState(1);
+  const { saved, stateFor } = usePartyListReturn();
+  const [month, setMonth] = useState(saved?.month ?? lastClosedMonth());
+  const [keyword, setKeyword] = useState(saved?.keyword ?? "");
+  const [page, setPage] = useState(saved?.page ?? 1);
+  const linkState = stateFor({ month, keyword, page });
   const [notice, setNotice] = useState("");
   const exportBatch = useExportBatch(setNotice);
 
@@ -549,7 +563,7 @@ export function OperatorReconPage() {
                             <Download size={13} /> 导出本批账单明细
                           </button>
                         )}{" "}
-                        <Link className="workspace-link" to={`/bos/ov/bill-detail?batch=${encodeURIComponent(row.batch_no)}`}>查看明细</Link>
+                        <Link className="workspace-link" to={`/bos/ov/bill-detail?batch=${encodeURIComponent(row.batch_no)}`} state={linkState}>查看明细</Link>
                       </td>
                     </tr>
                   ))
@@ -574,10 +588,13 @@ export function OperatorReconPage() {
 /* ── V-P6 运营商「账单明细」(⛔ 导出按钮——导出单位是批次;⛔「涉及分成方」卡) ────── */
 
 export function OperatorBillDetailPage() {
-  const [month, setMonth] = useState(lastClosedMonth());
-  const [batchKw, setBatchKw] = useState("");
-  const [customerKw, setCustomerKw] = useState("");
-  const [page, setPage] = useState(1);
+  const { location, saved, stateFor } = usePartyListReturn();
+  const [month, setMonth] = useState(saved?.month ?? lastClosedMonth());
+  const [batchKw, setBatchKw] = useState(saved?.batchKw ?? new URLSearchParams(location.search).get("batch") ?? "");
+  const [customerKw, setCustomerKw] = useState(saved?.customerKw ?? "");
+  const [page, setPage] = useState(saved?.page ?? 1);
+  const linkState = stateFor({ month, batchKw, customerKw, page });
+  const back = detailBack(location.state, "/bos/ov/bill-detail", "返回账单明细");
 
   const periodsFetch = useViewFetch(() => reconGetPeriods(), []);
   const periods = periodsFetch.data?.periods ?? null;
@@ -595,15 +612,9 @@ export function OperatorBillDetailPage() {
     if (!periods?.length || !month) return;
     if (!periods.includes(month)) setMonth(periods[0]);
   }, [periods, month]);
-  // 表 1「查看明细」跳入:`?batch=` 预选对账单号筛选。
-  useEffect(() => {
-    const initial = new URLSearchParams(window.location.search).get("batch");
-    if (initial) setBatchKw(initial);
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, []);
-
   return (
     <section className="ops-page reconcile-index page-fill">
+      {back.to !== "/bos/ov/bill-detail" && <Link className="ops-back-link self-start" to={back.to} state={back.state}>{back.label}</Link>}
       <header className="reconcile-page-heading">
         <div>
           <p className="ops-eyebrow"><span /> READONLY / 只读视图</p>
@@ -670,7 +681,7 @@ export function OperatorBillDetailPage() {
                       <td className="table-number">{moneyFromCents(row.share_base_cents)}</td>
                       <td><strong className="table-number">{moneyFromCents(row.share_amount_cents)}</strong></td>
                       <td className="ops-mono">{row.batch_no}</td>
-                      <td><Link className="workspace-link" to={`/bos/ov/bill-detail/${encodeURIComponent(row.bill_detail_id)}`}>查看详情</Link></td>
+                      <td><Link className="workspace-link" to={`/bos/ov/bill-detail/${encodeURIComponent(row.bill_detail_id)}`} state={linkState}>查看详情</Link></td>
                     </tr>
                   ))
                 )}
@@ -695,8 +706,10 @@ export function OperatorBillDetailPage() {
 
 export function PartyCustomerListPage({ kind }: { kind: "partner" | "operator" }) {
   const prefix = kindPrefix(kind);
-  const [keyword, setKeyword] = useState("");
-  const [page, setPage] = useState(1);
+  const { saved, stateFor } = usePartyListReturn();
+  const [keyword, setKeyword] = useState(saved?.keyword ?? "");
+  const [page, setPage] = useState(saved?.page ?? 1);
+  const linkState = stateFor({ keyword, page });
   // ⛔ 前端下传 partner_id/operator_id(总则§16.1:范围在服务端谓词层展开)。
   const fetchState = useViewFetch(
     // 分页器是 1 基、后端 `page` 是 0 基(openapi:页码 0 基索引)⇒ 只在请求边界换算。
@@ -754,7 +767,7 @@ export function PartyCustomerListPage({ kind }: { kind: "partner" | "operator" }
                     <td>{row.region_path === undefined ? <Tri tone="fail" text={WORD_NOT_PROVIDED} title="客户列表口未下发 region_path" /> : row.region_path ? row.region_path : <Tri tone="missing" text="未挂载区域" />}</td>
                     {/* 生效套餐摘要:后端 `plan_names`(在用订阅的套餐名,status ∈ pending/active)。 */}
                     <td>{row.plan_names === undefined ? <Tri tone="fail" text={WORD_NOT_PROVIDED} title="客户列表口未下发 plan_names" /> : row.plan_names.length ? row.plan_names.join("、") : <Tri tone="missing" text="无在用订阅" />}</td>
-                    <td><Link className="workspace-link" to={`${prefix}/customer/${encodeURIComponent(row.customer_id)}`}>查看</Link></td>
+                    <td><Link className="workspace-link" to={`${prefix}/customer/${encodeURIComponent(row.customer_id)}`} state={linkState}>查看</Link></td>
                   </tr>
                 ))}
                 {!rows.length && <OpsTableEmpty colSpan={6}>{VIEW_LIST_EMPTY}</OpsTableEmpty>}
@@ -790,8 +803,10 @@ function contractNameOf(row: ContractRow) {
 
 export function PartyContractListPage({ kind }: { kind: "partner" | "operator" }) {
   const prefix = kindPrefix(kind);
-  const [keyword, setKeyword] = useState("");
-  const [page, setPage] = useState(1);
+  const { saved, stateFor } = usePartyListReturn();
+  const [keyword, setKeyword] = useState(saved?.keyword ?? "");
+  const [page, setPage] = useState(saved?.page ?? 1);
+  const linkState = stateFor({ keyword, page });
   // 行集=本方客户集合传导(SQL-2 第二段);⛔ 前端下传范围入参。
   const fetchState = useViewFetch(
     // 分页器是 1 基、后端 `page` 是 0 基(openapi:页码 0 基索引)⇒ 只在请求边界换算。
@@ -845,7 +860,7 @@ export function PartyContractListPage({ kind }: { kind: "partner" | "operator" }
                     <td>{row.customer_name ?? <Tri tone="missing" text={WORD_NOT_PROVIDED} />}</td>
                     <td>{row.start_date ?? <span className="table-placeholder">—</span>} ~ {row.end_date ?? <span className="table-placeholder">—</span>}</td>
                     <td><OpsTag tone="neutral">{row.status}</OpsTag></td>
-                    <td><Link className="workspace-link" to={`${prefix}/contract/${encodeURIComponent(row.contract_id)}`}>查看</Link></td>
+                    <td><Link className="workspace-link" to={`${prefix}/contract/${encodeURIComponent(row.contract_id)}`} state={linkState}>查看</Link></td>
                   </tr>
                 ))}
                 {!rows.length && <OpsTableEmpty colSpan={6}>{VIEW_LIST_EMPTY}</OpsTableEmpty>}
@@ -862,22 +877,22 @@ export function PartyContractListPage({ kind }: { kind: "partner" | "operator" }
 /* ── V-D1 详情宿主层(返回链路固定文案+显式路由,⛔ history.back()) ────────── */
 
 /** 11104 ⇒ 空态卡片「数据不存在或归属已变更」+「刷新列表」(⚠️⛔「无权限」字样)。 */
-function DetailNotFound({ backTo, backText }: { backTo: string; backText: string }) {
+function DetailNotFound({ back }: { back: ReturnType<typeof detailBack> }) {
   return (
     <div className="ops-detail-callout" role="alert" style={{ textAlign: "center", padding: "48px 24px" }}>
       <strong>{VIEW_NOT_FOUND}</strong>
-      <p><Link className="workspace-link" to={backTo}>刷新列表({backText.replace("← ", "")})</Link></p>
+      <p><Link className="workspace-link" to={back.to} state={back.state}>刷新列表({back.label.replace("← ", "")})</Link></p>
     </div>
   );
 }
 
-function DetailHeader({ title, backTo, backText }: { title: string; backTo: string; backText: string }) {
+function DetailHeader({ title, back }: { title: string; back: ReturnType<typeof detailBack> }) {
   return (
     <header className="reconcile-page-heading">
       <div>
         <p className="ops-eyebrow"><span /> READONLY / 只读视图</p>
         <h1>{title}</h1>
-        <p><Link className="workspace-link" to={backTo}>{backText}</Link></p>
+        <p><Link className="workspace-link" to={back.to} state={back.state}>← {back.label.replace("← ", "")}</Link></p>
       </div>
     </header>
   );
@@ -887,12 +902,14 @@ function DetailHeader({ title, backTo, backText }: { title: string; backTo: stri
 export function PartyCustomerDetailPage({ kind }: { kind: "partner" | "operator" }) {
   const prefix = kindPrefix(kind);
   const { id = "" } = useParams();
+  const location = useLocation();
+  const back = detailBack(location.state, `${prefix}/customer`, BACK_TO_CUSTOMER_LIST);
   const fetchState = useViewFetch(() => customerGet({ customer_id: id }), [id]);
   const { data, fail } = fetchState;
   return (
     <section className="ops-page reconcile-index">
-      <DetailHeader title="客户详情" backTo={`${prefix}/customer`} backText={BACK_TO_CUSTOMER_LIST} />
-      {fail?.kind === "notfound" && <DetailNotFound backTo={`${prefix}/customer`} backText={BACK_TO_CUSTOMER_LIST} />}
+      <DetailHeader title="客户详情" back={back} />
+      {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} />}
       {data && (
         <div className="ops-table-wrap">
@@ -917,12 +934,14 @@ export function PartyCustomerDetailPage({ kind }: { kind: "partner" | "operator"
 export function PartyContractDetailPage({ kind }: { kind: "partner" | "operator" }) {
   const prefix = kindPrefix(kind);
   const { id = "" } = useParams();
+  const location = useLocation();
+  const back = detailBack(location.state, `${prefix}/contract`, BACK_TO_CONTRACT_LIST);
   const fetchState = useViewFetch(() => contractGet({ contract_id: id }), [id]);
   const { data, fail } = fetchState;
   return (
     <section className="ops-page reconcile-index">
-      <DetailHeader title="合同详情" backTo={`${prefix}/contract`} backText={BACK_TO_CONTRACT_LIST} />
-      {fail?.kind === "notfound" && <DetailNotFound backTo={`${prefix}/contract`} backText={BACK_TO_CONTRACT_LIST} />}
+      <DetailHeader title="合同详情" back={back} />
+      {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} />}
       {data && (
         <div className="ops-table-wrap">
@@ -950,18 +969,20 @@ export function PartyContractDetailPage({ kind }: { kind: "partner" | "operator"
  */
 export function PartyBillDetailPage({ kind }: { kind: ViewKind }) {
   const { id = "" } = useParams();
-  const back =
+  const location = useLocation();
+  const fallback =
     kind === "partner"
       ? { to: "/bos/pv/recon", text: BACK_TO_REGION_RECON }
       : kind === "team"
         ? { to: "/bos/tv/recon", text: BACK_TO_SELF_RECON }
         : { to: "/bos/ov/bill-detail", text: BACK_TO_BILL_DETAIL_LIST };
+  const back = detailBack(location.state, fallback.to, fallback.text);
   const fetchState = useViewFetch<BillDetailResult>(() => billGetDetail(id), [id]);
   const { data, fail } = fetchState;
   return (
     <section className="ops-page reconcile-index">
-      <DetailHeader title="账单明细详情" backTo={back.to} backText={back.text} />
-      {fail?.kind === "notfound" && <DetailNotFound backTo={back.to} backText={back.text} />}
+      <DetailHeader title="账单明细详情" back={back} />
+      {fail?.kind === "notfound" && <DetailNotFound back={back} />}
       {fail && fail.kind !== "notfound" && (
         <FullPageState
           text={fail.kind === "wiring" ? VIEW_WIRING_NOTE : fail.kind === "snapshot" ? VIEW_SNAPSHOT_NOT_READY : fail.kind === "forbidden" ? VIEW_ROLE_FORBIDDEN : fail.kind === "fail" ? fail.message : VIEW_LIST_EMPTY}

+ 19 - 12
web-scaffold/src/pages/SettlementPages.tsx

@@ -3,7 +3,8 @@ import { PageIntro } from "../components/PageIntro";
 import { FilterIcon, FilterSelect } from "../components/ui/filter-select";
 import { TreeSelect } from "../components/ui/tree-select";
 import { useEffect, useMemo, useState } from "react";
-import { useNavigate } from "react-router";
+import { useLocation, useNavigate } from "react-router";
+import { detailLinkState, type DetailLinkState } from "../lib/detail-navigation";
 import { ArrowRight, CalendarDays, Check, Info, RotateCcw, Search, X } from "lucide-react";
 import { Button } from "../components/ui/button";
 import { Input } from "../components/ui/input";
@@ -34,7 +35,7 @@ import {
 import { useBusinessView } from "../lib/use-business-view";
 import { onboardingRegions } from "../lib/customer-onboarding";
 import { ListPager } from "../components/ListPager";
-import { slicePage, useLocalPage } from "../lib/list-paging";
+import { LIST_PAGE_SIZE, slicePage, useLocalPage } from "../lib/list-paging";
 import { OpsNotice, OpsStatus, OpsTag, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit";
 import "../styles/operations.css";
 import "../styles/reconciliation-settings.css";
@@ -67,6 +68,8 @@ const ARCHIVE_EDIT_PATH: Record<CurrentSharePartyType, string> = {
   运维团队: "/organization/maintenance-teams",
 };
 export function ShareRulePage() {
+  const location = useLocation();
+  const savedView = location.state?.shareView as { region: string; kind: "全部" | CurrentSharePartyType; state: string; search: string; page: number; detailKey: string | null } | undefined;
   const tableOverflow = useHorizontalOverflow();
   /**
    * 列宽=按「页宽 1500 下不出现横向滚动条」反推的定值(比例由 OpsTableColumns 归一):
@@ -95,11 +98,12 @@ export function ShareRulePage() {
   /** 契约 14.1.3:列表页一次调用(⛔ 逐行请求);[位] 未接线 ⇒ fail="wiring"(两列「后端未下发」)。 */
   const summaryRefs = useMemo(() => rows.map((row) => ({ holder_type: PARTY_HOLDER_TYPE[row.type], holder_id: row.id })), [rows]);
   const summary = useShareParamSummary(summaryRefs);
-  const [region, setRegion] = useState("");
-  const [kind, setKind] = useState<"全部" | CurrentSharePartyType>("全部");
-  const [state, setState] = useState("全部状态");
-  const [search, setSearch] = useState("");
-  const [detail, setDetail] = useState<SharePartyRow | null>(null);
+  const [region, setRegion] = useState(savedView?.region ?? "");
+  const [kind, setKind] = useState<"全部" | CurrentSharePartyType>(savedView?.kind ?? "全部");
+  const [state, setState] = useState(savedView?.state ?? "全部状态");
+  const [search, setSearch] = useState(savedView?.search ?? "");
+  const [detailKey, setDetailKey] = useState<string | null>(savedView?.detailKey ?? null);
+  const detail = rows.find((row) => shareSummaryKey(PARTY_HOLDER_TYPE[row.type], row.id) === detailKey);
   const regionTree = regionTreeNodes(organization.regions, [...allowedRegions]);
   const regionScope = region ? new Set(descendants(organization, region)) : null;
   /**
@@ -118,7 +122,10 @@ export function ShareRulePage() {
     (state === "全部状态" || (rowConfigured(row) ? "已配分成" : "未配分成") === state) &&
     `${row.displayName} ${row.type} ${row.note} ${row.regionLabel}`.toLowerCase().includes(search.trim().toLowerCase()),
   );
-  const paging = useLocalPage(filtered.length);
+  const paging = useLocalPage(filtered.length, LIST_PAGE_SIZE, savedView?.page);
+  const linkState = detailLinkState(location.pathname + location.search + location.hash, {
+    ...location.state, shareView: { region, kind, state, search, page: paging.safePage, detailKey },
+  });
   const pageRows = slicePage(filtered, paging.safePage);
   const hasFilter = region !== "" || kind !== "全部" || state !== "全部状态" || search !== "";
   function reset() { setRegion(""); setKind("全部"); setState("全部状态"); setSearch(""); paging.resetPage(); }
@@ -162,11 +169,11 @@ export function ShareRulePage() {
           <td title={termsTitle(row)}>{termsCell(row)}</td>
           <td>{rowConfigured(row) ? <OpsStatus tone="success">已配分成</OpsStatus> : <small className="table-placeholder">未配分成</small>}</td>
           <td><span className="ops-money">{row.customerCount}</span></td>
-          <td><button type="button" className="ops-table-action" onClick={() => setDetail(row)} title="契约 14.2:弹窗出四卡+取值摘要(只读),配置分成请点弹窗里的「去档案里配置分成」">分成金额 <ArrowRight size={14} /></button></td>
+          <td><button type="button" className="ops-table-action" onClick={() => setDetailKey(shareSummaryKey(PARTY_HOLDER_TYPE[row.type], row.id))} title="契约 14.2:弹窗出四卡+取值摘要(只读),配置分成请点弹窗里的「去档案里配置分成」">分成金额 <ArrowRight size={14} /></button></td>
         </tr>)}{!filtered.length && <OpsTableEmpty colSpan={8}>{rows.length ? "没有符合筛选条件的分成方,可重置四组筛选" : "第 1 册档案里还没有运营商/合伙人/运维团队(分成方行源为空)"}</OpsTableEmpty>}</tbody></table></div>
       <ListPager total={filtered.length} page={paging.safePage} pageSize={paging.pageSize} onPageChange={paging.setPage} unit="条" />
     </div>
-    {detail && <ShareAmountDialog row={detail} summary={summary} canConfigure={canConfigureShare(identity?.role, detail.type)} onClose={() => setDetail(null)} />}
+    {detail && <ShareAmountDialog row={detail} linkState={linkState} summary={summary} canConfigure={canConfigureShare(identity?.role, detail.type)} onClose={() => setDetailKey(null)} />}
   </section>;
 }
 
@@ -190,7 +197,7 @@ function canConfigureShare(role: string | undefined, type: CurrentSharePartyType
  *    册 8 接口清单(06)无本场景读口,⛔ 造请求到不存在的接口、⛔ 读演示台账;
  *    故不再渲染占位行「后端未下发」、也不再留表格下方的口径说明行,弹窗只出四卡+取值摘要。
  */
-function ShareAmountDialog({ row, summary, canConfigure, onClose }: { row: SharePartyRow; summary: ShareSummaryState; canConfigure: boolean; onClose: () => void }) {
+function ShareAmountDialog({ row, summary, canConfigure, linkState, onClose }: { row: SharePartyRow; summary: ShareSummaryState; canConfigure: boolean; linkState: DetailLinkState; onClose: () => void }) {
   const navigate = useNavigate();
   useEffect(() => {
     const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") onClose(); };
@@ -252,7 +259,7 @@ function ShareAmountDialog({ row, summary, canConfigure, onClose }: { row: Share
     <footer>
       <Button variant="outline" onClick={onClose}>关闭</Button>
       {canConfigure
-        ? <Button onClick={() => { onClose(); navigate(`${ARCHIVE_EDIT_PATH[row.type]}?edit=${encodeURIComponent(row.id)}`); }}>去档案里配置分成</Button>
+        ? <Button onClick={() => { onClose(); navigate(`${ARCHIVE_EDIT_PATH[row.type]}?edit=${encodeURIComponent(row.id)}`, { state: linkState }); }}>去档案里配置分成</Button>
         : null}
     </footer>
   </div></div>;

+ 29 - 41
web-scaffold/src/pages/SettlementRecordPages.tsx

@@ -26,6 +26,7 @@ import type { StatusTone } from "../domain/statuses";
 import { WORD_FETCH_FAILED } from "../lib/api/lockedCopy";
 import { settleTextFromSnapshot } from "../lib/settle-text";
 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,
@@ -33,10 +34,7 @@ import {
 import {
   ACTION_FLAG_PENDING_NOTE,
   ALL_PERIODS_LABEL,
-  BACK_TO_BILL_DETAIL,
   BACK_TO_BILL_LIST,
-  BACK_TO_CORRECTIONS,
-  BACK_TO_RECON_DETAIL,
   BACK_TO_RECON_LIST,
   BACKEND_NOT_WIRED,
   BASE_FLOOR_NOTE,
@@ -111,6 +109,7 @@ const batchPath = (holderId: string, batchNo: string) =>
 
 /** URL 搜索参数筛选(返回列表时保留条件;⛔ 路由级收敛另行处理)。 */
 function useListFilters() {
+  const { state } = useLocation();
   const [params, setParams] = useSearchParams();
   const get = (key: string) => params.get(key) ?? "";
   const set = (key: string, value: string, resetPage = false) =>
@@ -120,8 +119,8 @@ function useListFilters() {
       if (value) next.set(key, value);
       else next.delete(key);
       return next;
-    }, { replace: true });
-  const reset = () => setParams({}, { replace: true });
+    }, { replace: true, state });
+  const reset = () => setParams({}, { replace: true, state });
   return { get, set, reset };
 }
 
@@ -135,7 +134,7 @@ function FailDot({ reason }: { reason: string | null }) {
 
 function RerunDialog({ onClose }: { onClose: () => void }) {
   const navigate = useNavigate();
-  const location = useLocation();
+  const returnState = useDetailLinkState();
   const typeId = useId();
   const holderInputId = useId();
   const [maxMonth] = useState(lastClosedMonth);
@@ -189,7 +188,7 @@ function RerunDialog({ onClose }: { onClose: () => void }) {
       .then((res) => {
         onClose();
         navigate(batchPath(holderId, res.batch_no), {
-          state: { from: location.pathname, listSearch: location.search },
+          state: returnState,
         });
       })
       .catch((e: unknown) => {
@@ -272,7 +271,8 @@ const statementTableWidth = statementColumns.reduce((sum, column) => sum + colum
 
 export function SettlementStatementListPage() {
   const identity = useDemoIdentity();
-  const location = useLocation();
+  const listState = useDetailLinkState();
+  const back = detailBack(listState.previousState, "/settlement-batches", BACK_TO_RECON_LIST);
   const filters = useListFilters();
   const tableOverflow = useHorizontalOverflow();
   const progressId = useId();
@@ -345,7 +345,6 @@ export function SettlementStatementListPage() {
     tableOverflow.canScrollLeft && "can-scroll-left",
     tableOverflow.canScrollRight && "can-scroll-right",
   ].filter(Boolean).join(" ");
-  const listState = { from: "/settlement-batches", listSearch: location.search };
 
   async function exportAll() {
     if (exporting || list.loading) return;
@@ -367,6 +366,7 @@ export function SettlementStatementListPage() {
 
   return (
     <section className="ops-page reconcile-index page-fill page-fill-window">
+      {back.to !== "/settlement-batches" && <Link className="ops-back-link self-start" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
       <header className="ops-heading statement-heading">
         <div>
           <h1>对账清单</h1>
@@ -553,16 +553,9 @@ export function SettlementStatementRecordPage() {
   const identity = useDemoIdentity();
   const navigate = useNavigate();
   const location = useLocation();
+  const outgoingState = useDetailLinkState();
   const { no } = useParams();
-  const state = (location.state ?? {}) as { from?: string; listSearch?: string };
-  // 返回恒回进来那一页(总则§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${state.listSearch ?? ""}`, label: BACK_TO_BILL_LIST }
-        : { to: `/settlement-batches${state.listSearch ?? ""}`, label: BACK_TO_RECON_LIST };
+  const back = detailBack(location.state, "/settlement-batches", BACK_TO_RECON_LIST);
 
   const detail = useReconDetail(no ?? null);
   const d = detail.data;
@@ -582,7 +575,7 @@ export function SettlementStatementRecordPage() {
       .then((res) => {
         setConfirmRerun(false);
         // 补跑成功 ⇒ 原批次作废、生成新批;直接落到新批详情(来路保留)。
-        navigate(batchPath(d.holder_id, res.batch_no), { state: location.state, replace: true });
+        navigate(batchPath(d.holder_id, res.batch_no), { state: outgoingState });
       })
       .catch((e: unknown) => {
         // 四道闸(60502→60503→60504→60506)/KLT-S407:文案直读后端 message。
@@ -600,7 +593,7 @@ export function SettlementStatementRecordPage() {
 
   return (
     <article className="ops-page reconcile-record">
-      <Link className="ops-back-link" to={back.to}><ArrowLeft size={16} />{back.label}</Link>
+      <Link className="ops-back-link" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label.replace(/^←\s*/, "")}</Link>
 
       {wiring && <p className="ops-import-note" role="status">{RECON_WIRING_NOTE}</p>}
       {detail.fail && !wiring && (
@@ -624,8 +617,8 @@ export function SettlementStatementRecordPage() {
         isAdmin={isAdmin}
         onRerun={() => { setRerunError(""); setConfirmRerun(true); }}
         onExport={exportDetail}
-        onCorrect={() => navigate("/correction-notes", { state: { ref: d.batch_no } })}
-        lineState={{ from: location.pathname }}
+        onCorrect={() => navigate("/correction-notes", { state: { ...outgoingState, ref: d.batch_no } })}
+        lineState={outgoingState}
       />}
 
       {confirmRerun && d && (
@@ -654,7 +647,7 @@ function BatchDetailBody({ d, isAdmin, onRerun, onExport, onCorrect, lineState }
   onRerun: () => void;
   onExport: () => void;
   onCorrect: () => void;
-  lineState: { from: string };
+  lineState: DetailLinkState;
 }) {
   // 动作可用性=服务端布尔位(与对账§5.5.4 同源常量;⚠️ 前端按角色自猜=第二套判据)。
   // null ⇒ 后端未下发 ⇒ 禁用+「可操作性位后端未下发」说明。
@@ -716,7 +709,7 @@ function BatchDetailBody({ d, isAdmin, onRerun, onExport, onCorrect, lineState }
         {d.status === "voided" && d.voided_by_batch_no && (
           <p className="reconcile-footnote">
             {VOIDED_BY_PREFIX}
-            <Link className="ops-table-action" to={batchPath(d.holder_id, d.voided_by_batch_no)}>{d.voided_by_batch_no} <ArrowRight size={14} /></Link>
+            <Link className="ops-table-action" to={batchPath(d.holder_id, d.voided_by_batch_no)} state={lineState}>{d.voided_by_batch_no} <ArrowRight size={14} /></Link>
             作废。
           </p>
         )}
@@ -779,15 +772,13 @@ function BatchDetailBody({ d, isAdmin, onRerun, onExport, onCorrect, lineState }
 /* ── FN-08 账单明细(14.3 列表) ─────────────────────────────────── */
 
 export function SettlementBillListPage() {
-  const location = useLocation();
+  const listNavState = useDetailLinkState();
   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;
@@ -895,14 +886,16 @@ function BillRecordPanel({ tab, active, children }: { tab: BillRecordTab; active
   </section>;
 }
 
-function BillBatchLink({ holderId, number, from }: { holderId: string; number: string; from: string }) {
-  return <Link className="ops-table-action bill-record-batch-link" to={batchPath(holderId, number)} state={{ from }}>
+function BillBatchLink({ holderId, number, linkState }: { holderId: string; number: string; linkState: DetailLinkState }) {
+  return <Link className="ops-table-action bill-record-batch-link" to={batchPath(holderId, number)} state={linkState}>
     <span>{number}</span><ArrowRight size={14} aria-hidden="true" />
   </Link>;
 }
 
-function BillRecordContent({ bill, from }: { bill: BillDetailResult; from: string }) {
-  const [tab, setTab] = useState<BillRecordTab>("billing");
+function BillRecordContent({ bill }: { bill: BillDetailResult }) {
+  const location = useLocation();
+  const [tab, setTab] = useState<BillRecordTab>(() => billRecordTabs.find(({ id }) => id === location.state?.billTab)?.id ?? "billing");
+  const outgoingState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, billTab: tab });
   const actualCost = bill.cost_deduct_cents ?? (bill.receivable_cents - bill.share_base_cents);
   const costCapped = bill.base_floor_protected || (
     bill.cost_should_deduct_cents != null && bill.cost_deduct_cents != null && bill.cost_should_deduct_cents > bill.cost_deduct_cents
@@ -981,7 +974,7 @@ function BillRecordContent({ bill, from }: { bill: BillDetailResult; from: strin
         <dl className="ops-record-summary bill-record-facts">
           <div><dt>分成方</dt><dd>{bill.holder_name || missing}</dd></div>
           <div><dt>分成方式与取值</dt><dd>{settleTextFromSnapshot(bill.share_mode, bill.share_value)}</dd></div>
-          <div><dt>所属对账单号</dt><dd><BillBatchLink holderId={bill.holder_id} number={bill.batch_no} from={from} /></dd></div>
+          <div><dt>所属对账单号</dt><dd><BillBatchLink holderId={bill.holder_id} number={bill.batch_no} linkState={outgoingState} /></dd></div>
         </dl>
         {bill.base_floor_protected && <p className="bill-record-note" role="note">{BASE_FLOOR_NOTE}</p>}
         {/* 仅在服务端下发其他分成方时展示。 */}
@@ -993,7 +986,7 @@ function BillRecordContent({ bill, from }: { bill: BillDetailResult; from: strin
               {bill.other_parties.map((party, i) => <tr key={`${party.holder_type}-${party.holder_name}-${i}`}>
                 <td><div className="bill-record-table-title"><strong className="table-cell-title">{party.holder_name}</strong><OpsTag tone={holderTone[party.holder_type]}>{HOLDER_TYPE_TEXT[party.holder_type]}</OpsTag></div></td>
                 <td className="bill-record-number"><span className="table-number">{moneyFromCents(party.share_amount_cents)}</span></td>
-                <td>{party.batch_no && party.holder_id ? <BillBatchLink holderId={party.holder_id} number={party.batch_no} from={from} /> : party.batch_no ?? missing}</td>
+                <td>{party.batch_no && party.holder_id ? <BillBatchLink holderId={party.holder_id} number={party.batch_no} linkState={outgoingState} /> : party.batch_no ?? missing}</td>
               </tr>)}
             </tbody>
           </table>
@@ -1024,12 +1017,7 @@ function BillRecordContent({ bill, from }: { bill: BillDetailResult; from: strin
 export function SettlementBillRecordPage() {
   const { index } = useParams();
   const location = useLocation();
-  const state = (location.state ?? {}) as { from?: string; listSearch?: string };
-  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${state.from === "/settlement-bills" ? (state.listSearch ?? "") : ""}`, label: BACK_TO_BILL_LIST };
+  const back = detailBack(location.state, "/settlement-bills", BACK_TO_BILL_LIST);
 
   const detail = useBillDetail(index ?? null);
   const bill = detail.data;
@@ -1037,7 +1025,7 @@ export function SettlementBillRecordPage() {
 
   return (
     <article className="ops-page ops-record-page record-detail bill-record">
-      <Link className="ops-back-link" to={back.to}><ArrowLeft size={16} aria-hidden="true" />{back.label.replace(/^←\s*/, "")}</Link>
+      <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 bill-record-masthead">
         <div className="customer-hero-symbol" aria-hidden="true"><FileSpreadsheet size={26} /></div>
         <div className="customer-hero-copy">
@@ -1059,7 +1047,7 @@ export function SettlementBillRecordPage() {
         {detail.fail.message} <Button variant="ghost" size="sm" onClick={detail.reload}>重试</Button>
       </p>}
       {!bill && detail.loading && <p className="bill-record-placeholder" role="status">正在读取账单明细…</p>}
-      {bill && <BillRecordContent key={bill.bill_detail_id} bill={bill} from={location.pathname} />}
+      {bill && <BillRecordContent key={bill.bill_detail_id} bill={bill} />}
     </article>
   );
 }

+ 1 - 4
web-scaffold/src/pages/TeamQueuePage.tsx

@@ -13,7 +13,7 @@
  */
 import { useState } from "react";
 import { ArrowRight, Check, ClipboardList, Clock3, Search, Shuffle, UserRoundCheck, UsersRound, X } from "lucide-react";
-import { Link, useLocation, useSearchParams } from "react-router";
+import { Link, useSearchParams } from "react-router";
 import { Button } from "../components/ui/button";
 import { FilterSelect } from "../components/ui/filter-select";
 import { FieldHint } from "../components/ui/field-hint";
@@ -58,7 +58,6 @@ type QueueBoardProps = {
 
 export function QueueBoard({ teamId, teamName, showTeamColumn = false, canAutoDispatch }: QueueBoardProps) {
   const [params, setParams] = useSearchParams();
-  const location = useLocation();
   const q = params.get("q") || "";
   const type = params.get("type") || "";
   const page = Math.max(1, Number(params.get("page")) || 1);
@@ -73,7 +72,6 @@ export function QueueBoard({ teamId, teamName, showTeamColumn = false, canAutoDi
   const fail = queue.error ? classifyTicketError(queue.error) : null;
   const lateCount = rows.filter((item) => item.overdue_7d).length;
   const teams = new Set(rows.map((row) => row.assign_team_id).filter(Boolean)).size;
-  const from = location.pathname + location.search;
 
   const submit = useSubmit();
   const [action, setAction] = useState<PendingQueueItem | "auto" | null>(null);
@@ -168,7 +166,6 @@ export function QueueBoard({ teamId, teamName, showTeamColumn = false, canAutoDi
       </div>
       <WorkOrderLedgerList
         rows={rows}
-        from={from}
         label="待分派工单"
         fallback={fallback}
         ownerColumn={showTeamColumn ? "team" : "none"}

+ 4 - 5
web-scaffold/src/pages/WorkOrderDeliveryPage.tsx

@@ -9,7 +9,8 @@
  * 页面只做「分发到处置」:回执、重推、报文处置的可用性一律由详情页服务端 `actions` 决定,
  * ⛔ 在这里按状态臆断按钮能不能点。
  */
-import { Link, Navigate, useLocation, useSearchParams } from "react-router";
+import { useDetailLinkState } from "../lib/detail-navigation";
+import { Link, Navigate, useSearchParams } from "react-router";
 import { PageIntro } from "../components/PageIntro";
 import { ArrowRight, PackageCheck, TriangleAlert } from "lucide-react";
 import { ListPager } from "../components/ListPager";
@@ -102,8 +103,7 @@ export function WorkOrderDeliveryPage() {
 
 function DeliveryList({ tab, page, onPageChange }: { tab: Exclude<DeliveryTab, "messages">; page: number; onPageChange: (page: number) => void }) {
   const receipt = tab === "receipt";
-  const location = useLocation();
-  const from = location.pathname + location.search;
+  const linkState = useDetailLinkState();
   const list = useTicketList({ statuses: [receipt ? "completed" : "rejected"] }, page);
   const fail = list.error ? classifyTicketError(list.error) : null;
   const rows = list.data?.rows ?? [];
@@ -122,7 +122,6 @@ function DeliveryList({ tab, page, onPageChange }: { tab: Exclude<DeliveryTab, "
     </div>
     <WorkOrderLedgerList
       rows={rows}
-      from={from}
       label={receipt ? "待回执工单" : "已驳回工单"}
       dateColumn="completed_at"
       showNextStep={false}
@@ -130,7 +129,7 @@ function DeliveryList({ tab, page, onPageChange }: { tab: Exclude<DeliveryTab, "
       renderRowAction={(row) => {
         if (receipt && !isMainlineTicketType(row.ticket_type)) return null;
         const href = `/work-orders/${encodeURIComponent(row.ticket_id)}`;
-        return <Link className="ops-table-action" to={receipt ? `${href}?act=receipt` : href} state={{ from }}>{receipt ? "确认回执" : "去重推"}<ArrowRight size={14} aria-hidden="true" /></Link>;
+        return <Link className="ops-table-action" to={receipt ? `${href}?act=receipt` : href} state={linkState}>{receipt ? "确认回执" : "去重推"}<ArrowRight size={14} aria-hidden="true" /></Link>;
       }}
     />
     {!list.loading && !fail && <ListPager total={total} page={page - 1} pageSize={TICKET_PAGE_SIZE} unit="张" onPageChange={(next) => onPageChange(next + 1)} />}

+ 11 - 4
web-scaffold/src/pages/WorkOrderManagementPage.tsx

@@ -1,3 +1,4 @@
+import { detailLinkState } from "../lib/detail-navigation";
 import { PageIntro } from "../components/PageIntro";
 import { OpsNotice } from "../components/OperationsKit";
 import { FilterSelect } from "../components/ui/filter-select";
@@ -198,8 +199,15 @@ export function WorkOrderLedgerPage() {
 
   useEffect(() => {
     const ticket = params.get("ticket");
-    if (ticket) navigate(`/work-orders/${encodeURIComponent(ticket)}`, { replace: true, state: { from: location.pathname + location.search } });
-  }, [navigate, params, location.pathname]);
+    if (!ticket) return;
+    const returnQuery = new URLSearchParams(params);
+    returnQuery.delete("ticket");
+    const search = returnQuery.size ? `?${returnQuery}` : "";
+    navigate(`/work-orders/${encodeURIComponent(ticket)}`, {
+      replace: true,
+      state: detailLinkState(location.pathname + search + location.hash, location.state),
+    });
+  }, [navigate, params, location.pathname, location.hash, location.state]);
 
   /** 更新多值筛选并回到第 1 页。 */
   function setMulti(key: string, values: string[]) {
@@ -231,7 +239,6 @@ export function WorkOrderLedgerPage() {
   const messagePending = summary?.item_4_message_pending;
   const activeTab = statuses.length === 1 ? statuses[0] : "";
   const filtered = Boolean(query || types.length || statuses.length || from || to);
-  const fromList = location.pathname + location.search;
   const numberOf = (value: number | undefined, loading: boolean) =>
     typeof value === "number" && Number.isSafeInteger(value) && value >= 0
       ? value.toLocaleString("zh-CN")
@@ -307,7 +314,7 @@ export function WorkOrderLedgerPage() {
         {statuses.map((s) => <button key={`s-${s}`} type="button" onClick={() => setMulti("status", statuses.filter((v) => v !== s))}>{statusFilterLabel(s)}<X size={13} /></button>)}
         <button type="button" className="is-clear" onClick={() => { const next = new URLSearchParams(); setParams(next); }}>清除全部</button>
       </div>}
-      <WorkOrderLedgerList rows={rows} from={fromList} label="工单列表" fallback={listState} clientView={clientView} />
+      <WorkOrderLedgerList rows={rows} label="工单列表" fallback={listState} clientView={clientView} />
       {!list.loading && !fail && <ListPager total={total} page={currentPage - 1} pageSize={TICKET_PAGE_SIZE} unit="张" onPageChange={(next) => patchParams("page", [String(next + 1)])} />}
     </div>
     {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}

+ 4 - 2
web-scaffold/src/pages/WorkOrderMinePage.tsx

@@ -14,6 +14,7 @@
  * 一次取 100 张(服务端 `page_norm` 上限),取满时页脚明说「还有更多,去我的工单」,
  * ⛔ 把当页说成全量。
  */
+import { useDetailLinkState } from "../lib/detail-navigation";
 import { Link, Navigate } from "react-router";
 import { PageIntro } from "../components/PageIntro";
 import { useState } from "react";
@@ -49,6 +50,7 @@ export function WorkOrderMinePage() {
 }
 
 function WorkOrderMineInner() {
+  const linkState = useDetailLinkState();
   // `assignee: "me"`:把「可见范围」收窄到「本人名下」(服务端解析 `me`,⛔ 前端传 user_id)。
   const list = useTicketList({ statuses: MINE_STATUSES, assignee: "me" }, 1, MINE_PAGE_SIZE);
   const fail = list.error ? classifyTicketError(list.error) : null;
@@ -101,7 +103,7 @@ function WorkOrderMineInner() {
           return <li key={row.ticket_id}>
             <div className="work-order-todo-main">
               <div className="work-order-todo-title">
-                <Link to={`/work-orders/${encodeURIComponent(row.ticket_id)}`} state={{ from: "/work-orders/mine" }}>{summary.title}</Link>
+                <Link to={`/work-orders/${encodeURIComponent(row.ticket_id)}`} state={linkState}>{summary.title}</Link>
                 <TicketTypeTag type={row.ticket_type} />
                 <TicketStatusTag status={row.status} type={row.ticket_type} />
               </div>
@@ -120,7 +122,7 @@ function WorkOrderMineInner() {
                   「催办」紧贴姓名右侧(同一行,见 `.work-order-todo-action` 的换行网格),
                   ⛔ 单独占一行——那会把「找谁」和「催谁」拆成两段读。 */}
               {step.label
-                ? <Link className={`work-order-next-step tone-${step.tone}`} to={`/work-orders/${encodeURIComponent(row.ticket_id)}${step.action ? `?act=${step.action}` : ""}`} state={{ from: "/work-orders/mine" }}>{step.label}<ArrowRight size={14} /></Link>
+                ? <Link className={`work-order-next-step tone-${step.tone}`} to={`/work-orders/${encodeURIComponent(row.ticket_id)}${step.action ? `?act=${step.action}` : ""}`} state={linkState}>{step.label}<ArrowRight size={14} /></Link>
                 : <span className={`work-order-next-step is-passive tone-${step.tone}`}>{passiveParts(step)}</span>}
               <UrgeControl row={row} onSent={list.reload} />
               {step.hint && <small>{step.hint}</small>}

+ 5 - 5
web-scaffold/src/pages/WorkOrderOverviewPage.tsx

@@ -1,6 +1,7 @@
+import { useDetailLinkState } from "../lib/detail-navigation";
 import { useEffect, useRef, useState, type MouseEvent } from "react";
 import { PageIntro } from "../components/PageIntro";
-import { Link, Navigate, useLocation } from "react-router";
+import { Link, Navigate } from "react-router";
 import { ArrowRight, ClipboardList, Clock3, Inbox, Info, PackageCheck, TriangleAlert, UserRoundCheck } from "lucide-react";
 import { FetchError } from "../components/fetchError";
 import { TicketState } from "../components/ticketState";
@@ -26,8 +27,7 @@ export function WorkOrderOverviewPage() {
 
 function WorkOrderOverviewInner() {
   const identity = useDemoIdentity();
-  const location = useLocation();
-  const from = location.pathname + location.search;
+  const linkState = useDetailLinkState();
   /** Wave B:首屏只保留 todo_counts + pending_queue;状态计数/最近列表 idle 后再拉。 */
   const [deferSecondary, setDeferSecondary] = useState(false);
   useEffect(() => {
@@ -120,7 +120,7 @@ function WorkOrderOverviewInner() {
           <div><h2 id="recent-work-orders">最近工单</h2><p>按创建时间倒序展示最近 6 张工单。</p></div>
           <Link className="ops-table-action" to="/work-orders">查看全部工单<ArrowRight size={14} aria-hidden="true" /></Link>
         </header>
-        <WorkOrderLedgerList rows={recentRows} from={from} label="最近工单" fallback={recentState} />
+        <WorkOrderLedgerList rows={recentRows} label="最近工单" fallback={recentState} />
       </section>
 
       <section className="order-list-shell work-order-overview-section" aria-labelledby="pending-work-orders">
@@ -142,7 +142,7 @@ function WorkOrderOverviewInner() {
                       <td><strong className="table-cell-title" title={row.customer_name || undefined}>{row.customer_name || <span className="table-placeholder">未关联客户</span>}</strong><small title={number}>{number}</small></td>
                       <td><TicketTypeTag type={row.ticket_type} /></td>
                       <td className="order-date">{row.created_at ? fmtTime(row.created_at) : <span className="table-placeholder">—</span>}</td>
-                      <td><Link className="ops-table-action" to={`/work-orders/${encodeURIComponent(row.ticket_id)}?act=assign`} state={{ from }} aria-label={`分派工单 ${number}`}>分派<ArrowRight size={14} aria-hidden="true" /></Link></td>
+                      <td><Link className="ops-table-action" to={`/work-orders/${encodeURIComponent(row.ticket_id)}?act=assign`} state={linkState} aria-label={`分派工单 ${number}`}>分派<ArrowRight size={14} aria-hidden="true" /></Link></td>
                     </tr>
                   );
                 })}</tbody>

+ 7 - 5
web-scaffold/src/pages/WorkOrderRecordPage.tsx

@@ -12,7 +12,7 @@ import { opsTeamGetList, rowsOf, subAccountGetList } from "../lib/api/bos";
 import { fetchAllPages } from "../lib/fetch-all-pages";
 import { LIST_PAGE_SIZE } from "../lib/list-paging";
 import type { SubAccountRow } from "../lib/api/types";
-import { customerTicketBack, detailBack } from "../lib/detail-navigation";
+import { customerTicketBack, detailBack, detailLinkState } from "../lib/detail-navigation";
 import { TicketStatusTag, TicketTypeTag } from "../components/work-order/TicketBadges";
 import { TicketExtForm, type TicketExtFormHandle } from "../components/work-order/TicketExtForm";
 import { ConstructionGuidePanel } from "../components/work-order/ConstructionGuidePanel";
@@ -1227,9 +1227,9 @@ export function WorkOrderRecordPage() {
     else setNotice(submitErrorText(submit.errorRef.current, "操作失败"));
   }
 
-  if (!id) return <Navigate to={back.to} replace />;
-  if (detail.loading) return <section className="ops-record-page"><div className="work-order-empty"><Info size={27} /><h3>正在读取工单详情…</h3></div></section>;
   const backLink = <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link>;
+  if (!id) return <Navigate to={back.to} state={back.state} replace />;
+  if (detail.loading) return <section className="ops-record-page">{backLink}<div className="work-order-empty"><Info size={27} /><h3>正在读取工单详情…</h3></div></section>;
   if (fail || !d) return <section className="ops-record-page">{backLink}{fail && <TicketState fail={fail} onRetry={detail.reload} />}</section>;
 
   const t = d.ticket;
@@ -1460,7 +1460,9 @@ export function WorkOrderRecordPage() {
     ...tab,
     count: tab.id === "messages" ? d.messages.length : undefined,
   }));
-  const activeTab = selectedTab?.ticketId === id && tabVisible[selectedTab.tab] ? selectedTab.tab : "overview";
+  const preferredTab = selectedTab?.ticketId === id ? selectedTab.tab : (location.state?.workOrderTab as WorkOrderRecordTab | undefined);
+  const activeTab = tabs.find(({ id: tab }) => tab === preferredTab)?.id ?? "overview";
+  const linkState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, workOrderTab: activeTab });
   const receiptState = d.completion
     ? d.completion.receipt_at && d.completion.receipt_valid !== "0" ? { text: "回执已确认", tone: "success" as const }
       : d.completion.receipt_at ? { text: "回执已失效", tone: "warning" as const }
@@ -1808,7 +1810,7 @@ export function WorkOrderRecordPage() {
       onDone={(message) => { setMaterialOpen(false); setNotice(message); detail.reload(); }} />}
     {sheet && <TicketActionSheet key={sheet} action={sheet} detail={d} focus={sheetFocus}
       onReload={detail.reload} onClose={() => { setSheet(null); setSheetFocus(undefined); if (sheet === "backfill") detail.reload(); }} onDone={(message) => { setSheet(null); setSheetFocus(undefined); setNotice(message); detail.reload(); }} />}
-    {refStack.length > 0 && <ReferenceDrawer presentation="dialog" stack={refStack} onPush={openRef} onBack={() => setRefStack((stack) => stack.slice(0, -1))} onClose={() => setRefStack([])} />}
+    {refStack.length > 0 && <ReferenceDrawer presentation="dialog" stack={refStack} linkState={linkState} onPush={openRef} onBack={() => setRefStack((stack) => stack.slice(0, -1))} onClose={() => setRefStack([])} />}
   </section>;
 }
 

+ 32 - 3
web-scaffold/src/pages/__tests__/settlement-bill-record.test.tsx

@@ -1,13 +1,14 @@
 import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
-import { MemoryRouter, Route, Routes } from "react-router";
+import { MemoryRouter, Route, Routes, useLocation } from "react-router";
 import { afterEach, expect, it, vi } from "vitest";
-import { billGetDetail } from "../../lib/api/bos";
+import { billGetDetail, reconGetDetail } from "../../lib/api/bos";
 import type { BillDetailResult } from "../../lib/api/types";
-import { SettlementBillRecordPage } from "../SettlementRecordPages";
+import { SettlementBillRecordPage, SettlementStatementRecordPage } from "../SettlementRecordPages";
 
 vi.mock("../../lib/api/bos", async (load) => ({
   ...await load<typeof import("../../lib/api/bos")>(),
   billGetDetail: vi.fn(),
+  reconGetDetail: vi.fn(),
 }));
 
 const bill: BillDetailResult = {
@@ -57,6 +58,7 @@ function renderBill(detail: BillDetailResult) {
 afterEach(() => {
   cleanup();
   vi.mocked(billGetDetail).mockReset();
+  vi.mocked(reconGetDetail).mockReset();
 });
 
 it("对齐前后应收始终可见,并按页签查看成本、分成和分账号计费", async () => {
@@ -95,3 +97,30 @@ it.each([
   fireEvent.click(tabs.getByRole("tab", { name: "分账号计费" }));
   expect(within(screen.getByRole("tabpanel", { name: "分账号计费" })).getByText(message)).toBeTruthy();
 });
+
+function BillListLocation() {
+  const { search } = useLocation();
+  return <output aria-label="账单列表参数">{search}</output>;
+}
+
+it("从账单进入对账批次,返回恢复原页签,再返回带筛选和页码的账单列表", async () => {
+  vi.mocked(billGetDetail).mockResolvedValue(bill);
+  vi.mocked(reconGetDetail).mockImplementation(() => new Promise(() => {}));
+  render(<MemoryRouter initialEntries={[{
+    pathname: "/settlement-bills/BILL-001",
+    state: { from: "/settlement-bills?month=2026-10&page=3" },
+  }]}>
+    <Routes>
+      <Route path="/settlement-bills" element={<BillListLocation />} />
+      <Route path="/settlement-bills/:index" element={<SettlementBillRecordPage />} />
+      <Route path="/settlement-batches/:partyId/:no" element={<SettlementStatementRecordPage />} />
+    </Routes>
+  </MemoryRouter>);
+
+  fireEvent.click(await screen.findByRole("tab", { name: "分成与对账" }));
+  fireEvent.click(screen.getByRole("link", { name: "RECON-001" }));
+  fireEvent.click(await screen.findByRole("link", { name: "返回账单明细详情" }));
+  expect(await screen.findByRole("tabpanel", { name: "分成与对账" })).toBeTruthy();
+  fireEvent.click(screen.getByRole("link", { name: "返回账单明细" }));
+  expect(screen.getByLabelText("账单列表参数").textContent).toBe("?month=2026-10&page=3");
+});

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

@@ -60,7 +60,7 @@ afterEach(() => {
 
 function Destination() {
   const { pathname, state } = useLocation();
-  return <output aria-label="补跑详情">{pathname} {state.listSearch}</output>;
+  return <output aria-label="补跑详情">{pathname} {state.from}</output>;
 }
 
 function renderPage(search = "") {
@@ -139,5 +139,5 @@ it("补跑对话框预览选择的分成方和账期,完成后进入新批次
   await waitFor(() => expect(reconRerun).toHaveBeenCalledWith({
     holder_type: "partner", holder_id: "PARTNER-1", period: "2026-10",
   }));
-  expect((await screen.findByLabelText("补跑详情")).textContent).toBe("/settlement-batches/PARTNER-1/RECON-002 ?type=operator");
+  expect((await screen.findByLabelText("补跑详情")).textContent).toBe("/settlement-batches/PARTNER-1/RECON-002 /settlement-batches?type=operator");
 });

+ 15 - 8
web-scaffold/src/pages/mobile/MobileWorkOrderPages.tsx

@@ -2,7 +2,7 @@
  * 运维现场移动端 H5:待办列表/精简详情/全屏回填(与桌面共用 API/回填表单)。
  */
 import { useState } from "react";
-import { Link, Navigate, useNavigate, useParams } from "react-router";
+import { Link, Navigate, useLocation, useNavigate, useParams } from "react-router";
 import { ArrowLeft, ArrowRight, Smartphone } from "lucide-react";
 import { Button } from "../../components/ui/button";
 import { TicketStatusTag, TicketTypeTag } from "../../components/work-order/TicketBadges";
@@ -13,6 +13,7 @@ import { nextStepOf } from "../../lib/work-order-next-step";
 import { businessToday } from "../../lib/business-date";
 import { groupTodoRows, todoRowSummary } from "../../lib/work-order-todo-row";
 import { useDemoIdentity } from "../../lib/demo-session";
+import { detailBack, useDetailLinkState } from "../../lib/detail-navigation";
 import { TicketState } from "../../components/ticketState";
 import { TicketActionSheet } from "../WorkOrderRecordPage";
 import "../../styles/work-order-guide.css";
@@ -58,10 +59,11 @@ function MobileMineInner() {
 }
 
 function MobileTodoCard({ row }: { row: TicketListItem }) {
+  const linkState = useDetailLinkState();
   const step = nextStepOf(row);
   const summary = todoRowSummary(row);
   return (
-    <Link className="wo-m-card" to={`/m/work-orders/${row.ticket_id}`}>
+    <Link className="wo-m-card" to={`/m/work-orders/${encodeURIComponent(row.ticket_id)}`} state={linkState}>
       <strong>{summary.title}</strong>
       <small>
         <TicketTypeTag type={row.ticket_type} />{" "}
@@ -74,16 +76,19 @@ function MobileTodoCard({ row }: { row: TicketListItem }) {
 }
 
 export function MobileWorkOrderDetailPage() {
+  const location = useLocation();
   const { id } = useParams();
   const navigate = useNavigate();
   const identity = useDemoIdentity();
   if (identity && !MINE_ROLES.includes(identity.role)) return <Navigate to="/work-orders" replace />;
   if (!id) return <Navigate to="/m/work-orders/mine" replace />;
-  return <MobileDetailInner id={id} onBack={() => navigate("/m/work-orders/mine")} />;
+  const back = detailBack(location.state, "/m/work-orders/mine", "返回移动端待办");
+  return <MobileDetailInner id={id} backLabel={back.label} onBack={() => navigate(back.to, { state: back.state })} />;
 }
 
-function MobileDetailInner({ id, onBack }: { id: string; onBack: () => void }) {
+function MobileDetailInner({ id, backLabel, onBack }: { id: string; backLabel: string; onBack: () => void }) {
   const navigate = useNavigate();
+  const linkState = useDetailLinkState();
   const detail = useTicketDetail(id, true);
   const fail = detail.error ? classifyTicketError(detail.error) : null;
   const d = detail.data;
@@ -94,7 +99,7 @@ function MobileDetailInner({ id, onBack }: { id: string; onBack: () => void }) {
   return (
     <div className="wo-m-page">
       <header className="wo-m-top">
-        <Button variant="ghost" size="sm" type="button" onClick={onBack}><ArrowLeft size={16} /></Button>
+        <Button variant="ghost" size="sm" type="button" aria-label={backLabel} onClick={onBack}><ArrowLeft size={16} aria-hidden="true" /></Button>
         <h1>工单详情</h1>
       </header>
       {detail.loading && <p className="wo-m-body">加载中…</p>}
@@ -120,12 +125,12 @@ function MobileDetailInner({ id, onBack }: { id: string; onBack: () => void }) {
           </div>
           <div className="wo-m-bar">
             {backfillReady ? (
-              <Button onClick={() => navigate(`/m/work-orders/${id}/backfill`)}>
+              <Button onClick={() => navigate(`/m/work-orders/${encodeURIComponent(id)}/backfill`, { state: linkState })}>
                 {can?.check_and_backfill ? "核对并回填" : "施工回填"}
                 <ArrowRight size={16} />
               </Button>
             ) : (
-              <Button variant="outline" onClick={() => navigate(`/work-orders/${id}`)}>
+              <Button variant="outline" onClick={() => navigate(`/work-orders/${encodeURIComponent(id)}`, { state: linkState })}>
                 打开完整详情
               </Button>
             )}
@@ -138,13 +143,15 @@ function MobileDetailInner({ id, onBack }: { id: string; onBack: () => void }) {
 
 /** 全屏回填:无 AppShell,直接挂桌面回填表单(`presentation=page`),⛔ 再嵌一整页桌面详情。 */
 export function MobileWorkOrderBackfillPage() {
+  const location = useLocation();
   const { id } = useParams();
   const navigate = useNavigate();
   const identity = useDemoIdentity();
   if (identity && !MINE_ROLES.includes(identity.role)) return <Navigate to="/work-orders" replace />;
   if (!id) return <Navigate to="/m/work-orders/mine" replace />;
+  const back = detailBack(location.state, `/m/work-orders/${encodeURIComponent(id)}`, "返回详情");
   return <MobileBackfillInner id={id} onLeave={(msg) => {
-    navigate(`/m/work-orders/${id}`, { replace: true, state: msg ? { notice: msg } : undefined });
+    navigate(back.to, { replace: true, state: msg ? { ...(back.state as object | null), notice: msg } : back.state });
   }} />;
 }
 

+ 29 - 1
web-scaffold/tests/detail-navigation.test.mjs

@@ -23,11 +23,39 @@ test("合同、客户、订单详情逐级返回保留前一级历史", () => {
 });
 
 test("返回路径只接受已知业务列表与详情,拒绝外部或任意路径", () => {
-  for (const from of ["https://example.com", "//example.com", "/login", "/workspace/other", "/contracts-evil?q=x", 123, null]) {
+  for (const from of ["https://example.com", "//example.com", "/\\example.com", "/login", "/workspace/other", "/contracts-evil?q=x", "/contracts/%2e%2e", 123, null]) {
     assert.equal(detailBack({ from }, "/contracts", "返回合同管理").to, "/contracts");
   }
 });
 
+test("跨财务详情逐级返回原入口,并保留查询、锚点和页面状态", () => {
+  const correction = detailLinkState("/correction-notes", { correctionView: { detailId: "C-9", page: 2 } });
+  const bill = detailLinkState("/settlement-bills/B-1?month=2026-10#details", { ...correction, billTab: "reconciliation" });
+  const batchBack = detailBack(bill, "/settlement-batches", "返回对账清单");
+  assert.deepEqual(batchBack, {
+    to: "/settlement-bills/B-1?month=2026-10#details",
+    state: { ...correction, billTab: "reconciliation" },
+    label: "返回账单明细详情",
+  });
+  assert.deepEqual(detailBack(batchBack.state, "/settlement-bills", "返回账单明细"), {
+    to: "/correction-notes", state: { correctionView: { detailId: "C-9", page: 2 } }, label: "返回出账更正记录",
+  });
+  assert.equal(detailBack({ from: "/settlement-bills", listSearch: "?month=2026-10" }, "/settlement-bills", "返回账单明细").to, "/settlement-bills?month=2026-10");
+});
+
+test("团队账号、只读台账和移动端支持返回各自的入口", () => {
+  for (const [from, label] of [
+    ["/organization/maintenance-teams?region=R-1", "返回运维团队"],
+    ["/organization/operations-teams/T-1/accounts", "返回运营团队账号"],
+    ["/bos/pv/recon", "返回本运营区域对账"],
+    ["/bos/ov/bill-detail?batch=B-2", "返回账单明细"],
+    ["/m/work-orders/T-1", "返回移动端工单详情"],
+    ["/workspace/submit", "返回提交工单"],
+  ]) {
+    assert.deepEqual(detailBack(detailLinkState(from, null), "/work-orders", "返回工单列表"), { to: from, state: null, label });
+  }
+});
+
 test("工单组四个新列表入口可返回并保留筛选,且不被当成详情", () => {
   const cases = [
     ["/work-orders/overview", "返回工单总览"],