# Analytics Service Proposal

> **Note**: This proposal has been implemented. The service is located in `src/services/analytics/` and types in `src/types/analytics/`. See the [README](../../services/analytics/README.md) for usage documentation.

## Overview

This document proposes the design and implementation of an `analytics.service.ts` service for the Clinic Admin app. This service will provide comprehensive financial and analytical intelligence about doctors, procedures, appointments, patients, products, and clinic operations.

**Status**: ✅ **IMPLEMENTED** - See `src/services/analytics/analytics.service.ts`

## Data Sources & Connections

### Primary Data Sources

1. **Appointments Collection** (`appointments`)
   - Status tracking (pending, confirmed, completed, canceled, no-show)
   - Time tracking (booked time vs actual time)
   - Cost and billing information
   - Procedure and product usage
   - Patient and practitioner associations

2. **Procedures Collection** (`procedures`)
   - Procedure metadata (category, subcategory, technology, family)
   - Pricing information
   - Duration information
   - Product associations

3. **Practitioners Collection** (`practitioners`)
   - Practitioner information
   - Clinic associations
   - Procedure associations

4. **Patients Collection** (`patients`)
   - Patient profiles
   - Appointment history
   - Clinic and practitioner associations

5. **Clinics Collection** (`clinics`)
   - Clinic information
   - Branch information
   - Practitioner associations

6. **Products Collection** (`products`)
   - Product information
   - Brand associations
   - Pricing information

### Key Data Relationships

```
Clinic → Practitioners → Procedures → Appointments → Patients
                              ↓
                          Products (via metadata.zonesData)
```

### Critical Appointment Fields for Analytics

From `Appointment` type:
- `status`: AppointmentStatus (for filtering completed/canceled/no-show)
- `appointmentStartTime`, `appointmentEndTime`: Booked time slots
- `procedureActualStartTime`, `actualDurationMinutes`: Actual time spent
- `cost`, `currency`: Base appointment cost
- `paymentStatus`: Payment tracking
- `metadata.finalbilling`: Final billing calculations
- `metadata.zonesData`: Product usage per zone
- `metadata.extendedProcedures`: Additional procedures performed
- `metadata.appointmentProducts`: Products used
- `clinicBranchId`, `practitionerId`, `patientId`: Entity associations
- `cancellationTime`, `canceledBy`: Cancellation tracking
- `procedureId`: Primary procedure reference

## Proposed Analytics Categories

### 1. Doctor/Practitioner Analytics

#### Metrics to Calculate:
- **Total appointments** by practitioner
- **Completed appointments** count
- **Cancellation rate** (by practitioner)
- **No-show rate** (by practitioner)
- **Average booked time** per appointment
- **Average actual time** per appointment
- **Time efficiency** (actual vs booked time ratio)
- **Total revenue** generated
- **Average revenue** per appointment
- **Most performed procedures**
- **Patient retention rate**

#### Data Sources:
- Appointments filtered by `practitionerId`
- Compare `appointmentEndTime - appointmentStartTime` vs `actualDurationMinutes`
- Count appointments by `status`
- Sum `metadata.finalbilling.finalPrice` or `cost`

### 2. Procedure Analytics

#### Metrics to Calculate:
- **Total appointments** per procedure
- **Average cost** per procedure
- **Total revenue** per procedure
- **Average duration** (booked vs actual)
- **Cancellation rate** by procedure
- **No-show rate** by procedure
- **Most popular procedures** (by count)
- **Most profitable procedures** (by revenue)
- **Procedure performance** by category/subcategory/technology
- **Product usage** per procedure

#### Data Sources:
- Appointments filtered by `procedureId`
- `procedureInfo` and `procedureExtendedInfo` for procedure details
- `metadata.extendedProcedures` for additional procedures
- `metadata.zonesData` for product usage

### 3. Appointment Time Analytics

#### Metrics to Calculate:
- **Booked time** vs **Actual time** comparison
- **Time efficiency** percentage
- **Average overrun** time
- **Average underutilization** time
- **Peak hours** analysis
- **Time distribution** by day of week
- **Appointment duration trends**

