# Admin Statistics API Documentation

## Overview

The Admin Statistics API provides comprehensive dashboard statistics for administrators, including recharge details, user statistics, and top users by recharge activity. These endpoints help admins monitor platform activity, track user engagement, and analyze recharge patterns.

---

## Base URL

```
https://api.alldigtalseva.com/api
```

**Authentication:** All endpoints require Admin Bearer Token

---

## API Endpoints

### 1. Dashboard Statistics

Get comprehensive dashboard statistics including recharge stats (today, this month, all-time), new users, and top users.

**Endpoint:** `GET /admin/user/dashboard-statistics`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Response (Success - 200):**
```json
{
    "success": true,
    "data": {
        "recharge_statistics": {
            "today": {
                "total_amount": 5000.00,
                "total_count": 5,
                "total_credited": 5500.00
            },
            "this_month": {
                "total_amount": 50000.00,
                "total_count": 45,
                "total_credited": 55000.00
            },
            "all_time": {
                "total_amount": 500000.00,
                "total_count": 450,
                "total_credited": 550000.00
            }
        },
        "user_statistics": {
            "today_new_users": 3,
            "this_month_new_users": 25,
            "total_users": 150,
            "verified_users": 145
        },
        "top_users": {
            "by_recharge_amount": [
                {
                    "user_id": 1,
                    "user": {
                        "id": 1,
                        "email": "user@example.com",
                        "phone_number": "1234567890",
                        "name": "John Doe",
                        "user_type": "user"
                    },
                    "total_recharge_amount": 10000.00,
                    "recharge_count": 10
                },
                {
                    "user_id": 2,
                    "user": {
                        "id": 2,
                        "email": "user2@example.com",
                        "phone_number": "9876543210",
                        "name": "Jane Smith",
                        "user_type": "distributor"
                    },
                    "total_recharge_amount": 8000.00,
                    "recharge_count": 8
                }
            ],
            "by_recharge_count": [
                {
                    "user_id": 1,
                    "user": {
                        "id": 1,
                        "email": "user@example.com",
                        "phone_number": "1234567890",
                        "name": "John Doe",
                        "user_type": "user"
                    },
                    "recharge_count": 10,
                    "total_recharge_amount": 10000.00
                }
            ]
        }
    }
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/admin/user/dashboard-statistics \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

### 2. User Recharge Details

Get detailed recharge information for all users, showing how much each user has recharged. Supports filtering and sorting.

**Endpoint:** `GET /admin/user/recharge-details`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| start_date | date | No | Filter by start date (YYYY-MM-DD) |
| end_date | date | No | Filter by end date (YYYY-MM-DD) |
| user_type | string | No | Filter by user type (user, distributor) |
| sort_by | string | No | Sort by: `total_recharge_amount` (default), `recharge_count`, `last_recharge_date` |
| sort_order | string | No | Sort order: `desc` (default), `asc` |
| per_page | integer | No | Items per page (1-100, default: 15) |

**Response (Success - 200):**
```json
{
    "success": true,
    "data": [
        {
            "user_id": 1,
            "user": {
                "id": 1,
                "email": "user@example.com",
                "phone_number": "1234567890",
                "name": "John Doe",
                "user_type": "user",
                "wallet_balance": 500.00
            },
            "total_recharge_amount": 10000.00,
            "total_credited_amount": 11000.00,
            "recharge_count": 10,
            "first_recharge_date": "2025-12-01T10:00:00.000000Z",
            "last_recharge_date": "2025-12-06T15:30:00.000000Z"
        },
        {
            "user_id": 2,
            "user": {
                "id": 2,
                "email": "user2@example.com",
                "phone_number": "9876543210",
                "name": "Jane Smith",
                "user_type": "distributor",
                "wallet_balance": 1200.00
            },
            "total_recharge_amount": 8000.00,
            "total_credited_amount": 8800.00,
            "recharge_count": 8,
            "first_recharge_date": "2025-12-02T09:00:00.000000Z",
            "last_recharge_date": "2025-12-05T14:20:00.000000Z"
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 50,
        "last_page": 4
    }
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Examples:**

```bash
# Get all user recharge details
curl -X GET "https://api.alldigtalseva.com/api/admin/user/recharge-details" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Filter by date range
curl -X GET "https://api.alldigtalseva.com/api/admin/user/recharge-details?start_date=2025-12-01&end_date=2025-12-31" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Filter by user type and sort by recharge count
curl -X GET "https://api.alldigtalseva.com/api/admin/user/recharge-details?user_type=distributor&sort_by=recharge_count&sort_order=desc" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Pagination
curl -X GET "https://api.alldigtalseva.com/api/admin/user/recharge-details?per_page=20" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

### 3. Top Users by Recharge

Get top users sorted by recharge amount or recharge count.

**Endpoint:** `GET /admin/user/top-users`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| sort_by | string | No | Sort by: `amount` (default), `count` |
| limit | integer | No | Number of results (1-50, default: 10) |
| start_date | date | No | Filter by start date (YYYY-MM-DD) |
| end_date | date | No | Filter by end date (YYYY-MM-DD) |

**Response (Success - 200):**
```json
{
    "success": true,
    "data": [
        {
            "user_id": 1,
            "user": {
                "id": 1,
                "email": "user@example.com",
                "phone_number": "1234567890",
                "name": "John Doe",
                "user_type": "user"
            },
            "total_recharge_amount": 10000.00,
            "recharge_count": 10
        },
        {
            "user_id": 2,
            "user": {
                "id": 2,
                "email": "user2@example.com",
                "phone_number": "9876543210",
                "name": "Jane Smith",
                "user_type": "distributor"
            },
            "total_recharge_amount": 8000.00,
            "recharge_count": 8
        }
    ],
    "sort_by": "amount",
    "limit": 10
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Examples:**

```bash
# Top 10 users by recharge amount (default)
curl -X GET "https://api.alldigtalseva.com/api/admin/user/top-users" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Top 20 users by recharge count
curl -X GET "https://api.alldigtalseva.com/api/admin/user/top-users?sort_by=count&limit=20" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Top users for a specific date range
curl -X GET "https://api.alldigtalseva.com/api/admin/user/top-users?start_date=2025-12-01&end_date=2025-12-31&limit=15" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

## JavaScript/Angular Examples

### Dashboard Statistics

```typescript
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AdminStatisticsService {
  private apiUrl = 'https://api.alldigtalseva.com/api';
  private headers: HttpHeaders;

  constructor(private http: HttpClient) {
    const token = localStorage.getItem('admin_token');
    this.headers = new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }

  getDashboardStatistics(): Observable<any> {
    return this.http.get(`${this.apiUrl}/admin/user/dashboard-statistics`, {
      headers: this.headers
    });
  }
}

// Usage in component
this.adminStatisticsService.getDashboardStatistics().subscribe(
  (response) => {
    if (response.success) {
      const stats = response.data;
      console.log('Today Recharge:', stats.recharge_statistics.today);
      console.log('This Month Recharge:', stats.recharge_statistics.this_month);
      console.log('New Users Today:', stats.user_statistics.today_new_users);
      console.log('Top Users:', stats.top_users.by_recharge_amount);
    }
  },
  (error) => {
    console.error('Error:', error);
  }
);
```

### User Recharge Details

```typescript
getUserRechargeDetails(params?: {
  start_date?: string;
  end_date?: string;
  user_type?: string;
  sort_by?: string;
  sort_order?: string;
  per_page?: number;
}): Observable<any> {
  let queryParams = new HttpParams();
  
  if (params) {
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        queryParams = queryParams.set(key, params[key].toString());
      }
    });
  }

  return this.http.get(`${this.apiUrl}/admin/user/recharge-details`, {
    headers: this.headers,
    params: queryParams
  });
}

