# Trend Analysis - Complete Guide

## Overview

Trend analysis provides time-series insights into key metrics, showing how values change over time and comparing current periods to previous periods. Trends help identify patterns, growth, and areas for improvement.

## Key Features

- **Period-based grouping**: Week, Month, Quarter, or Year
- **Percentage change calculations**: Compare current period to previous period
- **Direction indicators**: Up, down, or stable trends
- **Grouped trends**: Analyze trends by clinic, practitioner, procedure, technology, or patient
- **Visualization ready**: Data structured for easy chart rendering

## Available Trend Methods

### 1. **Revenue Trends** 💰

Analyze revenue changes over time with period-over-period comparisons.

```typescript
const revenueTrends = await analyticsService.getRevenueTrends(
  dateRange,
  'month', // Period: 'week' | 'month' | 'quarter' | 'year'
  { clinicBranchId: 'clinic-123' }, // Optional filters
  'practitioner' // Optional: group by entity
);

// Returns: RevenueTrend[]
// [
//   {
//     period: '2024-01',
//     startDate: Date,
//     endDate: Date,
//     revenue: 50000,
//     appointmentCount: 100,
//     averageRevenue: 500,
//     currency: 'CHF',
//     previousPeriod: {
//       revenue: 45000,
//       appointmentCount: 90,
//       percentageChange: 11.1, // 11.1% increase
//       direction: 'up'
//     }
//   },
//   ...
// ]
```

**Use Cases:**
- Track revenue growth month-over-month
- Compare revenue by practitioner over quarters
- Analyze seasonal patterns
- Identify revenue trends by technology

### 2. **Duration/Efficiency Trends** ⏱️

Monitor time efficiency trends to optimize scheduling and resource allocation.

```typescript
const durationTrends = await analyticsService.getDurationTrends(
  dateRange,
  'month',
  { clinicBranchId: 'clinic-123' },
  'procedure' // Optional: group by entity
);

// Returns: DurationTrend[]
// [
//   {
//     period: '2024-01',
//     startDate: Date,
//     endDate: Date,
//     averageBookedDuration: 60, // minutes
//     averageActualDuration: 55, // minutes
//     averageEfficiency: 91.7, // percentage
//     appointmentCount: 100,
//     previousPeriod: {
//       averageBookedDuration: 60,
//       averageActualDuration: 58,
//       averageEfficiency: 96.7,
//       efficiencyPercentageChange: 5.0, // 5% decrease in efficiency
//       direction: 'down'
//     }
//   },
//   ...
// ]
```

**Use Cases:**
- Track efficiency improvements over time
- Identify scheduling optimization opportunities
- Compare efficiency across practitioners
- Monitor time management trends

### 3. **Appointment Trends** 📅

Analyze appointment volume and status distribution over time.

```typescript
const appointmentTrends = await analyticsService.getAppointmentTrends(
  dateRange,
  'week',
  { clinicBranchId: 'clinic-123' }
);

// Returns: AppointmentTrend[]
// [
//   {
//     period: '2024-W01',
//     startDate: Date,
//     endDate: Date,
//     totalAppointments: 50,
//     completedAppointments: 45,
//     canceledAppointments: 3,
//     noShowAppointments: 2,
//     pendingAppointments: 0,
//     confirmedAppointments: 0,
//     previousPeriod: {
//       totalAppointments: 48,
//       completedAppointments: 43,
//       percentageChange: 4.2, // 4.2% increase
//       direction: 'up'
//     }
//   },
//   ...
// ]
```

**Use Cases:**
- Track appointment volume growth
- Monitor completion rates over time
- Analyze cancellation patterns
- Compare appointment trends across clinics

### 4. **Cancellation Rate Trends** ❌

Track cancellation and no-show rates to identify patterns and improve patient retention.

```typescript
const cancellationTrends = await analyticsService.getCancellationRateTrends(
  dateRange,
  'month',
  { clinicBranchId: 'clinic-123' },
  'practitioner' // Optional: group by entity
);

// Returns: CancellationRateTrend[]
// [
//   {
//     period: '2024-01',
//     startDate: Date,
//     endDate: Date,
//     cancellationRate: 5.0, // percentage
//     noShowRate: 2.0, // percentage
//     totalAppointments: 100,
//     canceledAppointments: 5,
//     noShowAppointments: 2,
//     previousPeriod: {
//       cancellationRate: 6.0,
//       noShowRate: 2.5,
//       cancellationRateChange: 1.0, // 1% decrease (improvement)
//       noShowRateChange: 0.5, // 0.5% decrease (improvement)
//       direction: 'down' // Lower is better for cancellations
//     }
//   },
//   ...
// ]
```

**Use Cases:**
- Monitor cancellation rate improvements
- Compare cancellation rates across practitioners
- Identify problematic time periods
- Track effectiveness of retention strategies

## Period Types

Trends support four period types:

### Week (`'week'`)
- Groups data by ISO week (Monday to Sunday)
- Period format: `"2024-W01"` (Year-WeekNumber)
- Best for: Short-term analysis, weekly patterns

### Month (`'month'`)
- Groups data by calendar month
- Period format: `"2024-01"` (Year-Month)
- Best for: Monthly reporting, seasonal analysis

### Quarter (`'quarter'`)
- Groups data by calendar quarter (3 months)
- Period format: `"2024-Q1"` (Year-Quarter)
- Best for: Quarterly business reviews, long-term trends

