# Brix Accounting API — Platform Companies

API reference for **platform administrators** to provision and manage tenant companies.

Platform admins operate outside tenant context (`company_id` is null). Tenant users continue to use [company.md](./company.md) for their own company profile.

---

## Base URL

```
{BASE_URL}/api/v1/platform/companies
```

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

---

## Authentication

Platform endpoints use the **same Sanctum login** as tenant users (`POST /api/v1/login`). The difference is the user account: `company_id` is `null` and the Spatie role is `PLATFORM_ADMIN`.

| Header | Value |
|--------|-------|
| `Authorization` | `Bearer {token}` |
| `Accept` | `application/json` |
| `Content-Type` | `application/json` | On `POST`, `PATCH` |

**Middleware:** `auth:sanctum`, `platform` — does **not** use the `company` middleware.

---

# Platform admin login

## Login

Issue a Sanctum API token for a platform administrator.

```
POST /login
```

**Authentication:** None

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `email` | string | Yes | Valid email |
| `password` | string | Yes | — |

### Example request

```http
POST /api/v1/login
Content-Type: application/json
Accept: application/json

{
  "email": "platform@brix.local",
  "password": "password"
}
```

### Success response — `200 OK`

```json
{
  "token": "1|abcdefghijklmnopqrstuvwxyz",
  "user": {
    "id": 1,
    "name": "Platform Admin",
    "email": "platform@brix.local",
    "role": "ADMIN",
    "active": true,
    "is_platform_admin": true,
    "created_at": "2026-06-17T10:00:00.000000Z"
  }
}
```

> **Note:** `company` is **omitted** for platform admins (`company_id` is null). Tenant logins still include a `company` object. See [auth-and-users.md](./auth-and-users.md).

### Error responses

| Status | Condition |
|--------|-----------|
| `422` | Invalid credentials |
| `422` | Deactivated account (`active` = false) |
| `422` | Missing or invalid `email` / `password` |

---

## Current profile

```
GET /me
```

**Authentication:** `Bearer {token}` only (no `company` middleware)

### Example request

```http
GET /api/v1/me
Authorization: Bearer {token}
Accept: application/json
```

### Success — `200 OK`

```json
{
  "data": {
    "id": 1,
    "name": "Platform Admin",
    "email": "platform@brix.local",
    "role": "ADMIN",
    "active": true,
    "is_platform_admin": true,
    "created_at": "2026-06-17T10:00:00.000000Z"
  }
}
```

> Login returns `user` at the root. `/me` wraps the user in a `data` envelope (Laravel API Resource).

---

## Logout

```
POST /logout
```

**Authentication:** `Bearer {token}`

### Example request

```http
POST /api/v1/logout
Authorization: Bearer {token}
Accept: application/json
```

### Success — `200 OK`

```json
{
  "message": "Logged out successfully."
}
```

---

## Using the token on platform routes

After login, send the token on every platform request:

```http
GET /api/v1/platform/companies
Authorization: Bearer {token}
Accept: application/json
```

### JavaScript example

```javascript
const response = await fetch('http://127.0.0.1:8000/api/v1/login', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'platform@brix.local',
    password: 'password',
  }),
});

const { token } = await response.json();

const companies = await fetch('http://127.0.0.1:8000/api/v1/platform/companies', {
  headers: {
    'Accept': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
});
```

---

## Seeded platform admin (development)

After `php artisan migrate --seed` (or `php database/scripts/recreate_database.php` then `php artisan migrate --seed` if the DB was corrupted):

| Field | Value |
|-------|-------|
| Email | `platform@brix.local` |
| Password | `password` |
| Spatie role | `PLATFORM_ADMIN` |
| `company_id` | `null` |
| `is_platform_admin` on login | `true` |

### Creating a platform admin manually

```bash
php artisan db:seed --class=PlatformAdminSeeder
```

Or via Tinker:

```php
use App\Modules\Auth\Models\User;
use Spatie\Permission\Models\Role;

Role::firstOrCreate(['name' => 'PLATFORM_ADMIN', 'guard_name' => 'web']);

$admin = User::withoutGlobalScopes()->create([
    'company_id' => null,
    'name'       => 'Platform Admin',
    'email'      => 'your-admin@yourdomain.com',
    'password'   => 'your-secure-password',
    'role'       => 'ADMIN',
    'active'     => true,
]);
$admin->assignRole('PLATFORM_ADMIN');
```

> There is no self-service password-change API for platform admins in v1. Use Tinker or direct DB update to change the password.

---

## Platform admin vs tenant login

