Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions app/api/admin/trash/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextResponse } from 'next/server';
import { forbidden, getCurrentUser, unauthorized } from '@/lib/auth';
import { syncPortListeners } from '@/lib/port-router';
import { deleteTrashItemForever, restoreTrashItem } from '@/lib/trash';

export const dynamic = 'force-dynamic';
type Ctx = { params: { id: string } };

async function admin() {
const me = await getCurrentUser();
if (!me) return unauthorized();
if (me.role !== 'ADMIN') return forbidden();
return null;
}

/** POST → restore this item (a form with its responses, or one response). */
export async function POST(_req: Request, { params }: Ctx) {
const denied = await admin();
if (denied) return denied;
try {
const result = await restoreTrashItem(params.id);
if (result.kind === 'form') await syncPortListeners();
return NextResponse.json(result);
} catch (e) {
return NextResponse.json({ error: e instanceof Error ? e.message : 'Could not restore it.' }, { status: 409 });
}
}

/** DELETE → remove this item (and its files) for good. */
export async function DELETE(_req: Request, { params }: Ctx) {
const denied = await admin();
if (denied) return denied;
const deleted = await deleteTrashItemForever(params.id);
if (!deleted) return NextResponse.json({ error: 'This item is no longer in the Trash.' }, { status: 404 });
return NextResponse.json({ deleted });
}
26 changes: 26 additions & 0 deletions app/api/admin/trash/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextResponse } from 'next/server';
import { forbidden, getCurrentUser, unauthorized } from '@/lib/auth';
import { emptyTrash, listTrash, TRASH_DAYS } from '@/lib/trash';

export const dynamic = 'force-dynamic';

async function admin() {
const me = await getCurrentUser();
if (!me) return unauthorized();
if (me.role !== 'ADMIN') return forbidden();
return null;
}

/** GET → everything in the Trash (newest first). */
export async function GET() {
const denied = await admin();
if (denied) return denied;
return NextResponse.json({ items: await listTrash(), days: TRASH_DAYS });
}

/** DELETE → empty the Trash: removes every item and its files for good. */
export async function DELETE() {
const denied = await admin();
if (denied) return denied;
return NextResponse.json({ deleted: await emptyTrash() });
}
7 changes: 4 additions & 3 deletions app/api/forms/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DOMAIN_RE, nextFreePort, portRange, SLUG_RE } from '@/lib/form-links';
import { syncPortListeners } from '@/lib/port-router';
import { isValidSchema, normalizeTags, sanitizeBranding, sanitizeLayout, toFormDTO } from '@/lib/forms';
import { formAudience, notifyFormEvent } from '@/lib/activity';
import { deleteFormFiles } from '@/lib/response-files';
import { trashForm } from '@/lib/trash';
import { sanitizeFormNotify } from '@/lib/form-alerts';
import { getSettings } from '@/lib/settings';

