Files
pn-new-crm/src/app/api/v1/admin/email-templates/route.ts

92 lines
2.9 KiB
TypeScript
Raw Normal View History

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>
2026-05-06 14:58:17 +02:00
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;