AddNotificationModal.tsx 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. import { useState, useEffect } from 'react';
  2. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Save, Loader2, Send, CheckCircle, XCircle } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { NotificationProvider, NotificationProviderCreate, NotificationProviderUpdate, ProviderType } from '../api/client';
  7. import { Button } from './Button';
  8. import { Toggle } from './Toggle';
  9. interface AddNotificationModalProps {
  10. provider?: NotificationProvider | null;
  11. onClose: () => void;
  12. }
  13. const PROVIDER_VALUES: ProviderType[] = ['email', 'telegram', 'discord', 'ntfy', 'pushover', 'bark', 'callmebot', 'webhook', 'homeassistant'];
  14. export function AddNotificationModal({ provider, onClose }: AddNotificationModalProps) {
  15. const { t } = useTranslation();
  16. const queryClient = useQueryClient();
  17. const isEditing = !!provider;
  18. const [name, setName] = useState(provider?.name || '');
  19. const [providerType, setProviderType] = useState<ProviderType>(provider?.provider_type || 'email');
  20. const [printerId, setPrinterId] = useState<number | null>(provider?.printer_id || null);
  21. const [quietHoursEnabled, setQuietHoursEnabled] = useState(provider?.quiet_hours_enabled || false);
  22. const [quietHoursStart, setQuietHoursStart] = useState(provider?.quiet_hours_start || '22:00');
  23. const [quietHoursEnd, setQuietHoursEnd] = useState(provider?.quiet_hours_end || '07:00');
  24. // Daily digest
  25. const [dailyDigestEnabled, setDailyDigestEnabled] = useState(provider?.daily_digest_enabled || false);
  26. const [dailyDigestTime, setDailyDigestTime] = useState(provider?.daily_digest_time || '08:00');
  27. // Event toggles
  28. const [onPrintStart, setOnPrintStart] = useState(provider?.on_print_start ?? false);
  29. const [onPrintComplete, setOnPrintComplete] = useState(provider?.on_print_complete ?? true);
  30. const [onPrintFailed, setOnPrintFailed] = useState(provider?.on_print_failed ?? true);
  31. const [onPrintStopped, setOnPrintStopped] = useState(provider?.on_print_stopped ?? true);
  32. const [onPrintProgress, setOnPrintProgress] = useState(provider?.on_print_progress ?? false);
  33. const [onBillingChargeFailed, setOnBillingChargeFailed] = useState(provider?.on_billing_charge_failed ?? true);
  34. const [onPrinterOffline, setOnPrinterOffline] = useState(provider?.on_printer_offline ?? false);
  35. const [onPrinterError, setOnPrinterError] = useState(provider?.on_printer_error ?? false);
  36. const [onAiFailureDetection, setOnAiFailureDetection] = useState(provider?.on_ai_failure_detection ?? false);
  37. const [onFilamentLow, setOnFilamentLow] = useState(provider?.on_filament_low ?? false);
  38. const [onMaintenanceDue, setOnMaintenanceDue] = useState(provider?.on_maintenance_due ?? false);
  39. const [onStockReorderAlert, setOnStockReorderAlert] = useState(provider?.on_stock_reorder_alert ?? false);
  40. const [onStockBreakAlert, setOnStockBreakAlert] = useState(provider?.on_stock_break_alert ?? false);
  41. const [onPlateClearRequired, setOnPlateClearRequired] = useState(provider?.on_plate_clear_required ?? false);
  42. // Post-print outcome confirmation (#1898). Defaults ON — it only fires for
  43. // prints that opted in per-job, so the toggle exists to mute a channel.
  44. const [onPrintConfirmRequest, setOnPrintConfirmRequest] = useState(provider?.on_print_confirm_request ?? true);
  45. const [onBedCooled, setOnBedCooled] = useState(provider?.on_bed_cooled ?? false);
  46. const [onHaSensorAlert, setOnHaSensorAlert] = useState(provider?.on_ha_sensor_alert ?? false);
  47. const [onLocationHaSensorAlert, setOnLocationHaSensorAlert] = useState(
  48. provider?.on_location_ha_sensor_alert ?? false
  49. );
  50. const [onFirstLayerComplete, setOnFirstLayerComplete] = useState(provider?.on_first_layer_complete ?? false);
  51. const [onAppMessage, setOnAppMessage] = useState(provider?.on_app_message ?? false);
  52. // Provider-specific config (scalar fields only — event_priorities is split out
  53. // into its own state because it's an object, not a string).
  54. const [config, setConfig] = useState<Record<string, string>>(
  55. provider?.config
  56. ? Object.fromEntries(
  57. Object.entries(provider.config)
  58. .filter(([k]) => k !== 'event_priorities')
  59. .map(([k, v]) => [k, String(v)]),
  60. )
  61. : {},
  62. );
  63. // Per-event ntfy priority (#990). Map of event key → 1-5. Persisted into
  64. // config.event_priorities on save; only sent when the provider is ntfy.
  65. const initialEventPriorities = (() => {
  66. const raw = provider?.config?.event_priorities;
  67. if (!raw || typeof raw !== 'object') return {} as Record<string, number>;
  68. const out: Record<string, number> = {};
  69. for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
  70. const n = Number(v);
  71. if (Number.isInteger(n) && n >= 1 && n <= 5) out[k] = n;
  72. }
  73. return out;
  74. })();
  75. const [eventPriorities, setEventPriorities] = useState<Record<string, number>>(initialEventPriorities);
  76. const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  77. const [error, setError] = useState<string | null>(null);
  78. // Fetch printers for linking
  79. const { data: printers } = useQuery({
  80. queryKey: ['printers'],
  81. queryFn: api.getPrinters,
  82. });
  83. // Close on Escape key
  84. useEffect(() => {
  85. const handleKeyDown = (e: KeyboardEvent) => {
  86. if (e.key === 'Escape') onClose();
  87. };
  88. window.addEventListener('keydown', handleKeyDown);
  89. return () => window.removeEventListener('keydown', handleKeyDown);
  90. }, [onClose]);
  91. // Test configuration mutation
  92. const testMutation = useMutation({
  93. mutationFn: () => api.testNotificationConfig({ provider_type: providerType, config }),
  94. onSuccess: (result) => {
  95. setTestResult(result);
  96. setError(null);
  97. },
  98. onError: (err: Error) => {
  99. setTestResult({ success: false, message: err.message });
  100. },
  101. });
  102. // Create mutation
  103. const createMutation = useMutation({
  104. mutationFn: (data: NotificationProviderCreate) => api.createNotificationProvider(data),
  105. onSuccess: () => {
  106. queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
  107. onClose();
  108. },
  109. onError: (err: Error) => {
  110. setError(err.message);
  111. },
  112. });
  113. // Update mutation
  114. const updateMutation = useMutation({
  115. mutationFn: (data: NotificationProviderUpdate) => api.updateNotificationProvider(provider!.id, data),
  116. onSuccess: () => {
  117. queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
  118. onClose();
  119. },
  120. onError: (err: Error) => {
  121. setError(err.message);
  122. },
  123. });
  124. const handleSubmit = (e: React.FormEvent) => {
  125. e.preventDefault();
  126. setError(null);
  127. if (!name.trim()) {
  128. setError(t('notifications.nameRequired'));
  129. return;
  130. }
  131. // Validate provider-specific config
  132. const requiredFields = getRequiredFields(providerType);
  133. for (const field of requiredFields) {
  134. if (!config[field.key]?.trim()) {
  135. setError(t('notifications.fieldRequired', { field: field.label }));
  136. return;
  137. }
  138. }
  139. // HA custom service-data must be a JSON object (#1441)
  140. if (providerType === 'homeassistant' && config.data?.trim()) {
  141. let parsed: unknown;
  142. try {
  143. parsed = JSON.parse(config.data);
  144. } catch {
  145. setError(t('notifications.haDataInvalid'));
  146. return;
  147. }
  148. if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
  149. setError(t('notifications.haDataInvalid'));
  150. return;
  151. }
  152. }
  153. // Telegram forum topic must be a plain integer (#1518) — type="number"
  154. // still lets "1e5" and "-" through, and Telegram would 400 on those.
  155. if (providerType === 'telegram' && config.message_thread_id?.trim()) {
  156. if (!/^\d+$/.test(config.message_thread_id.trim())) {
  157. setError(t('notifications.telegramThreadIdInvalid'));
  158. return;
  159. }
  160. }
  161. const finalConfig: Record<string, unknown> =
  162. providerType === 'ntfy' && Object.keys(eventPriorities).length > 0
  163. ? { ...config, event_priorities: eventPriorities }
  164. : config;
  165. const data = {
  166. name: name.trim(),
  167. provider_type: providerType,
  168. config: finalConfig,
  169. printer_id: printerId,
  170. quiet_hours_enabled: quietHoursEnabled,
  171. quiet_hours_start: quietHoursEnabled ? quietHoursStart : null,
  172. quiet_hours_end: quietHoursEnabled ? quietHoursEnd : null,
  173. // Daily digest
  174. daily_digest_enabled: dailyDigestEnabled,
  175. daily_digest_time: dailyDigestEnabled ? dailyDigestTime : null,
  176. // Event toggles
  177. on_print_start: onPrintStart,
  178. on_print_complete: onPrintComplete,
  179. on_print_failed: onPrintFailed,
  180. on_print_stopped: onPrintStopped,
  181. on_print_progress: onPrintProgress,
  182. on_billing_charge_failed: onBillingChargeFailed,
  183. on_printer_offline: onPrinterOffline,
  184. on_printer_error: onPrinterError,
  185. on_ai_failure_detection: onAiFailureDetection,
  186. on_filament_low: onFilamentLow,
  187. on_maintenance_due: onMaintenanceDue,
  188. on_stock_reorder_alert: onStockReorderAlert,
  189. on_stock_break_alert: onStockBreakAlert,
  190. on_plate_clear_required: onPlateClearRequired,
  191. on_print_confirm_request: onPrintConfirmRequest,
  192. on_bed_cooled: onBedCooled,
  193. on_ha_sensor_alert: onHaSensorAlert,
  194. on_location_ha_sensor_alert: onLocationHaSensorAlert,
  195. on_first_layer_complete: onFirstLayerComplete,
  196. on_app_message: onAppMessage,
  197. };
  198. if (isEditing) {
  199. updateMutation.mutate(data);
  200. } else {
  201. createMutation.mutate(data);
  202. }
  203. };
  204. const isPending = createMutation.isPending || updateMutation.isPending;
  205. // Get config fields for each provider type
  206. const getConfigFields = (type: ProviderType) => {
  207. switch (type) {
  208. case 'callmebot':
  209. return [
  210. { key: 'phone', label: 'Phone Number', placeholder: '+1234567890', type: 'text', required: true },
  211. { key: 'apikey', label: 'API Key', placeholder: 'Your CallMeBot API key', type: 'text', required: true },
  212. ];
  213. case 'ntfy':
  214. return [
  215. { key: 'server', label: 'Server URL', placeholder: 'https://ntfy.sh', type: 'text', required: false },
  216. { key: 'topic', label: 'Topic', placeholder: 'my-bambuddy', type: 'text', required: true },
  217. { key: 'auth_token', label: 'Auth Token', placeholder: 'Optional authentication', type: 'password', required: false },
  218. ];
  219. case 'pushover':
  220. return [
  221. { key: 'user_key', label: 'User Key', placeholder: 'Your Pushover user key', type: 'text', required: true },
  222. { key: 'app_token', label: 'App Token', placeholder: 'Your Pushover app token', type: 'text', required: true },
  223. { key: 'priority', label: 'Priority', placeholder: '0 (normal)', type: 'number', required: false },
  224. // Emergency priority (2) requires retry/expire — Pushover rejects the
  225. // message otherwise. Only shown when priority is set to 2.
  226. {
  227. key: 'retry',
  228. label: t('notifications.pushoverRetry'),
  229. placeholder: '60',
  230. type: 'number',
  231. required: false,
  232. showIf: (cfg: Record<string, string>) => cfg.priority === '2',
  233. },
  234. {
  235. key: 'expire',
  236. label: t('notifications.pushoverExpire'),
  237. placeholder: '3600',
  238. type: 'number',
  239. required: false,
  240. showIf: (cfg: Record<string, string>) => cfg.priority === '2',
  241. },
  242. ];
  243. case 'telegram':
  244. return [
  245. { key: 'bot_token', label: 'Bot Token', placeholder: 'Bot token from @BotFather', type: 'password', required: true },
  246. { key: 'chat_id', label: 'Chat ID', placeholder: 'Your chat or group ID', type: 'text', required: true },
  247. // Optional forum topic (#1518). Left empty, Telegram posts to the
  248. // group's General topic exactly as before.
  249. {
  250. key: 'message_thread_id',
  251. label: t('notifications.telegramThreadId'),
  252. placeholder: '123',
  253. type: 'number',
  254. required: false,
  255. help: t('notifications.telegramThreadIdHelp'),
  256. },
  257. ];
  258. case 'email':
  259. return [
  260. { key: 'smtp_server', label: 'SMTP Server', placeholder: 'smtp.gmail.com', type: 'text', required: true },
  261. { key: 'smtp_port', label: 'SMTP Port', placeholder: '587', type: 'number', required: false },
  262. { key: 'security', label: 'Security', type: 'select', required: false, options: [
  263. { value: 'starttls', label: 'STARTTLS (Port 587)' },
  264. { value: 'ssl', label: 'SSL/TLS (Port 465)' },
  265. { value: 'none', label: 'None (Port 25)' },
  266. ]},
  267. { key: 'auth_enabled', label: 'Authentication', type: 'select', required: false, options: [
  268. { value: 'true', label: 'Enabled' },
  269. { value: 'false', label: 'Disabled' },
  270. ]},
  271. { key: 'username', label: 'Username', placeholder: 'your@email.com', type: 'text', required: false },
  272. { key: 'password', label: 'Password', placeholder: 'App password', type: 'password', required: false },
  273. { key: 'from_email', label: 'From Email', placeholder: 'your@email.com', type: 'text', required: true },
  274. { key: 'to_email', label: 'To Email', placeholder: 'recipient@email.com', type: 'text', required: true },
  275. ];
  276. case 'discord':
  277. return [
  278. { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://discord.com/api/webhooks/...', type: 'text', required: true },
  279. ];
  280. case 'webhook':
  281. return [
  282. { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://example.com/webhook', type: 'text', required: true },
  283. { key: 'payload_format', label: 'Payload Format', type: 'select', required: false, options: [
  284. { value: 'generic', label: 'Generic JSON' },
  285. { value: 'slack', label: 'Slack / Mattermost' },
  286. ]},
  287. { key: 'auth_header', label: 'Authorization', placeholder: 'Bearer token (optional)', type: 'password', required: false },
  288. { key: 'field_title', label: 'Title Field Name', placeholder: 'title', type: 'text', required: false, showIf: (cfg: Record<string, string>) => cfg.payload_format !== 'slack' },
  289. { key: 'field_message', label: 'Message Field Name', placeholder: 'message', type: 'text', required: false, showIf: (cfg: Record<string, string>) => cfg.payload_format !== 'slack' },
  290. ];
  291. case 'homeassistant':
  292. return [
  293. { key: 'service', label: 'Home Assistant Service', placeholder: 'notify.mobile_app_myphone', type: 'text', required: false },
  294. { key: 'data', label: 'Data (JSON, optional)', placeholder: '{"priority": "high", "ttl": 0, "channel": "3D Printing"}', type: 'textarea', required: false },
  295. ];
  296. case 'bark':
  297. return [
  298. { key: 'device_key', label: 'Device Key', placeholder: 'Your Bark device key', type: 'text', required: true },
  299. { key: 'server', label: 'Server URL', placeholder: 'https://api.day.app', type: 'text', required: false },
  300. { key: 'group', label: 'Group', placeholder: 'Bambuddy', type: 'text', required: false },
  301. { key: 'sound', label: 'Sound', placeholder: 'minuet', type: 'text', required: false },
  302. { key: 'level', label: 'Interruption Level', type: 'select', required: false, options: [
  303. { value: '', label: 'Default' },
  304. { value: 'active', label: 'Active' },
  305. { value: 'timeSensitive', label: 'Time Sensitive' },
  306. { value: 'critical', label: 'Critical (bypasses Silent/Focus)' },
  307. { value: 'passive', label: 'Passive (no sound)' },
  308. ]},
  309. ];
  310. default:
  311. return [];
  312. }
  313. };
  314. const getRequiredFields = (type: ProviderType) => {
  315. return getConfigFields(type).filter(f => f.required);
  316. };
  317. const configFields = getConfigFields(providerType);
  318. return (
  319. <div
  320. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto"
  321. onClick={onClose}
  322. >
  323. <div
  324. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto"
  325. onClick={(e) => e.stopPropagation()}
  326. >
  327. {/* Header */}
  328. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  329. <h2 className="text-lg font-semibold text-white">
  330. {isEditing ? t('notifications.editTitle') : t('notifications.addTitle')}
  331. </h2>
  332. <button
  333. onClick={onClose}
  334. className="text-bambu-gray hover:text-white transition-colors"
  335. >
  336. <X className="w-5 h-5" />
  337. </button>
  338. </div>
  339. {/* Form */}
  340. <form onSubmit={handleSubmit} className="p-6 space-y-4">
  341. {error && (
  342. <div className="p-3 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded-lg text-sm text-red-700 dark:text-red-400">
  343. {error}
  344. </div>
  345. )}
  346. {/* Name */}
  347. <div>
  348. <label className="block text-sm text-bambu-gray mb-1">{t('notifications.nameLabel')}</label>
  349. <input
  350. type="text"
  351. value={name}
  352. onChange={(e) => setName(e.target.value)}
  353. placeholder={t('notifications.namePlaceholder')}
  354. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  355. />
  356. </div>
  357. {/* Provider Type */}
  358. <div>
  359. <label className="block text-sm text-bambu-gray mb-1">{t('notifications.providerTypeLabel')}</label>
  360. <select
  361. value={providerType}
  362. onChange={(e) => {
  363. setProviderType(e.target.value as ProviderType);
  364. setConfig({}); // Reset config when changing type
  365. setTestResult(null);
  366. }}
  367. disabled={isEditing}
  368. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none disabled:opacity-50"
  369. >
  370. {PROVIDER_VALUES.map((value) => (
  371. <option key={value} value={value}>
  372. {t(`notifications.providerTypes.${value}`, value)}
  373. </option>
  374. ))}
  375. </select>
  376. <p className="text-xs text-bambu-gray mt-1">
  377. {t(`notifications.providerDescriptions.${providerType}`, '')}
  378. </p>
  379. </div>
  380. {/* Provider-specific configuration */}
  381. <div className="space-y-3">
  382. <p className="text-sm text-bambu-gray">{t('notifications.configuration')}</p>
  383. {configFields
  384. .filter((field) => !('showIf' in field) || (field as { showIf?: (cfg: Record<string, string>) => boolean }).showIf?.(config) !== false)
  385. .map((field) => (
  386. <div key={field.key}>
  387. <label className="block text-sm text-bambu-gray mb-1">
  388. {field.label} {field.required && '*'}
  389. </label>
  390. {field.type === 'select' && 'options' in field && field.options ? (
  391. <select
  392. value={config[field.key] || field.options[0]?.value || ''}
  393. onChange={(e) => {
  394. setConfig({ ...config, [field.key]: e.target.value });
  395. setTestResult(null);
  396. }}
  397. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  398. >
  399. {field.options.map((opt) => (
  400. <option key={opt.value} value={opt.value}>
  401. {opt.label}
  402. </option>
  403. ))}
  404. </select>
  405. ) : field.type === 'textarea' ? (
  406. <textarea
  407. value={config[field.key] || ''}
  408. onChange={(e) => {
  409. setConfig({ ...config, [field.key]: e.target.value });
  410. setTestResult(null);
  411. }}
  412. placeholder={field.placeholder}
  413. rows={3}
  414. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none font-mono text-sm"
  415. />
  416. ) : (
  417. <input
  418. type={field.type}
  419. value={config[field.key] || ''}
  420. onChange={(e) => {
  421. setConfig({ ...config, [field.key]: e.target.value });
  422. setTestResult(null);
  423. }}
  424. placeholder={field.placeholder}
  425. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  426. />
  427. )}
  428. {'help' in field && (field as { help?: string }).help && (
  429. <p className="text-xs text-bambu-gray mt-1">{(field as { help?: string }).help}</p>
  430. )}
  431. </div>
  432. ))}
  433. </div>
  434. {/* Test Button */}
  435. <div className="flex gap-2">
  436. <Button
  437. type="button"
  438. variant="secondary"
  439. onClick={() => {
  440. setTestResult(null);
  441. testMutation.mutate();
  442. }}
  443. disabled={testMutation.isPending || (getRequiredFields(providerType).length > 0 && !config[getRequiredFields(providerType)[0]?.key])}
  444. className="flex-1"
  445. >
  446. {testMutation.isPending ? (
  447. <Loader2 className="w-4 h-4 animate-spin" />
  448. ) : (
  449. <Send className="w-4 h-4" />
  450. )}
  451. {t('notifications.testConfiguration')}
  452. </Button>
  453. </div>
  454. {/* Test Result */}
  455. {testResult && (
  456. <div className={`p-3 rounded-lg flex items-center gap-2 ${
  457. testResult.success
  458. ? 'bg-bambu-green/20 border border-bambu-green/50 text-bambu-green'
  459. : 'bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 text-red-700 dark:text-red-400'
  460. }`}>
  461. {testResult.success ? (
  462. <>
  463. <CheckCircle className="w-5 h-5" />
  464. <span>{testResult.message}</span>
  465. </>
  466. ) : (
  467. <>
  468. <XCircle className="w-5 h-5" />
  469. <span>{testResult.message}</span>
  470. </>
  471. )}
  472. </div>
  473. )}
  474. {/* Link to Printer */}
  475. <div>
  476. <label className="block text-sm text-bambu-gray mb-1">{t('notifications.printerFilter')}</label>
  477. <select
  478. value={printerId ?? ''}
  479. onChange={(e) => setPrinterId(e.target.value ? Number(e.target.value) : null)}
  480. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  481. >
  482. <option value="">{t('notifications.allPrinters')}</option>
  483. {printers?.map((p) => (
  484. <option key={p.id} value={p.id}>
  485. {p.name}
  486. </option>
  487. ))}
  488. </select>
  489. <p className="text-xs text-bambu-gray mt-1">
  490. {t('notifications.onlyFromPrinter')}
  491. </p>
  492. </div>
  493. {/* Quiet Hours */}
  494. <div className="space-y-2">
  495. <div className="flex items-center justify-between">
  496. <label className="text-sm text-white">{t('notifications.quietHoursDnd')}</label>
  497. <Toggle
  498. checked={quietHoursEnabled}
  499. onChange={setQuietHoursEnabled}
  500. />
  501. </div>
  502. {quietHoursEnabled && (
  503. <div className="grid grid-cols-2 gap-3">
  504. <div>
  505. <label className="block text-xs text-bambu-gray mb-1">{t('notifications.quietStart')}</label>
  506. <input
  507. type="time"
  508. value={quietHoursStart}
  509. onChange={(e) => setQuietHoursStart(e.target.value)}
  510. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  511. />
  512. </div>
  513. <div>
  514. <label className="block text-xs text-bambu-gray mb-1">{t('notifications.quietEnd')}</label>
  515. <input
  516. type="time"
  517. value={quietHoursEnd}
  518. onChange={(e) => setQuietHoursEnd(e.target.value)}
  519. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  520. />
  521. </div>
  522. </div>
  523. )}
  524. </div>
  525. {/* Daily Digest */}
  526. <div className="space-y-2">
  527. <div className="flex items-center justify-between">
  528. <div>
  529. <label className="text-sm text-white">{t('notifications.dailyDigestLabel')}</label>
  530. <p className="text-xs text-bambu-gray">{t('notifications.batchNotifications')}</p>
  531. </div>
  532. <Toggle
  533. checked={dailyDigestEnabled}
  534. onChange={setDailyDigestEnabled}
  535. />
  536. </div>
  537. {dailyDigestEnabled && (
  538. <div>
  539. <label className="block text-xs text-bambu-gray mb-1">{t('notifications.sendDigestAt')}</label>
  540. <input
  541. type="time"
  542. value={dailyDigestTime}
  543. onChange={(e) => setDailyDigestTime(e.target.value)}
  544. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  545. />
  546. <p className="text-xs text-bambu-gray mt-1">
  547. {t('notifications.digestCollected')}
  548. </p>
  549. </div>
  550. )}
  551. </div>
  552. {/* Event Toggles */}
  553. <div className="space-y-3">
  554. <p className="text-sm text-bambu-gray">{t('notifications.notificationEvents')}</p>
  555. {/* Print Events */}
  556. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  557. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.printEvents')}</p>
  558. <div className="grid grid-cols-2 gap-2">
  559. <div className="flex items-center justify-between">
  560. <span className="text-sm text-white">{t('notifications.start')}</span>
  561. <Toggle checked={onPrintStart} onChange={setOnPrintStart} />
  562. </div>
  563. <div className="flex items-center justify-between">
  564. <span className="text-sm text-white">{t('notifications.complete')}</span>
  565. <Toggle checked={onPrintComplete} onChange={setOnPrintComplete} />
  566. </div>
  567. <div className="flex items-center justify-between">
  568. <span className="text-sm text-white">{t('notifications.failed')}</span>
  569. <Toggle checked={onPrintFailed} onChange={setOnPrintFailed} />
  570. </div>
  571. <div className="flex items-center justify-between">
  572. <span className="text-sm text-white">{t('notifications.stopped')}</span>
  573. <Toggle checked={onPrintStopped} onChange={setOnPrintStopped} />
  574. </div>
  575. <div className="flex items-center justify-between col-span-2">
  576. <div>
  577. <span className="text-sm text-white">{t('notifications.progress')}</span>
  578. <span className="text-xs text-bambu-gray ml-1">{t('notifications.progressPercent')}</span>
  579. </div>
  580. <Toggle checked={onPrintProgress} onChange={setOnPrintProgress} />
  581. </div>
  582. <div className="flex items-center justify-between col-span-2">
  583. <div>
  584. <span className="text-sm text-white">{t('notifications.billingChargeFailedLabel')}</span>
  585. <span className="text-xs text-bambu-gray ml-1">{t('notifications.billingChargeFailedDescription')}</span>
  586. </div>
  587. <Toggle checked={onBillingChargeFailed} onChange={setOnBillingChargeFailed} />
  588. </div>
  589. <div className="flex items-center justify-between col-span-2">
  590. <div>
  591. <span className="text-sm text-white">{t('notifications.plateClearRequired')}</span>
  592. <span className="text-xs text-bambu-gray ml-1">{t('notifications.plateClearRequiredDescription')}</span>
  593. </div>
  594. <Toggle checked={onPlateClearRequired} onChange={setOnPlateClearRequired} />
  595. </div>
  596. <div className="flex items-center justify-between col-span-2">
  597. <div>
  598. <span className="text-sm text-white">{t('notifications.printConfirmRequest')}</span>
  599. <span className="text-xs text-bambu-gray ml-1">{t('notifications.printConfirmRequestDescription')}</span>
  600. </div>
  601. <Toggle checked={onPrintConfirmRequest} onChange={setOnPrintConfirmRequest} />
  602. </div>
  603. <div className="flex items-center justify-between col-span-2">
  604. <div>
  605. <span className="text-sm text-white">{t('notifications.bedCooled')}</span>
  606. <span className="text-xs text-bambu-gray ml-1">{t('notifications.bedCooledAfterPrint')}</span>
  607. </div>
  608. <Toggle checked={onBedCooled} onChange={setOnBedCooled} />
  609. </div>
  610. <div className="flex items-center justify-between col-span-2">
  611. <div>
  612. <span className="text-sm text-white">{t('notifications.firstLayerCompleteLabel')}</span>
  613. <span className="text-xs text-bambu-gray ml-1">{t('notifications.firstLayerCompleteDescription')}</span>
  614. </div>
  615. <Toggle checked={onFirstLayerComplete} onChange={setOnFirstLayerComplete} />
  616. </div>
  617. </div>
  618. </div>
  619. {/* Printer Status Events */}
  620. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  621. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.printerStatus')}</p>
  622. <div className="grid grid-cols-2 gap-2">
  623. <div className="flex items-center justify-between">
  624. <span className="text-sm text-white">{t('notifications.offline')}</span>
  625. <Toggle checked={onPrinterOffline} onChange={setOnPrinterOffline} />
  626. </div>
  627. <div className="flex items-center justify-between col-span-2">
  628. <div>
  629. <span className="text-sm text-white">{t('notifications.haSensorAlert')}</span>
  630. <span className="text-xs text-bambu-gray ml-1">{t('notifications.haSensorAlertDescription')}</span>
  631. </div>
  632. <Toggle checked={onHaSensorAlert} onChange={setOnHaSensorAlert} />
  633. </div>
  634. <div className="flex items-center justify-between col-span-2">
  635. <div>
  636. <span className="text-sm text-white">{t('notifications.locationHaSensorAlert')}</span>
  637. <span className="text-xs text-bambu-gray ml-1">{t('notifications.locationHaSensorAlertDescription')}</span>
  638. </div>
  639. <Toggle checked={onLocationHaSensorAlert} onChange={setOnLocationHaSensorAlert} />
  640. </div>
  641. <div className="flex items-center justify-between">
  642. <span className="text-sm text-white">{t('notifications.error')}</span>
  643. <Toggle checked={onPrinterError} onChange={setOnPrinterError} />
  644. </div>
  645. <div className="flex items-center justify-between">
  646. <span className="text-sm text-white">{t('notifications.aiFailureDetection')}</span>
  647. <Toggle checked={onAiFailureDetection} onChange={setOnAiFailureDetection} />
  648. </div>
  649. <div className="flex items-center justify-between">
  650. <span className="text-sm text-white">{t('notifications.lowFilament')}</span>
  651. <Toggle checked={onFilamentLow} onChange={setOnFilamentLow} />
  652. </div>
  653. <div className="flex items-center justify-between">
  654. <span className="text-sm text-white">{t('notifications.maintenance')}</span>
  655. <Toggle checked={onMaintenanceDue} onChange={setOnMaintenanceDue} />
  656. </div>
  657. </div>
  658. </div>
  659. {/* Inventory Stock Alerts */}
  660. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  661. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.inventoryAlerts')}</p>
  662. <div className="grid grid-cols-1 gap-2">
  663. <div className="flex items-center justify-between">
  664. <div>
  665. <span className="text-sm text-white">{t('notifications.stockReorderAlert')}</span>
  666. <span className="text-xs text-bambu-gray ml-1">{t('notifications.stockReorderAlertDescription')}</span>
  667. </div>
  668. <Toggle checked={onStockReorderAlert} onChange={setOnStockReorderAlert} />
  669. </div>
  670. <div className="flex items-center justify-between">
  671. <div>
  672. <span className="text-sm text-white">{t('notifications.stockBreakAlert')}</span>
  673. <span className="text-xs text-bambu-gray ml-1">{t('notifications.stockBreakAlertDescription')}</span>
  674. </div>
  675. <Toggle checked={onStockBreakAlert} onChange={setOnStockBreakAlert} />
  676. </div>
  677. </div>
  678. </div>
  679. {/* Messages other applications send (POST /notifications/app-message) */}
  680. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  681. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.connectedApps')}</p>
  682. <div className="flex items-center justify-between">
  683. <div>
  684. <span className="text-sm text-white">{t('notifications.appMessages')}</span>
  685. <span className="text-xs text-bambu-gray ml-1">{t('notifications.appMessagesDescription')}</span>
  686. </div>
  687. <Toggle checked={onAppMessage} onChange={setOnAppMessage} />
  688. </div>
  689. </div>
  690. {/* Per-event ntfy priority (#990) */}
  691. {providerType === 'ntfy' && (() => {
  692. const enabledEvents: Array<{ key: string; label: string }> = [];
  693. if (onPrintStart) enabledEvents.push({ key: 'on_print_start', label: t('notifications.start') });
  694. if (onPrintComplete) enabledEvents.push({ key: 'on_print_complete', label: t('notifications.complete') });
  695. if (onPrintFailed) enabledEvents.push({ key: 'on_print_failed', label: t('notifications.failed') });
  696. if (onPrintStopped) enabledEvents.push({ key: 'on_print_stopped', label: t('notifications.stopped') });
  697. if (onPrintProgress) enabledEvents.push({ key: 'on_print_progress', label: t('notifications.progress') });
  698. if (onBillingChargeFailed) enabledEvents.push({ key: 'on_billing_charge_failed', label: t('notifications.billingChargeFailedLabel') });
  699. if (onPlateClearRequired) enabledEvents.push({ key: 'on_plate_clear_required', label: t('notifications.plateClearRequired') });
  700. if (onPrintConfirmRequest) enabledEvents.push({ key: 'on_print_confirm_request', label: t('notifications.printConfirmRequest') });
  701. if (onBedCooled) enabledEvents.push({ key: 'on_bed_cooled', label: t('notifications.bedCooled') });
  702. if (onFirstLayerComplete) enabledEvents.push({ key: 'on_first_layer_complete', label: t('notifications.firstLayerCompleteLabel') });
  703. if (onPrinterOffline) enabledEvents.push({ key: 'on_printer_offline', label: t('notifications.offline') });
  704. if (onPrinterError) enabledEvents.push({ key: 'on_printer_error', label: t('notifications.error') });
  705. if (onHaSensorAlert) enabledEvents.push({ key: 'on_ha_sensor_alert', label: t('notifications.haSensorAlert') });
  706. if (onLocationHaSensorAlert) enabledEvents.push({ key: 'on_location_ha_sensor_alert', label: t('notifications.locationHaSensorAlert') });
  707. if (onAiFailureDetection) enabledEvents.push({ key: 'on_ai_failure_detection', label: t('notifications.aiFailureDetection') });
  708. if (onFilamentLow) enabledEvents.push({ key: 'on_filament_low', label: t('notifications.lowFilament') });
  709. if (onMaintenanceDue) enabledEvents.push({ key: 'on_maintenance_due', label: t('notifications.maintenance') });
  710. if (onStockReorderAlert) enabledEvents.push({ key: 'on_stock_reorder_alert', label: t('notifications.stockReorderAlert') });
  711. if (onStockBreakAlert) enabledEvents.push({ key: 'on_stock_break_alert', label: t('notifications.stockBreakAlert') });
  712. if (enabledEvents.length === 0) return null;
  713. return (
  714. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  715. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-1">
  716. {t('notifications.eventPriority.sectionTitle')}
  717. </p>
  718. <p className="text-xs text-bambu-gray mb-2">{t('notifications.eventPriority.helpNtfy')}</p>
  719. <div className="space-y-2">
  720. {enabledEvents.map((ev) => (
  721. <div key={ev.key} className="flex items-center justify-between gap-3">
  722. <span className="text-sm text-white">{ev.label}</span>
  723. <select
  724. value={eventPriorities[ev.key] ?? 3}
  725. onChange={(e) => {
  726. const next = Number(e.target.value);
  727. setEventPriorities((prev) => ({ ...prev, [ev.key]: next }));
  728. }}
  729. className="px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:border-bambu-green focus:outline-none"
  730. >
  731. <option value={1}>{t('notifications.eventPriority.min')}</option>
  732. <option value={2}>{t('notifications.eventPriority.low')}</option>
  733. <option value={3}>{t('notifications.eventPriority.default')}</option>
  734. <option value={4}>{t('notifications.eventPriority.high')}</option>
  735. <option value={5}>{t('notifications.eventPriority.urgent')}</option>
  736. </select>
  737. </div>
  738. ))}
  739. </div>
  740. </div>
  741. );
  742. })()}
  743. </div>
  744. {/* Actions */}
  745. <div className="flex gap-3 pt-2">
  746. <Button
  747. type="button"
  748. variant="secondary"
  749. onClick={onClose}
  750. className="flex-1"
  751. >
  752. {t('notifications.cancel')}
  753. </Button>
  754. <Button
  755. type="submit"
  756. disabled={isPending}
  757. className="flex-1"
  758. >
  759. {isPending ? (
  760. <Loader2 className="w-4 h-4 animate-spin" />
  761. ) : (
  762. <Save className="w-4 h-4" />
  763. )}
  764. {isEditing ? t('notifications.save') : t('notifications.add')}
  765. </Button>
  766. </div>
  767. </form>
  768. </div>
  769. </div>
  770. );
  771. }