Add visitor phone lookup flow

This commit is contained in:
wangxuming
2026-07-15 11:26:37 +08:00
parent 331e30894b
commit 7f751bebae
21 changed files with 971 additions and 104 deletions

View File

@@ -0,0 +1,69 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { usePollingResource } from "../hooks/usePollingResource";
import { VisitorLookupPage } from "./VisitorLookupPage";
const navigate = vi.fn();
vi.mock("react-router-dom", () => ({ useNavigate: () => navigate }));
vi.mock("../hooks/usePollingResource", () => ({ usePollingResource: vi.fn() }));
const activeTickets = [
{
project_name: "云岭漂流",
project: { id: "project-a", status: "RUNNING" },
ticket_number: "00012",
status: "WAITING",
phone_last4: "8000",
people_ahead: 2,
latest_called_number: "00010",
estimated_wait: { min: 10, max: 15 },
visitor_notice: "请留意现场叫号。",
},
{
project_name: "云顶索道",
project: { id: "project-b", status: "PAUSED" },
ticket_number: "00003",
status: "CALLED",
phone_last4: "8000",
called_at: "2026-07-15T03:00:00Z",
},
];
const mockedUsePollingResource = vi.mocked(usePollingResource);
beforeEach(() => {
navigate.mockReset();
mockedUsePollingResource.mockImplementation(((_loader: unknown, options: { enabled?: boolean } = {}) => ({
data: options.enabled ? { tickets: activeTickets } : undefined,
loading: false,
refreshing: false,
error: null,
offline: false,
lastClientSuccessAt: "2026-07-15T03:00:00Z",
refresh: vi.fn(),
})) as never);
});
describe("VisitorLookupPage", () => {
it("navigates to the number page after a successful phone query", async () => {
render(<VisitorLookupPage />);
fireEvent.change(screen.getByLabelText("手机号"), { target: { value: "13800138000" } });
fireEvent.click(screen.getByRole("button", { name: "查询排队状态" }));
await waitFor(() => expect(navigate).toHaveBeenCalledWith("/visitor/phone", {
replace: true,
state: { phone: "13800138000" },
}));
});
it("rejects an invalid phone before querying", () => {
render(<VisitorLookupPage />);
fireEvent.change(screen.getByLabelText("手机号"), { target: { value: "123" } });
fireEvent.click(screen.getByRole("button", { name: "查询排队状态" }));
expect(screen.getByRole("alert")).toHaveTextContent("请输入有效的手机号");
expect(screen.queryByText("找到 2 张排队单")).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,107 @@
import { useEffect, useState } from "react";
import type { FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "../api";
import { FeedbackBanner, LoadingState } from "../components/Feedback";
import { usePollingResource } from "../hooks/usePollingResource";
function isPhoneInputValid(value: string): boolean {
const digits = value.replace(/\D/g, "");
return /^[+\d\s\-()]+$/.test(value) && digits.length >= 7 && digits.length <= 15;
}
export function VisitorLookupPage() {
const navigate = useNavigate();
const [phoneInput, setPhoneInput] = useState("");
const [submittedPhone, setSubmittedPhone] = useState("");
const [formError, setFormError] = useState<string | null>(null);
const resource = usePollingResource((signal) => api.publicStatusByPhone(submittedPhone, signal), {
enabled: Boolean(submittedPhone),
intervalMs: 3_000,
resourceKey: submittedPhone,
});
const data = resource.data;
useEffect(() => {
if (!data || !submittedPhone) return;
navigate("/visitor/phone", {
replace: true,
state: { phone: submittedPhone },
});
}, [data, navigate, submittedPhone]);
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const nextPhone = phoneInput.trim();
if (!isPhoneInputValid(nextPhone)) {
setFormError("请输入有效的手机号7-15 位数字)");
return;
}
setFormError(null);
if (nextPhone === submittedPhone) {
void resource.refresh();
return;
}
setSubmittedPhone(nextPhone);
}
const liveTone = resource.offline ? "offline" : resource.error ? "stale" : "live";
const liveLabel = resource.offline ? "连接中断" : resource.error ? "查询延迟" : "手机号查询";
return (
<main className="visitor-page visitor-page--mobile visitor-lookup-page">
<header className="public-header visitor-public-header">
<div className="brand-lockup">
<img className="brand-logo" src="/xiaoqikong-logo.jpg" alt="" aria-hidden="true" />
<span><strong></strong><small></small></span>
</div>
<span className={`visitor-header__meta visitor-header__meta--${liveTone}`}><i aria-hidden="true" />{liveLabel}</span>
</header>
<div className="visitor-content">
<section className="visitor-lookup-card" aria-labelledby="visitor-lookup-title">
<div className="visitor-lookup-card__intro">
<span></span>
<h1 id="visitor-lookup-title"></h1>
<p></p>
</div>
<form className="visitor-lookup-form" onSubmit={submit} noValidate>
<label className="field" htmlFor="visitor-phone">
<span></span>
<input
id="visitor-phone"
name="phone"
type="tel"
inputMode="tel"
autoComplete="tel"
placeholder="请输入手机号"
value={phoneInput}
onChange={(event) => {
setPhoneInput(event.target.value);
if (formError) setFormError(null);
}}
aria-invalid={formError ? "true" : "false"}
aria-describedby={formError ? "visitor-phone-error" : "visitor-phone-help"}
/>
{formError ? <small id="visitor-phone-error" className="field-error" role="alert">{formError}</small> : null}
</label>
<button className="button button--primary button--wide" type="submit" disabled={resource.loading}>
{resource.loading ? "正在查询…" : "查询排队状态"}
</button>
</form>
<p id="visitor-phone-help" className="visitor-lookup-card__help"></p>
</section>
{resource.loading && !data ? <LoadingState label="正在查询您的排队号码" /> : null}
{resource.error && !data ? (
<FeedbackBanner
tone="danger"
title="暂时无法查询排队状态"
action={<button className="button button--secondary button--small" onClick={resource.refresh}></button>}
>
{resource.error.status === 429 ? "查询次数过多,请稍后再试。" : resource.error.message}
</FeedbackBanner>
) : null}
</div>
</main>
);
}

View File

@@ -3,8 +3,9 @@ import { useParams } from "react-router-dom";
import { api } from "../api";
import { EmptyState, FeedbackBanner, FreshnessBanner } from "../components/Feedback";
import { usePollingResource } from "../hooks/usePollingResource";
import { formatDateTime, formatEstimatedWait, isTimestampStale, visitorStatusMeta } from "../lib/format";
import { isTimestampStale } from "../lib/format";
import { gsap, useGSAP } from "../motion/gsap";
import { VisitorTicketCard } from "./VisitorTicketCard";
function VisitorLoadingState() {
return (
@@ -27,19 +28,10 @@ export function VisitorPage() {
resourceKey: token,
});
const data = resource.data;
const phoneLast4 = data?.phone_last4?.replace(/\D/g, "").slice(-4) || "未知";
const freshnessTime = resource.lastClientSuccessAt;
const stale = Boolean(data) && isTimestampStale(freshnessTime, 30_000);
const status = data?.status?.toUpperCase() ?? "";
const statusMeta = data ? visitorStatusMeta(data.status, data.people_ahead) : null;
const projectStatus = data?.project?.status?.toUpperCase();
const projectPaused = status === "WAITING" && projectStatus === "PAUSED";
const displayTone = projectPaused ? "warning" : statusMeta?.tone ?? "neutral";
const displayLabel = projectPaused ? "项目暂时暂停" : statusMeta?.label;
const lastUpdated = data?.last_updated_at || freshnessTime;
const visitorNotice = data?.visitor_notice == null
? "请您在景区附近等候,注意听从工作人员指引。"
: data.visitor_notice.trim();
const liveTone = resource.offline ? "offline" : stale || resource.error ? "stale" : "live";
const liveLabel = resource.offline ? "连接中断" : stale || resource.error ? "更新延迟" : "实时更新";
@@ -91,62 +83,7 @@ export function VisitorPage() {
errorMessage={resource.error?.message}
onRetry={resource.refresh}
/>
<article className={`visitor-ticket visitor-ticket--${displayTone}`} data-visitor-card>
<div className="visitor-ticket__topline" data-visitor-reveal>
<div>
<p className="visitor-ticket__project">{data.project_name}</p>
<h1 aria-live="polite">{displayLabel}</h1>
</div>
<span className="visitor-ticket__status-mark" aria-hidden="true" />
</div>
<div className="visitor-ticket__number" data-visitor-reveal>
<span></span>
<strong>{data.ticket_number}</strong>
</div>
<div className="visitor-ticket__metrics" data-visitor-reveal>
<div className="visitor-ticket__latest-called">
<span></span>
<strong>{data.latest_called_number || "暂无"}</strong>
</div>
{status === "WAITING" && !projectPaused ? (
<>
<div className="visitor-ticket__wait">
<span></span>
<strong>{formatEstimatedWait(data.estimated_wait)}</strong>
</div>
<div className="visitor-ticket__progress">
<span></span>
<strong>{data.people_ahead == null ? "未知" : `${data.people_ahead} 个号码`}</strong>
</div>
</>
) : null}
</div>
{status === "WAITING" && projectPaused ? (
<section className="visitor-ticket__service-status" aria-labelledby="visitor-paused-message" data-visitor-reveal>
<span id="visitor-paused-message"></span>
<strong></strong>
</section>
) : null}
{status === "CALLED" ? (
<div className="call-action" role="alert" aria-live="assertive" data-visitor-reveal>
<span></span>
<strong>{data.entrance || "现场入口"}</strong>
<p> {formatDateTime(data.called_at)}</p>
</div>
) : null}
{status !== "WAITING" && status !== "CALLED" ? <p className="visitor-ticket__guidance" data-visitor-reveal>{statusMeta?.guidance}</p> : null}
{data.message ? <p className="visitor-ticket__message" data-visitor-reveal>{data.message}</p> : null}
<div className="visitor-ticket__metadata" data-visitor-reveal>
<span aria-label={`联系手机号尾号 ${phoneLast4}`}><small></small><span>{`尾号 ${phoneLast4}`}</span></span>
<span> {formatDateTime(lastUpdated)}</span>
</div>
</article>
{visitorNotice ? (
<aside className="visitor-official-notice" data-visitor-reveal aria-label="官方提示">
<strong></strong>
<p>{visitorNotice}</p>
</aside>
) : null}
<VisitorTicketCard data={data} lastUpdatedAt={lastUpdated} />
<button className="button button--secondary visitor-refresh" onClick={resource.refresh}></button>
<p className="visitor-trust"></p>
</>

View File

@@ -0,0 +1,53 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
const navigate = vi.fn();
vi.mock("react-router-dom", () => ({
useLocation: () => ({ state: { phone: "13800138000" } }),
useNavigate: () => navigate,
}));
vi.mock("../hooks/usePollingResource", () => ({
usePollingResource: () => ({
data: {
tickets: [{
phone_last4: "8000",
project_name: "示范项目",
project: { id: "project-1", status: "RUNNING" },
ticket_number: "00012",
status: "WAITING",
people_ahead: 2,
latest_called_number: "00010",
estimated_wait: { min: 10, max: 15 },
}],
},
loading: false,
refreshing: false,
error: null,
offline: false,
lastClientSuccessAt: new Date().toISOString(),
refresh: vi.fn(),
}),
}));
import { VisitorPhonePage } from "./VisitorPhonePage";
describe("VisitorPhonePage", () => {
it("shows the number page without the phone input", () => {
render(<VisitorPhonePage />);
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
expect(screen.getByText("我的号码")).toBeVisible();
expect(screen.getByText("00012")).toBeVisible();
expect(screen.getByRole("button", { name: "刷新状态" })).toBeVisible();
expect(screen.getByRole("button", { name: "查询其他手机号" })).toBeVisible();
});
it("returns to the phone lookup without showing an input on the number page", () => {
render(<VisitorPhonePage />);
fireEvent.click(screen.getByRole("button", { name: "查询其他手机号" }));
expect(navigate).toHaveBeenCalledWith("/visitor");
});
});

View File

@@ -0,0 +1,168 @@
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { api } from "../api";
import { EmptyState, FeedbackBanner, FreshnessBanner, LoadingState } from "../components/Feedback";
import { usePollingResource } from "../hooks/usePollingResource";
import { isTimestampStale, visitorStatusMeta } from "../lib/format";
import type { PublicStatusDto } from "../types";
import { VisitorTicketCard } from "./VisitorTicketCard";
const PHONE_STORAGE_KEY = "scenic-visitor-query-phone";
function ticketKey(ticket: PublicStatusDto): string {
return `${ticket.project?.id ?? ticket.project_name}:${ticket.ticket_number}`;
}
function readStoredPhone(): string {
try {
return window.sessionStorage.getItem(PHONE_STORAGE_KEY) ?? "";
} catch {
return "";
}
}
function storePhone(phone: string): void {
try {
window.sessionStorage.setItem(PHONE_STORAGE_KEY, phone);
} catch {
// Session storage is only a refresh convenience for this temporary flow.
}
}
function clearStoredPhone(): void {
try {
window.sessionStorage.removeItem(PHONE_STORAGE_KEY);
} catch {
// Ignore storage failures; the page can still navigate normally.
}
}
interface VisitorPhoneLocationState {
phone?: string;
}
export function VisitorPhonePage() {
const location = useLocation();
const navigate = useNavigate();
const locationPhone = (location.state as VisitorPhoneLocationState | null)?.phone?.trim() ?? "";
const [phone] = useState(() => locationPhone || readStoredPhone());
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const resource = usePollingResource((signal) => api.publicStatusByPhone(phone, signal), {
enabled: Boolean(phone),
intervalMs: 3_000,
resourceKey: phone || "visitor-phone",
});
const data = resource.data;
const tickets = data?.tickets ?? [];
const selectedTicket = tickets.find((ticket) => ticketKey(ticket) === selectedKey) ?? tickets[0];
const freshnessTime = resource.lastClientSuccessAt;
const stale = Boolean(data) && isTimestampStale(freshnessTime, 30_000);
useEffect(() => {
if (locationPhone) storePhone(locationPhone);
}, [locationPhone]);
useEffect(() => {
if (!tickets.length) {
setSelectedKey(null);
return;
}
const currentKey = selectedKey && tickets.some((ticket) => ticketKey(ticket) === selectedKey)
? selectedKey
: ticketKey(tickets[0]);
if (currentKey !== selectedKey) setSelectedKey(currentKey);
}, [selectedKey, tickets]);
function returnToLookup() {
clearStoredPhone();
navigate("/visitor");
}
const liveTone = resource.offline ? "offline" : stale || resource.error ? "stale" : "live";
const liveLabel = resource.offline ? "连接中断" : stale || resource.error ? "更新延迟" : "实时更新";
return (
<main className="visitor-page visitor-page--mobile visitor-phone-page">
<header className="public-header visitor-public-header">
<div className="brand-lockup">
<img className="brand-logo" src="/xiaoqikong-logo.jpg" alt="" aria-hidden="true" />
<span><strong></strong><small></small></span>
</div>
<span className={`visitor-header__meta visitor-header__meta--${liveTone}`}><i aria-hidden="true" />{liveLabel}</span>
</header>
<div className="visitor-content">
{!phone ? (
<FeedbackBanner tone="warning" title="查询会话已失效" action={<button className="button button--secondary button--small" onClick={returnToLookup}></button>}>
</FeedbackBanner>
) : null}
{resource.loading && !data ? <LoadingState label="正在读取您的排队号码" /> : null}
{resource.error && !data ? (
<FeedbackBanner
tone="danger"
title="暂时无法读取排队状态"
action={<button className="button button--secondary button--small" onClick={resource.refresh}></button>}
>
{resource.error.status === 429 ? "查询次数过多,请稍后再试。" : resource.error.message}
</FeedbackBanner>
) : null}
{data ? (
<>
<FreshnessBanner
offline={resource.offline}
stale={stale}
timestamp={freshnessTime}
refreshing={resource.refreshing}
errorMessage={resource.error?.message}
onRetry={resource.refresh}
/>
{tickets.length === 0 ? (
<>
<EmptyState title="暂未找到活动排队号码" description="请核对手机号,或联系现场工作人员。" />
<button className="button button--secondary visitor-refresh" onClick={returnToLookup}></button>
</>
) : (
<>
{tickets.length > 1 ? (
<section className="visitor-lookup-results" aria-labelledby="visitor-lookup-results-title">
<div className="visitor-lookup-results__heading">
<div>
<span></span>
<h2 id="visitor-lookup-results-title"> {tickets.length} </h2>
</div>
<small></small>
</div>
<div className="visitor-lookup-options" role="list">
{tickets.map((ticket) => {
const key = ticketKey(ticket);
const statusMeta = visitorStatusMeta(ticket.status, ticket.people_ahead);
return (
<div key={key} role="listitem">
<button
className="visitor-lookup-option"
type="button"
aria-pressed={selectedTicket ? key === ticketKey(selectedTicket) : false}
onClick={() => setSelectedKey(key)}
>
<span>{ticket.project_name}</span>
<strong>{ticket.ticket_number}</strong>
<small>{statusMeta.label}</small>
</button>
</div>
);
})}
</div>
</section>
) : null}
{selectedTicket ? <VisitorTicketCard data={selectedTicket} lastUpdatedAt={freshnessTime} /> : null}
<button className="button button--secondary visitor-refresh" onClick={resource.refresh}></button>
<button className="button button--ghost visitor-refresh" onClick={returnToLookup}></button>
<p className="visitor-trust"></p>
</>
)}
</>
) : null}
</div>
</main>
);
}

View File

@@ -0,0 +1,80 @@
import type { PublicStatusDto } from "../types";
import { formatDateTime, formatEstimatedWait, visitorStatusMeta } from "../lib/format";
interface VisitorTicketCardProps {
data: PublicStatusDto;
lastUpdatedAt?: string | null;
}
export function VisitorTicketCard({ data, lastUpdatedAt }: VisitorTicketCardProps) {
const phoneLast4 = data.phone_last4?.replace(/\D/g, "").slice(-4) || "未知";
const status = data.status?.toUpperCase() ?? "";
const statusMeta = visitorStatusMeta(data.status, data.people_ahead);
const projectPaused = status === "WAITING" && data.project?.status?.toUpperCase() === "PAUSED";
const displayTone = projectPaused ? "warning" : statusMeta.tone;
const displayLabel = projectPaused ? "项目暂时暂停" : statusMeta.label;
const visitorNotice = data.visitor_notice == null
? "请您在景区附近等候,注意听从工作人员指引。"
: data.visitor_notice.trim();
return (
<>
<article className={`visitor-ticket visitor-ticket--${displayTone}`} data-visitor-card>
<div className="visitor-ticket__topline" data-visitor-reveal>
<div>
<p className="visitor-ticket__project">{data.project_name}</p>
<h1 aria-live="polite">{displayLabel}</h1>
</div>
<span className="visitor-ticket__status-mark" aria-hidden="true" />
</div>
<div className="visitor-ticket__number" data-visitor-reveal>
<span></span>
<strong>{data.ticket_number}</strong>
</div>
<div className="visitor-ticket__metrics" data-visitor-reveal>
<div className="visitor-ticket__latest-called">
<span></span>
<strong>{data.latest_called_number || "暂无"}</strong>
</div>
{status === "WAITING" && !projectPaused ? (
<>
<div className="visitor-ticket__wait">
<span></span>
<strong>{formatEstimatedWait(data.estimated_wait)}</strong>
</div>
<div className="visitor-ticket__progress">
<span></span>
<strong>{data.people_ahead == null ? "未知" : `${data.people_ahead} 个号码`}</strong>
</div>
</>
) : null}
</div>
{status === "WAITING" && projectPaused ? (
<section className="visitor-ticket__service-status" aria-label="服务状态" data-visitor-reveal>
<span></span>
<strong></strong>
</section>
) : null}
{status === "CALLED" ? (
<div className="call-action" role="alert" aria-live="assertive" data-visitor-reveal>
<span></span>
<strong>{data.entrance || "现场入口"}</strong>
<p> {formatDateTime(data.called_at)}</p>
</div>
) : null}
{status !== "WAITING" && status !== "CALLED" ? <p className="visitor-ticket__guidance" data-visitor-reveal>{statusMeta.guidance}</p> : null}
{data.message ? <p className="visitor-ticket__message" data-visitor-reveal>{data.message}</p> : null}
<div className="visitor-ticket__metadata" data-visitor-reveal>
<span aria-label={`联系手机号尾号 ${phoneLast4}`}><small></small><span>{`尾号 ${phoneLast4}`}</span></span>
<span> {formatDateTime(lastUpdatedAt || data.last_updated_at)}</span>
</div>
</article>
{visitorNotice ? (
<aside className="visitor-official-notice" data-visitor-reveal aria-label="官方提示">
<strong></strong>
<p>{visitorNotice}</p>
</aside>
) : null}
</>
);
}