import { useCallback, useEffect, useRef, useState } from "react"; import { Download, MoreHorizontal } from "lucide-react"; import { useReportQuery, ReportReadError } from "@/hooks/use-report-query"; import { DataEmptyState, DataPagination, ReportError, ReportSection, ReportSkeleton, ReportToolbar, } from "@/components/ui/reporting"; import { SettingsSection } from "@/components/ui/settings-section"; import { NumberStepper } from "@/components/ui/number-stepper"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import type { LoggingSettings } from "../../types"; interface ConsentLog { id: number; timestamp: string; ipHash: string; consentGiven: boolean; categories: string[]; policyVersion: string; } interface LogsReport { logs: ConsentLog[]; total: number; totalPages: number; } interface ConsentLogsTabProps { loggingSettings: LoggingSettings; updateLoggingSettings: ( key: K, value: LoggingSettings[K], ) => void; } const root = () => window.swiftCommerceData?.apiUrl || "/wp-json/swift-commerce/v1"; const headers = () => ({ "X-WP-Nonce": window.swiftCommerceData?.restNonce || "", }); const formatDate = (timestamp: string) => { const date = new Date(timestamp.replace(" ", "T")); return Number.isNaN(date.getTime()) ? "Unavailable" : date.toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit", }); }; export function ConsentLogsTab({ loggingSettings, updateLoggingSettings, }: ConsentLogsTabProps) { const [page, setPage] = useState(1); const [clearOpen, setClearOpen] = useState(false); const [busy, setBusy] = useState<"export" | "cleanup" | null>(null); const [actionError, setActionError] = useState(""); const [notice, setNotice] = useState(""); const activeAction = useRef(null); const perPage = 10; useEffect( () => () => { activeAction.current?.abort(); activeAction.current = null; }, [], ); const read = useCallback( async (signal: AbortSignal) => { const response = await fetch( root() + "/cookie-consent/logs?page=" + page + "&per_page=" + perPage, { signal, credentials: "same-origin", headers: headers() }, ); if (!response.ok) throw new ReportReadError( response.status === 401 || response.status === 403 ? "Access could not be verified. Reload the dashboard and try again." : "Consent records could not be loaded. Please try again.", ); const data = (await response.json()) as LogsReport; if ( !Array.isArray(data.logs) || !Number.isInteger(data.total) || data.total < 0 || !Number.isInteger(data.totalPages) || data.totalPages < 1 || !data.logs.every( (log) => typeof log.id === "number" && typeof log.timestamp === "string" && typeof log.ipHash === "string" && typeof log.consentGiven === "boolean" && Array.isArray(log.categories) && log.categories.every((category) => typeof category === "string") && typeof log.policyVersion === "string", ) ) throw new ReportReadError( "The consent log returned incomplete data. Please try again.", ); return data; }, [page], ); const report = useReportQuery("consent-logs-" + page, read); useEffect(() => { if (report.data && page > report.data.totalPages) setPage(report.data.totalPages); }, [report.data, page]); const canAct = !!report.data && report.data.total > 0 && !report.loading && !report.error && !busy; const runAction = async (kind: "export" | "cleanup") => { if (!canAct || activeAction.current) return false; const controller = new AbortController(); activeAction.current = controller; setBusy(kind); setActionError(""); setNotice(""); const timeout = setTimeout(() => controller.abort(), 30000); try { if (kind === "export") { const response = await fetch(root() + "/cookie-consent/logs/export", { signal: controller.signal, credentials: "same-origin", headers: headers(), }); if (!response.ok) throw new Error(); const body = await response.text(); // WordPress may JSON-encode a string REST response despite its CSV header. let csv = body; if (body.startsWith('"')) { try { const decoded: unknown = JSON.parse(body); if (typeof decoded === "string") csv = decoded; } catch { /* A normal CSV may also start with a quoted header. */ } } if (activeAction.current !== controller || controller.signal.aborted) return false; const url = URL.createObjectURL( new Blob([csv], { type: "text/csv;charset=utf-8;" }), ); const link = document.createElement("a"); link.href = url; link.download = "consent-logs-" + new Date().toISOString().slice(0, 10) + ".csv"; document.body.appendChild(link); link.click(); link.remove(); URL.revokeObjectURL(url); setNotice("CSV exported with up to the latest 5,000 consent records."); } else { let hasMore = true, batches = 0, deleted = 0; while (hasMore && batches < 20) { const response = await fetch(root() + "/cookie-consent/logs/clear", { method: "DELETE", signal: controller.signal, credentials: "same-origin", headers: headers(), }); if (!response.ok) throw new Error(); const result = await response.json(); if ( result.success !== true || typeof result.deleted !== "number" || typeof result.hasMore !== "boolean" ) throw new Error(); deleted += result.deleted; hasMore = result.hasMore; batches++; } if (activeAction.current !== controller || controller.signal.aborted) return false; setNotice( deleted.toLocaleString() + " expired records deleted." + (hasMore ? " More expired records remain. Run cleanup again to continue." : ""), ); setClearOpen(false); } return true; } catch { if (activeAction.current === controller) setActionError( controller.signal.aborted ? kind === "cleanup" ? "Cleanup timed out. Some expired records may already have been removed. Refresh and review the records before trying again." : "The CSV export timed out. Please try again." : kind === "cleanup" ? "Cleanup could not be completed. Some expired records may already have been removed. Refresh and review the records before trying again." : "The CSV could not be exported. Please try again.", ); return false; } finally { clearTimeout(timeout); if (activeAction.current === controller) { activeAction.current = null; setBusy(null); if (kind === "cleanup") { if (page === 1) void report.refresh(); else setPage(1); } } } }; return (
{ setActionError(""); setClearOpen(true); }} > Delete expired records {!loggingSettings.enabled && (

Logging is off in these settings. Existing consent records remain available.

)} {report.error && ( )} {actionError && !clearOpen && (

{actionError}

)} {notice && (

{notice}

)} {busy && (

{busy === "export" ? "Preparing the latest records for export..." : "Deleting records older than the saved retention period..."}

)} {!report.data && report.loading && ( )} {report.data && ( {report.data.logs.length ? ( Recorded Choice Accepted categories Client hash Policy version {report.data.logs.map((log) => ( {formatDate(log.timestamp)} {log.consentGiven ? "Consented" : "Declined"} {log.categories.length ? log.categories.join(", ") : "None recorded"} {log.ipHash ? log.ipHash.slice(0, 12) + (log.ipHash.length > 12 ? "..." : "") : "Not recorded"} {log.policyVersion} ))}
) : ( {loggingSettings.enabled ? "Records appear after visitors save their cookie preferences while logging is enabled." : "Enable consent logging below and save your settings to start recording preferences."} )}
)}
updateLoggingSettings("enabled", checked) } />
{loggingSettings.enabled && (
updateLoggingSettings("retention", value)} />

Retention and collection changes take effect after saving. Manual cleanup uses the saved retention period.

)}
{ if (!busy) setClearOpen(open); }} > Delete expired consent records? Only records older than the saved retention period will be deleted. Unsaved retention changes do not apply. This permanently removes those records and cannot be undone. {actionError && (

{actionError}

)} Cancel { event.preventDefault(); void runAction("cleanup"); }} > {busy === "cleanup" ? "Deleting..." : "Delete expired records"}
); }