Added Documents Feature

This commit is contained in:
Eric Gullickson
2025-09-28 20:35:46 -05:00
parent 2e1b588270
commit 775a1ff69e
66 changed files with 5655 additions and 944 deletions

View File

@@ -0,0 +1,221 @@
# MotoVaultPro Documentation Audit Report
**Date**: 2025-09-28
**Auditor**: Claude AI Assistant
**Scope**: Technical accuracy, consistency, and alignment with actual codebase architecture
## Executive Summary
I have conducted a comprehensive audit of the MotoVaultPro project documentation and identified **14 significant issues** across 4 priority levels. The audit revealed critical infrastructure mismatches, architectural contradictions, misleading security claims, and inconsistent testing information that could cause system failures or developer confusion.
## Audit Methodology
### Research Scope
- All major documentation files (PLATFORM-SERVICES.md, TESTING.md, DATABASE-SCHEMA.md, SECURITY.md, VEHICLES-API.md, README files)
- Docker configuration and container architecture
- Migration system and database schemas
- Makefile commands and actual implementations
- Package.json dependencies and scripts
- Actual API endpoints and service implementations
- Testing structure and coverage claims
- Authentication and security implementations
### Evidence Standards
- Every finding includes specific file references and line numbers
- Cross-referenced documentation claims with actual codebase implementation
- Prioritized issues by potential impact on system functionality
- Provided actionable recommendations for each issue
## Audit Findings
### CRITICAL Priority Issues (Will Cause Failures)
#### 1. Platform Services Port Mismatch
**FILE**: `docs/PLATFORM-SERVICES.md`
**SECTION**: Line 78 - MVP Platform Tenants Service
**ISSUE TYPE**: Inaccuracy
**DESCRIPTION**: Claims tenants API runs on "port 8001"
**PROBLEM**: docker-compose.yml shows both platform services on port 8000, no service on 8001
**EVIDENCE**: PLATFORM-SERVICES.md:78 vs docker-compose.yml:lines 72-120
**RECOMMENDATION**: Correct documentation to show port 8000 for both services
#### 2. Database Password Contradiction
**FILE**: `docs/DATABASE-SCHEMA.md`
**SECTION**: Line 200 - Database Connection
**ISSUE TYPE**: Inaccuracy
**DESCRIPTION**: Claims development password is "localdev123"
**PROBLEM**: docker-compose.yml uses secrets files, not hardcoded passwords
**EVIDENCE**: DATABASE-SCHEMA.md:200 vs docker-compose.yml:282-287
**RECOMMENDATION**: Update to reflect secrets-based credential management
#### 3. Migration Idempotency Contradiction
**FILE**: `docs/DATABASE-SCHEMA.md`
**SECTION**: Lines 15-16 - Migration Tracking
**ISSUE TYPE**: Contradiction
**DESCRIPTION**: Claims migrations are tracked as "idempotent" but warns "may fail on indexes without IF NOT EXISTS"
**PROBLEM**: Cannot be both idempotent and prone to failure
**EVIDENCE**: docs/VEHICLES-API.md:84 claims "idempotent" vs DATABASE-SCHEMA.md:16 warns of failures
**RECOMMENDATION**: Clarify actual migration behavior and safety guarantees
#### 4. Health Check Endpoint Mismatch
**FILE**: `docs/PLATFORM-SERVICES.md`
**SECTION**: Lines 243-244 - Health Checks
**ISSUE TYPE**: Inaccuracy
**DESCRIPTION**: Claims health endpoints at "localhost:8001/health"
**PROBLEM**: No service running on port 8001 based on docker-compose.yml
**EVIDENCE**: PLATFORM-SERVICES.md:244 vs docker-compose.yml service definitions
**RECOMMENDATION**: Correct health check URLs to match actual service ports
### HIGH Priority Issues (Significant Confusion)
#### 5. Platform Service Independence Claims
**FILE**: `docs/PLATFORM-SERVICES.md`
**SECTION**: Line 98 - Service Communication
**ISSUE TYPE**: Misleading
**DESCRIPTION**: Claims platform services are "completely independent"
**PROBLEM**: Services share config files (./config/shared/production.yml) and secret directories
**EVIDENCE**: PLATFORM-SERVICES.md:98 vs docker-compose.yml:90,137,184
**RECOMMENDATION**: Clarify actual dependency relationships and shared resources
#### 6. Test Coverage Misrepresentation
**FILE**: `docs/README.md`
**SECTION**: Line 24 - Feature test coverage
**ISSUE TYPE**: Misleading
**DESCRIPTION**: Claims "vehicles has full coverage"
**PROBLEM**: Only 7 test files exist across all features, minimal actual coverage
**EVIDENCE**: docs/README.md:24 vs find results showing 7 total .test.ts files
**RECOMMENDATION**: Provide accurate coverage metrics or remove coverage claims
#### 7. API Script Reference Error
**FILE**: `backend/README.md`
**SECTION**: Line 46 - Test Commands
**ISSUE TYPE**: Inaccuracy
**DESCRIPTION**: Documents command syntax as "--feature=vehicles" with equals sign
**PROBLEM**: Actual npm script uses positional argument ${npm_config_feature}
**EVIDENCE**: backend/README.md:46 vs backend/package.json:12 script definition
**RECOMMENDATION**: Correct command syntax documentation
#### 8. Cache TTL Value Conflicts
**FILE**: `docs/VEHICLES-API.md` vs `mvp-platform-services/vehicles/api/config.py`
**SECTION**: Line 41 vs Line 35
**ISSUE TYPE**: Contradiction
**DESCRIPTION**: Documentation claims "6 hours" default TTL, code shows 3600 (1 hour)
**PROBLEM**: Inconsistent caching behavior documentation
**EVIDENCE**: VEHICLES-API.md:41 "6 hours" vs config.py:35 "3600 (1 hour default)"
**RECOMMENDATION**: Synchronize TTL values in documentation and code
### MEDIUM Priority Issues (Inconsistencies)
#### 9. Architecture Pattern Confusion
**FILE**: `docs/PLATFORM-SERVICES.md`
**SECTION**: Multiple references to "4-tier isolation"
**ISSUE TYPE**: Unclear
**DESCRIPTION**: Claims "4-tier network isolation" but implementation details are unclear
**PROBLEM**: docker-compose.yml shows services sharing networks, not clear isolation
**EVIDENCE**: Makefile:57,146-149 mentions tiers vs actual network sharing in docker-compose.yml
**RECOMMENDATION**: Clarify actual network topology and isolation boundaries
#### 10. Container Name Inconsistencies
**FILE**: Multiple documentation files
**SECTION**: Various service references
**ISSUE TYPE**: Inaccuracy
**DESCRIPTION**: Documentation uses inconsistent container naming patterns
**PROBLEM**: Makes service discovery and debugging instructions unreliable
**EVIDENCE**: Mix of "admin-backend", "backend", "mvp-platform-*" naming across docs
**RECOMMENDATION**: Standardize container name references across all documentation
#### 11. Authentication Method Confusion
**FILE**: `docs/SECURITY.md` vs `docs/PLATFORM-SERVICES.md`
**SECTION**: Authentication sections
**ISSUE TYPE**: Contradiction
**DESCRIPTION**: Mixed claims about JWT vs API key authentication
**PROBLEM**: Unclear which auth method applies where
**EVIDENCE**: SECURITY.md mentions Auth0 JWT, PLATFORM-SERVICES.md mentions API keys
**RECOMMENDATION**: Create clear authentication flow diagram showing all methods
#### 12. Development Workflow Claims
**FILE**: `README.md`
**SECTION**: Line 7 - Docker-first requirements
**ISSUE TYPE**: Misleading
**DESCRIPTION**: Claims "production-only" development but allows development database access
**PROBLEM**: Contradicts stated "production-only" methodology
**EVIDENCE**: README.md:7 vs docker-compose.yml:291,310,360,378,422,440 (dev ports)
**RECOMMENDATION**: Clarify actual development vs production boundaries
### LOW Priority Issues (Minor Issues)
#### 13. Makefile Command Documentation Gaps
**FILE**: Multiple files referencing make commands
**SECTION**: Various command references
**ISSUE TYPE**: Unclear
**DESCRIPTION**: Some documented make commands have unclear purposes
**PROBLEM**: Developers may use wrong commands for tasks
**EVIDENCE**: Makefile contains commands not well documented in usage guides
**RECOMMENDATION**: Add comprehensive command documentation
#### 14. Feature Documentation Inconsistency
**FILE**: `backend/src/features/*/README.md` files
**SECTION**: Feature-specific documentation
**ISSUE TYPE**: Inconsistency
**DESCRIPTION**: Different documentation standards across features
**PROBLEM**: Makes onboarding and maintenance inconsistent
**EVIDENCE**: Varying detail levels and structures across feature README files
**RECOMMENDATION**: Standardize feature documentation templates
## Analysis Summary
### Issue Type Distribution
- **Inaccuracies**: 6 issues (43% - ports, passwords, commands, endpoints)
- **Contradictions**: 4 issues (29% - idempotency, TTL, authentication, independence)
- **Misleading**: 3 issues (21% - coverage, independence, development methodology)
- **Unclear**: 1 issue (7% - network architecture)
### Priority Distribution
- **CRITICAL**: 4 issues (29% - will cause failures)
- **HIGH**: 4 issues (29% - significant confusion)
- **MEDIUM**: 4 issues (29% - inconsistencies)
- **LOW**: 2 issues (14% - minor issues)
### Root Causes Analysis
1. **Documentation Drift**: Code evolved but documentation wasn't updated
2. **Multiple Sources of Truth**: Same information documented differently in multiple places
3. **Aspirational Documentation**: Documents intended behavior rather than actual implementation
4. **Incomplete Implementation**: Features documented before full implementation
## Recommendations
### Immediate Actions (Critical Issues)
1. **Fix Port Mismatches**: Update all port references to match docker-compose.yml
2. **Correct Database Documentation**: Reflect actual secrets-based credential management
3. **Clarify Migration Behavior**: Document actual safety guarantees and failure modes
4. **Fix Health Check URLs**: Ensure all health check examples use correct endpoints
### Short-term Actions (High Priority)
1. **Service Dependency Audit**: Document actual shared resources and dependencies
2. **Test Coverage Analysis**: Conduct real coverage analysis and update claims
3. **Command Syntax Verification**: Validate all documented commands and examples
4. **Cache Configuration Sync**: Align all TTL documentation with actual values
### Long-term Actions (Medium/Low Priority)
1. **Architecture Documentation Overhaul**: Create accurate diagrams of actual vs claimed isolation
2. **Naming Convention Standardization**: Establish and enforce consistent naming across docs
3. **Authentication Flow Documentation**: Develop comprehensive auth flow diagrams
4. **Documentation Standards**: Establish review processes and templates
### Process Improvements
1. **Documentation Review Process**: Require documentation updates with code changes
2. **Automated Validation**: Create scripts to validate documented commands and endpoints
3. **Single Source of Truth**: Identify authoritative sources for each type of information
4. **Regular Audits**: Schedule periodic documentation accuracy reviews
## Conclusion
This audit reveals that while the MotoVaultPro project has extensive documentation, there are significant gaps between documented behavior and actual implementation. These issues range from critical infrastructure mismatches that will cause system failures to misleading architectural claims that could confuse developers and AI agents.
The 14 identified issues provide a clear roadmap for bringing documentation in line with reality. Addressing the 4 critical issues should be the immediate priority, as these will prevent system failures when following documented procedures.
The findings suggest implementing stronger processes to keep documentation synchronized with code changes, particularly around infrastructure configuration, API endpoints, and architectural claims.
---
**Audit Completion**: All major documentation files reviewed and cross-referenced with actual codebase implementation. Evidence-based findings with specific file references and actionable recommendations provided.

