NotificationLogViewer.tsx 10 KB

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