# DropOps CRM — System Architecture Design

**Version:** 1.0  
**Date:** 2026-05-26  
**Type:** Frontend Architecture (Next.js 14 + React)

---

## 1. High-Level Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                         CLIENT BROWSER                            │
│  ┌───────────────────────────────────────────────────────────┐  │
│  │                   Next.js 14 Application                    │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐    │  │
│  │  │   Pages      │  │ Components   │  │   Hooks      │    │  │
│  │  │  (App Router)│  │  (Reusable)  │  │  (Logic)     │    │  │
│  │  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘    │  │
│  │         │                  │                  │            │  │
│  │         └──────────────────┼──────────────────┘            │  │
│  │                            │                               │  │
│  │                   ┌────────▼────────┐                     │  │
│  │                   │  Service Layer  │                     │  │
│  │                   │  (API Clients)  │                     │  │
│  │                   └────────┬────────┘                     │  │
│  │                            │                               │  │
│  │                   ┌────────▼────────┐                     │  │
│  │                   │  HTTP Client    │                     │  │
│  │                   │  (Axios + Auth)  │                     │  │
│  │                   └────────┬────────┘                     │  │
│  └────────────────────────────┼───────────────────────────────┘  │
└───────────────────────────────┼───────────────────────────────────┘
                                │ HTTPS
                                │
┌───────────────────────────────▼───────────────────────────────────┐
│                     BACKEND API (Python/Django?)                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │  Auth Layer  │  │  Business    │  │   Data       │           │
│  │  (JWT/Session)│  │  Logic       │  │  Layer       │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
└───────────────────────────────────────────────────────────────────┘
                                │
                                │
