# Brix Accounting API — Attachments

API reference for file attachments linked to business records (invoices, bills, items).

Attachments are stored privately (local disk in development; object storage such as Cloudflare R2 in production). Files are never exposed via public URLs — clients download through authenticated API endpoints.

Invoice and bill **create/update** endpoints accept JSON only. Staged files can be linked in the same JSON request via `staged_attachment_ids`, or uploaded separately via `multipart/form-data` after the parent exists. See [Client integration — single form (QuickBooks-style)](#client-integration--single-form-quickbooks-style) below.

Related docs: [staged-attachments.md](./staged-attachments.md) (QuickBooks-style upload for bills & invoices), [invoices.md](./invoices.md), [bills.md](./bills.md), [items.md](./items.md).

---

## Base URL

Nested routes are scoped under each parent resource. Flat attachment routes use:

```
{BASE_URL}/api/v1/attachments
```

| Environment | Example |
|-------------|---------|
| Local | `http://127.0.0.1:8000/api/v1/attachments` |

---

## Authentication

All endpoints require:

| Header | Value |
|--------|-------|
| `Authorization` | `Bearer {token}` |
| `Accept` | `application/json` |

| Header | Value | When |
|--------|-------|------|
| `Content-Type` | `application/json` | `PATCH` metadata |
| `Content-Type` | `multipart/form-data` | Upload endpoints |

Obtain a token via `POST /api/v1/login`. See [auth-and-users.md](./auth-and-users.md).

**Middleware:** `auth:sanctum`, `company` — records are scoped to the authenticated user's company.

---

## Role permissions

Permissions are inherited from the parent record. The attachment endpoints enforce the same roles as the linked entity.

| Action | ADMIN | ACCOUNTANT | MANAGER | CASHIER |
|--------|-------|------------|---------|---------|
| List / view / download | ✓ | ✓ | ✓ | ✓ |
| Upload | ✓ | ✓ | ✗ | ✗ |
| Update metadata (`note`, `include_on_send`) | ✓ | ✓ | ✗ | ✗ |
| Delete (parent is DRAFT) | ✓ | ✓ | ✗ | ✗ |
| Delete (parent is posted / received) | ✓ | ✗ | ✗ | ✗ |

---

## Supported parents (v1)

| `attachable_type` | Parent endpoint | Typical files |
|-------------------|-----------------|---------------|
| `invoice` | [invoices.md](./invoices.md) | Signed PO, delivery note, photos |
| `bill` | [bills.md](./bills.md) | Vendor invoice PDF, receipt |
| `payment` | [customer-payments.md](./customer-payments.md) | Bank receipt, cheque image |
| `bill_payment` | [bill-payments.md](./bill-payments.md) | Remittance advice, wire confirmation |
| `item` | [items.md](./items.md) | Catalog image, spec sheet |

---

## Attachment object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `status` | string | Yes | `STAGED` (uploaded, not yet linked) or `LINKED` (attached to parent) |
| `attachable_type` | string \| null | Yes | `invoice`, `bill`, or `item` — null while `STAGED` |
| `attachable_id` | integer \| null | Yes | Parent record ID — null while `STAGED` |
| `intended_attachable_type` | string \| null | Yes | Hint set at staging upload: `invoice`, `bill`, or `item` |
| `upload_session_id` | string \| null | Yes | Client UUID grouping files on one form |
| `kind` | string | Yes | `IMAGE` or `DOCUMENT` |
| `filename` | string | Yes | Original file name |
| `content_type` | string | Yes | MIME type, e.g. `application/pdf` |
| `byte_size` | integer | Yes | File size in bytes |
| `note` | string \| null | No* | Optional label or description (max 500) |
| `include_on_send` | boolean | No* | Invoice only — include when emailing (default `false`) |
| `expires_at` | datetime \| null | Yes | Set while `STAGED`; cleared on link |
| `download_url` | string | Yes | Relative path to download via API |
| `uploaded_by` | object \| null | Yes | User who uploaded the file |
| `created_at` | datetime | Yes | — |
| `updated_at` | datetime | Yes | — |

\* Updatable via `PATCH /attachments/{id}`.

### File rules

| Rule | Value |
|------|-------|
| Max file size | 20 MB |
| Allowed types | PDF, JPEG, PNG, GIF, TIFF, DOC, XLSX, CSV, XML |
| Filename | No special characters; sanitized server-side |
| Item `IMAGE` | Max **1** per item; uploading a new image replaces the previous one |
| Item `DOCUMENT` | Unlimited |
| Invoice / bill | Unlimited (reasonable per-company quota may apply later) |

### Item `kind` behaviour

| Upload | `kind` assigned |
|--------|-----------------|
| `image/jpeg`, `image/png`, `image/gif`, `image/tiff` on item | `IMAGE` (replaces existing image) |
| Any other allowed type on item | `DOCUMENT` |
| Any allowed type on invoice or bill | `DOCUMENT` |

---

# Client integration — single form (QuickBooks-style)

> **Bills & invoices:** See [staged-attachments.md](./staged-attachments.md) for the full upload-on-picker flow, examples, and error handling.

Users can fill an invoice (or bill) form **and** select files on the **same screen**, then click **Save once**. Two client patterns are supported:

| Pattern | When to use | Upload timing |
|---------|-------------|---------------|
| **A — Staged upload** | Upload on file picker (true QBO-style) | `POST /attachments/staging` immediately; link on Save via `staged_attachment_ids` on create/update |
| **B — Save chain** | Simpler client, no staging API | Hold files in browser; upload after parent create |

### Pattern A — Staged upload (upload on file picker)

```
User picks file  →  POST /attachments/staging     (immediate, returns staged id)
User clicks Save →  POST /bills { ..., staged_attachment_ids: [99, 100] }
                 →  optional POST /bills/{id}/receive
```

For editing an existing draft, use `PATCH /bills/{id}` with `staged_attachment_ids`. Alternatively, link after create via `POST /bills/{id}/attachments/link-staged` or `POST /attachments/{id}/link`.

Staged files expire after **24 hours** (configurable). Run `php artisan attachments:purge-staged` (or schedule hourly) to remove expired orphans.

### Pattern B — Save chain (browser buffer)

One form with customer, lines, memo, and an **Attachments** area (drag-and-drop or file picker). Files stay in browser memory until Save.

### What the client does on Save (Pattern B)

```
Step 1   POST /invoices              JSON — create draft, get id
Step 2   POST /invoices/{id}/attachments   multipart — one request per file (or batch)
Step 3   (optional) POST /invoices/{id}/post   if user chose Save and post
```

The same pattern applies to bills (`POST /bills` → `POST /bills/{id}/attachments` → optional `POST /bills/{id}/receive`).

### Sequence

```mermaid
sequenceDiagram
    participant User
    participant UI
    participant API

    User->>UI: Fill form + select files
    User->>UI: Click Save

    UI->>API: POST /invoices (JSON)
    API-->>UI: 201 { id: 12, status: DRAFT }

    par Upload each file
        UI->>API: POST /invoices/12/attachments
    end
    API-->>UI: 201 per attachment

    UI-->>User: Invoice saved
```

### Example client flow (create invoice with attachments)

**Step 1 — Create invoice**

```http
POST /api/v1/invoices
Authorization: Bearer {token}
Content-Type: application/json
Accept: application/json

{
  "customer_id": 3,
  "txn_date": "2026-06-16",
  "due_date": "2026-07-16",
  "memo": "Rush order",
  "lines": [
    { "item_id": 5, "qty": 2, "unit_price": 100 }
  ]
}
```

Response includes `"id": 12`.

**Step 2 — Upload each selected file**

```http
POST /api/v1/invoices/12/attachments
Authorization: Bearer {token}
Accept: application/json
Content-Type: multipart/form-data

file: (binary) signed_po.pdf
note: Customer PO #4421
include_on_send: true
```

Repeat for additional files. Uploads may run **in parallel** after step 1 succeeds.

**Step 3 — (optional) Post invoice**

```http
POST /api/v1/invoices/12/post
Authorization: Bearer {token}
Accept: application/json
```

Attachments are **not required** to post. They may be added before or after posting.

### Edit existing draft (same form)

| Action | API call |
|--------|----------|
| Load form | `GET /invoices/{id}` |
| Load attachments | `GET /invoices/{id}/attachments` |
| Save field changes | `PATCH /invoices/{id}` |
| Add new files | `POST /invoices/{id}/attachments` |
| Remove a file | `DELETE /attachments/{id}` |

New files and field updates can run in parallel on Save.

### Error handling

| Scenario | Recommended UX |
|----------|----------------|
| Invoice create fails (`422`) | Do not upload files; show validation errors |
| Invoice created, one file fails | Show “Invoice saved. 1 of 2 attachments failed.” Offer retry on failed file only |
| All uploads fail | Invoice still exists as DRAFT; user can retry from edit screen |
| User closes form mid-upload | Invoice remains saved; partial attachments are kept |

### UI loading states

1. **Saving invoice…** — during `POST /invoices`
2. **Uploading files (2 of 3)…** — during attachment uploads
3. **Posting…** — during optional post/receive step

Disable the Save button while the chain is in progress.

### Batch upload (optional)

When multiple files are selected, clients may use a single batch request instead of one request per file:

```
POST /api/v1/invoices/{id}/attachments/batch
```

See [Batch upload attachments](#batch-upload-attachments) below.

---

# Endpoints

## Stage attachment (upload without parent)

> Full bill/invoice staging guide: [staged-attachments.md](./staged-attachments.md)

```
POST /attachments/staging
GET  /attachments/staging
```

QuickBooks-style upload before a bill or invoice exists. **ADMIN or ACCOUNTANT only.**

### Stage upload

**Request** (`multipart/form-data`):

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `file` | file | **Yes** | Max 20 MB; allowed MIME types only |
| `note` | string | No | Max 500 |
| `intended_attachable_type` | string | No | `invoice`, `bill`, or `item` |
| `upload_session_id` | string | No | UUID — group files on one form |

**Response — `201 Created`**

Staged attachment object (`status: STAGED`, `attachable_type` and `attachable_id` null).

### List staged attachments

**Query params:**

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `upload_session_id` | string | — | Filter by form session |
| `intended_attachable_type` | string | — | Filter by intended parent |
| `mine_only` | boolean | `true` | Only files uploaded by current user |

Returns non-expired staged files, newest first. Expired staged files are excluded.

### Staged file rules

| Rule | Value |
|------|-------|
| TTL | 24 hours (`ATTACHMENTS_STAGING_TTL_HOURS`) |
| Cleanup | `php artisan attachments:purge-staged` |
| Download | Uploader or ADMIN/ACCOUNTANT in same company |
| Delete | Uploader or ADMIN/ACCOUNTANT in same company |
| Link to parent | `POST /attachments/{id}/link` or nested `link-staged` (see below) |
| Link permission | ADMIN/ACCOUNTANT; uploader only unless ADMIN |
| Batch link | All-or-nothing transaction |

---

## Link staged attachment to parent

```
POST /attachments/{attachment}/link
POST /bills/{bill}/attachments/link-staged
POST /invoices/{invoice}/attachments/link-staged
POST /items/{item}/attachments/link-staged
```

Link one or more staged uploads to an existing bill, invoice, or item. **ADMIN or ACCOUNTANT** with `uploadAttachments` permission on the parent.

### Link single staged file

**Request** (`application/json`):

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `attachable_type` | string | **Yes** | `invoice`, `bill`, or `item` |
| `attachable_id` | integer | **Yes** | Parent record ID (same company) |
| `include_on_send` | boolean | No | Invoice only |

**Response — `200 OK`**

Linked attachment object (`status: LINKED`).

**Error responses — `422`:**

| Condition | Message |
|-----------|---------|
| Not `STAGED` | Attachment is not staged |
| Expired | Staged attachment has expired |
| Wrong `intended_attachable_type` | Cannot link to this record type |
| Already linked | Attachment is not staged |

### Batch link staged files to parent

**Request** (`application/json`):

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `staged_attachment_ids` | integer[] | **Yes** | Min 1; each must be `STAGED` in same company |
| `include_on_send_by_id` | object | No | Invoice only — map of attachment id → boolean |

**Example:**

```http
POST /api/v1/bills/5/attachments/link-staged
Authorization: Bearer {token}
Content-Type: application/json

{
  "staged_attachment_ids": [99, 100]
}
```

**Response — `200 OK`**

```json
{
  "data": [
    { "id": 99, "status": "LINKED", "attachable_type": "bill", "attachable_id": 5, "...": "..." },
    { "id": 100, "status": "LINKED", "attachable_type": "bill", "attachable_id": 5, "...": "..." }
  ]
}
```

If any file fails validation (expired, wrong type, already linked), the entire batch rolls back.

---

## List attachments for invoice

```
GET /invoices/{invoice}/attachments
```

Returns all attachments linked to the invoice, newest first.

### Example request

```http
GET /api/v1/invoices/12/attachments
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": [
    {
      "id": 42,
      "attachable_type": "invoice",
      "attachable_id": 12,
      "kind": "DOCUMENT",
      "filename": "signed_po.pdf",
      "content_type": "application/pdf",
      "byte_size": 184320,
      "note": "Customer PO #4421",
      "include_on_send": true,
      "download_url": "/api/v1/attachments/42/download",
      "uploaded_by": {
        "id": 1,
        "name": "Admin User"
      },
      "created_at": "2026-06-16T10:05:00.000000Z",
      "updated_at": "2026-06-16T10:05:00.000000Z"
    }
  ]
}
```

---

## Upload attachment to invoice

```
POST /invoices/{invoice}/attachments
```

**ADMIN or ACCOUNTANT only.** Allowed on any invoice status (including `OPEN`). Parent invoice must belong to the same company.

### Request body (multipart)

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `file` | file | **Yes** | Max 20 MB; allowed MIME types only |
| `note` | string | No | Max 500 |
| `include_on_send` | boolean | No | Default `false` |

### Example request

```http
POST /api/v1/invoices/12/attachments
Authorization: Bearer {token}
Accept: application/json
Content-Type: multipart/form-data

file: (binary)
note: Customer PO #4421
include_on_send: true
```

### Success response — `201 Created`

Single attachment object in `data`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN or ACCOUNTANT |
| `404` | Invoice not found |
| `422` | File too large, invalid type, or invalid filename |

---

## Batch upload attachments to invoice

```
POST /invoices/{invoice}/attachments/batch
```

Upload multiple files in one request. Same permissions and rules as single upload.

### Request body (multipart)

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `files[]` | file[] | **Yes** | Min 1 file; each file obeys single-upload rules |
| `notes[]` | string[] | No | Optional note per file, matched by index |
| `include_on_send[]` | boolean[] | No | Optional flag per file, matched by index |

### Success response — `201 Created`

```json
{
  "data": [
    { "id": 42, "filename": "signed_po.pdf", "...": "..." },
    { "id": 43, "filename": "photo.jpg", "...": "..." }
  ]
}
```

If any file fails validation, the entire request returns `422` (no partial batch in v1).

---

## List / upload attachments for bill

```
GET  /bills/{bill}/attachments
POST /bills/{bill}/attachments
POST /bills/{bill}/attachments/batch
```

Same request/response shape as invoice attachments. `include_on_send` is ignored on bills.

---

## List / upload attachments for customer payment

```
GET  /customer-payments/{payment}/attachments
POST /customer-payments/{payment}/attachments
POST /customer-payments/{payment}/attachments/link-staged
```

Same multipart upload shape as bills. `include_on_send` is ignored. Payments are always `POSTED`; delete/update metadata on linked attachments requires **ADMIN**.

---

## List / upload attachments for bill payment

```
GET  /bill-payments/{billPayment}/attachments
POST /bill-payments/{billPayment}/attachments
POST /bill-payments/{billPayment}/attachments/link-staged
```

Same rules as customer payment attachments (`attachable_type: bill_payment`).

---

## List / upload attachments for item

```
GET  /items/{item}/attachments
POST /items/{item}/attachments
POST /items/{item}/attachments/batch
```

Same multipart upload shape. `include_on_send` is ignored on items.

- Image uploads (`image/*`) are stored as `kind: IMAGE` and replace any existing item image.
- Non-image uploads are stored as `kind: DOCUMENT`.

### Optional item image shortcut

```
PUT    /items/{item}/image      multipart — replaces primary IMAGE
DELETE /items/{item}/image      removes primary IMAGE only
```

Equivalent to uploading with `kind: IMAGE` via the attachments endpoint.

---

## List all attachments (company)

```
GET /attachments
```

Company-wide attachment browser. Optional filters:

| Parameter | Type | Description |
|-----------|------|-------------|
| `attachable_type` | string | `invoice`, `bill`, or `item` |
| `attachable_id` | integer | Parent record ID |
| `kind` | string | `IMAGE` or `DOCUMENT` |
| `page` | integer | Page number (paginated) |

### Example request

```http
GET /api/v1/attachments?attachable_type=invoice&attachable_id=12
Authorization: Bearer {token}
Accept: application/json
```

---

## Get attachment metadata

```
GET /attachments/{id}
```

### Error responses

| Status | Condition |
|--------|-----------|
| `404` | Attachment not found or belongs to another company |

---

## Download attachment

```
GET /attachments/{id}/download
```

Streams the file binary. Requires view permission on the parent record.

### Example request

```http
GET /api/v1/attachments/42/download
Authorization: Bearer {token}
```

### Success response — `200 OK`

| Header | Value |
|--------|-------|
| `Content-Type` | Attachment MIME type |
| `Content-Disposition` | `attachment; filename="signed_po.pdf"` |

Body: raw file bytes.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User cannot view parent record |
| `404` | Attachment or file not found |

---

## Update attachment metadata

```
PATCH /attachments/{id}
```

**ADMIN or ACCOUNTANT only.** Does not replace file content — upload a new attachment instead.

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `note` | string | No | Max 500; send `null` to clear |
| `include_on_send` | boolean | No | Invoice attachments only |

### Example request

```http
PATCH /api/v1/attachments/42
Authorization: Bearer {token}
Content-Type: application/json

{
  "note": "Updated label",
  "include_on_send": false
}
```

### Success response — `200 OK`

Updated attachment in `data`.

---

## Delete attachment

```
DELETE /attachments/{id}
```

| Parent status | Who can delete |
|---------------|----------------|
| Invoice `DRAFT` / Bill `DRAFT` | ADMIN, ACCOUNTANT |
| Invoice `OPEN`+ / Bill received | ADMIN only |
| Item (any) | ADMIN, ACCOUNTANT |

Deletes the database row and removes the file from storage.

### Success response — `204 No Content`

Empty body.

---

## Parent record includes attachments

`GET /invoices/{id}` and `GET /bills/{id}` do **not** include attachments by default. Load them explicitly:

```
GET /invoices/{id}/attachments
```

Or request eager loading when supported:

```http
GET /api/v1/invoices/12?include=attachments
```

---

## Cascade delete

When a **draft** invoice or bill is deleted, all linked attachments and stored files are removed automatically.

Posted invoices and received bills are voided, not deleted — attachments are retained for audit.

---

## Validation error format — `422`

```json
{
  "message": "The file failed to upload.",
  "errors": {
    "file": ["The file must be a file of type: pdf, jpg, jpeg, png, gif, tiff, doc, xlsx, csv, xml."]
  }
}
```

---

## Endpoint summary

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/attachments/staging` | Stage upload without parent |
| `GET` | `/attachments/staging` | List staged uploads |
| `POST` | `/attachments/{id}/link` | Link one staged file to parent |
| `POST` | `/bills/{bill}/attachments/link-staged` | Batch link staged files to bill |
| `POST` | `/invoices/{invoice}/attachments/link-staged` | Batch link staged files to invoice |
| `POST` | `/items/{item}/attachments/link-staged` | Batch link staged files to item |
| `POST` | `/customer-payments/{payment}/attachments/link-staged` | Batch link staged files to customer payment |
| `POST` | `/bill-payments/{billPayment}/attachments/link-staged` | Batch link staged files to bill payment |
| `GET` | `/invoices/{invoice}/attachments` | List invoice attachments |
| `POST` | `/invoices/{invoice}/attachments` | Upload file to invoice |
| `POST` | `/invoices/{invoice}/attachments/batch` | Upload multiple files to invoice |
| `GET` | `/bills/{bill}/attachments` | List bill attachments |
| `POST` | `/bills/{bill}/attachments` | Upload file to bill |
| `POST` | `/bills/{bill}/attachments/batch` | Upload multiple files to bill |
| `GET` | `/customer-payments/{payment}/attachments` | List customer payment attachments |
| `POST` | `/customer-payments/{payment}/attachments` | Upload file to customer payment |
| `GET` | `/bill-payments/{billPayment}/attachments` | List bill payment attachments |
| `POST` | `/bill-payments/{billPayment}/attachments` | Upload file to bill payment |
| `GET` | `/items/{item}/attachments` | List item attachments |
| `POST` | `/items/{item}/attachments` | Upload file to item |
| `POST` | `/items/{item}/attachments/batch` | Upload multiple files to item |
| `PUT` | `/items/{item}/image` | Replace item primary image |
| `DELETE` | `/items/{item}/image` | Remove item primary image |
| `GET` | `/attachments` | List company attachments (filtered, paginated) |
| `GET` | `/attachments/{id}` | Get attachment metadata |
| `GET` | `/attachments/{id}/download` | Download file |
| `PATCH` | `/attachments/{id}` | Update note / include_on_send |
| `DELETE` | `/attachments/{id}` | Delete attachment |

---

## Frontend notes

- **Pattern A (QBO-style):** upload on file picker via `POST /attachments/staging`; on Save pass `staged_attachment_ids` on `POST /bills` or `POST /invoices` (or `PATCH` on edit).
- **Pattern B (save chain):** keep selected files in `File[]` state until Save; chain `POST /invoices` → attachment uploads in one Save handler.
- Use `upload_session_id` (UUID per form) to reload staged files if the user refreshes before Save.
- Use `download_url` with the same Bearer token for downloads, or open in a new tab via a short-lived authenticated fetch + blob URL.
- Show `include_on_send` checkbox only on invoice attachment UI.
- On item forms, show one image slot (`kind: IMAGE`) plus a separate list for documents.
- Bill forms: typical flow is `POST /bills` → upload vendor PDF → `POST /bills/{id}/receive`.

---

## Storage (operations)

| Environment | Disk | Notes |
|-------------|------|-------|
| Local dev | `local` | `storage/app/private/attachments/{company_id}/…` |
| Production | `s3` (Cloudflare R2) | Private bucket; no public URLs |

Configured via `ATTACHMENTS_DISK` in `.env`. Application code uses Laravel `Storage` — switching disks does not change API contracts.

### Staging

| Variable | Default | Description |
|----------|---------|-------------|
| `ATTACHMENTS_STAGING_ENABLED` | `true` | Enable `POST /attachments/staging` |
| `ATTACHMENTS_STAGING_TTL_HOURS` | `24` | Hours before unlinked staged files expire |
