Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(dashboard): state the session form rules once
Yudhi Armyndharis69d8e800ccf0
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 60688a05b..8836b1722 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -26,6 +26,7 @@ import {replaceSession,} from '../utils/sessionActions';import { invalidateSessionQueries, reconcileSessionCache } from '../utils/sessionMutation';+import { canCreateSession, filterSessions, isValidPairingPhone, sessionNameIssues } from '../utils/sessionForm';import { useToast } from '../components/Toast';import { useWebSocket } from '../hooks/useWebSocket';import { useRole } from '../hooks/useRole';@@ -281,7 +282,7 @@ export function Sessions() {// input's Enter handler is not, so a rapid double-Enter would otherwise fire overlapping POSTs.if (requestingPairing) return;if (!qrData || !phoneNumber.trim()) return;- if (!/^[0-9]{6,15}$/.test(phoneNumber.trim())) {+ if (!isValidPairingPhone(phoneNumber)) {setPairingError(t('sessions.pairing.invalidPhone'));return;}@@ -471,19 +472,10 @@ export function Sessions() {const formatStatus = (status: string) => t(`sessionStatus.${status}`, { defaultValue: status });- const filteredSessions = sessions.filter(s => {- const matchesSearch =- s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||- s.id.toLowerCase().includes(searchQuery.toLowerCase());- const matchesStatus =- statusFilter === 'all' ||- (statusFilter === 'active' && s.status === 'ready') ||- (statusFilter === 'inactive' &&- ['created', 'disconnected', 'action_required', 'failed'].includes(s.status)) ||- (statusFilter === 'connecting' &&- ['initializing', 'authenticating', 'qr_ready'].includes(s.status));- return matchesSearch && matchesStatus;- });+ const filteredSessions = filterSessions(sessions, searchQuery, statusFilter);+ const existingSessionNames = sessions.map(s => s.name);+ // Empty is a disabled button, not a message: the form stays quiet until the user types something.+ const nameIssues = newSessionName ? sessionNameIssues(newSessionName, existingSessionNames) : [];if (loading) {return (@@ -565,13 +557,7 @@ export function Sessions() {<buttonclassName="btn-primary"onClick={handleCreate}- disabled={- creating ||- !newSessionName.trim() ||- !/^[a-z0-9-]+$/.test(newSessionName) ||- newSessionName.length > 50 ||- sessions.some(s => s.name === newSessionName)- }+ disabled={creating || !canCreateSession(newSessionName, existingSessionNames)}>{creating ? <Loader2 className="animate-spin" size={16} /> : t('common.create')}</button>@@ -592,18 +578,11 @@ export function Sessions() {<p className="input-hint"><Trans i18nKey="sessions.create.hint" components={{ code: <code /> }} /></p>- {newSessionName && !/^[a-z0-9-]+$/.test(newSessionName) && (- <p className="input-error">{t('sessions.create.invalidChars')}</p>- )}- {newSessionName && newSessionName.length > 50 && (+ {nameIssues.includes('format') && <p className="input-error">{t('sessions.create.invalidChars')}</p>}+ {nameIssues.includes('too-long') && (<p className="input-error">{t('sessions.create.tooLong', { length: newSessionName.length })}</p>)}- {newSessionName &&- /^[a-z0-9-]+$/.test(newSessionName) &&- newSessionName.length <= 50 &&- sessions.some(s => s.name === newSessionName) && (- <p className="input-error">{t('sessions.create.duplicate')}</p>- )}+ {nameIssues.includes('duplicate') && <p className="input-error">{t('sessions.create.duplicate')}</p>}</Modal>)}@@ -701,7 +680,7 @@ export function Sessions() {<buttonclassName="btn-primary"onClick={handleGeneratePairingCode}- disabled={requestingPairing || !/^[0-9]{6,15}$/.test(phoneNumber.trim())}+ disabled={requestingPairing || !isValidPairingPhone(phoneNumber)}style={{ width: '100%', justifyContent: 'center' }}>{requestingPairing ? (diff --git a/dashboard/src/utils/sessionForm.test.ts b/dashboard/src/utils/sessionForm.test.tsnew file mode 100644index 000000000..eba3c635e--- /dev/null+++ b/dashboard/src/utils/sessionForm.test.ts@@ -0,0 +1,85 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ sessionNameIssues,+ canCreateSession,+ isValidPairingPhone,+ matchesStatusFilter,+ filterSessions,+} from './sessionForm.ts';++test('a valid session name reports no issues', () => {+ assert.deepEqual(sessionNameIssues('sales-01', []), []);+ assert.equal(canCreateSession('sales-01', []), true);+});++test('an empty name is reported as empty and nothing else', () => {+ assert.deepEqual(sessionNameIssues('', ['sales']), ['empty']);+ assert.deepEqual(sessionNameIssues(' ', ['sales']), ['empty']);+ assert.equal(canCreateSession('', []), false);+});++test('format and length are reported together, because the form shows both', () => {+ const tooLongAndMalformed = 'A'.repeat(60);++ assert.deepEqual(sessionNameIssues(tooLongAndMalformed, []), ['format', 'too-long']);+});++test('duplicate is reported only once the name is otherwise usable', () => {+ assert.deepEqual(sessionNameIssues('sales', ['sales']), ['duplicate']);+ // Telling someone their unusable name is also taken is noise.+ assert.deepEqual(sessionNameIssues('Sales', ['Sales']), ['format']);+});++test('names become on-disk directories, so the format stays narrow', () => {+ assert.deepEqual(sessionNameIssues('sales-01', []), []);+ assert.deepEqual(sessionNameIssues('Sales', []), ['format'], 'uppercase rejected');+ assert.deepEqual(sessionNameIssues('sales_01', []), ['format'], 'underscore rejected');+ assert.deepEqual(sessionNameIssues('sales 01', []), ['format'], 'space rejected');+ assert.deepEqual(sessionNameIssues('../escape', []), ['format'], 'path traversal rejected');+});++test('the length cap is 50', () => {+ assert.deepEqual(sessionNameIssues('a'.repeat(50), []), []);+ assert.deepEqual(sessionNameIssues('a'.repeat(51), []), ['too-long']);+});++test('pairing accepts a bare international number and nothing else', () => {+ assert.equal(isValidPairingPhone('628123456789'), true);+ assert.equal(isValidPairingPhone(' 628123456789 '), true, 'trimmed');+ assert.equal(isValidPairingPhone('+628123456789'), false, 'no plus');+ assert.equal(isValidPairingPhone('62812-3456'), false, 'no separators');+ assert.equal(isValidPairingPhone('12345'), false, 'too short');+ assert.equal(isValidPairingPhone('1234567890123456'), false, 'too long');+});++test('the status groups follow the operator model, not the engine states', () => {+ assert.equal(matchesStatusFilter('anything', 'all'), true);+ assert.equal(matchesStatusFilter('ready', 'active'), true);++ for (const s of ['initializing', 'authenticating', 'qr_ready']) {+ assert.equal(matchesStatusFilter(s, 'connecting'), true, `${s} is connecting`);+ }+ // action_required and failed need the operator, not time — they belong with inactive, not connecting.+ for (const s of ['created', 'disconnected', 'action_required', 'failed']) {+ assert.equal(matchesStatusFilter(s, 'inactive'), true, `${s} is inactive`);+ assert.equal(matchesStatusFilter(s, 'connecting'), false, `${s} is not connecting`);+ }+});++test('an unknown filter matches nothing rather than everything', () => {+ assert.equal(matchesStatusFilter('ready', 'bogus'), false);+});++test('filterSessions combines the search box and the status group', () => {+ const sessions = [+ { id: 'u1', name: 'sales', status: 'ready' },+ { id: 'u2', name: 'support', status: 'disconnected' },+ { id: 'u3', name: 'sales-backup', status: 'disconnected' },+ ];++ assert.deepEqual(filterSessions(sessions, 'sales', 'all').map(s => s.id), ['u1', 'u3']);+ assert.deepEqual(filterSessions(sessions, 'sales', 'inactive').map(s => s.id), ['u3']);+ assert.deepEqual(filterSessions(sessions, '', 'active').map(s => s.id), ['u1']);+ assert.deepEqual(filterSessions(sessions, 'u2', 'all').map(s => s.id), ['u2'], 'id matches too');+});diff --git a/dashboard/src/utils/sessionForm.ts b/dashboard/src/utils/sessionForm.tsnew file mode 100644index 000000000..c4864eb83--- /dev/null+++ b/dashboard/src/utils/sessionForm.ts@@ -0,0 +1,71 @@+/**+ * Validation and filtering rules for the Sessions page.+ *+ * Each of these was re-derived inline at two or three places — the create button's disabled state,+ * the format hint under the input, and the duplicate-name warning each rebuilt the same name rule+ * with a different combination of its clauses. Stating a rule once and asking it what is wrong keeps+ * the three from drifting apart, and makes them testable.+ */++/** Everything wrong with a proposed session name. Empty when it is acceptable. */+export type SessionNameIssue = 'empty' | 'format' | 'too-long' | 'duplicate';++/** Names become on-disk directory names, so the format is deliberately narrow. */+const NAME_FORMAT = /^[a-z0-9-]+$/;+const NAME_MAX_LENGTH = 50;++/**+ * Report EVERY issue rather than the first, because the form shows the format and length messages+ * independently — a name can be both malformed and too long, and the user should see both.+ *+ * `duplicate` is reported only once format and length pass: telling someone their unusable name is+ * also taken is noise, and it is how the form already behaved.+ */+export function sessionNameIssues(name: string, existingNames: string[]): SessionNameIssue[] {+ if (!name.trim()) return ['empty'];+ const issues: SessionNameIssue[] = [];+ if (!NAME_FORMAT.test(name)) issues.push('format');+ if (name.length > NAME_MAX_LENGTH) issues.push('too-long');+ if (issues.length === 0 && existingNames.includes(name)) issues.push('duplicate');+ return issues;+}++/** The create button's gate: any issue at all blocks it. */+export function canCreateSession(name: string, existingNames: string[]): boolean {+ return sessionNameIssues(name, existingNames).length === 0;+}++/** Pairing accepts a bare international number: digits only, no `+`, no separators. */+export function isValidPairingPhone(phone: string): boolean {+ return /^[0-9]{6,15}$/.test(phone.trim());+}++/**+ * The status filter's groups do not map one-to-one onto engine statuses — they are the operator's+ * mental model, not the engine's. `connecting` covers the three transient states, and `inactive`+ * covers everything that is neither ready nor moving, INCLUDING `action_required` and `failed`, which+ * both need the operator rather than time.+ */+const STATUS_GROUPS: Record<string, string[]> = {+ active: ['ready'],+ connecting: ['initializing', 'authenticating', 'qr_ready'],+ inactive: ['created', 'disconnected', 'action_required', 'failed'],+};++export function matchesStatusFilter(status: string, filter: string): boolean {+ if (filter === 'all') return true;+ return (STATUS_GROUPS[filter] ?? []).includes(status);+}++export function filterSessions<T extends { id: string; name: string; status: string }>(+ sessions: T[],+ search: string,+ statusFilter: string,+): T[] {+ const needle = search.toLowerCase();+ return sessions.filter(+ s =>+ (s.name.toLowerCase().includes(needle) || s.id.toLowerCase().includes(needle)) &&+ matchesStatusFilter(s.status, statusFilter),+ );+}