feat(emails): sales send-out flows + brochures + email-from settings
Phase 7 of the berth-recommender refactor (plan §3.3, §4.8, §4.9, §5.7,
§5.8, §5.9, §11.1, §14.7, §14.9). Adds the rep-driven send-out path for
per-berth PDFs and port-wide brochures, the per-port sales SMTP/IMAP
config + body templates, and the supporting admin UI.
Migration: 0031_brochures_and_document_sends.sql
Schema additions:
- brochures (port-wide, with isDefault marker + archive)
- brochure_versions (versioned uploads, storageKey per §4.7a)
- document_sends (audit log of every rep-initiated send; failures
captured with failedAt + errorReason). berthPdfVersionId is a plain
text column (no FK) — loose-coupled to Phase 6b's berth_pdf_versions
so the two phases stay independent.
§14.7 critical mitigations:
- Body XSS: rep-authored markdown goes through renderEmailBody()
(HTML-escape first, then a tight allowlist of bold/italic/code/link
rules). https:// + mailto: only — javascript:/data: URLs stripped.
Tested against script/img/iframe/svg/onerror polyglots.
- Recipient typo: strict email regex + two-step confirm modal that
shows the exact recipient before send.
- Unresolved merge fields: pre-send dry-run /preview endpoint blocks
submission until findUnresolvedTokens() returns empty.
- SMTP failure: every transport rejection writes a document_sends row
with failedAt + errorReason; UI surfaces the message.
- Hourly per-user rate limit: 50 sends/user/hour via existing
checkRateLimit().
- Size threshold fallback (§11.1): files above
email_attach_threshold_mb (default 15) ship as a 24h signed-URL
download link in the body instead of an attachment. Storage stream
flows directly to nodemailer to avoid buffering 20MB+.
§14.10 critical mitigation:
- SMTP/IMAP passwords encrypted at rest via the existing
EMAIL_CREDENTIAL_KEY (AES-256-GCM). The /api/v1/admin/email/
sales-config GET endpoint never returns the decrypted value — only
a *PassIsSet boolean. PATCH treats empty string as "leave unchanged"
and explicit null as "clear", so the masked-placeholder UI round-
trips without forcing re-entry on every save.
system_settings keys (per-port unless noted):
- sales_from_address, sales_smtp_{host,port,secure,user,pass_encrypted}
- sales_imap_{host,port,user,pass_encrypted}
- sales_auth_method (default app_password)
- noreply_from_address
- email_template_send_berth_pdf_body, email_template_send_brochure_body
- brochure_max_upload_mb (default 50)
- email_attach_threshold_mb (default 15)
UI surfaces (per §5.7, §5.8, §5.9):
- <SendDocumentDialog> shared 2-step compose+confirm flow.
- <SendBerthPdfDialog>, <SendDocumentsDialog>, <SendFromInterestButton>
wrappers per detail page.
- /[portSlug]/admin/brochures: list, upload (direct-to-storage
presigned PUT for the 20MB+ files per §11.1), default toggle,
archive.
- /[portSlug]/admin/email extended with <SalesEmailConfigCard>:
SMTP + IMAP creds, body templates, threshold/max settings.
Storage: every upload + download goes through getStorageBackend() —
no direct minio imports, per Phase 6a contract.
Tests: 1145 vitest passing (+ 50 new in
markdown-email-sanitization.test.ts, document-sends-validators.test.ts,
sales-email-config-validators.test.ts).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
44
src/app/api/v1/admin/brochures/[id]/route.ts
Normal file
44
src/app/api/v1/admin/brochures/[id]/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { archiveBrochure, getBrochure, updateBrochure } from '@/lib/services/brochures.service';
|
||||
import { updateBrochureSchema } from '@/lib/validators/brochures';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
|
||||
try {
|
||||
const id = params.id!;
|
||||
const data = await getBrochure(ctx.portId, id);
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const PATCH = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx, params) => {
|
||||
try {
|
||||
const id = params.id!;
|
||||
const input = await parseBody(req, updateBrochureSchema);
|
||||
const data = await updateBrochure(ctx.portId, id, input);
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const DELETE = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
|
||||
try {
|
||||
const id = params.id!;
|
||||
await archiveBrochure(ctx.portId, id);
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
68
src/app/api/v1/admin/brochures/[id]/versions/route.ts
Normal file
68
src/app/api/v1/admin/brochures/[id]/versions/route.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import {
|
||||
generateBrochureStorageKey,
|
||||
registerBrochureVersion,
|
||||
} from '@/lib/services/brochures.service';
|
||||
import { registerBrochureVersionSchema } from '@/lib/validators/brochures';
|
||||
|
||||
/**
|
||||
* Two-step upload (per §11.1):
|
||||
* 1. GET (no body) — server returns a fresh storage key + presigned URL.
|
||||
* 2. POST (metadata) — after the browser PUTs to the URL, register the
|
||||
* version row server-side.
|
||||
*
|
||||
* Direct-to-storage uploads bypass Next.js's body-size limit; the server
|
||||
* never holds the 20MB+ payload in memory.
|
||||
*/
|
||||
import { getStorageBackend } from '@/lib/storage';
|
||||
import { getSalesContentConfig } from '@/lib/services/sales-email-config.service';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
|
||||
try {
|
||||
const id = params.id!;
|
||||
const content = await getSalesContentConfig(ctx.portId);
|
||||
const storageKey = await generateBrochureStorageKey(ctx.portId, id);
|
||||
const storage = await getStorageBackend();
|
||||
const { url } = await storage.presignUpload(storageKey, {
|
||||
expirySeconds: 900,
|
||||
contentType: 'application/pdf',
|
||||
});
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
storageKey,
|
||||
uploadUrl: url,
|
||||
method: 'PUT',
|
||||
maxBytes: content.brochureMaxUploadMb * 1024 * 1024,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const POST = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx, params) => {
|
||||
try {
|
||||
const id = params.id!;
|
||||
const input = await parseBody(req, registerBrochureVersionSchema);
|
||||
const data = await registerBrochureVersion({
|
||||
portId: ctx.portId,
|
||||
brochureId: id,
|
||||
storageKey: input.storageKey,
|
||||
fileName: input.fileName,
|
||||
fileSizeBytes: input.fileSizeBytes,
|
||||
contentSha256: input.contentSha256,
|
||||
uploadedBy: ctx.userId,
|
||||
});
|
||||
return NextResponse.json({ data }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
36
src/app/api/v1/admin/brochures/route.ts
Normal file
36
src/app/api/v1/admin/brochures/route.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { createBrochure, listBrochures } from '@/lib/services/brochures.service';
|
||||
import { createBrochureSchema } from '@/lib/validators/brochures';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx) => {
|
||||
try {
|
||||
const data = await listBrochures(ctx.portId, { includeArchived: true });
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const POST = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx) => {
|
||||
try {
|
||||
const input = await parseBody(req, createBrochureSchema);
|
||||
const data = await createBrochure({
|
||||
portId: ctx.portId,
|
||||
label: input.label,
|
||||
description: input.description ?? null,
|
||||
isDefault: input.isDefault,
|
||||
createdBy: ctx.userId,
|
||||
});
|
||||
return NextResponse.json({ data }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
67
src/app/api/v1/admin/email/sales-config/route.ts
Normal file
67
src/app/api/v1/admin/email/sales-config/route.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import {
|
||||
getSalesEmailConfig,
|
||||
getSalesImapConfig,
|
||||
getSalesContentConfig,
|
||||
redactSalesConfigForResponse,
|
||||
updateSalesEmailConfig,
|
||||
} from '@/lib/services/sales-email-config.service';
|
||||
import { updateSalesEmailConfigSchema } from '@/lib/validators/sales-email-config';
|
||||
|
||||
/**
|
||||
* GET /api/v1/admin/email/sales-config
|
||||
*
|
||||
* Returns the redacted view of the sales-email config. Per §14.10
|
||||
* "Permission escalation: who configures SMTP credentials?", reps cannot
|
||||
* see the decrypted password — the response only carries `*PassIsSet`
|
||||
* boolean markers.
|
||||
*/
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx) => {
|
||||
try {
|
||||
const [email, imap, content] = await Promise.all([
|
||||
getSalesEmailConfig(ctx.portId),
|
||||
getSalesImapConfig(ctx.portId),
|
||||
getSalesContentConfig(ctx.portId),
|
||||
]);
|
||||
const redacted = redactSalesConfigForResponse(email, imap, content);
|
||||
return NextResponse.json({ data: redacted });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* PATCH /api/v1/admin/email/sales-config
|
||||
*
|
||||
* Per-port admin only. Encrypts SMTP/IMAP passwords via AES-256-GCM before
|
||||
* storage; the API never returns decrypted secrets (mirror enforcement on
|
||||
* the GET handler).
|
||||
*/
|
||||
export const PATCH = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx) => {
|
||||
try {
|
||||
const input = await parseBody(req, updateSalesEmailConfigSchema);
|
||||
await updateSalesEmailConfig(ctx.portId, input, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
// Return the freshly-redacted view so the UI can re-render.
|
||||
const [email, imap, content] = await Promise.all([
|
||||
getSalesEmailConfig(ctx.portId),
|
||||
getSalesImapConfig(ctx.portId),
|
||||
getSalesContentConfig(ctx.portId),
|
||||
]);
|
||||
return NextResponse.json({ data: redactSalesConfigForResponse(email, imap, content) });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
33
src/app/api/v1/document-sends/berth-pdf/route.ts
Normal file
33
src/app/api/v1/document-sends/berth-pdf/route.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { sendBerthPdf } from '@/lib/services/document-sends.service';
|
||||
import { sendBerthPdfSchema } from '@/lib/validators/document-sends';
|
||||
|
||||
/**
|
||||
* POST /api/v1/document-sends/berth-pdf
|
||||
*
|
||||
* Sends the active per-berth PDF version to a client recipient. The body
|
||||
* markdown goes through the merge-field expander + sanitizer
|
||||
* (`renderEmailBody`) before reaching nodemailer (§14.7 critical mitigation:
|
||||
* body XSS).
|
||||
*/
|
||||
export const POST = withAuth(async (req, ctx) => {
|
||||
try {
|
||||
const input = await parseBody(req, sendBerthPdfSchema);
|
||||
const result = await sendBerthPdf({
|
||||
portId: ctx.portId,
|
||||
berthId: input.berthId,
|
||||
recipient: input.recipient,
|
||||
customBodyMarkdown: input.customBodyMarkdown,
|
||||
sentBy: ctx.userId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: result });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
});
|
||||
31
src/app/api/v1/document-sends/brochure/route.ts
Normal file
31
src/app/api/v1/document-sends/brochure/route.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { sendBrochure } from '@/lib/services/document-sends.service';
|
||||
import { sendBrochureSchema } from '@/lib/validators/document-sends';
|
||||
|
||||
/**
|
||||
* POST /api/v1/document-sends/brochure
|
||||
*
|
||||
* Sends a brochure (default or specified) to a client recipient. Same
|
||||
* sanitization + audit-row pipeline as the berth-pdf endpoint.
|
||||
*/
|
||||
export const POST = withAuth(async (req, ctx) => {
|
||||
try {
|
||||
const input = await parseBody(req, sendBrochureSchema);
|
||||
const result = await sendBrochure({
|
||||
portId: ctx.portId,
|
||||
brochureId: input.brochureId,
|
||||
recipient: input.recipient,
|
||||
customBodyMarkdown: input.customBodyMarkdown,
|
||||
sentBy: ctx.userId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: result });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
});
|
||||
31
src/app/api/v1/document-sends/preview/route.ts
Normal file
31
src/app/api/v1/document-sends/preview/route.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { previewBody } from '@/lib/services/document-sends.service';
|
||||
import { previewBodySchema } from '@/lib/validators/document-sends';
|
||||
|
||||
/**
|
||||
* POST /api/v1/document-sends/preview
|
||||
*
|
||||
* Renders a body for the dry-run UI without actually sending. Returns the
|
||||
* sanitized HTML, the post-merge markdown, and the list of unresolved
|
||||
* `{{tokens}}` so the UI can block submit until the rep fills them in
|
||||
* (§14.7 mitigation).
|
||||
*/
|
||||
export const POST = withAuth(async (req, ctx) => {
|
||||
try {
|
||||
const input = await parseBody(req, previewBodySchema);
|
||||
const result = await previewBody(
|
||||
ctx.portId,
|
||||
input.documentKind,
|
||||
input.recipient,
|
||||
input.customBodyMarkdown ?? null,
|
||||
{ berthId: input.berthId, brochureLabel: input.brochureId },
|
||||
);
|
||||
return NextResponse.json({ data: result });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
});
|
||||
23
src/app/api/v1/document-sends/route.ts
Normal file
23
src/app/api/v1/document-sends/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth } from '@/lib/api/helpers';
|
||||
import { parseQuery } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { listSends } from '@/lib/services/document-sends.service';
|
||||
import { listSendsQuerySchema } from '@/lib/validators/document-sends';
|
||||
|
||||
export const GET = withAuth(async (req, ctx) => {
|
||||
try {
|
||||
const query = parseQuery(req, listSendsQuerySchema);
|
||||
const data = await listSends({
|
||||
portId: ctx.portId,
|
||||
clientId: query.clientId,
|
||||
interestId: query.interestId,
|
||||
berthId: query.berthId,
|
||||
limit: query.limit,
|
||||
});
|
||||
return NextResponse.json({ data });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user