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>
This commit is contained in:
Matt Ciaccio
2026-05-06 14:58:17 +02:00
parent 8cdee99310
commit c90876abad
22 changed files with 1703 additions and 54 deletions

View File

@@ -0,0 +1,114 @@
import { NextResponse } from 'next/server';
import { and, eq, isNull, gte, sql } from 'drizzle-orm';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { interests } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths';
import { clients } from '@/lib/db/schema/clients';
import { websiteSubmissions } from '@/lib/db/schema/website-submissions';
import { errorResponse } from '@/lib/errors';
import { PIPELINE_STAGES } from '@/lib/constants';
export const GET = withAuth(
withPermission('reports', 'view_dashboard', async (_req, ctx) => {
try {
const portId = ctx.portId;
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const [pipelineRows, berthStatusRows, totals, recent] = await Promise.all([
db
.select({
stage: interests.pipelineStage,
count: sql<number>`count(*)::int`,
})
.from(interests)
.where(and(eq(interests.portId, portId), isNull(interests.archivedAt)))
.groupBy(interests.pipelineStage),
db
.select({
status: berths.status,
count: sql<number>`count(*)::int`,
})
.from(berths)
.where(eq(berths.portId, portId))
.groupBy(berths.status),
Promise.all([
db
.select({ count: sql<number>`count(*)::int` })
.from(clients)
.where(and(eq(clients.portId, portId), isNull(clients.archivedAt))),
db
.select({ count: sql<number>`count(*)::int` })
.from(interests)
.where(and(eq(interests.portId, portId), isNull(interests.archivedAt))),
db
.select({ count: sql<number>`count(*)::int` })
.from(berths)
.where(eq(berths.portId, portId)),
]),
Promise.all([
db
.select({ count: sql<number>`count(*)::int` })
.from(websiteSubmissions)
.where(
and(
eq(websiteSubmissions.portId, portId),
gte(websiteSubmissions.receivedAt, sevenDaysAgo),
),
),
db
.select({ count: sql<number>`count(*)::int` })
.from(interests)
.where(
and(
eq(interests.portId, portId),
eq(interests.pipelineStage, 'completed'),
gte(interests.updatedAt, thirtyDaysAgo),
),
),
]),
]);
const pipeline = Object.fromEntries(PIPELINE_STAGES.map((s) => [s, 0])) as Record<
string,
number
>;
for (const row of pipelineRows) pipeline[row.stage] = row.count;
const berthStatus: Record<string, number> = {
available: 0,
under_offer: 0,
sold: 0,
};
for (const row of berthStatusRows) berthStatus[row.status] = row.count;
const totalClients = totals[0][0]?.count ?? 0;
const totalInterests = totals[1][0]?.count ?? 0;
const totalBerths = totals[2][0]?.count ?? 0;
const newInquiries7d = recent[0][0]?.count ?? 0;
const completed30d = recent[1][0]?.count ?? 0;
const closedTotal = pipeline['completed'] ?? 0;
const openTotal = totalInterests - closedTotal;
const conversionPct =
totalInterests > 0 ? Math.round((closedTotal / totalInterests) * 100) : 0;
return NextResponse.json({
data: {
totals: { totalClients, totalInterests, totalBerths },
recent: { newInquiries7d, completed30d },
pipeline,
berthStatus,
conversion: { closedTotal, openTotal, conversionPct },
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,68 @@
import { NextResponse } from 'next/server';
import { and, desc, eq, isNotNull, isNull, sql, type SQL } from 'drizzle-orm';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { db } from '@/lib/db';
import { documentSends } from '@/lib/db/schema/brochures';
import { errorResponse } from '@/lib/errors';
const querySchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(50),
status: z.enum(['all', 'sent', 'failed']).default('all'),
kind: z.enum(['berth_pdf', 'brochure']).optional(),
cursorAt: z.string().optional(),
cursorId: z.string().optional(),
});
export const GET = withAuth(
withPermission('admin', 'view_audit_log', async (req, ctx) => {
try {
const query = parseQuery(req, querySchema);
const conds: SQL[] = [eq(documentSends.portId, ctx.portId)];
if (query.kind) conds.push(eq(documentSends.documentKind, query.kind));
if (query.status === 'failed') conds.push(isNotNull(documentSends.failedAt));
if (query.status === 'sent') conds.push(isNull(documentSends.failedAt));
if (query.cursorAt && query.cursorId) {
const cursorAt = new Date(query.cursorAt).toISOString();
conds.push(
sql`(${documentSends.sentAt}, ${documentSends.id}) < (${cursorAt}::timestamptz, ${query.cursorId})`,
);
}
const rows = await db
.select()
.from(documentSends)
.where(and(...conds))
.orderBy(desc(documentSends.sentAt), desc(documentSends.id))
.limit(query.limit + 1);
const hasMore = rows.length > query.limit;
const page = hasMore ? rows.slice(0, query.limit) : rows;
const last = page[page.length - 1];
const nextCursor =
hasMore && last ? { sentAt: last.sentAt.toISOString(), id: last.id } : null;
// Counts for the filter chips
const sentCountRows = await db
.select({ count: sql<number>`count(*)::int` })
.from(documentSends)
.where(and(eq(documentSends.portId, ctx.portId), isNull(documentSends.failedAt)));
const failedCountRows = await db
.select({ count: sql<number>`count(*)::int` })
.from(documentSends)
.where(and(eq(documentSends.portId, ctx.portId), isNotNull(documentSends.failedAt)));
const counts = {
sent: sentCountRows[0]?.count ?? 0,
failed: failedCountRows[0]?.count ?? 0,
all: (sentCountRows[0]?.count ?? 0) + (failedCountRows[0]?.count ?? 0),
};
return NextResponse.json({ data: page, pagination: { nextCursor }, counts });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,91 @@
import { NextResponse } from 'next/server';
import { eq, inArray } from 'drizzle-orm';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import {
TEMPLATE_CATALOG,
TEMPLATE_KEYS,
settingKeyForSubject,
type TemplateKey,
} from '@/lib/email/template-catalog';
import { upsertSetting, deleteSetting } from '@/lib/services/settings.service';
import { errorResponse } from '@/lib/errors';
const upsertSchema = z.object({
key: z.enum(TEMPLATE_KEYS),
subject: z.string().max(300).nullable(),
});
export const GET = withAuth(
withPermission('admin', 'manage_settings', async (_req, ctx) => {
try {
const subjectKeys = TEMPLATE_KEYS.map(settingKeyForSubject);
const rows = await db
.select({
key: systemSettings.key,
value: systemSettings.value,
portId: systemSettings.portId,
})
.from(systemSettings)
.where(inArray(systemSettings.key, subjectKeys));
const byKey = new Map<string, { port?: string; global?: string }>();
for (const r of rows) {
const slot = byKey.get(r.key) ?? {};
if (r.portId === ctx.portId && typeof r.value === 'string') slot.port = r.value;
if (r.portId === null && typeof r.value === 'string') slot.global = r.value;
byKey.set(r.key, slot);
}
const data = TEMPLATE_KEYS.map((key) => {
const meta = TEMPLATE_CATALOG[key];
const settingKey = settingKeyForSubject(key);
const overrides = byKey.get(settingKey) ?? {};
const effective = overrides.port ?? overrides.global ?? meta.defaultSubject;
return {
key,
label: meta.label,
description: meta.description,
mergeTokens: meta.mergeTokens,
defaultSubject: meta.defaultSubject,
subjectOverride: overrides.port ?? null,
effectiveSubject: effective,
};
});
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);
export const PUT = withAuth(
withPermission('admin', 'manage_settings', async (req, ctx) => {
try {
const body = await parseBody(req, upsertSchema);
const settingKey = settingKeyForSubject(body.key as TemplateKey);
const meta = {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
};
if (body.subject === null || body.subject === '') {
// Clear the override (and only at the per-port level — never touch global).
await deleteSetting(settingKey, ctx.portId, meta);
} else {
await upsertSetting(settingKey, body.subject, ctx.portId, meta);
}
return NextResponse.json({ data: { ok: true } });
} catch (error) {
return errorResponse(error);
}
}),
);
void eq;

View File

@@ -0,0 +1,67 @@
import { NextResponse } from 'next/server';
import { and, desc, eq, lt, sql, type SQL } from 'drizzle-orm';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { db } from '@/lib/db';
import { websiteSubmissions } from '@/lib/db/schema/website-submissions';
import { errorResponse } from '@/lib/errors';
const querySchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(50),
kind: z.enum(['berth_inquiry', 'residence_inquiry', 'contact_form']).optional(),
cursorAt: z.string().optional(),
cursorId: z.string().optional(),
});
export const GET = withAuth(
withPermission('admin', 'view_audit_log', async (req, ctx) => {
try {
const query = parseQuery(req, querySchema);
const conds: SQL[] = [eq(websiteSubmissions.portId, ctx.portId)];
if (query.kind) conds.push(eq(websiteSubmissions.kind, query.kind));
if (query.cursorAt && query.cursorId) {
const cursorAt = new Date(query.cursorAt).toISOString();
conds.push(
sql`(${websiteSubmissions.receivedAt}, ${websiteSubmissions.id}) < (${cursorAt}::timestamptz, ${query.cursorId})`,
);
}
const rows = await db
.select()
.from(websiteSubmissions)
.where(and(...conds))
.orderBy(desc(websiteSubmissions.receivedAt), desc(websiteSubmissions.id))
.limit(query.limit + 1);
const hasMore = rows.length > query.limit;
const page = hasMore ? rows.slice(0, query.limit) : rows;
const last = page[page.length - 1];
const nextCursor =
hasMore && last ? { receivedAt: last.receivedAt.toISOString(), id: last.id } : null;
// Lightweight count by kind for the page header
const countsRows = await db
.select({ kind: websiteSubmissions.kind, count: sql<number>`count(*)::int` })
.from(websiteSubmissions)
.where(eq(websiteSubmissions.portId, ctx.portId))
.groupBy(websiteSubmissions.kind);
const counts = Object.fromEntries(countsRows.map((r) => [r.kind, r.count])) as Record<
string,
number
>;
return NextResponse.json({
data: page,
pagination: { nextCursor },
counts,
});
} catch (error) {
return errorResponse(error);
}
}),
);
// Suppress lt unused-import lint
void lt;