Files
TimeTracker/app/utils/event_bus.py
T
Dries Peeters 1836cb3c2d chore(typing): resolve mypy errors and harden type checking
Drives ``mypy app/`` from 567 errors in 208 files to 0 errors across the
376 source files checked by ``./scripts/run-ci-local.sh code-quality``.

Configuration & dependencies
- pyproject.toml: enable implicit_optional (Flask-style ``x: str = None``
  defaults), silence truthy-function/truthy-bool (legitimate import-guard
  checks like ``KanbanColumn``), and disable warn_return_any (SQLAlchemy
  1.x ``Query`` API returns Any pervasively). Add module overrides for
  ``app.models.*``, repositories, base CRUD service, and known
  ``joinedload`` / ``Query.paginate`` callers where mypy cannot model the
  Flask-SQLAlchemy runtime API without a plugin.
- requirements-test.txt: pin ``types-requests``, ``types-bleach``,
  ``types-Markdown``, ``types-python-dateutil`` so mypy stops complaining
  about missing stubs.

Latent bugs fixed while driving mypy to zero
- app/utils/logger.py, app/utils/datetime_utils.py: drop imports of
  symbols that don't exist (``get_performance_metrics``,
  ``from_app_timezone``, ``to_app_timezone``) — these would have raised
  at import time on first use.
- app/services/currency_service.py: ``from typing import Decimal`` was a
  bug (typing has no Decimal); switch to ``decimal.Decimal`` and rename
  the ``D`` alias.
- app/utils/env_validation.py, app/utils/role_migration.py: ``Dict[str,
  any]`` → ``Dict[str, Any]`` (built-in ``any`` is not a type).
- app/utils/email.py: introduce ``send_template_email`` and update the
  three callers (``client_approval_service``,
  ``client_notification_service``, ``workflow_engine``) that were
  passing ``to=``/``template=``/etc. to ``send_email`` whose signature
  doesn't accept them — calls would have raised TypeError at runtime.
- app/services/permission_service.py: rewrite ``grant_permission`` /
  ``revoke_permission`` to use the actual ``Role`` ↔ ``Permission``
  many-to-many relationship; the old code referenced non-existent
  ``Permission.role_id`` / ``Permission.granted`` columns.
- app/services/gps_tracking_service.py: pass the required ``title`` and
  ``expense_date`` fields when creating mileage ``Expense`` rows.
- app/services/workflow_engine.py: ``_perform_action`` now forwards the
  ``rule`` argument to ``_action_log_time``, and ``_action_webhook``
  short-circuits when ``url`` is missing.
- app/services/time_tracking_service.py: validate ``start_time`` /
  ``end_time`` before comparing them.
- app/services/export_service.py: build CSV in a ``StringIO`` then wrap
  the bytes in ``BytesIO`` — ``csv.writer`` requires text I/O.
- app/integrations/peppol_smp.py: avoid attribute access on ``None`` in
  the SMP ``href`` fallback.
- app/integrations/{github,gitlab,slack}.py: coerce query-string params
  to strings so ``requests.get(params=...)`` matches the typed signature
  (and is what the HTTP layer expects anyway).
- app/integrations/{xero,quickbooks}.py: guard ``get_access_token()``
  returning ``None`` before calling private ``_api_request`` helpers.

Annotation-only changes
- Add ``Dict[str, Any]`` / ``list`` / ``Optional[...]`` annotations to
  service dict-literals that mypy could not infer from heterogeneous
  values (``ai_suggestion_service``, ``ai_categorization_service``,
  ``custom_report_service``, ``unpaid_hours_service``,
  ``integration_service``, ``invoice_service``, ``backup_service``,
  ``inventory_report_service``, ``analytics_service``, etc.).
- ``app/utils/event_bus.py``: ``emit_event`` accepts ``str |
  WebhookEvent`` and normalizes to ``str`` so all call-sites type-check.
- ``app/utils/api_responses.py``: introduce ``ApiResponse`` alias for
  ``Response | tuple[Response, int] | tuple[str, int]``.
- ``app/utils/budget_forecasting.py``: forecasting helpers return
  ``Optional[Dict]`` (they already returned ``None`` when the project
  was missing).
