# Frontend Architecture Overview

**Version:** 1.0
**Last Updated:** November 2025
**Audience:** Frontend Developers

---

## What is This Document?

This document provides a comprehensive overview of the Orion frontend architecture, covering all three distinct frontend applications and the shared design patterns that ensure consistency, maintainability, and developer productivity across the entire platform.

This serves as the introduction to three detailed architecture documents:
1. Admin Frontend Architecture
2. Store Frontend Architecture
3. Shop Frontend Architecture

---

## Platform Overview

Orion is a multi-tenant e-commerce marketplace platform with three distinct frontend applications, each serving different user groups:

```
┌─────────────────────────────────────────────────────────────────┐
│                                                                  │
│  ┌──────────────┐        ┌──────────────┐      ┌────────────┐  │
│  │    ADMIN     │        │    STORE    │      │    SHOP    │  │
│  │   FRONTEND   │        │   FRONTEND   │      │  FRONTEND  │  │
│  └──────────────┘        └──────────────┘      └────────────┘  │
│         │                        │                     │         │
│         ├────────────────────────┴─────────────────────┤         │
│         │                                              │         │
│         │           SHARED ARCHITECTURE                │         │
│         │           • Alpine.js                        │         │
│         │           • Jinja2 Templates                 │         │
│         │           • Tailwind CSS                     │         │
│         │           • FastAPI Backend                  │         │
│         │           • Design Patterns                  │         │
│         │                                              │         │
│         └──────────────────────────────────────────────┘         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

---

## Three Frontends Explained

### 1. Admin Frontend

**Purpose:** Platform administration and control
**Users:** Platform administrators
**Access:** `/admin/*`
**Auth:** Admin role required (`is_admin=True`)

**Key Features:**
- Store management (create, verify, suspend)
- User management (roles, permissions)
- Platform-wide analytics and monitoring
- Theme customization for stores
- Import job monitoring
- Audit log viewing
- System settings and configuration

**UI Theme:** Windmill Dashboard (professional admin UI)
**Colors:** Purple (#7c3aed) primary

**Pages:**
- `/admin/dashboard`
- `/admin/stores`
- `/admin/stores/{code}/edit`
- `/admin/stores/{code}/theme`
- `/admin/users`
- `/admin/products`
- `/admin/orders`
- `/admin/import-jobs`
- `/admin/audit-logs`
- `/admin/settings`

---

### 2. Store Frontend

**Purpose:** Store shop management and operations
**Users:** Store owners and their team members
**Access:** `/store/{store_code}/*`
**Auth:** Store role required + store ownership

**Key Features:**
- Product catalog management
- Inventory tracking
- Order management
- Customer management
- Marketplace imports (Amazon, eBay, etc.)
- Shop analytics and reports
- Team member management
- Shop settings

**UI Theme:** Windmill Dashboard (professional admin UI)
**Colors:** Purple (#7c3aed) primary

**Pages:**
- `/store/{code}/dashboard`
- `/store/{code}/products`
- `/store/{code}/inventory`
- `/store/{code}/orders`
- `/store/{code}/customers`
- `/store/{code}/marketplace`
- `/store/{code}/analytics`
- `/store/{code}/team`
- `/store/{code}/settings`

---

### 3. Shop Frontend

**Purpose:** Customer-facing e-commerce storefront
**Users:** Customers and visitors
**Access:** Store-specific domains or subdomains
**Auth:** Optional (guest checkout supported)

**Key Features:**
- Product browsing and search
- Shopping cart management
- Checkout and payment
- Order tracking
- Customer account (optional)
- Wishlist (optional)
- Product reviews (optional)
- Multi-theme system (store branding)

**UI Theme:** Custom per store (multi-theme system)
**Colors:** Store-specific via CSS variables

**Special Features:**
- Store Context Middleware (domain → store detection)
- Theme Context Middleware (loads store theme)
- CSS Variables for dynamic theming
- Client-side cart (localStorage)

**Pages:**
- `/` (homepage)
- `/products` (catalog)
- `/products/{id}` (product detail)
- `/category/{slug}` (category browse)
- `/search` (search results)
- `/cart` (shopping cart)
- `/checkout` (checkout flow)
- `/account` (customer account)
- `/orders` (order history)
- `/about` (about store)
- `/contact` (contact form)

---

## Shared Technology Stack

All three frontends share the same core technologies:

| Layer | Technology | Purpose |
|-------|-----------|---------|
| Backend | FastAPI | REST API + routing |
| Templates | Jinja2 | Server-side rendering |
| Interactivity | Alpine.js 3.x | Client-side reactivity |
| Styling | Tailwind CSS 2.2.x | Utility-first CSS (CDN + fallback) - [Build Guide](tailwind-css.md) |
| Icons | Heroicons | SVG icon system |
| HTTP Client | Fetch API | API requests |
| State Management | Alpine.js reactive | No external state lib |
| Logging | Custom LogConfig | Centralized logging |
| Error Handling | Custom exceptions | Structured errors |
| Asset Loading | CDN with fallback | Offline support - [Details](cdn-fallback-strategy.md) |

### Why This Stack?

- ✅ Minimal JavaScript complexity (no React/Vue build process)
- ✅ Server-side rendering for SEO
- ✅ Progressive enhancement (works without JS)
- ✅ Fast development iteration
- ✅ Small bundle sizes
- ✅ Easy to learn and maintain
- ✅ Python developers can contribute to frontend
- ✅ Works offline with CDN fallback (see [CDN Fallback Strategy](cdn-fallback-strategy.md))

---

## Architecture Philosophy

### 1. API-First Design
- Routes only render templates (no business logic)
- ALL data loaded client-side via REST APIs
- Clear separation: `pages.py` (templates) vs other API files
- Enables future mobile apps or SPA migrations

### 2. Progressive Enhancement
- HTML works without JavaScript (basic functionality)
- JavaScript enhances experience (filters, live updates)
- Graceful degradation for older browsers
- Accessible by default

### 3. Component-Based Templates
- Base templates provide layout
- Pages extend base templates
- Partials for reusable components
- Block overrides for customization

### 4. Centralized Design Patterns
- Shared utilities (logging, API client, utils)
- Consistent error handling across frontends
- Standardized state management patterns
- Common UI components and patterns

### 5. Developer Experience
- Copy-paste templates for new pages
- Consistent patterns reduce cognitive load
- Comprehensive documentation
- Clear file organization

---

## File Organization

The project follows a clear, frontend-specific organization:

```
app/
├── templates/
│   ├── admin/              ← Admin frontend templates
│   │   ├── base.html
│   │   ├── dashboard.html
│   │   └── partials/
│   ├── store/             ← Store frontend templates
│   │   ├── base.html
│   │   ├── dashboard.html
│   │   └── partials/
│   └── shop/               ← Shop frontend templates
│       ├── base.html
│       ├── home.html
│       └── partials/
│
├── static/
│   ├── admin/              ← Admin-specific assets
│   │   ├── css/
│   │   ├── js/
│   │   └── img/
│   ├── store/             ← Store-specific assets
│   │   ├── css/
│   │   ├── js/
│   │   └── img/
│   ├── shop/               ← Shop-specific assets
│   │   ├── css/
│   │   ├── js/
│   │   └── img/
│   └── shared/             ← Shared across all frontends
│       ├── js/
│       │   ├── log-config.js       ← Centralized logging
│       │   ├── api-client.js       ← HTTP client wrapper
│       │   ├── icons.js            ← Icon registry
│       │   └── utils.js            ← Utility functions
│       └── css/
│
├── api/v1/
│   ├── admin/              ← Admin API endpoints
│   │   ├── pages.py        ← Routes (templates only)
│   │   ├── stores.py      ← Business logic
│   │   ├── users.py
│   │   └── ...
│   ├── store/             ← Store API endpoints
│   │   ├── pages.py
│   │   ├── products.py
│   │   └── ...
│   └── shop/               ← Shop API endpoints
│       ├── pages.py
│       ├── products.py
│       └── ...
│
└── exceptions/             ← Custom exception classes
    ├── base.py             ← Base exception classes
    ├── admin.py            ← Admin-specific exceptions
    ├── shop.py             ← Shop-specific exceptions
    ├── product.py          ← Product exceptions
    └── handler.py          ← Exception handler setup
```

---

## Request Flow

### Page Load Flow

1. **Browser Request**
2. **FastAPI Route Handler** (`pages.py`)
   - Verify authentication
   - Extract route parameters
   - Render Jinja2 template
3. **Template Rendering**
   - Extend base template
   - Include partials
   - Inject server-side data (user, store, theme)
4. **Browser Receives HTML**
   - Load CSS (Tailwind)
   - Load JavaScript (Alpine.js, page scripts)
5. **Alpine.js Initialization**
   - `x-data` component initialized
   - `...data()` spreads base state
   - `init()` method runs
   - Initialization guard checked
6. **Client-Side Data Loading**
   - JavaScript calls REST API
   - apiClient handles request
   - JSON response received
7. **Reactive Updates**
   - Alpine.js updates reactive state
   - DOM automatically updates
   - Page fully interactive

### User Interaction Flow

1. **User Action** (click, input, etc.)
2. **Alpine.js Event Handler**
   - `@click`, `@input`, `@change`, etc.
   - Calls component method
3. **Business Logic**
   - Validate input
   - Update local state
   - Call API if needed
4. **API Request** (if needed)
   - `apiClient.post/put/delete`
   - Automatic error handling
   - Logging
5. **Update State**
   - Modify reactive data
   - Alpine.js watches changes
6. **DOM Updates**
   - Automatic reactive updates
   - No manual DOM manipulation
7. **User Feedback**
   - Toast notification
   - Loading indicator removed
   - Success/error message

---

## Core Design Patterns

For detailed information about the design patterns used across all frontends, see:

- **[Shared UI Components](shared/ui-components.md)** - Reusable UI components
- **[Pagination System](shared/pagination.md)** - Pagination implementation
- **[Sidebar Navigation](shared/sidebar.md)** - Sidebar setup guide
- **[Logging System](shared/logging.md)** - Frontend logging configuration
- **[Icons Guide](../development/icons-guide.md)** - Icon system usage

---

## Security Patterns

### Authentication & Authorization

1. **JWT Tokens**
   - Stored in localStorage
   - Automatically sent with API requests
   - Expiration handling

2. **Role-Based Access**
   - Admin: Full platform access
   - Store: Limited to own shop
   - Customer: Public + account access

3. **Route Protection**
   - FastAPI dependencies verify auth
   - Middleware for store context
   - Automatic redirects to login

### Input Validation

1. **Client-Side** (Alpine.js)
   - Immediate feedback
   - Better UX
   - Reduces server load

2. **Server-Side** (Pydantic)
   - Security boundary
   - Type validation
   - Cannot be bypassed

3. **Both Required**
   - Client-side for UX
   - Server-side for security

### XSS Prevention
- Jinja2 auto-escapes by default
- Use `| safe` only when necessary
- Sanitize user content

### CSRF Protection
- Token-based (if using forms)
- SameSite cookies
- API uses Bearer tokens (CSRF-safe)

---

## Learning Path

### For New Developers

**Week 1: Foundation**
- Day 1-2: Read this overview document
- Day 3-4: Study one detailed architecture doc (start with admin)
- Day 5: Review shared design patterns

**Week 2: Hands-On**
- Day 1-2: Examine existing `dashboard.js` (best example)
- Day 3-4: Copy template and create simple page
- Day 5: Test and understand data flow

**Week 3: Patterns**
- Day 1: Practice base layout inheritance
- Day 2: Implement initialization guards
- Day 3: Use centralized logging
- Day 4: Work with API client
- Day 5: Handle errors properly

**Week 4: Advanced**
- Day 1-2: Create complex page with filters/pagination
- Day 3: Implement modal forms
- Day 4: Add dark mode support
- Day 5: Review and refactor

**After 1 Month:**
- ✅ Understand all three frontends
- ✅ Can create new pages independently
- ✅ Follow all design patterns
- ✅ Debug issues effectively
- ✅ Contribute to architecture improvements

---

## Development Checklist

### Before Creating New Page
- □ Read relevant architecture document
- □ Review page template guide
- □ Study similar existing page
- □ Identify which patterns to use

### While Developing
- □ Use `...data()` for base inheritance
- □ Add initialization guard
- □ Set `currentPage` identifier
- □ Use lowercase `apiClient`
- □ Use centralized logger
- □ Handle errors gracefully
- □ Add loading states
- □ Support dark mode

### Before Committing
- □ No console errors
- □ Initialization guard works
- □ Dark mode works
- □ Mobile responsive
- □ API errors handled
- □ No duplicate API calls
- □ Logging consistent
- □ Code matches patterns

---

## Benefits of This Architecture

### For Developers
- ✅ Copy-paste templates reduce development time
- ✅ Consistent patterns reduce cognitive load
- ✅ Centralized utilities eliminate duplication
- ✅ Clear documentation speeds onboarding
- ✅ Shared patterns enable code reuse

### For The Platform
- ✅ Maintainable codebase
- ✅ Consistent user experience
- ✅ Easier debugging
- ✅ Faster feature development
- ✅ Scalable architecture

### For Users
- ✅ Consistent UI/UX
- ✅ Fast page loads
- ✅ Reliable functionality
- ✅ Professional appearance
- ✅ Works on all devices

---

## Next Steps

1. Read the detailed architecture document for the frontend you're working on (Admin, Store, or Shop)
2. Study the page template guide for that frontend
3. Review existing code examples (`dashboard.js` is the best)
4. Check the [Shared Components](shared/ui-components.md) documentation
5. Review the [Icons Guide](../development/icons-guide.md)
6. Copy templates and start building!

Questions? Check the detailed architecture docs or review existing implementations in the codebase.
