> ## Documentation Index
> Fetch the complete documentation index at: https://docs.winnerr.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture Overview

> Deep dive into Winnerr's monorepo structure, design patterns, and technology stack

Winnerr CRM is built as a modern monorepo using cutting-edge technologies to deliver a scalable, secure, and feature-rich real estate platform. This overview explains our architectural decisions and how the various components work together.

## Monorepo Structure

Winnerr uses a monorepo approach with pnpm workspaces and Turborepo for efficient development and deployment:

```
winnerr-works/
├── apps/                    # Application layers
│   ├── app/                # Main CRM application (Next.js 15)
│   ├── api/                # Backend API services
│   ├── web/                # Marketing website
│   ├── docs/               # This documentation site
│   ├── email/              # Email templates (React Email)
│   ├── storybook/          # Component documentation
│   └── chrome-extension/   # Browser extension for lead capture
├── packages/               # Shared packages
│   ├── ai/                 # AI services and components
│   ├── analytics/          # Analytics and tracking
│   ├── auth/               # Authentication (Clerk)
│   ├── database/           # Prisma schema and utilities
│   ├── design-system/      # shadcn/ui components
│   ├── mcp/                # Model Context Protocol
│   ├── notifications/      # Push notifications
│   ├── payments/           # Stripe integration
│   ├── storage/            # R2/S3 file storage
│   └── twilio/             # Phone and SMS services
└── dev-docs/              # Development documentation
```

## Design Principles

### 1. Security-First Architecture

<CardGroup cols={2}>
  <Card title="Multi-tenant Isolation" icon="shield-check">
    Complete data separation between organizations at the database level
  </Card>

  <Card title="Zero-Trust Authentication" icon="key">
    Every API request requires valid authentication with organization context
  </Card>

  <Card title="End-to-End Encryption" icon="lock">
    Sensitive data encrypted in transit and at rest
  </Card>

  <Card title="Audit Logging" icon="file-lines">
    Complete audit trail for all sensitive operations
  </Card>
</CardGroup>

### 2. Real Estate Domain Modeling

Unlike generic CRMs, Winnerr's architecture is purpose-built for real estate:

* **Property-Centric Design**: All entities relate back to properties
* **Deal Lifecycle Management**: Built-in pipeline stages and commission tracking
* **Communication Workflows**: Integrated phone, SMS, and email systems
* **Compliance Features**: Built-in support for real estate regulations

### 3. AI-First Integration

AI capabilities are not bolt-on features but core architectural components:

* **Voice Processing Pipeline**: Real-time voice commands and transcription
* **Sentiment Analysis Engine**: Continuous call and communication analysis
* **Predictive Analytics**: Lead scoring and market trend analysis
* **Context-Aware Assistance**: AI that understands real estate workflows

## Technology Stack

### Frontend Technologies

<CardGroup cols={2}>
  <Card title="Next.js 15" icon="react">
    App Router, Server Components, TypeScript, and advanced caching
  </Card>

  <Card title="shadcn/ui" icon="palette">
    Modern, accessible component library built on Radix UI
  </Card>

  <Card title="Tailwind CSS" icon="css3">
    Utility-first CSS framework for rapid development
  </Card>

  <Card title="Liveblocks" icon="users">
    Real-time collaboration features like presence and cursors
  </Card>
</CardGroup>

### Backend Technologies

<CardGroup cols={2}>
  <Card title="Node.js + TypeScript" icon="node-js">
    Type-safe backend development with modern JavaScript
  </Card>

  <Card title="Prisma ORM" icon="database">
    Type-safe database access with PostgreSQL
  </Card>

  <Card title="Clerk Authentication" icon="user-shield">
    Multi-tenant authentication with organization support
  </Card>

  <Card title="Socket.IO" icon="bolt">
    Real-time communication and presence tracking
  </Card>
</CardGroup>

### Integration Technologies

<CardGroup cols={2}>
  <Card title="Twilio" icon="phone">
    Voice calls, SMS, and programmable communications
  </Card>

  <Card title="Nylas" icon="envelope">
    Email and calendar integration across providers
  </Card>

  <Card title="Stripe" icon="credit-card">
    Payment processing and subscription management
  </Card>

  <Card title="R2/S3" icon="cloud">
    Scalable file storage for documents and recordings
  </Card>
