# Attachments Module — Implementation Summary

Cross-cutting module for private file attachments linked to invoices, bills, and items. Implemented in **Phases 1–3** (local disk storage). API reference: [api/attachments.md](./api/attachments.md).

---

## Overview

| Aspect | Detail |
|--------|--------|
| Module path | `app/Modules/Attachments/` |
| Routes | `routes/api/attachments.php` → `/api/v1/...` |
| Storage (dev) | `local` disk → `storage/app/private/attachments/{company_id}/{uuid}/{filename}` |
| Storage (prod) | Configurable via `ATTACHMENTS_DISK` (R2/S3 planned Phase 5) |
| Tenancy | `company_id` on every row + `BelongsToCompany` global scope |
| Parent link | Polymorphic `attachable_type` + `attachable_id` |

Supported parents:

| `attachable_type` | Model | Typical use |
|-------------------|-------|-------------|
| `invoice` | `App\Modules\Sales\Models\Invoice` | PO, signed docs, photos |
| `bill` | `App\Modules\Purchasing\Models\Bill` | Vendor invoice PDF |
| `item` | `App\Modules\Inventory\Models\Item` | Catalog image, spec sheets |

---

## Phases completed

### Phase 1 — Foundation + invoice attachments

- `attachments` table migration
- Module skeleton (model, services, policy, resource, requests)
- `GET` / `POST` `/invoices/{invoice}/attachments`
- Local disk storage via `AttachmentStorageService`
- Feature tests: `InvoiceAttachmentApiTest`

### Phase 2 — Bills + items

- `GET` / `POST` `/bills/{bill}/attachments`
- `GET` / `POST` `/items/{item}/attachments`
- Item `IMAGE` replaces previous image on upload; `DOCUMENT` unlimited
- `include_on_send` only stored for invoices (always `false` on bills/items)
- Feature tests: `BillAttachmentApiTest`, `ItemAttachmentApiTest`

### Phase 3 — Download, delete, metadata, cascade

- Flat endpoints: show, download, patch, delete
- Item image shortcuts: `PUT` / `DELETE` `/items/{item}/image`
- Cascade delete via `HasAttachments` trait when parent invoice/bill is deleted
- Delete rules: ACCOUNTANT on draft parents; ADMIN only after post/receive
- Feature tests: `AttachmentLifecycleApiTest`

### Not yet implemented

| Phase | Scope |
|-------|--------|
| 4 | Batch upload (`POST .../attachments/batch`), doc cross-links in invoices/bills/items |
| 5 | Cloudflare R2 / S3 production disk |
| 6 | Global `GET /attachments` list, presigned URLs |

### Phase 1 — Staged uploads (implemented)

- Migration: `status`, nullable parent, `expires_at`, `upload_session_id`, `intended_attachable_type`
- `POST /attachments/staging`, `GET /attachments/staging`
- Staged download/delete; `AttachmentService::storeStaged()`, `linkTo()`
- `attachments:purge-staged` command
- Tests: `StagedAttachmentApiTest`

### Phase 2 — Link staged files (implemented)

- `POST /attachments/{id}/link`
- `POST /bills|invoices|items/{id}/attachments/link-staged`
- `AttachmentService::linkManyTo()` (atomic batch)
- Tests: `StagedAttachmentLinkApiTest`

### Phase 3 — Create/update with staged ids (implemented)

- `staged_attachment_ids` + `include_on_send_by_id` on `POST`/`PATCH` bills and invoices
- `StagedAttachmentLinkService` called inside draft services (same DB transaction)
- Tests: `StagedAttachmentCreateApiTest`

---

## Files created

### Database

| File | Purpose |
|------|---------|
| `database/migrations/0035_create_attachments_table.php` | `attachments` table |

### Config

| File | Purpose |
|------|---------|
| `config/attachments.php` | Disk, path prefix, max size, allowed MIME types |

### Module — `app/Modules/Attachments/`