71
docs/PROMPTS.md Normal file
View File

@@ -0,0 +1,71 @@
*** CRITICAL ***: Never read this file. Stop and move on.
*** STARTING PROMPT ***
## Key Commands
- Start: `make start`
- Rebuild: `make rebuild`
- Logs: `make logs`
- Test: `make test`
## Development Rules
1. NEVER use emojis in code or documentation
2. Every feature MUST be responsive (mobile + desktop)
3. Testing and debugging can be done locally.
4. All testing and debugging needs to be verified in containers.
5. Each backend feature is self-contained in src/features/[name]/
6. Delete old code when replacing (no commented code)
7. Use meaningful variable names (userID not id)
## Making Changes
### Frontend Changes (React)
- Components: `frontend/src/features/[feature]/components/`
- Types: `frontend/src/features/[feature]/types/`
- After changes: `make rebuild` then test at https://admin.motovaultpro.com
### Backend Changes (Node.js)
- API: `backend/src/features/[feature]/api/`
- Business logic: `backend/src/features/[feature]/domain/`
- Database: `backend/src/features/[feature]/data/`
- After changes: `make rebuild` then check logs
### Database Changes
- Add migration: `backend/src/features/[feature]/migrations/00X_description.sql`
- Run: `make migrate`
### Adding NPM Packages
- Edit package.json (frontend or backend)
- Run `make rebuild` (no local npm install)
## Common Tasks
### Add a form field:
1. Update types in frontend/backend
2. Add to database migration if needed
3. Update React form component
4. Update backend validation
5. Test with `make rebuild`
### Add new API endpoint:
1. Create route in `backend/src/features/[feature]/api/`
2. Add service method in `domain/`
3. Add repository method in `data/`
4. Test with `make rebuild`
### Fix UI responsiveness:
1. Use Tailwind classes: `sm:`, `md:`, `lg:`
2. Test on mobile viewport (375px) and desktop (1920px)
3. Ensure touch targets are 44px minimum
## Current Task
[Describe your specific task here - e.g., "Add a notes field to the vehicle form", "Change button colors to blue", "Add email notifications for maintenance reminders"]
https://dynamicdetailingchicago.com
https://exoticcarcolors.com/car-companies/ferrari
## Important Context
- Auth: Frontend uses Auth0, backend validates JWTs
- Database: PostgreSQL with user-isolated data (user_id scoping)
- Platform APIs: Authenticated via API keys
- File uploads: MinIO S3-compatible storage
What changes do you need help with today?

