# Analytics System Documentation

## Overview

The analytics system provides comprehensive insights into store performance, sales trends, customer behavior, and order management. It supports both vendors and staff users (sub-users) with appropriate access controls and server-side rendering for optimal performance.

## Features

### 🔐 Multi-User Support
- **Vendors**: Access their own store analytics automatically
- **Staff/Sub-Users**: Access store analytics by providing a `storeId` parameter via URL or cookies
- **Role-based Access**: Different permissions for different user types
- **Server-side Rendering**: Initial data fetched server-side for better performance

### 📊 Analytics Dashboard
- **Overview Metrics**: Total revenue, orders, customers, and products
- **Revenue Trends**: Time-based revenue analysis with interactive charts
- **Product Performance**: Top-selling products with stock status
- **Customer Insights**: Customer segmentation and behavior analysis
- **Order Analytics**: Order status distribution and processing times

### 🎯 Key Metrics
- Total and monthly revenue
- Order completion rates
- Customer acquisition and retention
- Product performance rankings
- Average order processing times

## API Endpoints

### Authentication
All endpoints require authentication using the new `protectStore` middleware:

```javascript
// For vendors (automatic store access)
GET /api/analytics/overview

// For staff users (requires storeId parameter)
GET /api/analytics/overview?storeId=store_id_here
```

### Available Endpoints

#### 1. Analytics Overview
```http
GET /api/analytics/overview
```
Returns comprehensive overview metrics including:
- Order statistics (total, completed, pending, completion rate)
- Revenue data (total, monthly, weekly, average order value)
- Product count
- Unique customer count
- User type (vendor/staff)

#### 2. Revenue Trends
```http
GET /api/analytics/revenue-trends?period=30&storeId=optional
```
Returns daily revenue and order trends for the specified period.

#### 3. Product Performance
```http
GET /api/analytics/product-performance?storeId=optional
```
Returns top-performing products with sales metrics and stock status.

#### 4. Customer Insights
```http
GET /api/analytics/customer-insights?storeId=optional
```
Returns customer segmentation and top customer analysis.

#### 5. Order Analytics
```http
GET /api/analytics/order-analytics?period=30&storeId=optional
```
Returns order status distribution and processing time analysis.

## Frontend Implementation

### Server-Side Rendering
The analytics page uses server-side rendering for optimal performance:

```typescript
// app/dashboard/analytics/page.tsx
export default async function AnalyticsPage({
  searchParams,
}: {
  searchParams: { storeId?: string };
}) {
  const storeId = searchParams.storeId;
  const initialData = await getAnalyticsOverviewServer(storeId);
  
  return <AnalyticsDashboard initialData={initialData} />;
}
```

### Store Selection for Staff Users
Staff users can select which store to view analytics for:

```typescript
// URL-based store selection
/dashboard/analytics?storeId=store_id_here

// StoreSelector component for easy store switching
<StoreSelector />
```

### Components

#### AnalyticsDashboard
Main dashboard component with tabs for different analytics views.

**Props:**
- `initialData`: Initial analytics overview data (server-side fetched)

**Features:**
- Key metrics cards with trend indicators
- Tabbed interface for different analytics views
- Refresh functionality
- User type indicator (Vendor/Staff View)

#### StoreSelector
Client-side component for staff users to select stores.

**Features:**
- Input field for store ID
- URL-based navigation
- Current store display
- Error handling and validation

#### RevenueChart
Displays revenue trends over time with interactive charts.

**Props:**
- `timeRange`: Time period for analysis (7, 30, 90 days)

#### ProductPerformanceChart
Shows top-performing products in a table format.

#### CustomerInsightsChart
Displays customer segmentation and top customers.

#### OrderAnalyticsChart
Shows order status distribution and daily trends.

**Props:**
- `timeRange`: Time period for analysis

#### MetricsCard
Reusable component for displaying individual metrics.

**Props:**
- `title`: Metric title
- `value`: Metric value
- `description`: Metric description
- `icon`: Lucide icon component
- `trend`: Trend direction ("up", "down", "neutral")
- `trendValue`: Trend description

