feat: added designated area
Merge Request: Designated Area Implementation (Backend)
Overview
Implements the backend foundation for the "Designated Area/Stations" feature within the FastAPI application. This MR introduces the necessary database models, API routes, enums, and schemas to manage, track, and aggregate real-time volunteer station deployments during medical camps.
What does this MR do and why?
- Enable Workstation Deployments: Added the ability to track which specific workstation (e.g., registration, vitals, pharmacy) a volunteer is actively assigned to in real-time.
-
Operational Analytics: Added statistical endpoints (
/stats) allowing coordinators and administrators to view load distribution across all active workstations to optimize volunteer placement. -
Code Cleanup & Quality Check: Removed redundant legacy utility scripts that cluttered the codebase, enforced formatting using
ruff, and ensured proper test coverage on the new APIs.
Changes Made
-
Models: Introduced
VolunteerWorkstationAssignment(or equivalent) database model using SQLAlchemy to track current deployments. -
Enums: Defined
CampAreaEnumoutlining the standardized camp locations (e.g.,registration,vitals,consultation,pharmacy,counseling). -
Services: Created new service logic (
area_service.py/station_service.py) to handle business logic for deployments and aggregating stats independently of the routing layer. -
API Endpoints Added:
-
POST /api/v1/areas/assign- Assigns a volunteer to a specified area. -
GET /api/v1/areas/stats- Returns aggregated population metrics per workstation. -
GET /api/v1/areas/volunteer/{user_id}- Fetches the currently assigned area for a user.
-
-
Schemas: Added Pydantic data validation schemas (e.g.,
AreaAssignRequest,AreaStatResponse). -
Tests: Wrote comprehensive testing coverage in
tests/api/test_areas.pyusingpytest. - Refactor: Cleaned up and removed obsolete utility scripts per the tech debt guidelines.
Technical Details
-
Database Schema Changes: Auto-generated an Alembic migration script to construct the new assignments table with proper foreign keys mapping to the core
usersandcampstables. - Architecture Decisions: The assignment logic was built as a historical log/junction pattern. This way, we not only track where a volunteer is, but can easily query where they have been during a shift.
-
Performance consideration: The
/statsendpoint uses aggregate counting operations at the database level (func.count) rather than loading and counting rows in Python, ensuring efficient N+1-free queries.
Type of Change
-
🐛 Bug fix (non-breaking change that fixes an issue) -
✨ New feature (non-breaking change that adds functionality) -
💥 Breaking change (fix or feature that would cause existing functionality to change) -
📝 Documentation update -
♻ ️ Refactor (no functional changes) -
⚡ Performance improvement -
🧪 Test update -
🔧 Configuration change -
🚨 Security fix -
🗑 ️ Deprecation (removing deprecated code)
Related Issues / References
closes #110 (closed)
Screenshots or Screen Recordings
N/A - Backend API logic only
How to Validate Locally
- Pull down branch
feat/designated-areato your local environment. - Run database migrations:
alembic upgrade head - Start the FastAPI development server:
uvicorn app.main:app --reload - Access the auto-generated Swagger UI:
http://localhost:8000/docs. - Execute
POST /api/v1/areas/assignproviding a validuser_idandarea. - Execute
GET /api/v1/areas/statsand confirm that the assigned volunteer correctly reflects in the corresponding area's distribution count.
Testing Done
-
Unit tests added/updated -
API endpoint tests passing
Test Cases Covered:
| Scenario | Expected Result | Status |
|---|---|---|
| Admin assigns a volunteer | 200 OK, Assignment successfully recorded | |
| Admin fetches area stats | 200 OK, Returns aggregated metrics reflecting assignment | |
| Attempt assign non-existent user | 404 Not Found | |
| Attempt assign to invalid area | 422 Unprocessable Entity |
Test Commands Run:
# Example: Run all tests
pytest tests/api/test_areas.py -v
# Example: Run lint checks
ruff check .
ruff format . --check
Code Quality Checklist
Code Standards
-
Code follows project conventions (naming, structure, formatting) -
No debug statements or commented-out code left (unless necessary and intended) -
No unused imports, variables, or functions -
No duplicate code (DRY principle followed) -
Type hints are properly defined (no Anyunless justified and no mypy type check errors) -
Ruff checks pass
Python & FastAPI Best Practices
-
Functions follow single-responsibility principle -
Async/await used correctly (no blocking calls in async functions) -
Dependency injection used appropriately -
Pydantic models used for request/response validation -
SQLAlchemy queries are optimized (no N+1 queries) -
Error handling is comprehensive (try/except with proper logging)
API Design
-
RESTful conventions followed -
Proper HTTP status codes returned -
Input validation implemented -
Authentication/authorization enforced -
Role Base access control used for user restriction -
API documentation (docstrings) updated
Database & Migrations
-
Database migrations created (if schema changed) -
Database migrations version is pointing to the latest version (and version name follows project conventions) -
Migrations are reversible (migrations contain downgrade scripts) -
Indexes added for frequently queried fields -
No raw SQL queries (using SQLAlchemy ORM) -
Data integrity constraints maintained
Security
-
No sensitive data logged (passwords, tokens, PII) -
SQL injection prevention verified (ORM used) -
Input sanitization implemented -
Authentication tokens handled securely -
CORS settings appropriate
Error Handling
-
Errors are caught and handled gracefully -
User-friendly error messages returned -
Errors are logged appropriately -
HTTP error responses follow API standards
Documentation
-
README.md updated (if setup steps changed) -
.env.exampleupdated (if new env vars added) -
API documentation updated (docstrings, OpenAPI specs) -
CHANGELOG.md will be updated (if applicable) -
Code comments explain complex logic (not what, but why)
Known Limitations / Technical Debt
None
Additional Notes
Ensure this gets merged alongside the frontend MR counterpart that introduces the UI dashboards mapping to these endpoints.
MR Acceptance Checklist
Quality & Correctness
-
Code works as intended and solves the stated problem -
No bugs introduced (existing functionality not broken) -
Edge cases handled appropriately
Maintainability
-
Code is readable and well-organized -
Code is testable and well-tested -
Follows project patterns and conventions
Acceptance Review
-
Reviewed by at least 1 teammate -
Reviewed by product owner
Edited by Vandana reddy Balannagari