#### Calculation Formula:
```typescript
bookedDuration = appointmentEndTime - appointmentStartTime (minutes)
actualDuration = actualDurationMinutes || bookedDuration
efficiency = (actualDuration / bookedDuration) * 100
overrun = actualDuration > bookedDuration ? actualDuration - bookedDuration : 0
underutilization = bookedDuration > actualDuration ? bookedDuration - actualDuration : 0
```

### 4. Cancellation & No-Show Analytics

#### Metrics to Calculate:
- **Cancellation rate** (overall, by clinic, by practitioner, by patient)
- **No-show rate** (overall, by clinic, by practitioner, by patient)
- **Cancellation reasons** breakdown
- **Cancellation patterns** (by time of day, day of week)
- **Patient cancellation history**
- **Clinic cancellation trends**
- **Average cancellation lead time** (time between booking and cancellation)

#### Status Mapping:
```typescript
Cancellation Statuses:
- AppointmentStatus.CANCELED_PATIENT
- AppointmentStatus.CANCELED_CLINIC
- AppointmentStatus.CANCELED_PATIENT_RESCHEDULED
- AppointmentStatus.NO_SHOW
```

#### Calculation Formula:
```typescript
cancellationRate = (canceledCount / totalAppointments) * 100
noShowRate = (noShowCount / totalAppointments) * 100
```

### 5. Financial Analytics

#### Metrics to Calculate:
- **Total revenue** (overall, by clinic, by practitioner, by procedure, by patient)
- **Average cost** per appointment
- **Average cost** per patient
- **Total cost** per patient
- **Revenue by procedure**
- **Revenue by product**
- **Revenue trends** (daily, weekly, monthly)
- **Payment status** breakdown
- **Unpaid appointments** value
- **Refunded appointments** value
- **Product cost** analysis
- **Tax calculations** (from `metadata.finalbilling.taxPrice`)

#### Cost Calculation Sources:
1. **Primary**: `metadata.finalbilling.finalPrice` (if available)
2. **Fallback**: Sum of `metadata.zonesData` subtotals
3. **Base**: `appointment.cost` (if no zone data)

#### Formula:
```typescript
totalRevenue = sum(metadata.finalbilling?.finalPrice || calculateFromZones(appointment) || appointment.cost)
averageCostPerAppointment = totalRevenue / completedAppointmentsCount
averageCostPerPatient = totalRevenue / uniquePatientsCount
```

### 6. Product Usage Analytics

#### Metrics to Calculate:
- **Products used** per appointment
- **Total quantity** per product
- **Product revenue** contribution
- **Most used products**
- **Product usage** by procedure
- **Product usage** by zone
- **Average product cost** per appointment
- **Product cost trends**

#### Data Sources:
- `metadata.zonesData`: Zone-specific product usage with quantities and prices
- `metadata.appointmentProducts`: Product metadata
- `metadata.finalbilling`: Final billing calculations

#### Extraction Logic:
```typescript
// From zonesData
products = []
for each zone in zonesData:
  for each item in zone.items:
    if item.type === 'item' and item.productId:
      products.push({
        productId: item.productId,
        productName: item.productName,
        quantity: item.quantity,
        price: item.priceOverrideAmount || item.price,
        subtotal: item.subtotal,
        currency: item.currency
      })
```

### 7. Patient Analytics

#### Metrics to Calculate:
- **Total patients** (unique count)
- **New patients** vs **Returning patients**
- **Average appointments** per patient
- **Patient lifetime value** (total revenue per patient)
- **Patient retention rate**
- **Average cancellation rate** per patient
- **Average no-show rate** per patient
- **Most valuable patients** (by revenue)
- **Patient appointment frequency**

#### Calculation:
```typescript
uniquePatients = distinct(appointments.map(a => a.patientId))
newPatients = patients with firstAppointmentDate in dateRange
returningPatients = patients with multiple appointments
averageAppointmentsPerPatient = totalAppointments / uniquePatients
patientLifetimeValue = sum(revenue for patient) / uniquePatients
```

### 8. Clinic Analytics

#### Metrics to Calculate:
- **Total appointments** per clinic
- **Total revenue** per clinic
- **Average revenue** per appointment (by clinic)
- **Cancellation rate** by clinic
- **No-show rate** by clinic
- **Practitioner performance** by clinic
- **Procedure popularity** by clinic
- **Clinic efficiency** metrics

## Proposed Service Methods

### Service Structure