┌───────────────────────────────▼───────────────────────────────────┐
│              EXTERNAL INTEGRATIONS & SERVICES                      │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌────────┐ │
│  │Supplier  │ │WooCommerce│ │Amazon/eBay│ │Payment   │ │Ad      │ │
│  │Feeds     │ │Webhooks  │ │Marketplace│ │Gateways  │ │Accounts│ │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └────────┘ │
└───────────────────────────────────────────────────────────────────┘
```

---

## 2. Layered Architecture

### 2.1 Presentation Layer (`src/app/`)
**Pattern:** File-based routing (Next.js App Router)

| Directory | Responsibility | Example Pages |
|---|---|---|
| `/dashboard` | Main dashboard with KPIs | Overview, quick actions |
| `/orders` | Order management | List, view, create, edit |
| `/products` | Product catalogue | List, view, create, edit, import, price history |
| `/customers` | Customer management | List, view, create, edit |
| `/suppliers` | Supplier management | List, view, create, edit, import |
| `/inventory` | Stock management | List, alerts |
| `/tracking` | Shipment tracking | List, create, edit |
| `/returns` | Returns management | List, view, create, edit |
| `/support` | Customer support tickets | List, view, create, edit |
| `/pricing` | Pricing rules & repricer | Rules list, create, edit, repricer |
| `/analytics` | Business intelligence | Profit, margin alerts, scorecard, forecast, SEO, VAT |
| `/integrations` | Third-party integrations | Channels, WooCommerce, ad accounts, payment gateways |
| `/warehouses` | Warehouse management | List |
| `/despatch` | Shipping label generation | Scan, print labels |
| `/settings` | System configuration | Company, users, roles, billing, notifications, security |
| `/audit-logs` | Audit trail | List, view details |
| `/login` | Authentication | Login form |

**Design Decisions:**
- **App Router over Pages Router:** Leverages React Server Components, streaming, and improved performance
- **Route Groups:** Logical grouping by domain (e.g., `/settings/*`, `/analytics/*`)
- **Dynamic Routes:** `[id]` for entity detail pages (e.g., `/orders/[id]`)

### 2.2 Component Layer (`src/components/`)

| Component | Responsibility | Props |
|---|---|---|
| `ClientLayout` | Main app shell with sidebar, header, auth guard | `children` |
| `Sidebar` | Navigation menu with groups | `open`, `onClose`, `user` |
| `ErrorBoundary` | React error boundary for graceful failure | `children` |
| `AppShell` | (Legacy/unused) | — |
| `ui/StatusBadge` | Status badge component | `status` |
| `ui/LoadingSkeleton` | Loading placeholder | — |
| `ui/EmptyState` | Empty state display | `icon`, `message`, `action` |

**Design Patterns:**
- **Composition:** Components composed from smaller reusable pieces
- **Props Interface:** Clear prop contracts via TypeScript
- **Icon Consistency:** All icons from `lucide-react`

### 2.3 Custom Hooks Layer (`src/hooks/`)

| Hook | Responsibility | State Managed |
|---|---|---|
| `useAuth` | Authentication context | `user`, `loading`, `login`, `logout`, `refresh` |

**Design Patterns:**
- **Context API:** Global auth state shared across app
- **localStorage Persistence:** Token and user persisted client-side (security consideration)

### 2.4 Service Layer (`src/lib/`)

**Pattern:** Service objects per domain, Axios-based HTTP client

| Service | Domain | Key Methods |
|---|---|---|
| `authService` | Authentication | `login()`, `logout()`, `me()`, `refreshToken()` |
| `api` | HTTP client | Axios instance with interceptors |
| `productService` | Products | CRUD, import from supplier, bulk import, price history |
| `orderService` | Orders | CRUD, stats |
| `customerService` | Customers | CRUD, delete |
| `supplierService` | Suppliers | CRUD, get with products |
| `inventoryService` | Inventory | List, alerts |
| `trackingService` | Tracking | CRUD |
| `returnsService` | Returns | CRUD |
| `supportService` | Support tickets | CRUD |
| `pricingService` | Pricing rules | CRUD |
| `analyticsService` | Analytics | Profit, margin, scorecard, forecast, SEO, VAT |
| `wooCommerceService` | WooCommerce | CRUD, sync, sync status |
| `channelService` | Amazon/eBay | OAuth, token management |
| `adAccountService` | Ad accounts | CRUD |
| `paymentGatewayService` | Payment gateways | CRUD |
| `shippingService` | Shipping | Labels, couriers |
| `purchaseOrderService` | Purchase orders | CRUD |
| `warehouseService` | Warehouses | CRUD |
| `auditService` | Audit logs | List, view |
| `marginAlertsService` | Margin alerts | CRUD |
| `seoService` | SEO | Metrics |
| `featureFlagsService` | Feature flags | CRUD |
| `rolesApi` | RBAC | Users, roles, permissions |
| `security` | Security utilities | Sanitisation, validation, rate limiting |
| `csvExport` | CSV export | `exportToCsv()` |
| `currency` | Currency formatting | `formatCurrency()` |

**Design Patterns:**
- **Service Object Pattern:** Encapsulates API calls per domain
- **Axios Interceptors:** Request auth injection, response error handling, retry logic
- **Type Safety:** Full TypeScript interfaces for request/response

### 2.5 Type Layer (`src/types/`)

**Pattern:** Centralised TypeScript type definitions

| Domain | Types |
|---|---|
| Auth | `User`, `Role`, `Permission`, `LoginRequest`, `LoginResponse` |
| Company | `Company` |
| Suppliers | `Supplier`, `SupplierContact`, `SupplierFeed`, `SupplierProduct` |
| Products | `Product`, `ProductMapping`, `PricingRule`, `PriceHistory` |
| Inventory | `InventoryAlert` |
| Orders | `Order`, `OrderItem` |
| Integrations | `WooCommerceIntegration`, `WooCommerceSyncLog`, `WooCommerceSyncStatus` |
| Generic | `ApiResponse<T>` with pagination metadata |

---

## 3. Domain Model

### 3.1 Core Entities

```
Company (Multi-tenant root)
├── Users (with Roles & Permissions)
├── Suppliers
│   ├── Contacts
│   ├── Feeds (product sync)
│   └── Products (catalog)
├── Products (internal catalogue)
│   ├── Mappings (to supplier products)
│   └── Price History
├── Customers
├── Orders
│   └── Items
├── Inventory Alerts
├── Pricing Rules
├── Returns
├── Tracking
├── Support Tickets
├── Purchase Orders
├── Warehouses
├── Integrations
│   ├── WooCommerce
│   ├── Channels (Amazon/eBay)
│   ├── Ad Accounts
│   └── Payment Gateways
├── Audit Logs
└── Settings
```

### 3.2 Key Relationships

- **Company → Users:** One-to-many (multi-tenancy)
- **Company → Suppliers:** One-to-many
- **Supplier → Products:** One-to-many (supplier catalogue)
- **Product → Mappings:** One-to-many (to supplier products)
- **Order → Items:** One-to-many
- **Order → Customer:** Many-to-one
- **Product → Price History:** One-to-many (audit trail)

---

## 4. Data Flow

### 4.1 Authentication Flow

```
User → Login Form → useAuth.login() → authService.login()
→ API POST /login → Backend validates → Returns JWT + User
→ localStorage.setItem('token', 'user') → AuthContext updates
→ ClientLayout renders protected routes
```

**Security Considerations:**
- JWT stored in localStorage (XSS risk — see SECURITY_AUDIT.md)
- Token attached via `Authorization: Bearer` header
- 401 response triggers logout and redirect to login

### 4.2 Data Fetching Flow

```
Page Component → useEffect() → Service Method → api.get/post()
→ Axios Interceptor (add token) → Backend API
→ Response → Component State → Render
```

**Error Handling:**
- Axios interceptor catches 401 → logout
- 5xx errors → exponential backoff retry (max 2 attempts)
- 15s timeout on all requests

### 4.3 Bulk Import Flow

```
User → Select Supplier → Load Supplier Products
→ Select Products → Click Import
→ productService.importFromSupplier() (loop)
→ Backend creates Products → UI shows imported count
→ Redirect to Products page
```

---

## 5. Security Architecture

### 5.1 Current Implementation

| Layer | Mechanism | Status |
|---|---|---|
| Authentication | JWT in localStorage | ⚠️ Vulnerable to XSS |
| Authorization | Role-based (RBAC) on backend | ✅ Implemented |
| CSRF Protection | `X-Requested-With` header | ✅ Added |
| Rate Limiting | Client-side login limiter (5/30s) | ✅ Added |
| Input Validation | Security utility functions | ✅ Added |
| XSS Prevention | React auto-escaping | ✅ Built-in |
| Security Headers | CSP, HSTS, X-Frame-Options | ✅ Production only |
| Error Boundary | Graceful error UI | ✅ Added |

### 5.2 Recommended Improvements

1. **Move to httpOnly cookies** for JWT (requires backend change)
2. **Add CSRF tokens** for state-changing requests (if using cookies)
3. **Implement server-side rate limiting** (backend responsibility)
4. **Add Content Security Policy nonce** for inline scripts
5. **Implement audit logging** for sensitive actions

---

## 6. Integration Patterns

### 6.1 Supplier Feed Integration

**Pattern:** Poll-based sync from supplier feeds

```
Supplier Feed (XML/CSV/API) → Backend Parser → SupplierProducts Table
→ User selects products → Import → Products Table
```

### 6.2 WooCommerce Integration

**Pattern:** OAuth 1.0a + REST API + Webhooks

```
WooCommerce Store → OAuth Credentials → Sync Endpoint
→ Products/Orders Sync → Local Database
→ Webhooks → Real-time order updates
```

### 6.3 Marketplace Integration (Amazon/eBay)

**Pattern:** OAuth 2.0 + Marketplace APIs

```
Amazon/eBay → OAuth Flow → Access Token
→ Product Listing → Order Sync → Tracking Updates
```

---

## 7. State Management

### 7.1 Current Approach

- **Local Component State:** `useState` for form data, UI state
- **Global State:** React Context (`useAuth`) for authentication
- **Server State:** Direct API calls in `useEffect` (no caching library)

### 7.2 Recommended Improvements

1. **Add React Query / SWR** for server state caching, deduplication, optimistic updates
2. **Consider Zustand** for global state beyond auth (e.g., notifications, user preferences)
3. **Implement form libraries** (React Hook Form) for better form validation and performance

---

## 8. Performance Optimizations

### 8.1 Current Optimizations

- **Next.js 14 App Router:** React Server Components, streaming
- **SWC Minification:** Faster builds
- **Dynamic Imports:** Code splitting via Next.js automatic splitting
- **Image Optimization:** Next.js Image component (where used)

### 8.2 Recommended Improvements

1. **Add React.memo** for expensive component re-renders
2. **Implement virtual scrolling** for large tables (products, orders)
3. **Add service worker** for offline support (PWA)
4. **Optimize bundle size:** Tree-shaking, code splitting by route
5. **Add CDN** for static assets

---

## 9. Scalability Considerations

### 9.1 Current Limitations

- **No pagination** on list pages (loads all data)
- **No debouncing** on search inputs (triggers API on every keystroke)
- **No request cancellation** on unmount (stale requests)
- **No caching strategy** (re-fetches data on navigation)

### 9.2 Recommended Improvements

1. **Implement pagination** on all list pages
2. **Add debouncing** to search inputs (300-500ms)
3. **Cancel pending requests** on component unmount (AbortController)
4. **Add stale-while-revalidate** caching (React Query)
5. **Implement optimistic UI** for faster perceived performance

---

## 10. Testing Strategy

### 10.1 Current Coverage

| Type | Tool | Coverage |
|---|---|---|
| Unit Tests | Vitest + React Testing Library | Security utilities, auth hook |
| E2E Tests | Playwright | Login flow, protected routes (written, not run) |

### 10.2 Recommended Improvements

1. **Increase unit test coverage** to 80%+ for service layer
2. **Add component tests** for key UI components
3. **Add integration tests** for critical user flows
4. **Add visual regression tests** (Playwright + Percy)
5. **Add performance tests** (Lighthouse CI)

---

## 11. Technical Debt

| Item | Severity | Impact | Recommendation |
|---|---|---|---|
| JWT in localStorage | High | XSS vulnerability | Move to httpOnly cookies |
| No pagination | Medium | Performance with large datasets | Implement pagination |
| No request caching | Medium | Unnecessary API calls | Add React Query |
| No form validation library | Low | Boilerplate code | Add React Hook Form |
| No global state manager | Low | Prop drilling for non-auth state | Add Zustand if needed |
| Mixed rounded-lg/rounded-xl | Low | UI inconsistency | Standardise to rounded-xl |

---

## 12. Deployment Architecture

### 12.1 Current Setup

- **Build:** Next.js static + server-rendered pages
- **Hosting:** Vercel (implied by Next.js choice)
- **API Proxy:** Next.js rewrites to `http://localhost:8000/api` (dev only)

### 12.2 Recommended Production Setup

```
┌─────────────────────────────────────────────────────────┐
│                    CDN (Cloudflare/Vercel)              │
│  ┌───────────────────────────────────────────────────┐  │
│  │         Next.js Application (Edge Runtime)       │  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                            │
                            │
┌───────────────────────────▼─────────────────────────────┐
│              Application Load Balancer                   │
└───────────────────────────┬─────────────────────────────┘
                            │
        ┌───────────────────┼───────────────────┐
        │                   │                   │
┌───────▼────────┐  ┌──────▼────────┐  ┌──────▼────────┐
│  Backend API   │  │  Backend API  │  │  Backend API  │
│  Instance 1    │  │  Instance 2   │  │  Instance 3   │
└───────┬────────┘  └──────┬────────┘  └──────┬────────┘
        │                   │                   │
        └───────────────────┼───────────────────┘
                            │
┌───────────────────────────▼─────────────────────────────┐
│                  PostgreSQL Database                     │
└─────────────────────────────────────────────────────────┘
```

---

## 13. Monitoring & Observability

### 13.1 Current State

- **Error Tracking:** None (console.error only)
- **Performance Monitoring:** None
- **Analytics:** None

### 13.2 Recommended Additions

1. **Sentry** for error tracking and performance monitoring
2. **Google Analytics / Plausible** for user analytics
3. **LogRocket** for session replay (debugging)
4. **Vercel Analytics** for web vitals
5. **Custom logging** service for audit trail

---

## 14. Future Roadmap

### Phase 1: Foundation (Next 1-2 months)
- [ ] Implement React Query for server state
- [ ] Add pagination to all list pages
- [ ] Add debouncing to search inputs
- [ ] Move auth to httpOnly cookies (backend coordination)

### Phase 2: Performance (Next 2-3 months)
- [ ] Implement virtual scrolling for large tables
- [ ] Add service worker for PWA support
- [ ] Optimise bundle size and code splitting
- [ ] Add image optimization throughout

### Phase 3: Testing & Quality (Next 1-2 months)
- [ ] Increase unit test coverage to 80%
- [ ] Add component tests for key UI
- [ ] Add E2E tests for critical flows
- [ ] Set up CI/CD with automated tests

### Phase 4: Advanced Features (Next 3-6 months)
- [ ] Real-time updates (WebSocket / Server-Sent Events)
- [ ] Offline support with sync queue
- [ ] Advanced filtering and saved views
- [ ] Bulk actions on list pages

---

## 15. Architecture Decision Records (ADRs)

### ADR-001: Next.js App Router
**Decision:** Use Next.js 14 App Router over Pages Router
**Rationale:** React Server Components, streaming, improved performance, future-forward
**Consequences:** Requires 'use client' directive for interactive components

### ADR-002: Service Layer Pattern
**Decision:** Separate service objects per domain in `/lib`
**Rationale:** Clear separation of concerns, testable API layer, reusable across components
**Consequences:** More files, but better maintainability

### ADR-003: localStorage for Auth
**Decision:** Store JWT in localStorage (temporary)
**Rationale:** Quick implementation, works with current backend
**Consequences:** XSS vulnerability — must move to httpOnly cookies

### ADR-004: Tailwind CSS
**Decision:** Use Tailwind CSS for styling
**Rationale:** Rapid development, consistent design system, no custom CSS files
**Consequences:** Larger HTML markup, requires purging for production

---

## 16. Conclusion

The DropOps CRM frontend follows a **layered architecture** with clear separation between presentation, component, service, and type layers. The current implementation is **functional and modern** (Next.js 14, TypeScript, Tailwind), but has **opportunities for improvement** in:

1. **Security:** Move from localStorage to httpOnly cookies
2. **Performance:** Add caching, pagination, debouncing
3. **State Management:** Implement React Query for server state
4. **Testing:** Increase test coverage significantly
5. **Observability:** Add error tracking and monitoring

The architecture is **well-structured for growth** and can accommodate the recommended improvements without major refactoring.
