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:
@@ -1,14 +1,64 @@
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
export default function BackupManagementPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="Backup Management" description="Manage system backups and restoration" />
|
||||
<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 4</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This feature will be implemented in the next phase.
|
||||
</p>
|
||||
<div>
|
||||
<PageHeader
|
||||
title="Backup & Restore"
|
||||
description="How backups are taken today and what an in-app backup admin will look like."
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 mt-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Current backup posture</CardTitle>
|
||||
<CardDescription>
|
||||
Database snapshots run outside the app — there is no in-app trigger yet.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<p>
|
||||
<strong>PostgreSQL:</strong> snapshotted by the platform’s nightly{' '}
|
||||
<code>pg_dump</code> job. Retention is set at the infrastructure layer (see{' '}
|
||||
<code>docs/operations/</code> if a runbook exists). Restores are manual.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Object storage:</strong> when{' '}
|
||||
<code>system_settings.storage_backend = ‘s3’</code>, the bucket is
|
||||
versioned by the provider. When the filesystem backend is in use, the host’s
|
||||
snapshot policy is the only safety net — switch to s3 before relying on point-in-time
|
||||
recovery.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Redis / queue state:</strong> ephemeral. Failed jobs sit on the{' '}
|
||||
<code>removeOnFail</code> retention window (7 days) and then disappear. Anything
|
||||
durable belongs in PostgreSQL.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>What this page will become</CardTitle>
|
||||
<CardDescription>Planned admin surface, prioritised in upcoming work.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>List recent snapshot files with timestamp, size, and origin (cron vs manual).</li>
|
||||
<li>“Take backup now” button that enqueues a maintenance job.</li>
|
||||
<li>
|
||||
Per-port logical export (“give me everything for port-nimara”) for
|
||||
compliance.
|
||||
</li>
|
||||
<li>Restore preview that shows row-counts that would change before commit.</li>
|
||||
<li>GDPR per-client export bundled here.</li>
|
||||
</ul>
|
||||
<p className="text-xs text-muted-foreground pt-2">
|
||||
Until this lands, treat ops/devops as the source of truth for backup state.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { EmailTemplatesAdmin } from '@/components/admin/email-templates-admin';
|
||||
|
||||
export default function EmailTemplatesPage() {
|
||||
return <EmailTemplatesAdmin />;
|
||||
}
|
||||
@@ -1,14 +1,75 @@
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
export default function DataImportPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="Data Import" description="Import data from external sources" />
|
||||
<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 4</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This feature will be implemented in the next phase.
|
||||
</p>
|
||||
<div>
|
||||
<PageHeader
|
||||
title="Data import"
|
||||
description="What you can import today and what an in-app importer will look like."
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 mt-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Available imports today</CardTitle>
|
||||
<CardDescription>Run from the command line until the UI catches up.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<div>
|
||||
<p>
|
||||
<strong>Berths from NocoDB:</strong>
|
||||
</p>
|
||||
<pre className="bg-muted/40 rounded-md p-2 text-xs mt-1 overflow-auto">
|
||||
pnpm tsx scripts/import-berths-from-nocodb.ts --apply --port-slug port-nimara
|
||||
</pre>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Idempotent. Skips rows where <code>updated_at > last_imported_at</code> unless
|
||||
you pass <code>--force</code>. Add <code>--update-snapshot</code> to also rewrite{' '}
|
||||
<code>src/lib/db/seed-data/berths.json</code>.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p>
|
||||
<strong>Storage backend migration:</strong>
|
||||
</p>
|
||||
<pre className="bg-muted/40 rounded-md p-2 text-xs mt-1 overflow-auto">
|
||||
pnpm tsx scripts/migrate-storage.ts
|
||||
</pre>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Run after switching <code>system_settings.storage_backend</code> in System Settings.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p>
|
||||
<strong>Seed (rebuild dev fixtures):</strong>
|
||||
</p>
|
||||
<pre className="bg-muted/40 rounded-md p-2 text-xs mt-1 overflow-auto">
|
||||
pnpm db:seed
|
||||
</pre>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>What this page will become</CardTitle>
|
||||
<CardDescription>Planned UI for self-serve imports.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Drag-and-drop CSV / XLSX upload with column-mapping UI.</li>
|
||||
<li>Dry-run preview that shows new vs. matched-existing rows before commit.</li>
|
||||
<li>Conflict-resolution choices (skip, update, dedup-by-email) per import type.</li>
|
||||
<li>Per-port import history with rollback.</li>
|
||||
<li>Templates for clients, yachts, companies, berths, reservations, expenses.</li>
|
||||
</ul>
|
||||
<p className="text-xs text-muted-foreground pt-2">
|
||||
Imports run against the BullMQ <code>import</code> queue (concurrency 1) so partial
|
||||
failures don’t leave the database half-loaded.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
5
src/app/(dashboard)/[portSlug]/admin/inquiries/page.tsx
Normal file
5
src/app/(dashboard)/[portSlug]/admin/inquiries/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { InquiryInbox } from '@/components/admin/inquiry-inbox';
|
||||
|
||||
export default function InquiriesPage() {
|
||||
return <InquiryInbox />;
|
||||
}
|
||||
@@ -1,15 +1,114 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
interface ChecklistItem {
|
||||
href: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const CHECKLIST: ChecklistItem[] = [
|
||||
{
|
||||
href: 'branding',
|
||||
label: 'Set port name, logo, primary colour',
|
||||
description: 'Branding flows into the navbar, emails, and EOI PDFs.',
|
||||
},
|
||||
{
|
||||
href: 'email',
|
||||
label: 'Configure outgoing email',
|
||||
description:
|
||||
'From-address, signature, footer, plus per-port SMTP overrides if you don’t use the global account.',
|
||||
},
|
||||
{
|
||||
href: 'documenso',
|
||||
label: 'Connect Documenso for EOIs',
|
||||
description:
|
||||
'API credentials and the EOI template id, plus the in-app vs Documenso pathway choice.',
|
||||
},
|
||||
{
|
||||
href: 'settings',
|
||||
label: 'Tune business rules + recommender weights',
|
||||
description:
|
||||
'Pipeline weights, net-10 discount, berth recommender knobs (heat weights, fall-through policy).',
|
||||
},
|
||||
{
|
||||
href: 'roles',
|
||||
label: 'Create roles & assign users',
|
||||
description: 'Per-port roles inherit from the global system roles; override permissions here.',
|
||||
},
|
||||
{
|
||||
href: 'invitations',
|
||||
label: 'Invite the rest of the team',
|
||||
description:
|
||||
'Invitations track pending, expired, and accepted state and can be resent or revoked.',
|
||||
},
|
||||
{
|
||||
href: 'tags',
|
||||
label: 'Define starter tags',
|
||||
description: 'Color-coded labels used across clients, yachts, companies, and interests.',
|
||||
},
|
||||
{
|
||||
href: 'forms',
|
||||
label: 'Wire the website intake forms',
|
||||
description:
|
||||
'Inquiry forms on the marketing site dual-write into the CRM via /api/public/website-inquiries.',
|
||||
},
|
||||
];
|
||||
|
||||
export default function OnboardingPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="Onboarding" description="Guided setup for new port configurations" />
|
||||
<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 4</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This feature will be implemented in the next phase.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<PageHeader
|
||||
title="Port onboarding"
|
||||
description="Recommended order to bring a new port live. Each step links to the right admin page."
|
||||
/>
|
||||
|
||||
<Card className="mt-6">
|
||||
<CardHeader>
|
||||
<CardTitle>Setup checklist</CardTitle>
|
||||
<CardDescription>
|
||||
Work through these in order. The future onboarding wizard will track progress per port;
|
||||
for now this is a guided index.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ol className="space-y-4">
|
||||
{CHECKLIST.map((item, idx) => (
|
||||
<li key={item.href} className="flex gap-4">
|
||||
<span className="flex-none w-7 h-7 rounded-full bg-primary/10 text-primary font-medium text-sm flex items-center justify-center mt-0.5">
|
||||
{idx + 1}
|
||||
</span>
|
||||
<div className="flex-1">
|
||||
<Link
|
||||
href={`./${item.href}` as never}
|
||||
className="text-sm font-medium hover:underline"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{item.description}</p>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="mt-4">
|
||||
<CardHeader>
|
||||
<CardTitle>What this page will become</CardTitle>
|
||||
<CardDescription>
|
||||
A guided wizard that walks per-port admins through the same steps with progress
|
||||
tracking.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-muted-foreground">
|
||||
The wizard will record completion per port in <code>system_settings</code>, gate the
|
||||
public marketing-site cutover until required steps are done, and surface a banner on the
|
||||
dashboard when onboarding is incomplete.
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
Database,
|
||||
FileText,
|
||||
HardDrive,
|
||||
Inbox,
|
||||
Key,
|
||||
LayoutDashboard,
|
||||
Mail,
|
||||
@@ -120,6 +121,12 @@ const GROUPS: AdminGroup[] = [
|
||||
description: 'PDF + email templates with merge-field placeholders.',
|
||||
icon: FileText,
|
||||
},
|
||||
{
|
||||
href: 'email-templates',
|
||||
label: 'Email Templates',
|
||||
description: 'Customize subject lines for transactional emails (portal, inquiry, invite).',
|
||||
icon: Mail,
|
||||
},
|
||||
{
|
||||
href: 'tags',
|
||||
label: 'Tags',
|
||||
@@ -138,6 +145,19 @@ const GROUPS: AdminGroup[] = [
|
||||
title: 'Data Quality',
|
||||
description: 'Cleanup, imports, and the audit trail.',
|
||||
sections: [
|
||||
{
|
||||
href: 'inquiries',
|
||||
label: 'Inquiry Inbox',
|
||||
description:
|
||||
'Submissions captured from the public marketing site (berth, residence, contact).',
|
||||
icon: Inbox,
|
||||
},
|
||||
{
|
||||
href: 'sends',
|
||||
label: 'Send Log',
|
||||
description: 'Brochure and per-berth PDF sends, with delivery failures surfaced for retry.',
|
||||
icon: Mail,
|
||||
},
|
||||
{
|
||||
href: 'duplicates',
|
||||
label: 'Duplicates',
|
||||
|
||||
@@ -1,18 +1,5 @@
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { ReportsDashboard } from '@/components/admin/reports-dashboard';
|
||||
|
||||
export default function ScheduledReportsPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="Scheduled Reports"
|
||||
description="Configure and manage automated report delivery"
|
||||
/>
|
||||
<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 3</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This feature will be implemented in the next phase.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
export default function AdminReportsPage() {
|
||||
return <ReportsDashboard />;
|
||||
}
|
||||
|
||||
5
src/app/(dashboard)/[portSlug]/admin/sends/page.tsx
Normal file
5
src/app/(dashboard)/[portSlug]/admin/sends/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { SendsLog } from '@/components/admin/sends-log';
|
||||
|
||||
export default function SendsPage() {
|
||||
return <SendsLog />;
|
||||
}
|
||||
114
src/app/api/v1/admin/dashboard-stats/route.ts
Normal file
114
src/app/api/v1/admin/dashboard-stats/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
68
src/app/api/v1/admin/document-sends/route.ts
Normal file
68
src/app/api/v1/admin/document-sends/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
91
src/app/api/v1/admin/email-templates/route.ts
Normal file
91
src/app/api/v1/admin/email-templates/route.ts
Normal 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;
|
||||
67
src/app/api/v1/admin/website-submissions/route.ts
Normal file
67
src/app/api/v1/admin/website-submissions/route.ts
Normal 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;
|
||||
Reference in New Issue
Block a user