Przeglądaj źródła

fix(web): 修正订阅到期提示和登录退出交互

sy 3 godzin temu
rodzic
commit
d4d83d875f

+ 63 - 0
web-scaffold/src/auth/__tests__/session-notice.test.tsx

@@ -0,0 +1,63 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { useSyncExternalStore } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { authContext } from "../../lib/api/bos";
+import { UNAUTHORIZED_EVENT, setToken } from "../../lib/api/http";
+import type { AuthContext } from "../../lib/api/types";
+import { dismissSessionNotice, getSessionNotice, subscribeSessionNotice } from "../../lib/session-notice";
+import { SessionProvider, useSession } from "../session";
+
+vi.mock("../../lib/api/bos", async (load) => ({
+  ...await load<typeof import("../../lib/api/bos")>(),
+  authContext: vi.fn(),
+}));
+
+const context: AuthContext = {
+  user_id: "fixture-user",
+  username: "fixture",
+  role_code: "enterprise",
+  subject_type: "customer",
+  subject_id: "fixture-customer",
+  entry_only: false,
+  scope_mode: "self",
+  display_name: "测试用户",
+  subject_name: "测试客户",
+  mobile_hint: null,
+  scope: { kind: "self", region_node_ids: [], customer_ids: [], team_ids: [] },
+  acct_status: "normal",
+  must_change_password: false,
+  permissions: [],
+};
+
+afterEach(() => {
+  cleanup();
+  dismissSessionNotice();
+  setToken(null);
+  sessionStorage.removeItem("oss:returnTo");
+  vi.mocked(authContext).mockReset();
+});
+
+function SessionProbe() {
+  const { ctx, signIn } = useSession();
+  const notice = useSyncExternalStore(subscribeSessionNotice, getSessionNotice);
+  return <>
+    {notice && <p role="status">{notice}</p>}
+    {ctx && <p>{ctx.username}</p>}
+    <button type="button" onClick={() => void signIn("fixture-token").catch(() => {})}>重新登录</button>
+  </>;
+}
+
+it("登录失败保留会话过期提示,成功重新登录后立即清除", async () => {
+  vi.mocked(authContext).mockRejectedValueOnce(new Error("登录失败")).mockResolvedValueOnce(context);
+  render(<MemoryRouter><SessionProvider><SessionProbe /></SessionProvider></MemoryRouter>);
+  act(() => { window.dispatchEvent(new Event(UNAUTHORIZED_EVENT)); });
+  expect(screen.getByRole("status").textContent).toBe("登录已过期,请重新登录。");
+
+  await act(async () => { fireEvent.click(screen.getByRole("button", { name: "重新登录" })); });
+  expect(screen.getByRole("status").textContent).toBe("登录已过期,请重新登录。");
+
+  fireEvent.click(screen.getByRole("button", { name: "重新登录" }));
+  await screen.findByText("fixture");
+  expect(screen.queryByRole("status")).toBeNull();
+});

+ 2 - 1
web-scaffold/src/auth/session.tsx

@@ -12,7 +12,7 @@ import { useNavigate } from "react-router";
 import { authContext } from "../lib/api/bos";
 import { PERMISSION_DENIED_EVENT, UNAUTHORIZED_EVENT, getToken, setToken } from "../lib/api/http";
 import { resetCustomerListCache } from "../lib/customer-list-store";
-import { notifySessionNotice } from "../lib/session-notice";
+import { dismissSessionNotice, notifySessionNotice } from "../lib/session-notice";
 import type { AuthContext, RoleCode } from "../lib/api/types";
 import { type DemoIdentity, type DemoRole } from "../lib/demo-identities";
 import { setCurrentIdentity } from "../lib/demo-session";
