Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): stop, cancel and cap the multi-group send
Cares T.7f78b2141376
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef76ba266..829d49aab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,9 +15,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The dashboard Chats thread shows a quote preview and call detail on history-loaded messages, which previously rendered on live messages only. Thanks @gabrielmmoraes1999.- The dashboard Chats thread renders inbound Baileys prompt `buttons` and taps them through `POST .../messages/click-button`; prompt choices are also kept in persisted message `metadata` so they survive reload for rendering. Clicking still requires the prompt to be in the engine store, so an evicted prompt 404s. Thanks @gabrielmmoraes1999.- Webhook and automation filters accept a `chatId` condition, so a webhook can be scoped to specific groups or chats instead of only to a sender ([#1634](https://github.com/rmyndharis/OpenWA/issues/1634)). Thanks @krishshah9944 and @bhavyachopra99.+- The dashboard Message Tester sends to several groups at once: the Group dropdown is now a searchable checkbox list, and each selected group is messaged in turn ([#1650](https://github.com/rmyndharis/OpenWA/pull/1650)). Thanks @C24212.- The dashboard Templates list has a delete button on each row, so a template can be deleted without opening it in the editor first. Like the editor's delete button, it shows only for keys that can write templates. Thanks @C24212.- On the dashboard Chats page, Escape closes the open chat, channel or status viewer and returns to the list. It leaves the key alone while a dialog, a menu or the media viewer is open, since those handle Escape themselves. Thanks @C24212.-- The dashboard Message Tester sends to several groups at once: the Group dropdown is now a searchable checkbox list, and each selected group is messaged in turn ([#1650](https://github.com/rmyndharis/OpenWA/pull/1650)). Thanks @C24212.### Changeddiff --git a/dashboard/src/components/GroupPicker.tsx b/dashboard/src/components/GroupPicker.tsxindex 039b0004a..7acd3f920 100644--- a/dashboard/src/components/GroupPicker.tsx+++ b/dashboard/src/components/GroupPicker.tsx@@ -3,8 +3,8 @@ import { useTranslation } from 'react-i18next';import { Loader2 } from 'lucide-react';import {addGroupIds,- filterGroupsByName,- groupLabel,+ filterGroupRows,+ groupPickerRows,toggleGroupId,type SelectableGroup,} from '../utils/groupSelection';@@ -14,15 +14,28 @@ interface GroupPickerProps {selectedIds: string[];onChange: (ids: string[]) => void;loading: boolean;+ limit: number;labelledBy: string;+ disabled?: boolean;}-export function GroupPicker({ groups, selectedIds, onChange, loading, labelledBy }: GroupPickerProps) {+export function GroupPicker({+ groups,+ selectedIds,+ onChange,+ loading,+ limit,+ labelledBy,+ disabled = false,+}: GroupPickerProps) {const { t } = useTranslation();const [query, setQuery] = useState('');- const visibleGroups = useMemo(() => filterGroupsByName(groups, query), [groups, query]);+ const rows = useMemo(() => groupPickerRows(groups, selectedIds), [groups, selectedIds]);+ const visibleRows = useMemo(() => filterGroupRows(rows, query), [rows, query]);const selected = useMemo(() => new Set(selectedIds), [selectedIds]);- const noGroups = !loading && groups.length === 0;+ const atLimit = selectedIds.length >= limit;+ const noGroups = !loading && rows.length === 0;+ const filtering = query.trim() !== '';return (<div className="group-picker">@@ -32,7 +45,7 @@ export function GroupPicker({ groups, selectedIds, onChange, loading, labelledByonChange={e => setQuery(e.target.value)}placeholder={t('common.search')}aria-label={t('common.search')}- disabled={loading || noGroups}+ disabled={disabled || loading || noGroups}/><div className="group-picker-toolbar"><button@@ -42,42 +55,56 @@ export function GroupPicker({ groups, selectedIds, onChange, loading, labelledByonChange(addGroupIds(selectedIds,- visibleGroups.map(group => group.id),+ visibleRows.map(row => row.id),+ limit,),)}- disabled={loading || visibleGroups.length === 0}+ disabled={disabled || loading || atLimit || visibleRows.length === 0}>- {t('messageTester.selectAllGroups')}+ {filtering ? t('messageTester.selectMatchingGroups') : t('messageTester.selectAllGroups')}</button>- <button type="button" className="browse-btn" onClick={() => onChange([])} disabled={selectedIds.length === 0}>+ <button+ type="button"+ className="browse-btn"+ onClick={() => onChange([])}+ disabled={disabled || selectedIds.length === 0}+ >{t('messageTester.clearGroupSelection')}</button><span className="group-picker-count" role="status">- {t('messageTester.groupsSelectedCount', { count: selectedIds.length })}+ {t('messageTester.groupsSelectedCount', { count: selectedIds.length, max: limit })}</span></div>- <div className="group-picker-list" role="group" aria-labelledby={labelledBy}>+ <div className="group-picker-list">{loading ? (- <div className="group-picker-empty">+ <p className="group-picker-empty"><Loader2 className="animate-spin" size={16} />{t('messageTester.loadingGroups')}- </div>+ </p>) : noGroups ? (- <div className="group-picker-empty">{t('messageTester.noGroupsFound')}</div>- ) : visibleGroups.length === 0 ? (- <div className="group-picker-empty">{t('messageTester.noGroupsMatch')}</div>+ <p className="group-picker-empty">{t('messageTester.noGroupsFound')}</p>+ ) : visibleRows.length === 0 ? (+ <p className="group-picker-empty">{t('messageTester.noGroupsMatch')}</p>) : (- 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>- ))+ <ul aria-labelledby={labelledBy}>+ {visibleRows.map(row => {+ const checked = selected.has(row.id);+ return (+ <li key={row.id}>+ <label className="checkbox-label group-picker-option">+ <input+ type="checkbox"+ checked={checked}+ disabled={disabled || (!checked && atLimit)}+ onChange={() => onChange(toggleGroupId(selectedIds, row.id))}+ />+ <span title={row.label}>{row.label}</span>+ </label>+ </li>+ );+ })}+ </ul>)}</div></div>diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 346fc1c8a..f19f61b0a 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -660,9 +660,11 @@"noGroupsFound": "لم يتم العثور على مجموعات","selectGroupHint": "اختر مجموعة من واتساب الخاص بك","selectAllGroups": "تحديد الكل",+ "selectMatchingGroups": "تحديد النتائج","clearGroupSelection": "مسح",- "groupsSelectedCount": "المحدد: {{count}}",+ "groupsSelectedCount": "المحدد: {{count}}/{{max}}","noGroupsMatch": "لا توجد مجموعات تطابق بحثك",+ "forwardUsesFirstGroup": "تستخدم إعادة التوجيه أول مجموعة محددة فقط، كمحادثة يُعاد التوجيه منها.","phoneHint": "استخدم الصيغة الدولية بدون مسافات","messageType": "نوع الرسالة","types": {@@ -728,12 +730,15 @@"successLabel": "نجاح","failedLabel": "فشل","groupsSentSummary": "تم إرسال {{sent}}/{{total}}",+ "groupSendCancelled": "{{count}}، أُلغيت",+ "groupSendStopped": "{{count}}، توقف بعد HTTP {{status}}","response": {"timestamp": "الوقت","messageId": "معرّف الرسالة","batchId": "معرّف الدفعة","error": "خطأ",- "groups": "المجموعات"+ "groups": "المجموعات",+ "notSent": "لم تُرسل"},"sendFailed": "فشل إرسال الرسالة","notOnWhatsApp": "هذا الرقم غير مسجَّل على واتساب",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 97ddd6a9d..accefa951 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -645,9 +645,11 @@"noGroupsFound": "Keine Gruppen gefunden","selectGroupHint": "Wähle eine Gruppe aus deinem WhatsApp-Konto aus","selectAllGroups": "Alle auswählen",+ "selectMatchingGroups": "Treffer auswählen","clearGroupSelection": "Auswahl aufheben",- "groupsSelectedCount": "Ausgewählt: {{count}}",+ "groupsSelectedCount": "Ausgewählt: {{count}}/{{max}}","noGroupsMatch": "Keine Gruppen passen zu deiner Suche",+ "forwardUsesFirstGroup": "Weiterleiten verwendet nur die erste ausgewählte Gruppe, als Chat, aus dem weitergeleitet wird.","phoneHint": "Verwende das internationale Format ohne Leerzeichen","messageType": "Nachrichtentyp","types": {@@ -713,12 +715,15 @@"successLabel": "Erfolgreich","failedLabel": "Fehlgeschlagen","groupsSentSummary": "{{sent}}/{{total}} gesendet",+ "groupSendCancelled": "{{count}}, abgebrochen",+ "groupSendStopped": "{{count}}, gestoppt nach HTTP {{status}}","response": {"timestamp": "Zeitstempel","messageId": "Nachrichten-ID","batchId": "Batch-ID","error": "Fehler",- "groups": "Gruppen"+ "groups": "Gruppen",+ "notSent": "Nicht gesendet"},"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 2e2baa273..b7eb84367 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -645,9 +645,11 @@"noGroupsFound": "No groups found","selectGroupHint": "Select a group from your WhatsApp","selectAllGroups": "Select all",+ "selectMatchingGroups": "Select matches","clearGroupSelection": "Clear",- "groupsSelectedCount": "Selected: {{count}}",+ "groupsSelectedCount": "Selected: {{count}}/{{max}}","noGroupsMatch": "No groups match your search",+ "forwardUsesFirstGroup": "Forward uses only the first selected group, as the chat to forward from.","phoneHint": "Use international format without spaces","messageType": "Message Type","types": {@@ -713,12 +715,15 @@"successLabel": "Success","failedLabel": "Failed","groupsSentSummary": "{{sent}}/{{total}} sent",+ "groupSendCancelled": "{{count}}, cancelled",+ "groupSendStopped": "{{count}}, stopped after HTTP {{status}}","response": {"timestamp": "Timestamp","messageId": "Message ID","batchId": "Batch ID","error": "Error",- "groups": "Groups"+ "groups": "Groups",+ "notSent": "Not sent"},"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 7f8782c84..babe03014 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -596,9 +596,11 @@"noGroupsFound": "No se encontraron grupos","selectGroupHint": "Selecciona un grupo de tu WhatsApp","selectAllGroups": "Seleccionar todos",+ "selectMatchingGroups": "Seleccionar coincidencias","clearGroupSelection": "Limpiar",- "groupsSelectedCount": "Seleccionados: {{count}}",+ "groupsSelectedCount": "Seleccionados: {{count}}/{{max}}","noGroupsMatch": "Ningún grupo coincide con tu búsqueda",+ "forwardUsesFirstGroup": "Reenviar usa solo el primer grupo seleccionado, como chat de origen.","phoneHint": "Usa formato internacional sin espacios","messageType": "Tipo de mensaje","types": {@@ -664,12 +666,15 @@"successLabel": "Éxito","failedLabel": "Fallido","groupsSentSummary": "{{sent}}/{{total}} enviados",+ "groupSendCancelled": "{{count}}, cancelados",+ "groupSendStopped": "{{count}}, detenido tras HTTP {{status}}","response": {"timestamp": "Fecha/Hora","messageId": "ID de mensaje","batchId": "ID del lote","error": "Error",- "groups": "Grupos"+ "groups": "Grupos",+ "notSent": "No enviados"},"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 dc728bfb3..246a805a9 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -645,9 +645,11 @@"noGroupsFound": "Aucun groupe trouvé","selectGroupHint": "Sélectionnez un groupe depuis votre WhatsApp","selectAllGroups": "Tout sélectionner",+ "selectMatchingGroups": "Sélectionner les résultats","clearGroupSelection": "Effacer",- "groupsSelectedCount": "Sélectionnés : {{count}}",+ "groupsSelectedCount": "Sélectionnés : {{count}}/{{max}}","noGroupsMatch": "Aucun groupe ne correspond à votre recherche",+ "forwardUsesFirstGroup": "Le transfert n'utilise que le premier groupe sélectionné, comme discussion d'origine.","phoneHint": "Utilisez le format international sans espaces","messageType": "Type de message","types": {@@ -713,12 +715,15 @@"successLabel": "Succès","failedLabel": "Échec","groupsSentSummary": "{{sent}}/{{total}} envoyés",+ "groupSendCancelled": "{{count}}, annulés",+ "groupSendStopped": "{{count}}, arrêté après HTTP {{status}}","response": {"timestamp": "Horodatage","messageId": "ID du message","batchId": "ID du lot","error": "Erreur",- "groups": "Groupes"+ "groups": "Groupes",+ "notSent": "Non envoyés"},"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 41f54d008..facfa1cbd 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -654,9 +654,11 @@"noGroupsFound": "לא נמצאו קבוצות","selectGroupHint": "יש לבחור קבוצה מתוך WhatsApp","selectAllGroups": "בחירת הכל",+ "selectMatchingGroups": "בחירת התוצאות","clearGroupSelection": "ניקוי",- "groupsSelectedCount": "נבחרו: {{count}}",+ "groupsSelectedCount": "נבחרו: {{count}}/{{max}}","noGroupsMatch": "אין קבוצות התואמות לחיפוש",+ "forwardUsesFirstGroup": "העברה משתמשת רק בקבוצה הראשונה שנבחרה, כצ'אט שממנו מעבירים.","phoneHint": "יש להשתמש בפורמט בינלאומי ללא רווחים","messageType": "סוג הודעה","types": {@@ -722,12 +724,15 @@"successLabel": "הצלחה","failedLabel": "נכשל","groupsSentSummary": "נשלחו {{sent}}/{{total}}",+ "groupSendCancelled": "{{count}}, בוטלו",+ "groupSendStopped": "{{count}}, נעצר אחרי HTTP {{status}}","response": {"timestamp": "חותמת זמן","messageId": "מזהה הודעה","batchId": "מזהה אצווה","error": "שגיאה",- "groups": "קבוצות"+ "groups": "קבוצות",+ "notSent": "לא נשלחו"},"sendFailed": "שליחת ההודעה נכשלה","notOnWhatsApp": "מספר זה אינו רשום בוואטסאפ",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 91cb7e851..3f845305d 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -645,9 +645,11 @@"noGroupsFound": "Nessun gruppo trovato","selectGroupHint": "Seleziona un gruppo dal tuo WhatsApp","selectAllGroups": "Seleziona tutti",+ "selectMatchingGroups": "Seleziona risultati","clearGroupSelection": "Deseleziona",- "groupsSelectedCount": "Selezionati: {{count}}",+ "groupsSelectedCount": "Selezionati: {{count}}/{{max}}","noGroupsMatch": "Nessun gruppo corrisponde alla tua ricerca",+ "forwardUsesFirstGroup": "L'inoltro usa solo il primo gruppo selezionato, come chat di origine.","phoneHint": "Usa il formato internazionale senza spazi","messageType": "Tipo di Messaggio","types": {@@ -713,12 +715,15 @@"successLabel": "Successo","failedLabel": "Fallito","groupsSentSummary": "{{sent}}/{{total}} inviati",+ "groupSendCancelled": "{{count}}, annullati",+ "groupSendStopped": "{{count}}, interrotto dopo HTTP {{status}}","response": {"timestamp": "Timestamp","messageId": "ID Messaggio","batchId": "ID batch","error": "Errore",- "groups": "Gruppi"+ "groups": "Gruppi",+ "notSent": "Non inviati"},"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 f99a02f8f..9de67396f 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -645,9 +645,11 @@"noGroupsFound": "그룹을 찾을 수 없습니다","selectGroupHint": "내 WhatsApp에서 그룹을 선택하세요","selectAllGroups": "모두 선택",+ "selectMatchingGroups": "검색 결과 선택","clearGroupSelection": "선택 해제",- "groupsSelectedCount": "선택됨: {{count}}",+ "groupsSelectedCount": "선택됨: {{count}}/{{max}}","noGroupsMatch": "검색과 일치하는 그룹이 없습니다",+ "forwardUsesFirstGroup": "전달은 선택한 첫 번째 그룹만 원본 채팅으로 사용합니다.","phoneHint": "공백 없이 국제 형식으로 입력하세요","messageType": "메시지 유형","types": {@@ -713,12 +715,15 @@"successLabel": "성공","failedLabel": "실패","groupsSentSummary": "{{sent}}/{{total}}개 전송됨",+ "groupSendCancelled": "{{count}}개, 취소됨",+ "groupSendStopped": "{{count}}개, HTTP {{status}} 후 중지됨","response": {"timestamp": "타임스탬프","messageId": "메시지 ID","batchId": "배치 ID","error": "오류",- "groups": "그룹"+ "groups": "그룹",+ "notSent": "보내지 않음"},"sendFailed": "메시지를 보내지 못했습니다","notOnWhatsApp": "이 번호는 WhatsApp에 등록되어 있지 않습니다",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex a26c9f337..4198454a1 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -596,9 +596,11 @@"noGroupsFound": "Nenhum grupo encontrado","selectGroupHint": "Selecione um grupo do seu WhatsApp","selectAllGroups": "Selecionar todos",+ "selectMatchingGroups": "Selecionar resultados","clearGroupSelection": "Limpar",- "groupsSelectedCount": "Selecionados: {{count}}",+ "groupsSelectedCount": "Selecionados: {{count}}/{{max}}","noGroupsMatch": "Nenhum grupo corresponde à sua pesquisa",+ "forwardUsesFirstGroup": "Encaminhar usa só o primeiro grupo selecionado, como conversa de origem.","phoneHint": "Use formato internacional sem espaços","messageType": "Tipo de mensagem","types": {@@ -664,12 +666,15 @@"successLabel": "Sucesso","failedLabel": "Falhou","groupsSentSummary": "{{sent}}/{{total}} enviados",+ "groupSendCancelled": "{{count}}, cancelados",+ "groupSendStopped": "{{count}}, interrompido após HTTP {{status}}","response": {"timestamp": "Data/Hora","messageId": "ID da mensagem","batchId": "ID do lote","error": "Erro",- "groups": "Grupos"+ "groups": "Grupos",+ "notSent": "Não enviados"},"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 fa1125534..01d588895 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -645,9 +645,11 @@"noGroupsFound": "ఎలాంటి గ్రూప్లు కనుగొనబడలేదు","selectGroupHint": "మీ వాట్సాప్ నుండి ఒక గ్రూప్ను ఎంచుకోండి","selectAllGroups": "అన్నీ ఎంచుకోండి",+ "selectMatchingGroups": "సరిపోలినవి ఎంచుకోండి","clearGroupSelection": "క్లియర్ చేయండి",- "groupsSelectedCount": "ఎంచుకున్నవి: {{count}}",+ "groupsSelectedCount": "ఎంచుకున్నవి: {{count}}/{{max}}","noGroupsMatch": "మీ శోధనకు సరిపోయే గ్రూప్లు లేవు",+ "forwardUsesFirstGroup": "ఫార్వర్డ్ ఎంచుకున్న మొదటి గ్రూప్ను మాత్రమే, ఫార్వర్డ్ చేసే చాట్గా ఉపయోగిస్తుంది.","phoneHint": "ఖాళీలు (spaces) లేకుండా అంతర్జాతీయ ఆకృతిని ఉపయోగించండి","messageType": "సందేశం రకం","types": {@@ -713,12 +715,15 @@"successLabel": "విజయం","failedLabel": "విఫలమైంది","groupsSentSummary": "{{sent}}/{{total}} పంపబడ్డాయి",+ "groupSendCancelled": "{{count}}, రద్దు చేయబడ్డాయి",+ "groupSendStopped": "{{count}}, HTTP {{status}} తర్వాత ఆపబడింది","response": {"timestamp": "సమయము","messageId": "సందేశం ID","batchId": "బ్యాచ్ ID","error": "లోపం",- "groups": "గ్రూప్లు"+ "groups": "గ్రూప్లు",+ "notSent": "పంపబడలేదు"},"sendFailed": "సందేశాన్ని పంపడం విఫలమైంది","notOnWhatsApp": "ఈ నంబర్ WhatsAppలో నమోదు కాలేదు",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 177fe0277..28385f68f 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -645,9 +645,11 @@"noGroupsFound": "Grup bulunamadı","selectGroupHint": "WhatsApp'ınızdan bir grup seçin","selectAllGroups": "Tümünü seç",+ "selectMatchingGroups": "Eşleşenleri seç","clearGroupSelection": "Temizle",- "groupsSelectedCount": "Seçilen: {{count}}",+ "groupsSelectedCount": "Seçilen: {{count}}/{{max}}","noGroupsMatch": "Aramanızla eşleşen grup yok",+ "forwardUsesFirstGroup": "İletme yalnızca seçilen ilk grubu, iletilecek mesajın bulunduğu sohbet olarak kullanır.","phoneHint": "Boşluk bırakmadan uluslararası formatı kullanın","messageType": "Mesaj Türü","types": {@@ -713,12 +715,15 @@"successLabel": "Başarılı","failedLabel": "Başarısız","groupsSentSummary": "{{sent}}/{{total}} gönderildi",+ "groupSendCancelled": "{{count}}, iptal edildi",+ "groupSendStopped": "{{count}}, HTTP {{status}} sonrası durduruldu","response": {"timestamp": "Zaman Damgası","messageId": "Mesaj ID'si","batchId": "Toplu İşlem ID'si (Batch ID)","error": "Hata",- "groups": "Gruplar"+ "groups": "Gruplar",+ "notSent": "Gönderilmedi"},"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 b6e28b6b2..8923954b2 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -645,9 +645,11 @@"noGroupsFound": "未找到群组","selectGroupHint": "从你的 WhatsApp 中选择一个群组","selectAllGroups": "全选",+ "selectMatchingGroups": "选择匹配项","clearGroupSelection": "清除",- "groupsSelectedCount": "已选择:{{count}}",+ "groupsSelectedCount": "已选择:{{count}}/{{max}}","noGroupsMatch": "没有与搜索匹配的群组",+ "forwardUsesFirstGroup": "转发只使用第一个选中的群组,作为转发来源聊天。","phoneHint": "使用无空格的国际格式","messageType": "消息类型","types": {@@ -713,12 +715,15 @@"successLabel": "成功","failedLabel": "失败","groupsSentSummary": "已发送 {{sent}}/{{total}}",+ "groupSendCancelled": "{{count}} 个,已取消",+ "groupSendStopped": "{{count}} 个,在 HTTP {{status}} 后停止","response": {"timestamp": "时间戳","messageId": "消息 ID","batchId": "批次 ID","error": "错误",- "groups": "群组"+ "groups": "群组",+ "notSent": "未发送"},"sendFailed": "发送消息失败","notOnWhatsApp": "该号码未在 WhatsApp 注册",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 95af930b8..07b401a89 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -645,9 +645,11 @@"noGroupsFound": "找不到群組","selectGroupHint": "從你的 WhatsApp 選擇一個群組","selectAllGroups": "全選",+ "selectMatchingGroups": "選擇相符項目","clearGroupSelection": "清除",- "groupsSelectedCount": "已選擇:{{count}}",+ "groupsSelectedCount": "已選擇:{{count}}/{{max}}","noGroupsMatch": "沒有與搜尋相符的群組",+ "forwardUsesFirstGroup": "轉寄只會使用第一個選取的群組,作為轉寄來源對話。","phoneHint": "使用不含空格的國際格式","messageType": "訊息類型","types": {@@ -713,12 +715,15 @@"successLabel": "成功","failedLabel": "失敗","groupsSentSummary": "已傳送 {{sent}}/{{total}}",+ "groupSendCancelled": "{{count}} 個,已取消",+ "groupSendStopped": "{{count}} 個,在 HTTP {{status}} 後停止","response": {"timestamp": "時間戳記","messageId": "訊息 ID","batchId": "批次 ID","error": "錯誤",- "groups": "群組"+ "groups": "群組",+ "notSent": "未傳送"},"sendFailed": "傳送訊息失敗","notOnWhatsApp": "此號碼未在 WhatsApp 註冊",diff --git a/dashboard/src/pages/MessageTester.css b/dashboard/src/pages/MessageTester.cssindex 12bc1f168..93d89aa4b 100644--- a/dashboard/src/pages/MessageTester.css+++ b/dashboard/src/pages/MessageTester.css@@ -417,6 +417,12 @@background: var(--bg-white);}+.message-tester .group-picker-list ul {+ margin: 0;+ padding: 0;+ list-style: none;+}+.message-tester .form-group label.checkbox-label.group-picker-option {padding: 0.5rem 0.625rem;border-radius: 6px;@@ -437,11 +443,22 @@display: flex;align-items: center;gap: 0.5rem;+ margin: 0;padding: 0.75rem;font-size: 0.875rem;color: var(--text-muted);}+.message-tester .group-send-status {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ margin-top: 0.5rem;+ font-size: 0.8125rem;+ color: var(--text-secondary);+}+.message-tester .detail-row.group-failures {gap: 1rem;}diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 43c772c35..5cb880b78 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -13,10 +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 { groupLabel, isGatewayRefusal, planGroupSend } from '../utils/groupSelection';+import { sendSequentially } from '../utils/sendSequentially';import './MessageTester.css';interface ApiResponse {@@ -34,6 +34,9 @@ interface ApiResponse {sent: number;total: number;failures: { id: string; name: string; error: string }[];+ notSent: number;+ stoppedBy?: 'abort' | 'refusal';+ refusedWith?: number;};}@@ -107,6 +110,8 @@ export function MessageTester() {const [recipientType, setRecipientType] = useState<'personal' | 'group'>('personal');const [selectedGroups, setSelectedGroups] = useState<string[]>([]);const [groupSendProgress, setGroupSendProgress] = useState<{ current: number; total: number } | null>(null);+ const [groupSendCancelling, setGroupSendCancelling] = useState(false);+ const groupSendAbort = useRef<AbortController | null>(null);const [messageType, setMessageType] = useState<(typeof messageTypes)[number]>('text');const [content, setContent] = useState('');const [mediaUrl, setMediaUrl] = useState('');@@ -167,6 +172,8 @@ export function MessageTester() {setSelectedGroups([]);}, [session, recipientType]);+ useEffect(() => () => groupSendAbort.current?.abort(), []);+const stopBatchPolling = () => {if (batchPollRef.current) {clearInterval(batchPollRef.current);@@ -299,6 +306,54 @@ export function MessageTester() {!formValid ||(messageType !== 'bulk' && (recipientType === 'group' ? selectedGroups.length === 0 : !recipient));+ const isGroupSending = groupSendProgress !== null;++ const sendToGroups = async (chatIds: string[], sendTo: (chatId: string) => Promise<MessageResponse>) => {+ const controller = new AbortController();+ groupSendAbort.current = controller;+ const labels = new Map(groups.map(group => [group.id, groupLabel(group)]));+ try {+ const outcome = await sendSequentially(+ chatIds,+ async chatId => {+ const result = await sendTo(chatId);+ if (!result.messageId) throw new Error(t('messageTester.sendFailed'));+ },+ {+ delayMs: GROUP_SEND_DELAY_MS,+ signal: controller.signal,+ stopOn: isGatewayRefusal,+ onProgress: (current, total) => setGroupSendProgress({ current, total }),+ },+ );+ setResponse({+ success: outcome.sent === chatIds.length,+ timestamp: new Date().toISOString(),+ groups: {+ sent: outcome.sent,+ total: chatIds.length,+ failures: outcome.failures.map(({ target, error }) => ({+ id: target,+ name: labels.get(target) ?? target,+ error,+ })),+ notSent: outcome.notAttempted.length,+ stoppedBy: outcome.stoppedBy,+ refusedWith: outcome.stoppedBy === 'refusal' ? outcome.failures.at(-1)?.status : undefined,+ },+ });+ } finally {+ groupSendAbort.current = null;+ setGroupSendProgress(null);+ setGroupSendCancelling(false);+ }+ };++ const cancelGroupSend = () => {+ setGroupSendCancelling(true);+ groupSendAbort.current?.abort();+ };+const handleSend = async () => {const targetId = recipientType === 'group' ? (selectedGroups[0] ?? '') : recipient;if (!session || (messageType !== 'bulk' && !targetId)) return;@@ -309,80 +364,6 @@ export function MessageTester() {setBatchStatus(null);setBatchError(null);- const sendToChat = async (chatId: string): Promise<MessageResponse> => {- let result: MessageResponse;- switch (messageType) {- case 'text':- result = await messageApi.sendText(session, chatId, content);- break;- case 'image':- case 'video':- case 'audio':- case 'document': {- // sendMedia unifies URL and base64 (local file) sends; base64 wins when a file is picked. The- // backend accepts url XOR base64 and requires a mimetype for base64 (always provided here).- const payload: SendMediaPayload = mediaFile- ? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }- : { url: mediaUrl };- if ((messageType === 'image' || messageType === 'video') && content) payload.caption = content;- if (messageType === 'document' && content) payload.filename = content;- result = await messageApi.sendMedia(session, chatId, messageType, payload);- break;- }- case 'sticker': {- const payload: SendMediaPayload = mediaFile- ? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }- : { url: mediaUrl };- result = await messageApi.sendSticker(session, chatId, payload);- break;- }- case 'location':- result = await messageApi.sendLocation(session, {- chatId,- latitude: lat,- longitude: lng,- ...(locationDescription.trim() ? { description: locationDescription.trim() } : {}),- ...(locationAddress.trim() ? { address: locationAddress.trim() } : {}),- });- break;- case 'contact':- result = await messageApi.sendContact(session, {- chatId,- contactName: contactName.trim(),- contactNumber: contactNumber.trim(),- });- break;- case 'poll':- result = await messageApi.sendPoll(session, {- chatId,- name: pollQuestion.trim(),- options: pollOptionsFilled,- ...(allowMultipleAnswers ? { allowMultipleAnswers: true } : {}),- });- break;- case 'forward': {- // toChatId passes through as-is when it is a full chat ID; a bare number is resolved- // through the same check-number flow as the main recipient.- let toChatId = forwardTo.trim();- if (!toChatId.includes('@')) {- const resolvedTo = await contactApi.checkNumber(session, toChatId.replace(/[^0-9]/g, ''));- if (!resolvedTo.exists || !resolvedTo.whatsappId) throw new Error(t('messageTester.notOnWhatsApp'));- toChatId = resolvedTo.whatsappId;- }- result = await messageApi.forward(session, {- // An empty fromChatId defaults to the current (already resolved) recipient.- fromChatId: forwardFrom.trim() || chatId,- toChatId,- messageId: forwardMessageId.trim(),- });- break;- }- 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.@@ -423,36 +404,79 @@ export function MessageTester() {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,- })),- },- });+ const sendTo = async (target: string): Promise<MessageResponse> => {+ switch (messageType) {+ case 'text':+ return messageApi.sendText(session, target, content);+ case 'image':+ case 'video':+ case 'audio':+ case 'document': {+ // sendMedia unifies URL and base64 (local file) sends; base64 wins when a file is picked. The+ // backend accepts url XOR base64 and requires a mimetype for base64 (always provided here).+ const payload: SendMediaPayload = mediaFile+ ? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }+ : { url: mediaUrl };+ if ((messageType === 'image' || messageType === 'video') && content) payload.caption = content;+ if (messageType === 'document' && content) payload.filename = content;+ return messageApi.sendMedia(session, target, messageType, payload);+ }+ case 'sticker': {+ const payload: SendMediaPayload = mediaFile+ ? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }+ : { url: mediaUrl };+ return messageApi.sendSticker(session, target, payload);+ }+ case 'location':+ return messageApi.sendLocation(session, {+ chatId: target,+ latitude: lat,+ longitude: lng,+ ...(locationDescription.trim() ? { description: locationDescription.trim() } : {}),+ ...(locationAddress.trim() ? { address: locationAddress.trim() } : {}),+ });+ case 'contact':+ return messageApi.sendContact(session, {+ chatId: target,+ contactName: contactName.trim(),+ contactNumber: contactNumber.trim(),+ });+ case 'poll':+ return messageApi.sendPoll(session, {+ chatId: target,+ name: pollQuestion.trim(),+ options: pollOptionsFilled,+ ...(allowMultipleAnswers ? { allowMultipleAnswers: true } : {}),+ });+ case 'forward': {+ // toChatId passes through as-is when it is a full chat ID; a bare number is resolved+ // through the same check-number flow as the main recipient.+ let toChatId = forwardTo.trim();+ if (!toChatId.includes('@')) {+ const resolvedTo = await contactApi.checkNumber(session, toChatId.replace(/[^0-9]/g, ''));+ if (!resolvedTo.exists || !resolvedTo.whatsappId) throw new Error(t('messageTester.notOnWhatsApp'));+ toChatId = resolvedTo.whatsappId;+ }+ return messageApi.forward(session, {+ // An empty fromChatId defaults to the current (already resolved) recipient.+ fromChatId: forwardFrom.trim() || target,+ toChatId,+ messageId: forwardMessageId.trim(),+ });+ }+ default:+ throw new Error(`Unsupported message type: ${messageType}`);+ }+ };++ const plan = recipientType === 'group' ? planGroupSend(selectedGroups, messageType) : null;+ if (plan?.mode === 'sequential') {+ await sendToGroups(plan.chatIds, sendTo);return;}- const result = await sendToChat(chatId);+ const result = await sendTo(chatId);+setResponse({success: !!result.messageId,messageId: result.messageId,@@ -467,7 +491,6 @@ export function MessageTester() {});} finally {setIsLoading(false);- setGroupSendProgress(null);}};@@ -501,7 +524,7 @@ export function MessageTester() {<div className="form-group"><label htmlFor="mt-1">{t('messageTester.session')}</label>- <select id="mt-1" value={session} onChange={e => setSession(e.target.value)}>+ <select id="mt-1" value={session} onChange={e => setSession(e.target.value)} disabled={isGroupSending}>{sessions.length === 0 && <option value="">{t('messageTester.noReadySessions')}</option>}{sessions.map(s => (<option key={s.id} value={s.id}>@@ -526,6 +549,7 @@ export function MessageTester() {aria-pressed={recipientType === 'personal'}className={recipientType === 'personal' ? 'active' : ''}onClick={() => setRecipientType('personal')}+ disabled={isGroupSending}>{t('messageTester.personal')}</button>@@ -534,6 +558,7 @@ export function MessageTester() {aria-pressed={recipientType === 'group'}className={recipientType === 'group' ? 'active' : ''}onClick={() => setRecipientType('group')}+ disabled={isGroupSending}>{t('messageTester.group')}</button>@@ -551,9 +576,15 @@ export function MessageTester() {selectedIds={selectedGroups}onChange={setSelectedGroups}loading={loadingGroups}+ limit={BULK_MAX_RECIPIENTS}labelledBy="group-picker-label"+ disabled={isGroupSending}/>- <span className="hint">{t('messageTester.selectGroupHint')}</span>+ <span className="hint">+ {messageType === 'forward'+ ? t('messageTester.forwardUsesFirstGroup')+ : t('messageTester.selectGroupHint')}+ </span></>) : (<>@@ -919,14 +950,21 @@ export function MessageTester() {<button className="send-btn" onClick={handleSend} disabled={isSendDisabled}>{isLoading ? <Loader2 className="animate-spin" size={18} /> : <Send size={18} />}- {isLoading- ? groupSendProgress- ? t('messageTester.sendingProgress', groupSendProgress)- : t('messageTester.sending')- : canWrite- ? t('messageTester.send')- : t('messageTester.viewOnly')}+ {isLoading ? t('messageTester.sending') : canWrite ? t('messageTester.send') : t('messageTester.viewOnly')}</button>+ <div className="group-send-status">+ <span role="status">{groupSendProgress ? t('messageTester.sendingProgress', groupSendProgress) : ''}</span>+ {isGroupSending && (+ <button+ type="button"+ className="batch-cancel-btn"+ onClick={cancelGroupSend}+ disabled={groupSendCancelling}+ >+ {groupSendCancelling ? t('messageTester.batch.cancelling') : t('common.cancel')}+ </button>+ )}+ </div></div><div className="response-panel">@@ -1001,6 +1039,19 @@ export function MessageTester() {</ul></div>)}+ {response.groups && response.groups.notSent > 0 && (+ <div className="detail-row">+ <span className="detail-label">{t('messageTester.response.notSent')}</span>+ <span className="detail-value">+ {response.groups.stoppedBy === 'refusal'+ ? t('messageTester.groupSendStopped', {+ count: response.groups.notSent,+ status: response.groups.refusedWith,+ })+ : t('messageTester.groupSendCancelled', { count: response.groups.notSent })}+ </span>+ </div>+ )}</div>{response.batchId && batchStatus && response.batchId === batchStatus.batchId && (diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex cf1d330dd..d12cd47c5 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -817,7 +817,7 @@ export const sessionApi = {}),getStats: () => request<SessionStats>('/sessions/stats/overview'),getGroups: (id: string) =>- request<{ id: string; name: string; linkedParentJID?: string | null }[]>(`/sessions/${id}/groups`),+ request<{ id: string; name?: string; linkedParentJID?: string | null }[]>(`/sessions/${id}/groups`),getChats: (id: string) => request<Chat[]>(`/sessions/${id}/chats`),markChatRead: (id: string, chatId: string) =>request<{ success: boolean }>(`/sessions/${id}/chats/read`, {diff --git a/dashboard/src/utils/groupSelection.ts b/dashboard/src/utils/groupSelection.tsindex 0e29829ff..48e416bfc 100644--- a/dashboard/src/utils/groupSelection.ts+++ b/dashboard/src/utils/groupSelection.ts@@ -1,22 +1,57 @@export interface SelectableGroup {id: string;- name: string;+ name?: string;}+export interface GroupPickerRow {+ id: string;+ label: string;+}++export type GroupSendPlan = { mode: 'single'; chatId: string } | { mode: 'sequential'; chatIds: string[] };++const GATEWAY_REFUSAL_STATUSES: readonly number[] = [429, 503];+export function groupLabel(group: SelectableGroup): string {- return group.name.trim() || group.id;+ return group.name?.trim() || group.id;}-export function filterGroupsByName<T extends SelectableGroup>(groups: readonly T[], query: string): T[] {+export function groupPickerRows(groups: readonly SelectableGroup[], selectedIds: readonly string[]): GroupPickerRow[] {+ const listed = new Set(groups.map(group => group.id));+ const unlisted = [...new Set(selectedIds)].filter(id => !listed.has(id));+ return [+ ...groups.map(group => ({ id: group.id, label: groupLabel(group) })),+ ...unlisted.map(id => ({ id, label: id })),+ ];+}++export function filterGroupRows(rows: readonly GroupPickerRow[], query: string): GroupPickerRow[] {const needle = query.trim().toLocaleLowerCase();- if (!needle) return [...groups];- return groups.filter(group => groupLabel(group).toLocaleLowerCase().includes(needle));+ if (!needle) return [...rows];+ return rows.filter(row => row.label.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])];+export function addGroupIds(selectedIds: readonly string[], ids: readonly string[], limit: number): string[] {+ const next = [...selectedIds];+ for (const id of ids) {+ if (next.length >= limit) break;+ if (!next.includes(id)) next.push(id);+ }+ return next;+}++export function planGroupSend(selectedIds: readonly string[], messageType: string): GroupSendPlan | null {+ const [first] = selectedIds;+ if (first === undefined) return null;+ if (selectedIds.length === 1 || messageType === 'forward') return { mode: 'single', chatId: first };+ return { mode: 'sequential', chatIds: [...selectedIds] };+}++export function isGatewayRefusal(err: unknown): boolean {+ const status = (err as { status?: unknown } | null)?.status;+ return typeof status === 'number' && GATEWAY_REFUSAL_STATUSES.includes(status);}diff --git a/dashboard/src/utils/sendSequentially.ts b/dashboard/src/utils/sendSequentially.tsindex c24001044..674532af8 100644--- a/dashboard/src/utils/sendSequentially.ts+++ b/dashboard/src/utils/sendSequentially.ts@@ -1,37 +1,64 @@export interface SequentialSendFailure<T> {target: T;error: string;+ status?: number;}export interface SequentialSendResult<T> {sent: number;failures: SequentialSendFailure<T>[];+ notAttempted: T[];+ stoppedBy?: 'abort' | 'refusal';}export interface SequentialSendOptions {delayMs: number;- sleep?: (ms: number) => Promise<void>;+ signal?: AbortSignal;+ stopOn?: (err: unknown) => boolean;+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;onProgress?: (current: number, total: number) => void;}-const wait = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));+function wait(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise(resolve => {+ if (signal?.aborted) {+ resolve();+ return;+ }+ const finish = () => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', finish);+ resolve();+ };+ const timer = setTimeout(finish, ms);+ signal?.addEventListener('abort', finish);+ });+}++function toFailure<T>(target: T, err: unknown): SequentialSendFailure<T> {+ const status = (err as { status?: unknown } | null)?.status;+ const error = err instanceof Error ? err.message : String(err);+ return typeof status === 'number' ? { target, error, status } : { target, error };+}export async function sendSequentially<T>(targets: readonly T[],send: (target: T) => Promise<void>,- { delayMs, sleep = wait, onProgress }: SequentialSendOptions,+ { delayMs, signal, stopOn, 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);+ if (index > 0) await sleep(delayMs, signal);+ if (signal?.aborted) return { sent, failures, notAttempted: targets.slice(index), stoppedBy: 'abort' };onProgress?.(index + 1, targets.length);try {await send(target);sent += 1;} catch (err) {- failures.push({ target, error: err instanceof Error ? err.message : String(err) });+ failures.push(toFailure(target, err));+ if (stopOn?.(err)) return { sent, failures, notAttempted: targets.slice(index + 1), stoppedBy: 'refusal' };}}- return { sent, failures };+ return { sent, failures, notAttempted: [] };}