feat(frontend+backend): connect api backend with frontend

This commit is contained in:
2025-08-30 21:54:36 -04:00
parent 6063ed62e0
commit 133efdddea
21 changed files with 1202 additions and 91 deletions

306
CLAUDE.md
View File

@@ -2,145 +2,295 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Architecture
## Project Overview
NimbusFlow is a scheduling system with a **monorepo structure** containing separate backend and frontend applications:
NimbusFlow is a comprehensive scheduling system with a **monorepo structure** containing separate backend and frontend applications designed for church music ministry scheduling. The system handles round-robin member scheduling with sophisticated algorithms for fair distribution and availability management.
- **Backend**: Python-based scheduling service using SQLite with a repository pattern
- **Frontend**: .NET Blazor Server application with Bootstrap UI
### Architecture Overview
### Backend Architecture
- **Backend**: Python-based scheduling service with FastAPI REST API, SQLite database, and comprehensive CLI
- **Frontend**: .NET 8 Blazor Server application with Bootstrap UI for web-based management
## Backend Architecture
The backend follows a **layered architecture** with clear separation of concerns:
```
backend/
├── db/ # Database connection layer
├── models/ # Data models and enums
├── repositories/ # Data access layer
├── services/ # Business logic layer
── tests/ # Test suite
├── api/ # FastAPI REST API server
├── cli/ # Command-line interface
├── db/ # Database connection layer
├── models/ # Data models and enums
── repositories/ # Data access layer (Repository pattern)
├── services/ # Business logic layer
├── tests/ # Comprehensive test suite
├── utils/ # Utility functions
├── requirements.txt # Python dependencies
└── schema.sql # Database schema
```
**Key Components:**
### Key Components
- **DatabaseConnection** (`db/connection.py`): SQLite wrapper with context manager support
- **Repository Pattern**: Each domain entity has its own repository (Member, Service, Classification, etc.)
- **SchedulingService** (`services/scheduling_service.py`): Core business logic for round-robin scheduling with boost/cooldown algorithms
- **Data Models** (`models/dataclasses.py`): Dataclasses with SQLite row conversion utilities
#### API Layer (`api/`)
- **app.py**: FastAPI application with comprehensive REST endpoints
- **__main__.py**: Uvicorn server entry point with auto-reload
- Supports CORS for frontend communication on `localhost:5000/5001`
- Pydantic models for request/response validation with C# naming convention compatibility
**Database Schema** (`schema.sql`): SQLite-based with tables for Members, Services, Classifications, Schedules, and audit logging. Uses foreign key constraints and indexes for performance.
#### CLI Layer (`cli/`)
- **main.py**: Command-line interface coordinator with subcommands
- **interactive.py**: Interactive mode for user-friendly operations
- **commands/**: Modular command implementations (members, schedules, services)
- **base.py**: Base CLI class with common functionality
### Frontend Architecture
#### Database Layer (`db/`)
- **connection.py**: SQLite wrapper with context manager support
- **base_repository.py**: Abstract base repository with common CRUD operations
- Thread-safe connection handling for FastAPI
#### Repository Pattern (`repositories/`)
- **MemberRepository** (`member.py`): Member CRUD operations
- **ScheduleRepository** (`schedule.py`): Schedule management with status updates
- **ServiceRepository** (`service.py`): Service instance management
- **ClassificationRepository** (`classification.py`): Member role management
- **ServiceTypeRepository** (`service_type.py`): Time slot definitions
- **ServiceAvailabilityRepository** (`service_availability.py`): Member eligibility
#### Business Logic (`services/`)
- **SchedulingService** (`scheduling_service.py`): Core scheduling algorithms
- Round-robin scheduling based on `LastAcceptedAt` timestamps
- 5-day decline boost for recently declined members
- Same-day exclusion rules
- Multi-classification support
- Status-aware scheduling (pending/accepted/declined)
#### Data Models (`models/`)
- **dataclasses.py**: Core data models with SQLite row conversion utilities
- **enums.py**: Enumerated types for system constants
- Models: Member, Service, Schedule, Classification, ServiceType, etc.
### Database Schema (`schema.sql`)
SQLite-based with comprehensive relational design:
**Core Tables:**
- `Members`: Member information with scheduling timestamps
- `Services`: Service instances with dates and types
- `Schedules`: Member-service assignments with status tracking
- `Classifications`: Member roles (Soprano, Alto, Tenor, Baritone)
- `ServiceTypes`: Time slots (9AM, 11AM, 6PM)
- `ServiceAvailability`: Member eligibility for service types
**Audit Tables:**
- `AcceptedLog`, `DeclineLog`, `ScheduledLog` for comprehensive tracking
- Foreign key constraints and indexes for performance
## Frontend Architecture
.NET 8 Blazor Server application with the following structure:
```
frontend/
├── Components/
│ ├── Layout/ # Layout components (NavMenu, MainLayout)
── Pages/ # Razor pages (Dashboard, Members, Schedules, Services)
├── Models/ # C# models matching backend data structure
│ ├── Layout/ # Layout components (NavMenu, MainLayout)
── Pages/ # Razor pages (Members, Schedules, Services)
│ ├── App.razor # Root application component
│ └── _Imports.razor # Global imports
├── Models/ # C# models matching backend structure
├── Services/ # HTTP client services for API communication
── wwwroot/ # Static files and assets
── Properties/ # Launch settings and configuration
├── wwwroot/ # Static files and assets
└── Program.cs # Application startup and DI configuration
```
**Key Components:**
### Key Components
- **ApiService** (`Services/ApiService.cs`): HTTP client wrapper for Python backend API communication
- **Models** (`Models/Member.cs`): C# data models (Member, Schedule, Service, Classification, etc.)
- **Razor Components**: Interactive pages for member management, scheduling, and service administration
- **Bootstrap UI**: Responsive design with Bootstrap 5 styling
#### Services Layer
- **ApiService.cs**: HTTP client implementation with JSON serialization
- **IApiService.cs**: Service interface for dependency injection
- Configured for `http://localhost:8000/api/` backend communication
- Camel case JSON handling for API compatibility
The frontend communicates with the Python backend via HTTP API calls, expecting JSON responses that match the C# model structure.
#### Models (`Models/`)
- **Member.cs**: Complete data models matching backend structure
- Models: Member, Classification, Service, ServiceType, Schedule
- Navigation properties for related data
- Compatible with FastAPI Pydantic models
#### Razor Components (`Components/Pages/`)
- **Members.razor**: Member management interface
- **Schedules.razor**: Schedule management and workflow
- **Services.razor**: Service administration
- **Home.razor**: Dashboard and overview
- Bootstrap 5 styling with responsive design
#### Dependency Injection (`Program.cs`)
- HTTP client configuration for backend API
- Service registration with scoped lifetime
- HTTPS redirection and static file serving
## Development Commands
### Backend
### Backend Development
**Setup:**
**Environment Setup:**
```bash
cd backend
# Activate virtual environment (already exists)
source venv/bin/activate
# Virtual environment is pre-configured in .venv/
source .venv/bin/activate
```
**Dependencies:**
```bash
# Install from requirements.txt
pip install -r requirements.txt
```
**API Server:**
```bash
cd backend
source .venv/bin/activate
python -m api
# Starts FastAPI server on http://localhost:8000
# API documentation at http://localhost:8000/docs
```
**CLI Usage:**
```bash
cd backend
source .venv/bin/activate
python -m cli --help
python -m cli members list
python -m cli schedules schedule --help
```
**Demo/Development Data:**
```bash
cd backend
source .venv/bin/activate
python main.py # Runs demo data population
```
**Testing:**
```bash
cd backend
# Run tests using pytest from virtual environment
venv/bin/pytest
# Run specific test file
venv/bin/pytest tests/repositories/test_member.py
# Run with coverage
venv/bin/pytest --cov
source .venv/bin/activate
pytest # Run all tests
pytest tests/repositories/ # Run repository tests
pytest --cov # Run with coverage
```
**Run Application:**
```bash
cd backend
# Run the demo script
python main.py
```
### Frontend
### Frontend Development
**Setup:**
```bash
cd frontend
# Restore NuGet packages
dotnet restore
```
**Development:**
**Development Server:**
```bash
cd frontend
# Start development server (with hot reload)
dotnet watch
# Or run without watch
dotnet run
dotnet watch # Hot reload development
# Or: dotnet run
```
# Build for production
dotnet build
# Publish for deployment
dotnet publish -c Release
**Build & Deploy:**
```bash
cd frontend
dotnet build # Development build
dotnet build -c Release # Production build
dotnet publish -c Release # Publish for deployment
```
**Access:**
- Development: https://localhost:5001 (HTTPS) or http://localhost:5000 (HTTP)
- The application expects the Python backend API to be available at http://localhost:8000/api/
- Expects backend API at http://localhost:8000/api/
## Core Business Logic
The **SchedulingService** implements a sophisticated member scheduling algorithm:
### Scheduling Algorithm
1. **Round-robin scheduling** based on `Members.LastAcceptedAt` timestamps
2. **5-day decline boost** - recently declined members get priority
3. **Same-day exclusion** - members can't be scheduled for multiple services on the same day
4. **Service availability** - members must be eligible for the specific service type
5. **Status constraints** - prevents double-booking (pending/accepted/declined statuses)
The **SchedulingService** implements sophisticated member scheduling:
1. **Round-robin fairness**: Based on `LastAcceptedAt` timestamps
2. **Decline boost**: 5-day priority for recently declined members
3. **Same-day exclusion**: Members cannot serve multiple services per day
4. **Classification matching**: Multi-classification support for flexible roles
5. **Availability filtering**: Service type eligibility checking
6. **Status management**: Prevents double-booking across pending/accepted states
**Key Methods:**
- `schedule_next_member()` - Core scheduling logic with multi-classification support
- `decline_service_for_user()` - Handle member declining assignments
- `schedule_next_member(classification_ids, service_id)`: Core scheduling with multi-role support
- `decline_service_for_user(member_id, service_id, reason)`: Decline handling with boost logic
## Database
### API Endpoints
The system uses **SQLite** with the following key tables:
- `Members` - Core member data with scheduling timestamps
- `Services` - Service instances on specific dates
- `Schedules` - Member-service assignments with status tracking
- `Classifications` - Member roles (Soprano, Alto, Tenor, Baritone)
- `ServiceTypes` - Time slots (9AM, 11AM, 6PM)
- `ServiceAvailability` - Member eligibility for service types
**Member Management:**
- `GET /api/members` - List all members
- `GET /api/members/{id}` - Get member details
- `POST /api/members` - Create new member
- `PUT /api/members/{id}` - Update member
- `DELETE /api/members/{id}` - Delete member
**Audit Tables**: `AcceptedLog`, `DeclineLog`, `ScheduledLog` for comprehensive tracking.
**Scheduling Operations:**
- `GET /api/schedules` - List all schedules
- `POST /api/schedules/schedule-next` - Schedule next available member
- `POST /api/schedules/{id}/accept` - Accept assignment
- `POST /api/schedules/{id}/decline` - Decline with reason
- `DELETE /api/schedules/{id}` - Remove schedule
**Service Management:**
- `GET /api/services` - List services
- `POST /api/services` - Create new service
- `GET /api/service-types` - List service types
## Database Management
**Schema Location:** `backend/schema.sql`
**Database File:** `backend/db/sqlite/database.db` (auto-created)
**Key Features:**
- Automatic database creation from schema if missing
- Foreign key constraints enforced
- Comprehensive indexing for performance
- Audit logging for all schedule operations
## Testing
Backend uses **pytest** with fixtures for database setup. Tests cover:
- Repository layer functionality
- Business logic in services
- Database schema constraints
**Backend Testing with pytest:**
- Repository layer unit tests with in-memory SQLite
- Service layer business logic tests
- Fixtures for database setup and test data
- Comprehensive coverage of scheduling algorithms
All tests use in-memory SQLite databases created fresh for each test.
**Test Structure:**
```
tests/
├── conftest.py # Shared fixtures
├── repositories/ # Repository layer tests
└── services/ # Business logic tests
```
## Development Workflow
1. **Backend First**: Start with API development and testing
2. **Database Schema**: Modify `schema.sql` for data model changes
3. **Repository Layer**: Update repositories for new database operations
4. **Service Layer**: Implement business logic in services
5. **API Layer**: Add FastAPI endpoints with Pydantic models
6. **Frontend Models**: Update C# models to match API
7. **Frontend Services**: Extend ApiService for new endpoints
8. **Frontend UI**: Create/update Razor components
9. **Testing**: Add tests for new functionality
10. **Integration**: Test full stack communication
## Important Notes
- **Thread Safety**: FastAPI uses custom DatabaseConnection for thread safety
- **JSON Compatibility**: Backend uses PascalCase/camelCase aliasing for C# compatibility
- **Error Handling**: Comprehensive HTTP status codes and error responses
- **CORS**: Configured for frontend origins on localhost:5000/5001
- **Virtual Environment**: Pre-configured Python environment in `backend/.venv/`
- **Auto-reload**: Both backend (Uvicorn) and frontend (dotnet watch) support hot reload