mirror of
https://github.com/DRYTRIX/TimeTracker.git
synced 2026-05-07 13:00:22 -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.
123 lines
3.9 KiB
Python
123 lines
3.9 KiB
Python
"""
|
|
Service for payment business logic.
|
|
"""
|
|
|
|
from typing import Optional, Dict, Any, List
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
from app import db
|
|
from app.repositories import PaymentRepository, InvoiceRepository
|
|
from app.models import Payment, Invoice
|
|
from app.utils.db import safe_commit
|
|
from app.utils.event_bus import emit_event
|
|
from app.constants import WebhookEvent
|
|
|
|
|
|
class PaymentService:
|
|
"""Service for payment operations"""
|
|
|
|
def __init__(self):
|
|
self.payment_repo = PaymentRepository()
|
|
self.invoice_repo = InvoiceRepository()
|
|
|
|
def create_payment(
|
|
self,
|
|
invoice_id: int,
|
|
amount: Decimal,
|
|
payment_date: date,
|
|
currency: Optional[str] = None,
|
|
method: Optional[str] = None,
|
|
reference: Optional[str] = None,
|
|
notes: Optional[str] = None,
|
|
status: str = 'completed',
|
|
gateway_transaction_id: Optional[str] = None,
|
|
gateway_fee: Optional[Decimal] = None,
|
|
received_by: int
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Create a new payment.
|
|
|
|
Returns:
|
|
dict with 'success', 'message', and 'payment' keys
|
|
"""
|
|
# Validate invoice
|
|
invoice = self.invoice_repo.get_by_id(invoice_id)
|
|
if not invoice:
|
|
return {
|
|
'success': False,
|
|
'message': 'Invoice not found',
|
|
'error': 'invalid_invoice'
|
|
}
|
|
|
|
# Validate amount
|
|
if amount <= 0:
|
|
return {
|
|
'success': False,
|
|
'message': 'Amount must be greater than zero',
|
|
'error': 'invalid_amount'
|
|
}
|
|
|
|
# Get currency from invoice if not provided
|
|
if not currency:
|
|
currency = invoice.currency_code
|
|
|
|
# Create payment
|
|
payment = self.payment_repo.create(
|
|
invoice_id=invoice_id,
|
|
amount=amount,
|
|
currency=currency,
|
|
payment_date=payment_date,
|
|
method=method,
|
|
reference=reference,
|
|
notes=notes,
|
|
status=status,
|
|
received_by=received_by,
|
|
gateway_transaction_id=gateway_transaction_id,
|
|
gateway_fee=gateway_fee
|
|
)
|
|
|
|
# Calculate net amount
|
|
payment.calculate_net_amount()
|
|
|
|
# Update invoice payment status if payment is completed
|
|
if status == 'completed':
|
|
total_payments = self.payment_repo.get_total_for_invoice(invoice_id)
|
|
invoice.amount_paid = total_payments + amount
|
|
|
|
# Update payment status
|
|
if invoice.amount_paid >= invoice.total_amount:
|
|
invoice.payment_status = 'fully_paid'
|
|
elif invoice.amount_paid > 0:
|
|
invoice.payment_status = 'partially_paid'
|
|
else:
|
|
invoice.payment_status = 'unpaid'
|
|
|
|
if not safe_commit('create_payment', {'invoice_id': invoice_id, 'received_by': received_by}):
|
|
return {
|
|
'success': False,
|
|
'message': 'Could not create payment due to a database error',
|
|
'error': 'database_error'
|
|
}
|
|
|
|
# Emit domain event
|
|
emit_event('payment.created', {
|
|
'payment_id': payment.id,
|
|
'invoice_id': invoice_id,
|
|
'amount': float(amount)
|
|
})
|
|
|
|
return {
|
|
'success': True,
|
|
'message': 'Payment created successfully',
|
|
'payment': payment
|
|
}
|
|
|
|
def get_invoice_payments(self, invoice_id: int) -> List[Payment]:
|
|
"""Get all payments for an invoice"""
|
|
return self.payment_repo.get_by_invoice(invoice_id, include_relations=True)
|
|
|
|
def get_total_paid(self, invoice_id: int) -> Decimal:
|
|
"""Get total amount paid for an invoice"""
|
|
return self.payment_repo.get_total_for_invoice(invoice_id)
|
|
|