# Brix Accounting API — Staged Attachments

QuickBooks-style **upload on file picker, link on Save** for vendor bills, customer invoices, and payments.

Upload files **before** the bill or invoice exists, then link them when the user saves the form — in one API call or as a separate link step.

Related docs: [attachments.md](./attachments.md) (full attachment reference), [bills.md](./bills.md), [invoices.md](./invoices.md), [customer-payments.md](./customer-payments.md), [bill-payments.md](./bill-payments.md).

---

## Overview

| Step | What happens |
|------|----------------|
| 1. User picks file | Client calls `POST /attachments/staging` immediately |
| 2. User fills form | Staged file ids kept in UI state (`upload_session_id` optional) |
| 3. User clicks Save | Client calls `POST /bills`, `POST /invoices`, `POST /customer-payments`, or `POST /bill-payments` with `staged_attachment_ids[]` |
| 4. Optional | `POST /bills/{id}/receive`, `POST /invoices/{id}/post`, or link later via nested `/attachments/link-staged` |

Staged files are stored with `status: STAGED` and no parent. On link they become `status: LINKED` on the bill or invoice.

**Typical files**

| Parent | Examples |
|--------|----------|
| Bill | Vendor invoice PDF, delivery note, receipt |
| Invoice | Customer PO, signed document, photo |
| Customer payment | Bank receipt, cheque scan |
| Bill payment | Remittance advice, wire confirmation |

All payment attachments use `intended_attachable_type` of `payment` or `bill_payment` and are stored as `kind: DOCUMENT`.

---

## Base URL

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

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

Staging and link routes:

```
POST   /attachments/staging
GET    /attachments/staging
POST   /attachments/{id}/link
POST   /bills/{bill}/attachments/link-staged
POST   /invoices/{invoice}/attachments/link-staged
POST   /customer-payments/{payment}/attachments/link-staged
POST   /bill-payments/{billPayment}/attachments/link-staged
```

