# Company Contracts API — Integration Guide

How a company app creates a contract. Creation is **single-shot**: billing
cycle, every branch with its services (each service with its own
sub-services and visit count), and the signed document all go in one
request. There is no draft step and no update endpoint afterwards.

## Create contract

| | |
|---|---|
| **Method** | `POST` |
| **Path** | `/api/v1/company/contracts` |
| **Route name** | `company.contracts.store` |
| **Controller action** | `App\Http\Controllers\Api\V1\Company\ContractController@store` |
| **Middleware** | `api`, `set_locale`, `cors`, `auth:api`, `user:company`, `active` |
| **Success status** | `201 Created` |
| **Error statuses** | `422` (validation, invalid commercial register, missing signed media), `401`, `403` |

**Headers**

```
Accept: application/json
Content-Type: application/json
Accept-Language: en | ar
Authorization: Bearer {token}
```

### Request payload

```json
{
  "billing_cycle": "monthly",
  "currency": "SAR",
  "branches": [
    {
      "branch_id": 13,
      "service_ids": [
        { "id": 37, "sub_service_ids": [40, 41, 39, 45], "visits_allowed": 3 },
        { "id": 38, "sub_service_ids": [46, 47, 48, 49], "visits_allowed": 2 }
      ]
    }
  ],
  "signed_media_id": 170
}
```

Visits are set **per service**, not per branch: here service 37 gets 3 visits
and service 38 gets 2.

| Field | Type | Required | Notes |
|---|---|---|---|
| `billing_cycle` | string | yes | `monthly`, `quarterly` or `annual`. Also sets the default term when no dates are sent. |
| `currency` | string | no | 3 letters. Defaults to `SAR`. |
| `start_date` | date | no | `Y-m-d`, today or later. Defaults to today. |
| `end_date` | date | no | After `start_date`. Defaults to start + 1 / 3 / 12 months by `billing_cycle`. |
| `notes` | string | no | Max 1000 chars. |
| `branches` | array | yes | At least one entry. |
| `branches[].branch_id` | integer | yes | Must be one of the **authenticated company's own** branches. |
| `branches[].service_ids` | object[] | yes | At least one entry. One object per parent service booked at this branch. |
| `branches[].service_ids[].id` | integer | yes | Parent category id (e.g. 37). Must exist in `categories`. |
| `branches[].service_ids[].sub_service_ids` | integer[] | yes | Child services chosen under that parent (e.g. 40, 41, 39, 45). At least one; each must exist in `categories`. |
| `branches[].service_ids[].visits_allowed` | integer | yes | Visits for **this service at this branch**, minimum 1. |
| `signed_media_id` | integer | yes | `id` of an **unattached** upload of the signed contract PDF (see below). |

`total_amount` is **never sent** — the server computes it.

### Uploading the signed document first

1. (Optional) `GET /api/v1/company/contracts/{id}/template` returns the contract
   template file for the company to sign.
2. Upload the signed PDF with `POST /media` (multipart, field `file`). The
   response `data.id` is the `signed_media_id`.
3. Use that id in the create request. Once the contract is created the
   upload is attached to it and cannot be reused by another contract.

### How `total_amount` is calculated

Each service is priced per visit, then multiplied by its own visit count:

```
service total  = visits_allowed × (sum of that service's sub-service prices)
total_amount   = sum of service totals across every branch
```

- A sub-service's price is its `contract_price`, falling back to `price`,
  then `0`.
- Only sub-services whose **parent is the service they were sent under** are
  counted. A `sub_service_id` that belongs to a different parent is ignored,
  not billed.
- Contract-level `visits_allowed` is the sum of every service's
  `visits_allowed` across all branches.

Example with the payload above:

```
service 37 = 3 × (price(40) + price(41) + price(39) + price(45))
service 38 = 2 × (price(46) + price(47) + price(48) + price(49))
total_amount = service 37 + service 38        visits_allowed = 3 + 2 = 5
```

### Success response — `201`

```json
{
  "status": "success",
  "message": "Contract created successfully.",
  "data": {
    "id": 12,
    "contract_number": "CTR-2026-000012",
    "start_date": "2026-10-04",
    "end_date": "2026-11-04",
    "billing_cycle": "monthly",
    "visits_allowed": 5,
    "visits_consumed": 0,
    "remaining_visits": 5,
    "total_amount": "…",
    "currency": "SAR",
    "status": "pending_approval",
    "status_label": "Processing",
    "signed_pdf_path": "https://…/signed.pdf",
    "signed_at": "2026-10-04T10:00:00+00:00",
    "branches": [{ "id": 13, "name": "…", "address_text": "…" }],
    "categories": [
      { "id": 37, "name": "…", "image": "…", "services": [] },
      { "id": 38, "name": "…", "image": "…", "services": [] }
    ],
    "branch_services": [
      {
        "branch_id": 13,
        "branch_name": "…",
        "address_text": "…",
        "visits_allowed": 5,
        "services": [
          { "id": 37, "name": "…", "image": "…", "services": [], "visits_allowed": 3 },
          { "id": 38, "name": "…", "image": "…", "services": [], "visits_allowed": 2 }
        ]
      }
    ],
    "visits": { "allowed": 5, "consumed": 0, "remaining": 5 },
    "signatures": [{ "id": 1, "signer_type": "company", "signed_at": "…" }],
    "renewal_requests": []
  }
}
```

Values shown as `…` depend on your data; the shape comes from
`ContractDetailsResource`. In `branch_services`, the branch-level
`visits_allowed` is the sum of its services' visits, and each service entry
carries its own `visits_allowed`. The contract starts at **`pending_approval`**
— an admin approves it before it becomes `active`.

### Persisted data caveat

Only each service's parent `id` and `visits_allowed` are stored (one row per
branch + service). `sub_service_ids` are used for pricing at creation time and
are **not saved**, so the contract detail response lists the chosen parents —
with all their visible child services — not the exact sub-services picked.

### Error responses

All errors use the same envelope: `{ "status": "fail", "message": "...", "data": null }`.

| When | Status | Message |
|---|---|---|
| Commercial register not approved, pending, rejected or expired | 422 | Contract cannot be executed because the company's commercial register is expired or not approved. |
| `signed_media_id` points to a missing upload | 422 | Signed document not found in media. |
| Field validation fails (missing field, old flat `service_ids: [37, 42]` shape, `branch_id` of another company, `signed_media_id` already attached, …) | 422 | First validation message, localized by `Accept-Language`. |
| Missing or invalid token | 401 | — |
| Not an active company account | 403 | — |

## Related endpoints

| Method | Path | Purpose |
|---|---|---|
| `GET` | `/api/v1/company/contracts` | Paginated list; `status`, `per_page` (max 100) |
| `GET` | `/api/v1/company/contracts/{id}` | Full details |
| `DELETE` | `/api/v1/company/contracts/{id}` | Only in deletable states |
| `GET` | `/api/v1/company/contracts/{id}/template` | Contract template file |
| `POST` | `/api/v1/company/contracts/{id}/sign` | Re-sign (`signed_media_id`), for `draft` / `pending_signature` contracts |
| `POST` | `/api/v1/company/contracts/{id}/renew` | Request renewal (`note` optional), for `active` / `expired` |

## Source

- Service: `app/Services/Company/ContractService.php` (`store`, `calculateTotalAmount`)
- Validation: `app/Http/Requests/Company/Contract/StoreContractRequest.php`
- Response: `app/Http/Resources/Company/Contract/ContractDetailsResource.php`
