feat(admin): per-port email/Documenso/branding/reminder settings + invitations
All checks were successful
Build & Push Docker Images / lint (pull_request) Successful in 1m1s
Build & Push Docker Images / build-and-push (pull_request) Has been skipped

Centralizes everything operators need to configure into the admin panel,
each setting per-port with env fallback.

New admin pages
- /admin              landing page linking to every admin section as a card
- /admin/email        FROM name+address, reply-to, signature/footer HTML,
                      optional SMTP host/port/user/pass override
- /admin/documenso    API URL+key override, EOI Documenso template ID,
                      default EOI pathway (documenso-template vs inapp),
                      "Test connection" button
- /admin/branding     logo URL, primary color, app name, email
                      header/footer HTML
- /admin/reminders    port-level defaults for new interests +
                      port-wide daily-digest delivery window
- /admin/invitations  send / list / resend / revoke CRM invitations

Per-user reminder digest
- /notifications/preferences gains a Reminder digest card:
  immediate / daily / weekly / off, with HH:MM, day-of-week,
  IANA timezone fields. Stored in user_profiles.preferences.reminders.

Plumbing
- port-config.ts typed accessors (getPortEmailConfig, getPortDocumensoConfig,
  getPortBrandingConfig, getPortReminderConfig) — settings → env fallback.
- sendEmail accepts optional portId; resolves From/SMTP from settings
  when supplied.
- documensoFetch + downloadSignedPdf accept optional portId; each public
  function takes it through. checkDocumensoHealth() backs the test button.
- crm-invite.service gains listCrmInvites / revokeCrmInvite / resendCrmInvite
  with audit-log entries (revoke_invite, resend_invite added to AuditAction).
- AdminLandingPage card grid + shared SettingsFormCard component to remove
  per-page form boilerplate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-04-27 23:21:54 +02:00
parent f2c57c513e
commit 4877b97f27
22 changed files with 1937 additions and 43 deletions

View File

