Audit cleanup completion plan, all tiers shipped: Tier 1 (security + data integrity) - A.7 RTBF true wipe: redact email_messages body/subject/addresses for threads owned by deleted client; redact document_sends.recipient_email; collect file storage keys + delete blobs post-commit. - A.8 user_permission_overrides FK: documented inline why cascade is correct (not set-null as audit suggested) — overrides have no value without their user. - W2.14 PII redaction: camelCase normalization in audit.ts + error-events.service.ts isSensitiveKey; added city/postal/country/ birth fragments. firstName/lastName/dateOfBirth/postalCode etc. now caught in BOTH masker paths. 12 new test cases lock the coverage. Tier 2 (Documenso completion + refactor) - C.2: documentEvents.recipient_email column + partial unique index for per-recipient webhook dedup (migration 0075). handleDocumentSigned now sets recipient_email on insert. - Phase 2: completion_cc_emails distribution. handleDocumentCompleted reads documents.completionCcEmails, filters out signer-duplicates case-insensitively, fans signed PDF out to non-signer recipients. - C.4: extracted createPublicInterest() service from the 346-line api/public/interests route. Route becomes a thin shell (rate-limit, port resolution, audit log, email fan-out). The trio creation logic is now unit-testable without an HTTP fixture. - Phase 4: POST /api/v1/document-templates/[id]/detect-fields wired to document-field-detector.detectFields(). Sparkles "Auto-detect" button added to template-editor.tsx — maps DetectedField → marker with best-guess merge token (DATE / NAME / EMAIL); user retags. Tier 3 (reporting + recommender snapshot lockfiles) - W7.reports: extracted rollupStageRevenue / rollupStageCounts / computeTotalForecast / computeOccupancyRate / rollupBerthStatusCounts into src/lib/services/report-math.ts (pure functions). 16 new tests including an inline-snapshot lockfile on a representative 7-stage forecast. report-generators.ts now delegates. - W7.recommender: 18 new toMatchSnapshot tripwires on classifyTier boundaries + computeHeat at canonical input points. Tier 4 (rolling) - W6.attach: fixed outdated CLAUDE.md claim — threshold banner is informational and never depended on IMAP; bounce monitoring (the IMAP poller) is separate. - D.1 + D.2: documented deferral inline with full why-not-build-it reasoning so a future engineer sees the rationale. - G.1: representative formatDate sweep (audit-log-list, user-list, document-templates merge tokens, document-signing email). Rest of the ~100 sites stay rolling. Quality gates: 1420/1420 vitest (46 new tests above baseline of 1374), tsc clean, 0 lint errors. Plan: docs/superpowers/plans/2026-05-18-audit-cleanup-completion.md Migration: 0075_c2_document_events_recipient_email.sql (applied to dev DB). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
92 lines
3.5 KiB
TypeScript
92 lines
3.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { eq } from 'drizzle-orm';
|
|
|
|
import { db } from '@/lib/db';
|
|
import { ports } from '@/lib/db/schema/ports';
|
|
import { createAuditLog } from '@/lib/audit';
|
|
import { parseBody } from '@/lib/api/route-helpers';
|
|
import { errorResponse, RateLimitError, ValidationError } from '@/lib/errors';
|
|
import { checkRateLimit, rateLimiters } from '@/lib/rate-limit';
|
|
import { publicInterestSchema } from '@/lib/validators/interests';
|
|
import { sendInquiryNotifications } from '@/lib/services/inquiry-notifications.service';
|
|
import { createPublicInterest } from '@/lib/services/public-interest.service';
|
|
|
|
/**
|
|
* Throws RateLimitError if the IP has exceeded the public-form quota.
|
|
* Backed by the Redis sliding-window limiter so the cap survives restarts
|
|
* and is shared across worker processes.
|
|
*/
|
|
async function gateRateLimit(ip: string): Promise<void> {
|
|
const result = await checkRateLimit(ip, rateLimiters.publicForm);
|
|
if (!result.allowed) {
|
|
const retryAfter = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1000));
|
|
throw new RateLimitError(retryAfter);
|
|
}
|
|
}
|
|
|
|
// POST /api/public/interests — unauthenticated public interest registration.
|
|
// The transactional trio creation (client + yacht + interest, plus optional
|
|
// company + membership) lives in `createPublicInterest()` so it's testable
|
|
// without an HTTP fixture. This handler is the thin HTTP shell: rate-limit,
|
|
// port resolution, body parsing, then post-commit audit log + email fan-out.
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? 'unknown';
|
|
await gateRateLimit(ip);
|
|
|
|
const data = await parseBody(req, publicInterestSchema);
|
|
|
|
// Resolve portId from query param or header (public endpoints need explicit port)
|
|
const portId = req.nextUrl.searchParams.get('portId') ?? req.headers.get('X-Port-Id');
|
|
if (!portId) throw new ValidationError('Port context required');
|
|
|
|
const result = await createPublicInterest({ portId, data });
|
|
|
|
// ─── Post-commit side-effects (fire-and-forget) ─────────────────────────
|
|
// `AuditLogParams.userId` is `string | null`; null is the documented
|
|
// "system-generated" sentinel and matches `audit_logs.user_id` being
|
|
// nullable in the schema.
|
|
void createAuditLog({
|
|
userId: null,
|
|
portId,
|
|
action: 'create',
|
|
entityType: 'interest',
|
|
entityId: result.interestId,
|
|
newValue: {
|
|
clientId: result.clientId,
|
|
yachtId: result.yachtId,
|
|
companyId: result.companyId,
|
|
source: 'website',
|
|
pipelineStage: 'open',
|
|
berthId: result.berthId,
|
|
},
|
|
metadata: { type: 'public_registration', ip },
|
|
ipAddress: ip,
|
|
userAgent: req.headers.get('user-agent') ?? 'unknown',
|
|
});
|
|
|
|
const port = await db.query.ports.findFirst({
|
|
where: eq(ports.id, portId),
|
|
columns: { slug: true },
|
|
});
|
|
|
|
void sendInquiryNotifications({
|
|
portId,
|
|
portSlug: port?.slug ?? portId,
|
|
interestId: result.interestId,
|
|
clientFullName: result.fullName,
|
|
clientEmail: data.email,
|
|
clientPhone: data.phone,
|
|
mooringNumber: result.resolvedMooringNumber,
|
|
firstName: result.firstName,
|
|
});
|
|
|
|
return NextResponse.json(
|
|
{ data: { id: result.interestId, message: 'Interest registered successfully' } },
|
|
{ status: 201 },
|
|
);
|
|
} catch (error) {
|
|
return errorResponse(error);
|
|
}
|
|
}
|