# 07 — Paperless Pipeline Replacement (Transaction Coordination)

## Context
Fogbreak replaces Paperless Pipeline for transaction coordination. The existing `transactions.php` and `deadlines.php` have deal management and compliance checklists. This instruction upgrades them to full TC workflow automation with AI assistance.

## What Paperless Pipeline Does (Full Feature Set)
- Transaction lifecycle management (listing to close)
- Automated task checklists per transaction type
- Task assignment to agents, TCs, title, escrow, mortgage
- Deadline tracking with automated reminders
- Document collection and tracking
- Multi-party visibility (agent, TC, broker can all see progress)
- Email notifications at milestones
- Reporting: open transactions, overdue tasks, closing calendar
- Custom checklists per office/transaction type
- Compliance tracking

## What Already Exists
- `transactions.php`: Deal management, 9 jurisdiction templates (being extracted to DB in instruction 01)
- `deadlines.php`: Relative due dates, dependencies, critical path
- `documents.php`: Upload, versioning, review workflow
- `compliance_items` in database
- Cron: `deadline_notify` for overdue alerts

## What to Build

### 1. TC Workflow Engine
Upgrade beyond simple checklists to full workflow automation:

Create `app/api/tc_workflows.php`:
```
POST /api/tc_workflows.php?action=create         # Create workflow template
GET  /api/tc_workflows.php?action=list            # List templates
POST /api/tc_workflows.php?action=apply&txn=X     # Apply workflow to transaction
GET  /api/tc_workflows.php?action=tasks&txn=X     # Get all tasks for transaction
POST /api/tc_workflows.php?action=complete_task    # Complete a task
POST /api/tc_workflows.php?action=assign_task      # Assign/reassign task
GET  /api/tc_workflows.php?action=overdue          # All overdue tasks across transactions
GET  /api/tc_workflows.php?action=closing_calendar # Calendar of upcoming closings
POST /api/tc_workflows.php?action=ai_suggest       # AI suggests next actions
```

### 2. Transaction Types with Auto-Workflows
When a new deal is created, auto-apply the correct workflow:
- Buyer purchase (standard)
- Seller listing
- Dual agency
- Lease/rental
- Referral (incoming/outgoing)
- New construction/build
- Commercial

Each type has a different task template. Templates are market-aware (loaded from `tc_workflows` table, filtered by market_id).

### 3. Task Dependency Management
Upgrade `deadlines.php`:
- Tasks can depend on other tasks (Task B can't start until Task A completes)
- Critical path highlighting (which tasks, if delayed, push the closing date)
- Automatic due date recalculation when a dependency completes late
- Visual Gantt-style timeline in frontend

### 4. Multi-Party Collaboration
Each transaction involves multiple parties:
- Listing agent, buyer's agent
- Transaction coordinator
- Escrow officer
- Title company
- Mortgage lender
- Home inspector
- Appraiser

Create `transaction_parties` table:
```sql
CREATE TABLE transaction_parties (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL,
    transaction_id INT NOT NULL,
    role VARCHAR(50) NOT NULL,
    name VARCHAR(255),
    email VARCHAR(255),
    phone VARCHAR(50),
    company VARCHAR(255),
    can_view BOOLEAN DEFAULT TRUE,
    can_edit BOOLEAN DEFAULT FALSE,
    portal_token VARCHAR(64),
    created_at TIMESTAMPTZ DEFAULT NOW()
);
```

Each party gets a portal view showing their relevant tasks and documents.

### 5. Document Collection Tracking
Upgrade `documents.php`:
- Per-transaction document checklist (which docs are needed, which are received)
- Document request emails: "We still need your pre-approval letter"
- Auto-reminder if document not received within X days
- Version tracking: which version was signed, which is current
- Integration with eSign (instruction 08) for signature tracking

### 6. Compliance Engine (Market-Aware)
After geographic extraction (instruction 01):
- Load compliance requirements from `compliance_templates` table
- Each market has its own required inspections, permits, certifications
- Track status: not started → in progress → completed → verified
- Evidence file attachment per compliance item
- Auto-notify when compliance item is overdue
- AI suggests compliance items based on property characteristics

### 7. Closing Calendar
- Visual calendar of all upcoming closings
- Color-coded by status (on track, at risk, delayed)
- Click to see full transaction detail
- Filter by agent, office, market
- Export to Google Calendar

### 8. TC Dashboard
- All open transactions with progress bars
- Overdue tasks count (red badges)
- Today's tasks across all transactions
- Documents pending collection
- Upcoming deadlines (next 7 days)
- AI insights: "3 transactions are missing inspection contingency removal — all due this week"

### 9. AI TC Assistant
Via the AI layer (instruction 03):
- "What should I focus on today?" → AI prioritizes based on deadlines, overdue items, and closing dates
- "Is this transaction on track?" → AI analyzes tasks, deadlines, and flags risks
- Auto-generate status update emails to all parties
- Suggest task assignments based on workload
- Draft missing document request emails
- Flag unusual patterns: "This inspection was scheduled after the contingency deadline"

### 10. Reporting
- Open transactions by agent/office
- Average days-to-close by market
- Overdue task frequency (which tasks are most commonly late)
- TC workload (transactions per TC)
- Compliance completion rates
- Document collection rates

## Cron Jobs (add to cron.php)
- `tc_daily_digest`: Morning email to TCs with today's tasks
- `tc_overdue_alerts`: Alert when tasks pass due date
- `tc_document_reminders`: Re-request missing documents
- `tc_closing_countdown`: 7-day, 3-day, 1-day closing reminders
- `tc_compliance_check`: Flag overdue compliance items

## Acceptance Criteria
- [ ] TC workflow engine with market-aware task templates
- [ ] Auto-apply correct workflow based on transaction type + market
- [ ] Task dependencies with critical path and auto-recalculation
- [ ] Multi-party collaboration with role-based portal access
- [ ] Document collection tracking with auto-reminders
- [ ] Market-aware compliance engine (loads from database, not code)
- [ ] Closing calendar with status color-coding
- [ ] TC dashboard with overdue alerts and AI insights
- [ ] AI TC assistant for prioritization and drafting
- [ ] All features tenant-aware and market-aware
