# Admin Area Architecture Plan

## Overview
Design and implement a clean architecture admin area for Owner and Super Admin roles to manage all users, following TDD principles.

## 1. Architecture Layers

### 1.1 Domain Layer (`core/admin/domain/`)
**Purpose**: Business logic, entities, value objects, domain services - framework independent

#### Value Objects:
- `UserId` - Unique identifier for users
- `Email` - Validated email address
- `UserRole` - Role type (owner, admin, user, etc.)
- `UserStatus` - Account status (active, suspended, deleted)
- `PermissionKey` - Capability identifier
- `PermissionAction` - view | mutate

#### Entities:
- `User` - Main entity with roles, status, email
- `Permission` - Permission definition
- `RolePermission` - Role to permission mapping

#### Domain Services:
- `AuthorizationService` - Checks permissions and roles
- `UserManagementService` - User lifecycle management rules

#### Domain Errors:
- `UserDomainError` - Domain-specific errors
- `AuthorizationError` - Permission violations

### 1.2 Application Layer (`core/admin/application/`)
**Purpose**: Use cases, ports, orchestration - no framework dependencies

#### Ports (Interfaces):
- **Input Ports**:
  - `IManageUsersUseCase` - User CRUD operations
  - `IManageRolesUseCase` - Role management
  - `IQueryUsersUseCase` - User queries
  
- **Output Ports**:
  - `IUserRepository` - Persistence interface
  - `IPermissionRepository` - Permission storage
  - `IUserPresenter` - Output formatting

#### Use Cases:
- `ListUsersUseCase` - Get all users with filtering
- `GetUserDetailsUseCase` - Get single user details
- `UpdateUserRolesUseCase` - Modify user roles
- `UpdateUserStatusUseCase` - Suspend/activate users
- `DeleteUserUseCase` - Remove user accounts
- `GetUserPermissionsUseCase` - View user permissions

#### Services:
- `UserManagementService` - Orchestrates user operations
- `PermissionEvaluationService` - Evaluates access rights

### 1.3 Infrastructure Layer (`adapters/admin/`)
**Purpose**: Concrete implementations of ports

#### Persistence:
- `TypeOrmUserRepository` - Database implementation
- `TypeOrmPermissionRepository` - Permission storage
- `InMemoryUserRepository` - Test implementation

#### Presenters:
- `UserPresenter` - Maps domain to DTO
- `UserListPresenter` - Formats user list
- `PermissionPresenter` - Formats permissions

#### Security:
- `RolePermissionMapper` - Maps roles to permissions
- `AuthorizationGuard` - Enforces access control

### 1.4 API Layer (`apps/api/src/domain/admin/`)
**Purpose**: HTTP delivery mechanism

#### Controllers:
- `UsersController` - User management endpoints
- `RolesController` - Role management endpoints
- `PermissionsController` - Permission endpoints

#### DTOs:
- **Request**:
  - `UpdateUserRolesRequestDto`
  - `UpdateUserStatusRequestDto`
  - `CreateUserRequestDto`
  
- **Response**:
  - `UserResponseDto`
  - `UserListResponseDto`
  - `PermissionResponseDto`

#### Middleware/Guards:
- `RequireSystemAdminGuard` - Validates Owner/Super Admin access
- `PermissionGuard` - Checks specific permissions

### 1.5 Frontend Layer (`apps/website/`)
**Purpose**: User interface for admin operations

#### Pages:
- `/admin/users` - User management dashboard
- `/admin/users/[id]` - User detail page
- `/admin/roles` - Role management
- `/admin/permissions` - Permission matrix

#### Components:
- `UserTable` - Display users with filters
- `UserDetailCard` - User information display
- `RoleSelector` - Role assignment UI
- `StatusBadge` - User status display
- `PermissionMatrix` - Permission management

#### API Clients:
- `AdminUsersApiClient` - User management API calls
- `AdminRolesApiClient` - Role management API calls

#### Hooks:
- `useAdminUsers` - User data management
- `useAdminPermissions` - Permission data

## 2. Authorization Model

### 2.1 System Roles (from AUTHORIZATION.md)
- `owner` - Full system access
- `admin` - System admin access

### 2.2 Permission Structure
```
capabilityKey.actionType
```

Examples:
- `users.list` + `view`
- `users.roles` + `mutate`
- `users.status` + `mutate`

