# Provider API Documentation

## Statistics Endpoints

### Provider Statistics Overview
**GET** `/api/v1/provider/statistics/overview`

Comprehensive provider dashboard statistics including service orders, urgent orders, financial data, ratings, and team performance.

**Response Structure:**
```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": {
    "service_orders": {
      "totals": {
        "all": 125,
        "pending": 4,
        "accepted": 8,
        "active": 12,
        "provider_finished": 3,
        "pending_admin_review": 1,
        "completed": 89,
        "cancelled": 6,
        "rejected": 2
      },
      "rates": {
        "completion_rate": 71.2,
        "cancellation_rate": 6.4
      },
      "volume_chart": [
        {
          "period": "2026-08",
          "in_progress": 15,
          "completed": 23,
          "cancelled": 2
        },
        {
          "period": "2026-09",
          "in_progress": 18,
          "completed": 28,
          "cancelled": 1
        }
      ]
    },
    "urgent_orders": {
      "totals": {
        "all": 45,
        "searching_for_provider": 2,
        "accepted": 5,
        "completed": 35,
        "cancelled": 3
      },
      "rates": {
        "completion_rate": 77.8,
        "cancellation_rate": 6.7
      },
      "volume_chart": [
        {
          "period": "2026-08",
          "active": 3,
          "completed": 8,
          "cancelled": 1
        },
        {
          "period": "2026-09",
          "active": 4,
          "completed": 12,
          "cancelled": 0
        }
      ]
    },
    "financials": {
      "wallet_balance": 15750.00,
      "withdrawal_balance": 12500.00,
      "pending_earnings": 2800.00,
      "total_wallet_credits": 45600.00,
      "total_wallet_debits": 32850.00,
      "lifetime_earnings": {
        "service_orders": 89500.00,
        "urgent_orders": 23400.00,
        "combined": 112900.00
      },
      "withdrawals": {
        "pending_count": 1,
        "approved_count": 15,
        "rejected_count": 0,
        "pending_amount": 5000.00,
        "approved_amount": 75000.00
      },
      "earnings_chart": [
        {
          "period": "2026-08",
          "service_order_earnings": 8500.00,
          "urgent_order_earnings": 2100.00,
          "total_earnings": 10600.00
        },
        {
          "period": "2026-09",
          "service_order_earnings": 9200.00,
          "urgent_order_earnings": 2800.00,
          "total_earnings": 12000.00
        }
      ]
    },
    "ratings": {
      "average_rating": 4.7,
      "reviews_count": 89,
      "rating_distribution": {
        "5": 65,
        "4": 18,
        "3": 4,
        "2": 1,
        "1": 1
      }
    },
    "activity": {
      "latest_service_orders": [
        {
          "id": 123,
          "order_number": "NK-S0123#",
          "client": "Ahmed Al-Rashid",
          "status": "completed",
          "amount": 2500.00,
          "created_at": 1726502400
        }
      ],
      "latest_urgent_orders": [
        {
          "id": 456,
          "order_number": "NK-U0567#",
          "client": "Fatima Al-Zahra",
          "status": "active",
          "amount": 1200.00,
          "created_at": 1726488000
        }
      ]
    },
    "team_performance": {
      "teams_count": 2,
      "teams": [
        {
          "team_id": 12,
          "team_name": "Legal Experts",
          "is_leader": true,
          "joined_at": "2026-09-15T11:21:58.000000Z",
          "team_performance": {
            "total_orders": 45,
            "completed_orders": 42,
            "completion_rate": 93.3
          },
          "individual_vs_team": {
            "individual_orders": 28,
            "individual_completed": 25,
            "individual_completion_rate": 89.3,
            "team_orders": 45,
            "prefers_team_work": true
          }
        }
      ]
    }
  }
}
```

**Response includes:**
- Service order analytics with completion rates
- Urgent order performance metrics
- Financial statistics (wallet balance, lifetime earnings, withdrawal summary)
- Rating distribution and review analytics
- Recent activity summary
- Team performance data (if provider is team member)

### Team Performance Statistics
**GET** `/api/v1/provider/statistics/team-performance`

Detailed team performance analytics for providers who are team members.

**Features:**
- Individual vs team order comparison
- Team completion rates and performance metrics
- Leadership status and team contribution analysis
- Multi-team membership support

**Response Structure:**
```json
{
  "teams_count": 2,
  "teams": [
    {
      "team_id": 12,
      "team_name": "Legal Experts",
      "is_leader": true,
      "joined_at": "2026-09-15T11:21:58.000000Z",
      "team_performance": {
        "total_orders": 45,
        "completed_orders": 42,
        "completion_rate": 93.3
      },
      "individual_vs_team": {
        "individual_orders": 28,
        "team_orders": 45,
        "prefers_team_work": true
      }
    }
  ]
}
```

## Team Management

### Team Display Endpoints
**GET** `/api/v1/provider/teams`

List all teams the provider belongs to with filtering and sorting options.

**Available Filters:**
- `service_id` - Filter by service ID (integer)
- `is_active` - Filter by team status (true/false)
- `am_leader` - Filter teams where you are the leader (true/false)

**Available Sorting:**
- `sort_by` - Sort field: name, price, created_at, members_count (default: name)
- `sort_order` - Sort direction: asc, desc (default: asc)

**Example Request:**
```
GET /api/v1/provider/teams?service_id=5&am_leader=true&sort_by=members_count&sort_order=desc
```

**GET** `/api/v1/provider/teams/{id}`

Detailed team information including members, schedules, and service data.

