mirror of
https://github.com/DRYTRIX/TimeTracker.git
synced 2026-05-06 20:40:38 -05:00
9d1ece5263
This commit implements a complete architectural transformation of the TimeTracker application, introducing modern design patterns and comprehensive feature set. ## Architecture Improvements ### Service Layer (18 Services) - TimeTrackingService: Time entry management with timer functionality - ProjectService: Project operations and lifecycle management - InvoiceService: Invoice creation, management, and status tracking - TaskService: Task management and workflow - ExpenseService: Expense tracking and categorization - ClientService: Client relationship management - PaymentService: Payment processing and invoice reconciliation - CommentService: Comment system for projects, tasks, and quotes - UserService: User management and role operations - NotificationService: Notification delivery system - ReportingService: Report generation and analytics - AnalyticsService: Event tracking and analytics - ExportService: CSV export functionality - ImportService: CSV import with validation - EmailService: Email operations and invoice delivery - PermissionService: Role-based permission management - BackupService: Database backup operations - HealthService: System health checks and monitoring ### Repository Layer (9 Repositories) - BaseRepository: Generic CRUD operations - TimeEntryRepository: Time entry data access - ProjectRepository: Project data access with filtering - InvoiceRepository: Invoice queries and status management - TaskRepository: Task data access - ExpenseRepository: Expense data access - ClientRepository: Client data access - UserRepository: User data access - PaymentRepository: Payment data access - CommentRepository: Comment data access ### Schema Layer (9 Schemas) - Marshmallow schemas for validation and serialization - Create, update, and full schemas for all entities - Input validation and data transformation ### Utility Modules (15 Utilities) - api_responses: Standardized API response helpers - validation: Input validation utilities - query_optimization: N+1 query prevention and eager loading - error_handlers: Centralized error handling - cache: Caching foundation (Redis-ready) - transactions: Transaction management decorators - event_bus: Domain event system - performance: Performance monitoring decorators - logger: Enhanced structured logging - pagination: Pagination utilities - file_upload: Secure file upload handling - search: Full-text search utilities - rate_limiting: Rate limiting helpers - config_manager: Configuration management - datetime_utils: Enhanced date/time utilities ## Database Improvements - Performance indexes migration (15+ indexes) - Query optimization utilities - N+1 query prevention patterns ## Testing Infrastructure - Comprehensive test fixtures (conftest.py) - Service layer unit tests - Repository layer unit tests - Integration test examples ## CI/CD Pipeline - GitHub Actions workflow - Automated linting (Black, Flake8, Pylint) - Security scanning (Bandit, Safety, Semgrep) - Automated testing with coverage - Docker image builds ## Documentation - Architecture migration guide - Quick start guide - API enhancements documentation - Implementation summaries - Refactored route examples ## Key Benefits - Separation of concerns: Business logic decoupled from routes - Testability: Services and repositories can be tested in isolation - Maintainability: Consistent patterns across codebase - Performance: Database indexes and query optimization - Security: Input validation and security scanning - Scalability: Event-driven architecture and health checks ## Statistics - 70+ new files created - 8,000+ lines of code - 18 services, 9 repositories, 9 schemas - 15 utility modules - 5 test files with examples This transformation establishes a solid foundation for future development and follows industry best practices for maintainable, scalable applications.
163 lines
4.5 KiB
Python
163 lines
4.5 KiB
Python
"""
|
|
Service for user business logic.
|
|
"""
|
|
|
|
from typing import Optional, Dict, Any, List
|
|
from app import db
|
|
from app.repositories import UserRepository
|
|
from app.models import User
|
|
from app.constants import UserRole
|
|
from app.utils.db import safe_commit
|
|
|
|
|
|
class UserService:
|
|
"""Service for user operations"""
|
|
|
|
def __init__(self):
|
|
self.user_repo = UserRepository()
|
|
|
|
def create_user(
|
|
self,
|
|
username: str,
|
|
role: str = UserRole.USER.value,
|
|
email: Optional[str] = None,
|
|
full_name: Optional[str] = None,
|
|
is_active: bool = True,
|
|
created_by: int
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Create a new user.
|
|
|
|
Returns:
|
|
dict with 'success', 'message', and 'user' keys
|
|
"""
|
|
# Check for duplicate username
|
|
existing = self.user_repo.get_by_username(username)
|
|
if existing:
|
|
return {
|
|
'success': False,
|
|
'message': 'Username already exists',
|
|
'error': 'duplicate_username'
|
|
}
|
|
|
|
# Validate role
|
|
valid_roles = [r.value for r in UserRole]
|
|
if role not in valid_roles:
|
|
return {
|
|
'success': False,
|
|
'message': f'Invalid role. Must be one of: {", ".join(valid_roles)}',
|
|
'error': 'invalid_role'
|
|
}
|
|
|
|
# Create user
|
|
user = self.user_repo.create(
|
|
username=username,
|
|
role=role,
|
|
email=email,
|
|
full_name=full_name,
|
|
is_active=is_active
|
|
)
|
|
|
|
if not safe_commit('create_user', {'username': username, 'created_by': created_by}):
|
|
return {
|
|
'success': False,
|
|
'message': 'Could not create user due to a database error',
|
|
'error': 'database_error'
|
|
}
|
|
|
|
return {
|
|
'success': True,
|
|
'message': 'User created successfully',
|
|
'user': user
|
|
}
|
|
|
|
def update_user(
|
|
self,
|
|
user_id: int,
|
|
updated_by: int,
|
|
**kwargs
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Update a user.
|
|
|
|
Returns:
|
|
dict with 'success', 'message', and 'user' keys
|
|
"""
|
|
user = self.user_repo.get_by_id(user_id)
|
|
|
|
if not user:
|
|
return {
|
|
'success': False,
|
|
'message': 'User not found',
|
|
'error': 'not_found'
|
|
}
|
|
|
|
# Validate role if being updated
|
|
if 'role' in kwargs:
|
|
valid_roles = [r.value for r in UserRole]
|
|
if kwargs['role'] not in valid_roles:
|
|
return {
|
|
'success': False,
|
|
'message': f'Invalid role. Must be one of: {", ".join(valid_roles)}',
|
|
'error': 'invalid_role'
|
|
}
|
|
|
|
# Update fields
|
|
self.user_repo.update(user, **kwargs)
|
|
|
|
if not safe_commit('update_user', {'user_id': user_id, 'updated_by': updated_by}):
|
|
return {
|
|
'success': False,
|
|
'message': 'Could not update user due to a database error',
|
|
'error': 'database_error'
|
|
}
|
|
|
|
return {
|
|
'success': True,
|
|
'message': 'User updated successfully',
|
|
'user': user
|
|
}
|
|
|
|
def deactivate_user(
|
|
self,
|
|
user_id: int,
|
|
deactivated_by: int
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Deactivate a user.
|
|
|
|
Returns:
|
|
dict with 'success' and 'message' keys
|
|
"""
|
|
user = self.user_repo.get_by_id(user_id)
|
|
|
|
if not user:
|
|
return {
|
|
'success': False,
|
|
'message': 'User not found',
|
|
'error': 'not_found'
|
|
}
|
|
|
|
user.is_active = False
|
|
|
|
if not safe_commit('deactivate_user', {'user_id': user_id, 'deactivated_by': deactivated_by}):
|
|
return {
|
|
'success': False,
|
|
'message': 'Could not deactivate user due to a database error',
|
|
'error': 'database_error'
|
|
}
|
|
|
|
return {
|
|
'success': True,
|
|
'message': 'User deactivated successfully'
|
|
}
|
|
|
|
def get_active_users(self) -> List[User]:
|
|
"""Get all active users"""
|
|
return self.user_repo.get_active_users()
|
|
|
|
def get_by_role(self, role: str) -> List[User]:
|
|
"""Get users by role"""
|
|
return self.user_repo.get_by_role(role)
|
|
|