- ``app/utils/pdf_generator_reportlab.py``: ``_normalize_color`` is
  ``Optional[str]``.
- ``app/utils/pdfa3.py``: remove invalid ``force_version=None`` retry
  call.
- Narrow ``type: ignore`` markers on optional-dependency fallbacks
  (``redis``, ``bleach``, ``markdown``, ``babel``,
  ``powerpoint_export``) and on the documented ``requests.Session``
  / ``RotatingFileHandler`` typeshed limitations.
2026-05-13 10:32:06 +02:00

138 lines
4.0 KiB
Python

"""
Event bus for domain events.
Provides decoupled event-driven architecture.
"""
from functools import wraps
from typing import Any, Callable, Dict, List, Union
from flask import current_app
from app.constants import WebhookEvent
EventType = Union[str, WebhookEvent]
def _coerce_event_type(event_type: EventType) -> str:
"""Normalize an event type passed as ``str`` or ``WebhookEvent`` to ``str``."""
if isinstance(event_type, WebhookEvent):
return event_type.value
return event_type
class EventBus:
"""Simple event bus for domain events"""
def __init__(self):
self._handlers: Dict[str, List[Callable]] = {}
def subscribe(self, event_type: str, handler: Callable) -> None:
"""
Subscribe a handler to an event type.
Args:
event_type: Event type (e.g., 'time_entry.created')
handler: Function to call when event is emitted
"""
if event_type not in self._handlers:
self._handlers[event_type] = []
self._handlers[event_type].append(handler)
def unsubscribe(self, event_type: str, handler: Callable) -> None:
"""Unsubscribe a handler from an event type"""
if event_type in self._handlers:
try:
self._handlers[event_type].remove(handler)
except ValueError:
pass
def emit(self, event_type: str, data: Dict[str, Any]) -> None:
"""
Emit an event to all subscribed handlers.
Args:
event_type: Event type
data: Event data
"""
handlers = self._handlers.get(event_type, [])
for handler in handlers:
try:
handler(event_type, data)
except Exception as e:
current_app.logger.error(f"Error in event handler for {event_type}: {e}", exc_info=True)
def clear(self) -> None:
"""Clear all event handlers"""
self._handlers.clear()
# Global event bus instance
_event_bus = EventBus()
def get_event_bus() -> EventBus:
"""Get the global event bus instance"""
return _event_bus
def emit_event(event_type: EventType, data: Dict[str, Any]) -> None:
"""
Emit an event using the global event bus.
Args:
event_type: Event type (``str`` or ``WebhookEvent``)
data: Event data
"""
_event_bus.emit(_coerce_event_type(event_type), data)
def subscribe_to_event(event_type: str):
"""
Decorator to subscribe a function to an event type.
Usage:
@subscribe_to_event('time_entry.created')
def handle_time_entry_created(event_type, data):
# Handle event
"""
def decorator(func: Callable) -> Callable:
_event_bus.subscribe(event_type, func)
return func
return decorator
# Example event handlers
@subscribe_to_event(WebhookEvent.TIME_ENTRY_CREATED.value)
def handle_time_entry_created(event_type: str, data: Dict[str, Any]) -> None:
"""Handle time entry created event"""
try:
from app.utils.webhook_dispatcher import dispatch_webhook
dispatch_webhook(event_type, data)
except Exception as e:
current_app.logger.error(f"Failed to dispatch webhook for {event_type}: {e}")
@subscribe_to_event(WebhookEvent.PROJECT_CREATED.value)
def handle_project_created(event_type: str, data: Dict[str, Any]) -> None:
"""Handle project created event"""
try:
from app.utils.webhook_dispatcher import dispatch_webhook
dispatch_webhook(event_type, data)
except Exception as e:
current_app.logger.error(f"Failed to dispatch webhook for {event_type}: {e}")
@subscribe_to_event(WebhookEvent.INVOICE_CREATED.value)
def handle_invoice_created(event_type: str, data: Dict[str, Any]) -> None:
"""Handle invoice created event"""
try:
from app.utils.webhook_dispatcher import dispatch_webhook
dispatch_webhook(event_type, data)
except Exception as e:
current_app.logger.error(f"Failed to dispatch webhook for {event_type}: {e}")