```typescript
export class AnalyticsService extends BaseService {
  // Constructor and initialization
  
  // ==========================================
  // Practitioner Analytics
  // ==========================================
  
  /**
   * Get practitioner performance metrics
   * @param practitionerId - ID of the practitioner
   * @param dateRange - Optional date range filter
   * @returns Practitioner analytics object
   */
  async getPractitionerAnalytics(
    practitionerId: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<PractitionerAnalytics>
  
  /**
   * Get practitioner cancellation and no-show rates
   * @param practitionerId - ID of the practitioner
   * @param dateRange - Optional date range filter
   * @returns Cancellation and no-show metrics
   */
  async getPractitionerCancellationMetrics(
    practitionerId: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<CancellationMetrics>
  
  /**
   * Get practitioner time efficiency metrics
   * @param practitionerId - ID of the practitioner
   * @param dateRange - Optional date range filter
   * @returns Time efficiency metrics
   */
  async getPractitionerTimeMetrics(
    practitionerId: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<TimeEfficiencyMetrics>
  
  /**
   * Get practitioner revenue metrics
   * @param practitionerId - ID of the practitioner
   * @param dateRange - Optional date range filter
   * @returns Revenue metrics
   */
  async getPractitionerRevenueMetrics(
    practitionerId: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<RevenueMetrics>
  
  // ==========================================
  // Procedure Analytics
  // ==========================================
  
  /**
   * Get procedure performance metrics
   * @param procedureId - ID of the procedure (optional, if not provided returns all)
   * @param dateRange - Optional date range filter
   * @returns Procedure analytics object
   */
  async getProcedureAnalytics(
    procedureId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<ProcedureAnalytics | ProcedureAnalytics[]>
  
  /**
   * Get procedure popularity metrics
   * @param dateRange - Optional date range filter
   * @param limit - Number of top procedures to return
   * @returns Array of procedure popularity metrics
   */
  async getProcedurePopularity(
    dateRange?: { start: Date; end: Date },
    limit?: number
  ): Promise<ProcedurePopularity[]>
  
  /**
   * Get procedure profitability metrics
   * @param dateRange - Optional date range filter
   * @param limit - Number of top procedures to return
   * @returns Array of procedure profitability metrics
   */
  async getProcedureProfitability(
    dateRange?: { start: Date; end: Date },
    limit?: number
  ): Promise<ProcedureProfitability[]>
  
  // ==========================================
  // Appointment Time Analytics
  // ==========================================
  
  /**
   * Get time efficiency metrics for appointments
   * @param filters - Optional filters (clinicId, practitionerId, procedureId)
   * @param dateRange - Optional date range filter
   * @returns Time efficiency metrics
   */
  async getTimeEfficiencyMetrics(
    filters?: {
      clinicBranchId?: string;
      practitionerId?: string;
      procedureId?: string;
    },
    dateRange?: { start: Date; end: Date }
  ): Promise<TimeEfficiencyMetrics>
  
  /**
   * Get appointment duration trends
   * @param filters - Optional filters
   * @param dateRange - Date range for trend analysis
   * @param groupBy - Grouping period ('day' | 'week' | 'month')
   * @returns Duration trends
   */
  async getDurationTrends(
    filters?: {
      clinicBranchId?: string;
      practitionerId?: string;
      procedureId?: string;
    },
    dateRange?: { start: Date; end: Date },
    groupBy?: 'day' | 'week' | 'month'
  ): Promise<DurationTrend[]>
  
  // ==========================================
  // Cancellation & No-Show Analytics
  // ==========================================
  
  /**
   * Get cancellation metrics
   * @param groupBy - Group by 'clinic' | 'practitioner' | 'patient' | 'procedure'
   * @param dateRange - Optional date range filter
   * @returns Cancellation metrics grouped by specified entity
   */
  async getCancellationMetrics(
    groupBy: 'clinic' | 'practitioner' | 'patient' | 'procedure',
    dateRange?: { start: Date; end: Date }
  ): Promise<CancellationMetrics | CancellationMetrics[]>
  
  /**
   * Get no-show metrics
   * @param groupBy - Group by 'clinic' | 'practitioner' | 'patient' | 'procedure'
   * @param dateRange - Optional date range filter
   * @returns No-show metrics grouped by specified entity
   */
  async getNoShowMetrics(
    groupBy: 'clinic' | 'practitioner' | 'patient' | 'procedure',
    dateRange?: { start: Date; end: Date }
  ): Promise<NoShowMetrics | NoShowMetrics[]>
  
  /**
   * Get cancellation reasons breakdown
   * @param dateRange - Optional date range filter
   * @returns Cancellation reasons statistics
   */
  async getCancellationReasons(
    dateRange?: { start: Date; end: Date }
  ): Promise<CancellationReasonStats[]>
  
  // ==========================================
  // Financial Analytics
  // ==========================================
  
  /**
   * Get revenue metrics
   * @param filters - Optional filters
   * @param dateRange - Optional date range filter
   * @returns Revenue metrics
   */
  async getRevenueMetrics(
    filters?: {
      clinicBranchId?: string;
      practitionerId?: string;
      procedureId?: string;
      patientId?: string;
    },
    dateRange?: { start: Date; end: Date }
  ): Promise<RevenueMetrics>
  
  /**
   * Get revenue trends over time
   * @param filters - Optional filters
   * @param dateRange - Date range for trend analysis
   * @param groupBy - Grouping period ('day' | 'week' | 'month')
   * @returns Revenue trends
   */
  async getRevenueTrends(
    filters?: {
      clinicBranchId?: string;
      practitionerId?: string;
      procedureId?: string;
    },
    dateRange?: { start: Date; end: Date },
    groupBy?: 'day' | 'week' | 'month'
  ): Promise<RevenueTrend[]>
  
  /**
   * Get cost per patient metrics
   * @param patientId - Optional patient ID (if not provided, returns average)
   * @param dateRange - Optional date range filter
   * @returns Cost per patient metrics
   */
  async getCostPerPatient(
    patientId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<CostPerPatientMetrics>
  
  /**
   * Get payment status breakdown
   * @param filters - Optional filters
   * @param dateRange - Optional date range filter
   * @returns Payment status statistics
   */
  async getPaymentStatusBreakdown(
    filters?: {
      clinicBranchId?: string;
      practitionerId?: string;
    },
    dateRange?: { start: Date; end: Date }
  ): Promise<PaymentStatusBreakdown>
  
  // ==========================================
  // Product Usage Analytics
  // ==========================================
  
  /**
   * Get product usage metrics
   * @param productId - Optional product ID (if not provided, returns all products)
   * @param dateRange - Optional date range filter
   * @returns Product usage metrics
   */
  async getProductUsageMetrics(
    productId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<ProductUsageMetrics | ProductUsageMetrics[]>
  
  /**
   * Get product revenue contribution
   * @param dateRange - Optional date range filter
   * @param limit - Number of top products to return
   * @returns Product revenue metrics
   */
  async getProductRevenueMetrics(
    dateRange?: { start: Date; end: Date },
    limit?: number
  ): Promise<ProductRevenueMetrics[]>
  
  /**
   * Get product usage by procedure
   * @param procedureId - Optional procedure ID
   * @param dateRange - Optional date range filter
   * @returns Product usage by procedure
   */
  async getProductUsageByProcedure(
    procedureId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<ProductUsageByProcedure[]>
  
  // ==========================================
  // Patient Analytics
  // ==========================================
  
  /**
   * Get patient analytics
   * @param patientId - Optional patient ID (if not provided, returns aggregate)
   * @param dateRange - Optional date range filter
   * @returns Patient analytics
   */
  async getPatientAnalytics(
    patientId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<PatientAnalytics | PatientAnalytics[]>
  
  /**
   * Get patient lifetime value
   * @param patientId - Optional patient ID
   * @param dateRange - Optional date range filter
   * @returns Patient lifetime value metrics
   */
  async getPatientLifetimeValue(
    patientId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<PatientLifetimeValueMetrics>
  
  /**
   * Get patient retention metrics
   * @param dateRange - Optional date range filter
   * @returns Patient retention metrics
   */
  async getPatientRetentionMetrics(
    dateRange?: { start: Date; end: Date }
  ): Promise<PatientRetentionMetrics>
  
  // ==========================================
  // Clinic Analytics
  // ==========================================
  
  /**
   * Get clinic analytics
   * @param clinicBranchId - Optional clinic branch ID (if not provided, returns all)
   * @param dateRange - Optional date range filter
   * @returns Clinic analytics
   */
  async getClinicAnalytics(
    clinicBranchId?: string,
    dateRange?: { start: Date; end: Date }
  ): Promise<ClinicAnalytics | ClinicAnalytics[]>
  
  /**
   * Get clinic performance comparison
   * @param clinicBranchIds - Array of clinic branch IDs to compare
   * @param dateRange - Optional date range filter
   * @returns Clinic comparison metrics
   */
  async getClinicComparison(
    clinicBranchIds: string[],
    dateRange?: { start: Date; end: Date }
  ): Promise<ClinicComparisonMetrics[]>
  
  // ==========================================
  // Comprehensive Dashboard Data
  // ==========================================
  
  /**
   * Get comprehensive dashboard data
   * @param filters - Optional filters
   * @param dateRange - Optional date range filter
   * @returns Complete dashboard analytics
   */
  async getDashboardData(
    filters?: {
      clinicBranchId?: string;
      practitionerId?: string;
    },
    dateRange?: { start: Date; end: Date }
  ): Promise<DashboardAnalytics>
}
```