Bill and invoice create/update accept optional `staged_attachment_ids` — see [Link on create/update](#link-on-createupdate).

---

## Authentication

All endpoints require:

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

| Header | Value | When |
|--------|-------|------|
| `Content-Type` | `multipart/form-data` | Stage upload |
| `Content-Type` | `application/json` | Link, create bill/invoice |

**Middleware:** `auth:sanctum`, `company`

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

---

## Role permissions

| Action | ADMIN | ACCOUNTANT | CASHIER |
|--------|-------|------------|---------|
| Stage upload | ✓ | ✓ | ✗ |
| List / download staged | ✓ | ✓ | ✓ (linked only)* |
| Delete staged | ✓ | ✓ | ✗ |
| Link to bill / invoice | ✓ | ✓** | ✗ |
| Create / update bill or invoice with staged ids | ✓ | ✓ | ✗ |

\* Cashiers can view/download **linked** attachments on records they can view; not staged orphans.

\** ACCOUNTANT can link only **their own** staged files. ADMIN can link any staged file in the company.

---

## Staged attachment object

Same shape as a linked attachment, with staging fields populated:

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Primary key — store this after staging |
| `status` | string | `STAGED` until linked, then `LINKED` |
| `attachable_type` | string \| null | `bill` or `invoice` after link; `null` while staged |
| `attachable_id` | integer \| null | Bill or invoice id after link; `null` while staged |
| `intended_attachable_type` | string \| null | Hint set at upload: `bill` or `invoice` |
| `upload_session_id` | string \| null | Client UUID grouping files on one form |
| `expires_at` | datetime | TTL while staged; `null` after link |
| `kind` | string | Always `DOCUMENT` for bills and invoices |
| `filename` | string | Original file name |
| `content_type` | string | MIME type |
| `byte_size` | integer | Size in bytes |
| `note` | string \| null | Optional label (max 500) |
| `include_on_send` | boolean | Invoice only — set at link time (default `false`) |
| `download_url` | string | `/api/v1/attachments/{id}/download` |
| `uploaded_by` | object \| null | User who uploaded |
| `created_at` | datetime | — |
| `updated_at` | datetime | — |

### File rules

| Rule | Value |
|------|-------|
| Max file size | 20 MB |
| Allowed types | PDF, JPEG, PNG, GIF, TIFF, DOC, DOCX, XLSX, CSV, XML |
| Staging TTL | 24 hours (configurable) |
| Expired cleanup | `php artisan attachments:purge-staged` |

---

# Client flows

## New bill (recommended — one Save)

```mermaid
sequenceDiagram
    participant User
    participant UI
    participant API

    User->>UI: Pick vendor PDF
    UI->>API: POST /attachments/staging
    API-->>UI: 201 { id: 99, status: STAGED }

    User->>UI: Fill bill + Save
    UI->>API: POST /bills { staged_attachment_ids: [99] }
    API-->>UI: 201 bill + attachments linked

    opt Receive inventory
        UI->>API: POST /bills/{id}/receive
    end
```

```
1. POST /attachments/staging          (on file picker)
2. POST /bills                        (on Save — includes staged_attachment_ids)
3. POST /bills/{id}/receive           (optional)
```

## New invoice (recommended — one Save)

```
1. POST /attachments/staging          (on file picker)
2. POST /invoices                     (on Save — includes staged_attachment_ids)
3. POST /invoices/{id}/post           (optional)
```

For invoices, pass `include_on_send_by_id` when the file should be emailed with the invoice.

## Edit existing draft

| Action | Bill | Invoice |
|--------|------|---------|
| Load record | `GET /bills/{id}` | `GET /invoices/{id}` |
| Load attachments | `GET /bills/{id}/attachments` | `GET /invoices/{id}/attachments` |
| Add staged files on Save | `PATCH /bills/{id}` + `staged_attachment_ids` | `PATCH /invoices/{id}` + `staged_attachment_ids` |
| Or link without field changes | `POST /bills/{id}/attachments/link-staged` | `POST /invoices/{invoice}/attachments/link-staged` |
| Remove file | `DELETE /attachments/{id}` | `DELETE /attachments/{id}` |

## Alternative — link after create (two steps)

If the bill or invoice was already created without attachments:

```
POST /bills/{id}/attachments/link-staged
POST /invoices/{id}/attachments/link-staged
```

Or link one file via flat endpoint:

```
POST /attachments/{id}/link
{ "attachable_type": "bill", "attachable_id": 5 }
```

---

# Endpoints

## Stage upload

```
POST /attachments/staging
```

Upload a file **without** a bill or invoice. Call this when the user picks a file on a new or edit form.

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

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

**Example — bill form**

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

file: (binary) vendor_invoice.pdf
note: Vendor INV-8842
intended_attachable_type: bill
upload_session_id: 550e8400-e29b-41d4-a716-446655440000
```

**Response — `201 Created`**

```json
{
  "data": {
    "id": 99,
    "status": "STAGED",
    "attachable_type": null,
    "attachable_id": null,
    "intended_attachable_type": "bill",
    "upload_session_id": "550e8400-e29b-41d4-a716-446655440000",
    "filename": "vendor_invoice.pdf",
    "expires_at": "2026-06-20T10:05:00.000000Z",
    "download_url": "/api/v1/attachments/99/download"
  }
}
```

---

## List staged attachments

```
GET /attachments/staging
```

Returns the current user's non-expired staged files (default). Use after a page refresh to restore the attachment list on an unsaved form.

**Query params:**

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `upload_session_id` | string | — | Filter by form session UUID |
| `intended_attachable_type` | string | — | `bill` or `invoice` |
| `mine_only` | boolean | `true` | Only files uploaded by current user |

**Example**

```http
GET /api/v1/attachments/staging?upload_session_id=550e8400-e29b-41d4-a716-446655440000&intended_attachable_type=bill
Authorization: Bearer {token}
Accept: application/json
```

---

## Link on create/update

Pass staged ids on bill or invoice **create** or **update**. Linking runs in the **same database transaction** as the save — if link fails, the bill/invoice is not saved.

### Create bill with attachments

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

{
  "vendor_id": 2,
  "txn_date": "2026-06-16",
  "due_date": "2026-07-16",
  "memo": "PO #123",
  "lines": [
    { "item_id": 5, "qty": 10, "unit_price": 50 }
  ],
  "staged_attachment_ids": [99, 100]
}
```

See [bills.md — Create bill](./bills.md#create-bill) for full bill fields.

### Create invoice with attachments

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

{
  "customer_id": 3,
  "txn_date": "2026-06-16",
  "due_date": "2026-07-16",
  "lines": [
    { "item_id": 5, "qty": 2, "unit_price": 100 }
  ],
  "staged_attachment_ids": [101],
  "include_on_send_by_id": {
    "101": true
  }
}
```

See [invoices.md — Create invoice](./invoices.md#create-invoice) for full invoice fields.

### Update draft with new staged files

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

{
  "memo": "Updated memo",
  "staged_attachment_ids": [102]
}
```

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

{
  "notes": "Added signed PO",
  "staged_attachment_ids": [103],
  "include_on_send_by_id": {
    "103": true
  }
}
```

### Request fields

| Field | Bills | Invoices | Rules |
|-------|-------|----------|-------|
| `staged_attachment_ids` | ✓ | ✓ | Optional integer array; each id must be `STAGED` in same company |
| `include_on_send_by_id` | Ignored | ✓ | Map of attachment id → boolean |

---

## Link to existing bill

```
POST /bills/{bill}/attachments/link-staged
```

Use when the bill already exists and you only need to attach staged files (no field changes).

**Request**

```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,
      "filename": "vendor_invoice.pdf"
    }
  ]
}
```

Verify with `GET /bills/5/attachments`.

---

## Link to existing invoice

```
POST /invoices/{invoice}/attachments/link-staged
```

**Request**

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

{
  "staged_attachment_ids": [101],
  "include_on_send_by_id": {
    "101": true
  }
}
```