## Sub-User (Staff) Support

### Authentication Flow
1. Staff users authenticate using their staff credentials
2. When accessing analytics, they must provide a `storeId` parameter
3. The system verifies the store exists and grants access
4. All analytics data is filtered by the specified store

### Access Methods
Staff users can access store analytics in multiple ways:

1. **URL Parameter**: `/dashboard/analytics?storeId=store_id_here`
2. **Store Selector**: Use the StoreSelector component to choose a store
3. **Cookies**: Store ID can be stored in cookies for persistence

### Frontend Integration
The analytics service automatically handles both user types:

```typescript
// Server-side (for initial load)
const data = await getAnalyticsOverviewServer(storeId);

// Client-side (for refreshes and updates)
const data = await getAnalyticsOverviewWithStore();
```

## Usage Examples

### Basic Analytics Access
```typescript
// Server-side rendering
import { getAnalyticsOverviewServer } from '@/lib/server-api';
const overview = await getAnalyticsOverviewServer(storeId);

// Client-side updates
import { getAnalyticsOverviewWithStore } from '@/lib/services/analytics-service';
const overview = await getAnalyticsOverviewWithStore();
```

### Staff User with Specific Store
```typescript
// Navigate to analytics with store ID
router.push(`/dashboard/analytics?storeId=${storeId}`);

// Or use the store selector component
<StoreSelector />
```

### Revenue Trends with Time Range
```typescript
import { getRevenueTrendsWithStore } from '@/lib/services/analytics-service';

// Get 30-day revenue trends
const trends = await getRevenueTrendsWithStore('30');
```

## Data Structure

### AnalyticsOverview
```typescript
interface AnalyticsOverview {
  orders: {
    total: number;
    completed: number;
    pending: number;
    completionRate: string;
  };
  revenue: {
    total: number;
    monthly: number;
    weekly: number;
    averageOrderValue: number;
  };
  products: {
    total: number;
  };
  customers: {
    unique: number;
  };
  userType?: 'vendor' | 'staff';
}
```

### RevenueData
```typescript
interface RevenueData {
  _id: {
    year: number;
    month: number;
    day: number;
  };
  revenue: number;
  orders: number;
}
```

### ProductPerformance
```typescript
interface ProductPerformance {
  productId: string;
  name: string;
  image: string;
  unitType: string;
  currentStock: number;
  stockStatus: string;
  totalSold: number;
  totalRevenue: number;
  orderCount: number;
  averagePrice: number;
}
```

## Security Considerations

### Access Control
- Vendors can only access their own store data
- Staff users must provide valid storeId parameter
- All requests are authenticated and authorized
- Store ownership is verified for staff access

### Data Privacy
- Customer data is anonymized in analytics
- No sensitive information is exposed
- All data is filtered by store ownership

## Error Handling

The system provides comprehensive error handling:

- **401 Unauthorized**: Invalid or missing authentication → Redirect to login
- **400 Bad Request**: Missing storeId for staff users → Show store selector
- **403 Forbidden**: Access denied to specific store
- **404 Not Found**: Store not found
- **500 Server Error**: Internal server errors

All errors are displayed to users via toast notifications in the frontend.

## Performance Optimization

- **Server-side data fetching** for initial load
- **Client-side caching** for subsequent requests
- **Efficient database queries** with proper indexing
- **Pagination** for large datasets
- **Real-time data refresh** capabilities
- **Optimized rendering** with React Suspense

## Backend Implementation

### Middleware
- `protectStore`: Handles both vendors and staff users
- `protectVendorOnly`: Vendor-specific routes
- `protectStaffOnly`: Staff-specific routes

### Database Queries
- Uses `storeId` for consistent data filtering
- Aggregation pipelines for complex analytics
- Proper indexing for performance
- Time-based filtering for trends

## Future Enhancements

- Real-time analytics updates
- Export functionality for reports
- Advanced filtering and date range selection
- Custom dashboard configurations
- Email reports and notifications
- Comparative analytics (period-over-period)
- Predictive analytics and forecasting
- Multi-store comparison for staff users 