AddNotificationModal.tsx 32 KB

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