Files
TimeTracker/docs/implementation-notes/QUICK_START_ARCHITECTURE.md
Dries Peeters 29f7186ee8 docs: Reorganize documentation structure for better navigation
Complete reorganization of project documentation to improve discoverability,
navigation, and maintainability. All documentation has been restructured into
a clear, role-based hierarchy.

## Major Changes

### New Directory Structure
- Created `docs/api/` for API documentation
- Created `docs/admin/` with subdirectories:
  - `admin/configuration/` - Configuration guides
  - `admin/deployment/` - Deployment guides
  - `admin/security/` - Security documentation
  - `admin/monitoring/` - Monitoring and analytics
- Created `docs/development/` for developer documentation
- Created `docs/guides/` for user-facing guides
- Created `docs/reports/` for analysis reports and summaries
- Created `docs/changelog/` for detailed changelog entries (ready for future use)

### File Organization

#### Moved from Root Directory (40+ files)
- Implementation notes → `docs/implementation-notes/`
- Test reports → `docs/testing/`
- Analysis reports → `docs/reports/`
- User guides → `docs/guides/`

#### Reorganized within docs/
- API documentation → `docs/api/`
- Administrator documentation → `docs/admin/` (with subdirectories)
- Developer documentation → `docs/development/`
- Security documentation → `docs/admin/security/`
- Telemetry documentation → `docs/admin/monitoring/`

### Documentation Updates

#### docs/README.md
- Complete rewrite with improved navigation
- Added visual documentation map
- Organized by role (Users, Administrators, Developers)
- Better categorization and quick links
- Updated all internal links to new structure

#### README.md (root)
- Updated all documentation links to reflect new structure
- Fixed 8 broken links

#### app/templates/main/help.html
- Enhanced "Where can I get additional help?" section
- Added links to new documentation structure
- Added documentation index link
- Added admin documentation link for administrators
- Improved footer with organized documentation links
- Added "Complete Documentation" section with role-based links

### New Index Files
- Created README.md files for all new directories:
  - `docs/api/README.md`
  - `docs/guides/README.md`
  - `docs/reports/README.md`
  - `docs/development/README.md`
  - `docs/admin/README.md`

### Cleanup
- Removed empty `docs/security/` directory (moved to `admin/security/`)
- Removed empty `docs/telemetry/` directory (moved to `admin/monitoring/`)
- Root directory now only contains: README.md, CHANGELOG.md, LICENSE

## Results

**Before:**
- 45+ markdown files cluttering root directory
- Documentation scattered across root and docs/
- Difficult to find relevant documentation
- No clear organization structure

**After:**
- 3 files in root directory (README, CHANGELOG, LICENSE)
- Clear directory structure organized by purpose and audience
- Easy navigation with role-based organization
- All documentation properly categorized
- Improved discoverability

## Benefits

1. Better Organization - Documentation grouped by purpose and audience
2. Easier Navigation - Role-based sections (Users, Admins, Developers)
3. Improved Discoverability - Clear structure with README files in each directory
4. Cleaner Root - Only essential files at project root
5. Maintainability - Easier to add and organize new documentation

## Files Changed

- 40+ files moved from root to appropriate docs/ subdirectories
- 15+ files reorganized within docs/
- 3 major documentation files updated (docs/README.md, README.md, help.html)
- 5 new README index files created
- 2 empty directories removed

All internal links have been updated to reflect the new structure.
2025-12-14 07:56:07 +01:00

5.8 KiB

Quick Start: Using the New Architecture

This guide shows you how to use the new service layer, repository pattern, and other improvements.


🏗️ Architecture Overview

Routes → Services → Repositories → Models → Database

Layers

  1. Routes - Handle HTTP requests/responses
  2. Services - Business logic
  3. Repositories - Data access
  4. Models - Database models
  5. Schemas - Validation and serialization

📝 Quick Examples

Using Services in Routes

Before:

@route('/timer/start')
def start_timer():
    project = Project.query.get(project_id)
    if not project:
        return error
    timer = TimeEntry(...)
    db.session.add(timer)
    db.session.commit()

After:

from app.services import TimeTrackingService

@route('/timer/start')
def start_timer():
    service = TimeTrackingService()
    result = service.start_timer(user_id, project_id)
    if result['success']:
        return success_response(result['timer'])
    return error_response(result['message'])