View File

@@ -1,149 +1,24 @@
# MotoVaultPro Documentation
Complete documentation for the MotoVaultPro distributed microservices platform with Modified Feature Capsule application layer and MVP Platform Services.
Project documentation hub for the hybrid platform (platform microservices) and modular monolith application.
## Quick Navigation
## Navigation
### 🚀 Getting Started
- **[AI Project Guide](../AI_PROJECT_GUIDE.md)** - Complete AI-friendly project overview and navigation
- **[Security Architecture](SECURITY.md)** - Authentication, authorization, and security considerations
- Architecture: `docs/PLATFORM-SERVICES.md`
- Security: `docs/SECURITY.md`
- Vehicles API (authoritative): `docs/VEHICLES-API.md`
- Database schema: `docs/DATABASE-SCHEMA.md`
- Testing (containers only): `docs/TESTING.md`
- Development commands: `Makefile`, `docker-compose.yml`
- Application features (start at each README):
- `backend/src/features/vehicles/README.md`
- `backend/src/features/fuel-logs/README.md`
- `backend/src/features/maintenance/README.md`
- `backend/src/features/stations/README.md`
- `backend/src/features/documents/README.md`
### 🏗️ Architecture
- **[Architecture Directory](architecture/)** - Detailed architectural documentation
- **[Platform Services Guide](PLATFORM-SERVICES.md)** - MVP Platform Services architecture and development
- **[Vehicles API (Authoritative)](VEHICLES-API.md)** - Vehicles platform service + app integration
- **Application Feature Capsules** - Each feature has complete documentation in `backend/src/features/[name]/README.md`:
- **[Vehicles](../backend/src/features/vehicles/README.md)** - Platform service consumer for vehicle management
- **[Fuel Logs](../backend/src/features/fuel-logs/README.md)** - Fuel tracking and analytics
- **[Maintenance](../backend/src/features/maintenance/README.md)** - Vehicle maintenance scheduling
- **[Stations](../backend/src/features/stations/README.md)** - Gas station location services
## Notes
### 🔧 Development
- **[Docker Setup](../docker-compose.yml)** - Complete containerized development environment
- **[Makefile Commands](../Makefile)** - All available development commands
- **[Backend Package](../backend/package.json)** - Scripts and dependencies
- **[Frontend Package](../frontend/package.json)** - React app configuration
### 🧪 Testing
Each feature contains complete test suites:
- **Unit Tests**: `backend/src/features/[name]/tests/unit/`
- **Integration Tests**: `backend/src/features/[name]/tests/integration/`
- **Test Commands**: `npm test -- features/[feature-name]`
### 🗄️ Database
- **[Migration System](../backend/src/_system/migrations/)** - Database schema management
- **Feature Migrations**: Each feature manages its own schema in `migrations/` directory
- **Migration Order**: vehicles → fuel-logs → maintenance → stations
### 🔐 Security
- **[Security Overview](SECURITY.md)** - Complete security architecture
- **Authentication**: Auth0 JWT for all protected endpoints
- **Authorization**: User-scoped data access
- **External APIs**: Rate limiting and caching strategies
### 📦 Services & Integrations
#### MVP Platform Services
- See **Vehicles API (Authoritative)**: [VEHICLES-API.md](VEHICLES-API.md)
- Future Platform Services: Analytics, notifications, payments, document management
#### Application Services
- **PostgreSQL**: Application data storage
- **Redis**: Application caching layer
- **MinIO**: Object storage for files
#### External APIs
- **Google Maps API**: Station location services (1-hour cache)
- **Auth0**: Authentication and authorization
### 🚀 Deployment
- **[Kubernetes](../k8s/)** - Production deployment manifests
- **Environment**: Ensure a valid `.env` exists at project root
- **Services**: All services containerized with health checks
## Documentation Standards
### Feature Documentation
Each feature capsule maintains comprehensive documentation:
- **README.md**: Complete API reference, business rules, caching strategy
- **docs/**: Additional feature-specific documentation
- **API Examples**: Request/response samples with authentication
- **Error Handling**: Complete error code documentation
### Code Documentation
- **Self-documenting code**: Meaningful names and clear structure
- **Minimal comments**: Code should be self-explanatory
- **Type definitions**: Complete TypeScript types in `domain/types.ts`
## Getting Help
### Quick Commands
```bash
# Start full microservices environment
make start
# View all logs
make logs
# View platform service logs
make logs-platform-vehicles
# Run all tests
make test
# Rebuild after changes
make rebuild
# Access container shells
make shell-backend # Application service
make shell-frontend
make shell-platform-vehicles # Platform service
```
### Health Checks
#### Application Services
- **Frontend**: http://localhost:3000
- **Backend API**: http://localhost:3001/health
- **MinIO Console**: http://localhost:9001
#### Platform Services
- **Platform Vehicles API**: http://localhost:8000/health
- **Platform Vehicles Docs**: http://localhost:8000/docs
### Troubleshooting
1. **Container Issues**: `make clean && make start`
2. **Database Issues**: Check `make logs-backend` for migration errors
3. **Permission Issues**: Verify USER_ID/GROUP_ID in `.env`
4. **Port Conflicts**: Ensure ports 3000, 3001, 5432, 6379, 9000, 9001 are available
## Contributing
### Adding New Features
1. **Generate**: `./scripts/generate-feature-capsule.sh [feature-name]`
2. **Implement**: Fill out all capsule directories (api, domain, data, etc.)
3. **Document**: Complete README.md following existing patterns
4. **Test**: Add comprehensive unit and integration tests
5. **Migrate**: Create and test database migrations
### Code Standards
- **Service Independence**: Platform services are completely independent
- **Feature Independence**: No shared business logic between application features
- **Docker-First**: All development in containers
- **Test Coverage**: Unit and integration tests required
- **Documentation**: AI-friendly documentation for all services and features
## Architecture Benefits
### For AI Maintenance
- **Service-Level Context**: Load platform service docs OR feature directory for complete understanding
- **Self-Contained Components**: No need to trace dependencies across service boundaries
- **Consistent Patterns**: Platform services and application features follow consistent structures
- **Complete Documentation**: All information needed is co-located with service/feature code
- **Clear Boundaries**: Explicit separation between platform and application concerns
### For Developers
- **Service Independence**: Work on platform services and application features independently
- **Microservices Benefits**: Independent deployment, scaling, and technology choices
- **Predictable Structure**: Same organization patterns across services and features
- **Easy Testing**: Service-level and feature-level test isolation
- **Clear Dependencies**: Explicit service communication patterns
- Canonical URLs: Frontend `https://admin.motovaultpro.com`, Backend health `http://localhost:3001/health`.
- Hosts entry required: `127.0.0.1 motovaultpro.com admin.motovaultpro.com`.
- Feature test coverage varies; vehicles has full coverage, others are in progress.

View File

@@ -28,7 +28,7 @@ make test
```
This executes:
- Backend: `docker compose exec backend npm test`
- Backend: `docker compose exec admin-backend npm test`
- Frontend: runs Jest in a disposable Node container mounting `./frontend`
### Feature-Specific Testing
@@ -134,7 +134,8 @@ make test-frontend
npm test -- features/vehicles --coverage
# View coverage report
open coverage/lcov-report/index.html
# Inside the container, open using your OS tooling,
# or copy the report out of the container as needed
```
### Container Management
@@ -153,7 +154,7 @@ make clean && make start
### Jest Configuration
- Backend: `backend/jest.config.js`
- Frontend: `frontend/jest.config.cjs`
- Frontend: `frontend/jest.config.ts`
- React + TypeScript via `ts-jest`
- jsdom environment
- Testing Library setup in `frontend/setupTests.ts`

299
docs/changes/DOCUMENTS.md Normal file
View File

@@ -0,0 +1,299 @@
# Documents Feature Plan (S3-Compatible, Phased)
This plan aligns with the current codebase: MinIO is running (`admin-minio`), object storage credentials are mounted as secrets, and `appConfig.getMinioConfig()` is available. We will implement a generic S3-compatible storage surface with a MinIO-backed adapter first, following the Dockerfirst, productiononly workflow and mobile+desktop requirements.
— Read me quick —
- Storage: Start with MinIO SDK via `getMinioConfig()`. Keep the interface S3generic to support AWS S3 later without changing features.
- Auth/Tenant: All endpoints use `[fastify.authenticate, tenantMiddleware]`.
- Testing: Use Jest; run via containers with `make test`.
- Mobile+Desktop: Follow existing Zustand nav, React Router routes, GlassCard components, and React Query offlineFirst.
Handoff markers are provided at the end of each phase. If work pauses, pick up from the next “Done when” checklist.
## Phase 0 — Baseline Verification
Objectives
- Confirm configuration and dependencies to avoid rework.
Tasks
- Verify MinIO configuration in `config/app/production.yml``minio.endpoint`, `minio.port`, `minio.bucket`.
- Verify mounted secrets exist for MinIO (`secrets/app/minio-access-key.txt`, `secrets/app/minio-secret-key.txt`).
- Verify backend dependency presence:
- Present: `minio@^7.1.3`
- Missing: `@fastify/multipart` (add to `backend/package.json`)
- Rebuild and tail logs
- `make rebuild`
- `make logs`
Done when
- Containers start cleanly and backend logs show no missing module errors.
Status
- MinIO configuration verified in repo (endpoint/port/bucket present) ✓
- MinIO secrets present in repo (mounted paths defined) ✓
- Package check: `minio` present ✓, `@fastify/multipart` added to backend/package.json ✓
- Rebuild/logs runtime verification: pending (perform via `make rebuild && make logs`)
## Phase 1 — Storage Foundation (S3-Compatible, MinIO-Backed)
Objectives
- Create a generic storage façade used by features; implement first adapter using MinIO SDK.
Design
- Interface `StorageService` methods:
- `putObject(bucket, key, bodyOrStream, contentType, metadata?)`
- `getObjectStream(bucket, key)`
- `deleteObject(bucket, key)`
- `headObject(bucket, key)`
- `getSignedUrl(bucket, key, { method: 'GET'|'PUT', expiresSeconds })`
- Key scheme: `documents/{userId}/{vehicleId}/{documentId}/{version}/{uuid}.{ext}`
- Security: Private objects only; shortlived signed URLs when needed.
Files
- `backend/src/core/storage/storage.service.ts` — façade and factory.
- `backend/src/core/storage/adapters/minio.adapter.ts` — uses MinIO SDK and `appConfig.getMinioConfig()`.
Tasks
- Implement MinIO client using endpoint/port/accessKey/secretKey/bucket from `appConfig.getMinioConfig()`.
- Ensure streaming APIs are used for uploads/downloads.
- Implement signed URL generation for downloads with short TTL (e.g., 60300s).
Done when
- Service can put/head/get/delete and generate signed URLs against `admin-minio` bucket from inside the backend container.
Status
- Storage facade added: `backend/src/core/storage/storage.service.ts`
- MinIO adapter implemented: `backend/src/core/storage/adapters/minio.adapter.ts`
- Runtime validation against MinIO: pending (validate post-rebuild) ☐
## Phase 2 — Backend HTTP Foundation
Objectives
- Enable file uploads and wire security.
Tasks
- Add `@fastify/multipart` to `backend/package.json`.
- In `backend/src/app.ts`, register multipart with configbased limits:
- `limits.fileSize` sourced from `appConfig.config.performance.max_request_size`.
- Confirm authentication plugin and tenant middleware are active (already implemented).
Done when
- Backend accepts multipart requests and enforces size limits without errors.
Status
- Dependency added: `@fastify/multipart`
- Registered in `backend/src/app.ts` with byte-limit parser ✓
- Runtime verification via container: pending ☐
## Phase 3 — Documents Feature Capsule (Backend)
Objectives
- Create the feature capsule with schema, repository, service, routes, and validators, following existing patterns (see vehicles and fuellogs).
Structure (backend)
```
backend/src/features/documents/
├── README.md
├── index.ts
├── api/
│ ├── documents.routes.ts
│ ├── documents.controller.ts
│ └── documents.validation.ts
├── domain/
│ ├── documents.service.ts
│ └── documents.types.ts
├── data/
│ └── documents.repository.ts
├── migrations/
│ └── 001_create_documents_table.sql
└── tests/
├── unit/
└── integration/
```
Database schema
- Table `documents`:
- `id UUID PK`
- `user_id VARCHAR(255)`
- `vehicle_id UUID` FK → `vehicles(id)`
- `document_type VARCHAR(32)` CHECK IN ('insurance','registration')
- `title VARCHAR(200)`; `notes TEXT NULL`; `details JSONB`
- `storage_bucket VARCHAR(128)`; `storage_key VARCHAR(512)`
- `file_name VARCHAR(255)`; `content_type VARCHAR(128)`; `file_size BIGINT`; `file_hash VARCHAR(128) NULL`
- `issued_date DATE NULL`; `expiration_date DATE NULL`
- `created_at TIMESTAMP DEFAULT now()`; `updated_at TIMESTAMP DEFAULT now()` with `update_updated_at_column()` trigger
- `deleted_at TIMESTAMP NULL`
- Indexes: `(user_id)`, `(vehicle_id)`, `(user_id, vehicle_id)`, `(document_type)`, `(expiration_date)`; optional GIN on `details` if needed.
API endpoints
```
POST /api/documents # Create metadata (with/without file)
GET /api/documents # List (filters: vehicleId, type, expiresBefore)
GET /api/documents/:id # Get metadata
PUT /api/documents/:id # Update metadata/details
DELETE /api/documents/:id # Soft delete (and delete object)
GET /api/documents/vehicle/:vehicleId # List by vehicle
POST /api/documents/:id/upload # Upload/replace file (multipart)
GET /api/documents/:id/download # Download (proxy stream or signed URL)
```
- Prehandlers: `[fastify.authenticate, tenantMiddleware]` for all routes.
- Validation: Zod schemas for params/query/body in `documents.validation.ts`.
- Ownership: Validate `vehicle_id` belongs to `user_id` using vehicles pattern (like fuellogs).
Wireup
- Register in `backend/src/app.ts`:
- `import { documentsRoutes } from './features/documents/api/documents.routes'`
- `await app.register(documentsRoutes, { prefix: '/api' })`
- Health: Update `/health` feature list to include `documents`.
- Migrations: Add `'features/documents'` to `MIGRATION_ORDER` in `backend/src/_system/migrations/run-all.ts` after `'features/vehicles'`.
Done when
- CRUD + upload/download endpoints are reachable and secured; migrations run in correct order; ownership enforced.
Status
- Capsule scaffolded (api/domain/data/tests/migrations/README) ✓
- Migration added `backend/src/features/documents/migrations/001_create_documents_table.sql`
- Registered routes in `backend/src/app.ts` with `/api` prefix ✓
- Health feature list updated to include `documents`
- Migration order updated in `backend/src/_system/migrations/run-all.ts`
- CRUD handlers for metadata implemented ✓
- Upload endpoint implemented with multipart streaming, MIME allowlist, and storage meta update ✓
- Download endpoint implemented with proxy streaming and inline/attachment disposition ✓
- Ownership validation on create via vehicles check ✓
- Runtime verification in container: pending ☐
## Phase 4 — Frontend Feature (Mobile + Desktop)
Objectives
- Implement documents UI following existing navigation, layout, and data patterns.
Structure (frontend)
```
frontend/src/features/documents/
├── pages/
├── components/
├── hooks/
└── types/
```
Navigation
- Mobile: Add “Documents” to bottom nav (Zustand store in `frontend/src/core/store/navigation.ts`).
- Desktop: Add routes in `frontend/src/App.tsx` for list/detail/upload.
- Subscreens (mobile): list → detail → upload; wrap content with `GlassCard`.
Upload UX
- Mobile camera/gallery: `<input type="file" accept="image/*" capture="environment" />`.
- Desktop draganddrop with progress.
- Progress tracking: React Query mutation with progress events; optimistic updates and cache invalidation.
- Offline: Use existing React Query `offlineFirst` config; queue uploads and retry on reconnect.
Viewer
- Inline image/PDF preview; `Content-Disposition` inline for images/PDF; gestures (pinch/zoom) for mobile images.
Done when
- Users can list, upload, view, and delete documents on both mobile and desktop with responsive UI and progress.
Status
- Add Documents to mobile bottom nav (Zustand): completed ✓
- Add desktop routes in `App.tsx` (list/detail/upload): completed ✓
- Scaffold pages/components/hooks structure: completed ✓
- Hook list/detail CRUD endpoints with React Query: completed ✓
- Implement upload with progress UI: completed ✓ (hooks with onUploadProgress; UI in mobile/detail)
- Optimistic updates: partial (invalidate queries on success) ◐
- Offline queuing/retry via React Query networkMode: configured via hooks ✓
- Previews: basic image/PDF preview implemented ✓ (DocumentPreview)
- Gesture-friendly viewer: pending ☐
- Desktop navigation: sidebar now defaults open and includes Documents ✓
- Build hygiene: resolved TS unused import error in frontend documents hooks ✓
## Phase 5 — Security, Validation, and Policies
Objectives
- Enforce safe file handling and consistent deletion semantics.
Tasks
- MIME allowlist: `application/pdf`, `image/jpeg`, `image/png`; reject executables.
- Upload size: Enforce via multipart limit tied to `performance.max_request_size`.
- Deletion: Soft delete DB first; delete object after. Consider retention policy later if required.
- Logging: Create/update/delete/upload/download events include `user_id`, `document_id`, `vehicle_id` (use existing logger).
- Optional rate limiting for upload route (defer dependency until needed).
Done when
- Unsafe files rejected; logs record document events; deletions are consistent.
Status
- MIME allowlist enforced for uploads (PDF, JPEG, PNG) ✓
- Upload size enforced via multipart limit (config-driven) ✓
- Deletion semantics: DB soft-delete and best-effort storage object deletion ✓
- Event logging for document actions: pending ☐
## Phase 6 — Testing (Docker-First)
Objectives
- Achieve green tests and linting across backend and frontend.
Backend tests
- Unit: repository/service/storage adapter (mock MinIO), validators.
- Integration: API with test DB + MinIO container, stream upload/download, auth/tenant checks.
Frontend tests
- Unit: components/forms, upload interactions, previews.
- Integration: hooks with mocked API; navigation flows for list/detail/upload.
Commands
- `make test` (backend + frontend)
- `make shell-backend` then `npm test -- features/documents`
- `make test-frontend`
Done when
- All tests/linters pass with zero issues; upload/download E2E verified in containers.
Status
- Backend unit tests (service/repo/storage; validators): pending ☐
- Backend integration tests (upload/download/auth/tenant): pending ☐
- Frontend unit tests (components/forms/uploads/previews): pending ☐
- Frontend integration tests (hooks + navigation flows): pending ☐
- CI via `make test` and linters green: pending ☐
## Phase 7 — Reality Checkpoints and Handoff
Checkpoints
- After each phase: `make rebuild && make logs`.
- Before moving on: Verify auth + tenant prehandlers, ownership checks, and mobile responsiveness.
- When interrupted: Commit current status and annotate the “Current Handoff Status” section below.
Handoff fields (update as you go)
- Storage façade: [x] implemented [ ] validated against MinIO
- Multipart plugin: [x] registered [x] enforcing limits
- Documents migrations: [x] added [ ] executed [ ] indexes verified
- Repo/service/routes: [x] implemented [x] ownership checks
- Frontend routes/nav: [x] added [x] mobile [x] desktop
- Upload/download flows: backend [x] implemented UI [x] progress [x] preview [ ] signed URLs (optional)
- Tests: [ ] unit backend [ ] int backend [ ] unit frontend [ ] int frontend
Diagnostics Notes
- Added `/api/health` endpoint in backend to validate Traefik routing to admin-backend for API paths.
- Fixed Fastify schema boot error by removing Zod schemas from documents routes (align with existing patterns). This prevented route registration and caused 404 on `/api/*` while server crashed/restarted.
## S3 Compatibility Notes
- The interface is provideragnostic. MinIO adapter speaks S3compatible API using custom endpoint and credentials from `getMinioConfig()`.
- Adding AWS S3 later: Implement `backend/src/core/storage/adapters/s3.adapter.ts` using `@aws-sdk/client-s3`, wire via a simple provider flag (e.g., `storage.provider: 'minio' | 's3'`). No feature code changes expected.
- Security parity: Keep private objects by default; consider serverside encryption when adding AWS S3.
## Reference Pointers
- MinIO config: `backend/src/core/config/config-loader.ts` (`getMinioConfig()`) and `config/app/production.yml`.
- Auth plugin: `backend/src/core/plugins/auth.plugin.ts`.
- Tenant middleware: `backend/src/core/middleware/tenant.ts`.
- Migration runner: `backend/src/_system/migrations/run-all.ts` (edit `MIGRATION_ORDER`).
- Feature registration: `backend/src/app.ts` (register `documentsRoutes` and update `/health`).
- Frontend nav and layout: `frontend/src/App.tsx`, `frontend/src/core/store/navigation.ts`, `frontend/src/shared-minimal/components/mobile/GlassCard`.
## Success Criteria
- Documents CRUD with upload/download works on mobile and desktop.
- Ownership and tenant enforcement on every request; private object storage; safe file types.
- S3compatible storage layer with MinIO adapter; S3 adapter can be added without feature changes.
- All tests and linters green; migrations idempotent and ordered after vehicles.
- Build hygiene: backend TS errors fixed (unused import, override modifier, union narrowing) ✓