| | Platform admin | Tenant user |
|--|----------------|-------------|
| Login endpoint | `POST /api/v1/login` | Same |
| `user.company` | Omitted | Present |
| `user.is_platform_admin` | `true` | `false` |
| `GET /me` | ✓ | ✓ |
| `GET /platform/companies` | ✓ | ✗ (403) |
| `GET /company` | ✗ (403 — no company context) | ✓ |
| Invoices, bills, reports | ✗ (403) | ✓ |

Use a **separate platform admin UI** (or API client). Do not use the tenant accounting frontend with a platform admin account.

---

## Role permissions

| Action | PLATFORM_ADMIN | Tenant ADMIN |
|--------|----------------|--------------|
| List companies | ✓ | ✗ |
| Create company | ✓ | ✗ |
| View any company | ✓ | ✗ |
| Update any company | ✓ | ✗ |
| `GET/PATCH /company` (own tenant) | ✗ | ✓ |
| Business APIs (invoices, bills, …) | ✗ | ✓ |

---

## Company object (platform)

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Primary key |
| `name` | string | Max 200 |
| `email` | string \| null | Max 150 |
| `phone` | string \| null | Max 30 |
| `address` | string \| null | |
| `tax_number` | string \| null | Max 50 |
| `currency` | string | ISO 4217, 3 chars. Default `LKR` |
| `active` | boolean | Platform-level flag |
| `users_count` | integer | Included on list/show |
| `created_at` | datetime | |
| `updated_at` | datetime | |

---

# Endpoints

## List companies

```
GET /platform/companies
```

### Query parameters

| Param | Type | Description |
|-------|------|-------------|
| `search` | string | Match `name`, `email`, `tax_number` |
| `active` | boolean | Filter by active flag |
| `page` | integer | Default `1` |
| `per_page` | integer | Default `15`, max `100` |
| `sort` | string | `name`, `-name`, `created_at`, `-created_at` |

### Example

```http
GET /api/v1/platform/companies?search=acme&active=1
Authorization: Bearer {token}
Accept: application/json
```

### Success — `200 OK`

Paginated `data` array of company objects with `users_count`.

---

## Create company

```
POST /platform/companies
```

Atomically creates the company, first `ADMIN` user, default chart of accounts (16 accounts), and default tax codes (4).

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `name` | string | Yes | Max 200 |
| `email` | string | No | Email, max 150 |
| `phone` | string | No | Max 30 |
| `address` | string | No | |
| `tax_number` | string | No | Max 50 |
| `currency` | string | No | 3 chars. Default `LKR` |
| `active` | boolean | No | Default `true` |
| `admin.name` | string | Yes | Max 150 |
| `admin.email` | string | Yes | Email, max 150, must not already exist on any user account |
| `admin.password` | string | Yes | Min 8 |
| `admin.active` | boolean | No | Default `true` |
| `bootstrap.chart_of_accounts` | boolean | No | Default `true` |
| `bootstrap.tax_codes` | boolean | No | Default `true` |

### Example

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

{
  "name": "Acme Trading",
  "email": "contact@acme.com",
  "currency": "LKR",
  "admin": {
    "name": "Acme Admin",
    "email": "admin@acme.com",
    "password": "secure-password"
  }
}
```

### Success — `201 Created`

```json
{
  "data": {
    "company": {
      "id": 2,
      "name": "Acme Trading",
      "email": "contact@acme.com",
      "currency": "LKR",
      "active": true
    },
    "admin": {
      "id": 5,
      "name": "Acme Admin",
      "email": "admin@acme.com",
      "role": "ADMIN",
      "active": true,
      "company_id": 2
    },
    "bootstrap": {
      "accounts_created": 16,
      "tax_codes_created": 4
    }
  }
}
```

---

## Get company

```
GET /platform/companies/{id}
```

### Success — `200 OK`

Single company object with `users_count`.

---

## Update company

```
PATCH /platform/companies/{id}
```

Update tenant profile or deactivate at platform level. No hard delete in v1.

### Request body (all optional)

Same fields as create (except `admin` and `bootstrap`).

### Example — deactivate

```http
PATCH /api/v1/platform/companies/2
Authorization: Bearer {token}
Content-Type: application/json

{
  "active": false
}
```

### Success — `200 OK`

Updated company object.

---

## Error responses

| Status | When |
|--------|------|
| `401` | Missing or invalid token |
| `403` | Not `PLATFORM_ADMIN`, or platform admin on tenant routes |
| `404` | Company not found |
| `422` | Validation error |

---

## Related docs

- [auth-and-users.md](./auth-and-users.md) — login, tenant user management
- [company.md](./company.md) — tenant self-service company profile
