Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(dashboard): send a message to several groups from the message tester
Cares T.49926b306d68
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5c7f9ca1..bba32d7ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- The dashboard Message Tester can send to several groups at once. In Group mode a searchable checkbox list with Select all and Clear replaces the single-group dropdown, and the message goes to each selected group in turn, 3 seconds apart. A group that fails does not stop the rest: the response panel lists it by name with its error, and the send counts as failed only when every group failed. Forward still takes one source chat, the first selected group.+### Changed- The PostgreSQL data connection is pinned to UTC: parameters bind as UTC, naive timestamps read back as UTC, every pooled connection sets its session `TimeZone`, and boot fails when the effective zone is not UTC year round.diff --git a/dashboard/src/components/GroupPicker.tsx b/dashboard/src/components/GroupPicker.tsxnew file mode 100644index 000000000..039b0004a--- /dev/null+++ b/dashboard/src/components/GroupPicker.tsx@@ -0,0 +1,85 @@+import { useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Loader2 } from 'lucide-react';+import {+ addGroupIds,+ filterGroupsByName,+ groupLabel,+ toggleGroupId,+ type SelectableGroup,+} from '../utils/groupSelection';++interface GroupPickerProps {+ groups: SelectableGroup[];+ selectedIds: string[];+ onChange: (ids: string[]) => void;+ loading: boolean;+ labelledBy: string;+}++export function GroupPicker({ groups, selectedIds, onChange, loading, labelledBy }: GroupPickerProps) {+ const { t } = useTranslation();+ const [query, setQuery] = useState('');+ const visibleGroups = useMemo(() => filterGroupsByName(groups, query), [groups, query]);+ const selected = useMemo(() => new Set(selectedIds), [selectedIds]);+ const noGroups = !loading && groups.length === 0;++ return (+ <div className="group-picker">+ <input+ type="search"+ value={query}+ onChange={e => setQuery(e.target.value)}+ placeholder={t('common.search')}+ aria-label={t('common.search')}+ disabled={loading || noGroups}+ />+ <div className="group-picker-toolbar">+ <button+ type="button"+ className="browse-btn"+ onClick={() =>+ onChange(+ addGroupIds(+ selectedIds,+ visibleGroups.map(group => group.id),+ ),+ )+ }+ disabled={loading || visibleGroups.length === 0}+ >+ {t('messageTester.selectAllGroups')}+ </button>+ <button type="button" className="browse-btn" onClick={() => onChange([])} disabled={selectedIds.length === 0}>+ {t('messageTester.clearGroupSelection')}+ </button>+ <span className="group-picker-count" role="status">+ {t('messageTester.groupsSelectedCount', { count: selectedIds.length })}+ </span>+ </div>+ <div className="group-picker-list" role="group" aria-labelledby={labelledBy}>+ {loading ? (+ <div className="group-picker-empty">+ <Loader2 className="animate-spin" size={16} />+ {t('messageTester.loadingGroups')}+ </div>+ ) : noGroups ? (+ <div className="group-picker-empty">{t('messageTester.noGroupsFound')}</div>+ ) : visibleGroups.length === 0 ? (+ <div className="group-picker-empty">{t('messageTester.noGroupsMatch')}</div>+ ) : (+ visibleGroups.map(group => (+ <label key={group.id} className="checkbox-label group-picker-option">+ <input+ type="checkbox"+ checked={selected.has(group.id)}+ onChange={() => onChange(toggleGroupId(selectedIds, group.id))}+ />+ <span title={groupLabel(group)}>{groupLabel(group)}</span>+ </label>+ ))+ )}+ </div>+ </div>+ );+}diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 65bc4363f..674cee0ad 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -655,6 +655,10 @@"loadingGroups": "جارٍ تحميل المجموعات...","noGroupsFound": "لم يتم العثور على مجموعات","selectGroupHint": "اختر مجموعة من واتساب الخاص بك",+ "selectAllGroups": "تحديد الكل",+ "clearGroupSelection": "مسح",+ "groupsSelectedCount": "المحدد: {{count}}",+ "noGroupsMatch": "لا توجد مجموعات تطابق بحثك","phoneHint": "استخدم الصيغة الدولية بدون مسافات","messageType": "نوع الرسالة","types": {@@ -714,15 +718,18 @@"bulkDelayHint": "1000–60000 مللي ثانية (الافتراضي 3000)","send": "إرسال الرسالة","sending": "جارٍ الإرسال...",+ "sendingProgress": "جارٍ الإرسال {{current}}/{{total}}...","viewOnly": "للعرض فقط","responseEmpty": "أرسل رسالة لرؤية استجابة API","successLabel": "نجاح","failedLabel": "فشل",+ "groupsSentSummary": "تم إرسال {{sent}}/{{total}}","response": {"timestamp": "الوقت","messageId": "معرّف الرسالة","batchId": "معرّف الدفعة",- "error": "خطأ"+ "error": "خطأ",+ "groups": "المجموعات"},"sendFailed": "فشل إرسال الرسالة","notOnWhatsApp": "هذا الرقم غير مسجَّل على واتساب",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 6e38e5792..37caa259f 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -640,6 +640,10 @@"loadingGroups": "Gruppen werden geladen...","noGroupsFound": "Keine Gruppen gefunden","selectGroupHint": "Wähle eine Gruppe aus deinem WhatsApp-Konto aus",+ "selectAllGroups": "Alle auswählen",+ "clearGroupSelection": "Auswahl aufheben",+ "groupsSelectedCount": "Ausgewählt: {{count}}",+ "noGroupsMatch": "Keine Gruppen passen zu deiner Suche","phoneHint": "Verwende das internationale Format ohne Leerzeichen","messageType": "Nachrichtentyp","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 ms (Standard: 3000)","send": "Nachricht senden","sending": "Wird gesendet...",+ "sendingProgress": "Wird gesendet {{current}}/{{total}}...","viewOnly": "Nur ansehen","responseEmpty": "Sende eine Nachricht, um die API-Antwort anzuzeigen","successLabel": "Erfolgreich","failedLabel": "Fehlgeschlagen",+ "groupsSentSummary": "{{sent}}/{{total}} gesendet","response": {"timestamp": "Zeitstempel","messageId": "Nachrichten-ID","batchId": "Batch-ID",- "error": "Fehler"+ "error": "Fehler",+ "groups": "Gruppen"},"sendFailed": "Nachricht konnte nicht gesendet werden","notOnWhatsApp": "Diese Nummer ist nicht bei WhatsApp registriert",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex c81058bde..0c997e836 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -640,6 +640,10 @@"loadingGroups": "Loading groups...","noGroupsFound": "No groups found","selectGroupHint": "Select a group from your WhatsApp",+ "selectAllGroups": "Select all",+ "clearGroupSelection": "Clear",+ "groupsSelectedCount": "Selected: {{count}}",+ "noGroupsMatch": "No groups match your search","phoneHint": "Use international format without spaces","messageType": "Message Type","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 ms (default 3000)","send": "Send Message","sending": "Sending...",+ "sendingProgress": "Sending {{current}}/{{total}}...","viewOnly": "View Only","responseEmpty": "Send a message to see the API response","successLabel": "Success","failedLabel": "Failed",+ "groupsSentSummary": "{{sent}}/{{total}} sent","response": {"timestamp": "Timestamp","messageId": "Message ID","batchId": "Batch ID",- "error": "Error"+ "error": "Error",+ "groups": "Groups"},"sendFailed": "Failed to send message","notOnWhatsApp": "This number is not registered on WhatsApp",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 2c708a375..551c9f8fe 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -591,6 +591,10 @@"loadingGroups": "Cargando grupos...","noGroupsFound": "No se encontraron grupos","selectGroupHint": "Selecciona un grupo de tu WhatsApp",+ "selectAllGroups": "Seleccionar todos",+ "clearGroupSelection": "Limpiar",+ "groupsSelectedCount": "Seleccionados: {{count}}",+ "noGroupsMatch": "Ningún grupo coincide con tu búsqueda","phoneHint": "Usa formato internacional sin espacios","messageType": "Tipo de mensaje","types": {@@ -650,15 +654,18 @@"bulkDelayHint": "1000–60000 ms (predeterminado: 3000)","send": "Enviar mensaje","sending": "Enviando...",+ "sendingProgress": "Enviando {{current}}/{{total}}...","viewOnly": "Solo lectura","responseEmpty": "Envía un mensaje para ver la respuesta de la API","successLabel": "Éxito","failedLabel": "Fallido",+ "groupsSentSummary": "{{sent}}/{{total}} enviados","response": {"timestamp": "Fecha/Hora","messageId": "ID de mensaje","batchId": "ID del lote",- "error": "Error"+ "error": "Error",+ "groups": "Grupos"},"sendFailed": "Error al enviar el mensaje","notOnWhatsApp": "Este número no está registrado en WhatsApp",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex bd1692da4..5c51f1ae0 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -640,6 +640,10 @@"loadingGroups": "Chargement des groupes...","noGroupsFound": "Aucun groupe trouvé","selectGroupHint": "Sélectionnez un groupe depuis votre WhatsApp",+ "selectAllGroups": "Tout sélectionner",+ "clearGroupSelection": "Effacer",+ "groupsSelectedCount": "Sélectionnés : {{count}}",+ "noGroupsMatch": "Aucun groupe ne correspond à votre recherche","phoneHint": "Utilisez le format international sans espaces","messageType": "Type de message","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 ms (par défaut : 3000)","send": "Envoyer le message","sending": "Envoi...",+ "sendingProgress": "Envoi {{current}}/{{total}}...","viewOnly": "Lecture seule","responseEmpty": "Envoyez un message pour voir la réponse de l'API","successLabel": "Succès","failedLabel": "Échec",+ "groupsSentSummary": "{{sent}}/{{total}} envoyés","response": {"timestamp": "Horodatage","messageId": "ID du message","batchId": "ID du lot",- "error": "Erreur"+ "error": "Erreur",+ "groups": "Groupes"},"sendFailed": "Échec de l'envoi du message","notOnWhatsApp": "Ce numéro n'est pas enregistré sur WhatsApp",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 3c849d022..91dceefee 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -649,6 +649,10 @@"loadingGroups": "טוען קבוצות...","noGroupsFound": "לא נמצאו קבוצות","selectGroupHint": "יש לבחור קבוצה מתוך WhatsApp",+ "selectAllGroups": "בחירת הכל",+ "clearGroupSelection": "ניקוי",+ "groupsSelectedCount": "נבחרו: {{count}}",+ "noGroupsMatch": "אין קבוצות התואמות לחיפוש","phoneHint": "יש להשתמש בפורמט בינלאומי ללא רווחים","messageType": "סוג הודעה","types": {@@ -708,15 +712,18 @@"bulkDelayHint": "1000–60000 אלפיות שנייה (ברירת מחדל 3000)","send": "שליחת הודעה","sending": "שולח...",+ "sendingProgress": "שולח {{current}}/{{total}}...","viewOnly": "צפייה בלבד","responseEmpty": "יש לשלוח הודעה כדי לראות את תגובת ה-API","successLabel": "הצלחה","failedLabel": "נכשל",+ "groupsSentSummary": "נשלחו {{sent}}/{{total}}","response": {"timestamp": "חותמת זמן","messageId": "מזהה הודעה","batchId": "מזהה אצווה",- "error": "שגיאה"+ "error": "שגיאה",+ "groups": "קבוצות"},"sendFailed": "שליחת ההודעה נכשלה","notOnWhatsApp": "מספר זה אינו רשום בוואטסאפ",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 973fd5c2f..687b3eb75 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -640,6 +640,10 @@"loadingGroups": "Caricamento gruppi...","noGroupsFound": "Nessun gruppo trovato","selectGroupHint": "Seleziona un gruppo dal tuo WhatsApp",+ "selectAllGroups": "Seleziona tutti",+ "clearGroupSelection": "Deseleziona",+ "groupsSelectedCount": "Selezionati: {{count}}",+ "noGroupsMatch": "Nessun gruppo corrisponde alla tua ricerca","phoneHint": "Usa il formato internazionale senza spazi","messageType": "Tipo di Messaggio","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 ms (predefinito: 3000)","send": "Invia Messaggio","sending": "Invio in corso...",+ "sendingProgress": "Invio in corso {{current}}/{{total}}...","viewOnly": "Sola Visualizzazione","responseEmpty": "Invia un messaggio per vedere la risposta delle API","successLabel": "Successo","failedLabel": "Fallito",+ "groupsSentSummary": "{{sent}}/{{total}} inviati","response": {"timestamp": "Timestamp","messageId": "ID Messaggio","batchId": "ID batch",- "error": "Errore"+ "error": "Errore",+ "groups": "Gruppi"},"sendFailed": "Impossibile inviare il messaggio","notOnWhatsApp": "Questo numero non è registrato su WhatsApp",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 2bb71309a..98cd1e21c 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -640,6 +640,10 @@"loadingGroups": "그룹 불러오는 중...","noGroupsFound": "그룹을 찾을 수 없습니다","selectGroupHint": "내 WhatsApp에서 그룹을 선택하세요",+ "selectAllGroups": "모두 선택",+ "clearGroupSelection": "선택 해제",+ "groupsSelectedCount": "선택됨: {{count}}",+ "noGroupsMatch": "검색과 일치하는 그룹이 없습니다","phoneHint": "공백 없이 국제 형식으로 입력하세요","messageType": "메시지 유형","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000ms (기본값 3000)","send": "메시지 보내기","sending": "보내는 중...",+ "sendingProgress": "보내는 중 {{current}}/{{total}}...","viewOnly": "읽기 전용","responseEmpty": "메시지를 보내면 API 응답이 여기에 표시됩니다","successLabel": "성공","failedLabel": "실패",+ "groupsSentSummary": "{{sent}}/{{total}}개 전송됨","response": {"timestamp": "타임스탬프","messageId": "메시지 ID","batchId": "배치 ID",- "error": "오류"+ "error": "오류",+ "groups": "그룹"},"sendFailed": "메시지를 보내지 못했습니다","notOnWhatsApp": "이 번호는 WhatsApp에 등록되어 있지 않습니다",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 753e753a1..ae0b08e37 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -591,6 +591,10 @@"loadingGroups": "Carregando grupos...","noGroupsFound": "Nenhum grupo encontrado","selectGroupHint": "Selecione um grupo do seu WhatsApp",+ "selectAllGroups": "Selecionar todos",+ "clearGroupSelection": "Limpar",+ "groupsSelectedCount": "Selecionados: {{count}}",+ "noGroupsMatch": "Nenhum grupo corresponde à sua pesquisa","phoneHint": "Use formato internacional sem espaços","messageType": "Tipo de mensagem","types": {@@ -650,15 +654,18 @@"bulkDelayHint": "1000–60000 ms (padrão: 3000)","send": "Enviar mensagem","sending": "Enviando...",+ "sendingProgress": "Enviando {{current}}/{{total}}...","viewOnly": "Somente leitura","responseEmpty": "Envie uma mensagem para ver a resposta da API","successLabel": "Sucesso","failedLabel": "Falhou",+ "groupsSentSummary": "{{sent}}/{{total}} enviados","response": {"timestamp": "Data/Hora","messageId": "ID da mensagem","batchId": "ID do lote",- "error": "Erro"+ "error": "Erro",+ "groups": "Grupos"},"sendFailed": "Erro ao enviar a mensagem","notOnWhatsApp": "Este número não está registrado no WhatsApp",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex eaa4a8984..bf80b31f4 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -640,6 +640,10 @@"loadingGroups": "గ్రూప్లను లోడ్ చేస్తోంది...","noGroupsFound": "ఎలాంటి గ్రూప్లు కనుగొనబడలేదు","selectGroupHint": "మీ వాట్సాప్ నుండి ఒక గ్రూప్ను ఎంచుకోండి",+ "selectAllGroups": "అన్నీ ఎంచుకోండి",+ "clearGroupSelection": "క్లియర్ చేయండి",+ "groupsSelectedCount": "ఎంచుకున్నవి: {{count}}",+ "noGroupsMatch": "మీ శోధనకు సరిపోయే గ్రూప్లు లేవు","phoneHint": "ఖాళీలు (spaces) లేకుండా అంతర్జాతీయ ఆకృతిని ఉపయోగించండి","messageType": "సందేశం రకం","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 ms (డిఫాల్ట్ 3000)","send": "సందేశం పంపు","sending": "పంపుతోంది...",+ "sendingProgress": "పంపుతోంది {{current}}/{{total}}...","viewOnly": "చూడటానికి మాత్రమే","responseEmpty": "API రెస్పాన్స్ చూడటానికి ఒక సందేశాన్ని పంపండి","successLabel": "విజయం","failedLabel": "విఫలమైంది",+ "groupsSentSummary": "{{sent}}/{{total}} పంపబడ్డాయి","response": {"timestamp": "సమయము","messageId": "సందేశం ID","batchId": "బ్యాచ్ ID",- "error": "లోపం"+ "error": "లోపం",+ "groups": "గ్రూప్లు"},"sendFailed": "సందేశాన్ని పంపడం విఫలమైంది","notOnWhatsApp": "ఈ నంబర్ WhatsAppలో నమోదు కాలేదు",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 967d256b0..af029980d 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -640,6 +640,10 @@"loadingGroups": "Gruplar yükleniyor...","noGroupsFound": "Grup bulunamadı","selectGroupHint": "WhatsApp'ınızdan bir grup seçin",+ "selectAllGroups": "Tümünü seç",+ "clearGroupSelection": "Temizle",+ "groupsSelectedCount": "Seçilen: {{count}}",+ "noGroupsMatch": "Aramanızla eşleşen grup yok","phoneHint": "Boşluk bırakmadan uluslararası formatı kullanın","messageType": "Mesaj Türü","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 ms (varsayılan 3000)","send": "Mesajı Gönder","sending": "Gönderiliyor...",+ "sendingProgress": "Gönderiliyor {{current}}/{{total}}...","viewOnly": "Yalnızca Görüntüle","responseEmpty": "API yanıtını görmek için bir mesaj gönderin","successLabel": "Başarılı","failedLabel": "Başarısız",+ "groupsSentSummary": "{{sent}}/{{total}} gönderildi","response": {"timestamp": "Zaman Damgası","messageId": "Mesaj ID'si","batchId": "Toplu İşlem ID'si (Batch ID)",- "error": "Hata"+ "error": "Hata",+ "groups": "Gruplar"},"sendFailed": "Mesaj gönderilemedi","notOnWhatsApp": "Bu numara WhatsApp'ta kayıtlı değil",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex d67c61178..507b44540 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -640,6 +640,10 @@"loadingGroups": "正在加载群组...","noGroupsFound": "未找到群组","selectGroupHint": "从你的 WhatsApp 中选择一个群组",+ "selectAllGroups": "全选",+ "clearGroupSelection": "清除",+ "groupsSelectedCount": "已选择:{{count}}",+ "noGroupsMatch": "没有与搜索匹配的群组","phoneHint": "使用无空格的国际格式","messageType": "消息类型","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 毫秒(默认 3000)","send": "发送消息","sending": "正在发送...",+ "sendingProgress": "正在发送 {{current}}/{{total}}...","viewOnly": "仅查看","responseEmpty": "发送消息后即可查看 API 响应","successLabel": "成功","failedLabel": "失败",+ "groupsSentSummary": "已发送 {{sent}}/{{total}}","response": {"timestamp": "时间戳","messageId": "消息 ID","batchId": "批次 ID",- "error": "错误"+ "error": "错误",+ "groups": "群组"},"sendFailed": "发送消息失败","notOnWhatsApp": "该号码未在 WhatsApp 注册",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 494a7f688..0d8c6a570 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -640,6 +640,10 @@"loadingGroups": "正在載入群組...","noGroupsFound": "找不到群組","selectGroupHint": "從你的 WhatsApp 選擇一個群組",+ "selectAllGroups": "全選",+ "clearGroupSelection": "清除",+ "groupsSelectedCount": "已選擇:{{count}}",+ "noGroupsMatch": "沒有與搜尋相符的群組","phoneHint": "使用不含空格的國際格式","messageType": "訊息類型","types": {@@ -699,15 +703,18 @@"bulkDelayHint": "1000–60000 毫秒(預設 3000)","send": "傳送訊息","sending": "正在傳送...",+ "sendingProgress": "正在傳送 {{current}}/{{total}}...","viewOnly": "僅檢視","responseEmpty": "傳送訊息後即可查看 API 回應","successLabel": "成功","failedLabel": "失敗",+ "groupsSentSummary": "已傳送 {{sent}}/{{total}}","response": {"timestamp": "時間戳記","messageId": "訊息 ID","batchId": "批次 ID",- "error": "錯誤"+ "error": "錯誤",+ "groups": "群組"},"sendFailed": "傳送訊息失敗","notOnWhatsApp": "此號碼未在 WhatsApp 註冊",diff --git a/dashboard/src/pages/MessageTester.css b/dashboard/src/pages/MessageTester.cssindex af95f77f4..12bc1f168 100644--- a/dashboard/src/pages/MessageTester.css+++ b/dashboard/src/pages/MessageTester.css@@ -377,6 +377,83 @@margin: 0;}+.message-tester .group-picker {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.message-tester .group-picker-toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.5rem;+}++.message-tester .group-picker-toolbar .browse-btn {+ padding: 0.375rem 0.75rem;+ font-size: 0.8125rem;+}++.message-tester .group-picker-toolbar .browse-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.message-tester .group-picker-count {+ margin-inline-start: auto;+ font-size: 0.8125rem;+ color: var(--text-secondary);+}++.message-tester .group-picker-list {+ display: flex;+ flex-direction: column;+ max-height: 240px;+ overflow-y: auto;+ padding: 0.25rem;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ background: var(--bg-white);+}++.message-tester .form-group label.checkbox-label.group-picker-option {+ padding: 0.5rem 0.625rem;+ border-radius: 6px;+}++.message-tester .form-group label.checkbox-label.group-picker-option:hover {+ background: var(--bg-light);+}++.message-tester .group-picker-option span {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.message-tester .group-picker-empty {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.75rem;+ font-size: 0.875rem;+ color: var(--text-muted);+}++.message-tester .detail-row.group-failures {+ gap: 1rem;+}++.message-tester .detail-row.group-failures ul {+ margin: 0;+ padding: 0;+ list-style: none;+ color: var(--error);+ text-align: end;+}+/* Bulk batch progress block in the response panel. */.message-tester .batch-status {margin-bottom: 1rem;diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 1930787f9..43c772c35 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -13,7 +13,10 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useRole } from '../hooks/useRole';import { useSessionsQuery, useSessionGroupsQuery } from '../hooks/queries';import { parseBulkRecipients, BULK_MAX_RECIPIENTS, BULK_RECIPIENTS_FILE_MAX_BYTES } from '../utils/bulkRecipients';+import { groupLabel } from '../utils/groupSelection';+import { sendSequentially } from '../utils/sendSequentially';import { PageHeader } from '../components/PageHeader';+import { GroupPicker } from '../components/GroupPicker';import './MessageTester.css';interface ApiResponse {@@ -27,8 +30,15 @@ interface ApiResponse {// request was made (the recipient pre-check below short-circuits) — the panel then shows the// outcome without a code rather than inventing one.status?: number;+ groups?: {+ sent: number;+ total: number;+ failures: { id: string; name: string; error: string }[];+ };}+const GROUP_SEND_DELAY_MS = 3000;+const messageTypes = ['text','image',@@ -95,7 +105,8 @@ export function MessageTester() {const [session, setSession] = useState('');const [recipient, setRecipient] = useState('');const [recipientType, setRecipientType] = useState<'personal' | 'group'>('personal');- const [selectedGroup, setSelectedGroup] = useState('');+ const [selectedGroups, setSelectedGroups] = useState<string[]>([]);+ const [groupSendProgress, setGroupSendProgress] = useState<{ current: number; total: number } | null>(null);const [messageType, setMessageType] = useState<(typeof messageTypes)[number]>('text');const [content, setContent] = useState('');const [mediaUrl, setMediaUrl] = useState('');@@ -152,20 +163,9 @@ export function MessageTester() {}}, [sessions, session]);- // Clear the group selection when the session changes so a stale group id from the previous session- // can't be sent to; the effect below then re-seeds groups[0].id once the new session's groups load.useEffect(() => {- setSelectedGroup('');- }, [session]);-- useEffect(() => {- if (groups.length > 0 && !selectedGroup) {- setSelectedGroup(groups[0].id);- }- if (recipientType !== 'group') {- setSelectedGroup('');- }- }, [groups, selectedGroup, recipientType]);+ setSelectedGroups([]);+ }, [session, recipientType]);const stopBatchPolling = () => {if (batchPollRef.current) {@@ -297,10 +297,10 @@ export function MessageTester() {isLoading ||!session ||!formValid ||- (messageType !== 'bulk' && (recipientType === 'group' ? !selectedGroup : !recipient));+ (messageType !== 'bulk' && (recipientType === 'group' ? selectedGroups.length === 0 : !recipient));const handleSend = async () => {- const targetId = recipientType === 'group' ? selectedGroup : recipient;+ const targetId = recipientType === 'group' ? (selectedGroups[0] ?? '') : recipient;if (!session || (messageType !== 'bulk' && !targetId)) return;setIsLoading(true);setResponse(null);@@ -309,46 +309,7 @@ export function MessageTester() {setBatchStatus(null);setBatchError(null);- try {- // For a personal recipient, let the engine resolve the number to its canonical chat id rather- // than hand-building an engine-specific JID here (#265) — also surfaces unregistered numbers.- // Bulk carries its own recipient list, so the shared selector's target is not resolved there.- let chatId = targetId;- if (messageType !== 'bulk' && recipientType !== 'group') {- const resolved = await contactApi.checkNumber(session, targetId.replace(/[^0-9]/g, ''));- if (!resolved.exists || !resolved.whatsappId) {- setResponse({- success: false,- timestamp: new Date().toISOString(),- error: t('messageTester.notOnWhatsApp'),- });- return;- }- chatId = resolved.whatsappId;- }-- // Bulk is a batch, not a single send: 202 + batchId, then poll progress until terminal.- if (messageType === 'bulk') {- const batch = await messageApi.sendBulk(session, {- messages: bulkRecipientList.map(recipientChatId => ({- chatId: recipientChatId,- type: 'text' as const,- content: { text: content },- })),- ...(delayMs !== undefined ? { options: { delayBetweenMessages: delayMs } } : {}),- });- batchSessionRef.current = session;- setResponse({ success: true, timestamp: new Date().toISOString(), batchId: batch.batchId });- setBatchStatus({- batchId: batch.batchId,- status: 'pending',- progress: { total: batch.totalMessages, sent: 0, failed: 0, pending: batch.totalMessages, cancelled: 0 },- results: [],- });- startBatchPolling(session, batch.batchId);- return;- }-+ const sendToChat = async (chatId: string): Promise<MessageResponse> => {let result: MessageResponse;switch (messageType) {case 'text':@@ -405,14 +366,7 @@ export function MessageTester() {let toChatId = forwardTo.trim();if (!toChatId.includes('@')) {const resolvedTo = await contactApi.checkNumber(session, toChatId.replace(/[^0-9]/g, ''));- if (!resolvedTo.exists || !resolvedTo.whatsappId) {- setResponse({- success: false,- timestamp: new Date().toISOString(),- error: t('messageTester.notOnWhatsApp'),- });- return;- }+ if (!resolvedTo.exists || !resolvedTo.whatsappId) throw new Error(t('messageTester.notOnWhatsApp'));toChatId = resolvedTo.whatsappId;}result = await messageApi.forward(session, {@@ -426,7 +380,79 @@ export function MessageTester() {default:throw new Error(`Unsupported message type: ${messageType}`);}+ return result;+ };++ try {+ // For a personal recipient, let the engine resolve the number to its canonical chat id rather+ // than hand-building an engine-specific JID here (#265) — also surfaces unregistered numbers.+ // Bulk carries its own recipient list, so the shared selector's target is not resolved there.+ let chatId = targetId;+ if (messageType !== 'bulk' && recipientType !== 'group') {+ const resolved = await contactApi.checkNumber(session, targetId.replace(/[^0-9]/g, ''));+ if (!resolved.exists || !resolved.whatsappId) {+ setResponse({+ success: false,+ timestamp: new Date().toISOString(),+ error: t('messageTester.notOnWhatsApp'),+ });+ return;+ }+ chatId = resolved.whatsappId;+ }+ // Bulk is a batch, not a single send: 202 + batchId, then poll progress until terminal.+ if (messageType === 'bulk') {+ const batch = await messageApi.sendBulk(session, {+ messages: bulkRecipientList.map(recipientChatId => ({+ chatId: recipientChatId,+ type: 'text' as const,+ content: { text: content },+ })),+ ...(delayMs !== undefined ? { options: { delayBetweenMessages: delayMs } } : {}),+ });+ batchSessionRef.current = session;+ setResponse({ success: true, timestamp: new Date().toISOString(), batchId: batch.batchId });+ setBatchStatus({+ batchId: batch.batchId,+ status: 'pending',+ progress: { total: batch.totalMessages, sent: 0, failed: 0, pending: batch.totalMessages, cancelled: 0 },+ results: [],+ });+ startBatchPolling(session, batch.batchId);+ return;+ }++ if (recipientType === 'group' && messageType !== 'forward' && selectedGroups.length > 1) {+ const groupNames = new Map(groups.map(group => [group.id, groupLabel(group)]));+ const { sent, failures } = await sendSequentially(+ selectedGroups,+ async groupId => {+ const groupResult = await sendToChat(groupId);+ if (!groupResult.messageId) throw new Error(t('messageTester.sendFailed'));+ },+ {+ delayMs: GROUP_SEND_DELAY_MS,+ onProgress: (current, total) => setGroupSendProgress({ current, total }),+ },+ );+ setResponse({+ success: sent > 0,+ timestamp: new Date().toISOString(),+ groups: {+ sent,+ total: selectedGroups.length,+ failures: failures.map(({ target, error }) => ({+ id: target,+ name: groupNames.get(target) ?? target,+ error,+ })),+ },+ });+ return;+ }++ const result = await sendToChat(chatId);setResponse({success: !!result.messageId,messageId: result.messageId,@@ -441,6 +467,7 @@ export function MessageTester() {});} finally {setIsLoading(false);+ setGroupSendProgress(null);}};@@ -514,32 +541,25 @@ export function MessageTester() {</div><div className="form-group">- <label htmlFor="mt-13">- {recipientType === 'group' ? t('messageTester.selectGroup') : t('messageTester.recipientPhone')}- </label>{recipientType === 'group' ? (<>- <select- id="mt-13"- value={selectedGroup}- onChange={e => setSelectedGroup(e.target.value)}- disabled={loadingGroups || groups.length === 0}- >- {loadingGroups && <option value="">{t('messageTester.loadingGroups')}</option>}- {!loadingGroups && groups.length === 0 && (- <option value="">{t('messageTester.noGroupsFound')}</option>- )}- {groups.map(g => (- <option key={g.id} value={g.id}>- {g.name}- </option>- ))}- </select>+ <span className="group-label" id="group-picker-label">+ {t('messageTester.selectGroup')}+ </span>+ <GroupPicker+ groups={groups}+ selectedIds={selectedGroups}+ onChange={setSelectedGroups}+ loading={loadingGroups}+ labelledBy="group-picker-label"+ /><span className="hint">{t('messageTester.selectGroupHint')}</span></>) : (<>+ <label htmlFor="mt-13">{t('messageTester.recipientPhone')}</label><input+ id="mt-13"type="text"value={recipient}onChange={e => setRecipient(e.target.value)}@@ -802,7 +822,8 @@ export function MessageTester() {value={forwardFrom}onChange={e => setForwardFrom(e.target.value)}placeholder={- (recipientType === 'group' ? selectedGroup : recipient) || t('messageTester.forwardFromPlaceholder')+ (recipientType === 'group' ? selectedGroups[0] : recipient) ||+ t('messageTester.forwardFromPlaceholder')}/><span className="hint">{t('messageTester.forwardFromHint')}</span>@@ -898,7 +919,13 @@ export function MessageTester() {<button className="send-btn" onClick={handleSend} disabled={isSendDisabled}>{isLoading ? <Loader2 className="animate-spin" size={18} /> : <Send size={18} />}- {isLoading ? t('messageTester.sending') : canWrite ? t('messageTester.send') : t('messageTester.viewOnly')}+ {isLoading+ ? groupSendProgress+ ? t('messageTester.sendingProgress', groupSendProgress)+ : t('messageTester.sending')+ : canWrite+ ? t('messageTester.send')+ : t('messageTester.viewOnly')}</button></div>@@ -951,6 +978,29 @@ export function MessageTester() {</span></div>)}+ {response.groups && (+ <div className="detail-row">+ <span className="detail-label">{t('messageTester.response.groups')}</span>+ <span className="detail-value">+ {t('messageTester.groupsSentSummary', {+ sent: response.groups.sent,+ total: response.groups.total,+ })}+ </span>+ </div>+ )}+ {response.groups && response.groups.failures.length > 0 && (+ <div className="detail-row group-failures">+ <span className="detail-label">{t('messageTester.response.error')}</span>+ <ul className="detail-value">+ {response.groups.failures.map(failure => (+ <li key={failure.id}>+ <strong>{failure.name}</strong>: {failure.error}+ </li>+ ))}+ </ul>+ </div>+ )}</div>{response.batchId && batchStatus && response.batchId === batchStatus.batchId && (diff --git a/dashboard/src/utils/groupSelection.test.ts b/dashboard/src/utils/groupSelection.test.tsnew file mode 100644index 000000000..d78c68b89--- /dev/null+++ b/dashboard/src/utils/groupSelection.test.ts@@ -0,0 +1,56 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { addGroupIds, filterGroupsByName, groupLabel, toggleGroupId } from './groupSelection.ts';++const groups = [+ { id: '[email protected]', name: 'Family' },+ { id: '[email protected]', name: 'Work Team' },+ { id: '[email protected]', name: 'Football' },+ { id: '[email protected]', name: ' ' },+];++test('labels a group by its name, falling back to the id when the name is blank', () => {+ assert.equal(groupLabel(groups[0]), 'Family');+ assert.equal(groupLabel(groups[3]), '[email protected]');+});++test('an empty or whitespace query keeps every group', () => {+ assert.deepEqual(filterGroupsByName(groups, ''), groups);+ assert.deepEqual(filterGroupsByName(groups, ' '), groups);+});++test('filters by a case-insensitive substring of the name', () => {+ assert.deepEqual(+ filterGroupsByName(groups, 'fa').map(group => group.id),+ ['[email protected]'],+ );+ assert.deepEqual(+ filterGroupsByName(groups, ' TEAM ').map(group => group.id),+ ['[email protected]'],+ );+});++test('a nameless group is found by its id', () => {+ assert.deepEqual(+ filterGroupsByName(groups, '444').map(group => group.id),+ ['[email protected]'],+ );+});++test('returns a new array so callers never mutate the source list', () => {+ const result = filterGroupsByName(groups, '');+ assert.notEqual(result, groups);+});++test('toggling adds a missing id and removes a present one', () => {+ assert.deepEqual(toggleGroupId(['[email protected]'], '[email protected]'), ['[email protected]', '[email protected]']);+ assert.deepEqual(toggleGroupId(['[email protected]', '[email protected]'], '[email protected]'), ['[email protected]']);+});++test('adding ids keeps the existing selection first and drops duplicates', () => {+ assert.deepEqual(addGroupIds(['[email protected]', '[email protected]'], ['[email protected]', '[email protected]']), [+ '[email protected]',+ '[email protected]',+ '[email protected]',+ ]);+});diff --git a/dashboard/src/utils/groupSelection.ts b/dashboard/src/utils/groupSelection.tsnew file mode 100644index 000000000..0e29829ff--- /dev/null+++ b/dashboard/src/utils/groupSelection.ts@@ -0,0 +1,22 @@+export interface SelectableGroup {+ id: string;+ name: string;+}++export function groupLabel(group: SelectableGroup): string {+ return group.name.trim() || group.id;+}++export function filterGroupsByName<T extends SelectableGroup>(groups: readonly T[], query: string): T[] {+ const needle = query.trim().toLocaleLowerCase();+ if (!needle) return [...groups];+ return groups.filter(group => groupLabel(group).toLocaleLowerCase().includes(needle));+}++export function toggleGroupId(selectedIds: readonly string[], id: string): string[] {+ return selectedIds.includes(id) ? selectedIds.filter(current => current !== id) : [...selectedIds, id];+}++export function addGroupIds(selectedIds: readonly string[], ids: readonly string[]): string[] {+ return [...new Set([...selectedIds, ...ids])];+}diff --git a/dashboard/src/utils/sendSequentially.test.ts b/dashboard/src/utils/sendSequentially.test.tsnew file mode 100644index 000000000..f1776bf0e--- /dev/null+++ b/dashboard/src/utils/sendSequentially.test.ts@@ -0,0 +1,83 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { sendSequentially } from './sendSequentially.ts';++const noSleep = async () => {};++test('sends to every target in order and counts the successes', async () => {+ const calls: string[] = [];+ const result = await sendSequentially(+ ['a', 'b', 'c'],+ async target => {+ calls.push(target);+ },+ { delayMs: 3000, sleep: noSleep },+ );+ assert.deepEqual(calls, ['a', 'b', 'c']);+ assert.deepEqual(result, { sent: 3, failures: [] });+});++test('waits the delay between targets but not before the first or after the last', async () => {+ const events: string[] = [];+ await sendSequentially(+ ['a', 'b', 'c'],+ async target => {+ events.push(`send:${target}`);+ },+ {+ delayMs: 3000,+ sleep: async ms => {+ events.push(`sleep:${ms}`);+ },+ },+ );+ assert.deepEqual(events, ['send:a', 'sleep:3000', 'send:b', 'sleep:3000', 'send:c']);+});++test('a failing target is recorded and the remaining targets are still sent', async () => {+ const calls: string[] = [];+ const result = await sendSequentially(+ ['a', 'b', 'c'],+ async target => {+ calls.push(target);+ if (target === 'b') throw new Error('Group not found');+ },+ { delayMs: 3000, sleep: noSleep },+ );+ assert.deepEqual(calls, ['a', 'b', 'c']);+ assert.deepEqual(result, { sent: 2, failures: [{ target: 'b', error: 'Group not found' }] });+});++test('a non-Error rejection is stringified', async () => {+ const result = await sendSequentially(+ ['a'],+ async () => {+ throw 'offline';+ },+ { delayMs: 0, sleep: noSleep },+ );+ assert.deepEqual(result.failures, [{ target: 'a', error: 'offline' }]);+});++test('reports progress before each send', async () => {+ const progress: string[] = [];+ await sendSequentially(['a', 'b'], async () => {}, {+ delayMs: 0,+ sleep: noSleep,+ onProgress: (current, total) => progress.push(`${current}/${total}`),+ });+ assert.deepEqual(progress, ['1/2', '2/2']);+});++test('an empty target list sends nothing', async () => {+ let called = false;+ const result = await sendSequentially(+ [],+ async () => {+ called = true;+ },+ { delayMs: 3000, sleep: noSleep },+ );+ assert.equal(called, false);+ assert.deepEqual(result, { sent: 0, failures: [] });+});diff --git a/dashboard/src/utils/sendSequentially.ts b/dashboard/src/utils/sendSequentially.tsnew file mode 100644index 000000000..c24001044--- /dev/null+++ b/dashboard/src/utils/sendSequentially.ts@@ -0,0 +1,37 @@+export interface SequentialSendFailure<T> {+ target: T;+ error: string;+}++export interface SequentialSendResult<T> {+ sent: number;+ failures: SequentialSendFailure<T>[];+}++export interface SequentialSendOptions {+ delayMs: number;+ sleep?: (ms: number) => Promise<void>;+ onProgress?: (current: number, total: number) => void;+}++const wait = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));++export async function sendSequentially<T>(+ targets: readonly T[],+ send: (target: T) => Promise<void>,+ { delayMs, sleep = wait, onProgress }: SequentialSendOptions,+): Promise<SequentialSendResult<T>> {+ const failures: SequentialSendFailure<T>[] = [];+ let sent = 0;+ for (const [index, target] of targets.entries()) {+ if (index > 0) await sleep(delayMs);+ onProgress?.(index + 1, targets.length);+ try {+ await send(target);+ sent += 1;+ } catch (err) {+ failures.push({ target, error: err instanceof Error ? err.message : String(err) });+ }+ }+ return { sent, failures };+}