Using Repositories

from app.repositories import TimeEntryRepository

repo = TimeEntryRepository()
entries = repo.get_by_user(user_id, include_relations=True)
active_timer = repo.get_active_timer(user_id)

Using Schemas for Validation

from app.schemas import TimeEntryCreateSchema
from app.utils.api_responses import validation_error_response

@route('/api/time-entries', methods=['POST'])
def create_entry():
    schema = TimeEntryCreateSchema()
    try:
        data = schema.load(request.get_json())
    except ValidationError as err:
        return validation_error_response(err.messages)
    
    # Use validated data...

Using API Response Helpers

from app.utils.api_responses import (
    success_response,
    error_response,
    paginated_response,
    created_response
)

# Success response
return success_response(data=project.to_dict(), message="Project created")

# Error response
return error_response("Project not found", error_code="not_found", status_code=404)

# Paginated response
return paginated_response(
    items=projects,
    page=1,
    per_page=50,
    total=100
)

# Created response
return created_response(data=project.to_dict(), location=f"/api/projects/{project.id}")

Using Constants

from app.constants import ProjectStatus, TimeEntrySource, InvoiceStatus

# Use enums instead of magic strings
project.status = ProjectStatus.ACTIVE.value
entry.source = TimeEntrySource.MANUAL.value
invoice.status = InvoiceStatus.DRAFT.value

Using Query Optimization

from app.utils.query_optimization import eager_load_relations, optimize_list_query

# Eagerly load relations to prevent N+1 queries
query = Project.query
query = eager_load_relations(query, Project, ['client', 'time_entries'])

# Or use auto-optimization
query = optimize_list_query(Project.query, Project)

Using Validation Utilities

from app.utils.validation import (
    validate_required,
    validate_date_range,
    validate_email,
    sanitize_input
)

# Validate required fields
validate_required(data, ['name', 'email'])

# Validate date range
validate_date_range(start_date, end_date)

# Validate email
email = validate_email(data['email'])

# Sanitize input
clean_input = sanitize_input(user_input, max_length=500)

🔄 Migration Guide

Step 1: Identify Business Logic

Find code in routes that:

  • Validates data
  • Performs calculations
  • Checks permissions
  • Creates/updates multiple models
  • Has complex conditional logic

Step 2: Extract to Service

Move business logic to a service method:

# app/services/my_service.py
class MyService:
    def do_something(self, param1, param2):
        # Business logic here
        return {'success': True, 'data': result}

Step 3: Use Repository for Data Access

Replace direct model queries with repository calls:

# Before
projects = Project.query.filter_by(status='active').all()

# After
repo = ProjectRepository()
projects = repo.get_active_projects()

Step 4: Update Route

Use service in route:

@route('/endpoint')
def my_endpoint():
    service = MyService()
    result = service.do_something(param1, param2)
    if result['success']:
        return success_response(result['data'])
    return error_response(result['message'])

🧪 Testing

Testing Services

from unittest.mock import Mock
from app.services import TimeTrackingService

def test_start_timer():
    service = TimeTrackingService()
    service.time_entry_repo = Mock()
    service.project_repo = Mock()
    
    result = service.start_timer(user_id=1, project_id=1)
    assert result['success'] == True

Testing Repositories

from app.repositories import TimeEntryRepository

def test_get_active_timer(db_session, user, project):
    repo = TimeEntryRepository()
    timer = repo.create_timer(user.id, project.id)
    db_session.commit()
    
    active = repo.get_active_timer(user.id)
    assert active.id == timer.id

📚 Additional Resources

  • Full Documentation: See IMPLEMENTATION_SUMMARY.md
  • API Documentation: See docs/API_ENHANCEMENTS.md
  • Example Code: See app/routes/projects_refactored_example.py
  • Test Examples: See tests/test_services/ and tests/test_repositories/

Best Practices

  1. Always use services for business logic - Don't put business logic in routes
  2. Use repositories for data access - Don't query models directly in routes
  3. Use schemas for validation - Don't validate manually
  4. Use response helpers - Don't create JSON responses manually
  5. Use constants - Don't use magic strings
  6. Eager load relations - Prevent N+1 queries
  7. Handle errors consistently - Use error response helpers

Happy coding! 🚀