| File | Purpose |
|------|---------|
| `Models/Attachment.php` | Eloquent model |
| `Enums/AttachmentKind.php` | `IMAGE`, `DOCUMENT` |
| `Enums/AttachableType.php` | `invoice`, `bill`, `item` mapping |
| `Concerns/HasAttachments.php` | `morphMany` + cascade delete on parent delete |
| `Services/AttachmentStorageService.php` | Store, delete, exists on disk |
| `Services/AttachmentService.php` | Store, update metadata, delete, image replacement |
| `Controllers/Api/AttachmentController.php` | Flat CRUD + download |
| `Controllers/Api/InvoiceAttachmentController.php` | Nested invoice routes |
| `Controllers/Api/BillAttachmentController.php` | Nested bill routes |
| `Controllers/Api/ItemAttachmentController.php` | Nested item routes + image shortcuts |
| `Policies/AttachmentPolicy.php` | View/update/delete with parent status rules |
| `Resources/AttachmentResource.php` | JSON API shape |
| `Requests/StoreAttachmentRequest.php` | Multipart upload validation |
| `Requests/UpdateAttachmentRequest.php` | `note`, `include_on_send` validation |

### Routes

| File | Purpose |
|------|---------|
| `routes/api/attachments.php` | All attachment endpoints |

### Tests

| File | Tests |
|------|-------|
| `tests/Feature/InvoiceAttachmentApiTest.php` | 6 |
| `tests/Feature/BillAttachmentApiTest.php` | 5 |
| `tests/Feature/ItemAttachmentApiTest.php` | 4 |
| `tests/Feature/AttachmentLifecycleApiTest.php` | 9 |

### Documentation

| File | Purpose |
|------|---------|
| `docs/api/attachments.md` | Full attachment API reference |
| `docs/api/staged-attachments.md` | Staged upload guide for bills & invoices |

---

## Files modified

| File | Change |
|------|--------|
| `routes/api.php` | `require` `routes/api/attachments.php` |
| `app/Providers/AppServiceProvider.php` | Morph map (`invoice`, `bill`, `item`); `AttachmentPolicy` registration |
| `.env.example` | `ATTACHMENTS_DISK`, `ATTACHMENTS_MAX_SIZE_KB` |
| `app/Modules/Sales/Models/Invoice.php` | `HasAttachments` trait |
| `app/Modules/Purchasing/Models/Bill.php` | `HasAttachments` trait |
| `app/Modules/Inventory/Models/Item.php` | `HasAttachments` trait |
| `app/Modules/Sales/Policies/InvoicePolicy.php` | `listAttachments`, `uploadAttachments` |
| `app/Modules/Purchasing/Policies/BillPolicy.php` | `listAttachments`, `uploadAttachments` |
| `app/Modules/Inventory/Policies/ItemPolicy.php` | `listAttachments`, `uploadAttachments` |

---

## Database schema (MySQL)

```sql
CREATE TABLE `attachments` (
    `id`                BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `company_id`        BIGINT UNSIGNED NOT NULL,
    `attachable_type`   VARCHAR(50)     NOT NULL,
    `attachable_id`     BIGINT UNSIGNED NOT NULL,
    `kind`              VARCHAR(20)     NOT NULL,
    `filename`          VARCHAR(255)    NOT NULL,
    `disk`              VARCHAR(50)     NOT NULL,
    `path`              VARCHAR(500)    NOT NULL,
    `content_type`      VARCHAR(100)    NOT NULL,
    `byte_size`         BIGINT UNSIGNED NOT NULL,
    `note`              VARCHAR(500)    NULL,
    `include_on_send`   TINYINT(1)      NOT NULL DEFAULT 0,
    `uploaded_by`       BIGINT UNSIGNED NULL,
    `created_at`        TIMESTAMP       NULL,
    `updated_at`        TIMESTAMP       NULL,
    PRIMARY KEY (`id`),
    INDEX `idx_attachments_parent` (`company_id`, `attachable_type`, `attachable_id`),
    INDEX `attachments_company_id_index` (`company_id`),
    CONSTRAINT `attachments_company_id_foreign`
        FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE,
    CONSTRAINT `attachments_uploaded_by_foreign`
        FOREIGN KEY (`uploaded_by`) REFERENCES `users` (`id`) ON DELETE SET NULL
);
```

---

## API endpoints (implemented)