@@ -0,0 +1,64 @@
'use client';
import { useState } from 'react';
import { Loader2, CheckCircle2, XCircle } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';
interface HealthResponse {
ok: boolean;
status?: number;
error?: string;
}
export function DocumensoTestButton() {
const [pending, setPending] = useState(false);
const [result, setResult] = useState<HealthResponse | null>(null);
async function runTest() {
setPending(true);
setResult(null);
try {
const res = await apiFetch<{ data: HealthResponse }>('/api/v1/admin/documenso/health', {
method: 'POST',
});
setResult(res.data);
if (res.data.ok) {
toast.success(`Documenso reachable (HTTP ${res.data.status ?? 200})`);
} else {
toast.error(
res.data.error ?? `Documenso responded with HTTP ${res.data.status ?? 'unknown'}`,
);
}
} catch (err) {
const message = err instanceof Error ? err.message : 'Test failed';
setResult({ ok: false, error: message });
toast.error(message);
} finally {
setPending(false);
}
}
return (
<div className="flex items-center gap-3">
{result &&
(result.ok ? (
<span className="flex items-center text-xs text-green-600">
<CheckCircle2 className="mr-1 h-3.5 w-3.5" />
HTTP {result.status}
</span>
) : (
<span className="flex items-center text-xs text-destructive">
<XCircle className="mr-1 h-3.5 w-3.5" />
{result.error ?? `HTTP ${result.status}`}
</span>
))}
<Button variant="outline" onClick={runTest} disabled={pending}>
{pending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Test connection
</Button>
</div>
);
}

View File

@@ -0,0 +1,241 @@
'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2, Mail, RotateCw, Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { apiFetch } from '@/lib/api/client';
interface Invite {
id: string;
email: string;
name: string | null;
isSuperAdmin: boolean;
expiresAt: string;
usedAt: string | null;
createdAt: string;
status: 'pending' | 'accepted' | 'expired';
}
const STATUS_STYLES: Record<Invite['status'], string> = {
pending: 'bg-amber-100 text-amber-800 border-amber-200',
accepted: 'bg-green-100 text-green-800 border-green-200',
expired: 'bg-muted text-muted-foreground border-muted',
};
export function InvitationsManager() {
const qc = useQueryClient();
const [sheetOpen, setSheetOpen] = useState(false);
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [isSuperAdmin, setIsSuperAdmin] = useState(false);
const { data: invites = [], isLoading } = useQuery<Invite[]>({
queryKey: ['admin', 'invitations'],
queryFn: () => apiFetch<{ data: Invite[] }>('/api/v1/admin/invitations').then((r) => r.data),
});
const createMutation = useMutation({
mutationFn: () =>
apiFetch('/api/v1/admin/invitations', {
method: 'POST',
body: { email, name: name || undefined, isSuperAdmin },
}),
onSuccess: () => {
toast.success(`Invite sent to ${email}`);
setSheetOpen(false);
setEmail('');
setName('');
setIsSuperAdmin(false);
qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
},
onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to send invite'),
});
const resendMutation = useMutation({
mutationFn: (id: string) =>
apiFetch(`/api/v1/admin/invitations/${id}/resend`, { method: 'POST' }),
onSuccess: () => {
toast.success('Invite resent');
qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
},
onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to resend'),
});
const revokeMutation = useMutation({
mutationFn: (id: string) => apiFetch(`/api/v1/admin/invitations/${id}`, { method: 'DELETE' }),
onSuccess: () => {
toast.success('Invite revoked');
qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
},
onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to revoke'),
});
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold">Pending invitations</h2>
<p className="text-sm text-muted-foreground">
Invitations expire 72 hours after issue. Resending mints a new token and emails it.
</p>
</div>
<Button onClick={() => setSheetOpen(true)}>
<Plus className="h-4 w-4 mr-1.5" />
Send invite
</Button>
</div>
{isLoading ? (
<p className="text-sm text-muted-foreground">Loading</p>
) : invites.length === 0 ? (
<div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
<Mail className="mx-auto h-6 w-6 mb-2" />
<p className="text-sm">No invitations issued yet.</p>
</div>
) : (
<div className="rounded-lg border bg-card overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-muted/40 text-xs text-muted-foreground">
<tr>
<th className="text-left font-medium px-3 py-2">Email</th>
<th className="text-left font-medium px-3 py-2">Name</th>
<th className="text-left font-medium px-3 py-2">Role</th>
<th className="text-left font-medium px-3 py-2">Status</th>
<th className="text-left font-medium px-3 py-2">Expires</th>
<th className="px-3 py-2"></th>
</tr>
</thead>
<tbody>
{invites.map((i) => (
<tr key={i.id} className="border-t">
<td className="px-3 py-2 font-medium">{i.email}</td>
<td className="px-3 py-2 text-muted-foreground">{i.name ?? '—'}</td>
<td className="px-3 py-2 text-muted-foreground">
{i.isSuperAdmin ? 'Super admin' : 'Standard user'}
</td>
<td className="px-3 py-2">
<span
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium capitalize ${STATUS_STYLES[i.status]}`}
>
{i.status}
</span>
</td>
<td className="px-3 py-2 text-muted-foreground">
{new Date(i.expiresAt).toLocaleString()}
</td>
<td className="px-3 py-2 text-right">
{i.status === 'pending' || i.status === 'expired' ? (
<div className="inline-flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => resendMutation.mutate(i.id)}
disabled={resendMutation.isPending || !!i.usedAt}
title="Resend invite"
>
<RotateCw className="h-3.5 w-3.5" />
</Button>
{i.status === 'pending' && (
<ConfirmationDialog
trigger={
<Button
variant="ghost"
size="icon"
className="text-destructive"
title="Revoke"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
}
title="Revoke invitation?"
description={`Revoke the pending invitation for ${i.email}? The link in the email will stop working.`}
confirmLabel="Revoke"
onConfirm={() => revokeMutation.mutate(i.id)}
/>
)}
</div>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
<SheetContent>
<SheetHeader>
<SheetTitle>Send invitation</SheetTitle>
</SheetHeader>
<form
className="mt-6 space-y-4"
onSubmit={(e) => {
e.preventDefault();
createMutation.mutate();
}}
>
<div className="space-y-1.5">
<Label htmlFor="invite-email">Email *</Label>
<Input
id="invite-email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="invite-name">Display name</Label>
<Input
id="invite-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Optional"
/>
</div>
<div className="flex items-start justify-between gap-4 rounded-lg border p-3">
<div>
<Label htmlFor="invite-superadmin" className="text-sm font-medium">
Grant super admin
</Label>
<p className="text-xs text-muted-foreground">
Super admins bypass per-port permission checks. Use sparingly.
</p>
</div>
<Switch
id="invite-superadmin"
checked={isSuperAdmin}
onCheckedChange={setIsSuperAdmin}
/>
</div>
<SheetFooter>
<Button
type="button"
variant="outline"
onClick={() => setSheetOpen(false)}
disabled={createMutation.isPending}
>
Cancel
</Button>
<Button type="submit" disabled={!email.trim() || createMutation.isPending}>
{createMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Send invite
</Button>
</SheetFooter>
</form>
</SheetContent>
</Sheet>
</div>
);
}

View File

@@ -0,0 +1,309 @@
'use client';
import { useCallback, useEffect, useState, type ReactNode } from 'react';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';
export type SettingFieldType =
| 'string'
| 'password'
| 'number'
| 'boolean'
| 'textarea'
| 'html'
| 'select'
| 'color';
export interface SettingFieldDef {
key: string;
label: string;
description?: string;
type: SettingFieldType;
placeholder?: string;
defaultValue: unknown;
options?: Array<{ value: string; label: string }>;
}
interface SettingsRowResponse {
key: string;
value: unknown;
portId: string | null;
}
interface ListResponse {
data: { portSettings: SettingsRowResponse[]; globalSettings: SettingsRowResponse[] };
}
interface SettingsFormCardProps {
title: string;
description?: string;
fields: SettingFieldDef[];
/** Optional extra slot rendered below the form (e.g. test-connection button). */
extra?: ReactNode;
}
/**
* Reusable card that fetches /api/v1/admin/settings, renders editable form
* fields for the supplied keys, and PUTs each on save.
*/
export function SettingsFormCard({ title, description, fields, extra }: SettingsFormCardProps) {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [values, setValues] = useState<Record<string, unknown>>({});
const [originals, setOriginals] = useState<Record<string, unknown>>({});
const fetchValues = useCallback(async () => {
setLoading(true);
try {
const res = await apiFetch<ListResponse>('/api/v1/admin/settings');
const next: Record<string, unknown> = {};
for (const field of fields) {
const port = res.data.portSettings.find((s) => s.key === field.key);
const global = res.data.globalSettings.find((s) => s.key === field.key);
next[field.key] = port?.value ?? global?.value ?? field.defaultValue;
}
setValues(next);
setOriginals(next);
} finally {
setLoading(false);
}
}, [fields]);
useEffect(() => {
void fetchValues();
}, [fetchValues]);
function setField(key: string, value: unknown) {
setValues((prev) => ({ ...prev, [key]: value }));
}
async function handleSave() {
setSaving(true);
try {
const changedFields = fields.filter((f) => values[f.key] !== originals[f.key]);
if (changedFields.length === 0) {
toast.info('No changes to save');
return;
}
for (const f of changedFields) {
await apiFetch('/api/v1/admin/settings', {
method: 'PUT',
body: { key: f.key, value: values[f.key] },
});
}
toast.success(`Saved ${changedFields.length} setting(s)`);
setOriginals(values);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Save failed');
} finally {
setSaving(false);
}
}
if (loading) {
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Loading
</div>
</CardContent>
</Card>
);
}
const dirty = fields.some((f) => values[f.key] !== originals[f.key]);
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
{description && <CardDescription>{description}</CardDescription>}
</CardHeader>
<CardContent className="space-y-5">
{fields.map((field) => (
<FieldRow
key={field.key}
field={field}
value={values[field.key]}
onChange={(v) => setField(field.key, v)}
/>
))}
<div className="flex items-center justify-end gap-2 pt-2 border-t">
{extra}
<Button onClick={handleSave} disabled={saving || !dirty}>
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Save changes
</Button>
</div>
</CardContent>
</Card>
);
}
function FieldRow({
field,
value,
onChange,
}: {
field: SettingFieldDef;
value: unknown;
onChange: (v: unknown) => void;
}) {
const id = `setting-${field.key}`;
switch (field.type) {
case 'boolean':
return (
<div className="flex items-start justify-between gap-4">
<div className="space-y-0.5">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
</div>
<Switch id={id} checked={!!value} onCheckedChange={(checked) => onChange(checked)} />
</div>
);
case 'textarea':
case 'html':
return (
<div className="space-y-1">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
<Textarea
id={id}
rows={field.type === 'html' ? 6 : 3}
value={typeof value === 'string' ? value : ''}
placeholder={field.placeholder}
onChange={(e) => onChange(e.target.value)}
className={field.type === 'html' ? 'font-mono text-xs' : undefined}
/>
</div>
);
case 'select':
return (
<div className="space-y-1">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
<Select value={typeof value === 'string' ? value : ''} onValueChange={(v) => onChange(v)}>
<SelectTrigger id={id}>
<SelectValue placeholder={field.placeholder ?? 'Choose…'} />
</SelectTrigger>
<SelectContent>
{(field.options ?? []).map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
case 'number':
return (
<div className="space-y-1">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
<Input
id={id}
type="number"
value={typeof value === 'number' ? value : ''}
placeholder={field.placeholder}
onChange={(e) => {
const n = e.target.value === '' ? null : Number(e.target.value);
onChange(n);
}}
/>
</div>
);
case 'color':
return (
<div className="space-y-1">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
<div className="flex items-center gap-2">
<input
type="color"
value={typeof value === 'string' ? value : '#000000'}
onChange={(e) => onChange(e.target.value)}
className="h-9 w-14 cursor-pointer rounded border"
/>
<Input
id={id}
value={typeof value === 'string' ? value : ''}
onChange={(e) => onChange(e.target.value)}
placeholder="#000000"
className="font-mono"
/>
</div>
</div>
);
case 'password':
return (
<div className="space-y-1">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
<Input
id={id}
type="password"
value={typeof value === 'string' ? value : ''}
placeholder={field.placeholder ?? '(unchanged)'}
onChange={(e) => onChange(e.target.value)}
/>
</div>
);
case 'string':
default:
return (
<div className="space-y-1">
<Label htmlFor={id}>{field.label}</Label>
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
<Input
id={id}
value={typeof value === 'string' ? value : ''}
placeholder={field.placeholder}
onChange={(e) => onChange(e.target.value)}
/>
</div>
);
}
}

View File

@@ -0,0 +1,173 @@
'use client';
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';
interface ReminderPrefs {
delivery: 'immediate' | 'daily' | 'weekly' | 'off';
digestTime?: string;
digestDayOfWeek?: number;
timezone?: string;
}
interface UserPrefsResponse {
reminders?: ReminderPrefs;
timezone?: string;
}
const DAYS = [
{ value: '0', label: 'Sunday' },
{ value: '1', label: 'Monday' },
{ value: '2', label: 'Tuesday' },
{ value: '3', label: 'Wednesday' },
{ value: '4', label: 'Thursday' },
{ value: '5', label: 'Friday' },
{ value: '6', label: 'Saturday' },
];
export function ReminderDigestForm() {
const qc = useQueryClient();
const { data, isLoading } = useQuery<UserPrefsResponse>({
queryKey: ['user', 'preferences'],
queryFn: () =>
apiFetch<{ data: UserPrefsResponse }>('/api/v1/users/me/preferences').then((r) => r.data),
});
const [delivery, setDelivery] = useState<ReminderPrefs['delivery']>('immediate');
const [digestTime, setDigestTime] = useState('09:00');
const [digestDay, setDigestDay] = useState('1');
const [timezone, setTimezone] = useState('Europe/Warsaw');
useEffect(() => {
const r = data?.reminders;
if (r) {
setDelivery(r.delivery ?? 'immediate');
setDigestTime(r.digestTime ?? '09:00');
setDigestDay(String(r.digestDayOfWeek ?? 1));
setTimezone(r.timezone ?? data?.timezone ?? 'Europe/Warsaw');
} else if (data?.timezone) {
setTimezone(data.timezone);
}
}, [data]);
const mutation = useMutation({
mutationFn: () =>
apiFetch('/api/v1/users/me/preferences', {
method: 'PATCH',
body: {
reminders: {
delivery,
...(delivery !== 'immediate' && delivery !== 'off' ? { digestTime, timezone } : {}),
...(delivery === 'weekly' ? { digestDayOfWeek: Number(digestDay) } : {}),
},
},
}),
onSuccess: () => {
toast.success('Reminder preferences saved');
qc.invalidateQueries({ queryKey: ['user', 'preferences'] });
},
onError: (err) => toast.error(err instanceof Error ? err.message : 'Save failed'),
});
if (isLoading) {
return (
<Card>
<CardContent className="py-6 text-sm text-muted-foreground">
<Loader2 className="mr-2 inline h-4 w-4 animate-spin" />
Loading
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Reminder digest</CardTitle>
<CardDescription>
Choose how reminder notifications are delivered to you. Immediate fires as soon as a
reminder triggers; daily/weekly batch them into a digest at the time you pick.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1">
<Label>Delivery</Label>
<Select
value={delivery}
onValueChange={(v) => setDelivery(v as ReminderPrefs['delivery'])}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="immediate">Immediate (default)</SelectItem>
<SelectItem value="daily">Daily digest</SelectItem>
<SelectItem value="weekly">Weekly digest</SelectItem>
<SelectItem value="off">Off (do not send)</SelectItem>
</SelectContent>
</Select>
</div>
{(delivery === 'daily' || delivery === 'weekly') && (
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label>Delivery time (HH:MM)</Label>
<Input
value={digestTime}
onChange={(e) => setDigestTime(e.target.value)}
placeholder="09:00"
/>
</div>
{delivery === 'weekly' && (
<div className="space-y-1">
<Label>Day of week</Label>
<Select value={digestDay} onValueChange={setDigestDay}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{DAYS.map((d) => (
<SelectItem key={d.value} value={d.value}>
{d.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div className="space-y-1 col-span-2">
<Label>Timezone (IANA)</Label>
<Input
value={timezone}
onChange={(e) => setTimezone(e.target.value)}
placeholder="Europe/Warsaw"
/>
</div>
</div>
)}
<div className="flex justify-end">
<Button onClick={() => mutation.mutate()} disabled={mutation.isPending}>
{mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Save digest preferences
</Button>
</div>
</CardContent>
</Card>
);
}