NotificationLogViewer.tsx 11 KB

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