# Analytics Module Documentation Index

This directory contains comprehensive documentation about the GoodGo Platform Analytics Module. Start here to understand the architecture and implementation patterns.

---

## 📚 Documentation Files

### 1. 🎯 **EXPLORATION_SUMMARY.md** - START HERE
**Purpose**: High-level overview and quick findings
**Length**: ~12 KB | **Read Time**: 10 minutes
**Contains**:
- Key findings summary
- Quick statistics (2 controllers, 14+ queries, 3 commands)
- File path quick map
- Implementation templates for new handlers
- Next steps for implementation

👉 **Best for**: Getting oriented quickly, understanding what was discovered

---

### 2. 📖 **ANALYTICS_ARCHITECTURE.md** - COMPREHENSIVE REFERENCE
**Purpose**: Deep-dive technical documentation
**Length**: ~25 KB | **Read Time**: 30-40 minutes
**Contains** (10 detailed sections):
1. Module structure (DDD layers)
2. Controller & endpoint structure
3. Query/Handler pattern (CQRS implementation)
4. Redis caching patterns (cache-aside, Lua scripts)
5. Prisma schema for all models
6. Shared guards & decorators
7. DTO patterns
8. Dependency injection & module setup
9. Key patterns & conventions
10. Quick reference paths

👉 **Best for**: Deep understanding, implementation reference, code review

---

### 3. ⚡ **ANALYTICS_QUICK_REFERENCE.md** - DEVELOPER CHEAT SHEET
**Purpose**: Quick lookup guide for developers
**Length**: ~11 KB | **Read Time**: 5-10 minutes (reference)
**Contains**:
- Architecture stack overview
- All file paths organized by layer
- Guard & decorator stack explanation
- Cache patterns (TTLs, prefixes, code examples)
- Prisma models summary
- Complete handler pattern code example
- Common endpoints list
- Error handling pattern
- Conventions table

👉 **Best for**: Developers implementing features, quick syntax lookup, copy-paste templates

---

### 4. 🔄 **ANALYTICS_ARCHITECTURE_DIAGRAM.txt** - VISUAL OVERVIEW
**Purpose**: Visual representation of system architecture
**Length**: ~19 KB | **Read Time**: 15 minutes
**Contains**:
- Complete system architecture ASCII diagram
- All layers: HTTP → Database
- Data flow walkthrough for example request
- Component relationships
- External service integrations
- Shared utilities & exports

👉 **Best for**: Understanding system flow, presentations, documentation

---

## 🎓 Suggested Reading Order

### For New Team Members
1. EXPLORATION_SUMMARY.md (overview)
2. ANALYTICS_ARCHITECTURE_DIAGRAM.txt (visual)
3. ANALYTICS_QUICK_REFERENCE.md (reference)

### For Implementation
1. ANALYTICS_QUICK_REFERENCE.md (templates)
2. ANALYTICS_ARCHITECTURE.md (section 3-8 for patterns)
3. Look at existing handlers: `apps/api/src/modules/analytics/application/queries/`

### For Code Review
1. ANALYTICS_ARCHITECTURE.md (full reference)
2. ANALYTICS_QUICK_REFERENCE.md (conventions table)
3. Check against existing patterns

### For Architecture Understanding
1. ANALYTICS_ARCHITECTURE_DIAGRAM.txt
2. ANALYTICS_ARCHITECTURE.md (sections 1-3, 8)
3. Look at: `analytics.module.ts`, `analytics.controller.ts`

---

## 🔍 Quick Lookup Guide

### "How do I create a new query handler?"
→ ANALYTICS_QUICK_REFERENCE.md → "CQRS Handler Pattern" section
→ ANALYTICS_ARCHITECTURE.md → Section 3

### "What cache TTLs should I use?"
→ ANALYTICS_QUICK_REFERENCE.md → "Cache Patterns" section
→ ANALYTICS_ARCHITECTURE.md → Section 4 (Cache Configuration)

### "How does rate limiting work?"
→ ANALYTICS_QUICK_REFERENCE.md → "Guards & Decorators Stack"
→ ANALYTICS_ARCHITECTURE.md → Section 4 (Rate Limiting with Redis)

### "What are the Prisma models for analytics?"
→ ANALYTICS_QUICK_REFERENCE.md → "Prisma Models" section
→ ANALYTICS_ARCHITECTURE.md → Section 5

### "How should I handle errors?"
→ ANALYTICS_QUICK_REFERENCE.md → "Error Handling Pattern"
→ ANALYTICS_ARCHITECTURE.md → Section 6

### "What endpoints exist?"
→ ANALYTICS_QUICK_REFERENCE.md → "Common Endpoints" section
→ ANALYTICS_ARCHITECTURE.md → Section 2

### "How do I understand the full data flow?"
→ ANALYTICS_ARCHITECTURE_DIAGRAM.txt → "Data Flow Example" section

---

## 📊 Key Takeaways

### Architecture Pattern
**DDD + CQRS** with clear layer separation:
- Presentation (controllers, DTOs)
- Application (query/command handlers)
- Domain (interfaces, entities)
- Infrastructure (Prisma, external services)

### Caching Strategy
**Cache-aside pattern** with Redis:
- `cache.getOrSet(key, loader, TTL, metric)`
- Graceful degradation if Redis unavailable
- Prometheus metrics for cache hit/miss/degradation

### Rate Limiting
**Sliding-window with Redis sorted sets**:
- Per-endpoint configuration
- Key by user ID or IP
- 429 response with Retry-After header

### CQRS Pattern
**Separation of commands and queries**:
- Queries: read operations, cached with getOrSet()
- Commands: write operations, tracked
- Event handlers: listen to domain events