### 2.3 Role → Permission Mapping
```
owner: all permissions
admin: 
  - users.view
  - users.list
  - users.roles.mutate
  - users.status.mutate
```

## 3. TDD Implementation Strategy

### 3.1 Test-First Approach
1. **Write failing test** for domain entity/value object
2. **Implement minimal code** to pass test
3. **Refactor** while keeping tests green
4. **Repeat** for each layer

### 3.2 Test Structure
```
core/admin/
├── domain/
│   ├── entities/
│   │   ├── User.test.ts
│   │   └── Permission.test.ts
│   ├── value-objects/
│   │   ├── UserId.test.ts
│   │   ├── Email.test.ts
│   │   ├── UserRole.test.ts
│   │   └── UserStatus.test.ts
│   └── services/
│       ├── AuthorizationService.test.ts
│       └── UserManagementService.test.ts
├── application/
│   ├── use-cases/
│   │   ├── ListUsersUseCase.test.ts
│   │   ├── UpdateUserRolesUseCase.test.ts
│   │   └── UpdateUserStatusUseCase.test.ts
│   └── services/
│       └── UserManagementService.test.ts
```

### 3.3 Integration Tests
- API endpoint tests
- End-to-end user management flows
- Authorization guard tests

## 4. Implementation Phases

### Phase 1: Domain Layer (TDD)
- [ ] Value objects with tests
- [ ] Entities with tests
- [ ] Domain services with tests

### Phase 2: Application Layer (TDD)
- [ ] Ports/interfaces
- [ ] Use cases with tests
- [ ] Application services

### Phase 3: Infrastructure Layer (TDD)
- [ ] Repository implementations
- [ ] Presenters
- [ ] Authorization guards

### Phase 4: API Layer (TDD)
- [ ] Controllers
- [ ] DTOs
- [ ] Route definitions

### Phase 5: Frontend Layer
- [ ] Pages
- [ ] Components
- [ ] API clients
- [ ] Integration tests

### Phase 6: Integration & Verification
- [ ] End-to-end tests
- [ ] Authorization verification
- [ ] TDD compliance check

## 5. Key Clean Architecture Rules

1. **Dependency Direction**: API → Application → Domain
2. **No Framework Dependencies**: Domain/Application layers pure TypeScript
3. **Ports & Adapters**: Clear interfaces between layers
4. **Test Coverage**: All layers tested before implementation
5. **Single Responsibility**: Each use case does one thing

## 6. User Management Features

### 6.1 List Users
- Filter by role, status, email
- Pagination support
- Sort by various fields

### 6.2 User Details
- View user information
- See assigned roles
- View account status
- Audit trail

### 6.3 Role Management
- Add/remove roles
- Validate role assignments
- Prevent privilege escalation

### 6.4 Status Management
- Activate/suspend users
- Soft delete support
- Status history

### 6.5 Permission Management
- View user permissions
- Role-based permission matrix
- Permission validation

## 7. Security Considerations

### 7.1 Access Control
- Only Owner/Admin can access admin area
- Validate permissions on every operation
- Audit all changes

### 7.2 Data Protection
- Never expose sensitive data
- Validate all inputs
- Prevent self-modification of critical roles

### 7.3 Audit Trail
- Log all user management actions
- Track who changed what
- Maintain history of changes

## 8. API Endpoints

### 8.1 User Management
```
GET    /api/admin/users
GET    /api/admin/users/:id
PUT    /api/admin/users/:id/roles
PUT    /api/admin/users/:id/status
DELETE /api/admin/users/:id
```

### 8.2 Role Management
```
GET    /api/admin/roles
GET    /api/admin/roles/:id
POST   /api/admin/roles
PUT    /api/admin/roles/:id
DELETE /api/admin/roles/:id
```

### 8.3 Permission Management
```
GET    /api/admin/permissions
GET    /api/admin/permissions/:roleId
PUT    /api/admin/permissions/:roleId
```

## 9. Frontend Routes

```
/admin/users              - User list
/admin/users/:id          - User detail
/admin/roles              - Role management
/admin/permissions        - Permission matrix
```

## 10. Success Criteria

- [ ] All domain logic tested with TDD
- [ ] All application use cases tested
- [ ] API endpoints tested with integration tests
- [ ] Frontend components work correctly
- [ ] Authorization works for Owner and Super Admin only
- [ ] Clean architecture boundaries maintained
- [ ] No circular dependencies
- [ ] All tests pass
- [ ] Code follows project conventions