import React, { useState, useEffect } from 'react'; import { apiClient } from '../../services/apiService.ts'; import { AuditLogEntry } from '../../types/audit.ts'; /** * Activity Log Panel Component * * Displays audit trail of data changes in a collapsible panel. * * Timezone Handling: * - Database stores timestamps in UTC (TIMESTAMP WITH TIME ZONE) * - All timestamps are converted to WIB (UTC+7) for display * - Date filters send UTC dates to backend but are based on WIB time */ interface ActivityLogPanelProps { tableName: string; refreshTrigger?: number; } const ActivityLogPanel: React.FC = ({ tableName, refreshTrigger }) => { const [isExpanded, setIsExpanded] = useState(false); const [logs, setLogs] = useState([]); const [loading, setLoading] = useState(false); const [totalCount, setTotalCount] = useState(0); const [page, setPage] = useState(0); const [expandedLogIds, setExpandedLogIds] = useState>(new Set()); const [dateFilter, setDateFilter] = useState<'all' | 'today' | 'week' | 'month'>('all'); const limit = 30; // Reset page when date filter changes useEffect(() => { setPage(0); setLogs([]); }, [dateFilter]); const getDateRange = () => { // Get current time in WIB (UTC+7) const nowWIB = new Date(new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' })); const todayWIB = new Date(nowWIB.getFullYear(), nowWIB.getMonth(), nowWIB.getDate()); // Convert WIB dates to UTC for database query const toUTCDateString = (date: Date) => { // Convert WIB midnight to UTC timestamp const wibDateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; const wibDate = new Date(wibDateStr + 'T00:00:00+07:00'); // Explicitly set WIB timezone return wibDate.toISOString().split('T')[0]; }; switch (dateFilter) { case 'today': return { startDate: toUTCDateString(todayWIB), endDate: new Date().toISOString().split('T')[0], // Current UTC date }; case 'week': { const weekAgo = new Date(todayWIB); weekAgo.setDate(weekAgo.getDate() - 7); return { startDate: toUTCDateString(weekAgo), endDate: new Date().toISOString().split('T')[0], }; } case 'month': { const monthAgo = new Date(todayWIB); monthAgo.setMonth(monthAgo.getMonth() - 1); return { startDate: toUTCDateString(monthAgo), endDate: new Date().toISOString().split('T')[0], }; } default: return {}; } }; const fetchLogs = async () => { try { setLoading(true); const dateRange = getDateRange(); const response = await apiClient.getAuditLogs({ table: tableName, limit, offset: page * limit, ...dateRange, }); if (response.success) { if (page === 0) { setLogs(response.data); } else { setLogs((prev) => [...prev, ...response.data]); } setTotalCount(response.pagination.total); } } catch (error) { console.error('Error fetching audit logs:', error); } finally { setLoading(false); } }; // Fetch logs when expanded or when refresh is triggered useEffect(() => { if (isExpanded) { fetchLogs(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isExpanded, refreshTrigger, page, dateFilter]); const loadMore = () => { setPage((prev) => prev + 1); }; const toggleLogExpansion = (logId: number) => { setExpandedLogIds((prev) => { const newSet = new Set(prev); if (newSet.has(logId)) { newSet.delete(logId); } else { newSet.add(logId); } return newSet; }); }; const formatTimestamp = (timestamp: string) => { // Parse UTC timestamp and convert to WIB (UTC+7) const date = new Date(timestamp); // Format in WIB timezone const formatter = new Intl.DateTimeFormat('id-ID', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: 'Asia/Jakarta', hour12: false, }); return formatter.format(date) + ' WIB'; }; const formatTimeShort = (timestamp: string) => { // Parse UTC timestamp const date = new Date(timestamp); // Get current time in WIB for comparison const now = new Date(); const nowWIB = new Date(now.toLocaleString('en-US', { timeZone: 'Asia/Jakarta' })); const dateWIB = new Date(date.toLocaleString('en-US', { timeZone: 'Asia/Jakarta' })); const diffMs = nowWIB.getTime() - dateWIB.getTime(); const diffMins = Math.floor(diffMs / 60000); const diffHours = Math.floor(diffMs / 3600000); const diffDays = Math.floor(diffMs / 86400000); if (diffMins < 1) return 'just now'; if (diffMins < 60) return `${diffMins}m ago`; if (diffHours < 24) return `${diffHours}h ago`; if (diffDays < 7) return `${diffDays}d ago`; // For older dates, show date in WIB return new Intl.DateTimeFormat('id-ID', { day: 'numeric', month: 'short', timeZone: 'Asia/Jakarta', }).format(date); }; const formatFieldName = (field: string) => { return field.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()); }; const formatValue = (value: any) => { if (value === null || value === undefined || value === '') { return '(empty)'; } if (typeof value === 'boolean') { return value ? 'Yes' : 'No'; } return String(value); }; const getOneLinerSummary = (log: AuditLogEntry) => { if (log.action === 'CREATE') { return 'New record created'; } if (log.action === 'DELETE') { return 'Record deleted'; } // For UPDATE, show the most important changed field if (log.changed_fields && log.changed_fields.length > 0) { const primaryField = log.changed_fields[0] ?? ''; const oldVal = log.old_values?.[primaryField]; const newVal = log.new_values?.[primaryField]; const fieldName = formatFieldName(primaryField); const oldFormatted = formatValue(oldVal); const newFormatted = formatValue(newVal); let summary = `${fieldName}: ${oldFormatted} → ${newFormatted}`; // If there are more fields, indicate that if (log.changed_fields.length > 1) { summary += ` (+${log.changed_fields.length - 1} more)`; } return summary; } return 'Updated'; }; const getRecordInfo = (log: AuditLogEntry) => { // Extract day from record_id (format: "cycleId-day" or "cycleId-day-kandangId") const parts = log.record_id.split('-'); const day = parts[1]; const kandangId = parts[2]; let info = `Day ${day}`; if (kandangId) { info += `, Kandang ${kandangId}`; } return info; }; const renderFieldChange = (field: string, oldValue: any, newValue: any) => { const fieldLabel = formatFieldName(field); const oldFormatted = formatValue(oldValue); const newFormatted = formatValue(newValue); return (
{fieldLabel}: {oldFormatted} → {newFormatted}
); }; const renderLogEntry = (log: AuditLogEntry) => { const isLogExpanded = expandedLogIds.has(log.id); return (
{/* One-line summary */} {/* Expanded details */} {isLogExpanded && (
{/* Full timestamp */}
{formatTimestamp(log.created_at)}
{/* Action type */}
Action: {log.action}
{/* Changed fields */} {log.action === 'UPDATE' && log.old_values && log.new_values && log.changed_fields && (
Changes:
{log.changed_fields.map((field) => { const oldVal = log.old_values?.[field]; const newVal = log.new_values?.[field]; return renderFieldChange(field, oldVal, newVal); })}
)} {/* For CREATE, show all new values */} {log.action === 'CREATE' && log.new_values && (
Created with:
{Object.entries(log.new_values) .filter(([key]) => !['id', 'created_at', 'updated_at', 'is_edited'].includes(key)) .map(([key, value]) => renderFieldChange(key, undefined, value))}
)} {/* For DELETE, show what was deleted */} {log.action === 'DELETE' && log.old_values && (
Deleted record:
{Object.entries(log.old_values) .filter(([key]) => !['id', 'created_at', 'updated_at'].includes(key)) .map(([key, value]) => (
{formatFieldName(key)}: {formatValue(value)}
))}
)}
)}
); }; const hasMore = logs.length < totalCount; return (
{/* Header - Always visible */} {/* Content - Only when expanded */} {isExpanded && (
{/* Filter tabs */}
Filter: {/* Showing X of Y indicator */}
Showing {logs.length} of {totalCount}
{loading && logs.length === 0 ? (

Loading activity log...

) : logs.length === 0 ? (

No changes recorded yet

{dateFilter === 'all' ? 'Changes will appear here when data is modified' : `No changes found in the selected time period`}

) : ( <>
{logs.map((log) => renderLogEntry(log))}
{/* Pagination footer */} {hasMore && (
Loaded {logs.length} of {totalCount} changes
)} {/* End of logs indicator */} {!hasMore && logs.length > 0 && (
All changes loaded
)} )}
)}
); }; export default ActivityLogPanel;