### Repository Pattern
**Dependency inversion**:
- Domain: interface definition (Symbol)
- Infrastructure: Prisma implementation
- Handlers: inject repository abstraction

### Error Handling
**Consistent pattern**:
1. Catch DomainException → rethrow
2. Log unexpected errors
3. Return user-friendly message via InternalServerErrorException

---

## 🚀 Implementation Checklist

When adding a new analytics query:

- [ ] Create Query class in `application/queries/your-feature/`
- [ ] Create Handler with cache-aside pattern
- [ ] Define DTO interface as handler return type
- [ ] Create Request DTO for controller parameters
- [ ] Add endpoint to appropriate controller
- [ ] Apply guard stack: EndpointRateLimitGuard → JwtAuthGuard → QuotaGuard
- [ ] Add `@RequireQuota('analytics_queries')`
- [ ] Register handler in `analytics.module.ts` QueryHandlers array
- [ ] Follow naming convention: Query → Handler → Dto
- [ ] Use CacheService.buildKey() for cache keys
- [ ] Use CacheTTL.* constants for TTLs
- [ ] Catch DomainException separately
- [ ] Add comprehensive error handling
- [ ] Test with Swagger/Postman
- [ ] Add unit tests in `__tests__/` directory

---

## 📋 File Statistics

| File | Size | Sections | Key Purpose |
|------|------|----------|-------------|
| EXPLORATION_SUMMARY.md | 12 KB | 11 + templates | Overview & quick reference |
| ANALYTICS_ARCHITECTURE.md | 25 KB | 10 detailed | Deep technical reference |
| ANALYTICS_QUICK_REFERENCE.md | 11 KB | Reference | Developer cheat sheet |
| ANALYTICS_ARCHITECTURE_DIAGRAM.txt | 19 KB | ASCII diagrams | Visual architecture |

**Total Documentation**: ~67 KB of comprehensive guides

---

## 🔗 Key File Paths Mentioned

### Analytics Module Root
```
apps/api/src/modules/analytics/
```

### Controllers
```
presentation/controllers/analytics.controller.ts      (13+ endpoints)
presentation/controllers/avm.controller.ts            (5 endpoints)
```

### Query Handlers (14+)
```
application/queries/{query-name}/{query-name}.query.ts
application/queries/{query-name}/{query-name}.handler.ts
```

### Shared Module
```
apps/api/src/modules/shared/
├── infrastructure/cache.service.ts               (cache-aside)
├── infrastructure/redis.service.ts               (Redis connection)
├── infrastructure/guards/endpoint-rate-limit.guard.ts
├── domain/domain-exception.ts
└── ...
```

---

## 💡 Tips for Using These Docs

1. **Keep ANALYTICS_QUICK_REFERENCE.md open** while coding
2. **Use Ctrl+F to search** for specific concepts
3. **Read ANALYTICS_ARCHITECTURE.md sections sequentially** for learning
4. **Reference ANALYTICS_ARCHITECTURE_DIAGRAM.txt** when explaining to others
5. **Copy code templates** from ANALYTICS_QUICK_REFERENCE.md
6. **Check conventions table** before naming new classes/files

---

## 🎯 Common Scenarios

### I need to add a market analytics endpoint
→ See ANALYTICS_QUICK_REFERENCE.md: "CQRS Handler Pattern"
→ Use CachePrefix.MARKET_REPORT or MARKET_TREND
→ Check existing handlers: get-price-trend, get-heatmap, get-market-report

### I need to add a valuation endpoint
→ See ANALYTICS_QUICK_REFERENCE.md: "Common Endpoints"
→ Use CachePrefix.VALUATION
→ Check existing: predict-valuation, batch-valuation, valuation-history

### I need to understand the cache strategy
→ See ANALYTICS_QUICK_REFERENCE.md: "Cache Patterns"
→ See ANALYTICS_ARCHITECTURE.md: Section 4 (full details)

### I need to add rate limiting
→ Already applied via @EndpointRateLimit decorator
→ See ANALYTICS_QUICK_REFERENCE.md: "Guards & Decorators Stack"
→ Modify limit/windowSeconds/keyStrategy as needed

### I need to understand error handling
→ See ANALYTICS_QUICK_REFERENCE.md: "Error Handling Pattern"
→ See ANALYTICS_ARCHITECTURE.md: Section 6

---

## ✅ Documentation Quality Checklist

- ✅ Complete layer documentation (presentation → infrastructure)
- ✅ All 14+ query handlers covered
- ✅ Redis caching with Lua scripts explained
- ✅ Rate limiting architecture explained
- ✅ Prisma schema for analytics models
- ✅ Shared module exports documented
- ✅ Guard & decorator stack explained
- ✅ Error handling patterns shown
- ✅ Implementation templates provided
- ✅ Visual architecture diagram included
- ✅ Quick reference for developers
- ✅ File paths organized by layer

---

## 📞 Questions?

Refer to the specific documentation file for your scenario:
- **What?** → EXPLORATION_SUMMARY.md (quick findings)
- **How?** → ANALYTICS_QUICK_REFERENCE.md (templates & patterns)
- **Why?** → ANALYTICS_ARCHITECTURE.md (detailed explanations)
- **Where?** → ANALYTICS_ARCHITECTURE_DIAGRAM.txt (visual flow)

---

**Last Updated**: April 2026
**Scope**: Analytics Module (apps/api/src/modules/analytics/)
**Coverage**: DDD, CQRS, Caching, Rate Limiting, Prisma, Shared Utilities
