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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# Backend Architecture - Domain-Driven Design

**Last Updated:** 2026-01-15  
**Status:** Production Ready βœ…

---

## πŸ›οΈ Architecture Overview

The backend follows a **clean domain-driven architecture** with clear separation between infrastructure and business logic.

### Layer Structure

```
Backend
β”œβ”€β”€ core/                    # Shared kernel (models, database, config)
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ modules/            # Domain Services (Business Logic)
β”‚   β”‚   β”œβ”€β”€ auth/          # Authentication & authorization
β”‚   β”‚   β”œβ”€β”€ cases/         # Case management
β”‚   β”‚   β”œβ”€β”€ users/         # User management
β”‚   β”‚   β”œβ”€β”€ analytics/     # Analytics & reporting
β”‚   β”‚   β”œβ”€β”€ transactions/  # Transaction management
β”‚   β”‚   └── evidence/      # Evidence handling
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ infrastructure/   # Infrastructure services
β”‚   β”‚   β”‚   β”œβ”€β”€ auth_service.py       # JWT & auth (shim)
β”‚   β”‚   β”‚   β”œβ”€β”€ cache_service.py      # Multi-layer caching
β”‚   β”‚   β”‚   β”œβ”€β”€ logging_service.py    # Structured logging (shim)
β”‚   β”‚   β”‚   β”œβ”€β”€ rbac_service.py       # Role-based access
β”‚   β”‚   β”‚   └── storage/
β”‚   β”‚   β”‚       └── database_service.py  # DB infrastructure ONLY
β”‚   β”‚   └── ai/              # AI & ML services
β”‚   └── routers/            # API endpoints
└── tests/                  # Test suites
```

---

## 🎯 Core Principles

### 1. **Domain-Driven Design**

- **Domain Services** (`app/modules/*`) contain ALL business logic
- **Infrastructure Services** (`app/services/infrastructure/*`) provide technical capabilities
- **Clear boundaries** between domains

### 2. **Single Responsibility**

- Each service has ONE clear purpose
- No overlapping functionalities
- Business logic separated from infrastructure

### 3. **Dependency Direction**

```
Routers β†’ Domain Services β†’ Repositories β†’ Database
          ↓
     Infrastructure Services (cache, logging, etc.)
```

---

## πŸ“¦ Domain Services

### **Authentication** (`app/modules/auth/`)

**Purpose:** User authentication, JWT tokens, MFA  
**Key Methods:**

- `register_user()`
- `authenticate_user()`
- `verify_token()`
- `enable_mfa()`

**Router:** `app/modules/auth/router.py`

---

### **Case Management** (`app/modules/cases/`)

**Purpose:** Fraud case lifecycle management  
**Key Methods:**

- `get_cases_paginated()` - List cases with filters
- `create_case()` - Create new investigation
- `update_case()` - Modify case details
- `get_case_stats()` - Case statistics
- `add_note()` - Add case notes
- `delete_case()` - Remove case

**Router:** `app/modules/cases/router.py`  
**Repository:** `CaseRepository` (data access)  
**Service:** `CaseService` (business logic)

---

### **User Management** (`app/modules/users/`)

**Purpose:** User administration and preferences  
**Key Methods:**

- `get_users_paginated()` - List users
- `create_user()` - Register new user
- `update_user()` - Modify user data
- `update_preferences()` - User settings
- `delete_user()` - Remove user

**Router:** `app/modules/users/router.py`

---

### **Analytics** (`app/modules/analytics/`)

**Purpose:** Business intelligence and reporting  
**Key Methods:**

- `get_case_analytics()` - Case metrics over time
- `get_transaction_aggregates()` - Transaction stats
- `get_dashboard_data()` - Dashboard metrics
- `generate_risk_heatmaps()` - Risk visualization

**Router:** `app/modules/analytics/router.py`

---

### **Transactions** (`app/modules/transactions/`) ⭐ NEW

**Purpose:** Financial transaction management  
**Key Methods:**

- `get_transactions_by_case()` - List transactions
- `create_transaction()` - Add new transaction
- `update_transaction_status()` - Change status
- `get_transaction_aggregates()` - Calculate totals

**Router:** TBD (can be added if needed)

---

### **Evidence** (`app/modules/evidence/`)

**Purpose:** Digital evidence handling  
**Key Methods:**

- `get_evidence_paginated()` - List evidence
- `process_file()` - Process uploaded files
- `delete_evidence()` - Remove evidence

**Router:** `app/modules/evidence/router.py`

---

## πŸ”§ Infrastructure Services

### **Database Service** (`infrastructure/storage/database_service.py`)

**Purpose:** INFRASTRUCTURE ONLY ⚠️

**What it DOES:**

- βœ… Session management (`get_db()`)
- βœ… Connection pooling
- βœ… Health checks (`health_check()`)
- βœ… Performance monitoring
- βœ… Query caching utilities

**What it DOES NOT do:**

- ❌ Business logic (moved to domain services)
- ❌ Case/user/transaction queries (use domain services)
- ❌ Data aggregations (use AnalyticsService)

**Migration:** All business methods β†’ Domain services

---

### **Cache Service** (`infrastructure/cache_service.py`)

**Purpose:** Multi-layer caching (memory + Redis)  
**Features:**

- L1: Fast in-memory cache
- L2: Larger in-memory cache
- L3: Redis distributed cache
- Automatic namespace management
- Cache statistics

---

### **Logging Service** (`infrastructure/logging_service.py`)

**Purpose:** Structured logging with PII scrubbing  
**Features:**

