AddNotificationModal.tsx 54 KB

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