3.0 KiB
3.0 KiB
SPEC: Refactor Alert CRUD to Service Layer
Goal
Refactor the src/backend/routers/alerts.py file to move business logic and data access into a dedicated src/backend/services/alert_service.py file. This aligns the alerting module with the existing service-oriented architecture used in the rest of the project (e.g., SentimentService, RotationService).
Exact Requirements
- Create
src/backend/services/alert_service.py:- Implement an
AlertServiceclass containing methods for all current alert operations. - Methods required:
get_user_alerts(watchlist_id, status, page, page_size, user_id)create_alert(body, user_id)get_alert(alert_id, user_id)update_alert(alert_id, body, user_id)resolve_alert(alert_id, user_id)dismiss_alert(alert_id, user_id)
- Implement an
- Encapsulate Authorization:
- Move the ownership verification logic (
_require_watchlist_owner) into the service layer or a shared security service.
- Move the ownership verification logic (
- Encapsulate Data Access & Transformation:
- Move all
execute_query,execute_one, andexecute_commandcalls into theAlertService. - Handle the mapping of database rows to
AlertResponseandAlertListResponsemodels within the service.
- Move all
- Update
src/backend/routers/alerts.py:- Remove direct database calls and business logic.
- Inject/instantiate
AlertServiceand delegate all requests to it. - Maintain the existing FastAPI route definitions and dependency injection (e.g.,
get_current_user).
- Maintain Feature Parity:
- The API behavior (endpoints, status codes, response models) must remain identical to the current implementation.
Acceptance Criteria
- Code Structure:
src/backend/routers/alerts.pycontains only routing and request/response handling. - Service Implementation:
src/backend/services/alert_service.pyis the single source of truth for alert business logic. - Test Pass Rate: All tests in
src/backend/tests/test_alerts.pymust pass (including the previously failing tests). - No Regressions: All CRUD operations (Create, Read, Update, Delete, Resolve, Dismiss) must function exactly as before.
Constraints & Non-Goals
- Non-Goal: Do not change the database schema.
- Non-Goal: Do not change the external API contract (URLs, JSON structure, status codes).
- Constraint: Maintain existing error handling patterns (e.g., 404 for missing resources, 403/404 for ownership issues).
Recommended Implementation Approach
- Phase 1: Service Creation: Implement the
AlertServiceinsrc/backend/services/alert_service.pyby copying logic from the router, but parameterizing it for the service methods. - Phase 2: Router Migration: Replace the body of each router function with a call to the corresponding
AlertServicemethod. - Phase 3: Cleanup: Remove the old
_require_watchlist_ownerhelper from the router. - Phase 4: Verification: Run the existing test suite.