NotificationLogViewer.tsx 9.8 KB

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