# Service Order System

> Covers the full lifecycle for both **Client** and **Provider** sides, including the revision system, Golden Guarantee, auto-complete, and order reports.

---

## Order Number Format

| Type | Format | Example |
|---|---|---|
| Service Order | `NK-SXXXX#` | `NK-S0042#` |
| Urgent Order | `NK-UXXXX#` | `NK-U0015#` |

Prefixes make it structurally impossible to have duplicate order numbers across the two tables.

---

## Full Lifecycle

```
pending
  ├─ Provider accepts        → accepted
  ├─ Provider rejects        → rejected (client refunded)
  ├─ Pending timeout fires   → cancelled (client refunded)
  └─ Scheduled slot passes   → cancelled (client refunded)

accepted
  ├─ Provider starts work    → active
  └─ Client cancels          → cancelled (client refunded)

active
  ├─ Provider uploads files  → (status stays active)
  └─ Provider finishes       → provider_finished

provider_finished
  ├─ Client confirms         → completed (provider paid, chat closed)
  ├─ Client requests revision → active (revision round recorded)
  ├─ Client files GG*        → pending_admin_review
  └─ Auto-complete fires     → completed (provider paid, chat closed)

pending_admin_review
  ├─ Admin approves complaint → active (provider must redo, redo_count++)
  └─ Admin rejects complaint  → completed (provider paid, note sent to client)

completed / cancelled / rejected  → Terminal states
```

\* GG only available after all revision requests exhausted (`revision_count >= max_revision_requests` setting).

---

## Configurable Settings

| Key | Default | Description |
|---|---|---|
| `service_order_pending_timeout_minutes` | `60` | Auto-cancel if no provider accepts within X minutes |
| `service_order_auto_complete_minutes` | `1440` | Auto-complete if client takes no action after provider finishes (24h) |
| `golden_guarantee_window_minutes` | `2880` | Window within which client can file GG after provider finishes (48h) |
| `max_revision_requests` | `1` | How many revision rounds the client gets before GG unlocks |
| `vat_percentage` | `15.0` | VAT applied to all orders |

**Constraint enforced by settings validation:**
`auto_complete_minutes` must be greater than `golden_guarantee_window_minutes` — the system rejects configuration where the order could auto-close while GG is still fileable.

---

## Client Endpoints

> Base: `{{base_url}}/api/v1/client/orders/service`  
> All require: `Authorization: Bearer {token}`

| Method | Endpoint | Description |
|---|---|---|
| POST | `/` | Create order (pay + dispatch) |
| GET | `/` | List own orders. Filter: `?status=active\|cancelled\|pending…` |
| GET | `/{id}` | Show order details |
| PATCH | `/{id}/cancel` | Cancel (only while `pending` or `accepted`) |
| POST | `/{id}/confirm` | Confirm completion → provider paid |
| POST | `/{id}/request-revision` | Request revision (while `provider_finished`, revisions remaining) |
| POST | `/{id}/golden-guarantee` | File GG complaint (while `provider_finished`, revisions exhausted, within GG window) |
| POST | `/{id}/review` | Submit review (after `completed`) |
| POST | `/{id}/report` | Report an order problem |
| POST | `/apply-coupon` | Preview pricing with broker code |

### Create Order Payload

```json
{
  "service_id": 3,
  "provider_id": 42,
  "scheduled_date": "2026-09-20",
  "scheduled_time": "14:00",
  "form_data": [
    { "field_key": "case_type",    "answer": "civil" },
    { "field_key": "case_details", "answer": "Need help with contract dispute" },
    { "field_key": "attachments",  "answer": [101, 102] }
  ],
  "payment_method": "wallet",
  "broker_code": "BRK-XYZ123"
}
```

### Request Revision Payload

```json
{
  "revision_note": "The penalty clause percentage is wrong — should be 10% not 5%."
}
```

### Golden Guarantee Payload

```json
{
  "reason": "output_not_meeting_specs",
  "description": "The delivered contract is missing the arbitration clause we discussed.",
  "attachments": [201, 202]
}
```

**Reason values:** `output_not_meeting_specs` · `delivery_delay` · `error_in_output` · `incomplete_service` · `other`

### Review Payload

