feat(post-audit): finish Phase 3 / 4 / 5 / 7 — remaining work
Phase 3 — EOI overrides (now ☑):
- Address override field with the same per-component input UX as the
canonical address form (line1/line2/city/state/postal + ISO
subdivision + CountryCombobox). Two-checkbox intent semantics
identical to email/phone — useOnlyForThisEoi writes only to
documents.override_client_address_* columns; setAsDefault promotes
to the canonical client_addresses primary inside the override
transaction; neither flag inserts a non-primary address row for
future reuse. eoi-context route now returns available.addresses so
the dialog can render the picker over existing rows.
- yachts.source_document_id backfill — yachts spawned via EOI run
BEFORE generateAndSign creates the document row, so source_document_id
stayed NULL. Mirrored the bounded-recent backfill pattern from
contacts into persistDocumentOverrides for both client_addresses and
yachts (every row inserted in the last 60s with NULL source_document_id
and the right source flag gets attributed).
- Audit-log filter chips for the new verbs — eoi_field_override,
promote_to_primary, eoi_spawn_yacht now appear in /admin/audit
dropdown + get human labels in the card view.
Phase 4 — reminders inline section (now ☑):
- New <RemindersInline> shared component shows the 3-5 most recent
open reminders for an entity. Mounted on Overview tab of yacht /
client / interest detail. Empty state hints at the header button
rather than duplicating it.
Phase 5 — email tone (now ☑ across all 8 templates):
- admin-email-change, crm-invite, inquiry-sales-notification,
residential-inquiry — voice + sign-off match the 4 shipped earlier
("Dear X", "With warm regards, The {portName} Team", sentence-case
subjects). Snapshot tests deferred — they'd need a 2nd-port fixture
set up to catch port-name leaks; templates are correct in review.
Phase 7 — PDF editor (now ☑):
- 7.1 polish: unsaved-changes guard (beforeunload + "Unsaved changes"
badge), ResizeObserver-driven responsive PDF width, required-tokens-
unplaced indicator reading template.mergeFields.
- 7.2 drag-to-move with on-page clamping.
- 7.2 four-corner resize handles with min-size enforcement.
- 7.2 right-click context delete via onContextMenu.
- 7.2 multi-page navigation + per-page marker filter.
- 7.2 live preview endpoint POST /api/v1/document-templates/[id]/preview
runs the in-app pdf-lib fill against the supplied interest, uploads
to a transient previews/ key, returns a 15-min presigned URL.
- 7.2 new-PDF upload POST /api/v1/document-templates/[id]/source-pdf
takes multipart FormData, magic-byte verifies %PDF-, parses page
count via pdf-lib, swaps documentTemplates.sourceFileId. Editor
warns when the new page count truncates the prior set.
Quality gates: 1374/1374 vitest, tsc clean, lint 0 errors.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
80
src/app/api/v1/document-templates/[id]/preview/route.ts
Normal file
80
src/app/api/v1/document-templates/[id]/preview/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { db } from '@/lib/db';
|
||||
import { documentTemplates } from '@/lib/db/schema/documents';
|
||||
import { errorResponse, NotFoundError, ValidationError } from '@/lib/errors';
|
||||
import { generateEoiPdfFromTemplate } from '@/lib/pdf/fill-eoi-form';
|
||||
import { buildEoiContext } from '@/lib/services/eoi-context';
|
||||
import { getStorageBackend, presignDownloadUrl } from '@/lib/storage';
|
||||
import { buildStoragePath } from '@/lib/minio';
|
||||
|
||||
const previewBodySchema = z.object({
|
||||
interestId: z.string().uuid(),
|
||||
dimensionUnit: z.enum(['ft', 'm']).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Phase 7.2 — live preview endpoint for the PDF editor.
|
||||
*
|
||||
* Generates a transient EOI PDF against the supplied interest using the
|
||||
* template's current source PDF + overlay markers, uploads it to a
|
||||
* scratch storage key, and returns a 15-minute presigned download URL.
|
||||
*
|
||||
* The blob is intentionally not linked to a `files` row — preview PDFs
|
||||
* are throwaway. The storage backend's lifecycle policy (TTL on
|
||||
* `previews/` prefix) cleans them up; in dev the filesystem backend
|
||||
* just accumulates them, which is acceptable for the editor workflow.
|
||||
*/
|
||||
export const POST = withAuth(
|
||||
withPermission('documents', 'create', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, previewBodySchema);
|
||||
|
||||
const template = await db.query.documentTemplates.findFirst({
|
||||
where: and(eq(documentTemplates.id, params.id!), eq(documentTemplates.portId, ctx.portId)),
|
||||
});
|
||||
if (!template) throw new NotFoundError('Template');
|
||||
if (template.templateType !== 'eoi') {
|
||||
// Live preview is currently EOI-only — that's where the
|
||||
// editor's overlay-positions flow into rendering. Other
|
||||
// template types are deferred (no in-app fill yet).
|
||||
throw new ValidationError(
|
||||
`Live preview is only available for EOI templates (got "${template.templateType}").`,
|
||||
);
|
||||
}
|
||||
|
||||
const eoiContext = await buildEoiContext(body.interestId, ctx.portId);
|
||||
const pdfBytes = await generateEoiPdfFromTemplate(eoiContext, {
|
||||
dimensionUnit: body.dimensionUnit ?? eoiContext.yacht?.lengthUnit ?? 'ft',
|
||||
});
|
||||
|
||||
const previewKey = buildStoragePath(
|
||||
ctx.portSlug,
|
||||
'previews',
|
||||
'document-templates',
|
||||
template.id,
|
||||
`${crypto.randomUUID()}.pdf`,
|
||||
);
|
||||
const backend = await getStorageBackend();
|
||||
const buffer = Buffer.from(pdfBytes);
|
||||
await backend.put(previewKey, buffer, {
|
||||
contentType: 'application/pdf',
|
||||
sizeBytes: buffer.length,
|
||||
});
|
||||
|
||||
const previewUrl = await presignDownloadUrl(
|
||||
previewKey,
|
||||
900,
|
||||
`${template.name}.preview.pdf`,
|
||||
ctx.portSlug,
|
||||
);
|
||||
return NextResponse.json({ data: { previewUrl } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
114
src/app/api/v1/document-templates/[id]/source-pdf/route.ts
Normal file
114
src/app/api/v1/document-templates/[id]/source-pdf/route.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { PDFDocument } from 'pdf-lib';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { db } from '@/lib/db';
|
||||
import { documentTemplates, files } from '@/lib/db/schema/documents';
|
||||
import { errorResponse, NotFoundError, ValidationError } from '@/lib/errors';
|
||||
import { buildStoragePath } from '@/lib/minio';
|
||||
import { getStorageBackend } from '@/lib/storage';
|
||||
import { env } from '@/lib/env';
|
||||
import { createAuditLog } from '@/lib/audit';
|
||||
|
||||
const MAX_PDF_BYTES = 10 * 1024 * 1024;
|
||||
const PDF_MAGIC = Buffer.from([0x25, 0x50, 0x44, 0x46, 0x2d]); // "%PDF-"
|
||||
|
||||
/**
|
||||
* Phase 7.2 — replace the template's source PDF while preserving the
|
||||
* field map. The existing `overlay_positions` is kept exactly as-is;
|
||||
* the client warns when the new page count truncates the previous set
|
||||
* (markers on now-orphaned pages are invisible at render time).
|
||||
*
|
||||
* Magic-byte (`%PDF-`) verified server-side so a non-PDF file (with a
|
||||
* spoofed extension) can't sneak into the storage backend.
|
||||
*/
|
||||
export const POST = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (req, ctx, params) => {
|
||||
try {
|
||||
const template = await db.query.documentTemplates.findFirst({
|
||||
where: and(eq(documentTemplates.id, params.id!), eq(documentTemplates.portId, ctx.portId)),
|
||||
});
|
||||
if (!template) throw new NotFoundError('Template');
|
||||
|
||||
const form = await req.formData();
|
||||
const file = form.get('file');
|
||||
if (!file || typeof file === 'string') {
|
||||
throw new ValidationError('Missing "file" field');
|
||||
}
|
||||
const arrayBuf = await file.arrayBuffer();
|
||||
if (arrayBuf.byteLength > MAX_PDF_BYTES) {
|
||||
throw new ValidationError(
|
||||
`PDF exceeds the ${Math.floor(MAX_PDF_BYTES / 1024 / 1024)} MB cap`,
|
||||
);
|
||||
}
|
||||
const buf = Buffer.from(arrayBuf);
|
||||
if (buf.length < PDF_MAGIC.length || !buf.subarray(0, PDF_MAGIC.length).equals(PDF_MAGIC)) {
|
||||
throw new ValidationError('Uploaded file does not look like a PDF (missing %PDF- header)');
|
||||
}
|
||||
|
||||
// Resolve the page count so the client can surface a warning if
|
||||
// the new PDF truncates the prior page set + orphaned markers
|
||||
// exist. pdf-lib parses fully into memory but that's cheap for a
|
||||
// sub-10MB editor source.
|
||||
const pdfDoc = await PDFDocument.load(buf);
|
||||
const pageCount = pdfDoc.getPageCount();
|
||||
|
||||
const fileId = crypto.randomUUID();
|
||||
const storagePath = buildStoragePath(
|
||||
ctx.portSlug,
|
||||
'document-templates',
|
||||
template.id,
|
||||
fileId,
|
||||
'pdf',
|
||||
);
|
||||
const backend = await getStorageBackend();
|
||||
await backend.put(storagePath, buf, {
|
||||
contentType: 'application/pdf',
|
||||
sizeBytes: buf.length,
|
||||
});
|
||||
|
||||
const [fileRecord] = await db
|
||||
.insert(files)
|
||||
.values({
|
||||
portId: ctx.portId,
|
||||
filename: `${template.name.toLowerCase().replace(/\s+/g, '-')}.pdf`,
|
||||
originalName: file.name || `${template.name}.pdf`,
|
||||
mimeType: 'application/pdf',
|
||||
sizeBytes: String(buf.length),
|
||||
storagePath,
|
||||
storageBucket: env.MINIO_BUCKET,
|
||||
category: 'eoi',
|
||||
uploadedBy: ctx.userId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
await db
|
||||
.update(documentTemplates)
|
||||
.set({ sourceFileId: fileRecord!.id, updatedAt: new Date() })
|
||||
.where(eq(documentTemplates.id, template.id));
|
||||
|
||||
void createAuditLog({
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
action: 'update',
|
||||
entityType: 'documentTemplate',
|
||||
entityId: template.id,
|
||||
metadata: {
|
||||
action: 'replace_source_pdf',
|
||||
fileId: fileRecord!.id,
|
||||
pageCount,
|
||||
sizeBytes: buf.length,
|
||||
},
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
data: { sourceFileId: fileRecord!.id, pageCount },
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -4,7 +4,7 @@ import { and, desc, eq } from 'drizzle-orm';
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { db } from '@/lib/db';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { clientContacts } from '@/lib/db/schema/clients';
|
||||
import { clientAddresses, clientContacts } from '@/lib/db/schema/clients';
|
||||
import { errorResponse, NotFoundError } from '@/lib/errors';
|
||||
import { buildEoiContext } from '@/lib/services/eoi-context';
|
||||
|
||||
@@ -45,6 +45,21 @@ export const GET = withAuth(
|
||||
.where(eq(clientContacts.clientId, interest.clientId))
|
||||
.orderBy(desc(clientContacts.isPrimary), desc(clientContacts.updatedAt));
|
||||
|
||||
const addressRows = await db
|
||||
.select({
|
||||
id: clientAddresses.id,
|
||||
streetAddress: clientAddresses.streetAddress,
|
||||
city: clientAddresses.city,
|
||||
subdivisionIso: clientAddresses.subdivisionIso,
|
||||
postalCode: clientAddresses.postalCode,
|
||||
countryIso: clientAddresses.countryIso,
|
||||
isPrimary: clientAddresses.isPrimary,
|
||||
source: clientAddresses.source,
|
||||
})
|
||||
.from(clientAddresses)
|
||||
.where(eq(clientAddresses.clientId, interest.clientId))
|
||||
.orderBy(desc(clientAddresses.isPrimary), desc(clientAddresses.updatedAt));
|
||||
|
||||
const available = {
|
||||
emails: contactRows
|
||||
.filter((c) => c.channel === 'email')
|
||||
@@ -58,6 +73,7 @@ export const GET = withAuth(
|
||||
channel: c.channel,
|
||||
source: c.source,
|
||||
})),
|
||||
addresses: addressRows,
|
||||
};
|
||||
|
||||
return NextResponse.json({ data: { ...context, available } });
|
||||
|
||||
Reference in New Issue
Block a user