Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): read native digits in the group member field
Yudhi Armyndharis5be168f700d1
diff --git a/dashboard/src/components/NewChatPanel.test.ts b/dashboard/src/components/NewChatPanel.test.tsindex e30cd268e..ea290554b 100644--- a/dashboard/src/components/NewChatPanel.test.ts+++ b/dashboard/src/components/NewChatPanel.test.ts@@ -97,3 +97,17 @@ for (const [script, zero] of [assert.ok(rtl.screen.getByText('Anna'));});}++// A query that reads as a number, but is not one that can start a chat, is told to carry the country code: in the+// digits of any script, as it is in ASCII.+for (const [script, zero] of [+ ['ASCII', 0x30],+ ['Arabic-Indic', 0x0660],+ ['full-width', 0xff10],+] as const) {+ test(`a short number typed in ${script} digits gets the country code hint`, async () => {+ renderPanel();+ rtl.fireEvent.change(search(), { target: { value: native('628123', zero) } });+ assert.ok(await rtl.screen.findByText(/with the country code/));+ });+}diff --git a/dashboard/src/components/chats/GroupInfoDialog.test.ts b/dashboard/src/components/chats/GroupInfoDialog.test.tsnew file mode 100644index 000000000..2f47f8c5a--- /dev/null+++ b/dashboard/src/components/chats/GroupInfoDialog.test.ts@@ -0,0 +1,148 @@+// The member field of the group dialog reads a number the way the other number fields do: in the digits of any+// script, as the ASCII digits the gateway takes.+import '../../test-helpers/register-hooks.ts';+import { test, before, after, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { createElement, type ReactNode } from 'react';+import type { Chat, Session } from '../../services/api.ts';++let rtl: typeof import('@testing-library/react');+let GroupInfoDialog: (typeof import('./GroupInfoDialog.tsx'))['default'];+let wrap: (children: ReactNode) => ReactNode;+let realFetch: typeof fetch;+let queryClient: import('@tanstack/react-query').QueryClient;++const json = (data: unknown) => new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } });++const session = {+ id: 's1',+ name: 'Main',+ status: 'ready',+ phone: '15551234567',+ createdAt: '2026-01-01T00:00:00Z',+} as Session;+const group = { id: '[email protected]', name: 'Team', isGroup: true, kind: 'group' } as Chat;++// The numbers the gateway was asked to check, and the participants it was asked to add.+const checked: string[] = [];+const added: string[][] = [];++before(async () => {+ const { installJsdomGlobals } = await import('../../test-helpers/jsdom.ts');+ await installJsdomGlobals();+ const { i18nReady } = await import('../../i18n/index.ts');+ await i18nReady;+ rtl = await import('@testing-library/react');+ const { QueryClient, QueryClientProvider } = await import('@tanstack/react-query');+ const { ToastProvider } = await import('../Toast.tsx');+ const { RoleContext } = await import('../../hooks/useRole.tsx');+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const role = {+ role: 'admin' as const,+ setRole: () => undefined,+ isAdmin: true,+ isOperator: false,+ isViewer: false,+ canWrite: true,+ engineType: null,+ setEngineType: () => undefined,+ scoped: false,+ setScoped: () => undefined,+ };+ wrap = children =>+ createElement(+ QueryClientProvider,+ { client: queryClient },+ createElement(RoleContext.Provider, { value: role }, createElement(ToastProvider, null, children)),+ );+ ({ default: GroupInfoDialog } = await import('./GroupInfoDialog.tsx'));+ realFetch = globalThis.fetch;+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const path = new URL(typeof input === 'string' ? input : input.toString(), 'http://localhost').pathname;+ if (path.includes('/contacts/check/')) {+ const number = decodeURIComponent(path.split('/contacts/check/')[1]);+ checked.push(number);+ return json({ number, exists: true, whatsappId: `${number}@c.us` });+ }+ if (path.endsWith('/participants') && init?.method === 'POST') {+ const { participants } = JSON.parse(String(init.body)) as { participants: string[] };+ added.push(participants);+ return json({ results: participants.map(id => ({ id, success: true })) });+ }+ if (path.includes('/groups/')) {+ return json({+ id: group.id,+ name: 'Team',+ participants: [{ id: '[email protected]', number: '15551234567', isAdmin: true, isSuperAdmin: false }],+ });+ }+ return json({ url: null });+ }) as typeof fetch;+});++afterEach(() => {+ rtl.cleanup();+ checked.length = 0;+ added.length = 0;+});++// The dialog opens on the Info tab: the Participants tab holds the member field.+async function openMemberField(): Promise<HTMLInputElement> {+ rtl.render(wrap(createElement(GroupInfoDialog, { session, group, onClose: () => {}, onRenamed: () => {} })));+ rtl.fireEvent.click(await rtl.screen.findByRole('tab', { name: 'Participants' }));+ return (await rtl.screen.findByPlaceholderText('Add a number with country code')) as HTMLInputElement;+}++const addButton = () => rtl.screen.getByRole('button', { name: 'Add' }) as HTMLButtonElement;+const native = (ascii: string, zero: number) => [...ascii].map(d => String.fromCharCode(zero + Number(d))).join('');++for (const [script, zero] of [+ ['ASCII', 0x30],+ ['Arabic-Indic', 0x0660],+ ['Persian', 0x06f0],+ ['Devanagari', 0x0966],+ ['Telugu', 0x0c66],+ ['full-width', 0xff10],+] as const) {+ test(`a member typed in ${script} digits is checked and added as ASCII digits`, async () => {+ const field = await openMemberField();+ assert.equal(addButton().disabled, true, 'nothing typed yet');+ rtl.fireEvent.change(field, { target: { value: `+${native('628123456789', zero)}` } });+ assert.equal(addButton().disabled, false, 'a number of 12 digits enables Add');+ rtl.fireEvent.click(addButton());+ await rtl.waitFor(() => assert.equal(added.length, 1));+ assert.deepEqual(checked, ['628123456789']);+ assert.deepEqual(added, [['[email protected]']]);+ });+}++test('the 00 prefix is dropped from a number typed in native digits', async () => {+ const field = await openMemberField();+ rtl.fireEvent.change(field, { target: { value: native('00628123456789', 0x0660) } });+ rtl.fireEvent.click(addButton());+ await rtl.waitFor(() => assert.equal(added.length, 1));+ assert.deepEqual(checked, ['628123456789']);+});++test('a number shorter than seven digits keeps Add disabled in any script', async () => {+ const field = await openMemberField();+ for (const zero of [0x30, 0x0660]) {+ rtl.fireEvent.change(field, { target: { value: native('628123', zero) } });+ assert.equal(addButton().disabled, true);+ }+});++test('Enter submits a number typed in native digits', async () => {+ const field = await openMemberField();+ rtl.fireEvent.change(field, { target: { value: native('628123456789', 0x0966) } });+ rtl.fireEvent.submit(field.closest('form')!);+ await rtl.waitFor(() => assert.equal(added.length, 1));+ assert.deepEqual(added, [['[email protected]']]);+});++// Clearing the cache drops the garbage-collection timers of the group and picture queries, which would hold the+// process open after the last test.+after(() => {+ queryClient.clear();+ globalThis.fetch = realFetch;+});diff --git a/dashboard/src/components/chats/GroupInfoDialog.tsx b/dashboard/src/components/chats/GroupInfoDialog.tsxindex 1ec958d96..e979a6798 100644--- a/dashboard/src/components/chats/GroupInfoDialog.tsx+++ b/dashboard/src/components/chats/GroupInfoDialog.tsx@@ -17,6 +17,7 @@ import { useRole } from '../../hooks/useRole';import { useToast } from '../../hooks/useToast';import { formatPhoneForDisplay, isolateNumber } from '../../utils/formatPhone';import { MEDIA_UPLOAD_MAX_BYTES } from '../../utils/mediaUpload';+import { normalizePhoneText } from '../../utils/phone';import ChatAvatar from './ChatAvatar';// The gateway's caps (CreateGroupDto / GroupDescriptionDto).@@ -141,6 +142,8 @@ function GroupInfoDialog({ session, group, onClose, onRenamed }: GroupInfoDialog// --- Participants ---const [pending, setPending] = useState<string | null>(null);const [newMember, setNewMember] = useState('');+ // The gateway takes ASCII digits, whatever script the operator typed them in.+ const memberDigits = normalizePhoneText(newMember).replace(/\D/g, '');// The gateway answers 200 for a membership write even when it refused some participants, and says// which in `results`. Returns whether every participant was accepted.const runMemberAction = async (key: string, action: () => Promise<GroupParticipantsAck>): Promise<boolean> => {@@ -163,7 +166,7 @@ function GroupInfoDialog({ session, group, onClose, onRenamed }: GroupInfoDialog// A number is checked first, as in the new-chat panel: the gateway resolves it to the id WhatsApp uses.const addMember = async () => {const added = await runMemberAction('add', async () => {- const digits = newMember.replace(/\D/g, '').replace(/^00/, '');+ const digits = memberDigits.replace(/^00/, '');const check = await contactApi.checkNumber(session.id, digits);if (!check.exists || !check.whatsappId) {const number = isolateNumber(formatPhoneForDisplay(digits) ?? `+${digits}`);@@ -319,7 +322,7 @@ function GroupInfoDialog({ session, group, onClose, onRenamed }: GroupInfoDialogclassName="group-info-add"onSubmit={e => {e.preventDefault();- if (newMember.replace(/\D/g, '').length >= 7) void addMember();+ if (memberDigits.length >= 7) void addMember();}}><input@@ -329,11 +332,7 @@ function GroupInfoDialog({ session, group, onClose, onRenamed }: GroupInfoDialogplaceholder={t('chats.group.addPlaceholder')}aria-label={t('chats.group.addPlaceholder')}/>- <button- type="submit"- className="btn-primary"- disabled={newMember.replace(/\D/g, '').length < 7 || pending !== null}- >+ <button type="submit" className="btn-primary" disabled={memberDigits.length < 7 || pending !== null}>{pending === 'add' ? <Loader2 className="animate-spin" size={16} /> : <UserPlus size={16} />}{t('chats.group.add')}</button>diff --git a/dashboard/src/components/chats/NewChatPanel.tsx b/dashboard/src/components/chats/NewChatPanel.tsxindex 97cc1ef67..6f4bcb794 100644--- a/dashboard/src/components/chats/NewChatPanel.tsx+++ b/dashboard/src/components/chats/NewChatPanel.tsx@@ -130,7 +130,8 @@ function NewChatPanel({ sessionId, onOpenChat, findListedChat, onClose }: NewChaconst typedNumber = toInternationalDigits(query);// Placed in sentences (the start and add buttons, the not-registered toast), so it goes in as an isolate.const typedNumberLabel = typedNumber ? isolateNumber(formatPhoneForDisplay(typedNumber) ?? `+${typedNumber}`) : '';- const showNumberHint = Boolean(query.trim()) && !typedNumber && /^[\d\s+()-]+$/.test(query.trim());+ const showNumberHint =+ Boolean(query.trim()) && !typedNumber && /^[\d\s+()-]+$/.test(normalizePhoneText(query).trim());// Resolve a typed number to its canonical WhatsApp id. The send routes accept an unregistered number// without an error, so this check is the only thing that keeps a chat from going nowhere. An answer