// Usage
// Get all recharge details
this.adminStatisticsService.getUserRechargeDetails().subscribe(
  (response) => {
    if (response.success) {
      console.log('Recharge Details:', response.data);
      console.log('Pagination:', response.pagination);
    }
  }
);

// Get recharge details for this month
const today = new Date();
const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);

this.adminStatisticsService.getUserRechargeDetails({
  start_date: firstDay.toISOString().split('T')[0],
  end_date: lastDay.toISOString().split('T')[0],
  sort_by: 'total_recharge_amount',
  sort_order: 'desc',
  per_page: 20
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('This Month Recharge Details:', response.data);
    }
  }
);
```

### Top Users by Recharge

```typescript
getTopUsersByRecharge(params?: {
  sort_by?: 'amount' | 'count';
  limit?: number;
  start_date?: string;
  end_date?: string;
}): Observable<any> {
  let queryParams = new HttpParams();
  
  if (params) {
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        queryParams = queryParams.set(key, params[key].toString());
      }
    });
  }

  return this.http.get(`${this.apiUrl}/admin/user/top-users`, {
    headers: this.headers,
    params: queryParams
  });
}

// Usage
// Top 10 users by amount
this.adminStatisticsService.getTopUsersByRecharge({
  sort_by: 'amount',
  limit: 10
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('Top Users by Amount:', response.data);
    }
  }
);

