Files
pn-new-crm/src/components/admin/sends-log.tsx
Matt Ciaccio c90876abad 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

201 lines
7.1 KiB
TypeScript

'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { formatDistanceToNow, format } 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 SendRow {
id: string;
portId: string;
recipientEmail: string;
documentKind: 'berth_pdf' | 'brochure' | string;
fromAddress: string;
bodyMarkdown: string | null;
sentAt: string;
failedAt: string | null;
errorReason: string | null;
fallbackToLinkReason: string | null;
messageId: string | null;
berthId: string | null;
brochureId: string | null;
clientId: string | null;
interestId: string | null;
}
interface ListResponse {
data: SendRow[];
pagination: { nextCursor: { sentAt: string; id: string } | null };
counts: { sent: number; failed: number; all: number };
}
export function SendsLog() {
const [status, setStatus] = useState<'all' | 'sent' | 'failed'>('all');
const [expanded, setExpanded] = useState<string | null>(null);
const { data, isLoading, error } = useQuery({
queryKey: ['document-sends', status],
queryFn: () => apiFetch<ListResponse>(`/api/v1/admin/document-sends?status=${status}`),
});
const counts = data?.counts ?? { sent: 0, failed: 0, all: 0 };
const rows = data?.data ?? [];
return (
<div>
<PageHeader
title="Send log"
description="Every brochure and per-berth PDF sent from the CRM, with delivery failures surfaced for retry."
/>
<div className="flex items-center gap-2 mt-6 flex-wrap">
<FilterChip
label={`All (${counts.all})`}
active={status === 'all'}
onClick={() => setStatus('all')}
/>
<FilterChip
label={`Sent (${counts.sent})`}
active={status === 'sent'}
onClick={() => setStatus('sent')}
/>
<FilterChip
label={`Failed (${counts.failed})`}
active={status === 'failed'}
onClick={() => setStatus('failed')}
accent={counts.failed > 0 ? 'danger' : undefined}
/>
</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 sends: {error instanceof Error ? error.message : 'unknown error'}
</p>
) : rows.length === 0 ? (
<Card>
<CardContent className="py-10 text-center text-sm text-muted-foreground">
No sends recorded for this filter yet.
</CardContent>
</Card>
) : (
<div className="space-y-3">
{rows.map((row) => {
const sent = new Date(row.sentAt);
const ago = formatDistanceToNow(sent, { addSuffix: true });
const isOpen = expanded === row.id;
const failed = !!row.failedAt;
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 flex-wrap">
<Badge
className={
failed ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'
}
>
{failed ? 'Failed' : 'Sent'}
</Badge>
<Badge variant="secondary">
{row.documentKind === 'berth_pdf'
? 'Berth PDF'
: row.documentKind === 'brochure'
? 'Brochure'
: row.documentKind}
</Badge>
{row.fallbackToLinkReason ? (
<Badge className="bg-amber-100 text-amber-800">
Switched to download link
</Badge>
) : null}
<span
className="text-xs text-muted-foreground"
title={sent.toISOString()}
>
{ago} · {format(sent, 'PP p')}
</span>
</div>
<CardTitle className="mt-2 text-base font-medium">
{row.recipientEmail}
</CardTitle>
<div className="text-sm text-muted-foreground mt-1">
From {row.fromAddress}
{row.messageId ? (
<span className="text-xs ml-2 font-mono">{row.messageId}</span>
) : null}
</div>
{failed && row.errorReason ? (
<div className="mt-2 text-sm text-red-700 bg-red-50 rounded-md p-2">
{row.errorReason}
</div>
) : null}
{row.fallbackToLinkReason ? (
<div className="mt-2 text-sm text-amber-700 bg-amber-50 rounded-md p-2">
Attachment dropped sent as link. Reason: {row.fallbackToLinkReason}
</div>
) : null}
</div>
{row.bodyMarkdown ? (
<Button
size="sm"
variant="outline"
onClick={() => setExpanded(isOpen ? null : row.id)}
>
{isOpen ? 'Hide body' : 'View body'}
</Button>
) : null}
</div>
</CardHeader>
{isOpen && row.bodyMarkdown ? (
<CardContent>
<pre className="bg-muted/40 rounded-md p-3 text-xs overflow-auto max-h-96 whitespace-pre-wrap">
{row.bodyMarkdown}
</pre>
</CardContent>
) : null}
</Card>
);
})}
</div>
)}
</div>
</div>
);
}
function FilterChip({
label,
active,
onClick,
accent,
}: {
label: string;
active: boolean;
onClick: () => void;
accent?: 'danger';
}) {
const base = active
? 'bg-primary text-primary-foreground border-primary'
: 'bg-background text-foreground border-border hover:bg-muted';
const dangerActive =
accent === 'danger' && active ? 'bg-red-600 text-white border-red-600' : null;
return (
<button
type="button"
onClick={onClick}
className={`px-3 py-1.5 rounded-full text-sm border transition ${dangerActive ?? base}`}
>
{label}
</button>
);
}