# Company Visits API (Backend Reply)

## Correction on the finding

`GET /api/v1/company/visits` **did already exist** (`company.visits.index`,
undocumented — that part of the finding is fair) but only listed visits with
no `show`/`cancel` actions and a generic shape. This reply adds the missing
`show` and `cancel` endpoints and reshapes the list/details response to
match what was requested. No new routes beyond `show`/`cancel` were needed.

## Data model — read this before the endpoints

**There is no separate `Visit` entity.** A "visit" is a company job order
(`orders` table, `order_source` distinguishes individual/company/contract
visits) — this is an existing, established convention
(`Branch::hasScheduledVisits()` already treats any non-terminal order as a
scheduled visit; a prior `contract_visit_ledger` table was deliberately
dropped in favor of this). The three new/changed endpoints below all just
query/act on `Order`, scoped by `customer_id = <company user>`.

This answers several of your clarification questions directly:

- **One order = one branch = one visit.** There's no route concept —
  `from_branch`/`to_branch` don't apply. The response has a single `branch`
  object (the service-location branch). If a real pickup→dropoff route is a
  genuine future requirement, that's a schema change, not a documentation gap.
- **One visit can include multiple services** (via `OrderItem`, one row per
  service) but **only one branch**.
- **`scheduled_at` can be null** — unscheduled orders (e.g. still
  `pending`/`waiting_price`) have no date yet. Also note: the underlying
  column is date-only (`orders.scheduled_date`), there's no time-of-day
  component in the current schema — `scheduled_at` is that date rendered as
  ISO-8601 (`00:00:00` time), not a real timestamp. Flagging in case the
  calendar UI needs actual time slots — that would be a schema addition.
- **All visit statuses and lifecycle** — the existing, already-used
  `OrderStatus` enum, no new statuses invented:
  `pending → waiting_price → priced → accepted → on_the_way → start → finish → confirmed`,
  or `cancelled` from most of those. **Important naming clash**: in this
  system `confirmed` means *fully completed* (terminal, not "scheduled").
  Your doc's assumption that cancellation is allowed for "confirmed and
  scheduled" visits doesn't match this vocabulary — see the Cancel section.
- **Calendar markers**: `GET /api/v1/company/visits` returns every status by
  default (including `cancelled`/`finish`/`confirmed`) — filter with
  `filters[status]` or `scope=active`/`scope=history` client-side per marker
  type, same convention as the Orders list.
- **Starting a support conversation to schedule a visit**: out of scope
  here — that's the existing `POST /api/v1/company/conversations` endpoint
  (already documented), not something new to build for visits specifically.

## 1. List Visits

`GET /api/v1/company/visits`

Query params (all optional): `per_page` (max 100), `paginate=false` to
disable pagination, `scope=active|history`, `filters[status]` (or the
literal `current` alias for "not cancelled/confirmed"), `filters[branch_id]`,
`filters[contract_id]`, `filters[from_date]`/`filters[to_date]` (against
`scheduled_date`), `sort[scheduled_at]=asc|desc` (defaults to newest-first).

Real response, captured live:

```json
{
  "status": "success",
  "message": "Visits retrieved successfully.",
  "data": {
    "data": [
      {
        "id": 46,
        "uuid": "8f1aa12c-70c0-4eba-a1de-780a0a2f82eb",
        "order_number": "ORD-2026-000046",
        "scheduled_at": null,
        "status": "start",
        "status_label": "جاري التنفيذ",
        "service": {
          "id": 2,
          "name": "Pipe Leak Repair",
          "image": "https://example.com/storage/categories/pipe.png"
        },
        "services_summary": "Pipe Leak Repair, Faucet & Fixture Installation, +1",
        "branch": { "id": 2, "title": "Gulf Maintenance - Jeddah Branch" },
        "contract": { "id": 1, "contract_number": "CTR-2026-000001" }
      }
    ],
    "links": { "first": "...", "last": "...", "prev": null, "next": "..." },
    "meta": { "current_page": 1, "per_page": 15, "total": 51 }
  }
}
```

`service` is the visit's first/primary line item (including its `image` URL); `services_summary` lists
up to 2 service names then `", +N"` for the rest (empty/`null` for an order
with no items yet). `branch`/`contract` are `null` when not set (individual
job orders may have neither).

## 2. Visit Details

`GET /api/v1/company/visits/{visit}` (`{visit}` is the order UUID)

