# Package Appointments - New Workflow Implementation Plan ## Date: November 18, 2025 --- ## 📋 REQUIREMENTS CLARIFICATION ### Current Understanding (CORRECTED): **Package Assignment Logic:** - Packages are NOT pre-purchased by patients - Packages exist as templates in the system - When booking an appointment with a package: - User selects patient - System shows ALL available packages (not just patient's purchases) - User selects a package - **System creates PackagePurchase at this moment** (assigns package to patient) - Then schedules appointments from that package --- ## 🎯 NEW WORKFLOW REQUIREMENTS ### **1. Package Creation (Admin Panel)** ✅ Already Exists - Admin creates packages with: - Set of services - Number of sessions per service - Optional: default clinic, provider restrictions, validity period ### **2. Booking Workflow (User Side)** 🔄 NEEDS IMPLEMENTATION #### **Step 1: Start Appointment Booking** - User clicks "Book Appointment" - Options: - Normal booking flow (single session) - "Use Package" option #### **Step 2: Selecting "Use Package"** 🆕 NEW FEATURE **Modal Window Should Show:** - Patient selection dropdown (if not already selected) - After patient selected, show TWO categories of packages: 1. **Packages already assigned to this patient** (existing PackagePurchases) 2. **Available packages not yet assigned** (all active Packages) **Key Difference from Current Implementation:** - Current: Only shows PackagePurchases for patient ❌ - Required: Show ALL available Packages + existing PackagePurchases ✅ #### **Step 3: Linking Package to Patient (Backend)** 🆕 NEW LOGIC When user selects an unassigned package: - System creates new `PackagePurchase` record - Links package to patient - Tracks: - Remaining sessions - Services included - Used vs unused appointments - Purchase date - Expiry date ### **3. Dynamic Clinic & Provider Filtering** 🆕 NEW FEATURE #### **Populate Clinics Based on Package Services** After package selection: - Extract services from package - Filter clinics that can perform these services - Show only relevant clinics #### **Provider Selection** - Single provider OR multiple providers (multi-select) - Filter providers by: - Selected clinics - Services in package - Provider availability ### **4. Auto-Scheduling** ✅ Partially Exists, Needs Enhancement After selecting clinics & providers: - Show "Auto Schedule" button - Calculate best available slots considering: - Provider availability - Clinic hours - Remaining package sessions - Service duration - Pre-fill appointment details for confirmation ### **5. Final Confirmation** ✅ Already Exists - User confirms appointment - System deducts session from package - Appointment logged and linked to package --- ## 🔧 IMPLEMENTATION PLAN ### **Phase 1: Revert Incorrect Changes** ⚠️ CRITICAL **Current Issue:** - Form only shows PackagePurchases for patient - Should show ALL Packages + existing PackagePurchases **Files to Modify:** 1. `appointments/forms.py` - Change queryset logic 2. `appointments/views.py` - Update validation logic 3. `appointments/templates/appointments/appointment_form.html` - Update UI ### **Phase 2: Implement Modal for Package Selection** 🆕 **New Components:** 1. Create modal template for package selection 2. Add AJAX endpoint to fetch packages 3. Separate assigned vs unassigned packages 4. Handle package assignment on selection **Files to Create/Modify:** - `appointments/templates/appointments/partials/package_selection_modal.html` - `appointments/views.py` - Add `assign_package_to_patient` view - `appointments/api_views.py` - Add API endpoint for package list ### **Phase 3: Dynamic Clinic & Provider Filtering** 🆕 **Implementation:** 1. Extract services from selected package 2. Filter clinics by services 3. Multi-select provider dropdown 4. AJAX-based filtering **Files to Modify:** - `appointments/forms.py` - Add dynamic filtering - `appointments/templates/appointments/appointment_form.html` - Add multi-select - JavaScript for dynamic updates ### **Phase 4: Enhanced Auto-Scheduling** 🔄 **Enhancements:** 1. Support multiple providers 2. Better slot calculation 3. Preview before confirmation 4. Batch appointment creation **Files to Modify:** - `appointments/package_integration_service.py` - `appointments/views.py` - `schedule_package_view` ### **Phase 5: Testing & Validation** ✅ - Test package assignment flow - Test multi-provider scheduling - Test clinic filtering - Test auto-scheduling --- ## 📊 COMPARISON: CURRENT vs REQUIRED | Feature | Current Implementation | Required Implementation | |---------|----------------------|------------------------| | Package Display | Only PackagePurchases for patient | ALL Packages + PackagePurchases | | Package Assignment | Pre-purchased in finance | Assigned during appointment booking | | Clinic Selection | Manual | Auto-filtered by package services | | Provider Selection | Single provider | Single OR multiple providers | | Auto-Schedule | Basic | Enhanced with multi-provider support | | Modal UI | No modal | Modal for package selection | --- ## 🗂️ DATABASE SCHEMA (No Changes Needed) Current schema already supports the workflow: ``` finance.Package (Template) ↓ finance.PackagePurchase (Assignment to Patient) ↓ appointments.Appointment (Individual Sessions) ``` **Key Fields:** - `PackagePurchase.patient` - Links to patient - `PackagePurchase.package` - Links to package template - `PackagePurchase.purchase_date` - When assigned - `PackagePurchase.sessions_used` - Tracking - `Appointment.package_purchase` - Links appointment to package --- ## 🔄 WORKFLOW DIAGRAM ``` 1. User: "Book Appointment" ↓ 2. User: Select "Use Package" ↓ 3. Modal Opens: - Select Patient - Show Packages: * Already Assigned (PackagePurchases) * Available (Packages) ↓ 4. User Selects Package ↓ 5. System: - If new package → Create PackagePurchase - If existing → Use existing PackagePurchase ↓ 6. System: - Extract services from package - Filter clinics by services - Show filtered clinics ↓ 7. User: - Select clinic(s) - Select provider(s) - multi-select ↓ 8. User: Click "Auto Schedule" ↓ 9. System: - Calculate available slots - Consider all providers - Create appointments ↓ 10. User: Confirm ↓ 11. System: - Save appointments - Increment sessions_used - Link to PackagePurchase ``` --- ## 🚨 CRITICAL CHANGES NEEDED ### **1. Form Queryset Logic** ⚠️ HIGH PRIORITY **Current (INCORRECT):** ```python # Shows only PackagePurchases for patient self.fields['package_purchase'].queryset = PackagePurchase.objects.filter( patient=patient, status='ACTIVE' ).filter(sessions_used__lt=F('total_sessions')) ``` **Required (CORRECT):** ```python # Need TWO separate fields or combined logic: # 1. Show existing PackagePurchases for patient # 2. Show all available Packages # Option A: Two separate dropdowns self.fields['existing_package'].queryset = PackagePurchase.objects.filter(...) self.fields['new_package'].queryset = Package.objects.filter(is_active=True) # Option B: Combined with grouping in template # Return both and handle in JavaScript ``` ### **2. Package Assignment Logic** 🆕 NEW **Need to Add:** ```python def assign_package_to_patient(request): """ Create PackagePurchase when user selects unassigned package. """ package_id = request.POST.get('package_id') patient_id = request.POST.get('patient_id') # Create PackagePurchase package_purchase = PackagePurchase.objects.create( patient=patient, package=package, purchase_date=date.today(), expiry_date=date.today() + timedelta(days=package.validity_days), total_sessions=package.total_sessions, sessions_used=0, status='ACTIVE' ) return JsonResponse({'package_purchase_id': package_purchase.id}) ``` ### **3. Modal UI** 🆕 NEW **Need to Create:** - Modal template with package selection - AJAX calls for package list - Visual distinction between assigned/unassigned - Package assignment on selection --- ## 📝 IMPLEMENTATION STEPS ### **Step 1: Revert Previous Changes** ⚠️ - [ ] Revert form queryset to show all packages - [ ] Remove patient-only filtering - [ ] Update validation logic ### **Step 2: Create Modal UI** 🆕 - [ ] Create modal template - [ ] Add package selection logic - [ ] Implement AJAX endpoints - [ ] Add visual indicators ### **Step 3: Implement Package Assignment** 🆕 - [ ] Create assignment view - [ ] Add validation - [ ] Handle PackagePurchase creation - [ ] Link to appointment booking ### **Step 4: Dynamic Filtering** 🆕 - [ ] Extract services from package - [ ] Filter clinics by services - [ ] Implement multi-select for providers - [ ] Add AJAX updates ### **Step 5: Enhanced Auto-Schedule** 🔄 - [ ] Support multiple providers - [ ] Improve slot calculation - [ ] Add preview functionality - [ ] Batch create appointments ### **Step 6: Testing** ✅ - [ ] Test complete workflow - [ ] Test edge cases - [ ] Validate data integrity - [ ] User acceptance testing --- ## ⏱️ ESTIMATED EFFORT | Phase | Effort | Priority | |-------|--------|----------| | Revert Changes | 1 hour | HIGH | | Modal UI | 4 hours | HIGH | | Package Assignment | 2 hours | HIGH | | Dynamic Filtering | 3 hours | MEDIUM | | Enhanced Auto-Schedule | 3 hours | MEDIUM | | Testing | 2 hours | HIGH | | **TOTAL** | **15 hours** | | --- ## 🎯 NEXT STEPS 1. **Get User Confirmation** on this plan 2. **Revert incorrect changes** from previous implementation 3. **Implement modal-based package selection** 4. **Add package assignment logic** 5. **Implement dynamic filtering** 6. **Enhance auto-scheduling** 7. **Test complete workflow** --- ## 📞 QUESTIONS FOR USER 1. Should we show package prices in the selection modal? 2. Should there be approval workflow for package assignment? 3. Can users assign expired packages? 4. Should we limit how many times a package can be assigned? 5. What happens if a package is partially used and user wants to reassign? --- **Status:** PLAN READY - AWAITING USER CONFIRMATION TO PROCEED **Next Action:** User to confirm plan, then toggle to ACT MODE for implementation