# Admin Negotiation System Guide

## Overview
The negotiation system allows clients and providers to negotiate the price of service orders before payment and order activation. Admins can configure negotiation settings and monitor the negotiation process through service order details.

---

## Table of Contents
1. [Negotiation Settings](#negotiation-settings)
2. [Notification Types](#notification-types)
3. [Service Order Negotiation Flow](#service-order-negotiation-flow)
4. [Admin Monitoring](#admin-monitoring)
5. [API Reference](#api-reference)

---

## Negotiation Settings

Admins can configure the negotiation behavior system-wide through the **Settings** module. Two key settings control the negotiation flow:

### 1. Negotiation Max Rounds (`negotiation_max_rounds`)
- **Type**: Integer
- **Default**: `3`
- **Description**: Maximum number of counter-offers allowed across both parties (client + provider combined). Each counter-offer increments the round counter.
- **Special Value**: `0` = unlimited rounds
- **Validation**: 
  - Arabic: "الحد الأقصى لجولات التفاوض"
  - English: "Negotiation Max Rounds"

### 2. Negotiation Timeout Minutes (`negotiation_timeout_minutes`)
- **Type**: Integer
- **Default**: `60` (1 hour)
- **Description**: Time limit (in minutes) for each party to respond to an offer. If the time expires without a response, the order is automatically cancelled.
- **Special Value**: `0` = no timeout (disabled)
- **Validation**:
  - Arabic: "مهلة التفاوض"
  - English: "Negotiation Timeout"

### How to Configure
Navigate to:
```
Admin Dashboard → Settings → Order Settings (or appropriate group)
```

Update the values through:
- **Endpoint**: `POST /admin/settings/group/{group}` or `POST /admin/settings`
- **Keys**: `negotiation_max_rounds`, `negotiation_timeout_minutes`

---

## Notification Types

### New Contract Notification Type
The system now includes a **contracts** notification category for provider contract-related notifications (separate from service order negotiations).

**Contract Notification Types**:
- `contract_sent` - Provider receives notification when admin sends/resends contract
- `contract_accepted` - Admins receive notification when provider accepts contract
- `contract_rejected` - Admins receive notification when provider rejects contract
- `contract_expired` - Provider receives notification when contract expires

**Contract Endpoints**:
- **Admin**: `GET /admin/provider-contracts` - List all provider contracts
- **Provider**: `GET /provider/contracts` - List provider's contracts
- **Provider**: `POST /provider/contracts/{id}/accept` - Accept contract
- **Provider**: `POST /provider/contracts/{id}/reject` - Reject contract

These contract notifications use the **SYSTEM** notification type and are separate from the order negotiation system.

---

## Service Order Negotiation Flow

### Order Statuses During Negotiation
When an order enters negotiation, it has the following attributes:

| Field | Description |
|-------|-------------|
| `status` | `pending_negotiation` |
| `negotiation_turn` | `'provider'` or `'client'` - indicates whose turn it is to respond |
| `negotiation_round` | Integer starting at `1`, increments with each counter-offer |
| `negotiation_price` | Current offer price on the table |
| `negotiation_accepted_at` | Timestamp when the offer was accepted by one party (waiting for other party's payment) |

### Negotiation Workflow

```
Client Creates Order with Price
         ↓
   [pending_negotiation]
   negotiation_turn = 'provider'
   negotiation_round = 1
         ↓
    ┌─── Provider Options ───┐
    │                        │
  Accept                  Counter                Reject
    │                        │                     │
    ↓                        ↓                     ↓
Client's turn          Round increments      [cancelled]
to pay              Client's turn
    │                        │
    ↓                        ↓
  [Client Pays]      ┌─── Client Options ───┐
    │                │                       │
    ↓              Accept                Counter              Reject
[active]            │                       │                  │
                    ↓                       ↓                  ↓
              [Client Pays]           Round increments     [cancelled]
                    │                Provider's turn
                    ↓                       │
                [active]                    ↓
                                    (Loop continues until
                                     max rounds reached)
```

### Round Limit Enforcement
- When `negotiation_max_rounds` is reached:
  - **Provider**: Must accept or reject (cannot counter)
  - **Client**: Must accept (and pay) or reject (cannot counter)
  - Attempting to counter after max rounds throws error: *"Maximum negotiation rounds reached. You must accept or reject the current offer."*

### Price Range Validation
All negotiation prices (initial offer + counters) must be within the service's configured price range:
- Must be ≥ `service.price_from` (if set)
- Must be ≤ `service.price_to` (if set)

Error messages:
- Below minimum: *"The agreed price must be at least X SAR for this service."*
- Above maximum: *"The agreed price cannot exceed X SAR for this service."*

### Auto-Cancellation on Timeout
If `negotiation_timeout_minutes` > 0:
- A background job `AutoCancelExpiredNegotiation` is dispatched with the configured delay
- If the party whose turn it is doesn't respond in time, the order is automatically cancelled
- Both parties receive timeout notification

---

## Admin Monitoring

### Viewing Negotiation Details
Admins can view the full negotiation history on the service order detail page:

**Endpoint**: `GET /admin/service-orders/{order}`

**Response includes**:
```json
{
  "id": 123,
  "status": "pending_negotiation",
  "negotiation_turn": "client",
  "negotiation_round": 2,
  "negotiation_price": 750.00,
  "negotiation_accepted_at": null,
  "negotiation_offers": [
    {
      "id": 1,
      "service_order_id": 123,
      "made_by": "client",
      "price": 800.00,
      "round": 1,
      "created_at": "2026-10-28T10:00:00Z"
    },
    {
      "id": 2,
      "service_order_id": 123,
      "made_by": "provider",
      "price": 750.00,
      "round": 2,
      "created_at": "2026-10-28T10:15:00Z"
    }
  ],
  ...
}
```

### Key Admin Insights
Admins can see:
1. **Current negotiation status** - who's turn, what round, current price
2. **Full offer history** - all counter-offers from both parties with timestamps
3. **Acceptance status** - whether one party has accepted (waiting for payment)
4. **Timeout tracking** - when the negotiation started and when it will expire

---

## API Reference

### Negotiation Endpoints (Not Admin-Accessible)

Admins do not directly participate in negotiations but can view the results. The actual negotiation happens between client and provider:

#### Provider Endpoints
- `POST /provider/service-orders/{id}/negotiation/accept` - Provider accepts client's offer
- `POST /provider/service-orders/{id}/negotiation/reject` - Provider rejects and cancels order
- `POST /provider/service-orders/{id}/negotiation/counter` - Provider makes counter-offer
  - **Body**: `{ "counter_price": 750.00 }`

#### Client Endpoints
- `POST /client/orders/service/{id}/negotiation/accept` - Client accepts provider's counter-offer **and pays atomically**
  - **Body**: `{ "payment_method": "wallet"|"online", "broker_code": "ABC123" (optional), ... }`
- `POST /client/orders/service/{id}/negotiation/reject` - Client rejects and cancels order
- `POST /client/orders/service/{id}/negotiation/counter` - Client makes counter-offer
  - **Body**: `{ "counter_price": 850.00 }`

### Admin Endpoints (View Only)
- `GET /admin/service-orders` - List orders (filter by `status=pending_negotiation`)
- `GET /admin/service-orders/{order}` - View order details including negotiation history
- `PUT /admin/settings` - Configure `negotiation_max_rounds` and `negotiation_timeout_minutes`

---

## Negotiation Notifications

Both parties receive real-time notifications during negotiation:

### Client Notifications (Type: `orders`)
- **Provider accepted**: *"The provider accepted your submitted offer. Please complete payment to confirm the order and get started."*
- **Provider countered**: *"The provider submitted a new offer for your order. You can review and respond to it from the order details."*
- **Provider rejected**: *"The provider was unable to accept your submitted offer at this time..."*
- **Timeout (provider didn't respond)**: *"The provider did not respond to your offer within the allowed time, so the order was automatically cancelled..."*
- **Timeout (you didn't respond)**: *"You did not respond to the provider's offer within the allowed time, so the order was automatically cancelled..."*

### Provider Notifications (Type: `orders`)
- **Client accepted**: *"The client accepted your submitted offer. Awaiting their payment to confirm the order."*
- **Client countered**: *"The client submitted a counter-offer for the order. You can review and respond to it from the order details."*
- **Client rejected**: *"The client did not accept your submitted offer at this time..."*
- **Timeout (client didn't respond)**: *"The client did not respond to your offer within the allowed time, so the order was automatically cancelled."*
- **Timeout (you didn't respond)**: *"You did not respond to the client's offer within the allowed time, so the order was automatically cancelled."*

All negotiation notifications are categorized as **ORDERS** type for filtering purposes.

---

## Best Practices

### For System Configuration
1. **Set reasonable max rounds**: 3-5 rounds prevent endless back-and-forth
2. **Balance timeout duration**: 
   - Too short (< 30 min): Users may not respond in time
   - Too long (> 24 hours): Orders remain in limbo
   - Recommended: 60-120 minutes
3. **Monitor negotiation patterns**: Review orders frequently cancelled during negotiation to identify issues
4. **Ensure service price ranges**: Set realistic `price_from` and `price_to` on services to guide negotiations

### For Monitoring
1. Check orders stuck in `pending_negotiation` status
2. Review `negotiation_offers` table for patterns (who counters more, average rounds, etc.)
3. Monitor timeout cancellations vs. explicit rejections
4. Track successful negotiation conversion rate (accepted vs. rejected/cancelled)

---

## Related Documentation
- [Service Order System](./SERVICE_ORDER_SYSTEM.md)
- [Admin API Reference](./ADMIN_API_REFERENCE_UPDATED.md)
- [Notification System](./NOTIFICATION_SYSTEM.md)
- [Settings System](./SETTINGS_SYSTEM.md)

---

**Document Version**: 1.0  
**Last Updated**: October 28, 2026  
**Feature Status**: ✅ Implemented