**Response includes:**
- Complete team profile with service details (object format, not just ID)
- Team member information with leadership indicators
- Clean schedule format (without seconds, no timestamps)
- Team performance metrics
- Leadership responsibilities if applicable

### Team Schedule Format
Schedules are returned in clean format:
```json
{
  "schedules": [
    {
      "id": 12,
      "day_of_week": "sunday",
      "start_time": "11:11",
      "end_time": "12:11",
      "is_active": true
    }
  ]
}
```

## Order Management

### Order Types and Team Integration

Orders now include `order_type` field indicating handling method:
- `individual` - Provider handles order independently
- `team` - Team-based order with collaborative handling

### Individual Orders
When `order_type` is "individual":
- Provider has full control and responsibility
- Direct client communication
- Individual performance tracking
- Standard commission structure

### Team Orders
When `order_type` is "team":
- **Team Leader Role**: If you are the team leader, you manage the entire order process including:
  - Coordinating with team members
  - Primary client communication point
  - Order completion responsibility
  - Payment and delivery management
- **Team Member Role**: If you are a team member, you collaborate under the leader's coordination
- Team data is included in order responses for context
- Shared responsibility model with leader oversight

### Order Data Structure

### Order Data Structure

**Order Categorization System:**

All orders now include clear categorization with two key fields:

- **`order_category`**: Indicates the system type
  - `"service_order"` - Regular service orders (support both team and individual handling)
  - `"urgent_order"` - Emergency/urgent orders (always individual handling only)

- **`order_type`**: Indicates the handling method
  - `"team"` - Order handled by a team (only possible for service_orders)
  - `"individual"` - Order handled by individual provider

**Order Type Matrix:**
| Order Category | Possible Order Types | Description |
|---------------|---------------------|-------------|
| `service_order` | `team` or `individual` | Full flexibility in handling method |
| `urgent_order` | `individual` only | Always requires immediate individual response |

**Individual Order Response:**
```json
{
  "id": 123,
  "order_category": "service_order",
  "order_type": "individual",
  "provider_data": {
    "id": 456,
    "full_name": "Your Name",
    "type": "individual"
  },
  "team_data": null,
  "management_note": "You have full control over this individual order"
}
```

**Team Order Response (Leader):**
```json
{
  "id": 124,
  "order_category": "service_order",
  "order_type": "team",
  "provider_data": {
    "id": 789,
    "full_name": "Your Name",
    "type": "team_leader"
  },
  "team_data": {
    "id": 12,
    "name": "Legal Team Alpha",
    "members_count": 5,
    "your_role": "leader"
  },
  "management_note": "You manage this team order as the team leader with full control"
}
```

**Team Order Response (Member):**
```json
{
  "id": 125,
  "order_category": "service_order",
  "order_type": "team",
  "provider_data": {
    "id": 999,
    "full_name": "Team Leader Name",
    "type": "team_leader"
  },
  "team_data": {
    "id": 12,
    "name": "Legal Team Alpha",
    "members_count": 5,
    "your_role": "member"
  },
  "management_note": "This team order is managed by the team leader, you collaborate as a member"
}
```

**Urgent Order Response (Always Individual):**
```json
{
  "id": 126,
  "order_category": "urgent_order",
  "order_type": "individual",
  "provider_data": {
    "id": 456,
    "full_name": "Your Name",
    "type": "individual"
  },
  "team_data": null,
  "management_note": "Urgent orders require immediate individual response and cannot be handled by teams"
}
```

## Team Leadership Responsibilities

### As Team Leader
When you are a team leader:
- You receive all team-based order requests
- You coordinate task distribution among team members
- You manage client communication and expectations
- You oversee order completion and quality control
- You handle payment processing and team compensation
- You can access all team performance statistics
- You make final decisions on order acceptance and delivery

### As Team Member
When you are a team member:
- You collaborate on orders assigned by the team leader
- You contribute to team deliverables under leader coordination
- You can view team orders but the leader has primary control
- Your individual statistics are tracked separately from team performance
- You support the team leader in achieving order completion

## Financial Integration

### Team vs Individual Earnings
- Individual orders contribute to personal earnings statistics
- Team orders contribute to team performance metrics
- Commission rates may vary between individual and team orders
- Package discounts apply differently for individual vs team orders

### Package Discount Information
Orders include package discount details:
- `package_discount_amount` - Applied discount amount
- `package_discount_percentage` - Discount percentage from active package

## Performance Tracking

### Individual Performance
- Personal completion rates and client satisfaction
- Individual order volume and earnings
- Direct client feedback and ratings
- Personal skill development metrics

### Team Performance
- Collaborative order completion rates
- Team efficiency and coordination metrics
- Leadership effectiveness (for team leaders)
- Member contribution analysis

## Order Request Flow

### Individual Orders
1. Client submits order request
2. System matches with available individual providers
3. Provider receives direct order notification
4. Provider accepts and manages order independently
5. Direct completion and payment processing

### Team Orders
1. Client submits team order request
2. System matches with available teams
3. Team leader receives order notification
4. Leader coordinates with team members for acceptance
5. Leader manages order distribution and completion
6. Leader handles client communication and final delivery
7. Payment processed through leader with team compensation

## API Response Standards

All endpoints return consistent response format:
```json
{
  "status": "success", // or "fail" for errors
  "message": "Data retrieved successfully",
  "data": {
    // Response data
  }
}
```

**Note:** The API now uses string values for status (`"success"` or `"fail"`) instead of boolean values for consistency.

Team-related data is always presented in clean, professional format without unnecessary complexity, focusing on clear role definitions and management responsibilities.