From ddabe87578f4a65c206a4247e81771053c416a14 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 00:24:25 +0800 Subject: [PATCH 1/2] fix(web): address round-4 frontend review findings - FE-Q1: move hardcoded toast copy to i18n with matching en/zh-CN keys. - FE-Q2: extract shared ConfirmDialog and a RESEND_COUNTDOWN_SECONDS constant. - FE-Q3: normalize SQLite 0/1 flags to booleans in the API client and update types/usages. - FE-R4: retry queries only on transport/5xx errors and debounce list search by 300ms. - FE-R5: keep ?next= through expiry and login (same-origin paths only) and surface clipboard failures. - FE-C5: minutes for sub-hour expiry plus unit validation, disable admin controls while mutating, sync analytics params with history, count down from an absolute deadline. - #6: emit the session-expired toast once per expiry instead of once per request. - BE-Q2 (web): cover refresh outcomes, cross-tab locking and dedup with node:test. Checkpoint: rOmcynJUsp5cIiDIEfUC5 --- apps/web/package.json | 1 + apps/web/src/App.tsx | 22 +- apps/web/src/api/client.test.ts | 289 ++++++++++++++++++ apps/web/src/api/client.ts | 202 +++++++++--- apps/web/src/components/confirm-dialog.tsx | 53 ++++ apps/web/src/components/link-table-cells.tsx | 44 ++- apps/web/src/contexts/AuthContext.tsx | 21 +- apps/web/src/hooks/use-countdown.ts | 27 +- apps/web/src/hooks/use-debounced-value.ts | 13 + apps/web/src/i18n/locales/en.ts | 40 +++ apps/web/src/i18n/locales/zh-CN.ts | 40 +++ apps/web/src/lib/constants.ts | 7 + apps/web/src/lib/toast.ts | 12 + apps/web/src/lib/utils.test.ts | 95 ++++++ apps/web/src/lib/utils.ts | 74 ++++- apps/web/src/main.tsx | 7 +- apps/web/src/pages/admin/AdminLinksPage.tsx | 53 ++-- .../web/src/pages/admin/AdminSettingsPage.tsx | 19 +- apps/web/src/pages/admin/AdminUsersPage.tsx | 77 ++--- .../web/src/pages/auth/ForgotPasswordPage.tsx | 10 +- apps/web/src/pages/auth/LoginPage.tsx | 17 +- apps/web/src/pages/auth/RegisterPage.tsx | 12 +- apps/web/src/pages/auth/TwoFactorPage.tsx | 31 +- .../web/src/pages/dashboard/AnalyticsPage.tsx | 75 ++++- apps/web/src/pages/dashboard/LinksPage.tsx | 60 ++-- apps/web/src/pages/dashboard/SettingsPage.tsx | 42 +-- 26 files changed, 1109 insertions(+), 234 deletions(-) create mode 100644 apps/web/src/api/client.test.ts create mode 100644 apps/web/src/components/confirm-dialog.tsx create mode 100644 apps/web/src/hooks/use-debounced-value.ts create mode 100644 apps/web/src/lib/constants.ts create mode 100644 apps/web/src/lib/toast.ts create mode 100644 apps/web/src/lib/utils.test.ts diff --git a/apps/web/package.json b/apps/web/package.json index aa40b54..1f37f3e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,6 +7,7 @@ "dev": "vite", "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", + "test": "node --test src/api/client.test.ts src/lib/utils.test.ts", "preview": "vite preview" }, "dependencies": { diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 6f76da1..94524c1 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,8 +1,9 @@ import { lazy, type ReactNode, Suspense } from 'react'; -import { Link, Navigate, Route, Routes } from 'react-router-dom'; +import { Link, Navigate, Route, Routes, useLocation } from 'react-router-dom'; import { Button } from './components/ui/button.tsx'; import { useAuth } from './contexts/AuthContext.tsx'; import { useTranslation } from './i18n/index.tsx'; +import { buildLoginRedirect } from './lib/utils.ts'; const AdminLayout = lazy(() => import('./components/layout/AdminLayout.tsx')); const DashboardLayout = lazy( @@ -51,17 +52,32 @@ function SessionRestoreFailed() { function ProtectedRoute({ children }: { children: ReactNode }) { const { user, isLoading, restoreFailed } = useAuth(); + const location = useLocation(); if (isLoading) return ; if (!user && restoreFailed) return ; - if (!user) return ; + // FE-R5: remember where the user was so signing in returns them there. + if (!user) + return ( + + ); return <>{children}; } function AdminRoute({ children }: { children: ReactNode }) { const { user, isLoading, restoreFailed } = useAuth(); + const location = useLocation(); if (isLoading) return ; if (!user && restoreFailed) return ; - if (!user) return ; + if (!user) + return ( + + ); if (user.role !== 'admin') return ; return <>{children}; } diff --git a/apps/web/src/api/client.test.ts b/apps/web/src/api/client.test.ts new file mode 100644 index 0000000..d39cd21 --- /dev/null +++ b/apps/web/src/api/client.test.ts @@ -0,0 +1,289 @@ +import assert from 'node:assert/strict'; +import { afterEach, beforeEach, describe, test } from 'node:test'; +import { + ApiRequestError, + authApi, + getAccessToken, + isRetryableError, + isSessionExpiredError, + linksApi, + refreshSession, + SessionExpiredError, + setAccessToken, + setSessionExpiredHandler, +} from './client.ts'; + +// BE-Q2 (frontend half): the refresh path has three outcomes — ok, expired and +// transient — plus cross-tab serialization and in-flight dedup. These tests pin +// that behaviour down with a stubbed fetch, no extra dependencies. + +const originalFetch = globalThis.fetch; +const originalNavigator = Object.getOwnPropertyDescriptor( + globalThis, + 'navigator', +); + +type FetchCall = { url: string; init?: RequestInit }; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function mockFetch( + handler: (url: string, init?: RequestInit) => Response | Promise, +): FetchCall[] { + const calls: FetchCall[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + calls.push({ url, init }); + return handler(url, init); + }) as typeof fetch; + return calls; +} + +function headerValue( + init: RequestInit | undefined, + name: string, +): string | null { + return new Headers(init?.headers as HeadersInit | undefined).get(name); +} + +beforeEach(() => { + // `sessionExpiredHandled` is sticky for a session; a fresh token resets it. + setAccessToken('test-reset'); + setAccessToken(null); + setSessionExpiredHandler(null); +}); + +afterEach(() => { + globalThis.fetch = originalFetch; + if (originalNavigator) { + Object.defineProperty(globalThis, 'navigator', originalNavigator); + } +}); + +describe('refreshSession outcomes', () => { + test('ok stores the new access token', async () => { + mockFetch((url) => { + assert.match(url, /\/auth\/refresh$/); + return jsonResponse({ accessToken: 'token-1' }); + }); + + assert.equal(await refreshSession(), 'ok'); + assert.equal(getAccessToken(), 'token-1'); + }); + + test('a rejected refresh cookie is expired', async () => { + mockFetch(() => jsonResponse({ error: 'Invalid refresh token' }, 401)); + + assert.equal(await refreshSession(), 'expired'); + assert.equal(getAccessToken(), null); + }); + + test('a transport failure is transient, not expired', async () => { + mockFetch(() => { + throw new TypeError('Failed to fetch'); + }); + + assert.equal(await refreshSession(), 'transient'); + }); + + test('5xx, 408 and 429 are transient', async () => { + for (const status of [500, 502, 503, 408, 429]) { + mockFetch(() => jsonResponse({ error: 'later' }, status)); + assert.equal(await refreshSession(), 'transient', `status ${status}`); + } + }); + + test('a 200 without an access token is transient', async () => { + mockFetch(() => jsonResponse({})); + + assert.equal(await refreshSession(), 'transient'); + }); +}); + +describe('refresh concurrency', () => { + test('concurrent callers share one refresh request', async () => { + let release: ((response: Response) => void) | undefined; + const calls = mockFetch( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + + const first = refreshSession(); + const second = refreshSession(); + await Promise.resolve(); + assert.ok(release); + release(jsonResponse({ accessToken: 'shared-token' })); + + assert.deepEqual(await Promise.all([first, second]), ['ok', 'ok']); + assert.equal(calls.length, 1); + }); + + test('the refresh is serialized through the Web Locks API', async () => { + const requested: string[] = []; + Object.defineProperty(globalThis, 'navigator', { + configurable: true, + value: { + locks: { + request: async ( + name: string, + _options: unknown, + callback: () => Promise, + ) => { + requested.push(name); + return callback(); + }, + }, + }, + }); + mockFetch(() => jsonResponse({ accessToken: 'locked-token' })); + + assert.equal(await refreshSession(), 'ok'); + assert.deepEqual(requested, ['auth-refresh']); + assert.equal(getAccessToken(), 'locked-token'); + }); + + test('falls back to a direct call when Web Locks is unavailable', async () => { + Object.defineProperty(globalThis, 'navigator', { + configurable: true, + value: {}, + }); + const calls = mockFetch(() => jsonResponse({ accessToken: 'plain-token' })); + + assert.equal(await refreshSession(), 'ok'); + assert.equal(calls.length, 1); + }); +}); + +describe('request() after a 401', () => { + test('retries once with the refreshed token and normalizes booleans', async () => { + const calls = mockFetch((url, init) => { + if (url.endsWith('/auth/refresh')) { + return jsonResponse({ accessToken: 'fresh-token' }); + } + assert.match(url, /\/auth\/me$/); + if (headerValue(init, 'authorization') === 'Bearer fresh-token') { + return jsonResponse({ + user: { + id: 'u1', + email: 'a@example.com', + username: 'alice', + role: 'user', + is_active: 1, + totp_enabled: 0, + email_2fa_enabled: 1, + passkey_enabled: 0, + created_at: 1, + }, + }); + } + return jsonResponse({ error: 'Unauthorized' }, 401); + }); + setAccessToken('stale-token'); + + const { user } = await authApi.me(); + + assert.equal(user.is_active, true); + assert.equal(user.totp_enabled, false); + assert.equal(user.email_2fa_enabled, true); + assert.equal(user.passkey_enabled, false); + assert.equal(calls.length, 3); + }); + + test('reports an expired session once across concurrent requests', async () => { + let handled = 0; + setAccessToken('stale-token'); + setSessionExpiredHandler(() => { + handled += 1; + }); + mockFetch((url) => { + if (url.endsWith('/auth/refresh')) { + return jsonResponse({ error: 'Invalid refresh token' }, 401); + } + return jsonResponse({ error: 'Unauthorized' }, 401); + }); + + const results = await Promise.allSettled([authApi.me(), authApi.me()]); + + assert.equal(handled, 1); + for (const result of results) { + assert.equal(result.status, 'rejected'); + if (result.status === 'rejected') { + assert.ok(isSessionExpiredError(result.reason)); + } + } + }); + + test('a 4xx other than 401 is final and keeps its status', async () => { + const calls = mockFetch(() => + jsonResponse({ error: 'Validation failed' }, 400), + ); + setAccessToken('token'); + + await assert.rejects(authApi.me(), (error: unknown) => { + assert.ok(error instanceof ApiRequestError); + assert.equal(error.status, 400); + assert.equal(error.message, 'Validation failed'); + return true; + }); + assert.equal(calls.length, 1); + }); +}); + +describe('link boolean normalization (FE-Q3)', () => { + test('list() turns SQLite 0/1 into booleans', async () => { + setAccessToken('token'); + mockFetch(() => + jsonResponse({ + links: [ + { + id: 'l1', + slug: 'one', + destination_url: 'https://example.com', + title: null, + expires_at: null, + is_active: 1, + user_seq: 1, + created_at: 1, + }, + { + id: 'l2', + slug: 'two', + destination_url: 'https://example.com', + title: null, + expires_at: null, + is_active: 0, + user_seq: 2, + created_at: 1, + }, + ], + pagination: { page: 1, limit: 20, total: 2, pages: 1 }, + }), + ); + + const { links } = await linksApi.list(); + + assert.equal(links[0]?.is_active, true); + assert.equal(links[1]?.is_active, false); + }); +}); + +describe('isRetryableError (FE-R4)', () => { + test('retries transport errors and 5xx only', () => { + assert.equal(isRetryableError(new TypeError('Failed to fetch')), true); + assert.equal(isRetryableError(new ApiRequestError('boom', 500)), true); + assert.equal(isRetryableError(new ApiRequestError('nope', 400)), false); + assert.equal(isRetryableError(new ApiRequestError('nope', 404)), false); + assert.equal(isRetryableError(new ApiRequestError('expired', 401)), false); + }); + + test('never retries an expired session', () => { + assert.equal(isRetryableError(new SessionExpiredError()), false); + }); +}); diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index b9a0f1b..25a7911 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -28,7 +28,16 @@ function handleSessionExpired() { if (sessionExpiredHandled) return; sessionExpiredHandled = true; if (sessionExpiredHandler) sessionExpiredHandler(); - else window.location.assign('/login'); + else { + // No in-SPA handler registered (should not happen inside AuthProvider): + // keep the destination so the user returns after signing in again. + const next = `${window.location.pathname}${window.location.search}`; + window.location.assign( + next.startsWith('/login') + ? '/login' + : `/login?next=${encodeURIComponent(next)}`, + ); + } } const BASE = '/api'; @@ -37,6 +46,41 @@ interface ApiError { error: string; } +// FE-R4: react-query only retries transport failures and server errors. A 4xx +// is the server's final answer (validation, auth, not found); retrying it just +// delays the error the user needs to see. +export class ApiRequestError extends Error { + readonly status: number; + + constructor(message: string, status: number) { + super(message); + this.name = 'ApiRequestError'; + this.status = status; + } +} + +// #6: the session is over — every request waiting on the same refresh sees this +// error, so the UI layer must not toast once per request. `isSessionExpiredError` +// lets callers skip their own error toast; AuthProvider shows a single one. +export class SessionExpiredError extends Error { + constructor() { + super('Session expired'); + this.name = 'SessionExpiredError'; + } +} + +export function isSessionExpiredError(error: unknown): boolean { + return error instanceof SessionExpiredError; +} + +export function isRetryableError(error: unknown): boolean { + if (isSessionExpiredError(error)) return false; + if (error instanceof ApiRequestError) return error.status >= 500; + // Anything without a status (fetch TypeError, timeout, the 'transient' + // refresh outcome) is a transport problem that may succeed on retry. + return true; +} + async function request( path: string, options: RequestInit & { skipAuth?: boolean } = {}, @@ -71,7 +115,7 @@ async function request( const err = (await retryRes .json() .catch(() => ({ error: 'Request failed' }))) as ApiError; - throw new Error(err.error); + throw new ApiRequestError(err.error, retryRes.status); } return retryRes.json() as Promise; } @@ -83,14 +127,14 @@ async function request( } // The server rejected the refresh cookie — the session is really over. handleSessionExpired(); - throw new Error('Session expired'); + throw new SessionExpiredError(); } if (!res.ok) { const err = (await res .json() .catch(() => ({ error: 'Request failed' }))) as ApiError; - throw new Error(err.error); + throw new ApiRequestError(err.error, res.status); } if (res.status === 204) return undefined as T; @@ -170,13 +214,50 @@ export interface User { email: string; username: string; role: 'admin' | 'user'; - is_active: number; - totp_enabled: number; - email_2fa_enabled: number; - passkey_enabled: number; + is_active: boolean; + totp_enabled: boolean; + email_2fa_enabled: boolean; + passkey_enabled: boolean; created_at: number; } +// FE-Q3: SQLite has no boolean type — flag columns come back as 0/1 numbers. +// They are normalized once, at the client boundary, so pages deal in real +// booleans instead of sprinkling `!!x` (one forgotten coercion makes 0 truthy). +type Booleanish = boolean | number | null | undefined; + +interface WireUser { + id: string; + email: string; + username: string; + role: 'admin' | 'user'; + is_active?: Booleanish; + totp_enabled?: Booleanish; + email_2fa_enabled?: Booleanish; + passkey_enabled?: Booleanish; + created_at?: number; +} + +function asBoolean(value: Booleanish): boolean { + return value === true || value === 1; +} + +function normalizeUser(user: WireUser): User { + // Login and /auth/me return only id/email/username/role, so flag columns are + // absent there and default to false; the admin user list sends real values. + return { + id: user.id, + email: user.email, + username: user.username, + role: user.role, + is_active: asBoolean(user.is_active), + totp_enabled: asBoolean(user.totp_enabled), + email_2fa_enabled: asBoolean(user.email_2fa_enabled), + passkey_enabled: asBoolean(user.passkey_enabled), + created_at: user.created_at ?? 0, + }; +} + export interface LoginResult { requiresTwoFactor?: boolean; pendingToken?: string; @@ -185,28 +266,47 @@ export interface LoginResult { user?: User; } +interface WireLoginResult extends Omit { + user?: WireUser; +} + +function normalizeLoginResult(result: WireLoginResult): LoginResult { + const { user, ...rest } = result; + return user ? { ...rest, user: normalizeUser(user) } : rest; +} + export interface RegisterResult { user?: User; requiresEmailVerification?: boolean; userId?: string; } +interface WireRegisterResult extends Omit { + user?: WireUser; +} + export const authApi = { register: (email: string, username: string, password: string) => - request('/auth/register', { + request('/auth/register', { method: 'POST', body: JSON.stringify({ email, username, password }), skipAuth: true, + }).then((result) => { + const { user, ...rest } = result; + return user ? { ...rest, user: normalizeUser(user) } : rest; }), login: (email: string, password: string) => - request('/auth/login', { + request('/auth/login', { method: 'POST', body: JSON.stringify({ email, password }), skipAuth: true, - }), + }).then(normalizeLoginResult), - me: () => request<{ user: User }>('/auth/me'), + me: () => + request<{ user: WireUser }>('/auth/me').then((result) => ({ + user: normalizeUser(result.user), + })), logout: () => request<{ success: boolean }>('/auth/logout', { method: 'POST' }), @@ -226,11 +326,11 @@ export const authApi = { // Email verification (registration) verifyEmail: (userId: string, code: string) => - request('/auth/verify-email', { + request('/auth/verify-email', { method: 'POST', body: JSON.stringify({ userId, code }), skipAuth: true, - }), + }).then(normalizeLoginResult), resendVerifyEmail: (userId: string) => request<{ success: boolean }>('/auth/resend-verify-email', { method: 'POST', @@ -275,11 +375,11 @@ export const authApi = { body: JSON.stringify({ currentPassword }), }), totpVerify: (pendingToken: string, code: string) => - request('/auth/2fa/totp/verify', { + request('/auth/2fa/totp/verify', { method: 'POST', body: JSON.stringify({ pendingToken, code }), skipAuth: true, - }), + }).then(normalizeLoginResult), // Email OTP emailOtpSendVerify: () => @@ -303,11 +403,11 @@ export const authApi = { skipAuth: true, }), emailOtpVerify: (pendingToken: string, code: string) => - request('/auth/2fa/email-otp/verify', { + request('/auth/2fa/email-otp/verify', { method: 'POST', body: JSON.stringify({ pendingToken, code }), skipAuth: true, - }), + }).then(normalizeLoginResult), // Passkey passkeyList: () => @@ -356,11 +456,11 @@ export const authApi = { response: AuthenticationResponseJSON, challengeId: string, ) => - request('/auth/2fa/passkey/verify', { + request('/auth/2fa/passkey/verify', { method: 'POST', body: JSON.stringify({ pendingToken, response, challengeId }), skipAuth: true, - }), + }).then(normalizeLoginResult), }; // ─── Links API ──────────────────────────────────────────────────────────────── @@ -371,13 +471,35 @@ export interface Link { destination_url: string; title: string | null; expires_at: number | null; - is_active: number; + is_active: boolean; user_seq: number; created_at: number; updated_at?: number; click_count?: number; } +// FE-Q3: wire shape of a link — `is_active` arrives as SQLite's 0/1. +interface WireLink { + id: string; + slug: string; + destination_url: string; + title: string | null; + expires_at: number | null; + is_active?: Booleanish; + user_seq: number; + created_at: number; + updated_at?: number; + click_count?: number; +} + +// Generic over extra columns (admin links carry seq/user_email) so the +// normalized result keeps them. +function normalizeLink( + link: T, +): Omit & { is_active: boolean } { + return { ...link, is_active: asBoolean(link.is_active) }; +} + export interface CreateLinkPayload { destinationUrl: string; customSlug?: string; @@ -393,24 +515,30 @@ export const linksApi = { if (params?.limit) qs.set('limit', String(params.limit)); if (params?.search) qs.set('search', params.search); return request<{ - links: Link[]; + links: WireLink[]; pagination: { page: number; limit: number; total: number; pages: number }; - }>(`/links?${qs}`); + }>(`/links?${qs}`).then((result) => ({ + ...result, + links: result.links.map(normalizeLink), + })); }, - get: (id: string) => request<{ link: Link }>(`/links/${id}`), + get: (id: string) => + request<{ link: WireLink }>(`/links/${id}`).then((result) => ({ + link: normalizeLink(result.link), + })), create: (payload: CreateLinkPayload) => - request<{ link: Link }>('/links', { + request<{ link: WireLink }>('/links', { method: 'POST', body: JSON.stringify(payload), - }), + }).then((result) => ({ link: normalizeLink(result.link) })), update: ( id: string, payload: Partial, ) => - request<{ link: Link }>(`/links/${id}`, { + request<{ link: WireLink }>(`/links/${id}`, { method: 'PUT', body: JSON.stringify(payload), - }), + }).then((result) => ({ link: normalizeLink(result.link) })), delete: (id: string) => request<{ success: boolean }>(`/links/${id}`, { method: 'DELETE' }), }; @@ -467,9 +595,12 @@ export const adminApi = { if (params?.page) qs.set('page', String(params.page)); if (params?.search) qs.set('search', params.search); return request<{ - users: User[]; + users: WireUser[]; pagination: { page: number; limit: number; total: number; pages: number }; - }>(`/admin/users?${qs}`); + }>(`/admin/users?${qs}`).then((result) => ({ + ...result, + users: result.users.map(normalizeUser), + })); }, updateUser: ( id: string, @@ -488,10 +619,13 @@ export const adminApi = { if (params?.userId) qs.set('userId', params.userId); return request<{ links: Array< - Link & { seq: number; user_email: string; user_username: string } + WireLink & { seq: number; user_email: string; user_username: string } >; pagination: { page: number; limit: number; total: number; pages: number }; - }>(`/admin/links?${qs}`); + }>(`/admin/links?${qs}`).then((result) => ({ + ...result, + links: result.links.map(normalizeLink), + })); }, createUser: (payload: { email: string; @@ -499,10 +633,10 @@ export const adminApi = { password: string; role?: 'admin' | 'user'; }) => - request<{ user: User }>('/admin/users', { + request<{ user: WireUser }>('/admin/users', { method: 'POST', body: JSON.stringify(payload), - }), + }).then((result) => ({ user: normalizeUser(result.user) })), getSettings: () => request<{ settings: Record }>('/admin/settings'), updateSettings: (settings: Record) => diff --git a/apps/web/src/components/confirm-dialog.tsx b/apps/web/src/components/confirm-dialog.tsx new file mode 100644 index 0000000..eab5b7a --- /dev/null +++ b/apps/web/src/components/confirm-dialog.tsx @@ -0,0 +1,53 @@ +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; + +// FE-Q2: the three list pages each carried a copy-pasted delete confirmation. +export function ConfirmDialog({ + open, + onOpenChange, + title, + description, + confirmLabel, + cancelLabel, + onConfirm, + loading = false, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + description: string; + confirmLabel: string; + cancelLabel: string; + onConfirm: () => void; + loading?: boolean; +}) { + return ( + + + + {title} + {description} + + + + + + + + ); +} diff --git a/apps/web/src/components/link-table-cells.tsx b/apps/web/src/components/link-table-cells.tsx index ef874d3..acdcb50 100644 --- a/apps/web/src/components/link-table-cells.tsx +++ b/apps/web/src/components/link-table-cells.tsx @@ -8,23 +8,26 @@ import { useTranslation } from '@/i18n'; import { buildShortUrl, copyToClipboard, - expiryLabel, + expiryParts, isExpired, isSafeUrl, } from '@/lib/utils'; export function LinkSlugCell({ slug }: { slug: string }) { + const { t } = useTranslation(); return (
{slug} - - - - + !o && setDeleteId(null)} + title={t('admin.deleteLink')} + description={t('admin.deleteLinkDesc')} + confirmLabel={t('common.delete')} + cancelLabel={t('common.cancel')} + loading={deleteMutation.isPending} + onConfirm={() => deleteId && deleteMutation.mutate(deleteId)} + />
); } diff --git a/apps/web/src/pages/admin/AdminSettingsPage.tsx b/apps/web/src/pages/admin/AdminSettingsPage.tsx index cf6107b..7d77ab0 100644 --- a/apps/web/src/pages/admin/AdminSettingsPage.tsx +++ b/apps/web/src/pages/admin/AdminSettingsPage.tsx @@ -15,6 +15,7 @@ import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { useAppConfig } from '@/contexts/AppConfigContext'; import { useTranslation } from '@/i18n'; +import { toastApiError } from '@/lib/toast'; export default function AdminSettingsPage() { const { t } = useTranslation(); @@ -78,10 +79,14 @@ export default function AdminSettingsPage() { await adminApi.updateSettings({ registration_enabled: enabled ? 'true' : 'false', }); - toast.success(`Registration ${enabled ? 'enabled' : 'disabled'}`); + toast.success( + enabled + ? t('toast.registrationEnabled') + : t('toast.registrationDisabled'), + ); } catch (err) { setRegistrationEnabled(!enabled); - toast.error(err instanceof Error ? err.message : 'Failed'); + toastApiError(err, t('toast.requestFailed')); } }; @@ -98,7 +103,7 @@ export default function AdminSettingsPage() { ); } catch (err) { setRequireEmailVerification(!enabled); - toast.error(err instanceof Error ? err.message : 'Failed'); + toastApiError(err, t('toast.requestFailed')); } }; @@ -108,9 +113,9 @@ export default function AdminSettingsPage() { try { await adminApi.updateSettings({ app_name: appName }); reloadAppConfig(); - toast.success('App name updated'); + toast.success(t('toast.appNameUpdated')); } catch (err) { - toast.error(err instanceof Error ? err.message : 'Failed'); + toastApiError(err, t('toast.requestFailed')); } finally { setSavingAppName(false); } @@ -134,9 +139,9 @@ export default function AdminSettingsPage() { if (resendApiKey !== '') payload.resend_api_key = resendApiKey; if (smtpPass !== '') payload.smtp_pass = smtpPass; await adminApi.updateSettings(payload); - toast.success('Email settings saved'); + toast.success(t('toast.emailSettingsSaved')); } catch (err) { - toast.error(err instanceof Error ? err.message : 'Failed'); + toastApiError(err, t('toast.requestFailed')); } finally { setSavingEmail(false); } diff --git a/apps/web/src/pages/admin/AdminUsersPage.tsx b/apps/web/src/pages/admin/AdminUsersPage.tsx index 5de72d4..863558e 100644 --- a/apps/web/src/pages/admin/AdminUsersPage.tsx +++ b/apps/web/src/pages/admin/AdminUsersPage.tsx @@ -3,6 +3,7 @@ import { Search, Trash2, UserPlus } from 'lucide-react'; import { useState } from 'react'; import { toast } from 'sonner'; import { adminApi } from '@/api/client'; +import { ConfirmDialog } from '@/components/confirm-dialog'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { @@ -16,7 +17,10 @@ import { import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { useAuth } from '@/contexts/AuthContext'; +import { useDebouncedValue } from '@/hooks/use-debounced-value'; import { useTranslation } from '@/i18n'; +import { SEARCH_DEBOUNCE_MS } from '@/lib/constants'; +import { toastApiError } from '@/lib/toast'; import { formatDate } from '@/lib/utils'; export default function AdminUsersPage() { @@ -24,13 +28,15 @@ export default function AdminUsersPage() { const { t } = useTranslation(); const queryClient = useQueryClient(); const [search, setSearch] = useState(''); + const debouncedSearch = useDebouncedValue(search, SEARCH_DEBOUNCE_MS); const [page, setPage] = useState(1); const [deleteId, setDeleteId] = useState(null); const [showCreate, setShowCreate] = useState(false); const { data, isLoading } = useQuery({ - queryKey: ['admin-users', page, search], - queryFn: () => adminApi.users({ page, search: search || undefined }), + queryKey: ['admin-users', page, debouncedSearch], + queryFn: () => + adminApi.users({ page, search: debouncedSearch || undefined }), }); const updateMutation = useMutation({ @@ -43,23 +49,30 @@ export default function AdminUsersPage() { }) => adminApi.updateUser(id, payload), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin-users'] }); - toast.success('User updated'); + toast.success(t('toast.userUpdated')); }, - onError: (err) => - toast.error(err instanceof Error ? err.message : 'Failed'), + onError: (err) => toastApiError(err, t('toast.updateUserFailed')), }); const deleteMutation = useMutation({ mutationFn: (id: string) => adminApi.deleteUser(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin-users'] }); - toast.success('User deleted'); + toast.success(t('toast.userDeleted')); setDeleteId(null); }, - onError: (err) => - toast.error(err instanceof Error ? err.message : 'Failed'), + onError: (err) => toastApiError(err, t('toast.deleteUserFailed')), }); + // FE-C5: one mutation in flight at a time per row — a double click used to + // fire two racing PATCH/DELETE requests with conflicting payloads. + const updatePendingId = updateMutation.isPending + ? updateMutation.variables?.id + : undefined; + const deletePendingId = deleteMutation.isPending + ? deleteMutation.variables + : undefined; + return (
@@ -126,7 +139,9 @@ export default function AdminUsersPage() { updateMutation.mutate({ id: u.id, @@ -176,9 +177,7 @@ export default function AdminUsersPage() {