Skip to main content
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

Multi-tenant Isolation

Complete data separation between organizations at the database level

Zero-Trust Authentication

Every API request requires valid authentication with organization context

End-to-End Encryption

Sensitive data encrypted in transit and at rest

Audit Logging

Complete audit trail for all sensitive operations

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

Next.js 15

App Router, Server Components, TypeScript, and advanced caching

shadcn/ui

Modern, accessible component library built on Radix UI

Tailwind CSS

Utility-first CSS framework for rapid development

Liveblocks

Real-time collaboration features like presence and cursors

Backend Technologies

Node.js + TypeScript

Type-safe backend development with modern JavaScript

Prisma ORM

Type-safe database access with PostgreSQL

Clerk Authentication

Multi-tenant authentication with organization support

Socket.IO

Real-time communication and presence tracking

Integration Technologies

Twilio

Voice calls, SMS, and programmable communications

Nylas

Email and calendar integration across providers

Stripe

Payment processing and subscription management

R2/S3

Scalable file storage for documents and recordings

Core Architecture Patterns

1. Multi-Tenant Data Architecture

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

2. API-First Design

// 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

// 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:

Multi-Tenancy Implementation

Every table includes organizationId for data isolation:
-- 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:

Real-Time Features

// 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

Lead Scoring Engine

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

Data Protection

Encryption at Rest

All sensitive data encrypted using AES-256 in the database

Encryption in Transit

TLS 1.3 for all communications, certificate pinning

Secret Management

API keys and secrets stored in encrypted environment variables

Audit Logging

All sensitive operations logged with immutable audit trail

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

Sentry Integration

Real-time error tracking and performance monitoring

Structured Logging

Comprehensive logging with proper log levels and context

Analytics Pipeline

PostHog for user behavior and feature usage analytics

Health Checks

Automated health monitoring for all services

Business Metrics

// 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

Database Design Deep Dive

Explore the complete database schema and relationships

API Architecture

Learn about our API design patterns and best practices

Real-time Features

Understand our WebSocket and collaboration architecture

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