"use client"; import { useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { Download } from "lucide-react"; import { Button } from "@/app/components/ui/button"; import { ConfirmDialog } from "@/app/components/ui/confirm-dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; import { PageHeader } from "@/app/components/ui/page-header"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table"; import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states"; import { SortableHead } from "@/app/components/ui/sortable-head"; import { TablePager } from "@/app/components/ui/table-pager"; import type { CmsFormSubmission, CmsFormView } from "@/app/lib/cmsForms"; import { useTableSort } from "@/app/lib/hooks/useTableSort"; import { deleteSubmission, getForm, listSubmissions } from "@/app/lib/services/adminForms"; import { formatDateTime } from "@/app/lib/format"; import { downloadXlsx, toXlsx } from "@/app/lib/xlsx"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; import { useListFilters } from "@/app/lib/hooks/useListFilters"; import { useT } from "@/app/lib/i18n/MessagesProvider"; // One form's submissions (add-cms-forms): newest first, paged to fit the screen. Answers are customer PII and are // rendered as React text only, never as markup. const EXPORT_LIMIT = 5000; // Only the page lives in the URL here; useListFilters needs a module-level defaults object. const NO_FILTERS = {}; function summary(s: CmsFormSubmission): string { return s.answers .slice(0, 2) .map((a) => `${a.label}: ${a.value}`) .join(" ยท "); } export function SubmissionsView({ formId }: { formId: number }) { const t = useT(); const { tableRef, pageSize } = useFitPageSize(); const { page: pageNo, setPage: setPageNo } = useListFilters(NO_FILTERS); const { sorting, onSortingChange, sortBy, sortDir } = useTableSort(); const [form, setForm] = useState(null); const [rows, setRows] = useState([]); const [total, setTotal] = useState(0); const page = pageNo - 1; const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [actionError, setActionError] = useState(null); const [viewing, setViewing] = useState(null); const [deleting, setDeleting] = useState(null); const [exporting, setExporting] = useState(false); const [reloadKey, setReloadKey] = useState(0); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); useEffect(() => { let cancelled = false; getForm(formId) .then((f) => { if (!cancelled) setForm(f); }) .catch(() => {}); // the list still loads; the heading falls back to "Form submissions" return () => { cancelled = true; }; }, [formId]); useEffect(() => { if (pageSize == null) return; let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the fetch below. setLoading(true); setError(null); listSubmissions(formId, page, pageSize, ...(sortBy ? [{ sortBy, sortDir }] : [])) .then((result) => { if (cancelled) return; // Past the end (the last row of the last page was just deleted): step back to the real last page. if (result.content.length === 0 && page > 0) { setPageNo(Math.max(1, Math.ceil(result.totalElements / pageSize))); return; } setRows(result.content); setTotal(result.totalElements); }) .catch((err: unknown) => { if (!cancelled) setError(err instanceof Error ? err.message : "FrmSubLoadFailed"); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [formId, page, pageSize, reloadKey, sortBy, sortDir]); async function remove(target: CmsFormSubmission) { setActionError(null); try { await deleteSubmission(target.id); refetch(); } catch (err) { setActionError(err instanceof Error ? err.message : "FrmSubDeleteFailed"); } } async function exportAll() { setActionError(null); setExporting(true); try { const all = await listSubmissions(formId, 0, EXPORT_LIMIT); // The form's current fields first, then any answered field since removed, under its stored label. const labels = (form?.fields ?? []).map((f) => ({ key: f.key, label: f.label })); for (const s of all.content) { for (const a of s.answers) { if (!labels.some((l) => l.key === a.key)) labels.push({ key: a.key, label: a.label }); } } const columns = [ { key: "date", title: t("Date") }, { key: "page", title: t("FrmPage") }, ...labels.map((l) => ({ key: `f_${l.key}`, title: l.label })), ]; const data = all.content.map((s) => { const row: Record = { date: formatDateTime(s.createdAt), page: s.pageSlug ?? "" }; for (const a of s.answers) row[`f_${a.key}`] = a.value; return row; }); downloadXlsx(`form-${formId}-submissions.xlsx`, await toXlsx(data, columns, t("FrmSubmissions"))); } catch (err) { setActionError(err instanceof Error ? err.message : "FrmSubExportFailed"); } finally { setExporting(false); } } return (
} /> {total > EXPORT_LIMIT ? (

{t("FrmExportLimitNote", { count: EXPORT_LIMIT })}

) : null} {actionError &&

{t(actionError)}

} {error && } {error ? null : loading ? (
) : rows.length === 0 ? ( ) : ( <>
{t("FrmSummary")} {t("CatActions")} {rows.map((s) => ( {formatDateTime(s.createdAt)} {s.pageSlug ?? "โ€”"} {summary(s)}
))}
)} !open && setViewing(null)}> {viewing ? t("FrmSubmissionOf", { date: formatDateTime(viewing.createdAt) }) : t("FrmSubmission")} {viewing ? (
{viewing.answers.map((a) => (
{a.label}
{a.value || "โ€”"}
))}
{t("FrmPage")}
{viewing.pageSlug ?? "โ€”"}
) : null}
!open && setDeleting(null)} title={t("FrmSubDeleteConfirmTitle")} description={t("FrmSubDeleteConfirmDesc")} confirmLabel={t("Delete")} onConfirm={() => { if (deleting) void remove(deleting); setDeleting(null); }} />
); }