# Job Management System — Generated Backend

## Overview

This is a **FastAPI-based backend** for a comprehensive **Job Management System** that enables teams and departments to create, assign, track, and complete jobs with full workflow management, time tracking, checklists, comments, attachments, and reporting capabilities.

**Key Features:**
- **18 database entities** including departments, teams, users, jobs, comments, attachments, time logs, checklists, notifications, and reports
- **Role-based access control** with 4 roles: Administrator, Manager, Team Member, and Viewer
- **7 functional modules**: organization, user management, job configuration, job management, time tracking, checklist, and reporting
- **Comprehensive workflows** for job creation, assignment, status transitions, completion validation, time tracking, and notifications
- **Detailed audit trail** via job history tracking all changes and state transitions
- **Advanced features** including checklist validation before completion, bulk operations, time tracking with active timer limits, and customizable reporting

**System Architecture:**
- SQLAlchemy ORM models with UUID primary keys
- Pydantic schemas for request/response validation
- RESTful API with 40+ endpoints covering CRUD operations and custom workflows
- Business rule enforcement at the API layer
- Eager loading optimizations for detail endpoints

## Requirements

- **Python 3.11+**
- **uv** (fast Python package installer and resolver)
- **PostgreSQL 14+** (for production use)

## Install uv

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or source your shell configuration:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

The project uses `uv` for dependency management. Install all required packages:

```bash
uv sync
```

This will install:
- `fastapi` — Modern web framework for building APIs
- `uvicorn[standard]` — ASGI server
- `sqlalchemy` — ORM and database toolkit
- `pydantic` — Data validation using Python type annotations
- `pydantic-settings` — Settings management
- `asyncpg` — Async PostgreSQL driver (or `psycopg2-binary` for sync)
- `python-multipart` — For file upload support

## Run the Backend

Start the development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The API will be available at:
- **Base URL:** `http://localhost:8000`
- **Interactive API docs (Swagger UI):** `http://localhost:8000/docs`
- **Alternative docs (ReDoc):** `http://localhost:8000/redoc`

**Note:** The backend currently uses in-memory storage. See [Next Steps](#next-steps) for database configuration.

## API Docs

Access the interactive API documentation at `http://localhost:8000/docs` to:
- Browse all available endpoints
- View request/response schemas
- Test API calls directly from the browser
- Download the OpenAPI specification

### Key Endpoint Categories

**Organization Management:**
- `POST /departments` — Create department
- `GET /departments` — List departments
- `POST /teams` — Create team within department
- `GET /teams/{id}/details` — Get team details with members

**User Management:**
- `POST /users` — Create user account
- `GET /users/{id}/details` — Get user profile with department and teams
- `GET /users/{id}/jobs` — Get jobs assigned to user

**Job Configuration:**
- `POST /job-types` — Create job type
- `POST /job-statuses` — Create job status
- `POST /job-priorities` — Create job priority with level and color

**Job Management:**
- `POST /jobs` — Create new job
- `GET /jobs` — List jobs with filters (status, priority, assignee, department, team, date range)
- `GET /jobs/{id}/details` — Get complete job details with all related entities
- `POST /jobs/{id}/assign` — Assign job to user
- `POST /jobs/{id}/reassign` — Reassign job with notifications
- `POST /jobs/{id}/status` — Update job status
- `POST /jobs/{id}/complete` — Mark as completed (validates checklist completion)
- `POST /jobs/{id}/comments` — Add comment to job
- `POST /jobs/{id}/attachments` — Upload file attachment
- `GET /jobs/{id}/history` — View complete audit trail

**Time Tracking:**
- `POST /jobs/{id}/time-logs` — Create time log entry
- `POST /time-logs/{id}/start` — Start timer for job
- `POST /time-logs/{id}/stop` — Stop timer and calculate duration

**Checklist Management:**
- `POST /checklists` — Create checklist for job
- `POST /checklist-items` — Add checklist item
- `POST /checklist-items/{id}/complete` — Mark item as completed

**Notifications:**
- `GET /notifications` — Get user notifications
- `POST /notifications/{id}/read` — Mark notification as read
- `POST /notifications/mark-all-read` — Mark all as read

**Reporting:**
- `GET /reports` — List generated reports
- `POST /reports/generate` — Generate report with parameters (date range, filters, format)

## OpenAPI JSON

Download the complete OpenAPI specification:

```bash
curl http://localhost:8000/openapi.json -o openapi.json
```

Use this specification to:
- Generate client SDKs in multiple languages
- Import into API testing tools (Postman, Insomnia)
- Generate documentation for external consumers
- Validate API contracts

## Project Files

```
.
├── main.py                    # FastAPI application entry point with all routes
├── models.py                  # SQLAlchemy ORM models (18 entities)
├── schemas.py                 # Pydantic request/response schemas
├── database.py                # Database connection and session management
├── auth.py                    # Authentication and authorization logic
├── enums.py                   # Enumerations (UserRole, etc.)
├── pyproject.toml             # Project dependencies and metadata
├── uv.lock                    # Locked dependency versions
└── README.md                  # This file
```

## Example Workflow

### 1. Create a Department

```bash
curl -X POST http://localhost:8000/departments \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Engineering",
    "description": "Software development and infrastructure teams"
  }'
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440001",
  "name": "Engineering",
  "description": "Software development and infrastructure teams",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

### 2. Create a Team

```bash
curl -X POST http://localhost:8000/teams \
  -H "Content-Type: application/json" \
  -d '{
    "department_id": "550e8400-e29b-41d4-a716-446655440001",
    "name": "Backend Team",
    "description": "API and database development"
  }'