@@ -285,6 +285,7 @@ export function SessionProvider({ children }: { children: ReactNode }) {
     setLoading(true);
     try {
       const c = await authContext();
+      dismissSessionNotice();
       setCtx(c);
       setError(null);
       setLoading(false);

+ 26 - 9
web-scaffold/src/components/layout/HeaderMenus.tsx

@@ -25,11 +25,22 @@ export function HeaderMenus() {
   const rootRef = useRef<HTMLDivElement>(null);
   const messageButtonRef = useRef<HTMLButtonElement>(null);
   const userButtonRef = useRef<HTMLButtonElement>(null);
+  const logoutDialogRef = useRef<HTMLDialogElement>(null);
   const location = useLocation();
   const { openProfile } = useProfileOverlay();
 
   useEffect(() => setOpenMenu(null), [location.pathname]);
 
+  useEffect(() => {
+    const dialog = logoutDialogRef.current;
+    if (!confirmingExit || !dialog) return;
+    dialog.showModal();
+    return () => {
+      dialog.close();
+      userButtonRef.current?.focus();
+    };
+  }, [confirmingExit]);
+
   /**
    * 提醒箱可用角色=后端 `bos.inbox.*` 的授出面:总运营/运营主账号/运营子账号/运维团队长。
    * 客户(主/分账号)、合伙人、运营商、运维成员**没有**这把键 ⇒ 请求必回 `11001`。
@@ -183,16 +194,22 @@ export function HeaderMenus() {
       </div>
 
       {confirmingExit && (
-        <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4" role="alertdialog" aria-modal="true" aria-labelledby="logout-confirm-title">
-          <div className="w-[min(420px,100%)] rounded-lg border border-border bg-card p-5 shadow-[var(--shadow-panel)]">
-            <h2 className="text-base font-semibold" id="logout-confirm-title">退出登录?</h2>
-            <p className="mt-2 text-sm leading-6 text-muted-foreground">退出后需重新输入账号密码登录,未保存的编辑内容将丢失。</p>
-            <div className="mt-5 flex justify-end gap-2">
-              <Button disabled={exiting} onClick={() => setConfirmingExit(false)} variant="outline">取消</Button>
-              <Button disabled={exiting} onClick={confirmExit} variant="destructive">{exiting ? "退出中…" : "确认退出"}</Button>
-            </div>
+        <dialog
+          ref={logoutDialogRef}
+          className="ops-dialog header-logout-dialog"
+          role="alertdialog"
+          aria-modal="true"
+          aria-labelledby="logout-confirm-title"
+          aria-describedby="logout-confirm-description"
+          onCancel={(event) => { event.preventDefault(); if (!exiting) setConfirmingExit(false); }}
+        >
+          <h2 className="text-base font-semibold" id="logout-confirm-title">退出登录?</h2>
+          <p className="mt-2 text-sm leading-6 text-muted-foreground" id="logout-confirm-description">退出后需重新输入账号密码登录,未保存的编辑内容将丢失。</p>
+          <div className="mt-5 flex justify-end gap-2">
+            <Button type="button" autoFocus disabled={exiting} onClick={() => setConfirmingExit(false)} variant="outline">取消</Button>
+            <Button type="button" disabled={exiting} onClick={confirmExit} variant="destructive">{exiting ? "退出中…" : "确认退出"}</Button>
           </div>
-        </div>
+        </dialog>
       )}
     </div>
   );

+ 2 - 1
web-scaffold/src/pages/CustomerWorkspacePage.tsx

@@ -678,6 +678,7 @@ export function CustomerWorkspacePage() {
         const row = orderView(sub);
         const rowStatus = sub.status_display?.label ?? row.statusLabel;
         const statusText = sub.status_display?.label ?? sub.status;
+        const expired = row.statusCode === "expired" || statusText === "已到期";
         /** 只有生效中的订阅可替换(升降配)或叠加新建并存订阅;只读身份不挂入口。 */
         const orderMore: OpsMoreItem[] = writable && rowStatus === "生效中" ? [
           { label: "升降配", icon: <RefreshCw size={15} />, onSelect: () => setChangeTarget(row) },
@@ -693,7 +694,7 @@ export function CustomerWorkspacePage() {
           <td>{sub.start_date ?? missingValue("—")} 至 {sub.end_date ?? missingValue("—")}</td>
           <td className="table-number">{sub.quota_slots ?? 0} 个</td>
           <td>{sub.monthly_settle_cents ? <span className="table-number">{money(String(sub.monthly_settle_cents / 100))}</span> : <Tri tone="missing" text={MISSING} title={MISSING + ":monthly_settle_cents 未下发"} />}</td>
-          <td>{statusText ? <OpsStatus tone={statusTone(statusText)}>{statusText}</OpsStatus> : missingValue(MISSING)}{sub.editable === false && sub.reason ? `(${sub.reason.replace(/([^()]*)$/, "").replace(/[,。;]$/, "")})` : ""}</td>
+          <td>{statusText ? <OpsStatus tone={statusTone(statusText)}>{statusText}</OpsStatus> : missingValue(MISSING)}{!expired && sub.editable === false && sub.reason ? `(${sub.reason.replace(/([^()]*)$/, "").replace(/[,。;]$/, "")})` : ""}</td>
           <td><div className="ops-inline-actions">
             {writable && rowStatus === "生效中" ? <CustomerServiceStopAction customerId={no || ""} customerName={displayName} orderId={sub.subscription_id} orderLabel={rowStatus} /> : null}
             <OpsMore items={orderMore} placeholder />

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

@@ -216,7 +216,7 @@ export function OrderRecordPage() {
         <tr><th scope="row">套餐档</th><td>{cell(item.planName)}{plan ? <span className="order-record-inline-note"> · {label(PLAN_FAMILY, plan.plan_family) || "形态未填"} · 目录年价 <span className={plan.annual_price_cents == null ? undefined : "table-annual-price"}>{moneyCell(plan.annual_price_cents).text}</span> / 月标准 <span className={plan.monthly_settle_cents == null ? undefined : "table-number"}>{moneyCell(plan.monthly_settle_cents).text}</span> · 额度 <TableValueText>{plan.sub_account_quota ?? WORD_UNCONFIGURED}</TableValueText></span> : <span className="order-record-inline-note"> · {catalog.error ? `目录档位取数失败:${catalog.error.message}` : "目录档位未取到,本条按冻结价继续计费"}</span>}</td></tr>
         <tr><th scope="row">冻结价格</th><td>年订阅价格 {moneyCellView(item.annual, true)} · 月结算标准 {moneyCellView(item.settle)}<span className="order-record-inline-note">({plan ? catalogMatches ? "与当前目录价一致" : "与当前目录价不同,以本条冻结值为准" : "目录档位未取到,以本条冻结值为准"})</span></td></tr>
         <tr><th scope="row">订阅方式</th><td><TableValueText>{item.modeLabel || WORD_UNCONFIGURED}</TableValueText><span className="order-record-inline-note"> · 交付形态({item.familyLabel || WORD_UNCONFIGURED}){catalogMode}</span>{item.original && <> · 替换 <Link to={`/orders/${encodeURIComponent(item.original.subscription_id)}`} state={outgoingState}>{item.original.subscription_id}</Link></>}{item.replacedBy && <> · 已被 <Link to={`/orders/${encodeURIComponent(item.replacedBy.subscription_id)}`} state={outgoingState}>{item.replacedBy.subscription_id}</Link> 替换</>}</td></tr>
-        <tr><th scope="row">订阅状态</th><td>{item.statusLabel ? <OpsStatus tone={statusTone(item.statusLabel)}>{item.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} />}{item.reason && <span className="order-record-inline-note"> · 办理说明:{item.reason}</span>}</td></tr>
+        <tr><th scope="row">订阅状态</th><td>{item.statusLabel ? <OpsStatus tone={statusTone(item.statusLabel)}>{item.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} />}{item.statusCode !== "expired" && item.statusLabel !== "已到期" && item.reason && <span className="order-record-inline-note"> · 办理说明:{item.reason}</span>}</td></tr>
         <tr><th scope="row">起止时间</th><td>{cell(item.start)} 至 {cell(item.end)}<span className="order-record-inline-note"> · 应收从实际开通日与合同生效日的较晚者起算{billableStart ? `(${billableStart})` : "(尚未开通)"}</span></td></tr>
         {item.trialMonths ? <tr><th scope="row">试用优惠</th><td>{item.trialMonths} 个月 · {item.trialDiscount === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.trialDiscount === null ? "优惠金额未填写" : `${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>

+ 2 - 1
web-scaffold/src/styles/operations.css

@@ -411,7 +411,8 @@ button.ops-contract-exit.is-active svg { opacity: .7; }
 /* 通用对话框(原生 dialog):分账号编辑等轻量表单。 */
 .ops-dialog { width: min(560px, calc(100vw - 32px)); max-height: min(88vh, 820px); margin: auto; padding: 0; border: 1px solid var(--border); border-radius: 12px; background: var(--card); color: var(--foreground); box-shadow: var(--shadow-dialog); overflow: auto; }
 .ops-dialog::backdrop { background: var(--overlay); }
-body:has(.ops-content-dialog[open]) { overflow: hidden; }
+.ops-dialog.header-logout-dialog { position: fixed; inset: 0; width: min(420px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); padding: 20px; }
+body:has(:is(.ops-content-dialog, .header-logout-dialog)[open]) { overflow: hidden; }
 .ops-content-dialog { max-height: min(88dvh, 900px); }
 .ops-content-dialog > header { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px clamp(14px, 3vw, 24px); border-bottom: 1px solid var(--border); background: var(--card); }
 .ops-content-dialog > header p { margin-bottom: 4px; color: var(--muted-foreground); font-size: var(--type-meta); }