feat(eoi): in-app pathway fills the same source PDF as Documenso

When the in-app pathway is used for EOI templates, we now load the same
source PDF that the Documenso template uploads and fill its AcroForm
fields with values from EoiContext via pdf-lib. Field names mirror the
Documenso template's formValues keys exactly (Name, Email, Address,
Yacht Name, Length, Width, Draft, Berth Number + Lease_10 / Purchase
checkboxes), so both pathways produce equivalent legal documents — only
the renderer differs.

The form is left interactive (not flattened) so a recipient can still
adjust values before signing. Non-EOI templates (welcome letters,
acknowledgments, etc.) keep using the existing HTML→pdfme path.

Adds:
- pdf-lib direct dep
- src/lib/pdf/fill-eoi-form.ts — load + fill helpers, EOI_TEMPLATE_PDF_PATH
  env override
- assets/ + README documenting the expected source PDF
- next.config outputFileTracingIncludes so the asset is bundled in the
  standalone build

Tests: 8 new (4 fill-form unit + 2 source-PDF route + 2 fallback);
645/645 green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-04-26 13:38:02 +02:00
parent f8255cedb8
commit 2ff24a7132
8 changed files with 536 additions and 9 deletions

View File

@@ -23,6 +23,7 @@ import {
generateDocumentFromTemplate as documensoGenerateFromTemplate,
} from '@/lib/services/documenso-client';
import { buildDocumensoPayload } from '@/lib/services/documenso-payload';
import { generateEoiPdfFromTemplate } from '@/lib/pdf/fill-eoi-form';
import { buildEoiContext } from '@/lib/services/eoi-context';
import { sendEmail } from '@/lib/email';
import type {
@@ -687,12 +688,107 @@ export async function generateAndSend(
return { document, file };
}
// ─── EOI from source PDF (in-app pathway, EOI templates only) ─────────────────
/**
* BR-142: For EOI templates, the in-app pathway uses the same source PDF as
* the Documenso template — filled via pdf-lib with values from EoiContext.
* Same field names, same legal document; the only difference is who renders
* it. The form is left interactive so a recipient can adjust before signing.
*/
async function generateEoiFromSourcePdf(
template: typeof documentTemplates.$inferSelect,
portId: string,
context: GenerateInput,
meta: AuditMeta,
): Promise<{ document: DbDocument; file: DbFile }> {
if (!context.interestId) {
throw new ValidationError('interestId is required for EOI template generation');
}
const eoiContext = await buildEoiContext(context.interestId, portId);
const pdfBytes = await generateEoiPdfFromTemplate(eoiContext);
const port = await db.query.ports.findFirst({ where: eq(ports.id, portId) });
const fileId = crypto.randomUUID();
const storagePath = buildStoragePath(
port?.slug ?? portId,
'document-templates',
template.id,
fileId,
'pdf',
);
await minioClient.putObject(
env.MINIO_BUCKET,
storagePath,
Buffer.from(pdfBytes),
pdfBytes.byteLength,
{ 'Content-Type': 'application/pdf' },
);
const [fileRecord] = await db
.insert(files)
.values({
portId,
clientId: context.clientId ?? null,
filename: `${template.name.toLowerCase().replace(/\s+/g, '-')}.pdf`,
originalName: `${template.name}.pdf`,
mimeType: 'application/pdf',
sizeBytes: String(pdfBytes.byteLength),
storagePath,
storageBucket: env.MINIO_BUCKET,
category: 'eoi',
uploadedBy: meta.userId,
})
.returning();
const [documentRecord] = await db
.insert(documents)
.values({
portId,
clientId: context.clientId ?? null,
interestId: context.interestId,
documentType: template.templateType,
title: template.name,
status: 'draft',
fileId: fileRecord!.id,
isManualUpload: false,
createdBy: meta.userId,
})
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'create',
entityType: 'document',
entityId: documentRecord!.id,
newValue: {
templateId: template.id,
templateName: template.name,
source: 'eoi-source-pdf',
clientId: context.clientId,
interestId: context.interestId,
},
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'document:created', { documentId: documentRecord!.id });
return { document: documentRecord!, file: fileRecord! };
}
// ─── Generate and Sign ────────────────────────────────────────────────────────
/**
* BR-142: EOI / NDA signing. Dual pathway:
* - `inapp`: resolve the in-app template → pdfme → upload PDF to MinIO →
* upload to Documenso and send for signing.
* - `inapp`: produce the PDF locally (EOI templates fill the same source
* PDF as Documenso via pdf-lib; other template types fall back to the
* HTML→pdfme path), upload to MinIO, then upload to Documenso and send
* for signing.
* - `documenso-template`: skip our PDF generation entirely; call Documenso's
* template-generate endpoint with the shared EOI context. Documenso owns
* the PDF. We still record a `documents` row for tracking.
@@ -724,14 +820,19 @@ async function generateAndSignViaInApp(
if (!signers || signers.length === 0) {
throw new ValidationError('signers are required for inapp pathway');
}
const { document: documentRecord, file } = (await generateFromTemplate(
templateId,
portId,
context,
meta,
)) as { document: DbDocument; file: DbFile };
const template = await getTemplateById(templateId, portId);
// EOI templates fill the same source PDF as the Documenso template (so both
// pathways yield the same document). Other template types stay on the
// HTML→pdfme rendering path.
const { document: documentRecord, file } =
template.templateType === 'eoi'
? await generateEoiFromSourcePdf(template, portId, context, meta)
: ((await generateFromTemplate(templateId, portId, context, meta)) as {
document: DbDocument;
file: DbFile;
});
// Fetch PDF bytes from MinIO to send to Documenso
const pdfStream = await minioClient.getObject(env.MINIO_BUCKET, file.storagePath);
const chunks: Buffer[] = [];