dealroom/ENHANCED_LOVABLE_SPEC.md

478 lines
16 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Dealspace AI - Complete Lovable Prototype Specification
> Comprehensive analysis from Chrome DevTools extraction and Lovable development conversation
## Executive Summary
Dealspace AI is a sophisticated M&A data room platform with AI-powered diligence assistance. Built on Supabase with React/TypeScript frontend, it provides role-based access for sellers and buyers with comprehensive deal management, document organization, and Atlas AI integration for intelligent diligence support.
## Demo Data Overview
The platform contains rich demo data with:
- **4 Deals**: Project Aurora, Beacon, Catalyst, Delta
- **12 Documents** organized in 5 folders per deal
- **23 Diligence Requests** across 2 deals
- **8 Contacts** with buyer/seller/advisor types
- **Demo Organization**: "Apex Capital Partners"
- **Demo Users**:
- Sarah Chen (Seller/Owner role)
- James Park (Buyer/Viewer role)
## Architecture
### Frontend (React 18 + TypeScript)
```
src/
├── pages/ # Main application pages (11 pages)
│ ├── Analytics.tsx # Deal performance metrics
│ ├── AuditLog.tsx # Activity tracking
│ ├── Auth.tsx # Authentication with demo modes
│ ├── Contacts.tsx # Contact management
│ ├── Dashboard.tsx # Main overview with deal cards
│ ├── DealRoom.tsx # Individual deal room with tabs
│ ├── DealRooms.tsx # Deal listing with timelines
│ ├── ICMemos.tsx # Investment committee memos
│ ├── RequestList.tsx # Diligence request management
│ ├── Settings.tsx # User/org settings
│ └── PlatformGuide.tsx # Documentation
├── components/ # Core reusable components
│ ├── AppLayout.tsx # Main app shell
│ ├── AppShell.tsx # Navigation wrapper
│ ├── AtlasGlobalChat.tsx # AI chat interface
│ ├── AtlasSidebar.tsx # AI assistant sidebar
│ ├── DealRequestsPanel.tsx # Request management
│ └── NavLink.tsx # Navigation components
├── hooks/ # Custom React hooks
│ ├── useAuth.ts # Authentication state
│ ├── useOrganization.ts # Org context
│ ├── useTheme.ts # Dark/light mode
│ └── useUserRole.ts # Role-based access
├── lib/ # Utilities
│ ├── api.ts # API layer
│ └── utils.ts # Helper functions
├── integrations/supabase/ # Backend integration
│ ├── client.ts # Supabase client
│ └── types.ts # TypeScript types
└── components/ui/ # Shadcn/UI components (50+ components)
```
### Backend (Supabase)
```
supabase/
├── migrations/ # Database schema (5 migration files)
│ ├── 20260214204302_*.sql # Initial schema
│ ├── 20260214210921_*.sql # Demo data seeding
│ ├── 20260214212128_*.sql # Request list enhancements
│ ├── 20260214222633_*.sql # Buyer group segmentation
│ └── 20260214224626_*.sql # Role-based access
└── functions/ # Edge functions (5 functions)
├── atlas-chat/ # AI document Q&A
├── compute-deal-score/ # Deal scoring algorithms
├── demo-login/ # Demo account creation
├── folder-summary/ # AI folder summaries
└── generate-ic-memo/ # IC memo generation
```
## Database Schema (Inferred from Development History)
### Core Tables
- **organizations** - Multi-tenant organization structure
- **profiles** - User profiles linked to Supabase auth
- **deals** - Deal rooms with metadata
- **folders** - Document organization within deals
- **documents** - File storage and metadata
- **diligence_requests** - Request list items
- **contacts** - Contact management
- **audit_logs** - Activity tracking
### Key Fields Added During Development
- **diligence_requests**:
- `buyer_comment` (text, nullable) - Buyer notes on requests
- `seller_comment` (text, nullable) - Seller notes on requests
- `buyer_group` (text, nullable) - Segmentation by buyer groups
- `atlas_status` (enum) - fulfilled/partial/missing
- `atlas_note` (text) - AI assessment summary
- `confidence_score` (numeric) - AI confidence rating
- **deals**:
- `ioi_date` (date) - Indication of Interest date
- `loi_date` (date) - Letter of Intent date
- `exclusivity_days` (integer) - Days remaining in exclusivity
- `stage` (enum) - Deal stage tracking
### Row Level Security (RLS)
- **Owner Role (Sellers)**: Full access to organization data
- **Viewer Role (Buyers)**: Filtered access based on buyer_group assignments
- **Buyer Group Filtering**: Automatic data scoping based on user assignments
## Atlas AI System
### Core AI Functions
1. **Atlas Chat (`atlas-chat/index.ts`)**
- Document-based Q&A using RAG
- Concise, bullet-point responses
- Document hyperlinking (e.g., `[FileName.pdf](/folder)`)
- Emoji-prefixed status indicators (✅/⚠️/🔴)
- Integrated with markdown parser for rich rendering
2. **Deal Scoring (`compute-deal-score/index.ts`)**
- Automated deal risk assessment
- Completion probability calculations
- Timeline urgency scoring
3. **Folder Summarization (`folder-summary/index.ts`)**
- AI-generated folder summaries
- Document completeness scoring (e.g., "85%" for Financial Statements)
- Integration with deal room folder views
4. **IC Memo Generation (`generate-ic-memo/index.ts`)**
- Investment Committee memo creation
- Data synthesis from deal room contents
- Buyer-role specific functionality
5. **Demo Login (`demo-login/index.ts`)**
- Separate seller/buyer demo account creation
- Automatic organization assignment
- RLS policy compliance for demo data access
## User Roles & Access Control
### Seller (Owner) Role - "Sarah Chen"
**Full Platform Access:**
- Dashboard with all deals and metrics
- Deal Rooms management (create, upload, organize)
- Request Lists with "View All" consolidated view
- Analytics and performance metrics
- Contacts management
- Audit Log visibility
- Settings and configuration
- Platform Guide access
- **Excluded**: IC Memos tab (buyer-only feature)
**Capabilities:**
- Create new deal rooms
- Upload CSV request lists with optional "Buyer Group" column
- Edit seller comments on requests
- Manage document folders and uploads
- View all buyer group request lists
### Buyer (Viewer) Role - "James Park"
**Limited Platform Access:**
- Dashboard (filtered to assigned deals only)
- Deal Rooms (access only to assigned deals)
- Request Lists (filtered to buyer group only)
- IC Memos generation tool
- Platform Guide access
- **Excluded**: Analytics, Contacts, Audit Log, Settings
**Data Filtering:**
- Project Aurora via "Meridian Capital" buyer group
- Project Beacon via "Summit Health Equity" buyer group
- No create/upload actions available
- Can only edit buyer comments on requests
**Specific Deal Assignments:**
- **Project Aurora**: "Meridian Capital" / "Horizon Partners" buyer groups
- **Project Beacon**: "Summit Health Equity" / "Northstar Health Capital" buyer groups
- **Project Catalyst**: Additional buyer groups as configured
- **Project Delta**: Additional buyer groups as configured
## Key Features Deep Dive
### 1. Deal Room Management
**Structure:**
- Deal rooms with tabbed interface (Documents / Request List)
- 5 folders per deal with AI-generated summaries
- Document upload and organization
- Folder completeness scoring (e.g., "Financial Statements: 85%")
**Timeline Tracking:**
- IOI Date (Indication of Interest)
- LOI Date (Letter of Intent)
- Exclusivity Period with color-coded urgency:
- Green: >30 days remaining
- Yellow: 10-30 days remaining
- Red: <10 days remaining
**Deal Stages:**
- Stage badges replacing risk percentages
- Visual status indicators
- Progress tracking
### 2. Request List System
**Segmentation:**
- Buyer group tabs (e.g., "Meridian Capital", "Horizon Partners")
- "View All" tab for seller consolidated view
- 23 demo requests across Project Aurora and Beacon
**Column Structure:**
1. Request item description
2. Section grouping
3. Buyer comment (inline-editable)
4. Seller comment (inline-editable)
5. Atlas Note (AI assessment summary)
6. Atlas Status (fulfilled/partial/missing with confidence scores)
**CSV Import/Export:**
- Supports "Buyer Group" column for automatic segmentation
- Bulk request list management
- Data interchange capabilities
**Atlas Assessment:**
- **11 Fulfilled** requests with status
- **5 Partial** requests with status
- **7 Missing** requests with 🔴 status
- AI-generated notes for status rationale (blank when missing)
### 3. Authentication & Demo System
**Demo Mode Implementation:**
- Bifurcated demo buttons on auth page
- "Seller Demo" Sarah Chen (owner role)
- "Buyer Demo" James Park (viewer role)
- Real account creation with RLS compliance
- Identical data access as normal login
**Security:**
- Supabase authentication
- Organization-scoped access
- Role-based navigation filtering
- Comment editing permissions by role
### 4. Atlas AI Integration
**Response Characteristics:**
- Concise, bullet-point format
- Document hyperlinks: `[FileName.pdf](/folder)`
- Status indicators: (complete), (partial), 🔴 (missing)
- Markdown rendering with link support
- Context-aware responses based on deal room contents
**UI Integration:**
- AtlasGlobalChat component for document Q&A
- AtlasSidebar for persistent AI assistance
- Inline status indicators in request lists
- Confidence scoring for assessments
### 5. UI/UX Features
**Theme System:**
- Light/dark mode toggle in sidebar footer (sun/moon icon)
- Defaults to dark mode
- Persists via localStorage
- Flash-free loading with initial script
- Clean white/gray palette for light mode
- Consistent teal accent color
**Navigation:**
- Role-based sidebar navigation
- Platform Guide with TOC and expandable accordions
- Role badges displayed in sidebar
- Responsive design for mobile/desktop
## Technology Stack
**Frontend:**
- React 18 with TypeScript
- Vite build system
- Tailwind CSS for styling
- Shadcn/UI component library (50+ components)
- Lucide Icons
- State management via React Context API
**Backend:**
- Supabase (PostgreSQL + Auth + Edge Functions)
- Row Level Security (RLS) policies
- Real-time subscriptions
- File storage integration
**AI Integration:**
- OpenAI API via Supabase Edge Functions
- RAG (Retrieval Augmented Generation) for document Q&A
- Custom prompt engineering for concise responses
- Document embedding and vector search
## Detailed Development History
Based on the extracted conversation, the platform evolved through these key phases:
### Phase 1: Initial Demo Data Population
- Rich demo data creation with 4 deals
- 12 documents across 5 folders per deal
- 23 diligence requests with AI assessments
- 8 contacts with type classifications
- Platform Guide documentation
### Phase 2: Atlas AI Refinement
- Rewrote system prompts for concise responses
- Added document hyperlinking capability
- Implemented emoji status indicators
- Enhanced markdown parser for link rendering
### Phase 3: UI/UX Enhancements
- Light/dark mode toggle implementation
- Request list integration within deal rooms
- Tabbed interface (Documents / Request List)
- Responsive design improvements
### Phase 4: Demo Authentication System
- Demo mode implementation for testing
- Real demo account creation via edge function
- RLS compliance for demo data access
- Bypass authentication for UI testing
### Phase 5: Request List Enhancements
- Buyer/seller comment columns (inline-editable)
- Buyer group segmentation with tabs
- CSV import with "Buyer Group" column support
- Atlas Note column for AI assessments
### Phase 6: Buyer Group Segmentation
- Multiple request lists per deal by buyer group
- Demo data for buyer group assignments
- "View All" seller perspective
- Filtered buyer access by group
### Phase 7: Atlas Assessment Integration
- Atlas Note column implementation
- Brief AI summaries for request status
- Blank notes for missing items
- Status-based conditional display
### Phase 8: Deal Timeline Features
- Removed close percentage and risk metrics
- IOI/LOI date tracking implementation
- Exclusivity period countdown with color coding
- Stage-based deal progression
### Phase 9: Role-Based Access Control
- Bifurcated demo login (Seller/Buyer)
- Role-based sidebar navigation
- Data filtering by buyer group assignments
- Comment editing permissions by role
- Role badge display in sidebar
## Migration to Go - Implementation Guide
### 1. Database Migration
```sql
-- Example table structure based on features
CREATE TABLE organizations (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE deals (
id UUID PRIMARY KEY,
organization_id UUID REFERENCES organizations(id),
name TEXT NOT NULL,
stage TEXT,
ioi_date DATE,
loi_date DATE,
exclusivity_days INTEGER,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE diligence_requests (
id UUID PRIMARY KEY,
deal_id UUID REFERENCES deals(id),
description TEXT NOT NULL,
section TEXT,
buyer_group TEXT,
buyer_comment TEXT,
seller_comment TEXT,
atlas_status TEXT CHECK (atlas_status IN ('fulfilled', 'partial', 'missing')),
atlas_note TEXT,
confidence_score DECIMAL(3,2),
created_at TIMESTAMPTZ DEFAULT NOW()
);
```
### 2. Authentication System
- JWT-based authentication with organization scoping
- Role-based access control (owner/viewer)
- Demo account generation endpoints
- Session management with refresh tokens
### 3. AI Integration Architecture
```go
// Example Go structure for Atlas AI
type AtlasService struct {
openaiClient *openai.Client
vectorStore VectorStore
}
type DocumentQuery struct {
Question string `json:"question"`
DealID string `json:"deal_id"`
Context []string `json:"context"`
}
type AtlasResponse struct {
Answer string `json:"answer"`
Confidence float64 `json:"confidence"`
Sources []DocumentReference `json:"sources"`
Status string `json:"status"` // fulfilled, partial, missing
}
```
### 4. API Endpoints
```
POST /api/auth/demo-login
POST /api/atlas/chat
POST /api/atlas/folder-summary
POST /api/atlas/ic-memo
GET /api/deals
GET /api/deals/{id}/requests
POST /api/deals/{id}/requests/csv-import
PATCH /api/requests/{id}/comments
```
### 5. Role-Based Filtering
```go
func FilterRequestsByBuyerGroup(requests []Request, userRole string, buyerGroup string) []Request {
if userRole == "owner" {
return requests // Sellers see all
}
var filtered []Request
for _, req := range requests {
if req.BuyerGroup == buyerGroup || req.BuyerGroup == "" {
filtered = append(filtered, req)
}
}
return filtered
}
```
## Business Logic Patterns
### Demo Data Seeding
- 4 predefined deals with realistic names
- Buyer group assignments per deal
- AI-generated folder summaries
- Request list segmentation by buyer groups
### Atlas AI Prompt Engineering
- System prompts optimized for concise responses
- Document context injection for RAG
- Status classification logic (fulfilled/partial/missing)
- Confidence scoring algorithms
### Audit Logging
- Activity tracking across all user actions
- Role-based log filtering
- Timeline view of deal progression
- User interaction monitoring
## Critical Implementation Notes
1. **RLS Compliance**: All data access must respect buyer group assignments
2. **AI Response Format**: Maintain emoji status indicators and document linking
3. **Demo Mode**: Ensure demo accounts have identical data access to real accounts
4. **CSV Import**: Support buyer group column for request segmentation
5. **Timeline Urgency**: Implement color-coded exclusivity period warnings
6. **Comment System**: Separate buyer/seller comment fields with role-based editing
7. **Theme Persistence**: Implement localStorage-based theme switching
8. **Responsive Design**: Mobile-first approach with sidebar collapsing
This comprehensive specification captures the complete feature set, data model, and implementation patterns from the Dealspace AI Lovable prototype, providing a complete blueprint for Go migration.