AddNotificationModal.tsx 32 KB

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