---

## Link single staged file (flat)

```
POST /attachments/{attachment}/link
```

Alternative when linking one file to a known bill or invoice id.

**Request**

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

{
  "attachable_type": "bill",
  "attachable_id": 5
}
```

For invoices, optional:

```json
{
  "attachable_type": "invoice",
  "attachable_id": 12,
  "include_on_send": true
}
```

---

## Download / delete staged file

| Action | Endpoint |
|--------|----------|
| Download | `GET /attachments/{id}/download` |
| Delete (cancel upload) | `DELETE /attachments/{id}` |
| Metadata | `GET /attachments/{id}` |

While `status: STAGED`, only the uploader or ADMIN/ACCOUNTANT in the same company can download or delete.

---

# Error handling

### Frontend UX

| Scenario | Recommended UX |
|----------|----------------|
| Staging upload fails | Show error; do not add to list |
| Bill/invoice validation fails (`422`) | Do not call link; staged files remain for retry |
| Save with staged ids fails (expired, wrong type) | Show error; bill/invoice **not** created/updated |
| One file in batch invalid | Entire save rolls back (atomic) |
| User cancels form | `DELETE /attachments/{id}` per staged file, or rely on 24h TTL |
| User refreshes before Save | Reload via `GET /attachments/staging?upload_session_id=...` |

### HTTP status codes

| Status | Condition |
|--------|-----------|
| `201` | Staged upload or bill/invoice created with links |
| `200` | Link or update with staged ids succeeded |
| `403` | CASHIER, or ACCOUNTANT linking another user's staged file |
| `422` | Validation failed, expired staged file, wrong `intended_attachable_type`, already linked |
| `404` | Staged file not found, expired on download, or wrong company |

### Common `422` messages

| Message | Cause |
|---------|-------|
| Attachment is not staged. | Id already linked or invalid |
| Staged attachment has expired. | Past `expires_at` |
| Attachment cannot be linked to this record type. | e.g. staged as `bill`, linked to invoice |
| Cannot link another user's staged attachment. | ACCOUNTANT ownership rule |

---

# Configuration

`.env`:

```env
ATTACHMENTS_STAGING_ENABLED=true
ATTACHMENTS_STAGING_TTL_HOURS=24
ATTACHMENTS_DISK=local
ATTACHMENTS_MAX_SIZE_KB=20480
```

Schedule cleanup in production:

```bash
php artisan attachments:purge-staged
```

---

# Endpoint summary

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/attachments/staging` | Upload file without bill/invoice |
| `GET` | `/attachments/staging` | List staged files |
| `POST` | `/attachments/{id}/link` | Link one staged file to bill or invoice |
| `POST` | `/bills` | Create bill; optional `staged_attachment_ids` |
| `PATCH` | `/bills/{id}` | Update draft; optional `staged_attachment_ids` |
| `POST` | `/bills/{id}/attachments/link-staged` | Link staged files to existing bill |
| `GET` | `/bills/{id}/attachments` | List linked bill attachments |
| `POST` | `/invoices` | Create invoice; optional `staged_attachment_ids` |
| `PATCH` | `/invoices/{id}` | Update draft; optional `staged_attachment_ids` |
| `POST` | `/invoices/{id}/attachments/link-staged` | Link staged files to existing invoice |
| `GET` | `/invoices/{id}/attachments` | List linked invoice attachments |
| `GET` | `/attachments/{id}/download` | Download file |
| `DELETE` | `/attachments/{id}` | Delete staged or linked attachment |

---

# Frontend checklist

- Generate a `upload_session_id` (UUID) per form open; send on each stage upload.
- Store returned attachment `id`s in UI state until Save.
- On Save (new bill/invoice): include `staged_attachment_ids` on `POST /bills` or `POST /invoices`.
- On Save (edit draft): `PATCH` with `staged_attachment_ids`, or call `link-staged` separately.
- Show `include_on_send` checkbox **only on invoice** attachment UI; send via `include_on_send_by_id`.
- Disable Save while staging or save request is in flight.
- On form cancel, delete staged files or leave for TTL cleanup.

---

# Related documentation

- [attachments.md](./attachments.md) — full attachment API (direct upload, items, lifecycle)
- [bills.md](./bills.md) — bill CRUD, receive, void
- [invoices.md](./invoices.md) — invoice CRUD, post, void
- [attachments-module.md](../attachments-module.md) — implementation summary