### Year (`'year'`)
- Groups data by calendar year
- Period format: `"2024"` (Year)
- Best for: Annual comparisons, long-term growth

## Percentage Change Calculation

All trends include `previousPeriod` comparison data:

```typescript
previousPeriod: {
  // Previous period value
  value: number,
  
  // Percentage change (absolute value)
  percentageChange: number, // e.g., 11.1 means 11.1% change
  
  // Direction: 'up' | 'down' | 'stable'
  direction: 'up' // Indicates if trend is increasing, decreasing, or stable
}
```

**Calculation Formula:**
```typescript
percentageChange = ((current - previous) / previous) * 100
direction = percentageChange > 0.01 ? 'up' : percentageChange < -0.01 ? 'down' : 'stable'
```

**Note:** For cancellation/no-show rates, lower values are better, so the direction may be inverted in UI (e.g., a decrease in cancellation rate shows as 'up' trend).

## Grouped Trends

All trend methods support optional grouping by entity:

```typescript
// Overall trends (no grouping)
const overallTrends = await analyticsService.getRevenueTrends(
  dateRange,
  'month',
  { clinicBranchId: 'clinic-123' }
);

// Trends grouped by practitioner
const practitionerTrends = await analyticsService.getRevenueTrends(
  dateRange,
  'month',
  { clinicBranchId: 'clinic-123' },
  'practitioner' // Groups trends by practitioner
);

// Trends grouped by technology
const technologyTrends = await analyticsService.getRevenueTrends(
  dateRange,
  'quarter',
  { clinicBranchId: 'clinic-123' },
  'technology' // Aggregates all procedures using same technology
);
```

**Supported Grouping:**
- `'clinic'` - Trends by clinic
- `'practitioner'` - Trends by doctor
- `'procedure'` - Trends by procedure (includes practitioner association)
- `'technology'` - Trends by technology (aggregates procedures)
- `'patient'` - Trends by patient

## Frontend Integration

### Trend Indicators

Display percentage changes with visual indicators:

```typescript
import { TrendIndicator } from '@/pages/Analytics/components/TrendIndicator';

<TrendIndicator
  percentageChange={11.1}
  direction="up"
  size="small"
/>
// Displays: ↑ 11.1%
```

### Trend Charts

Visualize trends over time using line charts:

```typescript
import { TrendChart } from '@/pages/Analytics/components/TrendChart';

<TrendChart
  data={trendData.map(t => ({ period: t.period, value: t.revenue }))}
  dataKey="value"
  name="Revenue"
  color="#3b82f6"
  height={300}
  formatValue={(value) => `CHF ${value.toLocaleString()}`}
/>
```

### Period Selector

Allow users to switch between period types:

```typescript
import { PeriodSelector } from '@/pages/Analytics/components/PeriodSelector';

<PeriodSelector
  value={trendPeriod}
  onChange={setTrendPeriod}
/>
```

## Complete Example

```typescript
import { AnalyticsService } from '@blackcode_sa/metaestetics-api';

const analyticsService = new AnalyticsService(db, auth, app, appointmentService);

// Define date range
const dateRange = {
  start: new Date('2024-01-01'),
  end: new Date('2024-12-31')
};

// Get revenue trends by month
const revenueTrends = await analyticsService.getRevenueTrends(
  dateRange,
  'month',
  { clinicBranchId: 'clinic-123' }
);

// Process trends
revenueTrends.forEach(trend => {
  console.log(`Period: ${trend.period}`);
  console.log(`Revenue: ${trend.currency} ${trend.revenue.toLocaleString()}`);
  console.log(`Appointments: ${trend.appointmentCount}`);
  
  if (trend.previousPeriod) {
    const change = trend.previousPeriod.percentageChange;
    const direction = trend.previousPeriod.direction;
    console.log(`Change: ${direction === 'up' ? '+' : '-'}${change.toFixed(1)}%`);
  }
});

// Get efficiency trends grouped by practitioner
const efficiencyTrends = await analyticsService.getDurationTrends(
  dateRange,
  'quarter',
  { clinicBranchId: 'clinic-123' },
  'practitioner'
);

// Analyze efficiency improvements
efficiencyTrends.forEach(trend => {
  if (trend.previousPeriod && trend.previousPeriod.direction === 'up') {
    console.log(`Efficiency improved by ${trend.previousPeriod.efficiencyPercentageChange}%`);
  }
});
```

## Best Practices

1. **Choose appropriate period**: Use weeks for short-term analysis, quarters/years for strategic planning
2. **Compare periods**: Always check `previousPeriod` data to understand context
3. **Group when needed**: Use entity grouping to drill down into specific areas
4. **Visualize trends**: Use charts to make trends easier to understand
5. **Consider seasonality**: Account for seasonal patterns when analyzing trends
6. **Monitor direction**: Pay attention to trend direction (up/down/stable) for quick insights

## Limitations

- **No custom periods**: Trends only support week, month, quarter, and year periods
- **No trailing periods**: Trends require predefined periods (not "last 7 days" style)
- **Period alignment**: Date ranges should align with period boundaries for best results
- **In-memory calculation**: Trends are calculated on-demand (consider caching for large datasets)

## Related Documentation

- [Analytics Service README](./README.md)
- [Grouped Analytics Guide](./GROUPED_ANALYTICS.md)
- [Analytics Types](../../types/analytics/analytics.types.ts)
- [Trend Calculation Utils](./utils/trend-calculation.utils.ts)