</CardGroup>

## Core Architecture Patterns

### 1. Multi-Tenant Data Architecture

```mermaid theme={null}
graph TB
    A[User Request] --> B[Auth Middleware]
    B --> C[Organization Context]
    C --> D[Database Query]
    D --> E[Row-Level Security]
    E --> F[Filtered Results]
    
    subgraph "Organization A Data"
        G[Users A]
        H[Deals A]
        I[Properties A]
    end
    
    subgraph "Organization B Data"
        J[Users B]
        K[Deals B]
        L[Properties B]
    end
    
    E --> G
    E --> H
    E --> I
```

Every database query includes organization context to ensure complete data isolation.

### 2. API-First Design

```typescript theme={null}
// Standard API route pattern
export async function POST(req: Request) {
  // 1. Authentication & organization context
  const { userId, orgId } = await auth();
  
  // 2. Input validation with Zod
  const data = requestSchema.parse(await req.json());
  
  // 3. Business logic with proper error handling
  const result = await businessLogic(data, { userId, orgId });
  
  // 4. Structured response with CORS
  return NextResponse.json(result, { headers: corsHeaders });
}
```

### 3. Event-Driven Architecture

```typescript theme={null}
// Event system for real-time updates
export const eventBus = {
  emit: (event: string, data: unknown, orgId: string) => {
    // Emit to organization-specific channels
    io.to(`org:${orgId}`).emit(event, data);
    
    // Log for analytics
    analytics.track(event, data, { orgId });
  }
};
```

## Database Design

### Core Entities

The database schema centers around real estate workflows:

```mermaid theme={null}
erDiagram
    Organization ||--o{ User : has
    Organization ||--o{ Person : manages
    Organization ||--o{ Property : lists
    Organization ||--o{ Deal : tracks
    
    User ||--o{ TwilioPhoneNumber : assigned
    User ||--o{ Communication : sends
    
    Person ||--o{ Deal : involves
    Property ||--o{ Deal : associated
    
    Deal ||--o{ Task : generates
    Deal ||--o{ Communication : triggers
    
    TwilioCall ||--|| CallRecording : records
    CallRecording ||--o{ TranscriptSegment : contains
```

### Multi-Tenancy Implementation

Every table includes `organizationId` for data isolation:

```sql theme={null}
-- Example: People table with organization isolation
CREATE TABLE "Person" (
  "id" TEXT PRIMARY KEY,
  "organizationId" TEXT NOT NULL,
  "firstName" TEXT,
  "lastName" TEXT,
  "email" TEXT,
  "phone" TEXT,
  "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  
  FOREIGN KEY ("organizationId") REFERENCES "Organization"("id")
);

-- Row-level security policy
CREATE POLICY person_isolation ON "Person"
  FOR ALL USING (
    "organizationId" = current_setting('app.current_organization')
  );
```

## Communication Architecture

### Unified Communication Hub

All communication channels flow through a unified system:

```mermaid theme={null}
graph LR
    A[Twilio Webhooks] --> E[Communication Hub]
    B[Nylas Webhooks] --> E
    C[Chrome Extension] --> E
    D[Direct API] --> E
    
    E --> F[Database Storage]
    E --> G[Real-time Events]
    E --> H[AI Processing]
    
    F --> I[CRM Interface]
    G --> I
    H --> J[Sentiment Analysis]
    H --> K[Lead Scoring]
```

### Real-Time Features

```typescript theme={null}
// Real-time presence system
class PresenceManager {
  private connections = new Map<string, Set<string>>();
  
  joinOrganization(userId: string, orgId: string) {
    // Add user to organization room
    this.connections.get(orgId)?.add(userId);
    
    // Broadcast presence update
    this.broadcastPresence(orgId);
  }
  
  broadcastPresence(orgId: string) {
    const users = Array.from(this.connections.get(orgId) || []);
    io.to(`org:${orgId}`).emit('presence:update', { users });
  }
}
```

## AI Architecture

### Voice Processing Pipeline

