---
phase: 06-signing-flow
plan: "04"
subsystem: ui+api
tags: [signature-modal, signature_pad, mobile-canvas, draw-type-saved, atomic-submission, pdf-embed, sha256, audit-trail, one-time-enforcement]

# Dependency graph
requires:
  - phase: 06-signing-flow/06-01
    provides: embedSignatureInPdf(), logAuditEvent(), signingTokens table, verifySigningToken()
  - phase: 06-signing-flow/06-02
    provides: sendAgentNotificationEmail()
  - phase: 06-signing-flow/06-03
    provides: SigningPageClient.tsx with onFieldClick stub, signaturesRef, signedFields state

provides:
  - SignatureModal: Draw/Type/Use Saved tabs with signature_pad (devicePixelRatio scaling, touch-none)
  - SigningPageClient wired to modal: field click opens modal, confirmed field shows preview image
  - POST /api/sign/[token]: atomic one-time claim, PDF embedding, SHA-256 hash, full audit trail
  - /sign/[token]/confirmed: success page for post-submission redirect

affects: [06-05]

# Tech tracking
tech-stack:
  added: []
  patterns:
    - signature_pad initialized with devicePixelRatio scaling — canvas.width/height = offsetWidth/Height * ratio; ctx.scale(ratio, ratio) before mounting SignaturePad
    - Typed signature rendered via offscreen canvas (document.createElement('canvas')) in Dancing Script 700 at 44px
    - Use Saved tab conditioned on localStorage key 'teressa_homes_saved_signature' — only appears if saved sig exists
    - Atomic one-time token claim via Drizzle UPDATE...WHERE isNull(usedAt).returning() — 0 rows returned = 409, no PDF written
    - Coordinates for PDF embedding always from DB signatureFields, never from request body
    - Fire-and-forget email via .then().catch() — sendAgentNotificationEmail failure does not fail the signing response
    - /sign/[token]/confirmed is a static server component — no token re-validation (submission already committed)

key-files:
  created:
    - teressa-copeland-homes/src/app/sign/[token]/_components/SignatureModal.tsx
    - teressa-copeland-homes/src/app/sign/[token]/confirmed/page.tsx
  modified:
    - teressa-copeland-homes/src/app/sign/[token]/_components/SigningPageClient.tsx
    - teressa-copeland-homes/src/app/api/sign/[token]/route.ts

key-decisions:
  - "signedFields changed from Set<string> to Map<string,string> (fieldId->dataURL) to support preview image rendering in field overlays"
  - "handleSubmit in SigningPageClient POSTs to /api/sign/[token] and navigates to /sign/[token]/confirmed on 200 or 409"
  - "Confirmed page is static (no token validation) — the submission already committed the token as used; re-validating would return 'used' state"
  - "Agent notification email uses fire-and-forget pattern — email failure must never prevent the signing confirmation from reaching the client"
  - "void save pattern in handleModalConfirm — save flag acknowledged but localStorage write happens inside SignatureModal before onConfirm fires"

requirements-completed: [SIGN-04, SIGN-05, LEGAL-01, LEGAL-02]

# Metrics
duration: 7min
completed: 2026-03-20
---

# Phase 6 Plan 04: Signature Modal + Submission Route Summary

**SignatureModal with Draw/Type/Use Saved tabs (signature_pad + devicePixelRatio), POST /api/sign/[token] with atomic one-time-use enforcement, SHA-256 PDF hash, and full LEGAL-01/LEGAL-02 audit trail**

## Performance

- **Duration:** 7 min
- **Started:** 2026-03-20T17:33:56Z
- **Completed:** 2026-03-20T17:40:56Z
- **Tasks:** 2
- **Files modified:** 4

## Accomplishments

- SignatureModal.tsx: Draw tab with signature_pad (devicePixelRatio scaling + touch-action:none for mobile), Type tab with Dancing Script cursive preview, Use Saved tab conditionally shown from localStorage
- Save for later checkbox persists drawn/typed signature to localStorage under `teressa_homes_saved_signature` key
- SigningPageClient.tsx: modal wired to field click, signedFields Map tracks fieldId->dataURL, signed overlays show preview image
- POST /api/sign/[token]: atomic UPDATE...WHERE usedAt IS NULL RETURNING — 0 rows = 409, PDF never written on race condition
- embedSignatureInPdf called with server-side field coordinates (never client-supplied x/y)
- pdfHash (SHA-256) and signedFilePath stored in documents table; document status updated to Signed
- signature_submitted and pdf_hash_computed audit events logged (completing LEGAL-01 full 6-event audit trail)
- Fire-and-forget sendAgentNotificationEmail — email failure never fails the signing response
- /sign/[token]/confirmed success page created for post-submission redirect
- npm run build passes cleanly; /sign/[token]/confirmed visible in route manifest

