Kulcare Docs
DeveloperAppointments

Availability Settings Implementation

Overview

The Availability Settings feature allows clinic owners to configure doctor schedules through a user-friendly interface. This document covers the implementation details, API integration, and troubleshooting guide.

Implementation Status ✅

Status: Complete Last Updated: January 2025 Implementation: Fully functional with auto-selection and proper API integration

Architecture

Component Structure

AvailabilityTab
├── DoctorSelector (auto-selects first doctor)
├── ScheduleForm (with timezone support)
│   ├── DaysSelector
│   └── TimeRangePicker
├── CurrentSchedules (displays existing schedules)
│   └── ScheduleCard[]
└── EmptyState

Data Flow

1. Page loads → useClinicDoctorsAvailability hook fetches doctors
2. First doctor auto-selected → fetches doctor details
3. Formatted schedules displayed in CurrentSchedules
4. User creates new schedule → API call with correct format
5. Success → cache invalidation → UI updates

API Integration

Endpoints Used

  • GET /clinics/{clinicId}/clinic_doctors?basic=true - Get doctors list
  • GET /clinics/{clinicId}/clinic_doctors/{doctorId} - Get doctor details with schedules
  • POST /clinics/{clinicId}/clinic_doctors/{doctorId}/schedules - Create new schedule

API Payload Format

The implementation uses the correct API format as required by the backend:

// Payload sent to API
{
  "schedule_details": {
    "days": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    "start_time": "03:30",
    "end_time": "17:30",
    "timezone": "Asia/Kolkata",
    "discounted_fees": "",
    "scheduleId": ""
  }
}

Response Format

The API returns doctor details including formatted schedules:

{
  "success": true,
  "data": {
    "id": 206006,
    "formatted_schedules": [
      {
        "days": ["Mon-Sun"],
        "time": [
          {
            "id": 295314,
            "start_time": " 9:00 am",
            "end_time": " 8:00 pm"
          }
        ]
      }
    ]
    // ... other fields
  }
}

Key Features

1. Auto-Selection

  • Feature: First doctor automatically selected when page loads
  • Implementation: useEffect hook in AvailabilityTab.tsx
  • Trigger: When doctors array loads and no doctor is selected

2. Timezone Support

  • Default: "Asia/Kolkata"
  • Display: Shown in TimeRangePicker component
  • API: Included in all schedule creation requests

3. Real-time Updates

  • Cache Invalidation: Both doctor list and details queries invalidated on success
  • UI Updates: Schedules appear immediately after creation
  • Loading States: Proper loading indicators during operations

4. Backward Compatibility

  • Existing Methods: All existing API methods preserved unchanged
  • New Methods: Added createDoctorSchedule alongside existing updateClinicDoctorSchedule
  • No Breaking Changes: Other appointment booking flows unaffected

Files Modified

API Layer

  • practiceSettingsApi.ts: Added createDoctorSchedule method with correct payload format
  • availabilitySettings.ts: Added optional timezone field to ScheduleData type

Hook Layer

  • usePracticeSettings.ts:
    • Updated updateScheduleMutation to use new API method
    • Added proper data transformation for doctorDetails
    • Enhanced cache invalidation strategy

UI Layer

  • AvailabilityTab.tsx:
    • Added auto-selection logic with useEffect
    • Enhanced conditional rendering for schedules
    • Improved loading state handling

Performance Optimizations

React Query Caching

  • Doctor List: 10-minute stale time
  • Doctor Details: 5-minute stale time
  • Cache Keys: Properly structured for efficient invalidation

Component Memoization

All components use React.memo for performance:

  • DoctorSelector
  • ScheduleForm
  • CurrentSchedules
  • ScheduleCard

Error Handling

API Errors

  • Network Issues: Toast notifications with retry capability
  • Validation Errors: Form-level validation with error messages
  • Server Errors: Graceful degradation with user-friendly messages

Edge Cases

  • No Doctors: Proper empty state handling
  • No Schedules: Empty state with helpful guidance
  • Loading States: Skeleton loaders and spinners

Testing Strategy

Manual Testing Checklist

  • Page loads with first doctor auto-selected
  • Existing schedules display correctly
  • New schedule creation works with correct API format
  • Form validation prevents invalid submissions
  • Loading states work properly
  • Error states handled gracefully

API Testing

  • Verify payload matches required format exactly
  • Test timezone inclusion in all requests
  • Test both individual days and "Daily" selections
  • Verify cache invalidation triggers UI updates

Troubleshooting

Common Issues

1. Schedules Not Displaying

Symptoms: CurrentSchedules component is empty despite API returning data Causes:

  • Data transformation issues in hook
  • Incorrect conditional rendering
  • Cache invalidation problems

Solutions:

// Check if doctorDetails transformation is working
console.log('Doctor Details:', selectedDoctorDetails)
console.log('Formatted Schedules:', selectedDoctorDetails?.formatted_schedules)

// Verify API response structure
console.log('API Response:', doctorDetailsResponse?.data)

2. Auto-Selection Not Working

Symptoms: No doctor selected when page loads Causes:

  • useEffect dependencies incorrect
  • Doctors array empty or not loaded
  • Async timing issues

Solutions:

// Debug auto-selection
useEffect(() => {
  console.log('Doctors:', doctors.length, 'Selected:', selectedDoctorId)
  if (doctors.length > 0 && !selectedDoctorId) {
    console.log('Auto-selecting first doctor:', doctors[0].id)
    setSelectedDoctorId(doctors[0].id)
  }
}, [doctors, selectedDoctorId])

3. API Format Issues

Symptoms: 400/500 errors when creating schedules Causes:

  • Incorrect payload format
  • Missing required fields
  • Timezone issues

Solutions:

// Verify payload structure
const payload = {
  schedule_details: {
    days: scheduleData.days,
    start_time: scheduleData.start_time,
    end_time: scheduleData.end_time,
    timezone: scheduleData.timezone || "Asia/Kolkata",
    discounted_fees: "",
    scheduleId: ""
  }
}
console.log('API Payload:', payload)

Development Notes

Backward Compatibility

  • All existing methods preserved unchanged
  • New methods added alongside existing ones
  • No impact on other appointment booking flows
  • Safe rollback strategy available

Future Enhancements

  • Edit/Delete schedule functionality (TODO items in code)
  • Bulk schedule management
  • Schedule templates and presets
  • Advanced validation rules
  • Audit trail for schedule changes

On this page