```mermaid theme={null}
graph TB
    A[Voice Input] --> B[WebRTC Stream]
    B --> C[Twilio Recording]
    C --> D[Spectropic Transcription]
    D --> E[Speech-to-Text]
    E --> F[Intent Recognition]
    F --> G[Command Execution]
    
    D --> H[Sentiment Analysis]
    H --> I[Coaching Insights]
    
    E --> J[Search Processing]
    J --> K[Vector Search]
    K --> L[Results Display]
```

### Lead Scoring Engine

```typescript theme={null}
interface LeadScoringFactors {
  behavioralScore: number;    // Website interactions, email opens
  engagementScore: number;    // Response rates, call duration
  demographicScore: number;   // Location, property preferences
  timelineScore: number;      // Urgency indicators
  sourceScore: number;        // Lead source quality
}

class EnhancedLeadScoring {
  calculateScore(person: Person, factors: LeadScoringFactors): number {
    // AI-powered scoring algorithm
    return this.aiModel.predict({
      ...factors,
      historicalData: person.interactions,
      marketConditions: this.getMarketData(person.location)
    });
  }
}
```

## Security Architecture

### Authentication Flow

```mermaid theme={null}
sequenceDiagram
    participant C as Client
    participant A as App
    participant K as Clerk
    participant API as API Server
    participant D as Database
    
    C->>A: Login Request
    A->>K: Authenticate User
    K->>A: JWT Token + User Data
    A->>API: API Request + JWT
    API->>K: Verify Token
    K->>API: User + Organization Context
    API->>D: Query with Organization Filter
    D->>API: Filtered Results
    API->>A: Response
    A->>C: UI Update
```

### Data Protection

<CardGroup cols={2}>
  <Card title="Encryption at Rest" icon="database">
    All sensitive data encrypted using AES-256 in the database
  </Card>

  <Card title="Encryption in Transit" icon="shield-halved">
    TLS 1.3 for all communications, certificate pinning
  </Card>

  <Card title="Secret Management" icon="key">
    API keys and secrets stored in encrypted environment variables
  </Card>

  <Card title="Audit Logging" icon="file-shield">
    All sensitive operations logged with immutable audit trail
  </Card>
</CardGroup>

## Scalability Considerations

### Horizontal Scaling

* **Database**: Read replicas for analytics workloads
* **API Servers**: Stateless design enables easy horizontal scaling
* **File Storage**: R2/S3 for infinite storage scaling
* **Real-time**: Realtime provider channels plus database-backed event state

### Performance Optimization

* **Caching Strategy**: Database-backed durable state plus scoped in-memory request caches
* **Database Optimization**: Proper indexing and query optimization
* **CDN Integration**: Global content delivery for static assets
* **Code Splitting**: Lazy loading for optimal bundle sizes

## Monitoring & Observability

### Error Tracking & Performance

<CardGroup cols={2}>
  <Card title="Sentry Integration" icon="bug">
    Real-time error tracking and performance monitoring
  </Card>

  <Card title="Structured Logging" icon="list">
    Comprehensive logging with proper log levels and context
  </Card>

  <Card title="Analytics Pipeline" icon="chart-line">
    PostHog for user behavior and feature usage analytics
  </Card>

  <Card title="Health Checks" icon="heart-pulse">
    Automated health monitoring for all services
  </Card>
</CardGroup>

### Business Metrics

```typescript theme={null}
// Analytics event tracking
analytics.track('deal_created', {
  dealValue: deal.amount,
  propertyType: deal.property.type,
  leadSource: deal.person.source,
  agentId: deal.assignedTo,
  organizationId: deal.organizationId
});
```

## Next Steps

<CardGroup cols={3}>
  <Card title="Database Design Deep Dive" icon="database" href="/architecture/database-design">
    Explore the complete database schema and relationships
  </Card>

  <Card title="API Architecture" icon="code" href="/architecture/api-architecture">
    Learn about our API design patterns and best practices
  </Card>

  <Card title="Real-time Features" icon="bolt" href="/architecture/real-time-features">
    Understand our WebSocket and collaboration architecture
  </Card>
</CardGroup>

***

<Note>
  This architecture is designed to scale from individual agents to large enterprise brokerages while maintaining security, performance, and developer experience.
</Note>
