# System Architecture

High-level overview of the Orion multi-tenant e-commerce platform architecture.

## Overview

Orion is a **multi-tenant e-commerce platform** that supports three distinct interfaces:
- **Admin** - Platform administration and store management
- **Store** - Store dashboard for managing shops
- **Shop** - Customer-facing storefronts

## Technology Stack

### Backend
- **Framework**: FastAPI (Python)
- **Database**: PostgreSQL with SQLAlchemy ORM
- **Authentication**: JWT-based with bcrypt password hashing
- **API**: RESTful JSON APIs

### Frontend
- **Templates**: Jinja2 server-side rendering
- **JavaScript**: Alpine.js for reactive components
- **CSS**: Tailwind CSS
- **Icons**: Lucide Icons

### Infrastructure
- **Web Server**: Uvicorn (ASGI)
- **Middleware**: Custom middleware stack for multi-tenancy
- **Static Files**: FastAPI StaticFiles

## System Components

### 1. Multi-Tenant Routing

The platform supports three deployment modes:

#### Custom Domain Mode
```
customdomain.com → Store 1 Shop
anotherdomain.com → Store 2 Shop
```

#### Subdomain Mode
```
store1.platform.com → Store 1 Shop
store2.platform.com → Store 2 Shop
admin.platform.com → Admin Interface
```

#### Path-Based Mode (Development Only)
```
platform.com/stores/store1/shop → Store 1 Shop
platform.com/stores/store2/shop → Store 2 Shop
platform.com/admin                → Admin Interface
```

**See:** [Multi-Tenant System](multi-tenant.md) for detailed implementation

### 2. Middleware Stack

Custom middleware handles:
- Store detection and context injection
- Request context detection (API/Admin/Store/Shop)
- Theme loading for store shops
- Request/response logging
- Path rewriting for multi-tenant routing

**See:** [Middleware Stack](middleware.md) for complete documentation

### 3. Authentication & Authorization

- JWT-based authentication
- Role-based access control (RBAC)
- Three user roles: Admin, Store, Customer
- Hierarchical permissions system

**See:** [Authentication & RBAC](auth-rbac.md) for details

### 4. Module System

The platform uses a modular architecture with three-tier classification:

```
┌─────────────────────────────────────────────────────────────┐
│                    FRAMEWORK LAYER                          │
│  (Infrastructure - always available, not modules)           │
│  Config │ Database │ Auth │ Permissions │ Observability     │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                     MODULE LAYER                            │
│                                                             │
│  CORE (Always Enabled)     OPTIONAL (Per-Platform)         │
│  ├── core                  ├── payments                    │
│  ├── tenancy               ├── billing                     │
│  ├── cms                   ├── inventory                   │
│  └── customers             ├── orders                      │
│                            ├── marketplace                 │
│  INTERNAL (Admin-Only)     ├── analytics                   │
│  ├── dev-tools             └── messaging                   │
│  └── monitoring                                            │
└─────────────────────────────────────────────────────────────┘
```

**Module Features:**
- Enable/disable modules per platform
- Module dependencies (billing requires payments)
- Health checks and lifecycle hooks
- Self-contained modules with own services, models, migrations

**See:** [Module System](module-system.md) for complete documentation

### 5. Request Flow

```mermaid
graph TB
    A[Client Request] --> B[Logging Middleware]
    B --> C[Store Context Middleware]
    C --> D[Context Detection Middleware]
    D --> E[Theme Context Middleware]
    E --> F{Request Type?}

    F -->|API /api/*| G[API Router]
    F -->|Admin /admin/*| H[Admin Page Router]
    F -->|Store /store/*| I[Store Page Router]
    F -->|Shop /shop/*| J[Shop Page Router]

    G --> K[JSON Response]
    H --> L[Admin HTML]
    I --> M[Store HTML]
    J --> N[Shop HTML]
```

**See:** [Request Flow](request-flow.md) for detailed journey

## Application Areas

### Admin Interface (`/admin/*`)

**Purpose**: Platform administration

**Features**:
- Store management
- User management
- System settings
- Audit logs
- Analytics dashboard

**Access**: Admin users only

### Store Dashboard (`/store/*`)

**Purpose**: Store shop management

**Features**:
- Product management
- Inventory tracking
- Order processing
- Shop settings
- Team member management
- Analytics

**Access**: Store users (owners and team members)

### Shop Interface (`/shop/*` or custom domains)

**Purpose**: Customer-facing storefront

**Features**:
- Product browsing
- Shopping cart
- Checkout
- Order tracking
- Customer account

**Access**: Public + registered customers

### API (`/api/*`)

**Purpose**: RESTful JSON API for all operations

**Features**:
- All CRUD operations
- Authentication endpoints
- Data export/import
- Webhook support

**Access**: Authenticated users based on role

## Data Architecture

### Database Schema

```
┌─────────────────┐
│     stores     │ ← Multi-tenant root
└────────┬────────┘
         │
         ├─── store_domains
         ├─── store_themes
         ├─── store_settings
         │
         ├─── products ────┬─── product_variants
         │                 ├─── product_images
         │                 └─── product_categories
         │
         ├─── cart_items (session-based shopping cart)
         │
         ├─── orders ──────┬─── order_items
         │                 └─── order_status_history
         │
         └─── customers ───┬─── customer_addresses
                           └─── customer_sessions
```

### Key Design Patterns

1. **Tenant Isolation**: All data scoped to store_id
2. **Soft Deletes**: Records marked as deleted, not removed
3. **Audit Trail**: All changes tracked with user and timestamp
4. **JSON Fields**: Flexible metadata storage

