Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep a Number Checker run going across pages

Yudhi Armyndhariseaf531abf660
diff --git a/dashboard/src/App.test.ts b/dashboard/src/App.test.ts
index 46e68aa90..c525e8ad6 100644
--- a/dashboard/src/App.test.ts
+++ b/dashboard/src/App.test.ts
@@ -22,7 +22,10 @@ function installFetchStub(): void {
if (path === '/api/auth/validate') return Promise.resolve(jsonResponse({ valid: true, role, scoped }));
if (path === '/api/audit' || path.startsWith('/api/audit?'))
return Promise.resolve(jsonResponse({ data: [], total: 0 }));
- if (path === '/api/sessions' || path === '/api/webhooks') return Promise.resolve(jsonResponse([]));
+ // One ready session: the Number Checker runs below need one, and the app's query cache keeps the first answer.
+ if (path === '/api/sessions')
+ return Promise.resolve(jsonResponse([{ id: 's1', name: 'Primary', status: 'ready', phone: '1' }]));
+ if (path === '/api/webhooks') return Promise.resolve(jsonResponse([]));
return Promise.resolve(jsonResponse({ message: `unstubbed ${path}` }, 404));
}) as typeof fetch;
}
@@ -163,3 +166,68 @@ test('a startup validation that lands after a sign-in with another key is ignore
globalThis.fetch = previous;
}
});
+
+// The Number Checker page is a lazy route, so a bulk run held by the page itself ends with the page. These go
+// through the real App: the run has to survive a move to another route, and end with a logout.
+const THREE_NUMBERS = '911111111111\n912222222222\n913333333333';
+
+async function startBulkRun(role = 'operator'): Promise<{ lookups: string[]; restore: () => void }> {
+ const previous = globalThis.fetch;
+ const lookups: string[] = [];
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ if (url.includes('/contacts/check/')) {
+ const number = url.split('/contacts/check/')[1];
+ lookups.push(number);
+ return Promise.resolve(jsonResponse({ number, exists: true, whatsappId: `${number}@c.us` }));
+ }
+ return previous(input, init);
+ }) as typeof fetch;
+ renderAt('/number-checker', role);
+ rtl.fireEvent.click(await rtl.screen.findByRole('tab', { name: /Bulk/i }, { timeout: 10_000 }));
+ await rtl.screen.findByRole('option', { name: /Primary/ });
+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText(/9612345678/i), { target: { value: THREE_NUMBERS } });
+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Start Batch Check/i }));
+ await rtl.waitFor(() => assert.equal(lookups.length, 1));
+ return { lookups, restore: () => (globalThis.fetch = previous) };
+}
+
+test('a bulk Number Checker run goes on while another page is open and is there when the page is opened again', async () => {
+ const { lookups, restore } = await startBulkRun();
+ try {
+ rtl.fireEvent.click(document.querySelector('a[href="/webhooks"]')!);
+ // Compared as a boolean: a failed assert.equal on a DOM node formats the whole jsdom tree and stalls the runner.
+ await rtl.waitFor(() => assert.equal(document.querySelector('.number-checker') === null, true));
+ assert.equal(window.location.pathname, '/webhooks');
+ await rtl.waitFor(() => assert.equal(lookups.length, 3), { timeout: 5_000 });
+
+ rtl.fireEvent.click(document.querySelector('a[href="/number-checker"]')!);
+ await rtl.waitFor(() => assert.ok(document.querySelector('.number-checker')), { timeout: 10_000 });
+ const rows = () => document.querySelectorAll('.nc-history-table tbody tr').length;
+ await rtl.waitFor(() => assert.equal(rows(), 3));
+ assert.deepEqual(lookups, ['911111111111', '912222222222', '913333333333']);
+ } finally {
+ restore();
+ }
+});
+
+test('signing out ends a bulk Number Checker run, and the next sign-in starts with no rows', async () => {
+ const { lookups, restore } = await startBulkRun();
+ try {
+ rtl.fireEvent.click(document.querySelector('.logout-btn')!);
+ await rtl.waitFor(() => assert.ok(document.getElementById('apiKey')));
+ await new Promise(resolve => setTimeout(resolve, 1_500));
+ assert.deepEqual(lookups, ['911111111111']);
+
+ const input = document.getElementById('apiKey')!;
+ rtl.fireEvent.change(input, { target: { value: 'next-key' } });
+ rtl.fireEvent.submit(input.closest('form')!);
+ await rtl.waitFor(() => assert.ok(document.querySelector('a[href="/number-checker"]')));
+ window.history.replaceState(null, '', '/number-checker');
+ rtl.fireEvent.click(document.querySelector('a[href="/number-checker"]')!);
+ await rtl.waitFor(() => assert.ok(document.querySelector('.number-checker')), { timeout: 10_000 });
+ assert.equal(document.querySelectorAll('.nc-history-table tbody tr').length, 0);
+ } finally {
+ restore();
+ }
+});
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index c51e3e24a..b8675b7c1 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { Layout } from './components/Layout';
import { ToastProvider } from './components/Toast';
+import { NumberCheckProvider } from './components/NumberCheckProvider';
import { useRole } from './hooks/useRole';
import { RoleProvider } from './components/RoleProvider';
import { ErrorBoundary } from './components/ErrorBoundary';
@@ -116,26 +117,29 @@ function AppContent() {
return (
<ToastProvider>
- <BrowserRouter>
- <Suspense fallback={loadingFallback}>
- <Routes>
- <Route path="/" element={<Layout onLogout={handleLogout} userRole={role} />}>
- <Route index element={<Dashboard />} />
- <Route path="sessions" element={<Sessions />} />
- <Route path="chats" element={<Chats />} />
- <Route path="number-checker" element={<NumberChecker />} />
- <Route path="webhooks" element={<Webhooks />} />
- <Route path="templates" element={<Templates />} />
- {role === 'admin' && !scoped && <Route path="api-keys" element={<ApiKeys />} />}
- {role === 'admin' && <Route path="logs" element={<Logs />} />}
- <Route path="message-tester" element={<MessageTester />} />
- {role === 'admin' && !scoped && <Route path="infrastructure" element={<Infrastructure />} />}
- {role === 'admin' && !scoped && <Route path="plugins" element={<Plugins />} />}
- <Route path="*" element={<Navigate to="/" replace />} />
- </Route>
- </Routes>
- </Suspense>
- </BrowserRouter>
+ {/* Above the routes, so a bulk Number Checker run survives leaving its page; a logout unmounts it. */}
+ <NumberCheckProvider>
+ <BrowserRouter>
+ <Suspense fallback={loadingFallback}>
+ <Routes>
+ <Route path="/" element={<Layout onLogout={handleLogout} userRole={role} />}>
+ <Route index element={<Dashboard />} />
+ <Route path="sessions" element={<Sessions />} />
+ <Route path="chats" element={<Chats />} />
+ <Route path="number-checker" element={<NumberChecker />} />
+ <Route path="webhooks" element={<Webhooks />} />
+ <Route path="templates" element={<Templates />} />
+ {role === 'admin' && !scoped && <Route path="api-keys" element={<ApiKeys />} />}
+ {role === 'admin' && <Route path="logs" element={<Logs />} />}
+ <Route path="message-tester" element={<MessageTester />} />
+ {role === 'admin' && !scoped && <Route path="infrastructure" element={<Infrastructure />} />}
+ {role === 'admin' && !scoped && <Route path="plugins" element={<Plugins />} />}
+ <Route path="*" element={<Navigate to="/" replace />} />
+ </Route>
+ </Routes>
+ </Suspense>
+ </BrowserRouter>
+ </NumberCheckProvider>
</ToastProvider>
);
}
diff --git a/dashboard/src/components/NumberCheckProvider.tsx b/dashboard/src/components/NumberCheckProvider.tsx
new file mode 100644
index 000000000..afb66f240
--- /dev/null
+++ b/dashboard/src/components/NumberCheckProvider.tsx
@@ -0,0 +1,117 @@
+import { useState, useRef, useEffect, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+import { contactApi } from '../services/api';
+import { isGatewayRefusal } from '../utils/groupSelection';
+import { useToast } from '../hooks/useToast';
+import {
+ IDLE_RUN,
+ NumberCheckContext,
+ batchStopMessage,
+ type CheckResultItem,
+ type NumberCheckContextType,
+ type NumberCheckRun,
+} from '../hooks/useNumberCheck';
+
+// Mounted outside the routes and inside the signed-in tree: leaving the Number Checker page does not stop a run,
+// and a logout unmounts this, which ends the run and drops its rows before another key can sign in.
+export function NumberCheckProvider({ children }: { children: ReactNode }) {
+ const { t } = useTranslation();
+ const toast = useToast();
+ const [run, setRun] = useState<NumberCheckRun>(IDLE_RUN);
+ // Every await in a run re-checks this, so Stop, a newer run and the unmount all end a run the same way.
+ const runIdRef = useRef(0);
+ // Set at once, where `run.running` only changes on the next render: a second Start in the same tick is refused.
+ const runningRef = useRef(false);
+
+ useEffect(() => {
+ const runRef = runIdRef;
+ return () => {
+ runRef.current++;
+ };
+ }, []);
+
+ const update = (patch: Partial<NumberCheckRun>) => setRun(prev => ({ ...prev, ...patch }));
+
+ const start: NumberCheckContextType['start'] = async (numbers, session, delay) => {
+ if (runningRef.current || numbers.length === 0) return;
+ runningRef.current = true;
+ const runId = ++runIdRef.current;
+ setRun({ ...IDLE_RUN, running: true, session, numbers, delay, progress: { current: 0, total: numbers.length } });
+
+ const results: CheckResultItem[] = [];
+ let refusedWith: number | undefined;
+
+ for (let i = 0; i < numbers.length; i++) {
+ if (runIdRef.current !== runId) return;
+
+ const num = numbers[i];
+ try {
+ const res = await contactApi.checkNumber(session, num);
+ if (runIdRef.current !== runId) return;
+
+ const item: CheckResultItem = {
+ ...res,
+ status: res.exists ? 'registered' : 'unregistered',
+ error: null,
+ timestamp: new Date().toISOString(),
+ };
+ results.push(item);
+ update({ results: [...results] });
+ } catch (err) {
+ if (runIdRef.current !== runId) return;
+
+ const errorMsg = err instanceof Error ? err.message : t('numberChecker.toast.lookupFailed');
+ results.push({
+ number: num,
+ exists: false,
+ whatsappId: null,
+ status: 'failed',
+ error: errorMsg,
+ timestamp: new Date().toISOString(),
+ });
+ update({ results: [...results] });
+
+ // The gateway keeps refusing this route for the rest of its window, a stopped session or an unreachable
+ // gateway fails every later number too, so each would only become a false "Failed" row (and spend more
+ // of the limit).
+ if (isGatewayRefusal(err)) {
+ // A rejected fetch carries no status: the gateway never answered.
+ refusedWith = (err as { status?: number }).status ?? 0;
+ update({ progress: { current: i + 1, total: numbers.length } });
+ break;
+ }
+ }
+
+ if (runIdRef.current !== runId) return;
+ update({ progress: { current: i + 1, total: numbers.length } });
+
+ if (i < numbers.length - 1 && delay > 0) {
+ await new Promise(resolve => setTimeout(resolve, delay));
+ if (runIdRef.current !== runId) return;
+ }
+ }
+
+ if (runIdRef.current !== runId) return;
+ runningRef.current = false;
+ const stopped =
+ refusedWith === undefined ? null : { status: refusedWith, attempted: results.length, total: numbers.length };
+ update({ running: false, session: '', stopped });
+ if (stopped) {
+ toast.error(t('numberChecker.bulk.stoppedTitle'), batchStopMessage(t, stopped));
+ return;
+ }
+ if (results.every(r => r.status === 'failed')) {
+ toast.error(t('numberChecker.toast.checkFailed'), results[results.length - 1].error ?? undefined);
+ return;
+ }
+ toast.success(t('numberChecker.toast.completed', { count: results.length }));
+ };
+
+ const stop = () => {
+ runIdRef.current++;
+ runningRef.current = false;
+ update({ running: false, session: '' });
+ };
+
+ return <NumberCheckContext.Provider value={{ ...run, start, stop }}>{children}</NumberCheckContext.Provider>;
+}
diff --git a/dashboard/src/hooks/useNumberCheck.ts b/dashboard/src/hooks/useNumberCheck.ts
new file mode 100644
index 000000000..5a623e82c
--- /dev/null
+++ b/dashboard/src/hooks/useNumberCheck.ts
@@ -0,0 +1,81 @@
+import { createContext, useContext } from 'react';
+import type { TFunction } from 'i18next';
+import type { CheckNumberResponse } from '../services/api';
+
+export type CheckStatus = 'registered' | 'unregistered' | 'failed';
+
+export interface CheckResultItem extends CheckNumberResponse {
+ status: CheckStatus;
+ error?: string | null;
+ avatarUrl?: string | null;
+ // ISO instant of the check: the CSV carries it as is, the tables show the time of day.
+ timestamp: string;
+}
+
+export interface BatchStop {
+ // 0 when the lookup got no HTTP answer at all.
+ status: number;
+ attempted: number;
+ total: number;
+}
+
+// What each stopping status means, so a single unanswered lookup is not reported as the gateway refusing.
+// The check route answers 400 only for a session that is not started, the same condition as a 409.
+const STOP_REASON_KEYS: Record<number, string> = {
+ 400: 'numberChecker.stopped.reason409',
+ 409: 'numberChecker.stopped.reason409',
+ 429: 'numberChecker.stopped.reason429',
+ 503: 'numberChecker.stopped.reason503',
+};
+
+// `attempted` counts the lookup that stopped the run, which is the last one sent; only the rest were never sent.
+export function batchStopMessage(t: TFunction, { status, attempted, total }: BatchStop): string {
+ if (status === 0) return t('numberChecker.stopped.noAnswer', { attempted, total });
+ const reason = t(STOP_REASON_KEYS[status] ?? 'numberChecker.stopped.reasonOther');
+ const unsent = total - attempted;
+ return unsent > 0
+ ? t('numberChecker.stopped.partial', { reason, status, attempted, total, count: unsent })
+ : t('numberChecker.stopped.last', { reason, status });
+}
+
+export const DEFAULT_BATCH_DELAY = 1000;
+
+// The bulk run and its rows. They live above the routes so that leaving the page neither ends the run nor drops
+// the rows; the page only shows them.
+export interface NumberCheckRun {
+ running: boolean;
+ // The session a running run is bound to, '' otherwise.
+ session: string;
+ // What the last run was started with, so a page opened again can show it.
+ numbers: string[];
+ delay: number;
+ results: CheckResultItem[];
+ progress: { current: number; total: number };
+ stopped: BatchStop | null;
+}
+
+export const IDLE_RUN: NumberCheckRun = {
+ running: false,
+ session: '',
+ numbers: [],
+ delay: DEFAULT_BATCH_DELAY,
+ results: [],
+ progress: { current: 0, total: 0 },
+ stopped: null,
+};
+
+export interface NumberCheckContextType extends NumberCheckRun {
+ // Ignored while a run is going.
+ start: (numbers: string[], session: string, delay: number) => Promise<void>;
+ stop: () => void;
+}
+
+export const NumberCheckContext = createContext<NumberCheckContextType | undefined>(undefined);
+
+export function useNumberCheck(): NumberCheckContextType {
+ const context = useContext(NumberCheckContext);
+ if (context === undefined) {
+ throw new Error('useNumberCheck must be used within a NumberCheckProvider');
+ }
+ return context;
+}
diff --git a/dashboard/src/pages/NumberChecker.test.ts b/dashboard/src/pages/NumberChecker.test.ts
index 47136a2f4..69127391d 100644
--- a/dashboard/src/pages/NumberChecker.test.ts
+++ b/dashboard/src/pages/NumberChecker.test.ts
@@ -11,6 +11,11 @@ let NumberChecker: typeof import('./NumberChecker.tsx').NumberChecker;
let NUMBER_CHECK_BATCH_MAX: typeof import('./NumberChecker.tsx').NUMBER_CHECK_BATCH_MAX;
let ToastProvider: typeof import('../components/Toast.tsx').ToastProvider;
let MemoryRouter: typeof import('react-router-dom').MemoryRouter;
+let Routes: typeof import('react-router-dom').Routes;
+let Route: typeof import('react-router-dom').Route;
+let Link: typeof import('react-router-dom').Link;
+let NumberCheckProvider: typeof import('../components/NumberCheckProvider.tsx').NumberCheckProvider;
+let useNumberCheck: typeof import('../hooks/useNumberCheck.ts').useNumberCheck;
let RoleProvider: typeof import('../components/RoleProvider.tsx').RoleProvider;
let defaultFetch: typeof fetch;
@@ -40,7 +45,46 @@ function renderComponent(role = 'operator', queryClient = createTestQueryClient(
createElement(
RoleProvider,
null,
- createElement(ToastProvider, null, createElement(MemoryRouter, null, createElement(NumberChecker))),
+ createElement(
+ ToastProvider,
+ null,
+ createElement(NumberCheckProvider, null, createElement(MemoryRouter, null, createElement(NumberChecker))),
+ ),
+ ),
+ ),
+ );
+}
+
+// The page and a second route under the providers App mounts above its routes, with links to move between them.
+function renderRoutes() {
+ sessionStorage.setItem('openwa_user_role', 'operator');
+ return rtl.render(
+ createElement(
+ QueryClientProvider,
+ { client: createTestQueryClient() },
+ createElement(
+ RoleProvider,
+ null,
+ createElement(
+ ToastProvider,
+ null,
+ createElement(
+ NumberCheckProvider,
+ null,
+ createElement(
+ MemoryRouter,
+ { initialEntries: ['/number-checker'] },
+ createElement(Link, { to: '/elsewhere' }, 'Leave'),
+ createElement(Link, { to: '/number-checker' }, 'Return'),
+ createElement(
+ Routes,
+ null,
+ createElement(Route, { path: '/number-checker', element: createElement(NumberChecker) }),
+ createElement(Route, { path: '/elsewhere', element: createElement('p', null, 'Elsewhere') }),
+ ),
+ ),
+ ),
+ ),
),
),
);
@@ -88,7 +132,9 @@ before(async () => {
const { i18nReady } = await import('../i18n/index.ts');
await i18nReady;
rtl = await import('@testing-library/react');
- ({ MemoryRouter } = await import('react-router-dom'));
+ ({ MemoryRouter, Routes, Route, Link } = await import('react-router-dom'));
+ ({ NumberCheckProvider } = await import('../components/NumberCheckProvider.tsx'));
+ ({ useNumberCheck } = await import('../hooks/useNumberCheck.ts'));
({ ToastProvider } = await import('../components/Toast.tsx'));
({ RoleProvider } = await import('../components/RoleProvider.tsx'));
({ NumberChecker, NUMBER_CHECK_BATCH_MAX } = await import('./NumberChecker.tsx'));
@@ -786,8 +832,9 @@ const startBatch = () => rtl.fireEvent.click(rtl.screen.getByRole('button', { na
// Past the one-second pacing delay, which is when a run that went on would send its next lookup.
const pastPacing = () => new Promise(resolve => setTimeout(resolve, 1_200));
-test('NumberChecker: leaving the page ends a running batch', async () => {
+test('NumberChecker: signing out ends a running batch', async () => {
const lookups = stubLookups(registered);
+ // The providers are unmounted with the signed-in tree on a logout.
const { unmount } = renderComponent();
rtl.fireEvent.change(await openBulkTab(), { target: { value: THREE_NUMBERS } });
startBatch();
@@ -798,6 +845,85 @@ test('NumberChecker: leaving the page ends a running batch', async () => {
assert.deepEqual(lookups, ['911111111111']);
});
+test('NumberChecker: leaving the page keeps the run going and the rows are there on return', async () => {
+ let finishThird!: (res: Response) => void;
+ const third = new Promise<Response>(resolve => {
+ finishThird = resolve;
+ });
+ const lookups: string[] = [];
+ globalThis.fetch = ((input: RequestInfo | URL) => {
+ const url = String(input);
+ if (!url.includes('/contacts/check/')) return defaultFetch(input);
+ const number = url.split('/contacts/check/')[1];
+ lookups.push(number);
+ return number === '913333333333' ? third : Promise.resolve(registered(number));
+ }) as typeof fetch;
+ renderRoutes();
+ rtl.fireEvent.change(await openBulkTab(), { target: { value: THREE_NUMBERS } });
+ startBatch();
+ await rtl.waitFor(() => assert.equal(lookups.length, 1));
+
+ rtl.fireEvent.click(rtl.screen.getByText('Leave'));
+ assert.ok(rtl.screen.getByText('Elsewhere'));
+ assert.equal(document.querySelector('.number-checker') === null, true);
+ // The run goes on without the page: the second lookup is sent after the pacing delay, the third waits on its answer.
+ await rtl.waitFor(() => assert.equal(lookups.length, 3), { timeout: 5_000 });
+
+ rtl.fireEvent.click(rtl.screen.getByText('Return'));
+ // The Bulk tab is the one open, with the run in it: progress, the two rows so far, and Stop.
+ assert.equal(rtl.screen.getByRole('tab', { name: /Bulk/i }).getAttribute('aria-selected'), 'true');
+ assert.equal(rtl.screen.getByRole('progressbar').getAttribute('aria-valuenow'), '2');
+ assert.equal(statValue('Checked'), '2');
+ assert.ok(rtl.screen.getByText('+911111111111'));
+ assert.ok(rtl.screen.getByText('+912222222222'));
+ assert.ok(rtl.screen.getByRole('button', { name: /Stop Checking/i }));
+ // What the run was started with is in the form, which is locked meanwhile.
+ const textarea = rtl.screen.getByRole('textbox', { name: /Numbers/i }) as HTMLTextAreaElement;
+ assert.equal(textarea.value, THREE_NUMBERS);
+ assert.equal(textarea.disabled, true);
+
+ // It ends while the page is away: the toast comes from the provider, and the rows are there to export on return.
+ rtl.fireEvent.click(rtl.screen.getByText('Leave'));
+ finishThird(registered('913333333333'));
+ await rtl.screen.findByText('Completed checking 3 numbers.');
+ rtl.fireEvent.click(rtl.screen.getByText('Return'));
+ assert.equal(statValue('Checked'), '3');
+ assert.ok(rtl.screen.getByText('+913333333333'));
+ assert.ok(rtl.screen.getByRole('button', { name: /Export Results/i }));
+ assert.equal(rtl.screen.queryByRole('button', { name: /Stop Checking/i }), null);
+});
+
+test('NumberChecker: Stop from a page opened again ends the run that was started on the page before', async () => {
+ const lookups = stubLookups(registered);
+ renderRoutes();
+ rtl.fireEvent.change(await openBulkTab(), { target: { value: THREE_NUMBERS } });
+ startBatch();
+ await rtl.waitFor(() => assert.equal(lookups.length, 1));
+ rtl.fireEvent.click(rtl.screen.getByText('Leave'));
+ rtl.fireEvent.click(rtl.screen.getByText('Return'));
+
+ rtl.fireEvent.click(await rtl.screen.findByRole('button', { name: /Stop Checking/i }));
+ await pastPacing();
+ assert.deepEqual(lookups, ['911111111111']);
+ assert.equal(statValue('Checked'), '1');
+});
+
+test('NumberChecker: a second Start while a run is going is refused', async () => {
+ const lookups = stubLookups(registered);
+ function StartTwice() {
+ const run = useNumberCheck();
+ const twice = () => {
+ void run.start(['911111111111'], 'test-session-1', 0);
+ void run.start(['912222222222'], 'test-session-1', 0);
+ };
+ return createElement('button', { onClick: twice }, 'Start twice');
+ }
+ rtl.render(createElement(ToastProvider, null, createElement(NumberCheckProvider, null, createElement(StartTwice))));
+ rtl.fireEvent.click(rtl.screen.getByText('Start twice'));
+ await pastPacing();
+ assert.deepEqual(lookups, ['911111111111']);
+});
+
test('NumberChecker: Stop ends the run, so no further lookup is sent', async () => {
const lookups = stubLookups(registered);
renderComponent();
diff --git a/dashboard/src/pages/NumberChecker.tsx b/dashboard/src/pages/NumberChecker.tsx
index 125eacf68..a81325ee8 100644
--- a/dashboard/src/pages/NumberChecker.tsx
+++ b/dashboard/src/pages/NumberChecker.tsx
@@ -1,4 +1,4 @@
-import { useState, useMemo, useRef, useCallback, useEffect } from 'react';
+import { useState, useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import {
UserCheck,
@@ -17,59 +17,22 @@ import {
Search,
} from 'lucide-react';
import { Trans, useTranslation } from 'react-i18next';
-import type { TFunction } from 'i18next';
import { PageHeader } from '../components/PageHeader';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { copyToClipboard } from '../utils/clipboard';
import { useSessionsQuery } from '../hooks/queries';
-import { contactApi, type CheckNumberResponse } from '../services/api';
+import { contactApi } from '../services/api';
import { useToast } from '../hooks/useToast';
import { useRole } from '../hooks/useRole';
+import { batchStopMessage, useNumberCheck, type CheckResultItem } from '../hooks/useNumberCheck';
import { escapeCsvCell } from '../utils/csv';
-import { isGatewayRefusal } from '../utils/groupSelection';
import { normalizePhoneText } from '../utils/phone';
import './NumberChecker.css';
-export type CheckStatus = 'registered' | 'unregistered' | 'failed';
-
// Every lookup is an outbound WhatsApp query that counts against the gateway's per-IP limit on this route
// (100 a minute by default) and against the linked account's standing, so one run is capped.
export const NUMBER_CHECK_BATCH_MAX = 100;
-interface BatchStop {
- // 0 when the lookup got no HTTP answer at all.
- status: number;
- attempted: number;
- total: number;
-}
-
-// What each stopping status means, so a single unanswered lookup is not reported as the gateway refusing.
-// The check route answers 400 only for a session that is not started, the same condition as a 409.
-const STOP_REASON_KEYS: Record<number, string> = {
- 400: 'numberChecker.stopped.reason409',
- 409: 'numberChecker.stopped.reason409',
- 429: 'numberChecker.stopped.reason429',
- 503: 'numberChecker.stopped.reason503',
-};
-
-// `attempted` counts the lookup that stopped the run, which is the last one sent; only the rest were never sent.
-function batchStopMessage(t: TFunction, { status, attempted, total }: BatchStop): string {
- if (status === 0) return t('numberChecker.stopped.noAnswer', { attempted, total });
- const reason = t(STOP_REASON_KEYS[status] ?? 'numberChecker.stopped.reasonOther');
- const unsent = total - attempted;
- return unsent > 0
- ? t('numberChecker.stopped.partial', { reason, status, attempted, total, count: unsent })
- : t('numberChecker.stopped.last', { reason, status });
-}
-
-export interface CheckResultItem extends CheckNumberResponse {
- status: CheckStatus;
- error?: string | null;
- avatarUrl?: string | null;
- // ISO instant of the check: the CSV carries it as is, the tables show the time of day.
- timestamp: string;
-}
-
const timeOfDay = (iso: string) => new Date(iso).toLocaleTimeString();
export function NumberChecker() {
@@ -78,12 +41,20 @@ export function NumberChecker() {
const navigate = useNavigate();
const toast = useToast();
const { canWrite } = useRole();
+ // The bulk run lives above the routes, so it is still going (or its rows are still here) when this page opens again.
+ const run = useNumberCheck();
+ const isCheckingBatch = run.running;
+ const batchResults = run.results;
+ const batchProgress = run.progress;
+ const batchStop = run.stopped;
const { data: sessions = [], isLoading: loadingSessions } = useSessionsQuery();
const readySessions = useMemo(() => sessions.filter(s => s.status === 'ready'), [sessions]);
const [selectedSession, setSelectedSession] = useState<string>('');
- const [activeTab, setActiveTab] = useState<'single' | 'batch'>('single');
+ const [activeTab, setActiveTab] = useState<'single' | 'batch'>(
+ isCheckingBatch || batchResults.length > 0 ? 'batch' : 'single',
+ );
// The chosen session, else the first ready one (API requires session UUID). A chosen session that leaves
// the ready list on a refetch would otherwise stay in use while the select shows the first option.
@@ -99,25 +70,12 @@ export function NumberChecker() {
const [recentChecks, setRecentChecks] = useState<CheckResultItem[]>([]);
// Batch Check State
- const [batchInput, setBatchInput] = useState('');
- const [batchDelay, setBatchDelay] = useState<number>(1000);
- const [isCheckingBatch, setIsCheckingBatch] = useState(false);
+ const [batchInput, setBatchInput] = useState(() => run.numbers.join('\n'));
+ const [batchDelay, setBatchDelay] = useState<number>(run.delay);
// The session a running bulk run is bound to. Both selects are locked meanwhile, so they keep showing it even if
// the chosen session leaves the ready list and returns during the run, and a single check goes to it too.
- const [runSession, setRunSession] = useState('');
- const shownSession = isCheckingBatch ? runSession : currentSession;
- const [batchResults, setBatchResults] = useState<CheckResultItem[]>([]);
- const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0 });
+ const shownSession = isCheckingBatch ? run.session : currentSession;
const [batchFilter, setBatchFilter] = useState<'all' | 'registered' | 'unregistered' | 'failed'>('all');
- const [batchStop, setBatchStop] = useState<BatchStop | null>(null);
- const batchRunIdRef = useRef<number>(0);
-
- useEffect(() => {
- const runRef = batchRunIdRef;
- return () => {
- runRef.current++;
- };
- }, []);
// Opt-in: the +91 rewrite would turn any other country's 10-digit or 0-prefixed number into an Indian one.
const [autoPrefix91, setAutoPrefix91] = useState(false);
@@ -256,7 +214,7 @@ export function NumberChecker() {
};
// Perform batch check
- const handleStartBatch = async () => {
+ const handleStartBatch = () => {
if (!canWrite || isCheckingBatch) return;
const numbers = batchParsedStats.list;
@@ -269,87 +227,8 @@ export function NumberChecker() {
return;
}
- const runId = ++batchRunIdRef.current;
- setRunSession(currentSession);
- setIsCheckingBatch(true);
- setBatchResults([]);
setBatchFilter('all');
- setBatchStop(null);
- setBatchProgress({ current: 0, total: numbers.length });
-
- const results: CheckResultItem[] = [];
- let refusedWith: number | undefined;
-
- for (let i = 0; i < numbers.length; i++) {
- if (batchRunIdRef.current !== runId) return;
-
- const num = numbers[i];
- try {
- const res = await contactApi.checkNumber(currentSession, num);
- if (batchRunIdRef.current !== runId) return;
-
- const item: CheckResultItem = {
- ...res,
- status: res.exists ? 'registered' : 'unregistered',
- error: null,
- timestamp: new Date().toISOString(),
- };
- results.push(item);
- setBatchResults([...results]);
- } catch (err) {
- if (batchRunIdRef.current !== runId) return;
-
- const errorMsg = err instanceof Error ? err.message : t('numberChecker.toast.lookupFailed');
- results.push({
- number: num,
- exists: false,
- whatsappId: null,
- status: 'failed',
- error: errorMsg,
- timestamp: new Date().toISOString(),
- });
- setBatchResults([...results]);
-
- // The gateway keeps refusing this route for the rest of its window, a stopped session or an unreachable
- // gateway fails every later number too, so each would only become a false "Failed" row (and spend more
- // of the limit).
- if (isGatewayRefusal(err)) {
- // A rejected fetch carries no status: the gateway never answered.
- refusedWith = (err as { status?: number }).status ?? 0;
- setBatchProgress({ current: i + 1, total: numbers.length });
- break;
- }
- }
-
- if (batchRunIdRef.current !== runId) return;
- setBatchProgress({ current: i + 1, total: numbers.length });
-
- if (i < numbers.length - 1 && batchDelay > 0) {
- await new Promise(resolve => setTimeout(resolve, batchDelay));
- if (batchRunIdRef.current !== runId) return;
- }
- }
-
- if (batchRunIdRef.current !== runId) return;
- setIsCheckingBatch(false);
- setRunSession('');
- if (refusedWith !== undefined) {
- const stop = { status: refusedWith, attempted: results.length, total: numbers.length };
- setBatchStop(stop);
- toast.error(t('numberChecker.bulk.stoppedTitle'), batchStopMessage(t, stop));
- return;
- }
- if (results.every(r => r.status === 'failed')) {
- toast.error(t('numberChecker.toast.checkFailed'), results[results.length - 1].error ?? undefined);
- return;
- }
- toast.success(t('numberChecker.toast.completed', { count: results.length }));
- };
-
- const handleStopBatch = () => {
- batchRunIdRef.current++;
- setIsCheckingBatch(false);
- setRunSession('');
+ void run.start(numbers, currentSession, batchDelay);
};
// Filter batch results
@@ -843,7 +722,7 @@ export function NumberChecker() {
<UserCheck size={18} /> {t('numberChecker.bulk.start')}
</button>
) : (
- <button className="nc-btn nc-btn-danger" onClick={handleStopBatch}>
+ <button className="nc-btn nc-btn-danger" onClick={run.stop}>
<Trash2 size={18} /> {t('numberChecker.bulk.stop')}
</button>
)}
diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.md
index 16d1fabb6..de6d7c068 100644
--- a/docs/17-dashboard-design.md
+++ b/docs/17-dashboard-design.md
@@ -36,8 +36,8 @@ Every page — and most shared components — ships its own stylesheet colocated
component (see §17.4 for the handful that carry no stylesheet of their own). Icons come from
`lucide-react`; charts from `recharts`; i18n from `react-i18next`.
Client state is **TanStack Query** for most server data (see `src/hooks/queries.ts`; §17.5 names the
-pages that keep their own copy) plus two small React
-Context providers (`RoleProvider`, `ToastProvider`); theme mode is a provider-less `useTheme` hook
+pages that keep their own copy) plus three small React
+Context providers (`RoleProvider`, `ToastProvider`, `NumberCheckProvider`); theme mode is a provider-less `useTheme` hook
backed by `localStorage` — there is no Zustand store.
### Design Principles
@@ -475,9 +475,10 @@ library — those visuals are composed directly with `div`s and the page's own C
## 17.5 State Management
There is **no Zustand store** (and no global client-state library). Most server data is owned by
-**TanStack Query** (`@tanstack/react-query`); the only other shared state lives in the two React
+**TanStack Query** (`@tanstack/react-query`); the only other shared state lives in the three React
Context providers in the app — `RoleProvider` (the authenticated key's role, read through the
-`useRole` hook) and `ToastProvider` (transient notifications). Theme mode is deliberately _not_ a
+`useRole` hook), `ToastProvider` (transient notifications) and `NumberCheckProvider` (the Number
+Checker's bulk run and its rows, which outlive the page). Theme mode is deliberately _not_ a
context: `useTheme` is a plain hook that persists to `localStorage` and writes one attribute on
`<html>` (see §17.7).