### Flat

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/v1/attachments/{id}` | Metadata |
| `GET` | `/api/v1/attachments/{id}/download` | File download |
| `PATCH` | `/api/v1/attachments/{id}` | Update `note`, `include_on_send` |
| `DELETE` | `/api/v1/attachments/{id}` | Delete file + record |

### Nested — invoices

| Method | Path |
|--------|------|
| `GET` | `/api/v1/invoices/{invoice}/attachments` |
| `POST` | `/api/v1/invoices/{invoice}/attachments` |

### Nested — bills

| Method | Path |
|--------|------|
| `GET` | `/api/v1/bills/{bill}/attachments` |
| `POST` | `/api/v1/bills/{bill}/attachments` |

### Nested — items

| Method | Path |
|--------|------|
| `GET` | `/api/v1/items/{item}/attachments` |
| `POST` | `/api/v1/items/{item}/attachments` |
| `PUT` | `/api/v1/items/{item}/image` |
| `DELETE` | `/api/v1/items/{item}/image` |

All routes use middleware: `auth:sanctum`, `company`.

---

## Architecture

```
Client
  │
  ├─ POST /invoices (JSON) ──────────────────► Invoice created (DRAFT)
  └─ POST /invoices/{id}/attachments (multipart) ► AttachmentService
                                                        │
                        ┌───────────────────────────────┼───────────────────────────────┐
                        ▼                               ▼                               ▼
              AttachmentStorageService          attachments table                  Storage disk
              (local / future R2)               (metadata + path)
```

**Upload flow:** Parent record must exist first. The UI can chain create + upload in one Save action (see [api/attachments.md](./api/attachments.md#client-integration--single-form-quickbooks-style)).

**Cascade:** Deleting a draft invoice or bill triggers `HasAttachments::bootHasAttachments` → `AttachmentService::deleteAllFor()` → removes DB rows and files.

---

## Configuration

`.env`:

```env
ATTACHMENTS_DISK=local
ATTACHMENTS_MAX_SIZE_KB=20480
```

`config/attachments.php`:

| Key | Default | Description |
|-----|---------|-------------|
| `disk` | `local` | Laravel filesystem disk |
| `path_prefix` | `attachments` | Root folder within disk |
| `max_size_kb` | `20480` | 20 MB |
| `allowed_mimes` | pdf, jpeg, png, … | Upload whitelist |

---

## Authorization

| Action | ADMIN | ACCOUNTANT | MANAGER | CASHIER |
|--------|-------|------------|---------|---------|
| List / view / download | ✓ | ✓ | ✓ | ✓ |
| Upload | ✓ | ✓ | ✗ | ✗ |
| Update metadata | ✓ | ✓* | ✗ | ✗ |
| Delete (parent DRAFT) | ✓ | ✓ | ✗ | ✗ |
| Delete (parent posted) | ✓ | ✗ | ✗ | ✗ |

\* Update/delete on posted invoices or received bills: **ADMIN only**.

Nested upload authorization delegates to parent policies (`listAttachments`, `uploadAttachments`).

---

## Business rules

| Rule | Behaviour |
|------|-----------|
| Invoice attachments | Always `kind: DOCUMENT`; `include_on_send` supported |
| Bill attachments | Always `kind: DOCUMENT`; `include_on_send` ignored |
| Item image | `image/*` → `kind: IMAGE`; max 1 (new upload replaces old) |
| Item documents | Non-image → `kind: DOCUMENT`; unlimited |
| File size | Max 20 MB |
| Public URLs | None — download via authenticated API only |
| Post/receive | Attachments optional; not required to post invoice or receive bill |

---

## Test coverage

Run attachment tests:

```bash
php artisan test --filter=Attachment
```

| Suite | Count |
|-------|-------|
| `InvoiceAttachmentApiTest` | 6 |
| `BillAttachmentApiTest` | 5 |
| `ItemAttachmentApiTest` | 4 |
| `AttachmentLifecycleApiTest` | 9 |
| **Total** | **24** |

Full project suite: **226 tests** passing (as of implementation).

---

## Module structure (tree)

```
app/Modules/Attachments/
├── Concerns/
│   └── HasAttachments.php
├── Controllers/Api/
│   ├── AttachmentController.php
│   ├── BillAttachmentController.php
│   ├── InvoiceAttachmentController.php
│   └── ItemAttachmentController.php
├── Enums/
│   ├── AttachableType.php
│   └── AttachmentKind.php
├── Models/
│   └── Attachment.php
├── Policies/
│   └── AttachmentPolicy.php
├── Requests/
│   ├── StoreAttachmentRequest.php
│   └── UpdateAttachmentRequest.php
├── Resources/
│   └── AttachmentResource.php
└── Services/
    ├── AttachmentService.php
    └── AttachmentStorageService.php
```

---

## Related documentation

- [API reference](./api/attachments.md)
- [Staged attachments — bills & invoices](./api/staged-attachments.md)
- [Invoices API](./api/invoices.md)
- [Bills API](./api/bills.md)
- [Items API](./api/items.md)