## Security Architecture

### Authentication Flow

```
1. User submits credentials
2. Server validates against database
3. JWT token generated with user info
4. Token returned to client
5. Client includes token in subsequent requests
6. Server validates token on each request
```

### Authorization Layers

1. **Route-level**: Middleware checks user authentication
2. **Role-level**: Decorators enforce role requirements
3. **Resource-level**: Services check ownership/permissions
4. **Tenant-level**: All queries scoped to store

**See:** [Authentication & RBAC](auth-rbac.md)

## Scalability Considerations

### Current Architecture
- **Single server**: Suitable for small to medium deployments
- **In-memory rate limiting**: Per-process limits
- **Session state**: Stateless JWT tokens

### Future Enhancements
- **Horizontal scaling**: Load balancer + multiple app servers
- **Redis integration**: Distributed rate limiting and caching
- **Database replication**: Read replicas for scaling
- **CDN integration**: Static asset distribution
- **Message queue**: Async task processing (Celery + Redis)

## Development Workflow

### Local Development

```bash
# Setup
make install-all
make db-setup

# Development
make dev          # Start FastAPI server
make docs-serve   # Start documentation server

# Testing
make test         # Run all tests
make test-coverage  # Run with coverage report

# Code Quality
make format       # Format code (black + isort)
make lint         # Run linters (ruff + mypy)
```

### Project Structure

```
project/
├── app/                    # Application code
│   ├── api/               # API routes
│   ├── routes/            # Page routes (HTML)
│   ├── services/          # Business logic
│   ├── core/              # Core functionality (config, db, observability)
│   ├── modules/           # Module definitions and self-contained modules
│   │   ├── base.py       # ModuleDefinition class
│   │   ├── registry.py   # Module registry (CORE, OPTIONAL, INTERNAL)
│   │   ├── service.py    # Module enablement service
│   │   ├── events.py     # Module event bus
│   │   ├── cms/          # Self-contained CMS module
│   │   ├── payments/     # Self-contained payments module
│   │   └── ...           # Other modules
│   └── exceptions/        # Custom exceptions
│
├── middleware/            # Custom middleware
│   ├── auth.py           # Authentication
│   ├── store_context.py # Tenant detection
│   ├── context_middleware.py  # Context detection
│   └── theme_context.py  # Theme loading
│
├── models/               # Data models
│   ├── database/        # SQLAlchemy models
│   └── schema/          # Pydantic schemas
│
├── static/              # Static files
│   ├── admin/          # Admin assets
│   ├── store/         # Store assets
│   └── shop/           # Shop assets
│
├── templates/           # Jinja2 templates
│   ├── admin/
│   ├── store/
│   └── shop/
│
├── tests/              # Test suite
│   ├── unit/
│   └── integration/
│
└── docs/               # Documentation
    ├── architecture/   # System architecture
    ├── frontend/       # Frontend guides
    ├── backend/        # Backend development
    └── api/            # API documentation
```

## Monitoring & Observability

The platform includes a comprehensive observability framework:

### Health Checks

- Aggregated health endpoint (`/health`)
- Kubernetes probes (`/health/live`, `/health/ready`)
- Module health check integration
- External tool links (`/health/tools`)

### Metrics

- Prometheus metrics endpoint (`/metrics`)
- Request latency histograms
- Counter and gauge support

### Error Tracking

- Sentry integration for production
- Exception capture with context
- Environment-aware configuration

### Logging

- Structured logging with Python logging module
- Request/response logging via middleware
- Error tracking with stack traces
- Audit logging for admin actions

**See:** [Observability](observability.md) for complete documentation

## Deployment Architecture

### Production Deployment

```
                    ┌─────────────┐
Internet ───────────│ Load Balancer│
                    └──────┬───────┘
                           │
            ┌──────────────┼──────────────┐
            │              │              │
       ┌────▼────┐    ┌────▼────┐   ┌────▼────┐
       │ App     │    │ App     │   │ App     │
       │ Server 1│    │ Server 2│   │ Server 3│
       └────┬────┘    └────┬────┘   └────┬────┘
            │              │              │
            └──────────────┼──────────────┘
                           │
                    ┌──────▼───────┐
                    │  PostgreSQL  │
                    │  (Primary +  │
                    │   Replicas)  │
                    └──────────────┘
```

**See:** [Deployment Documentation](../deployment/index.md)

## Related Documentation

- [Multi-Tenant System](multi-tenant.md) - Detailed multi-tenancy implementation
- [Module System](module-system.md) - Module architecture and classification
- [Menu Management](menu-management.md) - Sidebar and menu configuration
- [Observability](observability.md) - Health checks, metrics, error tracking
- [Middleware Stack](middleware.md) - Complete middleware documentation
- [Authentication & RBAC](auth-rbac.md) - Security and access control
- [Request Flow](request-flow.md) - Detailed request processing
- [Frontend Architecture](../frontend/overview.md) - Frontend development guides
- [Backend Development](../backend/overview.md) - Backend development guides
- [API Documentation](../api/index.md) - API reference

## Quick Links

### For Developers
- [Creating a New Admin Page](../frontend/admin/page-templates.md)
- [Backend Development Guide](../backend/overview.md)
- [Database Migrations](../development/migration/database-migrations.md)

### For Operations
- [Deployment Guide](../deployment/production.md)
- [Environment Configuration](../deployment/environment.md)
- [Database Setup](../getting-started/database-setup.md)

### For Team Members
- [Contributing Guide](../development/contributing.md)
- [PyCharm Setup](../development/pycharm-configuration-make.md)
- [Troubleshooting](../development/troubleshooting.md)
