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

@@ -0,0 +1,101 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { PDFDocument } from 'pdf-lib';
import type { EoiContext } from '@/lib/services/eoi-context';
/**
* Source PDF for the in-app EOI pathway. Must contain AcroForm fields whose
* names match the Documenso template's `formValues` keys exactly:
*
* Text: Name, Email, Address, Yacht Name, Length, Width, Draft,
* Berth Number
* Checkbox: Lease_10, Purchase
*
* See assets/eoi-template/README.md for full details and the field mapping
* doc at docs/eoi-documenso-field-mapping.md for the canonical list.
*/
const DEFAULT_EOI_TEMPLATE_PATH = path.join(process.cwd(), 'assets', 'eoi-template.pdf');
function eoiTemplatePath(): string {
return process.env.EOI_TEMPLATE_PDF_PATH ?? DEFAULT_EOI_TEMPLATE_PATH;
}
export async function loadEoiTemplatePdf(): Promise<Uint8Array> {
const filePath = eoiTemplatePath();
try {
return await fs.readFile(filePath);
} catch (err) {
throw new Error(
`EOI source PDF not found at ${filePath}. Drop the same PDF used by the Documenso template (with AcroForm fields: Name, Email, Address, Yacht Name, Length, Width, Draft, Berth Number, Lease_10, Purchase) at this path, or override via EOI_TEMPLATE_PDF_PATH. Original error: ${(err as Error).message}`,
);
}
}
function formatAddress(address: EoiContext['client']['address']): string {
if (!address) return '';
return [address.street, address.city, address.country].filter(Boolean).join(', ');
}
function setText(form: ReturnType<PDFDocument['getForm']>, name: string, value: string): void {
try {
form.getTextField(name).setText(value);
} catch {
// Field absent or wrong type — skip silently so a slightly different PDF
// template still produces output. Missing field issues surface in QA, not
// at runtime as a 500.
}
}
function setCheckbox(
form: ReturnType<PDFDocument['getForm']>,
name: string,
checked: boolean,
): void {
try {
const cb = form.getCheckBox(name);
if (checked) cb.check();
else cb.uncheck();
} catch {
// See comment in setText.
}
}
/**
* Fills the AcroForm fields of the EOI source PDF with values drawn from
* EoiContext. Field names mirror the Documenso template `formValues` keys so
* a single source PDF can serve both pathways.
*
* The form is left interactive (not flattened) so a recipient can still tweak
* fields if needed before signing.
*/
export async function fillEoiFormFields(
pdfBytes: Uint8Array,
context: EoiContext,
): Promise<Uint8Array> {
const doc = await PDFDocument.load(pdfBytes);
const form = doc.getForm();
setText(form, 'Name', context.client.fullName);
setText(form, 'Email', context.client.primaryEmail ?? '');
setText(form, 'Address', formatAddress(context.client.address));
setText(form, 'Yacht Name', context.yacht.name);
setText(form, 'Length', context.yacht.lengthFt ?? '');
setText(form, 'Width', context.yacht.widthFt ?? '');
setText(form, 'Draft', context.yacht.draftFt ?? '');
setText(form, 'Berth Number', context.berth.mooringNumber);
setCheckbox(form, 'Purchase', true);
setCheckbox(form, 'Lease_10', false);
return doc.save();
}
/**
* Convenience: loads the source PDF from disk and returns the filled bytes.
*/
export async function generateEoiPdfFromTemplate(context: EoiContext): Promise<Uint8Array> {
const bytes = await loadEoiTemplatePdf();
return fillEoiFormFields(bytes, context);
}

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[] = [];