NotificationLogViewer.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { useState } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { History, CheckCircle, XCircle, Loader2, Trash2, RefreshCw, ChevronDown, ChevronUp } from 'lucide-react';
  4. import { api } from '../api/client';
  5. import { parseUTCDate, formatTimeOnly, formatDateTime, type TimeFormat } from '../utils/date';
  6. import type { NotificationLogEntry } from '../api/client';
  7. import { Button } from './Button';
  8. import { useToast } from '../contexts/ToastContext';
  9. const EVENT_LABELS: Record<string, string> = {
  10. print_start: 'Print Started',
  11. print_complete: 'Print Complete',
  12. print_failed: 'Print Failed',
  13. print_stopped: 'Print Stopped',
  14. print_progress: 'Progress',
  15. printer_offline: 'Printer Offline',
  16. printer_error: 'Printer Error',
  17. filament_low: 'Low Filament',
  18. maintenance_due: 'Maintenance Due',
  19. test: 'Test',
  20. };
  21. const EVENT_COLORS: Record<string, string> = {
  22. print_start: 'text-blue-400',
  23. print_complete: 'text-bambu-green',
  24. print_failed: 'text-red-400',
  25. print_stopped: 'text-orange-400',
  26. print_progress: 'text-yellow-400',
  27. printer_offline: 'text-gray-400',
  28. printer_error: 'text-rose-400',
  29. filament_low: 'text-cyan-400',
  30. maintenance_due: 'text-purple-400',
  31. test: 'text-bambu-gray',
  32. };
  33. interface NotificationLogViewerProps {
  34. onClose: () => void;
  35. }
  36. export function NotificationLogViewer({ onClose }: NotificationLogViewerProps) {
  37. const queryClient = useQueryClient();
  38. const { showToast } = useToast();
  39. const [days, setDays] = useState(7);
  40. const [expandedId, setExpandedId] = useState<number | null>(null);
  41. const [showFailedOnly, setShowFailedOnly] = useState(false);
  42. const { data: settings } = useQuery({
  43. queryKey: ['settings'],
  44. queryFn: api.getSettings,
  45. });
  46. const timeFormat: TimeFormat = settings?.time_format || 'system';
  47. const { data: logs, isLoading, refetch, isRefetching } = useQuery({
  48. queryKey: ['notification-logs', days, showFailedOnly],
  49. queryFn: () => api.getNotificationLogs({
  50. days,
  51. limit: 100,
  52. success: showFailedOnly ? false : undefined,
  53. }),
  54. });
  55. const { data: stats } = useQuery({
  56. queryKey: ['notification-log-stats', days],
  57. queryFn: () => api.getNotificationLogStats(days),
  58. });
  59. const clearMutation = useMutation({
  60. mutationFn: () => api.clearNotificationLogs(30),
  61. onSuccess: (data) => {
  62. showToast(data.message, 'success');
  63. queryClient.invalidateQueries({ queryKey: ['notification-logs'] });
  64. queryClient.invalidateQueries({ queryKey: ['notification-log-stats'] });
  65. },
  66. onError: (error: Error) => {
  67. showToast(`Failed to clear logs: ${error.message}`, 'error');
  68. },
  69. });
  70. const formatDate = (dateStr: string) => {
  71. const date = parseUTCDate(dateStr);
  72. if (!date) return '';
  73. const now = new Date();
  74. const diff = now.getTime() - date.getTime();
  75. if (diff < 60000) return 'Just now';
  76. if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
  77. if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
  78. return date.toLocaleDateString() + ' ' + formatTimeOnly(date, timeFormat);
  79. };
  80. return (
  81. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
  82. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col">
  83. {/* Header */}
  84. <div className="p-4 border-b border-bambu-dark-tertiary flex items-center justify-between">
  85. <div className="flex items-center gap-3">
  86. <History className="w-5 h-5 text-bambu-green" />
  87. <h2 className="text-lg font-semibold text-white">Notification Log</h2>
  88. </div>
  89. <button
  90. onClick={onClose}
  91. className="text-bambu-gray hover:text-white transition-colors"
  92. >
  93. &times;
  94. </button>
  95. </div>
  96. {/* Stats Bar */}
  97. {stats && (
  98. <div className="px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50">
  99. <div className="flex items-center gap-6 text-sm">
  100. <span className="text-bambu-gray">
  101. Last {days} days: <span className="text-white font-medium">{stats.total}</span> notifications
  102. </span>
  103. <span className="flex items-center gap-1 text-bambu-green">
  104. <CheckCircle className="w-4 h-4" />
  105. {stats.success_count} sent
  106. </span>
  107. {stats.failure_count > 0 && (
  108. <span className="flex items-center gap-1 text-red-400">
  109. <XCircle className="w-4 h-4" />
  110. {stats.failure_count} failed
  111. </span>
  112. )}
  113. </div>
  114. </div>
  115. )}
  116. {/* Filters */}
  117. <div className="px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4">
  118. <select
  119. value={days}
  120. onChange={(e) => setDays(Number(e.target.value))}
  121. className="px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green"
  122. >
  123. <option value={1}>Last 24 hours</option>
  124. <option value={7}>Last 7 days</option>
  125. <option value={30}>Last 30 days</option>
  126. <option value={90}>Last 90 days</option>
  127. </select>
  128. <label className="flex items-center gap-2 text-sm text-bambu-gray cursor-pointer">
  129. <input
  130. type="checkbox"
  131. checked={showFailedOnly}
  132. onChange={(e) => setShowFailedOnly(e.target.checked)}
  133. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  134. />
  135. Show failed only
  136. </label>
  137. <div className="flex-1" />
  138. <Button
  139. size="sm"
  140. variant="secondary"
  141. onClick={() => refetch()}
  142. disabled={isRefetching}
  143. >
  144. {isRefetching ? (
  145. <Loader2 className="w-4 h-4 animate-spin" />
  146. ) : (
  147. <RefreshCw className="w-4 h-4" />
  148. )}
  149. Refresh
  150. </Button>
  151. <Button
  152. size="sm"
  153. variant="secondary"
  154. onClick={() => clearMutation.mutate()}
  155. disabled={clearMutation.isPending}
  156. className="text-red-400 hover:text-red-300"
  157. >
  158. {clearMutation.isPending ? (
  159. <Loader2 className="w-4 h-4 animate-spin" />
  160. ) : (
  161. <Trash2 className="w-4 h-4" />
  162. )}
  163. Clear Old
  164. </Button>
  165. </div>
  166. {/* Log List */}
  167. <div className="flex-1 overflow-y-auto p-4">
  168. {isLoading ? (
  169. <div className="flex justify-center py-12">
  170. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  171. </div>
  172. ) : logs && logs.length > 0 ? (
  173. <div className="space-y-2">
  174. {logs.map((log) => (
  175. <LogEntry
  176. key={log.id}
  177. log={log}
  178. isExpanded={expandedId === log.id}
  179. onToggle={() => setExpandedId(expandedId === log.id ? null : log.id)}
  180. formatDate={formatDate}
  181. formatFullDate={(dateStr) => formatDateTime(dateStr, timeFormat)}
  182. />
  183. ))}
  184. </div>
  185. ) : (
  186. <div className="text-center py-12 text-bambu-gray">
  187. <History className="w-12 h-12 mx-auto mb-3 opacity-30" />
  188. <p className="text-sm">
  189. {showFailedOnly ? 'No failed notifications' : 'No notifications logged'}
  190. </p>
  191. </div>
  192. )}
  193. </div>
  194. </div>
  195. </div>
  196. );
  197. }
  198. function LogEntry({
  199. log,
  200. isExpanded,
  201. onToggle,
  202. formatDate,
  203. formatFullDate,
  204. }: {
  205. log: NotificationLogEntry;
  206. isExpanded: boolean;
  207. onToggle: () => void;
  208. formatDate: (date: string) => string;
  209. formatFullDate: (date: string) => string;
  210. }) {
  211. return (
  212. <div
  213. className={`border rounded-lg overflow-hidden transition-colors ${
  214. log.success
  215. ? 'border-bambu-dark-tertiary bg-bambu-dark/30'
  216. : 'border-red-500/30 bg-red-500/5'
  217. }`}
  218. >
  219. <button
  220. className="w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors"
  221. onClick={onToggle}
  222. >
  223. {log.success ? (
  224. <CheckCircle className="w-4 h-4 text-bambu-green shrink-0" />
  225. ) : (
  226. <XCircle className="w-4 h-4 text-red-400 shrink-0" />
  227. )}
  228. <span className={`text-xs font-medium ${EVENT_COLORS[log.event_type] || 'text-bambu-gray'}`}>
  229. {EVENT_LABELS[log.event_type] || log.event_type}
  230. </span>
  231. <span className="text-sm text-white truncate flex-1">
  232. {log.provider_name || 'Unknown Provider'}
  233. </span>
  234. {log.printer_name && (
  235. <span className="text-xs text-bambu-gray">
  236. {log.printer_name}
  237. </span>
  238. )}
  239. <span className="text-xs text-bambu-gray shrink-0">
  240. {formatDate(log.created_at)}
  241. </span>
  242. {isExpanded ? (
  243. <ChevronUp className="w-4 h-4 text-bambu-gray shrink-0" />
  244. ) : (
  245. <ChevronDown className="w-4 h-4 text-bambu-gray shrink-0" />
  246. )}
  247. </button>
  248. {isExpanded && (
  249. <div className="px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2">
  250. <div>
  251. <p className="text-xs text-bambu-gray mb-1">Title</p>
  252. <p className="text-sm text-white">{log.title}</p>
  253. </div>
  254. <div>
  255. <p className="text-xs text-bambu-gray mb-1">Message</p>
  256. <p className="text-sm text-white whitespace-pre-wrap">{log.message}</p>
  257. </div>
  258. {!log.success && log.error_message && (
  259. <div>
  260. <p className="text-xs text-red-400 mb-1">Error</p>
  261. <p className="text-sm text-red-300">{log.error_message}</p>
  262. </div>
  263. )}
  264. <div className="flex gap-4 text-xs text-bambu-gray pt-1">
  265. <span>Provider: {log.provider_type}</span>
  266. <span>Time: {formatFullDate(log.created_at)}</span>
  267. </div>
  268. </div>
  269. )}
  270. </div>
  271. );
  272. }