Files
pn-new-crm/src/components/admin/ports/port-form.tsx

211 lines
6.4 KiB
TypeScript
Raw Normal View History

'use client';
fix(audit-tier-2-routes): manual NextResponse.json error sweep + admin form banners Two final waves of error-surface hygiene closing the audit's MED §12 + HIGH §15 + HIGH §17 findings: * 50 route files swept (61 sites): manual NextResponse.json({error, status: 4xx|5xx}) early-returns replaced by typed throws + errorResponse(err) at the catch. - Super-admin gates (13 sites) use new requireSuperAdmin(ctx, action) helper from src/lib/api/helpers.ts so denials hit the audit log. - Path-param + body validation 400s become ValidationError throws. - 404s become NotFoundError or CodedError('NOT_FOUND') for AI feature-flag paths. - 11 manual 5xx returns now re-throw so error_events captures the request-id (the admin error inspector becomes usable from real incidents). - website-analytics 200-with-error anti-pattern flipped to 409 + UMAMI_NOT_CONFIGURED. 502 upstream paths use UMAMI_UPSTREAM_ERROR. - 11 sites intentionally preserved: storage/[token] anti-enumeration token-failure paths, webhook-secret 401, "Unknown port" 400 in public intake. * 7 admin forms (roles, users, ports, webhooks, custom-fields, document-templates, tags) gain a formatErrorBanner() helper from src/lib/api/toast-error.ts that builds a multi-line "Error code / Reference ID" banner — the rep can copy the request id when reporting a failed save. Banners get whitespace-pre-line so newlines render. Test status: 1168/1168 vitest, tsc clean. Refs: docs/audit-comprehensive-2026-05-05.md MED §12 (auditor-F Issue 1) + HIGH §15 (auditor-F Issue 2) + HIGH §17 (auditor-H Issue 2). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:36:59 +02:00
import { formatErrorBanner } from '@/lib/api/toast-error';
import { useState, useEffect } from 'react';
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, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { apiFetch } from '@/lib/api/client';
interface PortFormProps {
open: boolean;
onOpenChange: (open: boolean) => void;
port?: {
id: string;
name: string;
slug: string;
logoUrl: string | null;
primaryColor: string | null;
defaultCurrency: string;
timezone: string;
isActive: boolean;
} | null;
onSuccess: () => void;
}
export function PortForm({ open, onOpenChange, port, onSuccess }: PortFormProps) {
const [name, setName] = useState('');
const [slug, setSlug] = useState('');
const [primaryColor, setPrimaryColor] = useState('#0F4C81');
const [defaultCurrency, setDefaultCurrency] = useState('USD');
const [timezone, setTimezone] = useState('America/Anguilla');
const [isActive, setIsActive] = useState(true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const isEdit = !!port;
useEffect(() => {
if (open) {
if (port) {
setName(port.name);
setSlug(port.slug);
setPrimaryColor(port.primaryColor ?? '#0F4C81');
setDefaultCurrency(port.defaultCurrency);
setTimezone(port.timezone);
setIsActive(port.isActive);
} else {
setName('');
setSlug('');
setPrimaryColor('#0F4C81');
setDefaultCurrency('USD');
setTimezone('America/Anguilla');
setIsActive(true);
}
setError(null);
}
}, [open, port]);
function handleNameChange(value: string) {
setName(value);
if (!isEdit) {
setSlug(
value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, ''),
);
}
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLoading(true);
try {
if (isEdit) {
await apiFetch(`/api/v1/admin/ports/${port.id}`, {
method: 'PATCH',
body: { name, slug, primaryColor, defaultCurrency, timezone, isActive },
});
} else {
await apiFetch('/api/v1/admin/ports', {
method: 'POST',
body: { name, slug, primaryColor, defaultCurrency, timezone },
});
}
onSuccess();
onOpenChange(false);
} catch (err: unknown) {
fix(audit-tier-2-routes): manual NextResponse.json error sweep + admin form banners Two final waves of error-surface hygiene closing the audit's MED §12 + HIGH §15 + HIGH §17 findings: * 50 route files swept (61 sites): manual NextResponse.json({error, status: 4xx|5xx}) early-returns replaced by typed throws + errorResponse(err) at the catch. - Super-admin gates (13 sites) use new requireSuperAdmin(ctx, action) helper from src/lib/api/helpers.ts so denials hit the audit log. - Path-param + body validation 400s become ValidationError throws. - 404s become NotFoundError or CodedError('NOT_FOUND') for AI feature-flag paths. - 11 manual 5xx returns now re-throw so error_events captures the request-id (the admin error inspector becomes usable from real incidents). - website-analytics 200-with-error anti-pattern flipped to 409 + UMAMI_NOT_CONFIGURED. 502 upstream paths use UMAMI_UPSTREAM_ERROR. - 11 sites intentionally preserved: storage/[token] anti-enumeration token-failure paths, webhook-secret 401, "Unknown port" 400 in public intake. * 7 admin forms (roles, users, ports, webhooks, custom-fields, document-templates, tags) gain a formatErrorBanner() helper from src/lib/api/toast-error.ts that builds a multi-line "Error code / Reference ID" banner — the rep can copy the request id when reporting a failed save. Banners get whitespace-pre-line so newlines render. Test status: 1168/1168 vitest, tsc clean. Refs: docs/audit-comprehensive-2026-05-05.md MED §12 (auditor-F Issue 1) + HIGH §15 (auditor-F Issue 2) + HIGH §17 (auditor-H Issue 2). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:36:59 +02:00
const message = formatErrorBanner(err);
setError(message);
} finally {
setLoading(false);
}
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="overflow-y-auto">
<SheetHeader>
<SheetTitle>{isEdit ? 'Edit Port' : 'New Port'}</SheetTitle>
</SheetHeader>
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
<div className="space-y-2">
<Label htmlFor="port-name">Name</Label>
<Input
id="port-name"
value={name}
onChange={(e) => handleNameChange(e.target.value)}
placeholder="Port Nimara"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="port-slug">Slug</Label>
<Input
id="port-slug"
value={slug}
onChange={(e) => setSlug(e.target.value)}
placeholder="port-nimara"
pattern="^[a-z0-9-]+$"
required
/>
<p className="text-xs text-muted-foreground">
Used in URLs. Lowercase letters, numbers, and hyphens only.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="port-color">Brand Color</Label>
<div className="flex items-center gap-2">
<input
type="color"
id="port-color"
value={primaryColor}
onChange={(e) => setPrimaryColor(e.target.value)}
className="h-9 w-9 rounded border cursor-pointer"
/>
<Input
value={primaryColor}
onChange={(e) => setPrimaryColor(e.target.value)}
placeholder="#0F4C81"
className="w-28 font-mono text-sm"
maxLength={7}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="port-currency">Currency</Label>
<Input
id="port-currency"
value={defaultCurrency}
onChange={(e) => setDefaultCurrency(e.target.value.toUpperCase())}
placeholder="USD"
maxLength={3}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="port-timezone">Timezone</Label>
<Input
id="port-timezone"
value={timezone}
onChange={(e) => setTimezone(e.target.value)}
placeholder="America/Anguilla"
required
/>
</div>
</div>
{isEdit && (
<div className="flex items-center justify-between rounded-lg border p-3">
<div>
<Label htmlFor="port-active">Port Active</Label>
<p className="text-xs text-muted-foreground">
Inactive ports are hidden from users
</p>
</div>
<Switch id="port-active" checked={isActive} onCheckedChange={setIsActive} />
</div>
)}
fix(audit-tier-2-routes): manual NextResponse.json error sweep + admin form banners Two final waves of error-surface hygiene closing the audit's MED §12 + HIGH §15 + HIGH §17 findings: * 50 route files swept (61 sites): manual NextResponse.json({error, status: 4xx|5xx}) early-returns replaced by typed throws + errorResponse(err) at the catch. - Super-admin gates (13 sites) use new requireSuperAdmin(ctx, action) helper from src/lib/api/helpers.ts so denials hit the audit log. - Path-param + body validation 400s become ValidationError throws. - 404s become NotFoundError or CodedError('NOT_FOUND') for AI feature-flag paths. - 11 manual 5xx returns now re-throw so error_events captures the request-id (the admin error inspector becomes usable from real incidents). - website-analytics 200-with-error anti-pattern flipped to 409 + UMAMI_NOT_CONFIGURED. 502 upstream paths use UMAMI_UPSTREAM_ERROR. - 11 sites intentionally preserved: storage/[token] anti-enumeration token-failure paths, webhook-secret 401, "Unknown port" 400 in public intake. * 7 admin forms (roles, users, ports, webhooks, custom-fields, document-templates, tags) gain a formatErrorBanner() helper from src/lib/api/toast-error.ts that builds a multi-line "Error code / Reference ID" banner — the rep can copy the request id when reporting a failed save. Banners get whitespace-pre-line so newlines render. Test status: 1168/1168 vitest, tsc clean. Refs: docs/audit-comprehensive-2026-05-05.md MED §12 (auditor-F Issue 1) + HIGH §15 (auditor-F Issue 2) + HIGH §17 (auditor-H Issue 2). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:36:59 +02:00
{error && <p className="whitespace-pre-line text-sm text-destructive">{error}</p>}
<SheetFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={loading}
>
Cancel
</Button>
<Button type="submit" disabled={loading || !name.trim() || !slug.trim()}>
{loading ? 'Saving...' : isEdit ? 'Save Changes' : 'Create Port'}
</Button>
</SheetFooter>
</form>
</SheetContent>
</Sheet>
);
}