Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(dashboard): add message templates management (#266)

Leslie Ajayi84f3373efa7f
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 4e0a1a77e..e690b4e4d 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -14,6 +14,7 @@ const Dashboard = lazy(() => import('./pages/Dashboard').then(m => ({ default: m
const Sessions = lazy(() => import('./pages/Sessions').then(m => ({ default: m.Sessions })));
const Chats = lazy(() => import('./pages/Chats').then(m => ({ default: m.Chats })));
const Webhooks = lazy(() => import('./pages/Webhooks').then(m => ({ default: m.Webhooks })));
+const Templates = lazy(() => import('./pages/Templates').then(m => ({ default: m.Templates })));
const Logs = lazy(() => import('./pages/Logs').then(m => ({ default: m.Logs })));
const ApiKeys = lazy(() => import('./pages/ApiKeys').then(m => ({ default: m.ApiKeys })));
const MessageTester = lazy(() => import('./pages/MessageTester').then(m => ({ default: m.MessageTester })));
@@ -105,6 +106,7 @@ function AppContent() {
<Route path="sessions" element={<Sessions />} />
<Route path="chats" element={<Chats />} />
<Route path="webhooks" element={<Webhooks />} />
+ <Route path="templates" element={<Templates />} />
{role === 'admin' && <Route path="api-keys" element={<ApiKeys />} />}
<Route path="logs" element={<Logs />} />
<Route path="message-tester" element={<MessageTester />} />
diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsx
index 7eb396b4f..458ab3933 100644
--- a/dashboard/src/components/Layout.tsx
+++ b/dashboard/src/components/Layout.tsx
@@ -8,6 +8,7 @@ import {
Webhook,
Key,
FileText,
+ ClipboardList,
LogOut,
Send,
Server,
@@ -36,6 +37,7 @@ const allNavItems = [
{ to: '/sessions', icon: Smartphone, key: 'sessions' as const, adminOnly: false },
{ to: '/chats', icon: MessageSquare, key: 'chats' as const, adminOnly: false },
{ to: '/webhooks', icon: Webhook, key: 'webhooks' as const, adminOnly: false },
+ { to: '/templates', icon: ClipboardList, key: 'templates' as const, adminOnly: false },
{ to: '/api-keys', icon: Key, key: 'apiKeys' as const, adminOnly: true },
{ to: '/message-tester', icon: Send, key: 'messageTester' as const, adminOnly: false },
// Backend /infra/* is ADMIN-only; hide the nav item from non-admins (UX + defense-in-depth).
diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.ts
index e7c912df3..d0851214e 100644
--- a/dashboard/src/hooks/queries.ts
+++ b/dashboard/src/hooks/queries.ts
@@ -2,11 +2,13 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
sessionApi,
webhookApi,
+ templateApi,
apiKeyApi,
auditApi,
infraApi,
pluginsApi,
type Webhook,
+ type TemplatePayload,
} from '../services/api';
// ── Query Keys ────────────────────────────────────────────────────────
@@ -17,6 +19,7 @@ export const queryKeys = {
sessionGroups: (sessionId: string) => ['sessions', sessionId, 'groups'] as const,
sessionChats: (sessionId: string) => ['sessions', sessionId, 'chats'] as const,
webhooks: ['webhooks'] as const,
+ templates: (sessionId: string) => ['sessions', sessionId, 'templates'] as const,
apiKeys: ['apiKeys'] as const,
logs: (params: { severity?: string; page: number; limit: number }) =>
['logs', params] as const,
@@ -147,6 +150,50 @@ export function useDeleteWebhookMutation() {
});
}
+// ── Template Queries ─────────────────────────────────────────────────────────
+
+export function useTemplatesQuery(sessionId: string, enabled = true) {
+ return useQuery({
+ queryKey: queryKeys.templates(sessionId),
+ queryFn: () => templateApi.list(sessionId),
+ enabled: enabled && !!sessionId,
+ staleTime: 30_000,
+ });
+}
+
+export function useCreateTemplateMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (params: { sessionId: string; data: TemplatePayload }) =>
+ templateApi.create(params.sessionId, params.data),
+ onSuccess: (_template, params) => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.templates(params.sessionId) });
+ },
+ });
+}
+
+export function useUpdateTemplateMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (params: { sessionId: string; id: string; data: Partial<TemplatePayload> }) =>
+ templateApi.update(params.sessionId, params.id, params.data),
+ onSuccess: (_template, params) => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.templates(params.sessionId) });
+ },
+ });
+}
+
+export function useDeleteTemplateMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (params: { sessionId: string; id: string }) =>
+ templateApi.delete(params.sessionId, params.id),
+ onSuccess: (_template, params) => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.templates(params.sessionId) });
+ },
+ });
+}
+
// ── API Key Queries ───────────────────────────────────────────────────
export function useApiKeysQuery() {
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 8b81a9bb8..fe230f025 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -58,6 +58,7 @@
"sessions": "الجلسات",
"chats": "المحادثات",
"webhooks": "الويب هوك",
+ "templates": "Templates",
"apiKeys": "مفاتيح API",
"messageTester": "اختبار الرسائل",
"infrastructure": "البنية التحتية",
@@ -289,6 +290,51 @@
"all": "كل الأحداث"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "مفاتيح API",
"subtitle": "إدارة مفاتيح API للمصادقة والتحكم في الوصول",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 5603d7609..30d1274e5 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -58,6 +58,7 @@
"sessions": "Sessions",
"chats": "Chats",
"webhooks": "Webhooks",
+ "templates": "Templates",
"apiKeys": "API Keys",
"messageTester": "Message Tester",
"infrastructure": "Infrastructure",
@@ -289,6 +290,51 @@
"all": "All events"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "API Keys",
"subtitle": "Manage API keys for authentication and access control",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 873ec8396..8f004b802 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -58,6 +58,7 @@
"sessions": "Sessions",
"chats": "Discussions",
"webhooks": "Webhooks",
+ "templates": "Templates",
"apiKeys": "Clés API",
"messageTester": "Testeur de messages",
"infrastructure": "Infrastructure",
@@ -289,6 +290,51 @@
"all": "Tous les événements"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "Clés API",
"subtitle": "Gérez les clés API pour l'authentification et le contrôle d'accès",
@@ -556,4 +602,4 @@
"saveFailed": "Échec de l'enregistrement"
}
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 115dfd7a3..96f48f499 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -58,6 +58,7 @@
"sessions": "Sessions",
"chats": "שיחות",
"webhooks": "Webhooks",
+ "templates": "Templates",
"apiKeys": "מפתחות API",
"messageTester": "בדיקת הודעות",
"infrastructure": "תשתית",
@@ -289,6 +290,51 @@
"all": "כל האירועים"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "מפתחות API",
"subtitle": "ניהול מפתחות API לאימות ובקרת גישה",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index c93e33c89..d68752c9c 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -58,6 +58,7 @@
"sessions": "Sessioni",
"chats": "Chat",
"webhooks": "Webhook",
+ "templates": "Templates",
"apiKeys": "Chiavi API",
"messageTester": "Tester Messaggi",
"infrastructure": "Infrastruttura",
@@ -289,6 +290,51 @@
"all": "Tutti gli eventi"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "Chiavi API",
"subtitle": "Gestisci le chiavi API per l'autenticazione e il controllo degli accessi",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 458b32ab6..d6c22b99a 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -58,6 +58,7 @@
"sessions": "సెషన్స్",
"chats": "చాట్‌లు",
"webhooks": "వెబ్‌హుక్స్",
+ "templates": "Templates",
"apiKeys": "API కీలు",
"messageTester": "మెసేజ్ టెస్టర్",
"infrastructure": "ఇన్‌ఫ్రాస్ట్రక్చర్",
@@ -289,6 +290,51 @@
"all": "అన్ని ఈవెంట్స్"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "API కీలు",
"subtitle": "అథెంటికేషన్ మరియు యాక్సెస్ కంట్రోల్ కోసం API కీలను నిర్వహించండి",
@@ -556,4 +602,4 @@
"saveFailed": "సేవ్ చేయడం విఫలమైంది"
}
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index cb4b751f7..76953ad87 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -58,6 +58,7 @@
"sessions": "会话",
"chats": "聊天",
"webhooks": "Webhooks",
+ "templates": "Templates",
"apiKeys": "API 密钥",
"messageTester": "消息测试器",
"infrastructure": "基础设施",
@@ -289,6 +290,51 @@
"all": "所有事件"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "API 密钥",
"subtitle": "管理用于认证和访问控制的 API 密钥",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 9434b5e72..a7f2c4bd7 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -58,6 +58,7 @@
"sessions": "工作階段",
"chats": "聊天",
"webhooks": "Webhooks",
+ "templates": "Templates",
"apiKeys": "API 金鑰",
"messageTester": "訊息測試器",
"infrastructure": "基礎架構",
@@ -289,6 +290,51 @@
"all": "所有事件"
}
},
+ "templates": {
+ "title": "Templates",
+ "subtitle": "Create reusable message templates for each WhatsApp session",
+ "createTitle": "Create Template",
+ "editTitle": "Edit Template",
+ "newTemplate": "New Template",
+ "createTemplate": "Create Template",
+ "saveChanges": "Save Changes",
+ "viewOnly": "View Only",
+ "noSessions": "No sessions",
+ "sessionHint": "Saved under {{name}}",
+ "namePlaceholder": "e.g., order-confirmation",
+ "header": "Header",
+ "headerPlaceholder": "Optional intro line",
+ "body": "Body",
+ "bodyPlaceholder": "Hi {{customer}}, your order {{orderId}} is ready.",
+ "footer": "Footer",
+ "footerPlaceholder": "Optional closing line",
+ "previewTitle": "Preview",
+ "previewValuePlaceholder": "Sample value",
+ "previewEmpty": "Start writing a template to preview it here.",
+ "noPlaceholders": "Use {{name}} placeholders to test substitutions.",
+ "savedTitle": "Saved Templates",
+ "count": "{{count}} total",
+ "deleteTitle": "Delete Template",
+ "deleteConfirm": "Delete template \"{{name}}\"? This action cannot be undone.",
+ "actions": {
+ "copyName": "Copy template name"
+ },
+ "empty": {
+ "title": "No templates saved",
+ "description": "Create a reusable template to speed up common replies and notifications.",
+ "noSessionsTitle": "No sessions available",
+ "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ },
+ "toasts": {
+ "created": "Template created successfully",
+ "createFailed": "Failed to create template: {{message}}",
+ "updated": "Template updated successfully",
+ "updateFailed": "Failed to update template: {{message}}",
+ "deleted": "Template deleted successfully",
+ "deleteFailed": "Failed to delete template: {{message}}",
+ "copied": "Template name copied"
+ }
+ },
"apiKeys": {
"title": "API 金鑰",
"subtitle": "管理用於認證及存取控制的 API 金鑰",
diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsx
index 82c07a99c..1009c0f06 100644
--- a/dashboard/src/pages/ApiKeys.tsx
+++ b/dashboard/src/pages/ApiKeys.tsx
@@ -12,6 +12,7 @@ import type { ApiKey } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useApiKeysQuery, useCreateApiKeyMutation, useDeleteApiKeyMutation, useRevokeApiKeyMutation } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
+import { copyToClipboard } from '../utils/clipboard';
import './ApiKeys.css';
const roleNames = ['admin', 'operator', 'viewer'] as const;
@@ -96,31 +97,8 @@ export function ApiKeys() {
});
};
- const copyToClipboard = (text: string, id: string) => {
- // The async Clipboard API is only available in a secure context (HTTPS / localhost). Over
- // plain HTTP on a LAN IP `navigator.clipboard` is undefined, so fall back to a hidden
- // textarea + execCommand('copy') instead of throwing.
- const copied = (() => {
- if (navigator.clipboard?.writeText) {
- void navigator.clipboard.writeText(text);
- return true;
- }
- try {
- const ta = document.createElement('textarea');
- ta.value = text;
- ta.setAttribute('readonly', '');
- ta.style.position = 'fixed';
- ta.style.opacity = '0';
- document.body.appendChild(ta);
- ta.select();
- const ok = document.execCommand('copy');
- document.body.removeChild(ta);
- return ok;
- } catch {
- return false;
- }
- })();
- if (copied) {
+ const handleCopy = async (text: string, id: string) => {
+ if (await copyToClipboard(text)) {
setCopied(id);
setTimeout(() => setCopied(null), 2000);
}
@@ -270,7 +248,7 @@ export function ApiKeys() {
>
{createdKey}
</code>
- <button className="btn-primary" onClick={() => copyToClipboard(createdKey, 'modal')}>
+ <button className="btn-primary" onClick={() => void handleCopy(createdKey, 'modal')}>
{copied === 'modal' ? <Check size={16} /> : <Copy size={16} />}
</button>
</div>
diff --git a/dashboard/src/pages/Templates.css b/dashboard/src/pages/Templates.css
new file mode 100644
index 000000000..1aa548af0
--- /dev/null
+++ b/dashboard/src/pages/Templates.css
@@ -0,0 +1,400 @@
+.templates-page {
+ padding: 2rem;
+ width: 100%;
+ overflow-x: hidden;
+}
+
+.templates-loading,
+.templates-loading-inline,
+.templates-empty-page,
+.templates-empty-list {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.templates-loading {
+ min-height: 400px;
+}
+
+.templates-session-select {
+ min-width: 240px;
+}
+
+.templates-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 340px;
+ gap: 1.5rem;
+ align-items: start;
+}
+
+.template-editor,
+.template-preview,
+.templates-list {
+ background: var(--bg-white);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: var(--shadow-sm);
+}
+
+.template-editor {
+ overflow: hidden;
+}
+
+.template-editor-header,
+.templates-list-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ padding: 1.25rem 1.5rem;
+ border-bottom: 1px solid var(--border);
+ background: var(--bg-light);
+}
+
+.template-editor-header h2,
+.template-preview h2,
+.templates-list-header h2 {
+ font-size: 0.8125rem;
+ font-weight: 700;
+ color: var(--text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+
+.template-editor-header p,
+.template-muted,
+.templates-list-header span {
+ margin: 0.25rem 0 0;
+ font-size: 0.875rem;
+ color: var(--text-secondary);
+}
+
+.template-form {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ padding: 1.5rem;
+}
+
+.template-form .form-group {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.template-form label,
+.placeholder-list label > span {
+ font-size: 0.875rem;
+ font-weight: 600;
+ color: var(--text-secondary);
+}
+
+.template-form input,
+.template-form textarea,
+.placeholder-list input {
+ width: 100%;
+ padding: 0.875rem 1rem;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--bg-light);
+ color: var(--text-primary);
+ font-size: 0.9375rem;
+ resize: vertical;
+}
+
+.template-form textarea {
+ min-height: 180px;
+ line-height: 1.5;
+}
+
+.template-form input:focus,
+.template-form textarea:focus,
+.placeholder-list input:focus {
+ outline: none;
+ border-color: var(--primary);
+ background: var(--bg-white);
+ box-shadow: 0 0 0 3px rgba(37, 211, 102, 0.1);
+}
+
+.template-editor-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.75rem;
+}
+
+.template-preview {
+ padding: 1.25rem;
+ position: sticky;
+ top: 1rem;
+}
+
+.placeholder-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.875rem;
+ margin-top: 1rem;
+}
+
+.placeholder-list label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+}
+
+.placeholder-list label > span {
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ color: var(--primary);
+}
+
+.template-preview-box {
+ margin: 1rem 0 0;
+ min-height: 180px;
+ max-height: 360px;
+ overflow: auto;
+ padding: 1rem;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--bg-light);
+ color: var(--text-primary);
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-size: 0.875rem;
+ line-height: 1.6;
+}
+
+.templates-list {
+ grid-column: 1 / -1;
+ overflow: hidden;
+}
+
+.templates-loading-inline,
+.templates-empty-list,
+.templates-empty-page {
+ min-height: 240px;
+ flex-direction: column;
+ gap: 0.75rem;
+ padding: 2rem;
+ text-align: center;
+ color: var(--text-muted);
+}
+
+.templates-empty-page {
+ background: var(--bg-white);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: var(--shadow-sm);
+}
+
+.templates-empty-list h3,
+.templates-empty-page h3 {
+ color: var(--text-secondary);
+}
+
+.templates-empty-list p,
+.templates-empty-page p {
+ max-width: 340px;
+ margin: 0;
+ color: var(--text-secondary);
+}
+
+.template-card-list {
+ display: flex;
+ flex-direction: column;
+}
+
+.template-card {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ gap: 1rem;
+ padding: 1.25rem 1.5rem;
+ border-top: 1px solid var(--border);
+}
+
+.template-card:first-child {
+ border-top: 0;
+}
+
+.template-card-main {
+ min-width: 0;
+}
+
+.template-card-title-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ min-width: 0;
+}
+
+.template-card-title-row h3 {
+ margin: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.template-card p {
+ margin: 0.5rem 0 0;
+ color: var(--text-secondary);
+ font-size: 0.9375rem;
+ line-height: 1.5;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.template-placeholder-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.375rem;
+ margin-top: 0.875rem;
+}
+
+.template-placeholder-tags span {
+ padding: 0.25rem 0.5rem;
+ border: 1px solid rgba(37, 211, 102, 0.25);
+ border-radius: 6px;
+ background: rgba(37, 211, 102, 0.12);
+ color: var(--primary);
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-size: 0.75rem;
+ font-weight: 600;
+}
+
+.template-card-actions {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.375rem;
+}
+
+.icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 36px;
+ height: 36px;
+ padding: 0;
+ background: transparent;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--text-secondary);
+}
+
+.icon-btn:hover {
+ background: var(--bg-light);
+ color: var(--text-primary);
+}
+
+.icon-btn.danger:hover {
+ background: #fee2e2;
+ border-color: #fecaca;
+ color: #dc2626;
+}
+
+.btn-danger {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.75rem 1.25rem;
+ background: #dc2626;
+ color: white;
+ border: none;
+ border-radius: var(--radius);
+ font-size: 0.9375rem;
+ font-weight: 600;
+}
+
+.btn-danger:hover {
+ background: #b91c1c;
+}
+
+.toast {
+ position: fixed;
+ top: 1.5rem;
+ right: 1.5rem;
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 1rem 1.25rem;
+ border-radius: 8px;
+ font-size: 0.875rem;
+ font-weight: 500;
+ box-shadow: var(--shadow-lg);
+ z-index: 1000;
+}
+
+.toast.success {
+ background: #ecfdf5;
+ border: 1px solid #a7f3d0;
+ color: #047857;
+}
+
+.toast.error {
+ background: #fef2f2;
+ border: 1px solid #fecaca;
+ color: #dc2626;
+}
+
+.toast-close {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ color: inherit;
+ opacity: 0.7;
+}
+
+.toast-close:hover {
+ opacity: 1;
+}
+
+@media (max-width: 1100px) {
+ .templates-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .template-preview {
+ position: static;
+ }
+}
+
+@media (max-width: 768px) {
+ .templates-page {
+ padding: 1rem;
+ }
+
+ .templates-session-select {
+ min-width: 0;
+ width: 100%;
+ }
+
+ .template-editor-header,
+ .templates-list-header,
+ .template-card {
+ padding: 1rem;
+ }
+
+ .template-form {
+ padding: 1rem;
+ }
+
+ .template-editor-header,
+ .template-editor-actions {
+ flex-direction: column;
+ align-items: stretch;
+ }
+
+ .template-card {
+ grid-template-columns: 1fr;
+ }
+
+ .template-card-actions {
+ justify-content: flex-end;
+ }
+}
diff --git a/dashboard/src/pages/Templates.tsx b/dashboard/src/pages/Templates.tsx
new file mode 100644
index 000000000..e5922513d
--- /dev/null
+++ b/dashboard/src/pages/Templates.tsx
@@ -0,0 +1,399 @@
+import { useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { AlertTriangle, Check, Copy, Edit, FileText, Loader2, Plus, Trash2, X } from 'lucide-react';
+import { type MessageTemplate, type TemplatePayload } from '../services/api';
+import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import { useRole } from '../hooks/useRole';
+import {
+ useCreateTemplateMutation,
+ useDeleteTemplateMutation,
+ useSessionsQuery,
+ useTemplatesQuery,
+ useUpdateTemplateMutation,
+} from '../hooks/queries';
+import { PageHeader } from '../components/PageHeader';
+import { copyToClipboard } from '../utils/clipboard';
+import './Templates.css';
+
+type TemplateForm = {
+ name: string;
+ header: string;
+ body: string;
+ footer: string;
+};
+
+const emptyForm: TemplateForm = {
+ name: '',
+ header: '',
+ body: '',
+ footer: '',
+};
+
+function extractPlaceholders(template: TemplateForm | MessageTemplate) {
+ const source = [template.header, template.body, template.footer].filter(Boolean).join('\n');
+ return Array.from(new Set(Array.from(source.matchAll(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g), match => match[1]))).sort();
+}
+
+function toPayload(form: TemplateForm): TemplatePayload {
+ return {
+ name: form.name.trim(),
+ header: form.header.trim() || null,
+ body: form.body.trim(),
+ footer: form.footer.trim() || null,
+ };
+}
+
+function renderPreview(template: TemplateForm, values: Record<string, string>) {
+ return [template.header, template.body, template.footer]
+ .filter(Boolean)
+ .join('\n\n')
+ .replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_match, key: string) => values[key] || `{{${key}}}`);
+}
+
+export function Templates() {
+ const { t } = useTranslation();
+ useDocumentTitle(t('templates.title'));
+ const { canWrite } = useRole();
+ const { data: sessions = [], isLoading: loadingSessions } = useSessionsQuery();
+ const [selectedSessionId, setSelectedSessionId] = useState('');
+ const [form, setForm] = useState<TemplateForm>(emptyForm);
+ const [editingTemplate, setEditingTemplate] = useState<MessageTemplate | null>(null);
+ const [deleteTarget, setDeleteTarget] = useState<MessageTemplate | null>(null);
+ const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
+ const [previewValues, setPreviewValues] = useState<Record<string, string>>({});
+
+ const { data: templates = [], isLoading: loadingTemplates } = useTemplatesQuery(selectedSessionId, !!selectedSessionId);
+ const createMutation = useCreateTemplateMutation();
+ const updateMutation = useUpdateTemplateMutation();
+ const deleteMutation = useDeleteTemplateMutation();
+
+ const selectedSession = sessions.find(session => session.id === selectedSessionId);
+ const placeholders = useMemo(() => extractPlaceholders(form), [form]);
+ const preview = useMemo(() => renderPreview(form, previewValues), [form, previewValues]);
+ const isSaving = createMutation.isPending || updateMutation.isPending;
+
+ useEffect(() => {
+ if (!selectedSessionId && sessions.length > 0) {
+ setSelectedSessionId(sessions[0].id);
+ }
+ }, [selectedSessionId, sessions]);
+
+ useEffect(() => {
+ if (!toast) return;
+ const timer = setTimeout(() => setToast(null), 4000);
+ return () => clearTimeout(timer);
+ }, [toast]);
+
+ useEffect(() => {
+ setPreviewValues(current => {
+ const next: Record<string, string> = {};
+ for (const key of placeholders) {
+ next[key] = current[key] || '';
+ }
+ return next;
+ });
+ }, [placeholders]);
+
+ const resetForm = () => {
+ setForm(emptyForm);
+ setEditingTemplate(null);
+ setPreviewValues({});
+ };
+
+ const openEdit = (template: MessageTemplate) => {
+ setEditingTemplate(template);
+ setForm({
+ name: template.name,
+ header: template.header || '',
+ body: template.body,
+ footer: template.footer || '',
+ });
+ window.scrollTo({ top: 0, behavior: 'smooth' });
+ };
+
+ const handleSave = async () => {
+ if (!selectedSessionId || !form.name.trim() || !form.body.trim()) return;
+
+ try {
+ if (editingTemplate) {
+ await updateMutation.mutateAsync({
+ sessionId: selectedSessionId,
+ id: editingTemplate.id,
+ data: toPayload(form),
+ });
+ setToast({ type: 'success', message: t('templates.toasts.updated') });
+ } else {
+ await createMutation.mutateAsync({
+ sessionId: selectedSessionId,
+ data: toPayload(form),
+ });
+ setToast({ type: 'success', message: t('templates.toasts.created') });
+ }
+ resetForm();
+ } catch (err) {
+ setToast({
+ type: 'error',
+ message: t(editingTemplate ? 'templates.toasts.updateFailed' : 'templates.toasts.createFailed', {
+ message: err instanceof Error ? err.message : t('common.unknownError'),
+ }),
+ });
+ }
+ };
+
+ const handleDelete = async () => {
+ if (!selectedSessionId || !deleteTarget) return;
+ try {
+ await deleteMutation.mutateAsync({ sessionId: selectedSessionId, id: deleteTarget.id });
+ setToast({ type: 'success', message: t('templates.toasts.deleted') });
+ if (editingTemplate?.id === deleteTarget.id) resetForm();
+ setDeleteTarget(null);
+ } catch (err) {
+ setToast({
+ type: 'error',
+ message: t('templates.toasts.deleteFailed', {
+ message: err instanceof Error ? err.message : t('common.unknownError'),
+ }),
+ });
+ }
+ };
+
+ const copyName = async (name: string) => {
+ if (await copyToClipboard(name)) {
+ setToast({ type: 'success', message: t('templates.toasts.copied') });
+ }
+ };
+
+ if (loadingSessions) {
+ return (
+ <div className="templates-page templates-loading">
+ <Loader2 className="animate-spin" size={32} />
+ </div>
+ );
+ }
+
+ return (
+ <div className="templates-page">
+ {toast && (
+ <div className={`toast ${toast.type}`}>
+ {toast.type === 'success' ? <Check size={18} /> : <AlertTriangle size={18} />}
+ <span>{toast.message}</span>
+ <button className="toast-close" onClick={() => setToast(null)} aria-label={t('common.close')}>
+ <X size={16} />
+ </button>
+ </div>
+ )}
+
+ <PageHeader
+ title={t('templates.title')}
+ subtitle={t('templates.subtitle')}
+ actions={
+ <select
+ className="templates-session-select"
+ value={selectedSessionId}
+ onChange={event => {
+ setSelectedSessionId(event.target.value);
+ resetForm();
+ }}
+ >
+ {sessions.length === 0 && <option value="">{t('templates.noSessions')}</option>}
+ {sessions.map(session => (
+ <option key={session.id} value={session.id}>
+ {session.name}
+ </option>
+ ))}
+ </select>
+ }
+ />
+
+ {sessions.length === 0 ? (
+ <div className="templates-empty-page">
+ <FileText size={48} strokeWidth={1} />
+ <h3>{t('templates.empty.noSessionsTitle')}</h3>
+ <p>{t('templates.empty.noSessionsDesc')}</p>
+ </div>
+ ) : (
+ <div className="templates-grid">
+ <section className="template-editor">
+ <div className="template-editor-header">
+ <div>
+ <h2>{editingTemplate ? t('templates.editTitle') : t('templates.createTitle')}</h2>
+ <p>{selectedSession ? t('templates.sessionHint', { name: selectedSession.name }) : ''}</p>
+ </div>
+ {editingTemplate && (
+ <button className="btn-secondary" onClick={resetForm}>
+ {t('templates.newTemplate')}
+ </button>
+ )}
+ </div>
+
+ <div className="template-form">
+ <div className="form-group">
+ <label>{t('common.name')}</label>
+ <input
+ value={form.name}
+ onChange={event => setForm({ ...form, name: event.target.value })}
+ placeholder={t('templates.namePlaceholder')}
+ disabled={!canWrite}
+ />
+ </div>
+
+ <div className="form-group">
+ <label>{t('templates.header')}</label>
+ <input
+ value={form.header}
+ onChange={event => setForm({ ...form, header: event.target.value })}
+ placeholder={t('templates.headerPlaceholder')}
+ disabled={!canWrite}
+ />
+ </div>
+
+ <div className="form-group">
+ <label>{t('templates.body')}</label>
+ <textarea
+ value={form.body}
+ onChange={event => setForm({ ...form, body: event.target.value })}
+ placeholder={t('templates.bodyPlaceholder')}
+ rows={8}
+ disabled={!canWrite}
+ />
+ </div>
+
+ <div className="form-group">
+ <label>{t('templates.footer')}</label>
+ <input
+ value={form.footer}
+ onChange={event => setForm({ ...form, footer: event.target.value })}
+ placeholder={t('templates.footerPlaceholder')}
+ disabled={!canWrite}
+ />
+ </div>
+
+ <div className="template-editor-actions">
+ <button className="btn-secondary" onClick={resetForm} disabled={isSaving}>
+ {t('common.cancel')}
+ </button>
+ <button
+ className="btn-primary"
+ onClick={handleSave}
+ disabled={!canWrite || isSaving || !selectedSessionId || !form.name.trim() || !form.body.trim()}
+ >
+ {isSaving ? <Loader2 size={18} className="animate-spin" /> : <Plus size={18} />}
+ {canWrite ? t(editingTemplate ? 'templates.saveChanges' : 'templates.createTemplate') : t('templates.viewOnly')}
+ </button>
+ </div>
+ </div>
+ </section>
+
+ <aside className="template-preview">
+ <h2>{t('templates.previewTitle')}</h2>
+ {placeholders.length > 0 ? (
+ <div className="placeholder-list">
+ {placeholders.map(key => (
+ <label key={key}>
+ <span>{`{{${key}}}`}</span>
+ <input
+ value={previewValues[key] || ''}
+ onChange={event => setPreviewValues({ ...previewValues, [key]: event.target.value })}
+ placeholder={t('templates.previewValuePlaceholder')}
+ />
+ </label>
+ ))}
+ </div>
+ ) : (
+ <p className="template-muted">{t('templates.noPlaceholders')}</p>
+ )}
+ <pre className="template-preview-box">{preview || t('templates.previewEmpty')}</pre>
+ </aside>
+
+ <section className="templates-list">
+ <div className="templates-list-header">
+ <h2>{t('templates.savedTitle')}</h2>
+ <span>{t('templates.count', { count: templates.length })}</span>
+ </div>
+
+ {loadingTemplates ? (
+ <div className="templates-loading-inline">
+ <Loader2 className="animate-spin" size={24} />
+ </div>
+ ) : templates.length === 0 ? (
+ <div className="templates-empty-list">
+ <FileText size={40} strokeWidth={1} />
+ <h3>{t('templates.empty.title')}</h3>
+ <p>{t('templates.empty.description')}</p>
+ </div>
+ ) : (
+ <div className="template-card-list">
+ {templates.map(template => {
+ const templatePlaceholders = extractPlaceholders(template);
+ return (
+ <article key={template.id} className="template-card">
+ <div className="template-card-main">
+ <div className="template-card-title-row">
+ <h3>{template.name}</h3>
+ <button
+ className="icon-btn"
+ title={t('templates.actions.copyName')}
+ onClick={() => void copyName(template.name)}
+ >
+ <Copy size={16} />
+ </button>
+ </div>
+ <p>{template.body}</p>
+ {templatePlaceholders.length > 0 && (
+ <div className="template-placeholder-tags">
+ {templatePlaceholders.map(key => (
+ <span key={key}>{`{{${key}}}`}</span>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="template-card-actions">
+ <button className="icon-btn" title={t('common.edit')} onClick={() => openEdit(template)}>
+ <Edit size={16} />
+ </button>
+ {canWrite && (
+ <button
+ className="icon-btn danger"
+ title={t('common.delete')}
+ onClick={() => setDeleteTarget(template)}
+ >
+ <Trash2 size={16} />
+ </button>
+ )}
+ </div>
+ </article>
+ );
+ })}
+ </div>
+ )}
+ </section>
+ </div>
+ )}
+
+ {deleteTarget && (
+ <div className="modal-overlay" onClick={() => setDeleteTarget(null)}>
+ <div className="modal modal-sm" onClick={event => event.stopPropagation()}>
+ <div className="modal-header">
+ <h2>{t('templates.deleteTitle')}</h2>
+ <button className="btn-icon" onClick={() => setDeleteTarget(null)}>
+ <X size={20} />
+ </button>
+ </div>
+ <div className="modal-body">
+ <p>{t('templates.deleteConfirm', { name: deleteTarget.name })}</p>
+ </div>
+ <div className="modal-footer">
+ <button className="btn-secondary" onClick={() => setDeleteTarget(null)}>
+ {t('common.cancel')}
+ </button>
+ <button className="btn-danger" onClick={handleDelete} disabled={deleteMutation.isPending}>
+ {deleteMutation.isPending ? <Loader2 size={18} className="animate-spin" /> : <Trash2 size={18} />}
+ {t('common.delete')}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 4027cfd8e..76fc0df8f 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -49,6 +49,24 @@ export interface Webhook {
updatedAt: string;
}
+export interface MessageTemplate {
+ id: string;
+ sessionId: string;
+ name: string;
+ body: string;
+ header?: string | null;
+ footer?: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface TemplatePayload {
+ name: string;
+ body: string;
+ header?: string | null;
+ footer?: string | null;
+}
+
export interface ApiKey {
id: string;
name: string;
@@ -318,6 +336,27 @@ export const webhookApi = {
}),
};
+// =============================================================================
+// Template API
+// =============================================================================
+
+export const templateApi = {
+ list: (sessionId: string) => request<MessageTemplate[]>(`/sessions/${sessionId}/templates`),
+ get: (sessionId: string, id: string) => request<MessageTemplate>(`/sessions/${sessionId}/templates/${id}`),
+ create: (sessionId: string, data: TemplatePayload) =>
+ request<MessageTemplate>(`/sessions/${sessionId}/templates`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ }),
+ update: (sessionId: string, id: string, data: Partial<TemplatePayload>) =>
+ request<MessageTemplate>(`/sessions/${sessionId}/templates/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data),
+ }),
+ delete: (sessionId: string, id: string) =>
+ request<void>(`/sessions/${sessionId}/templates/${id}`, { method: 'DELETE' }),
+};
+
// =============================================================================
// API Key API
// =============================================================================
@@ -411,6 +450,14 @@ export const messageApi = {
method: 'POST',
body: JSON.stringify(data),
}),
+ sendTemplate: (
+ sessionId: string,
+ data: { chatId: string; templateId?: string; templateName?: string; variables?: Record<string, string> },
+ ) =>
+ request<MessageResponse>(`/sessions/${sessionId}/messages/send-template`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ }),
delete: (sessionId: string, data: { chatId: string; messageId: string; forEveryone?: boolean }) =>
request<void>(`/sessions/${sessionId}/messages/delete`, {
method: 'POST',
diff --git a/dashboard/src/utils/clipboard.ts b/dashboard/src/utils/clipboard.ts
new file mode 100644
index 000000000..40757cc5d
--- /dev/null
+++ b/dashboard/src/utils/clipboard.ts
@@ -0,0 +1,31 @@
+/**
+ * Copy text to the clipboard, returning whether it succeeded.
+ *
+ * The async Clipboard API is only available in a secure context (HTTPS / localhost). Over plain
+ * HTTP on a LAN IP `navigator.clipboard` is undefined (and can also reject on permission denial),
+ * so fall back to a hidden textarea + `execCommand('copy')` instead of throwing (#244).
+ */
+export async function copyToClipboard(text: string): Promise<boolean> {
+ if (navigator.clipboard?.writeText) {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ // Fall through to the legacy path (e.g. NotAllowedError outside a user gesture).
+ }
+ }
+ try {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ const ok = document.execCommand('copy');
+ document.body.removeChild(ta);
+ return ok;
+ } catch {
+ return false;
+ }
+}