## Task Commits

Each task was committed atomically:

1. **Task 1: SignatureModal + SigningPageClient wiring** - `05b5207` (feat)
2. **Task 2: POST /api/sign/[token] + confirmed page** - `d445c28` (feat)

**Plan metadata:** (docs commit — see below)

## Files Created/Modified

- `teressa-copeland-homes/src/app/sign/[token]/_components/SignatureModal.tsx` - Draw/Type/Use Saved modal; signature_pad with DPR scaling; Dancing Script typed rendering; localStorage save/load
- `teressa-copeland-homes/src/app/sign/[token]/_components/SigningPageClient.tsx` - Updated: modal state, signedFields Map, handleModalConfirm, handleSubmit POST, field preview images
- `teressa-copeland-homes/src/app/api/sign/[token]/route.ts` - Added POST handler: atomic token claim, audit events, PDF embed, hash storage, document status update, agent notification
- `teressa-copeland-homes/src/app/sign/[token]/confirmed/page.tsx` - Static success page: branded header, green checkmark, "Document Signed" message

## Decisions Made

- `signedFields` type changed from `Set<string>` to `Map<string, string>` (fieldId -> dataURL) — needed to render the signature preview image inside each signed overlay.
- `handleSubmit` wired directly in `SigningPageClient` (not as a prop from the server component) — the token is already available as a prop; no need to thread a submit handler through the component tree.
- `/sign/[token]/confirmed` is a static server component with no token validation — re-validation at this point would return `used` state (because the POST already set `usedAt`). The user has already confirmed submission.
- `sendAgentNotificationEmail` is fire-and-forget via `.then().catch()` to avoid blocking the signing response on email delivery.
- `clientName` for the agent email falls back to `doc.name` — the `sendAgentNotificationEmail` signature expects clientName; we use document name as a reasonable fallback when client lookup isn't worth an extra join.

## Deviations from Plan

### Auto-fixed Issues

**1. [Rule 2 - Missing Critical] Created /sign/[token]/confirmed page**
- **Found during:** Task 2 (POST handler)
- **Issue:** The POST handler returns `{ ok: true }` and the client-side `handleSubmit` navigates to `/sign/${token}/confirmed`. Without this page, the redirect would land on a Next.js 404. The plan specified the redirect behavior but did not include a confirmed page task.
- **Fix:** Created a static server component at `/sign/[token]/confirmed/page.tsx` with a branded success UI.
- **Files modified:** `teressa-copeland-homes/src/app/sign/[token]/confirmed/page.tsx` (new)
- **Commit:** `d445c28` (Task 2 commit)

---

**Total deviations:** 1 auto-fixed (Rule 2 — missing critical confirmed landing page)
**Impact on plan:** Necessary for correctness — the POST redirect would 404 without it. Simple static page, no scope creep.

## Issues Encountered

None.

## User Setup Required

None — no external service configuration required for this plan.

## Next Phase Readiness

Phase 6 Plan 04 completes the core signing capture and submission loop:
- Clients can draw, type, or reuse a saved signature for each field
- Submitting POSTs all captured signatures; the server atomically claims the token, embeds all signatures at server-stored coordinates, records SHA-256 hash, updates document status to Signed
- Full LEGAL-01 audit trail (6 events: document_prepared, email_sent, link_opened, document_viewed, signature_submitted, pdf_hash_computed) is now complete
- LEGAL-02 SHA-256 hash stored in documents.pdfHash
- Plan 05 can read signedFilePath to allow the agent to download the signed PDF from the portal

---
*Phase: 06-signing-flow*
*Completed: 2026-03-20*

## Self-Check: PASSED

- FOUND: `teressa-copeland-homes/src/app/sign/[token]/_components/SignatureModal.tsx`
- FOUND: `teressa-copeland-homes/src/app/sign/[token]/_components/SigningPageClient.tsx`
- FOUND: `teressa-copeland-homes/src/app/api/sign/[token]/route.ts`
- FOUND: `teressa-copeland-homes/src/app/sign/[token]/confirmed/page.tsx`
- FOUND: `.planning/phases/06-signing-flow/06-04-SUMMARY.md`
- Commit `05b5207` verified in git log
- Commit `d445c28` verified in git log
