# 08 — DocuSign Replacement (eSignature)

## Context
Fogbreak replaces DocuSign. The existing `esign.php` (2,793 lines) + `sign.html` is 70% complete but has 5 critical security issues and missing features. This instruction fixes security first, then builds the remaining features.

## Existing State
Built: envelope creation (27 endpoints), sequential/parallel signing, SHA-256 audit trail, email automation, PDF viewer with 3 signature methods, ESIGN Act compliance, cron reminders.

## CRITICAL FIXES (Do These First — ~45 minutes)

### Fix 1: SQL Injection (Line 758)
`handleRemoveRecipient` has raw string interpolation. Replace with prepared statement.

### Fix 2: Hardcoded tenant_id=1 (8 Locations)
Search `esign.php` for `tenant_id = 1` or `tenant_id=1`. Replace all 8 with `$_SESSION['tenant_id']` or the tenant parameter.

### Fix 3: Missing tenant_id Filters
Several envelope queries don't filter by tenant_id. Add `AND tenant_id = ?` to every query. Cross-tenant data leak risk.

### Fix 4: PIN Validation Bypass
PIN is generated but never validated during signing. Add PIN check before allowing signature submission.

### Fix 5: Deal Ownership Check
No verification that the requesting user owns the deal they're creating an envelope for. Add ownership check.

See `app/api/ESIGN_CRITICAL_FIXES.md` for exact line numbers and patches.

## Features to Build After Fixes

### 1. Entity Signer Workflows
80% of luxury deals involve trusts, corporations, LLCs. Build:
- Entity type selection (trust, corp, LLC, partnership, estate)
- Trust certification document attachment
- Corporate resolution document attachment
- Authorized signer designation (who can sign for the entity)
- Multiple authorized signers support
- Entity name appears on signature line, authorized signer signs

### 2. Signing Groups
"Both spouses must sign" — common in real estate:
- Create signing group with N required signers
- Envelope doesn't complete until all group members sign
- Track individual progress within group
- Reminder sent to group members who haven't signed

### 3. Delegation
Transfer signing authority:
- Signer A delegates to Signer B (e.g., power of attorney)
- Audit trail records delegation
- Delegation requires authorization document upload
- Original signer still listed, delegate signs on their behalf

### 4. Anchor Tagging
Auto-place signature fields from template variables (currently manual x/y):
- Define anchor text in document (e.g., "{{BUYER_SIGNATURE}}", "{{DATE}}", "{{INITIALS}}")
- When document is uploaded, scan for anchors
- Auto-place signature/date/initial fields at anchor positions
- Fallback to manual placement if no anchors found

### 5. Auto-Populate from Deal Data
Connect envelopes to transaction data:
- When creating envelope from a deal, auto-fill: buyer name, seller name, property address, purchase price, closing date, agent info
- Template variables: {{buyer_name}}, {{seller_name}}, {{property_address}}, {{purchase_price}}, etc.
- Populate from `transactions` and `clients` tables

### 6. Pre-Built Template Library
Market-aware document templates:
- Purchase Agreement (market-specific)
- Counter Offer
- Addendums (inspection, financing, appraisal)
- Disclosures (loaded from market compliance templates)
- Listing Agreement
- Buyer Representation Agreement
- Commission Agreement

Templates stored in database, associated with market_id. Each market has its own required documents.

### 7. Webhook Callbacks
Push notifications when signing events occur:
- Envelope sent, viewed, signed, completed, declined, voided
- Webhook URL configurable per tenant
- Retry logic for failed deliveries
- Event log for debugging

### 8. Bulk Send
Send same document to multiple recipients:
- Upload once, send to N signers with personalized fields
- Use case: disclosure package to all buyers
- Progress tracking per recipient

### 9. Mobile Signing Experience
Optimize `sign.html` for mobile:
- Touch-friendly signature pad
- Pinch-to-zoom on document
- Responsive field placement
- Progressive loading for large PDFs

### 10. Audit Trail Enhancement
- Downloadable certificate of completion (PDF)
- Complete timeline: created → sent → viewed → signed → completed
- IP address, device, browser for each action
- Tamper-evident seal (hash chain)

## Acceptance Criteria
- [ ] All 5 critical security fixes applied and verified
- [ ] Entity signer workflows (trust, corp, LLC)
- [ ] Signing groups with multi-signer tracking
- [ ] Delegation with authorization documents
- [ ] Anchor tagging auto-places signature fields
- [ ] Auto-populate from deal data
- [ ] Pre-built template library (market-aware)
- [ ] Webhook callbacks for signing events
- [ ] Bulk send capability
- [ ] Mobile-optimized signing experience
- [ ] Enhanced audit trail with downloadable certificate
- [ ] All features tenant-aware and market-aware
