Files
co-lite/solvway-admin-portal/app/components/forms/SubmissionsView.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

238 lines
9.7 KiB
TypeScript

"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<CmsFormView | null>(null);
const [rows, setRows] = useState<CmsFormSubmission[]>([]);
const [total, setTotal] = useState(0);
const page = pageNo - 1;
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [viewing, setViewing] = useState<CmsFormSubmission | null>(null);
const [deleting, setDeleting] = useState<CmsFormSubmission | null>(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<string, unknown> = { 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 (
<div className="space-y-4">
<PageHeader
title={form ? t("FrmSubmissionsOfForm", { name: form.name }) : t("FrmFormSubmissions")}
actions={
<>
<Button variant="outline" asChild>
<Link href={`/forms/${formId}`}>{t("FrmEditForm")}</Link>
</Button>
<Button type="button" disabled={exporting || total === 0} onClick={() => void exportAll()}>
<Download aria-hidden="true" className="size-4" />
{t("Export")}
</Button>
</>
}
/>
{total > EXPORT_LIMIT ? (
<p className="text-xs text-muted-foreground">{t("FrmExportLimitNote", { count: EXPORT_LIMIT })}</p>
) : null}
{actionError && <p role="alert" className="text-sm text-destructive">{t(actionError)}</p>}
{error && <ErrorState message={t(error)} onRetry={refetch} />}
{error ? null : loading ? (
<div ref={tableRef}><TableSkeleton columns={4} /></div>
) : rows.length === 0 ? (
<EmptyState title={t("FrmNoSubmissions")} />
) : (
<>
<div ref={tableRef} className="space-y-3">
<div className="overflow-hidden rounded-table border bg-card">
<Table aria-label={t("FrmSubmissions")}>
<TableHeader>
<TableRow>
<SortableHead label={t("Date")} sortKey="date" sorting={sorting} onSortingChange={onSortingChange} className="tabular" />
<SortableHead label={t("FrmPage")} sortKey="page" sorting={sorting} onSortingChange={onSortingChange} />
<TableHead>{t("FrmSummary")}</TableHead>
<TableHead className="text-right">{t("CatActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((s) => (
<TableRow key={s.id}>
<TableCell className="tabular">{formatDateTime(s.createdAt)}</TableCell>
<TableCell className="text-xs text-muted-foreground">{s.pageSlug ?? "—"}</TableCell>
<TableCell className="max-w-md truncate">{summary(s)}</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => setViewing(s)}>
{t("FrmView")}
</Button>
<Button type="button" variant="destructive-outline" size="sm" onClick={() => setDeleting(s)}>
{t("Delete")}
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<TablePager page={pageNo} pageSize={pageSize ?? MIN_PAGE_SIZE} total={total} onPageChange={setPageNo} isLoading={loading} />
</div>
</>
)}
<Dialog open={viewing != null} onOpenChange={(open) => !open && setViewing(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>{viewing ? t("FrmSubmissionOf", { date: formatDateTime(viewing.createdAt) }) : t("FrmSubmission")}</DialogTitle>
</DialogHeader>
{viewing ? (
<dl className="space-y-3 text-sm">
{viewing.answers.map((a) => (
<div key={a.key}>
<dt className="font-medium">{a.label}</dt>
<dd className="whitespace-pre-wrap break-words text-muted-foreground">{a.value || "—"}</dd>
</div>
))}
<div>
<dt className="font-medium">{t("FrmPage")}</dt>
<dd className="text-muted-foreground">{viewing.pageSlug ?? "—"}</dd>
</div>
</dl>
) : null}
</DialogContent>
</Dialog>
<ConfirmDialog
open={deleting != null}
onOpenChange={(open) => !open && setDeleting(null)}
title={t("FrmSubDeleteConfirmTitle")}
description={t("FrmSubDeleteConfirmDesc")}
confirmLabel={t("Delete")}
onConfirm={() => {
if (deleting) void remove(deleting);
setDeleting(null);
}}
/>
</div>
);
}