## Type Definitions

### Core Types

```typescript
// Base metrics interface
interface BaseMetrics {
  total: number;
  dateRange?: { start: Date; end: Date };
}

// Practitioner Analytics
interface PractitionerAnalytics extends BaseMetrics {
  practitionerId: string;
  practitionerName: string;
  totalAppointments: number;
  completedAppointments: number;
  canceledAppointments: number;
  noShowAppointments: number;
  cancellationRate: number; // percentage
  noShowRate: number; // percentage
  averageBookedTime: number; // minutes
  averageActualTime: number; // minutes
  timeEfficiency: number; // percentage
  totalRevenue: number;
  averageRevenuePerAppointment: number;
  topProcedures: Array<{
    procedureId: string;
    procedureName: string;
    count: number;
  }>;
  patientRetentionRate: number; // percentage
}

// Procedure Analytics
interface ProcedureAnalytics extends BaseMetrics {
  procedureId: string;
  procedureName: string;
  totalAppointments: number;
  completedAppointments: number;
  canceledAppointments: number;
  noShowAppointments: number;
  cancellationRate: number;
  noShowRate: number;
  averageCost: number;
  totalRevenue: number;
  averageBookedDuration: number; // minutes
  averageActualDuration: number; // minutes
  categoryName: string;
  subcategoryName: string;
  technologyName: string;
  productUsage: Array<{
    productId: string;
    productName: string;
    totalQuantity: number;
    totalRevenue: number;
  }>;
}

// Time Efficiency Metrics
interface TimeEfficiencyMetrics {
  totalAppointments: number;
  averageBookedDuration: number; // minutes
  averageActualDuration: number; // minutes
  averageEfficiency: number; // percentage
  totalOverrun: number; // minutes
  totalUnderutilization: number; // minutes
  averageOverrun: number; // minutes
  averageUnderutilization: number; // minutes
  efficiencyDistribution: Array<{
    range: string; // e.g., "0-50%", "50-75%", "75-100%", "100%+"
    count: number;
  }>;
}

// Cancellation Metrics
interface CancellationMetrics {
  entityId: string;
  entityName: string;
  entityType: 'clinic' | 'practitioner' | 'patient' | 'procedure';
  totalAppointments: number;
  canceledAppointments: number;
  cancellationRate: number; // percentage
  canceledByPatient: number;
  canceledByClinic: number;
  canceledByPractitioner: number;
  averageCancellationLeadTime: number; // hours
  cancellationReasons: Array<{
    reason: string;
    count: number;
  }>;
}

// No-Show Metrics
interface NoShowMetrics {
  entityId: string;
  entityName: string;
  entityType: 'clinic' | 'practitioner' | 'patient' | 'procedure';
  totalAppointments: number;
  noShowAppointments: number;
  noShowRate: number; // percentage
}

// Revenue Metrics
interface RevenueMetrics {
  totalRevenue: number;
  averageRevenuePerAppointment: number;
  totalAppointments: number;
  completedAppointments: number;
  currency: string;
  revenueByStatus: Record<AppointmentStatus, number>;
  revenueByPaymentStatus: Record<PaymentStatus, number>;
  unpaidRevenue: number;
  refundedRevenue: number;
}

// Product Usage Metrics
interface ProductUsageMetrics {
  productId: string;
  productName: string;
  brandId: string;
  brandName: string;
  totalQuantity: number;
  totalRevenue: number;
  averagePrice: number;
  usageCount: number; // number of appointments using this product
  averageQuantityPerAppointment: number;
}

// Patient Analytics
interface PatientAnalytics {
  patientId: string;
  patientName: string;
  totalAppointments: number;
  completedAppointments: number;
  canceledAppointments: number;
  noShowAppointments: number;
  cancellationRate: number;
  noShowRate: number;
  totalRevenue: number;
  averageRevenuePerAppointment: number;
  lifetimeValue: number;
  firstAppointmentDate: Date;
  lastAppointmentDate: Date;
  averageDaysBetweenAppointments: number;
}

// Clinic Analytics
interface ClinicAnalytics {
  clinicBranchId: string;
  clinicName: string;
  totalAppointments: number;
  completedAppointments: number;
  canceledAppointments: number;
  noShowAppointments: number;
  cancellationRate: number;
  noShowRate: number;
  totalRevenue: number;
  averageRevenuePerAppointment: number;
  practitionerCount: number;
  patientCount: number;
  procedureCount: number;
}

// Dashboard Analytics
interface DashboardAnalytics {
  overview: {
    totalAppointments: number;
    completedAppointments: number;
    canceledAppointments: number;
    noShowAppointments: number;
    totalRevenue: number;
    averageRevenuePerAppointment: number;
    uniquePatients: number;
    uniquePractitioners: number;
  };
  practitionerMetrics: PractitionerAnalytics[];
  procedureMetrics: ProcedureAnalytics[];
  cancellationMetrics: CancellationMetrics;
  noShowMetrics: NoShowMetrics;
  revenueTrends: RevenueTrend[];
  timeEfficiency: TimeEfficiencyMetrics;
  topProducts: ProductUsageMetrics[];
  recentActivity: Array<{
    type: 'appointment' | 'cancellation' | 'completion';
    date: Date;
    description: string;
  }>;
}
```