Expand Down Expand Up @@ -102,9 +102,10 @@ export async function DELETE(_req: Request, { params }: Ctx) {
if (!canEditForm(me, params.id)) return forbidden();
try {
const audience = await formAudience(params.id);
const form = await prisma.form.delete({ where: { id: params.id } });
// Into the Trash (Settings → Trash) for 30 days; its uploaded files stay until it leaves the Trash.
const form = await trashForm(params.id, me);
if (!form) throw new Error('not found');
await syncPortListeners();
void deleteFormFiles(form.id);
void notifyFormEvent('form.deleted', me, form, audience);
return NextResponse.json({ ok: true });
} catch {
Expand Down
13 changes: 4 additions & 9 deletions app/api/forms/[id]/submissions/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { formLanguages } from '@/lib/form-i18n';
import { notifySubmission } from '@/lib/notify';
import { sendConfirmation } from '@/lib/form-alerts';
import { notifySubmissionInApp } from '@/lib/activity';
import { deleteAnswerFiles, responseFileExists } from '@/lib/response-files';
import { responseFileExists } from '@/lib/response-files';
import { trashSubmissions } from '@/lib/trash';
import { computeScore } from '@/lib/scoring';
import { validateAnswers } from '@/lib/validation';
import { duplicateAnswers } from '@/lib/unique-answers';
Expand Down Expand Up @@ -100,13 +101,7 @@ export async function DELETE(req: Request, { params }: Ctx) {
const body = await req.json().catch(() => null);
const ids: string[] = Array.isArray(body?.ids) ? body.ids.filter((x: unknown) => typeof x === 'string') : [];
if (!ids.length) return NextResponse.json({ error: 'No ids provided' }, { status: 400 });
// Remember attached files first so they can be removed with the responses.
const doomed = await prisma.submission.findMany({ where: { formId: params.id, id: { in: ids } }, select: { data: true } });
const { count } = await prisma.submission.deleteMany({ where: { formId: params.id, id: { in: ids } } });
const form = await prisma.form.findUnique({ where: { id: params.id }, select: { schema: true } });
if (form) {
const answers = doomed.map((d) => { try { return JSON.parse(d.data); } catch { return {}; } });
await deleteAnswerFiles(params.id, parseSchema(form.schema).fields, answers).catch(() => {});
}
// Into the Trash (Settings → Trash) for 30 days; attached files stay until they leave the Trash.
const count = await trashSubmissions(params.id, ids, me);
return NextResponse.json({ deleted: count });
}
16 changes: 16 additions & 0 deletions app/settings/trash/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { Metadata } from 'next';
import { TrashSettings } from '@/components/settings/trash-settings';
import { requireAdmin } from '@/lib/auth';
import { getServerT } from '@/lib/i18n/server';
import { listTrash, TRASH_DAYS } from '@/lib/trash';

export const dynamic = 'force-dynamic';
export async function generateMetadata(): Promise<Metadata> {
const t = await getServerT();
return { title: t('Trash') };
}

export default async function TrashPage() {
await requireAdmin();
return <TrashSettings initial={await listTrash()} days={TRASH_DAYS} />;
}
4 changes: 2 additions & 2 deletions components/hub/hub-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,8 @@ export function HubClient({ forms, canCreate, portRange }: { forms: HubForm[]; c
<strong className="text-slate-900">{toDelete?.title}</strong>
{' — '}
{toDelete?.responses === 1
? t('This form and its 1 response will be permanently deleted. This can’t be undone.')
: t('This form and all of its {n} responses will be permanently deleted. This can’t be undone.', { n: fmtNumber(toDelete?.responses ?? 0, locale) })}
? t('This form and its 1 response will move to the Trash. An admin can restore them from Settings → Trash for 30 days.')
: t('This form and all of its {n} responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.', { n: fmtNumber(toDelete?.responses ?? 0, locale) })}
</>
}
/>
Expand Down
3 changes: 2 additions & 1 deletion components/settings/settings-nav.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { Bell, Database, Info, Palette, UserCircle2, Users } from 'lucide-react';
import { Bell, Database, Info, Palette, Trash2, UserCircle2, Users } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';
Expand All @@ -13,6 +13,7 @@ const WORKSPACE = [
{ href: '/settings/users', label: 'Users & roles', icon: Users },
{ href: '/settings/notifications', label: 'Notifications', icon: Bell },
{ href: '/settings/database', label: 'Database & Backup', icon: Database },
{ href: '/settings/trash', label: 'Trash', icon: Trash2 },
{ href: '/settings/about', label: 'About', icon: Info },
];

Expand Down
131 changes: 131 additions & 0 deletions components/settings/trash-settings.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
'use client';

import { FileText, Inbox, RotateCcw, Trash2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useI18n } from '@/components/i18n';
import { useToast } from '@/components/toast';
import { Button, ConfirmDialog, EmptyState } from '@/components/ui';
import type { TrashEntry } from '@/lib/trash';
import { cn, formatDateTime, timeAgo } from '@/lib/utils';
import { SettingsCard } from './settings-ui';

const DAY_MS = 86_400_000;

/** Settings → Trash: deleted forms and responses, kept for `days` days, with Restore and Delete forever. */
export function TrashSettings({ initial, days }: { initial: TrashEntry[]; days: number }) {
const { t, locale } = useI18n();
const toast = useToast();
const router = useRouter();
const [items, setItems] = useState(initial);
const [busy, setBusy] = useState<string | null>(null);
const [confirm, setConfirm] = useState<{ kind: 'one'; item: TrashEntry } | { kind: 'all' } | null>(null);

const restore = async (item: TrashEntry) => {
setBusy(item.id);
const res = await fetch(`/api/admin/trash/${item.id}`, { method: 'POST' });
const j = await res.json().catch(() => null);
setBusy(null);
if (!res.ok) return toast(t(typeof j?.error === 'string' ? j.error : 'Could not restore it.'), 'error');
setItems((list) => list.filter((i) => i.id !== item.id));
toast(
item.kind === 'form'
? j?.changedLink
? t('Form restored. Its old link was taken, so it got a new one.')
: t('Form restored with its responses.')
: t('Response restored.'),
);
router.refresh();
};

const remove = async () => {
if (!confirm) return;
setBusy(confirm.kind === 'all' ? 'all' : confirm.item.id);
const res = await fetch(confirm.kind === 'all' ? '/api/admin/trash' : `/api/admin/trash/${confirm.item.id}`, { method: 'DELETE' });
setBusy(null);
if (!res.ok) {
const j = await res.json().catch(() => null);
return toast(t(typeof j?.error === 'string' ? j.error : 'Could not delete it.'), 'error');
}
if (confirm.kind === 'all') setItems([]);
// Deleting a form for good also removes its responses that were in the Trash.
else setItems((list) => list.filter((i) => i.id !== confirm.item.id && !(confirm.item.kind === 'form' && i.kind === 'submission' && i.formId === confirm.item.formId)));
setConfirm(null);
toast(confirm.kind === 'all' ? t('Trash emptied.') : t('Deleted for good.'));
};

const daysLeft = (i: TrashEntry) => Math.max(0, Math.ceil((new Date(i.expiresAt).getTime() - Date.now()) / DAY_MS));

return (
<div className="space-y-6">
<SettingsCard
title={t('Trash')}
icon={<Trash2 />}
description={t('Deleted forms and responses stay here for {n} days, then they are removed for good together with their uploaded files.', { n: days })}
aside={
items.length > 0 && (
<Button variant="danger" size="sm" onClick={() => setConfirm({ kind: 'all' })} loading={busy === 'all'}>
{t('Empty Trash')}
</Button>
)
}
>
{items.length === 0 ? (
<EmptyState icon={<Trash2 />} title={t('The Trash is empty')} description={t('Forms and responses you delete appear here.')} />
) : (
<ul className="-my-2 divide-y divide-slate-100">
{items.map((i) => {
const left = daysLeft(i);
return (
<li key={i.id} className="flex flex-col gap-3 py-3 sm:flex-row sm:items-center">
<span className={cn('flex h-9 w-9 shrink-0 items-center justify-center rounded-lg', i.kind === 'form' ? 'bg-brand-50 text-brand-600' : 'bg-slate-100 text-slate-500')}>
{i.kind === 'form' ? <FileText className="h-4 w-4" /> : <Inbox className="h-4 w-4" />}
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
<span className="truncate text-sm font-semibold text-slate-900">{i.title || t('Untitled form')}</span>
<span className="rounded-md bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-slate-500">
{i.kind === 'form' ? (i.count === 1 ? t('Form · 1 response') : t('Form · {n} responses', { n: i.count })) : t('Response')}
</span>
</div>
{i.preview && <p className="mt-0.5 truncate text-sm text-slate-600">{i.preview}</p>}
<p className="mt-0.5 text-xs text-slate-500" title={formatDateTime(i.deletedAt, locale)}>
{t('Deleted {when} by {name}', { when: timeAgo(i.deletedAt, t), name: i.deletedByName || t('someone') })}
{' · '}
<span className={cn(left <= 3 && 'font-medium text-rose-600')}>{left === 1 ? t('removed for good in 1 day') : t('removed for good in {n} days', { n: left })}</span>
</p>
{i.formMissing && <p className="mt-0.5 text-xs text-amber-600">{t('Its form is deleted. Restore the form first, then this response.')}</p>}
</div>
<div className="flex shrink-0 gap-2">
<Button size="sm" onClick={() => restore(i)} loading={busy === i.id} disabled={!!busy || i.formMissing}>
<RotateCcw className="h-3.5 w-3.5" /> {t('Restore')}
</Button>
<Button size="sm" variant="ghost" onClick={() => setConfirm({ kind: 'one', item: i })} disabled={!!busy} aria-label={t('Delete forever')} title={t('Delete forever')}>
<Trash2 className="h-3.5 w-3.5 text-rose-600" />
</Button>
</div>
</li>
);
})}
</ul>
)}
</SettingsCard>

<ConfirmDialog
open={!!confirm}
onClose={() => setConfirm(null)}
onConfirm={remove}
loading={!!busy}
title={confirm?.kind === 'all' ? t('Empty the Trash?') : t('Delete forever?')}
description={
confirm?.kind === 'all'
? t('Everything in the Trash and its uploaded files will be removed for good. This can’t be undone.')
: confirm?.item.kind === 'form'
? t('This form, its responses and its uploaded files will be removed for good. This can’t be undone.')
: t('This response and its uploaded files will be removed for good. This can’t be undone.')
}
confirmLabel={t('Delete forever')}
/>
</div>
);
}
2 changes: 1 addition & 1 deletion components/submissions/submissions-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ export function SubmissionsView({
onConfirm={doDelete}
loading={deleting}
title={confirm && confirm.length > 1 ? t('Delete {n} responses?', { n: confirm.length }) : t('Delete response?')}
description={t('This permanently removes the selected response data. This can’t be undone.')}
description={t('The selected responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.')}
confirmLabel={t('Delete')}
/>
</div>
Expand Down
Loading
Loading