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:
2026-04-08 15:53:33 -04:00
parent f60159e91a
commit c8320023cc
12 changed files with 1096 additions and 28 deletions

View 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!;
}

View 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,
});
}

View 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>;

View 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>;