Files
TimeTracker/pyproject.toml
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

112 lines
3.5 KiB
TOML

[tool.black]
line-length = 120
[tool.isort]
profile = "black"
line_length = 120
skip = [".eggs", ".git", ".hg", ".mypy_cache", ".tox", ".venv", "venv", "_build", "buck-out", "build", "dist", "migrations"]
[tool.pylint.messages_control]
disable = [
"C0111", # missing-docstring
"C0103", # invalid-name
"R0903", # too-few-public-methods
"R0913", # too-many-arguments
]
[tool.pylint.format]
max-line-length = 120
[tool.bandit]
exclude_dirs = ["tests", "migrations", "venv", ".venv"]
skips = ["B101"] # Skip assert_used test
[tool.coverage.run]
source = ["app"]
omit = [
"*/tests/*",
"*/test_*.py",
"*/__pycache__/*",
"*/venv/*",
"*/env/*",
"*/migrations/*",
"app/utils/pdf_generator.py",
"app/utils/pdf_generator_fallback.py",
]
[tool.coverage.report]
precision = 2
show_missing = true
skip_covered = false
exclude_lines = [
"pragma: no cover",
"def __repr__",
"raise AssertionError",
"raise NotImplementedError",
"if __name__ == .__main__.:",
"if TYPE_CHECKING:",
"@abstractmethod",
]
[tool.mypy]
python_version = "3.11"
# warn_return_any is intentionally OFF: SQLAlchemy 1.x-style ``Model.query`` and
# ``.first()`` / ``.all()`` return ``Any``, so wrapping them in a typed return
# yields hundreds of false positives until/unless the codebase migrates to
# SQLAlchemy 2.x ``Mapped[X]`` annotations.
warn_return_any = false
warn_unused_configs = true
disallow_untyped_defs = false
ignore_missing_imports = true
# Restore pre-mypy-0.991 implicit Optional so ``def foo(x: str = None)`` is not
# flagged. The codebase uses this Flask-style idiom in many places.
implicit_optional = true
disable_error_code = [
# ``if SomeClass:`` truthy-class checks are used as import-guards across
# routes/services; their meaning is intentional.
"truthy-function",
"truthy-bool",
]
exclude = [
"migrations/",
"tests/",
"venv/",
".venv/",
]
# Flask-SQLAlchemy models defined as ``class Foo(db.Model)`` are not understood
# by mypy without a dedicated plugin. Skip them rather than chase ~150 false
# positives of "Name 'db.Model' is not defined".
[[tool.mypy.overrides]]
module = "app.models.*"
ignore_errors = true
# Repositories use ``TypeVar("ModelType")`` which mypy cannot bind to the
# Flask-SQLAlchemy ``.query`` / ``joinedload(rel)`` runtime API. The patterns
# are correct at runtime; suppress the documented limitation.
[[tool.mypy.overrides]]
module = "app.repositories.*"
disable_error_code = ["arg-type", "attr-defined"]
# Generic base service uses ``RepositoryType`` TypeVar; same limitation as
# repositories — methods exist at runtime via the bound class.
[[tool.mypy.overrides]]
module = "app.services.base_crud_service"
disable_error_code = ["attr-defined"]
# ``Query.paginate`` is added by Flask-SQLAlchemy and is missing from the
# SQLAlchemy stubs. Suppress this single attr-defined case in helpers that
# wrap pagination.
[[tool.mypy.overrides]]
module = ["app.utils.pagination", "app.services.project_service"]
disable_error_code = ["attr-defined"]
# SQLAlchemy joinedload(rel) accepts ``RelationshipProperty`` at runtime but
# is typed as ``QueryableAttribute``. This pattern is used pervasively in
# services and is correct.
[[tool.mypy.overrides]]
module = ["app.services.task_service", "app.services.quote_service", "app.services.invoice_service", "app.services.expense_service", "app.services.scheduled_report_service"]
disable_error_code = ["arg-type"]
# Pytest config is in pytest.ini (single source of truth to avoid duplicate config warning)