AddNotificationModal.tsx 33 KB

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