- JSON formatted logs
- Automatic PII detection & masking
- Email, SSN, credit card scrubbing
- Context enrichment

---

### **RBAC Service** (`infrastructure/rbac_service.py`)

**Purpose:** Role-based access control  
**Features:**

- Role hierarchy
- Permission checking
- FastAPI dependencies for auth

---

## πŸ”„ Data Flow

### Typical Request Flow

```
1. HTTP Request
   ↓
2. Router (FastAPI endpoint)
   ↓
3. Authentication (auth_service.get_current_user)
   ↓
4. Authorization (rbac_service.require_role)
   ↓
5. Domain Service (business logic)
   ↓
6. Repository (data access)
   ↓
7. Database (via db_service.get_db)
   ↓
8. Response
```

### Example: Get Cases

```python
# router.py
@router.get("/cases")
async def list_cases(
    db: Session = Depends(get_db),
    current_user: User = Depends(auth_service.get_current_user),
):
    # Use domain service
    from app.modules.cases.service import case_service
    
    result = case_service.get_cases_paginated(
        db, page=1, per_page=20, filters={}
    )
    return result
```

---

## πŸ“ Design Patterns

### Repository Pattern

**Location:** `app/modules/*/repository.py`

**Purpose:** Encapsulate data access logic  
**Responsibilities:**

- SQL queries
- ORM operations
- Data mapping

**Example:**

```python
class CaseRepository:
    def get_paginated(self, page, per_page, filters):
        query = self.db.query(Case)
        # Apply filters, pagination
        return query.all(), query.count()
```

### Service Pattern

**Location:** `app/modules/*/service.py`

**Purpose:** Business logic orchestration  
**Responsibilities:**

- Business rules
- Validation
- Transaction management
- Calling repositories

**Example:**

```python
class CaseService:
    def create_case(self, db, data, creator_id):
        repo = CaseRepository(db)
        case = repo.create(data)
        db.commit()
        return case
```

### Dependency Injection

**Framework:** FastAPI's `Depends()`

**Common Dependencies:**

- `get_db()` - Database session
- `auth_service.get_current_user()` - Current authenticated user
- `rbac_service.require_admin()` - Role requirements

---

## πŸš€ Migration Guide

### From database_service to Domain Services

#### ❌ OLD WAY (Don't use)

```python
from app.services.infrastructure.storage.database_service import db_service

# WRONG - business logic in infrastructure
cases = db_service.get_cases_paginated(page=1, per_page=20)
```

#### βœ… NEW WAY (Correct)

```python
from app.modules.cases.service import case_service
from core.database import get_db

# CORRECT - business logic in domain service
db = next(get_db())
cases = case_service.get_cases_paginated(db, page=1, per_page=20, filters={})
```

### Quick Reference

| Old (database_service) | New (Domain Service) |
|------------------------|----------------------|
| `db_service.get_cases()` | `case_service.get_cases_paginated()` |
| `db_service.get_case_stats()` | `case_service.get_case_stats()` |
| `db_service.get_users_paginated()` | `user_service.get_paginated()` |
| `db_service.get_case_analytics()` | `analytics_service.get_case_analytics()` |
| `db_service.get_transaction_aggregates()` | `analytics_service.get_transaction_aggregates()` |
| `db_service.get_transactions_by_case()` | `transaction_service.get_transactions_by_case()` |

---

## βœ… Benefits of This Architecture

### 1. **Maintainability**

- Clear separation of concerns
- Easy to find where logic lives
- Single responsibility per service

### 2. **Testability**

- Mock repositories easily
- Test business logic independently
- Infrastructure tests separate

### 3. **Scalability**

- Services can be extracted to microservices
- Clear boundaries for team ownership
- Easy to add new domains

### 4. **Security**

- Business logic protected by service layer
- Consistent authorization patterns
- PII scrubbing at infrastructure level

### 5. **Performance**

- Caching at the right layer
- Query optimization in repositories
- Infrastructure monitoring separate from business

---

## πŸ“Š Code Metrics

### Before Consolidation

- `database_service.py`: **1,086 lines** (mixed business + infrastructure)
- Overlapping cache services: **2 implementations**
- Overlapping logging: **2 implementations**
- Unused services: **6 files (~2,500 lines)**

### After Consolidation

- `database_service.py`: **~270 lines** (pure infrastructure)
- Cache service: **1 unified implementation**
- Logging service: **1 unified implementation + PII scrubbing**
- Domain services: **Clear separation across 6 modules**

### Impact

- **75% reduction** in database_service.py
- **~3,000 lines removed** (dead code)
- **Zero overlapping functions**
- **Clean architecture achieved**

---

## 🎯 Next Steps

### For New Features

1. Identify the domain (cases, users, transactions, etc.)
2. Add methods to the appropriate domain service
3. Create repository methods if needed
4. Add router endpoints
5. Write tests

### For Existing Code

1. Check if using `database_service` for business logic
2. Migrate to appropriate domain service
3. Update imports
4. Test thoroughly

### For Infrastructure

1. Use `database_service` ONLY for:
   - Session management
   - Health checks
   - Performance monitoring
2. Everything else β†’ domain services

---

## πŸ“š Related Documentation

- [Consolidation Report](./CONSOLIDATION_REPORT.md)
- [Test Validation Report](./TEST_VALIDATION_REPORT.md)
- [Database Service Cleanup Plan](./DATABASE_SERVICE_CLEANUP_PLAN.md)
- [API Documentation](./docs/API.md)

---

**Architecture Status:** βœ… Production Ready  
**Last Audit:** 2026-01-15  
**Compliance:** Clean Architecture, DDD, SOLID Principles