- DocumentPageClient fetches /api/documents/:docId/fields on mount and aiPlacementKey change
- Derives selectedFieldHint from selected field's hint property
- Passes selectedFieldHint prop to PreparePanel
- PreparePanel renders Template Hint chip in Quick Fill section when hint exists
- Add DocumentTemplateRow type and activeTab/docTemplates/selectedDocTemplate state
- Lazy-fetch /api/templates on first My Templates tab click
- handleSwitchToTemplates lazy-loads on first click only
- handleSelectDocTemplate clears selectedTemplate and customFile (mutual exclusivity)
- handleSelectTemplate now also clears selectedDocTemplate
- handleSubmit: new branch at top sends documentTemplateId to POST /api/documents
- Guard and disabled condition updated to include selectedDocTemplate
- Tab bar renders with underline-style active indicator matching project Tailwind patterns
- Existing Forms Library content and custom upload section wrapped in activeTab === 'forms' conditional
- Parse documentTemplateId from JSON body alongside formTemplateId
- Fetch document template with formTemplate relation for PDF filename
- Copy signatureFields with fresh crypto.randomUUID per field (snapshot independence)
- Map template signer role labels to client email + contacts array
- Return early with inserted doc; existing form-library and upload paths unchanged
- Server component at /portal/templates/[id] queries documentTemplates with formTemplate relation
- notFound() for archived/missing templates
- TemplatePageClient: state owner mirroring DocumentPageClient pattern
- deriveRolesFromFields initializes Buyer/Seller defaults or extracts from existing fields
- handlePersist merges textFillData hints into f.hint for type='text' fields
- handleAiAutoPlace POSTs to /api/templates/[id]/ai-prepare and increments aiPlacementKey
- Role rename/remove re-fetches fields and PATCHes with updated signerEmail values
- TemplatePanel: 280px right panel with inline styles matching portal design system
- Signers/Roles section with color dots, click-to-rename, remove with ConfirmDialog
- Add role input with preset chips (Buyer, Co-Buyer, Seller, Co-Seller)
- AI Auto-place button (navy) with spinner/loading state and error display
- Save Template button (gold) with success 'Saved' text fading after 3s
- Server component at /portal/templates queries documentTemplates with LEFT JOIN to formTemplates
- TemplatesListClient renders list rows with name, form name, field count, last updated
- Create modal POSTs to /api/templates and navigates to /portal/templates/[id] on success
- Empty state with CTA when no templates exist
- Gold #C9A84C accent, navy #1B2B4B headings, inline styles matching portal patterns
- GET /api/templates/[id]/file: streams form PDF from seeds/forms/ with path traversal guard
- GET /api/templates/[id]/fields: returns signatureFields array (or []) from documentTemplates
- POST /api/templates/[id]/ai-prepare: runs AI field placement with null client context, writes to DB
- All routes: auth guard + isNull(archivedAt) soft-delete filter consistent with Phase 18
- PATCH accepts name and signatureFields for rename and field save per D-10
- PATCH sets updatedAt: new Date() explicitly per D-05
- PATCH returns 404 for archived or missing templates
- DELETE soft-deletes by setting archivedAt: new Date() per D-07 (no hard delete)
- DELETE sets updatedAt: new Date() per D-05, returns 204 No Content
- Both handlers auth-gated with auth() per D-11
- GET lists active templates (archivedAt IS NULL) with LEFT JOIN for formName
- GET computes fieldCount server-side from signatureFields.length per D-12
- POST validates name + formTemplateId, verifies FK exists, returns 201
- Both handlers auth-gated with auth() per D-11
- CREATE TABLE document_templates with 7 columns
- FK constraint form_template_id -> form_templates(id) ON DELETE no action
- No alterations to existing tables
- env_file: .env.production — secrets injected at runtime, not baked into image
- dns array [8.8.8.8, 1.1.1.1] + NODE_OPTIONS=--dns-result-order=ipv4first for SMTP EAI_AGAIN fix
- Named volume uploads:/app/uploads persists PDFs across container restarts
- restart: unless-stopped, port 3000:3000
- .gitignore: added /uploads/ entry for production Docker volume path
- Three-stage node:20-slim Dockerfile with --platform=linux/amd64 on all 3 FROM lines
- Non-root nextjs:nodejs user, seeds/ copied for form library, uploads/ dir pre-created
- HEALTHCHECK via wget pointing to /api/health, CMD node server.js
- .dockerignore excludes node_modules, .next, .git, .env*, uploads/, *.md
- .env.production.example with exactly 11 required vars (template, no real secrets, force-added past .env* glob)
- Runs SELECT 1 via Drizzle db client
- Returns { ok: true, db: 'connected' } with status 200 on success
- Returns { ok: false, error: message } with status 503 on DB failure
- No auth check — intentionally public for Docker HEALTHCHECK
- Extend DocumentRow type with optional signedCount, totalSigners, hasMultipleSigners
- Render badge after StatusBadge only for multi-signer Sent documents (D-11, D-12, D-13)
- Badge: inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 ml-1.5
- Shows '{N}/{M} signed' text from server-computed token counts
- No badge for single-signer or fully-signed documents
- Import signingTokens and sql from drizzle-orm
- Add documents.signers to main select
- Fetch token counts per document in single grouped query (avoids N+1)
- Build tokenMap for O(1) lookup per row
- Produce enrichedRows with signedCount, totalSigners, hasMultipleSigners fields
- Pass enrichedRows to DocumentsTable instead of filteredRows
- PdfViewerWrapper accepts and passes signers/unassignedFieldIds to PdfViewer
- PdfViewer accepts and passes both props to FieldPlacer
- FieldPlacer adds signers/unassignedFieldIds to FieldPlacerProps (optional, defaulted to []/ new Set())
- No rendering changes — prop tunnel only for Wave 2 consumers
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- Server page passes doc.signers as initialSigners to DocumentPageClient
- DocumentPageClient adds signers + unassignedFieldIds state (initialized from server)
- Props threaded to PdfViewerWrapper (signers, unassignedFieldIds) and PreparePanel (signers, onSignersChange, unassignedFieldIds, onUnassignedFieldIdsChange)
- PreparePanel interface extended to accept new optional multi-signer props
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- Step 3.5: fetch signerEmail from tokenRow after atomic claim
- Step 7: accumulate pattern — read from signedFilePath or preparedFilePath as working PDF
- Step 7: write to JTI-keyed _partial_ path to prevent concurrent signer collisions
- Step 8a: date stamps scoped to this signer's date fields (D-09)
- Step 8b: signable fields scoped to this signer's fields (Pitfall 4)
- Step 9.5: JTI-keyed datestamped temp file to prevent collision
- Step 10.5: update signedFilePath to this signer's partial after each signing
- Step 11: remaining-token count check before completion attempt
- Step 11: completionTriggeredAt atomic guard (UPDATE WHERE IS NULL RETURNING)
- Step 12: status='Signed' only in completion winner block (fixes first-signer-wins bug)
- Step 13: agent notification + signer completion emails only at completion
- Legacy null-signerEmail tokens fall through all signer filters unchanged
- Loop over doc.signers when populated: one createSigningToken per signer with signerEmail
- Dispatch all signing emails in parallel via Promise.all
- Preserve legacy single-signer path unchanged when signers is null/empty
- Replace NEXT_PUBLIC_BASE_URL with APP_BASE_URL for signing URLs
- Add audit event with metadata.signerEmail for each signer in multi-signer path
- Import DocumentSigner from schema for type casting
- Sends plain-text email with signed document download link to signer
- Follows established createTransporter() + sendMail() pattern
- Subject: 'Signed copy ready: {documentName}', 72h expiry in body text
- createSigningToken now accepts optional signerEmail param and persists to DB
- Added createSignerDownloadToken (72h TTL, purpose: signer-download)
- Added verifySignerDownloadToken with purpose claim validation
- Migration 0010_sharp_archangel.sql adds signer_email to signing_tokens
- Migration adds signers JSONB column to documents
- Migration adds completion_triggered_at TIMESTAMP to documents
- Additive-only: no DROP columns, no ALTER TYPE, no backfills
- Applied successfully to local Neon/Postgres instance
- Remove 3 console.log statements that printed blank count, all blank descriptions, and AI classifications
- These were development debug statements; not appropriate for production code
- Tests pass (prepare-document.test.ts: 10/10), TypeScript clean
- Red PAGE N label stamped on each image so GPT-4o correctly attributes fields to pages
- Prompt: add 'blank line above label' signature block pattern (common in real estate docs)
- Prompt: explicit rule — place field on blank underline, not on the (Label) text below it
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Max heights reduced: text/date 16pt, initials 18pt, signature 26pt
- 0.5% y nudge pushes fields onto the underline instead of floating above it
- Prompt specifies 1.2% height for text/date, 1.8% for signatures
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Replace fixed 144x36 with AI widthPct/heightPct clamped to per-type min/max
(signatures 100-250x20-40pt, initials 36-80x16-28pt, date 60-130x14-24pt, text 60-280x14-24pt)
- Prompt: explicit 'no inline body text' rule — if text is part of a sentence, skip it
- Prompt: widthPct should match visual underline width, heightPct kept thin (~2-2.5%)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>