All list fields plus `services` (full array, each with `id`, `name`, and `image`),
`branch.address`/`.latitude`/`.longitude`, `technician`, `technician_attachments`,
`allowed_actions.cancel`:

```json
{
  "data": {
    "id": 46,
    "uuid": "8f1aa12c-70c0-4eba-a1de-780a0a2f82eb",
    "order_number": "ORD-2026-000046",
    "scheduled_at": null,
    "status": "start",
    "status_label": "جاري التنفيذ",
    "service": {
      "id": 2,
      "name": "Pipe Leak Repair",
      "image": "https://example.com/storage/categories/pipe.png"
    },
    "services": [
      { "id": 2, "name": "Pipe Leak Repair", "image": "https://example.com/storage/categories/pipe.png" },
      { "id": 4, "name": "Faucet & Fixture Installation", "image": "https://example.com/storage/categories/faucet.png" },
      { "id": 5, "name": "Water Heater Repair", "image": "https://example.com/storage/categories/heater.png" }
    ],
    "branch": {
      "id": 2,
      "title": "Gulf Maintenance - Jeddah Branch",
      "address": "Tahlia Street, Jeddah",
      "latitude": "21.543300",
      "longitude": "39.172800"
    },
    "contract": { "id": 1, "contract_number": "CTR-2026-000001" },
    "technician": { "id": 10, "name": "...", "image": "https://..." },
    "technician_attachments": [
      { "id": 1, "url": "https://...", "type": "after", "note": null }
    ],
    "allowed_actions": { "cancel": false },
    "created_at": "2026-09-07T09:46:40+00:00"
  }
}
```

`technician_attachments[].type` is the real stored value
(`before|after|report|issue|signature|other`, from the technician's upload
form) — **not a MIME/file-type category** (`"image"`/`"video"`); there's no
MIME column in the schema. `allowed_actions.cancel` is computed the same way
the cancel endpoint itself validates (see below) — trust this field over
inferring from `status` client-side, so a business-rule change only needs a
backend deploy.

## 3. Cancel Visit

`POST /api/v1/company/visits/{visit}/cancel`

Body: `{"reason": "Schedule conflict"}` — **`reason` is required**
(`422` if missing, reuses the existing `Client\Order\CancelOrderRequest`,
same validation as order cancellation elsewhere in the API).

**Cancellable statuses — corrected from your doc's assumption**: cancellation
is allowed while status is one of
`pending, waiting_price, priced, accepted, on_the_way` — i.e., *before* the
technician has actually started (`Order::canBeCancelledByCustomer()`,
pre-existing, reused as-is — not new logic). **Not** "confirmed and
scheduled" as your doc stated — in this system `confirmed` = completed
(terminal) and there's no separate "scheduled" status; `accepted` is the
closest equivalent to what you meant. No cutoff *period* (e.g. "24h before")
exists today — it's purely status-based.

If the paid amount is non-zero, a refund is attempted automatically
(existing `RefundService`, unchanged) — no separate refund step needed by
the app.

```json
{"status": "success", "message": "Order cancelled successfully.", "data": { "...": "full updated order" }}
```
```json
{"status": "fail", "message": "This order can no longer be cancelled.", "data": null}
```

(Message currently says "order", not "visit" — same underlying entity/error
message as `POST /api/v1/company/orders/{order}/cancel`, kept consistent
rather than duplicated.)

## 4. Errors

Standard envelope: `{"status": "fail", "message": "...", "data": null}`.

| Case | HTTP |
|---|---|
| Unauthenticated | 401 |
| Unauthorized (wrong user type) | 403 |
| Visit not found / belongs to another company | 404 |
| Cancel: wrong status / already terminal | 422 |
| Cancel: missing `reason` | 422 |
| Empty list | 200, `data.data: []` |

## Files changed

- `app/Http/Controllers/Api/V1/Company/VisitController.php` — added
  `show()`, `cancel()` (delegates straight to
  `Client\Commands\OrderCommandService::cancel()`, same pattern
  `Company\OrderController::cancel()` already uses — no duplicated
  cancellation/refund logic).
- `app/Services/Company/VisitService.php` — `getVisits()` extended with the
  new filters/sort; added `show()`.
- `app/Http/Resources/Company/Order/VisitResource.php` (new),
  `VisitDetailsResource.php` (new).
- `routes/api/v1/company.php` — added `show`/`cancel` under
  `company.visits.*`.
- `lang/en/api.php`, `lang/ar/api.php` — added `visit_retrieved`.