```

### 3. Create a User (Manager)

```bash
curl -X POST http://localhost:8000/users \
  -H "Content-Type: application/json" \
  -d '{
    "email": "alice.manager@company.com",
    "password": "SecurePass123!",
    "first_name": "Alice",
    "last_name": "Johnson",
    "role": "manager",
    "department_id": "550e8400-e29b-41d4-a716-446655440001",
    "phone": "+1-555-0123"
  }'
```

### 4. Create Job Configuration Entities

```bash
# Create job type
curl -X POST http://localhost:8000/job-types \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Bug Fix",
    "description": "Fix defects in production code",
    "is_active": true
  }'

# Create job status
curl -X POST http://localhost:8000/job-statuses \
  -H "Content-Type: application/json" \
  -d '{
    "name": "In Progress",
    "description": "Work is actively being done",
    "display_order": 2,
    "is_active": true
  }'

# Create job priority
curl -X POST http://localhost:8000/job-priorities \
  -H "Content-Type: application/json" \
  -d '{
    "name": "High",
    "level": 3,
    "color": "#FF5733",
    "is_active": true
  }'
```

### 5. Create a Job

```bash
curl -X POST http://localhost:8000/jobs \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Fix authentication timeout issue",
    "description": "Users are experiencing session timeouts after 5 minutes instead of the configured 60 minutes",
    "job_type_id": "<job-type-id>",
    "job_status_id": "<job-status-id>",
    "job_priority_id": "<job-priority-id>",
    "created_by_user_id": "<user-id>",
    "department_id": "550e8400-e29b-41d4-a716-446655440001",
    "due_date": "2024-01-20T17:00:00Z",
    "estimated_hours": 4.0
  }'
```

### 6. Assign Job to User

```bash
curl -X POST http://localhost:8000/jobs/{job-id}/assign \
  -H "Content-Type: application/json" \
  -d '{
    "assigned_to_user_id": "<team-member-id>"
  }'
```

### 7. Add a Comment

```bash
curl -X POST http://localhost:8000/jobs/{job-id}/comments \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Started investigating. Found the issue in the session configuration. Will push fix by EOD. @alice.manager please review when ready."
  }'
```

### 8. Start Time Tracking

```bash
curl -X POST http://localhost:8000/time-logs \
  -H "Content-Type: application/json" \
  -d '{
    "job_id": "<job-id>",
    "user_id": "<user-id>",
    "start_time": "2024-01-15T14:00:00Z"
  }'

# Later, stop the timer
curl -X POST http://localhost:8000/time-logs/{time-log-id}/stop \
  -H "Content-Type: application/json"
```

### 9. Create Checklist with Items

```bash
# Create checklist
curl -X POST http://localhost:8000/checklists \
  -H "Content-Type: application/json" \
  -d '{
    "job_id": "<job-id>",
    "title": "Deployment Checklist",
    "description": "Steps before production deployment",
    "display_order": 1
  }'

# Add checklist items
curl -X POST http://localhost:8000/checklist-items \
  -H "Content-Type: application/json" \
  -d '{
    "checklist_id": "<checklist-id>",
    "description": "Run all unit tests",
    "display_order": 1,
    "is_completed": false
  }'

# Mark item complete
curl -X POST http://localhost:8000/checklist-items/{item-id}/complete \
  -H "Content-Type: application/json"
```

### 10. Get Job Details (with all related data)

```bash
curl http://localhost:8000/jobs/{job-id}/details
```

**Response includes:**
- Job type, status, priority details
- Creator and assignee information
- Department and team details
- All comments with user info
- All attachments with uploader info
- Complete history of changes
- All time log entries
- Associated tags
- Checklists with all items and assignees

### 11. Update Job Status

```bash
curl -X POST http://localhost:8000/jobs/{job-id}/status \
  -H "Content-Type: application/json" \
  -d '{
    "job_status_id": "<pending-review-status-id>"
  }'
