472 lines
17 KiB
TypeScript
472 lines
17 KiB
TypeScript
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<ActivityLogPanelProps> = ({ tableName, refreshTrigger }) => {
|
|
const [isExpanded, setIsExpanded] = useState(false);
|
|
const [logs, setLogs] = useState<AuditLogEntry[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [totalCount, setTotalCount] = useState(0);
|
|
const [page, setPage] = useState(0);
|
|
const [expandedLogIds, setExpandedLogIds] = useState<Set<number>>(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 (
|
|
<div key={field} className="flex items-baseline gap-2 text-sm">
|
|
<span className="font-medium text-gray-700 min-w-[120px]">{fieldLabel}:</span>
|
|
<span className="text-red-600">{oldFormatted}</span>
|
|
<span className="text-gray-400">→</span>
|
|
<span className="text-green-600">{newFormatted}</span>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const renderLogEntry = (log: AuditLogEntry) => {
|
|
const isLogExpanded = expandedLogIds.has(log.id);
|
|
|
|
return (
|
|
<div
|
|
key={log.id}
|
|
className="border-b border-gray-100 last:border-b-0 hover:bg-gray-50 transition-colors"
|
|
>
|
|
{/* One-line summary */}
|
|
<button
|
|
onClick={() => toggleLogExpansion(log.id)}
|
|
className="w-full px-4 py-2 flex items-center gap-3 text-left"
|
|
>
|
|
<i
|
|
className={`fa-solid fa-chevron-${isLogExpanded ? 'down' : 'right'} text-xs text-gray-400`}
|
|
/>
|
|
<span className="text-xs text-gray-500 min-w-[80px]">
|
|
{formatTimeShort(log.created_at)}
|
|
</span>
|
|
<span className="text-sm text-gray-700 flex-1">{getOneLinerSummary(log)}</span>
|
|
<span className="text-xs text-gray-400">{getRecordInfo(log)}</span>
|
|
</button>
|
|
|
|
{/* Expanded details */}
|
|
{isLogExpanded && (
|
|
<div className="px-4 pb-3 pl-14 space-y-2 bg-blue-50">
|
|
{/* Full timestamp */}
|
|
<div className="text-xs text-gray-600">
|
|
<i className="fa-solid fa-clock mr-1" />
|
|
{formatTimestamp(log.created_at)}
|
|
</div>
|
|
|
|
{/* Action type */}
|
|
<div className="text-xs text-gray-600">
|
|
<i className="fa-solid fa-tag mr-1" />
|
|
Action: <span className="font-medium">{log.action}</span>
|
|
</div>
|
|
|
|
{/* Changed fields */}
|
|
{log.action === 'UPDATE' && log.old_values && log.new_values && log.changed_fields && (
|
|
<div className="mt-2 space-y-1 border-t border-blue-200 pt-2">
|
|
<div className="text-xs font-semibold text-gray-700 mb-1">Changes:</div>
|
|
{log.changed_fields.map((field) => {
|
|
const oldVal = log.old_values?.[field];
|
|
const newVal = log.new_values?.[field];
|
|
return renderFieldChange(field, oldVal, newVal);
|
|
})}
|
|
</div>
|
|
)}
|
|
|
|
{/* For CREATE, show all new values */}
|
|
{log.action === 'CREATE' && log.new_values && (
|
|
<div className="mt-2 space-y-1 border-t border-blue-200 pt-2">
|
|
<div className="text-xs font-semibold text-gray-700 mb-1">Created with:</div>
|
|
{Object.entries(log.new_values)
|
|
.filter(([key]) => !['id', 'created_at', 'updated_at', 'is_edited'].includes(key))
|
|
.map(([key, value]) => renderFieldChange(key, undefined, value))}
|
|
</div>
|
|
)}
|
|
|
|
{/* For DELETE, show what was deleted */}
|
|
{log.action === 'DELETE' && log.old_values && (
|
|
<div className="mt-2 space-y-1 border-t border-blue-200 pt-2">
|
|
<div className="text-xs font-semibold text-gray-700 mb-1">Deleted record:</div>
|
|
{Object.entries(log.old_values)
|
|
.filter(([key]) => !['id', 'created_at', 'updated_at'].includes(key))
|
|
.map(([key, value]) => (
|
|
<div key={key} className="flex items-baseline gap-2 text-sm">
|
|
<span className="font-medium text-gray-700 min-w-[120px]">
|
|
{formatFieldName(key)}:
|
|
</span>
|
|
<span className="text-gray-600">{formatValue(value)}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const hasMore = logs.length < totalCount;
|
|
|
|
return (
|
|
<div className="mt-8 bg-white rounded-xl shadow-sm border border-gray-200">
|
|
{/* Header - Always visible */}
|
|
<button
|
|
onClick={() => setIsExpanded(!isExpanded)}
|
|
className="w-full flex items-center justify-between p-4 hover:bg-gray-50 transition-colors rounded-t-xl"
|
|
>
|
|
<div className="flex items-center gap-3">
|
|
<i
|
|
className={`fa-solid fa-chevron-${isExpanded ? 'down' : 'right'} text-gray-500 transition-transform`}
|
|
/>
|
|
<h3 className="text-lg font-semibold text-gray-800">Activity Log</h3>
|
|
{totalCount > 0 && (
|
|
<span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full font-medium">
|
|
{totalCount} {totalCount === 1 ? 'change' : 'changes'}
|
|
</span>
|
|
)}
|
|
</div>
|
|
<div className="text-xs text-gray-500">
|
|
{isExpanded ? 'Click to collapse' : 'Click to view recent changes'}
|
|
</div>
|
|
</button>
|
|
|
|
{/* Content - Only when expanded */}
|
|
{isExpanded && (
|
|
<div className="border-t border-gray-200">
|
|
{/* Filter tabs */}
|
|
<div className="flex items-center gap-2 px-4 py-3 border-b border-gray-200 bg-gray-50">
|
|
<span className="text-xs font-semibold text-gray-600 mr-2">Filter:</span>
|
|
<button
|
|
onClick={() => setDateFilter('all')}
|
|
className={`px-3 py-1 text-xs font-medium rounded-lg transition-colors ${
|
|
dateFilter === 'all'
|
|
? 'bg-blue-600 text-white'
|
|
: 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-300'
|
|
}`}
|
|
>
|
|
All Time
|
|
</button>
|
|
<button
|
|
onClick={() => setDateFilter('today')}
|
|
className={`px-3 py-1 text-xs font-medium rounded-lg transition-colors ${
|
|
dateFilter === 'today'
|
|
? 'bg-blue-600 text-white'
|
|
: 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-300'
|
|
}`}
|
|
>
|
|
Today
|
|
</button>
|
|
<button
|
|
onClick={() => setDateFilter('week')}
|
|
className={`px-3 py-1 text-xs font-medium rounded-lg transition-colors ${
|
|
dateFilter === 'week'
|
|
? 'bg-blue-600 text-white'
|
|
: 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-300'
|
|
}`}
|
|
>
|
|
Last 7 Days
|
|
</button>
|
|
<button
|
|
onClick={() => setDateFilter('month')}
|
|
className={`px-3 py-1 text-xs font-medium rounded-lg transition-colors ${
|
|
dateFilter === 'month'
|
|
? 'bg-blue-600 text-white'
|
|
: 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-300'
|
|
}`}
|
|
>
|
|
Last 30 Days
|
|
</button>
|
|
|
|
{/* Showing X of Y indicator */}
|
|
<div className="ml-auto text-xs text-gray-500">
|
|
Showing {logs.length} of {totalCount}
|
|
</div>
|
|
</div>
|
|
|
|
{loading && logs.length === 0 ? (
|
|
<div className="text-center py-12">
|
|
<i className="fa-solid fa-spinner fa-spin text-3xl text-gray-400 mb-2" />
|
|
<p className="text-sm text-gray-500">Loading activity log...</p>
|
|
</div>
|
|
) : logs.length === 0 ? (
|
|
<div className="text-center py-12">
|
|
<i className="fa-solid fa-clipboard-list text-4xl text-gray-300 mb-3" />
|
|
<p className="font-medium text-gray-600">No changes recorded yet</p>
|
|
<p className="text-sm text-gray-500 mt-1">
|
|
{dateFilter === 'all'
|
|
? 'Changes will appear here when data is modified'
|
|
: `No changes found in the selected time period`}
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div className="max-h-96 overflow-y-auto">
|
|
{logs.map((log) => renderLogEntry(log))}
|
|
</div>
|
|
|
|
{/* Pagination footer */}
|
|
{hasMore && (
|
|
<div className="border-t border-gray-200 px-4 py-3 flex items-center justify-between bg-gray-50">
|
|
<div className="text-xs text-gray-600">
|
|
Loaded {logs.length} of {totalCount} changes
|
|
</div>
|
|
<button
|
|
onClick={loadMore}
|
|
disabled={loading}
|
|
className="px-4 py-2 text-sm font-medium text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
|
>
|
|
{loading ? (
|
|
<>
|
|
<i className="fa-solid fa-spinner fa-spin mr-2" />
|
|
Loading...
|
|
</>
|
|
) : (
|
|
<>
|
|
Load More ({totalCount - logs.length} remaining)
|
|
<i className="fa-solid fa-chevron-down ml-2" />
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
{/* End of logs indicator */}
|
|
{!hasMore && logs.length > 0 && (
|
|
<div className="border-t border-gray-200 px-4 py-2 text-center">
|
|
<span className="text-xs text-gray-500">
|
|
<i className="fa-solid fa-check-circle mr-1 text-green-500" />
|
|
All changes loaded
|
|
</span>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default ActivityLogPanel;
|