diff --git a/CL_backendfixes.md b/CL_backendfixes.md deleted file mode 100644 index b098283..0000000 --- a/CL_backendfixes.md +++ /dev/null @@ -1,261 +0,0 @@ -# ๐ŸŽฏ **Backend Implementation TODO List** - -## **Priority 1: Core API Gaps (Essential)** - -### **1.1 Plan Generation Endpoint** -- [ ] **Add plan generation endpoint** in `app/routes/plan.py` - ```python - @router.post("/generate", response_model=PlanSchema) - async def generate_plan( - plan_request: PlanGenerationRequest, - db: AsyncSession = Depends(get_db) - ): - ``` -- [ ] **Create PlanGenerationRequest schema** in `app/schemas/plan.py` - ```python - class PlanGenerationRequest(BaseModel): - rule_ids: List[UUID] - goals: Dict[str, Any] - user_preferences: Optional[Dict[str, Any]] = None - duration_weeks: int = 12 - ``` -- [ ] **Update AIService.generate_plan()** to handle rule fetching from DB -- [ ] **Add validation** for rule compatibility and goal requirements -- [ ] **Add tests** for plan generation workflow - -### **1.2 Rule Parsing API** -- [ ] **Add natural language rule parsing endpoint** in `app/routes/rule.py` - ```python - @router.post("/parse-natural-language") - async def parse_natural_language_rules( - request: NaturalLanguageRuleRequest, - db: AsyncSession = Depends(get_db) - ): - ``` -- [ ] **Create request/response schemas** in `app/schemas/rule.py` - ```python - class NaturalLanguageRuleRequest(BaseModel): - natural_language_text: str - rule_name: str - - class ParsedRuleResponse(BaseModel): - parsed_rules: Dict[str, Any] - confidence_score: Optional[float] - suggestions: Optional[List[str]] - ``` -- [ ] **Enhance AIService.parse_rules_from_natural_language()** with better error handling -- [ ] **Add rule validation** after parsing -- [ ] **Add preview mode** before saving parsed rules - -### **1.3 Section Integration with GPX Parsing** -- [ ] **Update `app/services/gpx.py`** to create sections automatically - ```python - async def parse_gpx_with_sections(file_path: str, route_id: UUID, db: AsyncSession) -> dict: - # Parse GPX into segments - # Create Section records for each segment - # Return enhanced GPX data with section metadata - ``` -- [ ] **Modify `app/routes/gpx.py`** to create sections after route creation -- [ ] **Add section creation logic** in GPX upload workflow -- [ ] **Update Section model** to include more GPX-derived metadata -- [ ] **Add section querying endpoints** for route visualization - -## **Priority 2: Data Model Enhancements** - -### **2.1 Missing Schema Fields** -- [ ] **Add missing fields to User model** in `app/models/user.py` - ```python - class User(BaseModel): - name: Optional[str] - email: Optional[str] - fitness_level: Optional[str] - preferences: Optional[JSON] - ``` -- [ ] **Enhance Plan model** with additional metadata - ```python - class Plan(BaseModel): - user_id: Optional[UUID] = Column(ForeignKey("users.id")) - name: str - description: Optional[str] - start_date: Optional[Date] - end_date: Optional[Date] - goal_type: Optional[str] - active: Boolean = Column(default=True) - ``` -- [ ] **Add plan-rule relationship table** (already exists but ensure proper usage) -- [ ] **Update all schemas** to match enhanced models - -### **2.2 Database Relationships** -- [ ] **Fix User-Plan relationship** in models -- [ ] **Add cascade delete rules** where appropriate -- [ ] **Add database constraints** for data integrity -- [ ] **Create missing indexes** for performance - ```sql - CREATE INDEX idx_workouts_garmin_activity_id ON workouts(garmin_activity_id); - CREATE INDEX idx_plans_user_active ON plans(user_id, active); - CREATE INDEX idx_analyses_workout_approved ON analyses(workout_id, approved); - ``` - -## **Priority 3: API Completeness** - -### **3.1 Export/Import Functionality** -- [ ] **Create export service** `app/services/export_import.py` - ```python - class ExportImportService: - async def export_user_data(user_id: UUID) -> bytes: - async def export_routes() -> bytes: - async def import_user_data(data: bytes, user_id: UUID): - ``` -- [ ] **Add export endpoints** in new `app/routes/export.py` - ```python - @router.get("/export/routes") - @router.get("/export/plans/{plan_id}") - @router.get("/export/user-data") - @router.post("/import/routes") - @router.post("/import/plans") - ``` -- [ ] **Support multiple formats** (JSON, GPX, ZIP) -- [ ] **Add data validation** for imports -- [ ] **Handle version compatibility** for imports - -### **3.2 Enhanced Dashboard API** -- [ ] **Expand dashboard data** in `app/routes/dashboard.py` - ```python - @router.get("/metrics/weekly") - @router.get("/metrics/monthly") - @router.get("/progress/{plan_id}") - @router.get("/upcoming-workouts") - ``` -- [ ] **Add aggregation queries** for metrics -- [ ] **Cache dashboard data** for performance -- [ ] **Add real-time updates** capability - -### **3.3 Advanced Workout Features** -- [ ] **Add workout comparison endpoint** - ```python - @router.get("/workouts/{workout_id}/compare/{compare_workout_id}") - ``` -- [ ] **Add workout search/filtering** - ```python - @router.get("/workouts/search") - async def search_workouts( - activity_type: Optional[str] = None, - date_range: Optional[DateRange] = None, - power_range: Optional[PowerRange] = None - ): - ``` -- [ ] **Add bulk workout operations** -- [ ] **Add workout tagging system** - -## **Priority 4: Service Layer Improvements** - -### **4.1 AI Service Enhancements** -- [ ] **Add prompt caching** to reduce API calls -- [ ] **Implement prompt A/B testing** framework -- [ ] **Add AI response validation** and confidence scoring -- [ ] **Create AI service health checks** -- [ ] **Add fallback mechanisms** for AI failures -- [ ] **Implement rate limiting** for AI calls -- [ ] **Add cost tracking** for AI API usage - -### **4.2 Garmin Service Improvements** -- [ ] **Add incremental sync** instead of full sync -- [ ] **Implement activity deduplication** logic -- [ ] **Add webhook support** for real-time sync -- [ ] **Enhance error recovery** for failed syncs -- [ ] **Add activity type filtering** -- [ ] **Support multiple Garmin accounts** per user - -### **4.3 Plan Evolution Enhancements** -- [ ] **Add plan comparison** functionality -- [ ] **Implement plan rollback** mechanism -- [ ] **Add plan branching** for different scenarios -- [ ] **Create plan templates** system -- [ ] **Add automated plan adjustments** based on performance - -## **Priority 5: Validation & Error Handling** - -### **5.1 Input Validation** -- [ ] **Add comprehensive Pydantic validators** for all schemas -- [ ] **Validate GPX file integrity** before processing -- [ ] **Add business rule validation** (e.g., plan dates, workout conflicts) -- [ ] **Validate AI responses** before storing -- [ ] **Add file size/type restrictions** - -### **5.2 Error Handling** -- [ ] **Create custom exception hierarchy** - ```python - class CyclingCoachException(Exception): - class GarminSyncError(CyclingCoachException): - class AIServiceError(CyclingCoachException): - class PlanGenerationError(CyclingCoachException): - ``` -- [ ] **Add global exception handler** -- [ ] **Improve error messages** for user feedback -- [ ] **Add error recovery mechanisms** -- [ ] **Log errors with context** for debugging - -## **Priority 6: Performance & Monitoring** - -### **6.1 Performance Optimizations** -- [ ] **Add database query optimization** -- [ ] **Implement caching** for frequently accessed data -- [ ] **Add connection pooling** configuration -- [ ] **Optimize GPX file parsing** for large files -- [ ] **Add pagination** to list endpoints -- [ ] **Implement background job queue** for long-running tasks - -### **6.2 Enhanced Monitoring** -- [ ] **Add application metrics** (response times, error rates) -- [ ] **Create health check dependencies** -- [ ] **Add performance profiling** endpoints -- [ ] **Implement alerting** for critical errors -- [ ] **Add audit logging** for data changes - -## **Priority 7: Security & Configuration** - -### **7.1 Security Improvements** -- [ ] **Implement user authentication/authorization** -- [ ] **Add rate limiting** to prevent abuse -- [ ] **Validate file uploads** for security -- [ ] **Add CORS configuration** properly -- [ ] **Implement request/response logging** (without sensitive data) -- [ ] **Add API versioning** support - -### **7.2 Configuration Management** -- [ ] **Add environment-specific configs** -- [ ] **Validate configuration** on startup -- [ ] **Add feature flags** system -- [ ] **Implement secrets management** -- [ ] **Add configuration reload** without restart - -## **Priority 8: Testing & Documentation** - -### **8.1 Testing** -- [ ] **Create comprehensive test suite** - - Unit tests for services - - Integration tests for API endpoints - - Database migration tests - - AI service mock tests -- [ ] **Add test fixtures** for common data -- [ ] **Implement test database** setup/teardown -- [ ] **Add performance tests** for critical paths -- [ ] **Create end-to-end tests** for workflows - -### **8.2 Documentation** -- [ ] **Generate OpenAPI documentation** -- [ ] **Add endpoint documentation** with examples -- [ ] **Create service documentation** -- [ ] **Document deployment procedures** -- [ ] **Add troubleshooting guides** - ---- - -## **๐ŸŽฏ Recommended Implementation Order:** - -1. **Week 1:** Priority 1 (Core API gaps) - Essential for feature completeness -2. **Week 2:** Priority 2 (Data model) + Priority 5.1 (Validation) - Foundation improvements -3. **Week 3:** Priority 3.1 (Export/Import) + Priority 4.1 (AI improvements) - User-facing features -4. **Week 4:** Priority 6 (Performance) + Priority 8.1 (Testing) - Production readiness - -This todo list will bring your backend implementation to 100% design doc compliance and beyond, making it production-ready with enterprise-level features! ๐Ÿš€ \ No newline at end of file diff --git a/CL_frontendfixes.md b/CL_frontendfixes.md deleted file mode 100644 index 84e7897..0000000 --- a/CL_frontendfixes.md +++ /dev/null @@ -1,255 +0,0 @@ -# Frontend Development TODO List - -## ๐Ÿšจ Critical Missing Features (High Priority) - -### 1. Rules Management System -- [ ] **Create Rules page component** (`/src/pages/Rules.jsx`) - - [ ] Natural language textarea editor - - [ ] AI parsing button with loading state - - [ ] JSON preview pane with syntax highlighting - - [ ] Rule validation feedback - - [ ] Save/cancel actions -- [ ] **Create RuleEditor component** (`/src/components/rules/RuleEditor.jsx`) - - [ ] Rich text input with auto-resize - - [ ] Character count and validation - - [ ] Template suggestions dropdown -- [ ] **Create RulePreview component** (`/src/components/rules/RulePreview.jsx`) - - [ ] JSON syntax highlighting (use `react-json-view`) - - [ ] Editable JSON with validation - - [ ] Diff view for rule changes -- [ ] **Create RulesList component** (`/src/components/rules/RulesList.jsx`) - - [ ] Rule set selection dropdown - - [ ] Version history per rule set - - [ ] Delete/duplicate rule sets -- [ ] **API Integration** - - [ ] `POST /api/rules` - Create new rule set - - [ ] `PUT /api/rules/{id}` - Update rule set - - [ ] `GET /api/rules` - List all rule sets - - [ ] `POST /api/rules/{id}/parse` - AI parsing endpoint - -### 2. Plan Generation Workflow -- [ ] **Create PlanGeneration page** (`/src/pages/PlanGeneration.jsx`) - - [ ] Goal selection interface - - [ ] Rule set selection - - [ ] Plan parameters (duration, weekly hours) - - [ ] Progress tracking for AI generation -- [ ] **Create GoalSelector component** (`/src/components/plans/GoalSelector.jsx`) - - [ ] Predefined goal templates - - [ ] Custom goal input - - [ ] Goal validation -- [ ] **Create PlanParameters component** (`/src/components/plans/PlanParameters.jsx`) - - [ ] Duration slider (4-20 weeks) - - [ ] Weekly hours slider (5-15 hours) - - [ ] Difficulty level selection - - [ ] Available days checkboxes -- [ ] **Enhance PlanTimeline component** - - [ ] Week-by-week breakdown - - [ ] Workout details expandable cards - - [ ] Progress tracking indicators - - [ ] Edit individual workouts -- [ ] **API Integration** - - [ ] `POST /api/plans/generate` - Generate new plan - - [ ] `GET /api/plans/{id}/preview` - Preview before saving - - [ ] Plan generation status polling - -### 3. Route Management & Visualization -- [ ] **Enhance RoutesPage** (`/src/pages/RoutesPage.jsx`) - - [ ] Route list with metadata - - [ ] GPX file upload integration - - [ ] Route preview cards - - [ ] Search and filter functionality -- [ ] **Create RouteVisualization component** (`/src/components/routes/RouteVisualization.jsx`) - - [ ] Interactive map (use Leaflet.js) - - [ ] GPX track overlay - - [ ] Elevation profile chart - - [ ] Distance markers -- [ ] **Create RouteMetadata component** (`/src/components/routes/RouteMetadata.jsx`) - - [ ] Distance, elevation gain, grade analysis - - [ ] Estimated time calculations - - [ ] Difficulty rating - - [ ] Notes/description editing -- [ ] **Create SectionManager component** (`/src/components/routes/SectionManager.jsx`) - - [ ] Split routes into sections - - [ ] Section-specific metadata - - [ ] Gear recommendations per section -- [ ] **Dependencies to add** - - [ ] `npm install leaflet react-leaflet` - - [ ] GPX parsing library integration - -### 4. Export/Import System -- [ ] **Create ExportImport page** (`/src/pages/ExportImport.jsx`) - - [ ] Export options (JSON, ZIP) - - [ ] Import validation - - [ ] Bulk operations -- [ ] **Create DataExporter component** (`/src/components/export/DataExporter.jsx`) - - [ ] Selective export (routes, rules, plans) - - [ ] Format selection (JSON, GPX, ZIP) - - [ ] Export progress tracking -- [ ] **Create DataImporter component** (`/src/components/export/DataImporter.jsx`) - - [ ] File validation and preview - - [ ] Conflict resolution interface - - [ ] Import progress tracking -- [ ] **API Integration** - - [ ] `GET /api/export` - Generate export package - - [ ] `POST /api/import` - Import data package - - [ ] `POST /api/import/validate` - Validate before import - -## ๐Ÿ”ง Code Quality & Architecture Improvements - -### 5. Enhanced Error Handling -- [ ] **Create GlobalErrorHandler** (`/src/components/GlobalErrorHandler.jsx`) - - [ ] Centralized error logging - - [ ] User-friendly error messages - - [ ] Retry mechanisms -- [ ] **Improve API error handling** - - [ ] Consistent error response format - - [ ] Network error recovery - - [ ] Timeout handling -- [ ] **Add error boundaries** - - [ ] Page-level error boundaries - - [ ] Component-level error recovery - -### 6. State Management Improvements -- [ ] **Enhance AuthContext** - - [ ] Add user preferences - - [ ] API caching layer - - [ ] Offline capability detection -- [ ] **Create AppStateContext** (`/src/context/AppStateContext.jsx`) - - [ ] Global loading states - - [ ] Toast notifications - - [ ] Modal management -- [ ] **Add React Query** (Optional but recommended) - - [ ] `npm install @tanstack/react-query` - - [ ] API data caching - - [ ] Background refetching - - [ ] Optimistic updates - -### 7. UI/UX Enhancements -- [ ] **Improve responsive design** - - [ ] Better mobile navigation - - [ ] Touch-friendly interactions - - [ ] Responsive charts and maps -- [ ] **Add loading skeletons** - - [ ] Replace generic spinners - - [ ] Component-specific skeletons - - [ ] Progressive loading -- [ ] **Create ConfirmDialog component** (`/src/components/ui/ConfirmDialog.jsx`) - - [ ] Delete confirmations - - [ ] Destructive action warnings - - [ ] Custom confirmation messages -- [ ] **Add keyboard shortcuts** - - [ ] Navigation shortcuts - - [ ] Action shortcuts - - [ ] Help overlay - -## ๐Ÿงช Testing & Quality Assurance - -### 8. Testing Infrastructure -- [ ] **Expand component tests** - - [ ] Rules management tests - - [ ] Plan generation tests - - [ ] Route visualization tests -- [ ] **Add integration tests** - - [ ] API integration tests - - [ ] User workflow tests - - [ ] Error scenario tests -- [ ] **Performance testing** - - [ ] Large dataset handling - - [ ] Chart rendering performance - - [ ] Memory leak detection - -### 9. Development Experience -- [ ] **Add Storybook** (Optional) - - [ ] Component documentation - - [ ] Design system documentation - - [ ] Interactive component testing -- [ ] **Improve build process** - - [ ] Bundle size optimization - - [ ] Dead code elimination - - [ ] Tree shaking verification -- [ ] **Add development tools** - - [ ] React DevTools integration - - [ ] Performance monitoring - - [ ] Bundle analyzer - -## ๐Ÿ“š Documentation & Dependencies - -### 10. Missing Dependencies -```json -{ - "leaflet": "^1.9.4", - "react-leaflet": "^4.2.1", - "react-json-view": "^1.21.3", - "@tanstack/react-query": "^4.32.0", - "react-hook-form": "^7.45.0", - "react-select": "^5.7.4", - "file-saver": "^2.0.5" -} -``` - -### 11. Configuration Files -- [ ] **Create environment config** (`/src/config/index.js`) - - [ ] API endpoints configuration - - [ ] Feature flags - - [ ] Environment-specific settings -- [ ] **Add TypeScript support** (Optional) - - [ ] Convert critical components - - [ ] Add type definitions - - [ ] Improve IDE support - -## ๐Ÿš€ Deployment & Performance - -### 12. Production Readiness -- [ ] **Optimize bundle size** - - [ ] Code splitting implementation - - [ ] Lazy loading for routes - - [ ] Image optimization -- [ ] **Add PWA features** (Optional) - - [ ] Service worker - - [ ] Offline functionality - - [ ] App manifest -- [ ] **Performance monitoring** - - [ ] Core Web Vitals tracking - - [ ] Error tracking integration - - [ ] User analytics - -## ๐Ÿ“… Implementation Priority - -### Phase 1 (Week 1-2): Core Missing Features -1. Rules Management System -2. Plan Generation Workflow -3. Enhanced Route Management - -### Phase 2 (Week 3): Data Management -1. Export/Import System -2. Enhanced Error Handling -3. State Management Improvements - -### Phase 3 (Week 4): Polish & Quality -1. UI/UX Enhancements -2. Testing Infrastructure -3. Performance Optimization - -### Phase 4 (Ongoing): Maintenance -1. Documentation -2. Monitoring -3. User Feedback Integration - ---- - -## ๐ŸŽฏ Success Criteria - -- [ ] All design document workflows implemented -- [ ] 90%+ component test coverage -- [ ] Mobile-responsive design -- [ ] Sub-3s initial page load -- [ ] Accessibility compliance (WCAG 2.1 AA) -- [ ] Cross-browser compatibility (Chrome, Firefox, Safari, Edge) - -## ๐Ÿ“ Notes - -- **Prioritize user-facing features** over internal architecture improvements -- **Test each feature** as you implement it -- **Consider Progressive Web App features** for offline functionality -- **Plan for internationalization** if expanding globally -- **Monitor bundle size** as you add dependencies \ No newline at end of file diff --git a/CL_implementation_guide.md b/CL_implementation_guide.md deleted file mode 100644 index 1ea9149..0000000 --- a/CL_implementation_guide.md +++ /dev/null @@ -1,1565 +0,0 @@ -# Junior Developer Implementation Guide -## AI Cycling Coach - Critical Features Implementation - -This guide provides step-by-step instructions to implement the missing core features identified in the codebase evaluation. - ---- - -## ๐ŸŽฏ **Implementation Phases Overview** - -| Phase | Focus | Duration | Difficulty | -|-------|-------|----------|------------| -| **Phase 1** | Backend Core APIs | 2-3 weeks | Medium | -| **Phase 2** | Frontend Core Features | 3-4 weeks | Medium | -| **Phase 3** | Integration & Testing | 1-2 weeks | Easy-Medium | -| **Phase 4** | Polish & Production | 1-2 weeks | Easy | - ---- - -# Phase 1: Backend Core APIs Implementation - -## Step 1.1: Plan Generation Endpoint - -### **File:** `backend/app/routes/plan.py` - -**Add this endpoint to the existing router:** - -```python -from app.schemas.plan import PlanGenerationRequest, PlanGenerationResponse -from app.services.ai_service import AIService, AIServiceError - -@router.post("/generate", response_model=PlanGenerationResponse) -async def generate_plan( - request: PlanGenerationRequest, - db: AsyncSession = Depends(get_db) -): - """Generate a new training plan using AI based on rules and goals.""" - try: - # Fetch rules from database - rules_query = select(Rule).where(Rule.id.in_(request.rule_ids)) - result = await db.execute(rules_query) - rules = result.scalars().all() - - if len(rules) != len(request.rule_ids): - raise HTTPException(status_code=404, detail="One or more rules not found") - - # Get plaintext rules - rule_texts = [rule.rule_text for rule in rules] - - # Initialize AI service - ai_service = AIService(db) - - # Generate plan - plan_data = await ai_service.generate_plan(rule_texts, request.goals.dict()) - - # Create plan record - db_plan = Plan( - jsonb_plan=plan_data, - version=1, - parent_plan_id=None - ) - db.add(db_plan) - await db.commit() - await db.refresh(db_plan) - - return PlanGenerationResponse( - plan=db_plan, - generation_metadata={ - "rules_used": len(rules), - "goals": request.goals.dict(), - "generated_at": datetime.utcnow().isoformat() - } - ) - - except AIServiceError as e: - raise HTTPException(status_code=503, detail=f"AI service error: {str(e)}") - except Exception as e: - raise HTTPException(status_code=500, detail=f"Plan generation failed: {str(e)}") -``` - -### **File:** `backend/app/schemas/plan.py` - -**Add these new schemas:** - -```python -from typing import Dict, List, Optional, Any -from pydantic import BaseModel, Field -from uuid import UUID - -class TrainingGoals(BaseModel): - """Training goals for plan generation.""" - primary_goal: str = Field(..., description="Primary training goal") - target_weekly_hours: int = Field(..., ge=3, le=20, description="Target hours per week") - fitness_level: str = Field(..., description="Current fitness level") - event_date: Optional[str] = Field(None, description="Target event date (YYYY-MM-DD)") - preferred_routes: List[int] = Field(default=[], description="Preferred route IDs") - avoid_days: List[str] = Field(default=[], description="Days to avoid training") - -class PlanGenerationRequest(BaseModel): - """Request schema for plan generation.""" - rule_ids: List[UUID] = Field(..., description="Rule set IDs to apply") - goals: TrainingGoals = Field(..., description="Training goals") - duration_weeks: int = Field(4, ge=1, le=20, description="Plan duration in weeks") - user_preferences: Optional[Dict[str, Any]] = Field(None, description="Additional preferences") - -class PlanGenerationResponse(BaseModel): - """Response schema for plan generation.""" - plan: Plan = Field(..., description="Generated training plan") - generation_metadata: Dict[str, Any] = Field(..., description="Generation metadata") - - class Config: - orm_mode = True -``` - ---- - - - - - -**Add these endpoints after the existing routes:** - -```python -from app.schemas.rule import NaturalLanguageRuleRequest, ParsedRuleResponse - -@router.post("/parse-natural-language", response_model=ParsedRuleResponse) -async def parse_natural_language_rules( - request: NaturalLanguageRuleRequest, - db: AsyncSession = Depends(get_db) -): - """Parse natural language text into structured training rules.""" - try: - # Initialize AI service - ai_service = AIService(db) - - # Parse rules using AI - parsed_data = await ai_service.parse_rules_from_natural_language( - request.natural_language_text - ) - - # Validate parsed rules - validation_result = _validate_parsed_rules(parsed_data) - - return ParsedRuleResponse( - parsed_rules=parsed_data, - confidence_score=parsed_data.get("confidence", 0.0), - suggestions=validation_result.get("suggestions", []), - validation_errors=validation_result.get("errors", []), - rule_name=request.rule_name - ) - - except AIServiceError as e: - raise HTTPException(status_code=503, detail=f"AI parsing failed: {str(e)}") - except Exception as e: - raise HTTPException(status_code=500, detail=f"Rule parsing failed: {str(e)}") - -@router.post("/validate-rules") -async def validate_rule_consistency( - rules_data: Dict[str, Any], - db: AsyncSession = Depends(get_db) -): - """Validate rule consistency and detect conflicts.""" - validation_result = _validate_parsed_rules(rules_data) - return { - "is_valid": len(validation_result.get("errors", [])) == 0, - "errors": validation_result.get("errors", []), - "warnings": validation_result.get("warnings", []), - "suggestions": validation_result.get("suggestions", []) - } - -def _validate_parsed_rules(parsed_rules: Dict[str, Any]) -> Dict[str, List[str]]: - """Validate parsed rules for consistency and completeness.""" - errors = [] - warnings = [] - suggestions = [] - - # Check for required fields - required_fields = ["max_rides_per_week", "min_rest_between_hard"] - for field in required_fields: - if field not in parsed_rules: - errors.append(f"Missing required field: {field}") - - # Validate numeric ranges - max_rides = parsed_rules.get("max_rides_per_week", 0) - if max_rides > 7: - errors.append("Maximum rides per week cannot exceed 7") - elif max_rides < 1: - errors.append("Must have at least 1 ride per week") - - # Check for conflicts - max_hours = parsed_rules.get("max_duration_hours", 0) - if max_rides and max_hours: - avg_duration = max_hours / max_rides - if avg_duration > 5: - warnings.append("Very long average ride duration detected") - elif avg_duration < 0.5: - warnings.append("Very short average ride duration detected") - - # Provide suggestions - if "weather_constraints" not in parsed_rules: - suggestions.append("Consider adding weather constraints for outdoor rides") - - return { - "errors": errors, - "warnings": warnings, - "suggestions": suggestions - } -``` - -### **File:** `backend/app/schemas/rule.py` - -**Replace the existing content with:** - -```python -from pydantic import BaseModel, Field, validator -from typing import Optional, Dict, Any, List - -class NaturalLanguageRuleRequest(BaseModel): - """Request schema for natural language rule parsing.""" - natural_language_text: str = Field( - ..., - min_length=10, - max_length=5000, - description="Natural language rule description" - ) - rule_name: str = Field(..., min_length=1, max_length=100, description="Rule set name") - - @validator('natural_language_text') - def validate_text_content(cls, v): - # Check for required keywords - required_keywords = ['ride', 'week', 'hour', 'day', 'rest', 'training'] - if not any(keyword in v.lower() for keyword in required_keywords): - raise ValueError("Text must contain training-related keywords") - return v - -class ParsedRuleResponse(BaseModel): - """Response schema for parsed rules.""" - parsed_rules: Dict[str, Any] = Field(..., description="Structured rule data") - confidence_score: Optional[float] = Field(None, ge=0.0, le=1.0, description="Parsing confidence") - suggestions: List[str] = Field(default=[], description="Improvement suggestions") - validation_errors: List[str] = Field(default=[], description="Validation errors") - rule_name: str = Field(..., description="Rule set name") - -class RuleBase(BaseModel): - """Base rule schema.""" - name: str = Field(..., min_length=1, max_length=100) - description: Optional[str] = Field(None, max_length=500) - user_defined: bool = Field(True, description="Whether rule is user-defined") - jsonb_rules: Dict[str, Any] = Field(..., description="Structured rule data") - version: int = Field(1, ge=1, description="Rule version") - parent_rule_id: Optional[int] = Field(None, description="Parent rule for versioning") - -class RuleCreate(RuleBase): - """Schema for creating new rules.""" - pass - -class Rule(RuleBase): - """Complete rule schema with database fields.""" - id: int - created_at: datetime - updated_at: datetime - - class Config: - orm_mode = True -``` - ---- - - - - - -**Add these enhanced methods:** - -```python -async def parse_rules_from_natural_language(self, natural_language: str) -> Dict[str, Any]: - """Enhanced natural language rule parsing with better prompts.""" - prompt_template = await self.prompt_manager.get_active_prompt("rule_parsing") - - if not prompt_template: - # Fallback prompt if none exists in database - prompt_template = """ - Parse the following natural language training rules into structured JSON format. - - Input: "{user_rules}" - - Required output format: - {{ - "max_rides_per_week": , - "min_rest_between_hard": , - "max_duration_hours": , - "intensity_limits": {{ - "max_zone_5_minutes_per_week": , - "max_consecutive_hard_days": - }}, - "weather_constraints": {{ - "min_temperature": , - "max_wind_speed": , - "no_rain": - }}, - "schedule_constraints": {{ - "preferred_days": [], - "avoid_days": [] - }}, - "confidence": <0.0-1.0> - }} - - Extract specific numbers and constraints. If information is missing, omit the field. - """ - - prompt = prompt_template.format(user_rules=natural_language) - response = await self._make_ai_request(prompt) - parsed_data = self._parse_rules_response(response) - - # Add confidence scoring - if "confidence" not in parsed_data: - parsed_data["confidence"] = self._calculate_parsing_confidence( - natural_language, parsed_data - ) - - return parsed_data - -def _calculate_parsing_confidence(self, input_text: str, parsed_data: Dict) -> float: - """Calculate confidence score for rule parsing.""" - confidence = 0.5 # Base confidence - - # Increase confidence for explicit numbers - import re - numbers = re.findall(r'\d+', input_text) - if len(numbers) >= 2: - confidence += 0.2 - - # Increase confidence for key training terms - training_terms = ['rides', 'hours', 'week', 'rest', 'recovery', 'training'] - found_terms = sum(1 for term in training_terms if term in input_text.lower()) - confidence += min(0.3, found_terms * 0.05) - - # Decrease confidence if parsed data is sparse - if len(parsed_data) < 3: - confidence -= 0.2 - - return max(0.0, min(1.0, confidence)) -``` - ---- - -# Phase 2: Frontend Core Features Implementation - -## Step 2.1: Simplified Rules Management - -### **File:** `frontend/src/pages/Rules.jsx` - -**Replace with simplified plaintext rules interface:** - -```jsx -import React, { useState, useEffect } from 'react'; -import { toast } from 'react-toastify'; -import RuleEditor from '../components/rules/RuleEditor'; -import RulePreview from '../components/rules/RulePreview'; -import RulesList from '../components/rules/RulesList'; -import { useAuth } from '../context/AuthContext'; -import * as ruleService from '../services/ruleService'; - -const Rules = () => { - const { apiKey } = useAuth(); - const [activeTab, setActiveTab] = useState('list'); - const [rules, setRules] = useState([]); - const [selectedRule, setSelectedRule] = useState(null); - const [naturalLanguageText, setNaturalLanguageText] = useState(''); - const [parsedRules, setParsedRules] = useState(null); - const [isLoading, setIsLoading] = useState(false); - - useEffect(() => { - loadRules(); - }, []); - - const loadRules = async () => { - try { - const response = await ruleService.getRules(); - setRules(response.data); - } catch (error) { - console.error('Failed to load rules:', error); - toast.error('Failed to load rules'); - } - }; - - const handleParseRules = async (parsedData) => { - setParsedRules(parsedData); - setActiveTab('preview'); - }; - - const handleSaveRules = async (ruleName, finalRules) => { - setIsLoading(true); - try { - const ruleData = { - name: ruleName, - jsonb_rules: finalRules, - user_defined: true, - version: 1 - }; - - await ruleService.createRule(ruleData); - toast.success('Rules saved successfully!'); - - // Reset form and reload rules - setNaturalLanguageText(''); - setParsedRules(null); - setActiveTab('list'); - await loadRules(); - } catch (error) { - console.error('Failed to save rules:', error); - toast.error('Failed to save rules'); - } finally { - setIsLoading(false); - } - }; - - const handleEditRule = (rule) => { - setSelectedRule(rule); - setNaturalLanguageText(rule.description || ''); - setParsedRules(rule.jsonb_rules); - setActiveTab('edit'); - }; - - return ( -
-
-
-

Training Rules

-

- Define your training constraints and preferences using natural language -

-
- - -
- - {/* Tab Navigation */} -
- -
- - {/* Tab Content */} - {activeTab === 'list' && ( - { - try { - await ruleService.deleteRule(ruleId); - toast.success('Rule deleted'); - await loadRules(); - } catch (error) { - toast.error('Failed to delete rule'); - } - }} - /> - )} - - {isEditing ? ( -
-
- - setRuleName(e.target.value)} - className="w-full p-3 border border-gray-300 rounded-lg" - /> -
- -
- -