```

### 12. Complete Job (with validation)

```bash
curl -X POST http://localhost:8000/jobs/{job-id}/complete \
  -H "Content-Type: application/json"
```

This endpoint validates that:
- All checklist items are marked complete
- User has appropriate permissions
- Job is in valid status for completion

### 13. Generate Report

```bash
curl -X POST http://localhost:8000/reports/generate \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Monthly Team Performance",
    "report_type": "team_performance",
    "parameters": {
      "department_id": "550e8400-e29b-41d4-a716-446655440001",
      "start_date": "2024-01-01",
      "end_date": "2024-01-31"
    },
    "generated_by_user_id": "<user-id>",
    "export_format": "PDF"
  }'
```

### 14. Get User Dashboard Data

```bash
curl http://localhost:8000/dashboard?user_id={user-id}
```

Returns:
- Job counts by status
- Overdue jobs
- Jobs due within 24 hours
- Recent activity
- Assigned jobs summary
- Team performance metrics (for managers)

## Next Steps

### 1. **Configure Database Persistence**
Replace in-memory storage with PostgreSQL:
- Update `database.py` with your PostgreSQL connection string
- Run Alembic migrations to create all 18 tables
- Configure connection pooling for production

```python
DATABASE_URL = "postgresql+asyncpg://user:password@localhost:5432/jobmanagement"
```

### 2. **Implement Authentication & Authorization**
- Add JWT token generation and validation in `auth.py`
- Implement password hashing with bcrypt
- Create middleware for role-based access control (Administrator, Manager, Team Member, Viewer)
- Add token refresh mechanism
- Implement permission checks per endpoint based on user roles

### 3. **Refactor into Modular Structure**
Split `main.py` into organized modules:

```
app/
├── routers/
│   ├── departments.py
│   ├── teams.py
│   ├── users.py
│   ├── jobs.py
│   ├── time_tracking.py
│   ├── checklists.py
│   ├── notifications.py
│   └── reports.py
├── services/
│   ├── job_service.py       # Business logic for job workflows
│   ├── auth_service.py       # Authentication logic
│   ├── notification_service.py
│   └── report_service.py
├── models/
│   ├── organization.py       # Department, Team
│   ├── user.py
│   ├── job.py
│   └── ...
├── schemas/
│   ├── job_schemas.py
│   ├── user_schemas.py
│   └── ...
└── core/
    ├── config.py             # Settings and environment variables
    ├── security.py           # Password hashing, JWT utilities
    └── dependencies.py       # FastAPI dependencies
```

### 4. **Add Comprehensive Tests**
Create test suite covering:
- **Unit tests** for business logic and validation rules
- **Integration tests** for API endpoints
- **Test database fixtures** with SQLAlchemy
- **Authentication tests** for role-based access
- **Workflow tests** for job lifecycle, assignment, completion validation
- **Edge case tests** for checklist validation, time tracking limits, concurrent updates

```bash
# Install pytest
uv add --dev pytest pytest-asyncio httpx

# Run tests
uv run pytest
```

### 5. **Implement File Storage**
- Configure cloud storage (AWS S3, Azure Blob, GCS) for attachments
- Add file type validation and virus scanning
- Implement file size limits per upload and per job (10MB per file, 50MB total)
- Generate presigned URLs for secure file downloads

### 6. **Add Real-time Features**
- Implement WebSocket support for live notifications
- Add real-time job status updates
- Enable live collaboration features (who's viewing, typing indicators in comments)

### 7. **Enhance Reporting**
- Implement asynchronous report generation for large datasets
- Add scheduled reports with email delivery
- Create custom report builder with drag-and-drop interface
- Add data visualization (charts, graphs) in reports

### 8. **Add Background Tasks**
- Use Celery or FastAPI BackgroundTasks for:
  - Sending notification emails
  - Generating large reports
  - Cleanup of old attachments
  - SLA breach checking
  - Automated job status reminders

### 9. **Production Readiness**
- Add comprehensive logging with structured output
- Implement error tracking (Sentry, Rollbar)
- Add health check endpoints (`/health`, `/ready`)
- Configure CORS for frontend integration
- Set up rate limiting and request throttling
- Add database query optimization with indexes
- Implement caching strategy (Redis) for frequently accessed data
- Configure monitoring and alerting

### 10. **Documentation & Deployment**
- Add inline code documentation
- Create developer onboarding guide
- Document all business rules and validation logic
- Set up CI/CD pipeline (GitHub Actions, GitLab CI)
- Create Docker containers for deployment
- Write deployment documentation for various environments

---

**Generated Backend Ready!** Start the server with `uv run uvicorn main:app --reload` and visit `http://localhost:8000/docs` to explore the API.
