Files
pn-new-crm/src/components/admin/inquiry-inbox.tsx

207 lines
6.9 KiB
TypeScript
Raw Normal View History

feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
'use client';
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { formatDistanceToNow } from 'date-fns';
import { PageHeader } from '@/components/shared/page-header';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';
interface Submission {
id: string;
portId: string;
submissionId: string;
kind: 'berth_inquiry' | 'residence_inquiry' | 'contact_form';
payload: Record<string, unknown> | null;
legacyNocodbId: string | null;
sourceIp: string | null;
userAgent: string | null;
receivedAt: string;
}
interface ListResponse {
data: Submission[];
pagination: { nextCursor: { receivedAt: string; id: string } | null };
counts: Record<string, number>;
}
const KIND_LABELS: Record<Submission['kind'], string> = {
berth_inquiry: 'Berth inquiry',
residence_inquiry: 'Residence inquiry',
contact_form: 'Contact form',
};
const KIND_COLORS: Record<Submission['kind'], string> = {
berth_inquiry: 'bg-blue-100 text-blue-800',
residence_inquiry: 'bg-amber-100 text-amber-800',
contact_form: 'bg-slate-100 text-slate-800',
};
function pickName(payload: Record<string, unknown> | null): string {
if (!payload) return '';
const candidates = ['name', 'fullName', 'full_name', 'firstName', 'first_name'];
for (const k of candidates) {
const v = payload[k];
if (typeof v === 'string' && v.trim()) return v.trim();
}
return '';
}
function pickEmail(payload: Record<string, unknown> | null): string {
if (!payload) return '';
const v = payload['email'];
return typeof v === 'string' ? v : '';
}
function pickPhone(payload: Record<string, unknown> | null): string {
if (!payload) return '';
const v = payload['phone'] ?? payload['phoneNumber'] ?? payload['phone_number'];
return typeof v === 'string' ? v : '';
}
export function InquiryInbox() {
const [kind, setKind] = useState<Submission['kind'] | 'all'>('all');
const [expanded, setExpanded] = useState<string | null>(null);
const { data, isLoading, error } = useQuery({
queryKey: ['inquiry-inbox', kind],
queryFn: () =>
apiFetch<ListResponse>(
`/api/v1/admin/website-submissions${kind === 'all' ? '' : `?kind=${kind}`}`,
),
});
const counts = data?.counts ?? {};
const totalAll = useMemo(() => Object.values(counts).reduce((sum, n) => sum + n, 0), [counts]);
const rows = data?.data ?? [];
return (
<div>
<PageHeader
title="Inquiry inbox"
description="Submissions captured from the public marketing site (berth, residence, and contact forms)."
/>
<div className="flex items-center gap-2 mt-6 flex-wrap">
<FilterChip
label={`All (${totalAll})`}
active={kind === 'all'}
onClick={() => setKind('all')}
/>
<FilterChip
label={`Berth inquiries (${counts.berth_inquiry ?? 0})`}
active={kind === 'berth_inquiry'}
onClick={() => setKind('berth_inquiry')}
/>
<FilterChip
label={`Residence (${counts.residence_inquiry ?? 0})`}
active={kind === 'residence_inquiry'}
onClick={() => setKind('residence_inquiry')}
/>
<FilterChip
label={`Contact (${counts.contact_form ?? 0})`}
active={kind === 'contact_form'}
onClick={() => setKind('contact_form')}
/>
</div>
<div className="mt-6">
{isLoading ? (
<p className="text-sm text-muted-foreground py-6">Loading</p>
) : error ? (
<p className="text-sm text-red-600 py-6">
Failed to load inquiries: {error instanceof Error ? error.message : 'unknown error'}
</p>
) : rows.length === 0 ? (
<Card>
<CardContent className="py-10 text-center text-sm text-muted-foreground">
No website submissions yet for this filter.
</CardContent>
</Card>
) : (
<div className="space-y-3">
{rows.map((row) => {
const name = pickName(row.payload);
const email = pickEmail(row.payload);
const phone = pickPhone(row.payload);
const ago = formatDistanceToNow(new Date(row.receivedAt), { addSuffix: true });
const isOpen = expanded === row.id;
return (
<Card key={row.id}>
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-3">
<div className="flex-1">
<div className="flex items-center gap-2">
<Badge className={KIND_COLORS[row.kind]}>{KIND_LABELS[row.kind]}</Badge>
<span
className="text-xs text-muted-foreground"
title={new Date(row.receivedAt).toISOString()}
>
{ago}
</span>
</div>
<CardTitle className="mt-2 text-base font-medium">
{name || '(no name supplied)'}
</CardTitle>
<div className="text-sm text-muted-foreground mt-1 space-x-3">
{email ? <span>{email}</span> : null}
{phone ? <span>{phone}</span> : null}
{row.sourceIp ? (
<span className="text-xs">from {row.sourceIp}</span>
) : null}
</div>
</div>
<Button
size="sm"
variant="outline"
onClick={() => setExpanded(isOpen ? null : row.id)}
>
{isOpen ? 'Hide payload' : 'View payload'}
</Button>
</div>
</CardHeader>
{isOpen && (
<CardContent>
<pre className="bg-muted/40 rounded-md p-3 text-xs overflow-auto max-h-96">
{JSON.stringify(row.payload, null, 2)}
</pre>
</CardContent>
)}
</Card>
);
})}
</div>
)}
</div>
</div>
);
}
function FilterChip({
label,
active,
onClick,
}: {
label: string;
active: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
className={`px-3 py-1.5 rounded-full text-sm border transition ${
active
? 'bg-primary text-primary-foreground border-primary'
: 'bg-background text-foreground border-border hover:bg-muted'
}`}
>
{label}
</button>
);
}