## Implementation Strategy

### Phase 1: Core Infrastructure
1. Create `analytics.service.ts` with base structure
2. Implement appointment querying utilities
3. Implement cost calculation utilities (handling finalbilling, zonesData, base cost)
4. Implement time calculation utilities

### Phase 2: Basic Metrics
1. Implement practitioner analytics
2. Implement procedure analytics
3. Implement basic financial metrics
4. Implement cancellation/no-show metrics

### Phase 3: Advanced Analytics
1. Implement time efficiency metrics
2. Implement product usage analytics
3. Implement patient analytics
4. Implement clinic analytics

### Phase 4: Dashboard & Trends
1. Implement dashboard data aggregation
2. Implement trend analysis
3. Implement comparison metrics

## Performance Considerations

### Query Optimization
- Use Firestore composite indexes for common query patterns
- Implement pagination for large datasets
- Cache frequently accessed metrics
- Use aggregation queries where possible

### Data Processing
- Process data in batches for large date ranges
- Use server-side calculations (Cloud Functions) for complex aggregations
- Consider pre-aggregating common metrics in Firestore documents

### Caching Strategy
- Cache dashboard data for short periods (5-15 minutes)
- Invalidate cache on appointment updates
- Use Firestore real-time listeners for live updates

## Data Validation & Edge Cases

### Cost Calculation Priority
1. Use `metadata.finalbilling.finalPrice` if available
2. Calculate from `metadata.zonesData` if finalbilling not available
3. Fall back to `appointment.cost` if no zone data

### Time Calculation
- Handle missing `actualDurationMinutes` gracefully
- Use booked duration as fallback
- Account for timezone differences

### Status Filtering
- Completed: `AppointmentStatus.COMPLETED`
- Canceled: `CANCELED_PATIENT`, `CANCELED_CLINIC`, `CANCELED_PATIENT_RESCHEDULED`
- No-show: `AppointmentStatus.NO_SHOW`
- Active: All statuses except canceled and no-show

## Next Steps

1. Review and approve this proposal
2. Create TypeScript type definitions file
3. Implement core service structure
4. Implement utility functions for cost and time calculations
5. Implement basic metrics methods
6. Add comprehensive tests
7. Create API documentation
8. Integrate with Clinic Admin app

