Implement admin ports and system settings management
- Port CRUD: list, create, update with branding, currency, timezone - System settings: upsert key-value pairs per port with known settings UI (AI feature flags, invoice discount, pipeline weights, berth rules) - Settings manager with toggle switches, number inputs, and JSON editors - Replace both stub pages with real implementations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,16 +1,5 @@
|
||||
import { PortList } from '@/components/admin/ports/port-list';
|
||||
|
||||
export default function PortManagementPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Port Management</h1>
|
||||
<p className="text-muted-foreground">Manage port locations and configurations</p>
|
||||
</div>
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12">
|
||||
<p className="text-lg font-medium text-muted-foreground">Coming in Layer 2</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This feature will be implemented in the next phase.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <PortList />;
|
||||
}
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
import { SettingsManager } from '@/components/admin/settings/settings-manager';
|
||||
|
||||
export default function SystemSettingsPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">System Settings</h1>
|
||||
<p className="text-muted-foreground">Configure system-wide settings</p>
|
||||
</div>
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12">
|
||||
<p className="text-lg font-medium text-muted-foreground">Coming in Layer 2</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This feature will be implemented in the next phase.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <SettingsManager />;
|
||||
}
|
||||
|
||||
35
src/app/api/v1/admin/ports/[id]/route.ts
Normal file
35
src/app/api/v1/admin/ports/[id]/route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { getPort, updatePort } from '@/lib/services/ports.service';
|
||||
import { updatePortSchema } from '@/lib/validators/ports';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, _ctx, params) => {
|
||||
try {
|
||||
const data = await getPort(params.id!);
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const PATCH = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, updatePortSchema);
|
||||
const data = await updatePort(params.id!, body, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
35
src/app/api/v1/admin/ports/route.ts
Normal file
35
src/app/api/v1/admin/ports/route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { listPorts, createPort } from '@/lib/services/ports.service';
|
||||
import { createPortSchema } from '@/lib/validators/ports';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async () => {
|
||||
try {
|
||||
const data = await listPorts();
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const POST = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx) => {
|
||||
try {
|
||||
const body = await parseBody(req, createPortSchema);
|
||||
const data = await createPort(body, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
52
src/app/api/v1/admin/settings/route.ts
Normal file
52
src/app/api/v1/admin/settings/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { listSettings, upsertSetting, deleteSetting } from '@/lib/services/settings.service';
|
||||
import { upsertSettingSchema, deleteSettingSchema } from '@/lib/validators/settings';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx) => {
|
||||
try {
|
||||
const data = await listSettings(ctx.portId);
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const PUT = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx) => {
|
||||
try {
|
||||
const { key, value } = await parseBody(req, upsertSettingSchema);
|
||||
const data = await upsertSetting(key, value, ctx.portId, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const DELETE = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx) => {
|
||||
try {
|
||||
const { key } = await parseBody(req, deleteSettingSchema);
|
||||
await deleteSetting(key, ctx.portId, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
209
src/components/admin/ports/port-form.tsx
Normal file
209
src/components/admin/ports/port-form.tsx
Normal file
@@ -0,0 +1,209 @@
|
||||
'use client';
|
||||
|
||||
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) {
|
||||
const message = err instanceof Error ? err.message : 'Something went wrong';
|
||||
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>
|
||||
)}
|
||||
|
||||
{error && <p className="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>
|
||||
);
|
||||
}
|
||||
147
src/components/admin/ports/port-list.tsx
Normal file
147
src/components/admin/ports/port-list.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { type ColumnDef } from '@tanstack/react-table';
|
||||
import { Pencil, Plus } from 'lucide-react';
|
||||
|
||||
import { DataTable } from '@/components/shared/data-table';
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { PortForm } from './port-form';
|
||||
|
||||
interface PortRow {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
logoUrl: string | null;
|
||||
primaryColor: string | null;
|
||||
defaultCurrency: string;
|
||||
timezone: string;
|
||||
isActive: boolean;
|
||||
settings: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export function PortList() {
|
||||
const [ports, setPorts] = useState<PortRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editingPort, setEditingPort] = useState<PortRow | null>(null);
|
||||
|
||||
const fetchPorts = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiFetch<{ data: PortRow[] }>('/api/v1/admin/ports');
|
||||
setPorts(res.data);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchPorts();
|
||||
}, [fetchPorts]);
|
||||
|
||||
function handleNewPort() {
|
||||
setEditingPort(null);
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function handleEditPort(port: PortRow) {
|
||||
setEditingPort(port);
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
const columns: ColumnDef<PortRow, unknown>[] = [
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Name',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
{row.original.primaryColor && (
|
||||
<span
|
||||
className="inline-block h-3 w-3 rounded-full"
|
||||
style={{ backgroundColor: row.original.primaryColor }}
|
||||
/>
|
||||
)}
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'slug',
|
||||
header: 'Slug',
|
||||
cell: ({ row }) => (
|
||||
<code className="text-xs bg-muted px-1.5 py-0.5 rounded">{row.original.slug}</code>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'defaultCurrency',
|
||||
header: 'Currency',
|
||||
},
|
||||
{
|
||||
accessorKey: 'timezone',
|
||||
header: 'Timezone',
|
||||
},
|
||||
{
|
||||
accessorKey: 'isActive',
|
||||
header: 'Status',
|
||||
cell: ({ row }) =>
|
||||
row.original.isActive ? (
|
||||
<Badge variant="default" className="bg-green-600">
|
||||
Active
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="destructive">Inactive</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
header: '',
|
||||
cell: ({ row }) => (
|
||||
<Button variant="ghost" size="sm" onClick={() => handleEditPort(row.original)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
<span className="sr-only">Edit</span>
|
||||
</Button>
|
||||
),
|
||||
enableSorting: false,
|
||||
size: 60,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title="Port Management"
|
||||
description="Manage marina ports and their configuration"
|
||||
actions={
|
||||
<Button onClick={handleNewPort}>
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
New Port
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={ports}
|
||||
isLoading={loading}
|
||||
getRowId={(row) => row.id}
|
||||
emptyState={
|
||||
<div className="text-center py-8">
|
||||
<p className="text-muted-foreground">No ports configured.</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<PortForm
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
port={editingPort}
|
||||
onSuccess={fetchPorts}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
340
src/components/admin/settings/settings-manager.tsx
Normal file
340
src/components/admin/settings/settings-manager.tsx
Normal file
@@ -0,0 +1,340 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Trash2, Plus, Save } from 'lucide-react';
|
||||
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
|
||||
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 { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
interface Setting {
|
||||
key: string;
|
||||
value: unknown;
|
||||
portId: string | null;
|
||||
updatedBy: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Well-known settings with their display metadata */
|
||||
const KNOWN_SETTINGS: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
description: string;
|
||||
type: 'boolean' | 'number' | 'json';
|
||||
defaultValue: unknown;
|
||||
}> = [
|
||||
{
|
||||
key: 'ai_interest_scoring',
|
||||
label: 'AI Interest Scoring',
|
||||
description: 'Enable AI-powered interest scoring based on engagement signals',
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
},
|
||||
{
|
||||
key: 'ai_email_drafts',
|
||||
label: 'AI Email Drafts',
|
||||
description: 'Enable AI-assisted email draft generation',
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
},
|
||||
{
|
||||
key: 'invoice_net10_discount',
|
||||
label: 'Net-10 Invoice Discount (%)',
|
||||
description: 'Discount percentage applied when payment terms are net-10',
|
||||
type: 'number',
|
||||
defaultValue: 2,
|
||||
},
|
||||
{
|
||||
key: 'pipeline_weights',
|
||||
label: 'Pipeline Stage Weights',
|
||||
description: 'Probability weights for revenue forecast by pipeline stage (JSON)',
|
||||
type: 'json',
|
||||
defaultValue: {
|
||||
open: 0.05,
|
||||
details_sent: 0.1,
|
||||
in_communication: 0.2,
|
||||
signed_eoi_nda: 0.4,
|
||||
deposit_10pct: 0.6,
|
||||
contract: 0.8,
|
||||
completed: 1.0,
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'berth_rules',
|
||||
label: 'Berth Status Rules',
|
||||
description: 'Auto/suggest/off rules for berth status transitions (JSON)',
|
||||
type: 'json',
|
||||
defaultValue: [],
|
||||
},
|
||||
];
|
||||
|
||||
export function SettingsManager() {
|
||||
const [portSettings, setPortSettings] = useState<Setting[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
const [values, setValues] = useState<Record<string, unknown>>({});
|
||||
const [customKey, setCustomKey] = useState('');
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
|
||||
const fetchSettings = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiFetch<{ data: { portSettings: Setting[]; globalSettings: Setting[] } }>(
|
||||
'/api/v1/admin/settings',
|
||||
);
|
||||
setPortSettings(res.data.portSettings);
|
||||
|
||||
// Build values map from existing settings
|
||||
const vals: Record<string, unknown> = {};
|
||||
for (const s of res.data.portSettings) {
|
||||
vals[s.key] = s.value;
|
||||
}
|
||||
setValues(vals);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchSettings();
|
||||
}, [fetchSettings]);
|
||||
|
||||
async function saveSetting(key: string, value: unknown) {
|
||||
setSaving(key);
|
||||
try {
|
||||
await apiFetch('/api/v1/admin/settings', {
|
||||
method: 'PUT',
|
||||
body: { key, value },
|
||||
});
|
||||
await fetchSettings();
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteSetting(key: string) {
|
||||
await apiFetch('/api/v1/admin/settings', {
|
||||
method: 'DELETE',
|
||||
body: { key },
|
||||
});
|
||||
await fetchSettings();
|
||||
}
|
||||
|
||||
async function handleAddCustom() {
|
||||
if (!customKey.trim()) return;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(customValue);
|
||||
} catch {
|
||||
parsed = customValue;
|
||||
}
|
||||
await saveSetting(customKey, parsed);
|
||||
setCustomKey('');
|
||||
setCustomValue('');
|
||||
}
|
||||
|
||||
function getEffectiveValue(key: string, defaultValue: unknown): unknown {
|
||||
return values[key] ?? defaultValue;
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div>
|
||||
<PageHeader title="System Settings" description="Configure system behavior for this port" />
|
||||
<div className="flex items-center justify-center py-12 text-muted-foreground">
|
||||
Loading...
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Custom settings = port settings that aren't in KNOWN_SETTINGS
|
||||
const knownKeys = new Set(KNOWN_SETTINGS.map((s) => s.key));
|
||||
const customSettings = portSettings.filter((s) => !knownKeys.has(s.key));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader title="System Settings" description="Configure system behavior for this port" />
|
||||
|
||||
<div className="space-y-6 mt-6">
|
||||
{/* Feature Flags */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Feature Flags</CardTitle>
|
||||
<CardDescription>Enable or disable optional features</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{KNOWN_SETTINGS.filter((s) => s.type === 'boolean').map((setting) => (
|
||||
<div key={setting.key} className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>{setting.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{setting.description}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={getEffectiveValue(setting.key, setting.defaultValue) === true}
|
||||
disabled={saving === setting.key}
|
||||
onCheckedChange={(checked) => saveSetting(setting.key, checked)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Numeric Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Business Rules</CardTitle>
|
||||
<CardDescription>Configure financial and operational parameters</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{KNOWN_SETTINGS.filter((s) => s.type === 'number').map((setting) => (
|
||||
<div key={setting.key} className="flex items-center justify-between gap-4">
|
||||
<div className="flex-1">
|
||||
<Label>{setting.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{setting.description}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
className="w-24"
|
||||
value={String(getEffectiveValue(setting.key, setting.defaultValue) ?? '')}
|
||||
onChange={(e) =>
|
||||
setValues((prev) => ({
|
||||
...prev,
|
||||
[setting.key]: parseFloat(e.target.value) || 0,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={saving === setting.key}
|
||||
onClick={() =>
|
||||
saveSetting(setting.key, values[setting.key] ?? setting.defaultValue)
|
||||
}
|
||||
>
|
||||
<Save className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* JSON Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Advanced Configuration</CardTitle>
|
||||
<CardDescription>
|
||||
JSON-based settings for pipeline weights and berth rules
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{KNOWN_SETTINGS.filter((s) => s.type === 'json').map((setting) => {
|
||||
const currentValue = getEffectiveValue(setting.key, setting.defaultValue);
|
||||
const jsonStr =
|
||||
values[`${setting.key}_edit`] !== undefined
|
||||
? String(values[`${setting.key}_edit`])
|
||||
: JSON.stringify(currentValue, null, 2);
|
||||
return (
|
||||
<div key={setting.key} className="space-y-2">
|
||||
<Label>{setting.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{setting.description}</p>
|
||||
<Textarea
|
||||
className="font-mono text-xs"
|
||||
rows={6}
|
||||
value={jsonStr}
|
||||
onChange={(e) =>
|
||||
setValues((prev) => ({ ...prev, [`${setting.key}_edit`]: e.target.value }))
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={saving === setting.key}
|
||||
onClick={() => {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
String(values[`${setting.key}_edit`] ?? JSON.stringify(currentValue)),
|
||||
);
|
||||
void saveSetting(setting.key, parsed);
|
||||
} catch {
|
||||
// invalid JSON — do nothing
|
||||
}
|
||||
}}
|
||||
>
|
||||
{saving === setting.key ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Custom Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Custom Settings</CardTitle>
|
||||
<CardDescription>Additional key-value settings for this port</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{customSettings.map((setting) => (
|
||||
<div key={setting.key} className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<code className="text-sm font-mono">{setting.key}</code>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{typeof setting.value === 'object'
|
||||
? JSON.stringify(setting.value)
|
||||
: String(setting.value)}
|
||||
</p>
|
||||
</div>
|
||||
<ConfirmationDialog
|
||||
trigger={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
}
|
||||
title="Delete Setting"
|
||||
description={`Delete "${setting.key}"? This may affect system behavior.`}
|
||||
confirmLabel="Delete"
|
||||
onConfirm={() => handleDeleteSetting(setting.key)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Key"
|
||||
value={customKey}
|
||||
onChange={(e) => setCustomKey(e.target.value)}
|
||||
className="w-40"
|
||||
/>
|
||||
<Input
|
||||
placeholder="Value (JSON or string)"
|
||||
value={customValue}
|
||||
onChange={(e) => setCustomValue(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button variant="outline" onClick={handleAddCustom} disabled={!customKey.trim()}>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
110
src/lib/services/ports.service.ts
Normal file
110
src/lib/services/ports.service.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { ports } from '@/lib/db/schema';
|
||||
import type { PortSettings } from '@/lib/db/schema/ports';
|
||||
import { createAuditLog } from '@/lib/audit';
|
||||
import { ConflictError, NotFoundError } from '@/lib/errors';
|
||||
import { emitToRoom } from '@/lib/socket/server';
|
||||
import type { CreatePortInput, UpdatePortInput } from '@/lib/validators/ports';
|
||||
|
||||
interface AuditMeta {
|
||||
userId: string;
|
||||
portId: string;
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
}
|
||||
|
||||
export async function listPorts() {
|
||||
return db.select().from(ports).orderBy(ports.name);
|
||||
}
|
||||
|
||||
export async function getPort(id: string) {
|
||||
const port = await db.query.ports.findFirst({
|
||||
where: eq(ports.id, id),
|
||||
});
|
||||
if (!port) throw new NotFoundError('Port');
|
||||
return port;
|
||||
}
|
||||
|
||||
export async function createPort(data: CreatePortInput, meta: AuditMeta) {
|
||||
const existing = await db.query.ports.findFirst({
|
||||
where: eq(ports.slug, data.slug),
|
||||
});
|
||||
if (existing) {
|
||||
throw new ConflictError(`A port with slug "${data.slug}" already exists`);
|
||||
}
|
||||
|
||||
const [port] = await db
|
||||
.insert(ports)
|
||||
.values({
|
||||
name: data.name,
|
||||
slug: data.slug,
|
||||
logoUrl: data.logoUrl ?? null,
|
||||
primaryColor: data.primaryColor ?? null,
|
||||
defaultCurrency: data.defaultCurrency,
|
||||
timezone: data.timezone,
|
||||
})
|
||||
.returning();
|
||||
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId: meta.portId,
|
||||
action: 'create',
|
||||
entityType: 'port',
|
||||
entityId: port!.id,
|
||||
newValue: { name: port!.name, slug: port!.slug },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
|
||||
return port!;
|
||||
}
|
||||
|
||||
export async function updatePort(id: string, data: UpdatePortInput, meta: AuditMeta) {
|
||||
const port = await db.query.ports.findFirst({
|
||||
where: eq(ports.id, id),
|
||||
});
|
||||
if (!port) throw new NotFoundError('Port');
|
||||
|
||||
if (data.slug && data.slug !== port.slug) {
|
||||
const conflict = await db.query.ports.findFirst({
|
||||
where: eq(ports.slug, data.slug),
|
||||
});
|
||||
if (conflict) {
|
||||
throw new ConflictError(`A port with slug "${data.slug}" already exists`);
|
||||
}
|
||||
}
|
||||
|
||||
const updates: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (data.name !== undefined) updates.name = data.name;
|
||||
if (data.slug !== undefined) updates.slug = data.slug;
|
||||
if (data.logoUrl !== undefined) updates.logoUrl = data.logoUrl;
|
||||
if (data.primaryColor !== undefined) updates.primaryColor = data.primaryColor;
|
||||
if (data.defaultCurrency !== undefined) updates.defaultCurrency = data.defaultCurrency;
|
||||
if (data.timezone !== undefined) updates.timezone = data.timezone;
|
||||
if (data.isActive !== undefined) updates.isActive = data.isActive;
|
||||
if (data.settings !== undefined) updates.settings = data.settings as PortSettings;
|
||||
|
||||
const [updated] = await db.update(ports).set(updates).where(eq(ports.id, id)).returning();
|
||||
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId: meta.portId,
|
||||
action: 'update',
|
||||
entityType: 'port',
|
||||
entityId: id,
|
||||
oldValue: { name: port.name, slug: port.slug, isActive: port.isActive },
|
||||
newValue: { name: updated!.name, slug: updated!.slug, isActive: updated!.isActive },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
|
||||
emitToRoom(`port:${id}`, 'system:alert', {
|
||||
alertType: 'port:updated',
|
||||
message: `Port "${updated!.name}" updated`,
|
||||
severity: 'info',
|
||||
});
|
||||
|
||||
return updated!;
|
||||
}
|
||||
107
src/lib/services/settings.service.ts
Normal file
107
src/lib/services/settings.service.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { and, eq, isNull } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { systemSettings } from '@/lib/db/schema';
|
||||
import { createAuditLog } from '@/lib/audit';
|
||||
import { NotFoundError } from '@/lib/errors';
|
||||
import { emitToRoom } from '@/lib/socket/server';
|
||||
|
||||
interface AuditMeta {
|
||||
userId: string;
|
||||
portId: string;
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
}
|
||||
|
||||
export async function listSettings(portId: string) {
|
||||
// Get port-specific settings
|
||||
const portSettings = await db
|
||||
.select()
|
||||
.from(systemSettings)
|
||||
.where(eq(systemSettings.portId, portId))
|
||||
.orderBy(systemSettings.key);
|
||||
|
||||
// Get global settings (portId is null)
|
||||
const globalSettings = await db
|
||||
.select()
|
||||
.from(systemSettings)
|
||||
.where(isNull(systemSettings.portId))
|
||||
.orderBy(systemSettings.key);
|
||||
|
||||
return { portSettings, globalSettings };
|
||||
}
|
||||
|
||||
export async function getSetting(key: string, portId: string) {
|
||||
// Try port-specific first, fall back to global
|
||||
const setting = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
|
||||
});
|
||||
if (setting) return setting;
|
||||
|
||||
const global = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), isNull(systemSettings.portId)),
|
||||
});
|
||||
return global ?? null;
|
||||
}
|
||||
|
||||
export async function upsertSetting(key: string, value: unknown, portId: string, meta: AuditMeta) {
|
||||
const existing = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await db
|
||||
.update(systemSettings)
|
||||
.set({ value, updatedBy: meta.userId, updatedAt: new Date() })
|
||||
.where(and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)));
|
||||
} else {
|
||||
await db.insert(systemSettings).values({
|
||||
key,
|
||||
value,
|
||||
portId,
|
||||
updatedBy: meta.userId,
|
||||
});
|
||||
}
|
||||
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId,
|
||||
action: existing ? 'update' : 'create',
|
||||
entityType: 'setting',
|
||||
entityId: key,
|
||||
oldValue: existing ? { value: existing.value } : undefined,
|
||||
newValue: { value },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
|
||||
emitToRoom(`port:${portId}`, 'system:alert', {
|
||||
alertType: 'setting:updated',
|
||||
message: `Setting "${key}" updated`,
|
||||
severity: 'info',
|
||||
});
|
||||
|
||||
return { key, value, portId };
|
||||
}
|
||||
|
||||
export async function deleteSetting(key: string, portId: string, meta: AuditMeta) {
|
||||
const existing = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
|
||||
});
|
||||
if (!existing) throw new NotFoundError('Setting');
|
||||
|
||||
await db
|
||||
.delete(systemSettings)
|
||||
.where(and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)));
|
||||
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId,
|
||||
action: 'delete',
|
||||
entityType: 'setting',
|
||||
entityId: key,
|
||||
oldValue: { value: existing.value },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
}
|
||||
41
src/lib/validators/ports.ts
Normal file
41
src/lib/validators/ports.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const createPortSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
slug: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.regex(/^[a-z0-9-]+$/, 'Slug must be lowercase alphanumeric with hyphens'),
|
||||
logoUrl: z.string().url().optional(),
|
||||
primaryColor: z
|
||||
.string()
|
||||
.regex(/^#[0-9a-fA-F]{6}$/)
|
||||
.optional(),
|
||||
defaultCurrency: z.string().length(3).default('USD'),
|
||||
timezone: z.string().min(1).default('America/Anguilla'),
|
||||
});
|
||||
|
||||
export type CreatePortInput = z.infer<typeof createPortSchema>;
|
||||
|
||||
export const updatePortSchema = z.object({
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
slug: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.regex(/^[a-z0-9-]+$/, 'Slug must be lowercase alphanumeric with hyphens')
|
||||
.optional(),
|
||||
logoUrl: z.string().url().nullable().optional(),
|
||||
primaryColor: z
|
||||
.string()
|
||||
.regex(/^#[0-9a-fA-F]{6}$/)
|
||||
.nullable()
|
||||
.optional(),
|
||||
defaultCurrency: z.string().length(3).optional(),
|
||||
timezone: z.string().min(1).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
settings: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
|
||||
export type UpdatePortInput = z.infer<typeof updatePortSchema>;
|
||||
14
src/lib/validators/settings.ts
Normal file
14
src/lib/validators/settings.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const upsertSettingSchema = z.object({
|
||||
key: z.string().min(1).max(100),
|
||||
value: z.unknown(),
|
||||
});
|
||||
|
||||
export type UpsertSettingInput = z.infer<typeof upsertSettingSchema>;
|
||||
|
||||
export const deleteSettingSchema = z.object({
|
||||
key: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
export type DeleteSettingInput = z.infer<typeof deleteSettingSchema>;
|
||||
Reference in New Issue
Block a user