```json
{
  "rating": 5,
  "response_speed_rating": 5,
  "interaction_quality_rating": 4,
  "output_clarity_rating": 5,
  "general_satisfaction_rating": 5,
  "comment": "Excellent work, very professional."
}
```

### Report Payload

```json
{
  "reason": "no_show",
  "description": "Provider accepted the order but never showed up or responded."
}
```

**Reason values:** `no_show` · `fraud` · `wrong_service` · `harassment_or_abuse` · `other`

### Show Order Response Keys

```json
{
  "id": 1,
  "order_number": "NK-S0001#",
  "status": "provider_finished",
  "status_trans": "Awaiting Confirmation",
  "scheduled_date": "2026-09-20",
  "scheduled_time": "14:00",
  "payment_method": "wallet",
  "paid_at": 1725379200,
  "accepted_at": 1725379300,
  "started_at": 1725379500,
  "provider_finished_at": 1725380000,
  "completed_at": null,
  "cancelled_at": null,
  "rejected_at": null,
  "created_at": 1725379200,

  "pricing_details": {
    "service_price": 230.00,
    "discount_amount": 20.00,
    "vat_percentage": 15.0,
    "vat_amount": 31.50,
    "total_price": 241.50
  },

  "completion_note": "Added the penalty clause in section 5 as requested.",

  "revision": {
    "count": 1,
    "note": "Penalty clause should be 10%, not 5%.",
    "requested_at": 1725379800
  },

  "golden_guarantee": {
    "is_submitted": false,
    "reason": null,
    "description": null,
    "filed_at": null,
    "redo_count": 0,
    "admin_review_notes": null,
    "admin_reviewed_at": null,
    "deadline": 1725554800
  },

  "auto_complete_at": 1725466400,

  "work_files": [
    { "id": 201, "url": "https://...", "type": "file", "option": "provider_work_files", "is_single": false }
  ],

  "chat_id": 5,

  "is_reviewed": false,

  "can_cancel": false,
  "can_confirm": true,
  "can_request_revision": true,
  "can_file_gg": false,
  "can_review": false,

  "service_data": { "id": 3, "title": "Legal Consultation", "image": "https://..." },
  "provider_data": {
    "id": 42,
    "full_name": "Ahmed Ali",
    "avatar": "https://...",
    "provider_type": "Lawyer",
    "avg_rating": 4.8,
    "reviews_count": 34
  }
}
```

---

## Provider Endpoints

> Base: `{{base_url}}/api/v1/provider/service-orders`  
> All require: `Authorization: Bearer {token}`

| Method | Endpoint | Description |
|---|---|---|
| GET | `/` | List all orders. Filter: `?status=` |
| GET | `/{id}` | Show order details |
| POST | `/{id}/accept` | Accept pending order (blocked if scheduled time passed) |
| POST | `/{id}/reject` | Reject + auto-refund client |
| POST | `/{id}/start` | Start work (client can no longer cancel) |
| POST | `/{id}/upload-files` | Upload work files (while `active`) |
| POST | `/{id}/finish` | Mark finished (requires at least one file) |

### Finish Payload (optional note)

```json
{
  "completion_note": "Contract is ready. I've added all clauses including section 7."
}
```

### Upload Files Payload

```json
{
  "files": [201, 202, 203]
}
```

> Files must be pre-uploaded via `POST /attachment` with `option: provider_work_files`.

---

## Revision Audit Trail

Every revision round is recorded in `order_revisions`:

| Field | Description |
|---|---|
| `round` | Round number (1-based) |
| `client_note` | What the client asked to fix |
| `revision_requested_at` | When client requested it |
| `completion_note` | Provider's note when re-finishing |
| `provider_finished_at` | When provider re-delivered |
| `provider_responded` | `true` if provider has re-finished this round |

---

## Chat

A chat is automatically created between client and provider when the order is created (paid). It closes when the order reaches `completed` status.

| Endpoint | Description |
|---|---|
| `GET /client/chats` | List all chats |
| `GET /client/chats/{chatId}` | Paginated messages (`?per_page=20`), marks incoming as read |
| `POST /client/chats/{chatId}/messages` | Send message (blocked if chat is closed) |

---

## Urgent Order Reports

> Urgent orders have no GG but clients can report problems.

```
POST /client/orders/urgent/{id}/report
```

Same payload as service order reports.