// Top 20 users by count
this.adminStatisticsService.getTopUsersByRecharge({
  sort_by: 'count',
  limit: 20
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('Top Users by Count:', response.data);
    }
  }
);
```

---

## React/Next.js Examples

### Dashboard Statistics

```javascript
const getDashboardStatistics = async (adminToken) => {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/admin/user/dashboard-statistics', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        data: data.data
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage in component
const [stats, setStats] = useState(null);

useEffect(() => {
  const adminToken = localStorage.getItem('admin_token');
  getDashboardStatistics(adminToken).then(result => {
    if (result.success) {
      setStats(result.data);
    }
  });
}, []);
```

### User Recharge Details

```javascript
const getUserRechargeDetails = async (adminToken, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/user/recharge-details${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        data: data.data,
        pagination: data.pagination
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Get all recharge details
getUserRechargeDetails(adminToken).then(result => {
  if (result.success) {
    console.log('Recharge Details:', result.data);
  }
});

// Get this month's recharge details
const today = new Date();
const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);

getUserRechargeDetails(adminToken, {
  start_date: firstDay.toISOString().split('T')[0],
  end_date: lastDay.toISOString().split('T')[0],
  sort_by: 'total_recharge_amount',
  sort_order: 'desc',
  per_page: 20
}).then(result => {
  if (result.success) {
    console.log('This Month Recharge:', result.data);
  }
});
```

### Top Users by Recharge

```javascript
const getTopUsersByRecharge = async (adminToken, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/user/top-users${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        data: data.data
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Top 10 by amount
getTopUsersByRecharge(adminToken, {
  sort_by: 'amount',
  limit: 10
}).then(result => {
  if (result.success) {
    console.log('Top Users by Amount:', result.data);
  }
});

// Top 20 by count
getTopUsersByRecharge(adminToken, {
  sort_by: 'count',
  limit: 20
}).then(result => {
  if (result.success) {
    console.log('Top Users by Count:', result.data);
  }
});
```

---

## Data Structure

### Recharge Statistics

```typescript
interface RechargeStatistics {
  today: {
    total_amount: number;
    total_count: number;
    total_credited: number;
  };
  this_month: {
    total_amount: number;
    total_count: number;
    total_credited: number;
  };
  all_time: {
    total_amount: number;
    total_count: number;
    total_credited: number;
  };
}
```

### User Statistics

```typescript
interface UserStatistics {
  today_new_users: number;
  this_month_new_users: number;
  total_users: number;
  verified_users: number;
}
```

### User Recharge Detail

```typescript
interface UserRechargeDetail {
  user_id: number;
  user: {
    id: number;
    email: string;
    phone_number: string;
    name: string;
    user_type: 'user' | 'distributor';
    wallet_balance: number;
  };
  total_recharge_amount: number;
  total_credited_amount: number;
  recharge_count: number;
  first_recharge_date: string;
  last_recharge_date: string;
}
```

---

## Use Cases

### 1. Dashboard Overview

Display key metrics on admin dashboard:
- Today's total recharge amount and count
- This month's recharge statistics
- New users today and this month
- Top 10 users by recharge amount

### 2. User Analysis

Analyze individual user recharge patterns:
- Who recharges the most
- Recharge frequency
- Total amount recharged per user
- First and last recharge dates

### 3. Performance Tracking

Track platform performance:
- Monthly recharge trends
- User growth metrics
- Top performing users
- Revenue analysis

### 4. Reporting

Generate reports for management:
- Export user recharge details
- Filter by date range
- Filter by user type
- Sort by various criteria

---

## Error Handling

### Common Error Scenarios

1. **Unauthorized Access (401)**
   - Status: 401
   - Message: "Unauthorized. Admin access required."
   - Solution: Ensure valid admin token is provided

2. **Invalid Date Format (422)**
   - Status: 422
   - Message: "Validation error"
   - Solution: Use YYYY-MM-DD format for dates

3. **Invalid Parameters (422)**
   - Status: 422
   - Message: "Validation error"
   - Solution: Check parameter values and types

---

## Best Practices

1. **Caching**: Consider caching dashboard statistics for better performance
2. **Pagination**: Always use pagination for large datasets
3. **Date Filtering**: Use date ranges to limit data and improve performance
4. **Error Handling**: Implement proper error handling in frontend
5. **Loading States**: Show loading indicators during API calls
6. **Token Management**: Store and refresh admin tokens securely

---

## Integration Checklist

- [ ] Implement dashboard statistics display
- [ ] Add user recharge details table with filters
- [ ] Create top users leaderboard
- [ ] Add date range picker for filtering
- [ ] Implement pagination for recharge details
- [ ] Add sorting functionality
- [ ] Handle loading and error states
- [ ] Add export functionality (if needed)
- [ ] Test with various date ranges
- [ ] Test with different user types
- [ ] Verify admin authentication

---

## Support

For issues or questions regarding the Admin Statistics API, please contact the development team.

---

**Last Updated:** December 2025


