AddNotificationModal.tsx 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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, TelegramVerdictMode } from '../api/client';
  7. import { Button } from './Button';
  8. import { Toggle } from './Toggle';
  9. import { isNotifyPushOnlyTarget, isNotifyPhotoUnsupported } from '../utils/notify';
  10. interface ConfigField {
  11. key: string;
  12. label: string;
  13. type: string;
  14. required: boolean;
  15. placeholder?: string;
  16. help?: string;
  17. options?: { value: string; label: string }[];
  18. showIf?: (config: Record<string, string>) => boolean;
  19. advanced?: boolean;
  20. pattern?: string;
  21. }
  22. const NOTIFY_METRICS = ['progress', 'eta', 'layers', 'nozzle', 'bed', 'chamber'] as const;
  23. type NotifyMetric = (typeof NOTIFY_METRICS)[number];
  24. interface AddNotificationModalProps {
  25. provider?: NotificationProvider | null;
  26. onClose: () => void;
  27. }
  28. const PROVIDER_VALUES: ProviderType[] = ['email', 'telegram', 'discord', 'ntfy', 'pushover', 'bark', 'gotify', 'callmebot', 'webhook', 'homeassistant', 'notify'];
  29. export function AddNotificationModal({ provider, onClose }: AddNotificationModalProps) {
  30. const { t, i18n } = useTranslation();
  31. const queryClient = useQueryClient();
  32. const isEditing = !!provider;
  33. const [name, setName] = useState(provider?.name || '');
  34. const [providerType, setProviderType] = useState<ProviderType>(provider?.provider_type || 'email');
  35. const [printerId, setPrinterId] = useState<number | null>(provider?.printer_id || null);
  36. const [attachPhoto, setAttachPhoto] = useState(
  37. provider?.provider_type === 'notify' && isNotifyPhotoUnsupported(String(provider.config.device_id || ''))
  38. ? false
  39. : provider?.attach_photo ?? true
  40. );
  41. const [quietHoursEnabled, setQuietHoursEnabled] = useState(provider?.quiet_hours_enabled || false);
  42. const [quietHoursStart, setQuietHoursStart] = useState(provider?.quiet_hours_start || '22:00');
  43. const [quietHoursEnd, setQuietHoursEnd] = useState(provider?.quiet_hours_end || '07:00');
  44. // Daily digest
  45. const [dailyDigestEnabled, setDailyDigestEnabled] = useState(provider?.daily_digest_enabled || false);
  46. const [dailyDigestTime, setDailyDigestTime] = useState(provider?.daily_digest_time || '08:00');
  47. // Event toggles
  48. const [onPrintStart, setOnPrintStart] = useState(provider?.on_print_start ?? false);
  49. const [onPrintComplete, setOnPrintComplete] = useState(provider?.on_print_complete ?? true);
  50. const [onPrintFailed, setOnPrintFailed] = useState(provider?.on_print_failed ?? true);
  51. const [onPrintStopped, setOnPrintStopped] = useState(provider?.on_print_stopped ?? true);
  52. const [onPrintProgress, setOnPrintProgress] = useState(provider?.on_print_progress ?? false);
  53. const [onBillingChargeFailed, setOnBillingChargeFailed] = useState(provider?.on_billing_charge_failed ?? true);
  54. const [onPrinterOffline, setOnPrinterOffline] = useState(provider?.on_printer_offline ?? false);
  55. const [onPrinterError, setOnPrinterError] = useState(provider?.on_printer_error ?? false);
  56. const [onAiFailureDetection, setOnAiFailureDetection] = useState(provider?.on_ai_failure_detection ?? false);
  57. const [onFilamentLow, setOnFilamentLow] = useState(provider?.on_filament_low ?? false);
  58. const [onMaintenanceDue, setOnMaintenanceDue] = useState(provider?.on_maintenance_due ?? false);
  59. const [onStockReorderAlert, setOnStockReorderAlert] = useState(provider?.on_stock_reorder_alert ?? false);
  60. const [onStockBreakAlert, setOnStockBreakAlert] = useState(provider?.on_stock_break_alert ?? false);
  61. const [onPlateClearRequired, setOnPlateClearRequired] = useState(provider?.on_plate_clear_required ?? false);
  62. // Post-print outcome confirmation (#1898). Defaults ON — it only fires for
  63. // prints that opted in per-job, so the toggle exists to mute a channel.
  64. const [onPrintConfirmRequest, setOnPrintConfirmRequest] = useState(provider?.on_print_confirm_request ?? true);
  65. // Telegram only (#3046): inline link buttons, a thumbs reaction, or both.
  66. const [telegramVerdictMode, setTelegramVerdictMode] = useState<TelegramVerdictMode>(
  67. provider?.telegram_verdict_mode ?? 'buttons'
  68. );
  69. const [onBedCooled, setOnBedCooled] = useState(provider?.on_bed_cooled ?? false);
  70. const [onHaSensorAlert, setOnHaSensorAlert] = useState(provider?.on_ha_sensor_alert ?? false);
  71. const [onLocationHaSensorAlert, setOnLocationHaSensorAlert] = useState(
  72. provider?.on_location_ha_sensor_alert ?? false
  73. );
  74. const [onFirstLayerComplete, setOnFirstLayerComplete] = useState(provider?.on_first_layer_complete ?? false);
  75. const [onAppMessage, setOnAppMessage] = useState(provider?.on_app_message ?? false);
  76. const [notifyLiveActivities, setNotifyLiveActivities] = useState(
  77. provider?.config?.live_activities === true && !isNotifyPushOnlyTarget(String(provider?.config?.device_id || ''))
  78. );
  79. const [notifyLockScreenWidgets, setNotifyLockScreenWidgets] = useState(
  80. provider?.config?.lock_screen_widgets === true && !isNotifyPushOnlyTarget(String(provider?.config?.device_id || ''))
  81. );
  82. const [notifyMetrics, setNotifyMetrics] = useState<NotifyMetric[]>(() => {
  83. const metrics = provider?.config?.live_activity_metrics;
  84. return Array.isArray(metrics) ? NOTIFY_METRICS.filter((metric) => metrics.includes(metric)) : [];
  85. });
  86. // Provider-specific config (scalar fields only — event_priorities is split out
  87. // into its own state because it's an object, not a string).
  88. const [config, setConfig] = useState<Record<string, string>>(
  89. provider?.config
  90. ? Object.fromEntries(
  91. Object.entries(provider.config)
  92. .filter(([k]) => k !== 'event_priorities' && k !== 'live_activities' && k !== 'live_activity_metrics' && k !== 'lock_screen_widgets')
  93. .map(([k, v]) => [k, String(v)]),
  94. )
  95. : {},
  96. );
  97. // Per-event priority for ntfy (#990) and Gotify (#2743). Map of event key →
  98. // 1-5. Persisted into config.event_priorities on save for those two only.
  99. const initialEventPriorities = (() => {
  100. const raw = provider?.config?.event_priorities;
  101. if (!raw || typeof raw !== 'object') return {} as Record<string, number>;
  102. const out: Record<string, number> = {};
  103. for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
  104. const n = Number(v);
  105. if (Number.isInteger(n) && n >= 1 && n <= 5) out[k] = n;
  106. }
  107. return out;
  108. })();
  109. const [eventPriorities, setEventPriorities] = useState<Record<string, number>>(initialEventPriorities);
  110. const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  111. const [error, setError] = useState<string | null>(null);
  112. // Fetch printers for linking
  113. const { data: printers } = useQuery({
  114. queryKey: ['printers'],
  115. queryFn: api.getPrinters,
  116. });
  117. // Close on Escape key
  118. useEffect(() => {
  119. const handleKeyDown = (e: KeyboardEvent) => {
  120. if (e.key === 'Escape') onClose();
  121. };
  122. window.addEventListener('keydown', handleKeyDown);
  123. return () => window.removeEventListener('keydown', handleKeyDown);
  124. }, [onClose]);
  125. const notifyPushOnlyTarget = providerType === 'notify' && isNotifyPushOnlyTarget(config.device_id || '');
  126. const notifyPhotosUnsupported = providerType === 'notify' && isNotifyPhotoUnsupported(config.device_id || '');
  127. const configForRequest = () => providerType === 'notify'
  128. ? {
  129. ...config,
  130. live_activities: notifyLiveActivities && !notifyPushOnlyTarget,
  131. lock_screen_widgets: notifyLockScreenWidgets && !notifyPushOnlyTarget,
  132. live_activity_privacy: config.live_activity_privacy === 'true',
  133. live_activity_stage: config.live_activity_stage === 'true',
  134. live_activity_metrics: notifyMetrics,
  135. time_sensitive: config.time_sensitive === 'true',
  136. }
  137. : config;
  138. // Test configuration mutation
  139. const testMutation = useMutation({
  140. mutationFn: () => api.testNotificationConfig({ provider_type: providerType, config: configForRequest(), attach_photo: attachPhoto && !notifyPhotosUnsupported }),
  141. onSuccess: (result) => {
  142. setTestResult(result);
  143. setError(null);
  144. },
  145. onError: (err: Error) => {
  146. setTestResult({ success: false, message: err.message });
  147. },
  148. });
  149. // Create mutation
  150. const createMutation = useMutation({
  151. mutationFn: (data: NotificationProviderCreate) => api.createNotificationProvider(data),
  152. onSuccess: () => {
  153. queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
  154. onClose();
  155. },
  156. onError: (err: Error) => {
  157. setError(err.message);
  158. },
  159. });
  160. // Update mutation
  161. const updateMutation = useMutation({
  162. mutationFn: (data: NotificationProviderUpdate) => api.updateNotificationProvider(provider!.id, data),
  163. onSuccess: () => {
  164. queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
  165. onClose();
  166. },
  167. onError: (err: Error) => {
  168. setError(err.message);
  169. },
  170. });
  171. const handleSubmit = (e: React.FormEvent) => {
  172. e.preventDefault();
  173. setError(null);
  174. if (!name.trim()) {
  175. setError(t('notifications.nameRequired'));
  176. return;
  177. }
  178. // Validate provider-specific config
  179. const requiredFields = getRequiredFields(providerType);
  180. for (const field of requiredFields) {
  181. if (!config[field.key]?.trim()) {
  182. setError(t('notifications.fieldRequired', { field: field.label }));
  183. return;
  184. }
  185. }
  186. // HA custom service-data must be a JSON object (#1441)
  187. if (providerType === 'homeassistant' && config.data?.trim()) {
  188. let parsed: unknown;
  189. try {
  190. parsed = JSON.parse(config.data);
  191. } catch {
  192. setError(t('notifications.haDataInvalid'));
  193. return;
  194. }
  195. if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
  196. setError(t('notifications.haDataInvalid'));
  197. return;
  198. }
  199. }
  200. // Telegram forum topic must be a plain integer (#1518) — type="number"
  201. // still lets "1e5" and "-" through, and Telegram would 400 on those.
  202. if (providerType === 'telegram' && config.message_thread_id?.trim()) {
  203. if (!/^\d+$/.test(config.message_thread_id.trim())) {
  204. setError(t('notifications.telegramThreadIdInvalid'));
  205. return;
  206. }
  207. }
  208. const finalConfig: Record<string, unknown> =
  209. (providerType === 'ntfy' || providerType === 'gotify') && Object.keys(eventPriorities).length > 0
  210. ? { ...config, event_priorities: eventPriorities }
  211. : configForRequest();
  212. const data = {
  213. name: name.trim(),
  214. provider_type: providerType,
  215. config: finalConfig,
  216. printer_id: printerId,
  217. attach_photo: attachPhoto && !notifyPhotosUnsupported,
  218. quiet_hours_enabled: quietHoursEnabled,
  219. quiet_hours_start: quietHoursEnabled ? quietHoursStart : null,
  220. quiet_hours_end: quietHoursEnabled ? quietHoursEnd : null,
  221. // Daily digest
  222. daily_digest_enabled: dailyDigestEnabled,
  223. daily_digest_time: dailyDigestEnabled ? dailyDigestTime : null,
  224. // Event toggles
  225. on_print_start: onPrintStart,
  226. on_print_complete: onPrintComplete,
  227. on_print_failed: onPrintFailed,
  228. on_print_stopped: onPrintStopped,
  229. on_print_progress: onPrintProgress,
  230. on_billing_charge_failed: onBillingChargeFailed,
  231. on_printer_offline: onPrinterOffline,
  232. on_printer_error: onPrinterError,
  233. on_ai_failure_detection: onAiFailureDetection,
  234. on_filament_low: onFilamentLow,
  235. on_maintenance_due: onMaintenanceDue,
  236. on_stock_reorder_alert: onStockReorderAlert,
  237. on_stock_break_alert: onStockBreakAlert,
  238. on_plate_clear_required: onPlateClearRequired,
  239. on_print_confirm_request: onPrintConfirmRequest,
  240. telegram_verdict_mode: providerType === 'telegram' ? telegramVerdictMode : 'buttons',
  241. on_bed_cooled: onBedCooled,
  242. on_ha_sensor_alert: onHaSensorAlert,
  243. on_location_ha_sensor_alert: onLocationHaSensorAlert,
  244. on_first_layer_complete: onFirstLayerComplete,
  245. on_app_message: onAppMessage,
  246. };
  247. if (isEditing) {
  248. updateMutation.mutate(data);
  249. } else {
  250. createMutation.mutate(data);
  251. }
  252. };
  253. const isPending = createMutation.isPending || updateMutation.isPending;
  254. // Get config fields for each provider type
  255. const getConfigFields = (type: ProviderType): ConfigField[] => {
  256. switch (type) {
  257. case 'callmebot':
  258. return [
  259. { key: 'phone', label: 'Phone Number', placeholder: '+1234567890', type: 'text', required: true },
  260. { key: 'apikey', label: 'API Key', placeholder: 'Your CallMeBot API key', type: 'text', required: true },
  261. ];
  262. case 'ntfy':
  263. return [
  264. { key: 'server', label: 'Server URL', placeholder: 'https://ntfy.sh', type: 'text', required: false },
  265. { key: 'topic', label: 'Topic', placeholder: 'my-bambuddy', type: 'text', required: true },
  266. { key: 'auth_token', label: 'Auth Token', placeholder: 'Optional authentication', type: 'password', required: false },
  267. ];
  268. case 'pushover':
  269. return [
  270. { key: 'user_key', label: 'User Key', placeholder: 'Your Pushover user key', type: 'text', required: true },
  271. { key: 'app_token', label: 'App Token', placeholder: 'Your Pushover app token', type: 'text', required: true },
  272. { key: 'priority', label: 'Priority', placeholder: '0 (normal)', type: 'number', required: false },
  273. // Emergency priority (2) requires retry/expire — Pushover rejects the
  274. // message otherwise. Only shown when priority is set to 2.
  275. {
  276. key: 'retry',
  277. label: t('notifications.pushoverRetry'),
  278. placeholder: '60',
  279. type: 'number',
  280. required: false,
  281. showIf: (cfg: Record<string, string>) => cfg.priority === '2',
  282. },
  283. {
  284. key: 'expire',
  285. label: t('notifications.pushoverExpire'),
  286. placeholder: '3600',
  287. type: 'number',
  288. required: false,
  289. showIf: (cfg: Record<string, string>) => cfg.priority === '2',
  290. },
  291. ];
  292. case 'notify':
  293. return [
  294. { key: 'device_id', label: t('notifications.notifyDeviceId'), type: 'text', required: true },
  295. { key: 'token', label: t('notifications.notifyToken'), type: 'password', required: true },
  296. { key: 'icon_url', label: t('notifications.notifyIconUrl'), placeholder: 'https://example.com/icon.png', type: 'url', pattern: 'https://.*', required: false },
  297. { key: 'group_type', label: t('notifications.notifyGroupType'), type: 'text', required: false, help: t('notifications.notifyGroupTypeHelp') },
  298. {
  299. key: 'time_sensitive', label: t('notifications.notifyTimeSensitive'), type: 'select', required: false,
  300. options: [{ value: 'false', label: t('common.no') }, { value: 'true', label: t('common.yes') }],
  301. help: t('notifications.notifyTimeSensitiveHelp'),
  302. },
  303. {
  304. key: 'live_activity_privacy', label: t('notifications.notifyPrivacy'), type: 'select', required: false, advanced: true,
  305. options: [{ value: 'false', label: t('common.no') }, { value: 'true', label: t('common.yes') }],
  306. help: t('notifications.notifyPrivacyHelp'),
  307. },
  308. {
  309. key: 'live_activity_stage', label: t('notifications.notifyShowStage'), type: 'select', required: false, advanced: true,
  310. options: [{ value: 'false', label: t('common.no') }, { value: 'true', label: t('common.yes') }],
  311. },
  312. {
  313. key: 'live_activity_style', label: t('notifications.notifyStyle'), type: 'select', required: false, advanced: true,
  314. options: [
  315. { value: 'bar', label: t('notifications.notifyStyleBar') },
  316. { value: 'segments', label: t('notifications.notifyStyleSegments') },
  317. { value: 'none', label: t('notifications.notifyStyleNone') },
  318. ],
  319. },
  320. { key: 'live_activity_button_url', label: t('notifications.notifyDashboardUrl'), type: 'url', pattern: 'https://.*', placeholder: 'https://bambuddy.example.com', required: false, advanced: true },
  321. { key: 'live_activity_symbol', label: t('notifications.notifySymbol'), type: 'text', placeholder: 'printer.fill', required: false, advanced: true },
  322. { key: 'live_activity_tint', label: t('notifications.notifyTint'), type: 'text', placeholder: '#00AE42', pattern: '#[0-9a-fA-F]{6}', required: false, advanced: true },
  323. ];
  324. case 'telegram':
  325. return [
  326. { key: 'bot_token', label: 'Bot Token', placeholder: 'Bot token from @BotFather', type: 'password', required: true },
  327. { key: 'chat_id', label: 'Chat ID', placeholder: 'Your chat or group ID', type: 'text', required: true },
  328. // Optional forum topic (#1518). Left empty, Telegram posts to the
  329. // group's General topic exactly as before.
  330. {
  331. key: 'message_thread_id',
  332. label: t('notifications.telegramThreadId'),
  333. placeholder: '123',
  334. type: 'number',
  335. required: false,
  336. help: t('notifications.telegramThreadIdHelp'),
  337. },
  338. ];
  339. case 'email':
  340. return [
  341. { key: 'smtp_server', label: 'SMTP Server', placeholder: 'smtp.gmail.com', type: 'text', required: true },
  342. { key: 'smtp_port', label: 'SMTP Port', placeholder: '587', type: 'number', required: false },
  343. { key: 'security', label: 'Security', type: 'select', required: false, options: [
  344. { value: 'starttls', label: 'STARTTLS (Port 587)' },
  345. { value: 'ssl', label: 'SSL/TLS (Port 465)' },
  346. { value: 'none', label: 'None (Port 25)' },
  347. ]},
  348. { key: 'auth_enabled', label: 'Authentication', type: 'select', required: false, options: [
  349. { value: 'true', label: 'Enabled' },
  350. { value: 'false', label: 'Disabled' },
  351. ]},
  352. { key: 'username', label: 'Username', placeholder: 'your@email.com', type: 'text', required: false },
  353. { key: 'password', label: 'Password', placeholder: 'App password', type: 'password', required: false },
  354. { key: 'from_email', label: 'From Email', placeholder: 'your@email.com', type: 'text', required: true },
  355. { key: 'to_email', label: 'To Email', placeholder: 'recipient@email.com', type: 'text', required: true },
  356. ];
  357. case 'discord':
  358. return [
  359. { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://discord.com/api/webhooks/...', type: 'text', required: true },
  360. ];
  361. case 'webhook':
  362. return [
  363. { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://example.com/webhook', type: 'text', required: true },
  364. { key: 'payload_format', label: 'Payload Format', type: 'select', required: false, options: [
  365. { value: 'generic', label: 'Generic JSON' },
  366. { value: 'slack', label: 'Slack / Mattermost' },
  367. ]},
  368. { key: 'auth_header', label: 'Authorization', placeholder: 'Bearer token (optional)', type: 'password', required: false },
  369. { key: 'field_title', label: 'Title Field Name', placeholder: 'title', type: 'text', required: false, showIf: (cfg: Record<string, string>) => cfg.payload_format !== 'slack' },
  370. { key: 'field_message', label: 'Message Field Name', placeholder: 'message', type: 'text', required: false, showIf: (cfg: Record<string, string>) => cfg.payload_format !== 'slack' },
  371. ];
  372. case 'homeassistant':
  373. return [
  374. {
  375. key: 'service',
  376. label: 'Home Assistant Service',
  377. placeholder: 'notify.mobile_app_myphone',
  378. type: 'text',
  379. required: false,
  380. help: t('notifications.haServiceHelp'),
  381. },
  382. { key: 'data', label: 'Data (JSON, optional)', placeholder: '{"priority": "high", "ttl": 0, "channel": "3D Printing"}', type: 'textarea', required: false },
  383. ];
  384. case 'bark':
  385. return [
  386. { key: 'device_key', label: 'Device Key', placeholder: 'Your Bark device key', type: 'text', required: true },
  387. { key: 'server', label: 'Server URL', placeholder: 'https://api.day.app', type: 'text', required: false },
  388. { key: 'group', label: 'Group', placeholder: 'Bambuddy', type: 'text', required: false },
  389. { key: 'sound', label: 'Sound', placeholder: 'minuet', type: 'text', required: false },
  390. { key: 'level', label: 'Interruption Level', type: 'select', required: false, options: [
  391. { value: '', label: 'Default' },
  392. { value: 'active', label: 'Active' },
  393. { value: 'timeSensitive', label: 'Time Sensitive' },
  394. { value: 'critical', label: 'Critical (bypasses Silent/Focus)' },
  395. { value: 'passive', label: 'Passive (no sound)' },
  396. ]},
  397. ];
  398. case 'gotify':
  399. return [
  400. { key: 'server', label: 'Server URL', placeholder: 'https://gotify.example.com', type: 'text', required: true },
  401. { key: 'app_token', label: 'App Token', placeholder: 'Token of a Gotify application', type: 'password', required: true },
  402. ];
  403. default:
  404. return [];
  405. }
  406. };
  407. const getRequiredFields = (type: ProviderType) => {
  408. return getConfigFields(type).filter(f => f.required);
  409. };
  410. const configFields = getConfigFields(providerType);
  411. const renderConfigFields = (fields: ConfigField[]) =>
  412. fields
  413. .filter((field) => field.showIf?.(config) !== false)
  414. .map((field) => (
  415. <div key={field.key}>
  416. <label htmlFor={`notification-config-${field.key}`} className="block text-sm text-bambu-gray mb-1">
  417. {field.label} {field.required && '*'}
  418. </label>
  419. {field.type === 'select' && field.options ? (
  420. <select
  421. id={`notification-config-${field.key}`}
  422. value={config[field.key] || field.options[0]?.value || ''}
  423. onChange={(e) => {
  424. setConfig({ ...config, [field.key]: e.target.value });
  425. setTestResult(null);
  426. }}
  427. 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"
  428. >
  429. {field.options.map((opt) => (
  430. <option key={opt.value} value={opt.value}>
  431. {opt.label}
  432. </option>
  433. ))}
  434. </select>
  435. ) : field.type === 'textarea' ? (
  436. <textarea
  437. id={`notification-config-${field.key}`}
  438. value={config[field.key] || ''}
  439. onChange={(e) => {
  440. setConfig({ ...config, [field.key]: e.target.value });
  441. setTestResult(null);
  442. }}
  443. placeholder={field.placeholder}
  444. rows={3}
  445. 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"
  446. />
  447. ) : (
  448. <input
  449. id={`notification-config-${field.key}`}
  450. type={field.type}
  451. pattern={field.pattern}
  452. value={config[field.key] || ''}
  453. onChange={(e) => {
  454. setConfig({ ...config, [field.key]: e.target.value });
  455. if (providerType === 'notify' && field.key === 'device_id' && isNotifyPushOnlyTarget(e.target.value)) {
  456. setNotifyLiveActivities(false);
  457. setNotifyLockScreenWidgets(false);
  458. }
  459. if (providerType === 'notify' && field.key === 'device_id' && isNotifyPhotoUnsupported(e.target.value)) {
  460. setAttachPhoto(false);
  461. }
  462. setTestResult(null);
  463. }}
  464. placeholder={field.placeholder}
  465. 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"
  466. />
  467. )}
  468. {field.help && (
  469. <p className="text-xs text-bambu-gray mt-1">{field.help}</p>
  470. )}
  471. </div>
  472. ));
  473. return (
  474. <div
  475. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto"
  476. onClick={onClose}
  477. >
  478. <div
  479. 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"
  480. onClick={(e) => e.stopPropagation()}
  481. >
  482. {/* Header */}
  483. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  484. <h2 className="text-lg font-semibold text-white">
  485. {isEditing ? t('notifications.editTitle') : t('notifications.addTitle')}
  486. </h2>
  487. <button
  488. onClick={onClose}
  489. className="text-bambu-gray hover:text-white transition-colors"
  490. >
  491. <X className="w-5 h-5" />
  492. </button>
  493. </div>
  494. {/* Form */}
  495. <form onSubmit={handleSubmit} className="p-6 space-y-4">
  496. {error && (
  497. <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">
  498. {error}
  499. </div>
  500. )}
  501. {/* Name */}
  502. <div>
  503. <label className="block text-sm text-bambu-gray mb-1">{t('notifications.nameLabel')}</label>
  504. <input
  505. type="text"
  506. value={name}
  507. onChange={(e) => setName(e.target.value)}
  508. placeholder={t('notifications.namePlaceholder')}
  509. 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"
  510. />
  511. </div>
  512. {/* Provider Type */}
  513. <div>
  514. <label className="block text-sm text-bambu-gray mb-1">{t('notifications.providerTypeLabel')}</label>
  515. <select
  516. value={providerType}
  517. onChange={(e) => {
  518. setProviderType(e.target.value as ProviderType);
  519. setConfig({}); // Reset config when changing type
  520. setNotifyLiveActivities(false);
  521. setNotifyLockScreenWidgets(false);
  522. setNotifyMetrics([]);
  523. setTestResult(null);
  524. }}
  525. disabled={isEditing}
  526. 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"
  527. >
  528. {/* Sorted by the label shown, so the order holds in every language */}
  529. {PROVIDER_VALUES.map((value) => ({ value, label: t(`notifications.providerTypes.${value}`, value) }))
  530. .sort((a, b) => a.label.localeCompare(b.label, i18n.language, { sensitivity: 'base' }))
  531. .map(({ value, label }) => (
  532. <option key={value} value={value}>
  533. {label}
  534. </option>
  535. ))}
  536. </select>
  537. <p className="text-xs text-bambu-gray mt-1">
  538. {t(`notifications.providerDescriptions.${providerType}`, '')}
  539. </p>
  540. </div>
  541. {/* Provider-specific configuration */}
  542. <div className="space-y-3">
  543. <p className="text-sm text-bambu-gray">{t('notifications.configuration')}</p>
  544. {renderConfigFields(configFields.filter((field) => !field.advanced))}
  545. {providerType === 'notify' && (
  546. <div className="space-y-2">
  547. <div className="flex items-center justify-between gap-3" role="group" aria-label={t('notifications.notifyLiveActivities')}>
  548. <div>
  549. <label className="text-sm text-white">{t('notifications.notifyLiveActivities')}</label>
  550. <p className="text-xs text-bambu-gray">{t('notifications.notifyLiveActivitiesHelp')}</p>
  551. </div>
  552. <Toggle
  553. checked={notifyLiveActivities && !notifyPushOnlyTarget}
  554. disabled={notifyPushOnlyTarget}
  555. onChange={(checked) => {
  556. setNotifyLiveActivities(checked);
  557. setTestResult(null);
  558. setError(null);
  559. }}
  560. />
  561. </div>
  562. {notifyLiveActivities && (
  563. <>
  564. <p className="text-xs text-bambu-gray">{t('notifications.notifyLifecycleHelp')}</p>
  565. <details className="rounded-lg border border-bambu-dark-tertiary p-3">
  566. <summary className="cursor-pointer text-sm text-white">{t('notifications.notifyAppearance')}</summary>
  567. <div className="mt-3 space-y-3">
  568. {renderConfigFields(configFields.filter((field) => field.advanced))}
  569. <fieldset>
  570. <legend className="text-sm text-bambu-gray mb-1">{t('notifications.notifyMetrics')}</legend>
  571. <p className="text-xs text-bambu-gray mb-2">{t('notifications.notifyMetricsHelp')}</p>
  572. <div className="flex flex-wrap gap-3">
  573. {NOTIFY_METRICS.map((metric) => (
  574. <label key={metric} className="flex items-center gap-1 text-sm text-white">
  575. <input
  576. type="checkbox"
  577. checked={notifyMetrics.includes(metric)}
  578. onChange={(e) => {
  579. setNotifyMetrics(e.target.checked
  580. ? [...notifyMetrics, metric]
  581. : notifyMetrics.filter((selected) => selected !== metric));
  582. setTestResult(null);
  583. }}
  584. className="accent-bambu-green"
  585. />
  586. {t(metric === 'progress' ? 'notifications.progress'
  587. : metric === 'eta' ? 'streamOverlay.eta'
  588. : metric === 'layers' ? 'streamOverlay.layer'
  589. : `printers.temperatures.${metric}`)}
  590. </label>
  591. ))}
  592. </div>
  593. </fieldset>
  594. </div>
  595. </details>
  596. </>
  597. )}
  598. <div className="flex items-center justify-between gap-3" role="group" aria-label={t('notifications.notifyLockScreenWidgets')}>
  599. <div>
  600. <label className="text-sm text-white">{t('notifications.notifyLockScreenWidgets')}</label>
  601. <p className="text-xs text-bambu-gray">{t('notifications.notifyLockScreenWidgetsHelp')}</p>
  602. </div>
  603. <Toggle
  604. checked={notifyLockScreenWidgets && !notifyPushOnlyTarget}
  605. disabled={notifyPushOnlyTarget}
  606. onChange={(checked) => {
  607. setNotifyLockScreenWidgets(checked);
  608. setTestResult(null);
  609. setError(null);
  610. }}
  611. />
  612. </div>
  613. {notifyPushOnlyTarget && (
  614. <p className="text-xs text-bambu-gray">{t('notifications.notifyIosFeaturesUnavailable')}</p>
  615. )}
  616. <p className="text-xs text-bambu-gray">{t('notifications.notifyTestHelp')}</p>
  617. </div>
  618. )}
  619. {providerType === 'telegram' && (
  620. <div>
  621. <label htmlFor="telegram-verdict-mode" className="block text-sm text-bambu-gray mb-1">
  622. {t('notifications.telegramVerdictMode')}
  623. </label>
  624. <select
  625. id="telegram-verdict-mode"
  626. value={telegramVerdictMode}
  627. onChange={(e) => setTelegramVerdictMode(e.target.value as TelegramVerdictMode)}
  628. 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"
  629. >
  630. <option value="buttons">{t('notifications.telegramVerdictModeButtons')}</option>
  631. <option value="reactions">{t('notifications.telegramVerdictModeReactions')}</option>
  632. <option value="both">{t('notifications.telegramVerdictModeBoth')}</option>
  633. </select>
  634. <p className="text-xs text-bambu-gray mt-1">{t('notifications.telegramVerdictModeHelp')}</p>
  635. </div>
  636. )}
  637. </div>
  638. {/* Test Button */}
  639. <div className="flex gap-2">
  640. <Button
  641. type="button"
  642. variant="secondary"
  643. onClick={() => {
  644. setTestResult(null);
  645. testMutation.mutate();
  646. }}
  647. disabled={testMutation.isPending || getRequiredFields(providerType).some((field) => !config[field.key]?.trim())}
  648. className="flex-1"
  649. >
  650. {testMutation.isPending ? (
  651. <Loader2 className="w-4 h-4 animate-spin" />
  652. ) : (
  653. <Send className="w-4 h-4" />
  654. )}
  655. {t('notifications.testConfiguration')}
  656. </Button>
  657. </div>
  658. {/* Test Result */}
  659. {testResult && (
  660. <div className={`p-3 rounded-lg flex items-center gap-2 ${
  661. testResult.success
  662. ? 'bg-bambu-green/20 border border-bambu-green/50 text-bambu-green'
  663. : 'bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 text-red-700 dark:text-red-400'
  664. }`}>
  665. {testResult.success ? (
  666. <>
  667. <CheckCircle className="w-5 h-5" />
  668. <span>{testResult.message}</span>
  669. </>
  670. ) : (
  671. <>
  672. <XCircle className="w-5 h-5" />
  673. <span>{testResult.message}</span>
  674. </>
  675. )}
  676. </div>
  677. )}
  678. {/* Link to Printer */}
  679. <div>
  680. <label className="block text-sm text-bambu-gray mb-1">{t('notifications.printerFilter')}</label>
  681. <select
  682. value={printerId ?? ''}
  683. onChange={(e) => setPrinterId(e.target.value ? Number(e.target.value) : null)}
  684. 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"
  685. >
  686. <option value="">{t('notifications.allPrinters')}</option>
  687. {printers?.map((p) => (
  688. <option key={p.id} value={p.id}>
  689. {p.name}
  690. </option>
  691. ))}
  692. </select>
  693. <p className="text-xs text-bambu-gray mt-1">
  694. {t('notifications.onlyFromPrinter')}
  695. </p>
  696. </div>
  697. {/* Attach Photo */}
  698. <div className="flex items-center justify-between">
  699. <div>
  700. <label className="text-sm text-white">{t('notifications.attachPhotoLabel')}</label>
  701. <p className="text-xs text-bambu-gray">{t(notifyPhotosUnsupported ? 'notifications.notifyPhotoUnavailable' : 'notifications.attachPhotoDescription')}</p>
  702. </div>
  703. <Toggle
  704. checked={attachPhoto && !notifyPhotosUnsupported}
  705. disabled={notifyPhotosUnsupported}
  706. onChange={setAttachPhoto}
  707. />
  708. </div>
  709. {/* Quiet Hours */}
  710. <div className="space-y-2">
  711. <div className="flex items-center justify-between">
  712. <label className="text-sm text-white">{t('notifications.quietHoursDnd')}</label>
  713. <Toggle
  714. checked={quietHoursEnabled}
  715. onChange={setQuietHoursEnabled}
  716. />
  717. </div>
  718. {quietHoursEnabled && (
  719. <div className="grid grid-cols-2 gap-3">
  720. <div>
  721. <label className="block text-xs text-bambu-gray mb-1">{t('notifications.quietStart')}</label>
  722. <input
  723. type="time"
  724. value={quietHoursStart}
  725. onChange={(e) => setQuietHoursStart(e.target.value)}
  726. 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"
  727. />
  728. </div>
  729. <div>
  730. <label className="block text-xs text-bambu-gray mb-1">{t('notifications.quietEnd')}</label>
  731. <input
  732. type="time"
  733. value={quietHoursEnd}
  734. onChange={(e) => setQuietHoursEnd(e.target.value)}
  735. 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"
  736. />
  737. </div>
  738. </div>
  739. )}
  740. </div>
  741. {/* Daily Digest */}
  742. <div className="space-y-2">
  743. <div className="flex items-center justify-between">
  744. <div>
  745. <label className="text-sm text-white">{t('notifications.dailyDigestLabel')}</label>
  746. <p className="text-xs text-bambu-gray">{t('notifications.batchNotifications')}</p>
  747. </div>
  748. <Toggle
  749. checked={dailyDigestEnabled}
  750. onChange={setDailyDigestEnabled}
  751. />
  752. </div>
  753. {dailyDigestEnabled && (
  754. <div>
  755. <label className="block text-xs text-bambu-gray mb-1">{t('notifications.sendDigestAt')}</label>
  756. <input
  757. type="time"
  758. value={dailyDigestTime}
  759. onChange={(e) => setDailyDigestTime(e.target.value)}
  760. 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"
  761. />
  762. <p className="text-xs text-bambu-gray mt-1">
  763. {t('notifications.digestCollected')}
  764. </p>
  765. </div>
  766. )}
  767. </div>
  768. {/* Event Toggles */}
  769. <div className="space-y-3">
  770. <p className="text-sm text-bambu-gray">{t('notifications.notificationEvents')}</p>
  771. {/* Print Events */}
  772. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  773. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.printEvents')}</p>
  774. <div className="grid grid-cols-2 gap-2">
  775. <div className="flex items-center justify-between">
  776. <span className="text-sm text-white">{t('notifications.start')}</span>
  777. <Toggle checked={onPrintStart} onChange={setOnPrintStart} />
  778. </div>
  779. <div className="flex items-center justify-between">
  780. <span className="text-sm text-white">{t('notifications.complete')}</span>
  781. <Toggle checked={onPrintComplete} onChange={setOnPrintComplete} />
  782. </div>
  783. <div className="flex items-center justify-between">
  784. <span className="text-sm text-white">{t('notifications.failed')}</span>
  785. <Toggle checked={onPrintFailed} onChange={setOnPrintFailed} />
  786. </div>
  787. <div className="flex items-center justify-between">
  788. <span className="text-sm text-white">{t('notifications.stopped')}</span>
  789. <Toggle checked={onPrintStopped} onChange={setOnPrintStopped} />
  790. </div>
  791. <div className="flex items-center justify-between col-span-2">
  792. <div>
  793. <span className="text-sm text-white">{t('notifications.progress')}</span>
  794. <span className="text-xs text-bambu-gray ml-1">{t('notifications.progressPercent')}</span>
  795. </div>
  796. <Toggle checked={onPrintProgress} onChange={setOnPrintProgress} />
  797. </div>
  798. <div className="flex items-center justify-between col-span-2">
  799. <div>
  800. <span className="text-sm text-white">{t('notifications.billingChargeFailedLabel')}</span>
  801. <span className="text-xs text-bambu-gray ml-1">{t('notifications.billingChargeFailedDescription')}</span>
  802. </div>
  803. <Toggle checked={onBillingChargeFailed} onChange={setOnBillingChargeFailed} />
  804. </div>
  805. <div className="flex items-center justify-between col-span-2">
  806. <div>
  807. <span className="text-sm text-white">{t('notifications.plateClearRequired')}</span>
  808. <span className="text-xs text-bambu-gray ml-1">{t('notifications.plateClearRequiredDescription')}</span>
  809. </div>
  810. <Toggle checked={onPlateClearRequired} onChange={setOnPlateClearRequired} />
  811. </div>
  812. <div className="flex items-center justify-between col-span-2">
  813. <div>
  814. <span className="text-sm text-white">{t('notifications.printConfirmRequest')}</span>
  815. <span className="text-xs text-bambu-gray ml-1">{t('notifications.printConfirmRequestDescription')}</span>
  816. </div>
  817. <Toggle checked={onPrintConfirmRequest} onChange={setOnPrintConfirmRequest} />
  818. </div>
  819. <div className="flex items-center justify-between col-span-2">
  820. <div>
  821. <span className="text-sm text-white">{t('notifications.bedCooled')}</span>
  822. <span className="text-xs text-bambu-gray ml-1">{t('notifications.bedCooledAfterPrint')}</span>
  823. </div>
  824. <Toggle checked={onBedCooled} onChange={setOnBedCooled} />
  825. </div>
  826. <div className="flex items-center justify-between col-span-2">
  827. <div>
  828. <span className="text-sm text-white">{t('notifications.firstLayerCompleteLabel')}</span>
  829. <span className="text-xs text-bambu-gray ml-1">{t('notifications.firstLayerCompleteDescription')}</span>
  830. </div>
  831. <Toggle checked={onFirstLayerComplete} onChange={setOnFirstLayerComplete} />
  832. </div>
  833. </div>
  834. </div>
  835. {/* Printer Status Events */}
  836. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  837. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.printerStatus')}</p>
  838. <div className="grid grid-cols-2 gap-2">
  839. <div className="flex items-center justify-between">
  840. <span className="text-sm text-white">{t('notifications.offline')}</span>
  841. <Toggle checked={onPrinterOffline} onChange={setOnPrinterOffline} />
  842. </div>
  843. <div className="flex items-center justify-between col-span-2">
  844. <div>
  845. <span className="text-sm text-white">{t('notifications.haSensorAlert')}</span>
  846. <span className="text-xs text-bambu-gray ml-1">{t('notifications.haSensorAlertDescription')}</span>
  847. </div>
  848. <Toggle checked={onHaSensorAlert} onChange={setOnHaSensorAlert} />
  849. </div>
  850. <div className="flex items-center justify-between col-span-2">
  851. <div>
  852. <span className="text-sm text-white">{t('notifications.locationHaSensorAlert')}</span>
  853. <span className="text-xs text-bambu-gray ml-1">{t('notifications.locationHaSensorAlertDescription')}</span>
  854. </div>
  855. <Toggle checked={onLocationHaSensorAlert} onChange={setOnLocationHaSensorAlert} />
  856. </div>
  857. <div className="flex items-center justify-between">
  858. <span className="text-sm text-white">{t('notifications.error')}</span>
  859. <Toggle checked={onPrinterError} onChange={setOnPrinterError} />
  860. </div>
  861. <div className="flex items-center justify-between">
  862. <span className="text-sm text-white">{t('notifications.aiFailureDetection')}</span>
  863. <Toggle checked={onAiFailureDetection} onChange={setOnAiFailureDetection} />
  864. </div>
  865. <div className="flex items-center justify-between">
  866. <span className="text-sm text-white">{t('notifications.lowFilament')}</span>
  867. <Toggle checked={onFilamentLow} onChange={setOnFilamentLow} />
  868. </div>
  869. <div className="flex items-center justify-between">
  870. <span className="text-sm text-white">{t('notifications.maintenance')}</span>
  871. <Toggle checked={onMaintenanceDue} onChange={setOnMaintenanceDue} />
  872. </div>
  873. </div>
  874. </div>
  875. {/* Inventory Stock Alerts */}
  876. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  877. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.inventoryAlerts')}</p>
  878. <div className="grid grid-cols-1 gap-2">
  879. <div className="flex items-center justify-between">
  880. <div>
  881. <span className="text-sm text-white">{t('notifications.stockReorderAlert')}</span>
  882. <span className="text-xs text-bambu-gray ml-1">{t('notifications.stockReorderAlertDescription')}</span>
  883. </div>
  884. <Toggle checked={onStockReorderAlert} onChange={setOnStockReorderAlert} />
  885. </div>
  886. <div className="flex items-center justify-between">
  887. <div>
  888. <span className="text-sm text-white">{t('notifications.stockBreakAlert')}</span>
  889. <span className="text-xs text-bambu-gray ml-1">{t('notifications.stockBreakAlertDescription')}</span>
  890. </div>
  891. <Toggle checked={onStockBreakAlert} onChange={setOnStockBreakAlert} />
  892. </div>
  893. </div>
  894. </div>
  895. {/* Messages other applications send (POST /notifications/app-message) */}
  896. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  897. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-2">{t('notifications.connectedApps')}</p>
  898. <div className="flex items-center justify-between">
  899. <div>
  900. <span className="text-sm text-white">{t('notifications.appMessages')}</span>
  901. <span className="text-xs text-bambu-gray ml-1">{t('notifications.appMessagesDescription')}</span>
  902. </div>
  903. <Toggle checked={onAppMessage} onChange={setOnAppMessage} />
  904. </div>
  905. </div>
  906. {/* Per-event priority: ntfy (#990), Gotify (#2743) */}
  907. {(providerType === 'ntfy' || providerType === 'gotify') && (() => {
  908. const enabledEvents: Array<{ key: string; label: string }> = [];
  909. if (onPrintStart) enabledEvents.push({ key: 'on_print_start', label: t('notifications.start') });
  910. if (onPrintComplete) enabledEvents.push({ key: 'on_print_complete', label: t('notifications.complete') });
  911. if (onPrintFailed) enabledEvents.push({ key: 'on_print_failed', label: t('notifications.failed') });
  912. if (onPrintStopped) enabledEvents.push({ key: 'on_print_stopped', label: t('notifications.stopped') });
  913. if (onPrintProgress) enabledEvents.push({ key: 'on_print_progress', label: t('notifications.progress') });
  914. if (onBillingChargeFailed) enabledEvents.push({ key: 'on_billing_charge_failed', label: t('notifications.billingChargeFailedLabel') });
  915. if (onPlateClearRequired) enabledEvents.push({ key: 'on_plate_clear_required', label: t('notifications.plateClearRequired') });
  916. if (onPrintConfirmRequest) enabledEvents.push({ key: 'on_print_confirm_request', label: t('notifications.printConfirmRequest') });
  917. if (onBedCooled) enabledEvents.push({ key: 'on_bed_cooled', label: t('notifications.bedCooled') });
  918. if (onFirstLayerComplete) enabledEvents.push({ key: 'on_first_layer_complete', label: t('notifications.firstLayerCompleteLabel') });
  919. if (onPrinterOffline) enabledEvents.push({ key: 'on_printer_offline', label: t('notifications.offline') });
  920. if (onPrinterError) enabledEvents.push({ key: 'on_printer_error', label: t('notifications.error') });
  921. if (onHaSensorAlert) enabledEvents.push({ key: 'on_ha_sensor_alert', label: t('notifications.haSensorAlert') });
  922. if (onLocationHaSensorAlert) enabledEvents.push({ key: 'on_location_ha_sensor_alert', label: t('notifications.locationHaSensorAlert') });
  923. if (onAiFailureDetection) enabledEvents.push({ key: 'on_ai_failure_detection', label: t('notifications.aiFailureDetection') });
  924. if (onFilamentLow) enabledEvents.push({ key: 'on_filament_low', label: t('notifications.lowFilament') });
  925. if (onMaintenanceDue) enabledEvents.push({ key: 'on_maintenance_due', label: t('notifications.maintenance') });
  926. if (onStockReorderAlert) enabledEvents.push({ key: 'on_stock_reorder_alert', label: t('notifications.stockReorderAlert') });
  927. if (onStockBreakAlert) enabledEvents.push({ key: 'on_stock_break_alert', label: t('notifications.stockBreakAlert') });
  928. if (enabledEvents.length === 0) return null;
  929. return (
  930. <div className="space-y-2 p-3 bg-bambu-dark rounded-lg">
  931. <p className="text-xs text-bambu-gray uppercase tracking-wide mb-1">
  932. {providerType === 'gotify'
  933. ? t('notifications.eventPriority.sectionTitleGotify')
  934. : t('notifications.eventPriority.sectionTitle')}
  935. </p>
  936. <p className="text-xs text-bambu-gray mb-2">
  937. {providerType === 'gotify'
  938. ? t('notifications.eventPriority.helpGotify')
  939. : t('notifications.eventPriority.helpNtfy')}
  940. </p>
  941. <div className="space-y-2">
  942. {enabledEvents.map((ev) => (
  943. <div key={ev.key} className="flex items-center justify-between gap-3">
  944. <span className="text-sm text-white">{ev.label}</span>
  945. <select
  946. value={eventPriorities[ev.key] ?? 3}
  947. onChange={(e) => {
  948. const next = Number(e.target.value);
  949. setEventPriorities((prev) => ({ ...prev, [ev.key]: next }));
  950. }}
  951. 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"
  952. >
  953. <option value={1}>{t('notifications.eventPriority.min')}</option>
  954. <option value={2}>{t('notifications.eventPriority.low')}</option>
  955. <option value={3}>{t('notifications.eventPriority.default')}</option>
  956. <option value={4}>{t('notifications.eventPriority.high')}</option>
  957. <option value={5}>{t('notifications.eventPriority.urgent')}</option>
  958. </select>
  959. </div>
  960. ))}
  961. </div>
  962. </div>
  963. );
  964. })()}
  965. </div>
  966. {/* Actions */}
  967. <div className="flex gap-3 pt-2">
  968. <Button
  969. type="button"
  970. variant="secondary"
  971. onClick={onClose}
  972. className="flex-1"
  973. >
  974. {t('notifications.cancel')}
  975. </Button>
  976. <Button
  977. type="submit"
  978. disabled={isPending}
  979. className="flex-1"
  980. >
  981. {isPending ? (
  982. <Loader2 className="w-4 h-4 animate-spin" />
  983. ) : (
  984. <Save className="w-4 h-4" />
  985. )}
  986. {isEditing ? t('notifications.save') : t('notifications.add')}
  987. </Button>
  988. </div>
  989. </form>
  990. </div>
  991. </div>
  992. );
  993. }