# Contrato — Perfis VM123 (FOSSBilling · Odoo · OpenPanel)

**Spec:** 027 · **VM:** `10.10.10.123` · **Atualizado:** 2026-06-19

Este documento define **como mapear** cada função Desk Ligbox para perfis nos três produtos da VM123 e quais **APIs** o Desk (VM122) deve usar na Fase 3 de provisionamento.

---

## 1. Arquitectura de integração

```text
Utilizador humano
    → Login Desk (VM122) — role: sales_admin | sales_support | finance | …
    → Desk API valida RBAC (Spec 027)
    → Opcional: provisionamento / deep-link VM123
         ├── FOSSBilling  REST  /api/admin/*
         ├── Odoo 16      XML-RPC  /odoo/xmlrpc/2/{common,object}
         └── OpenPanel    REST  :2087 (Enterprise) ou bridge :18087 (Community)
```

**Conta de serviço Desk (M2M):** `api_service` com API keys por produto — **nunca** credenciais pessoais do Roger.

| Segredo | Onde | Uso |
|---------|------|-----|
| `FOSS_ADMIN_API_KEY` | VM122 `.env` | Basic Auth `admin:KEY` → `/api/admin/*` |
| `ODOO_API_KEY` + login | VM122 `.env` | XML-RPC `authenticate` + `execute_kw` |
| `OPENPANEL_BRIDGE_TOKEN` | VM122 + bridge | Bearer → `http://10.10.10.123:18087` |
| `OPENPANEL_JWT` | VM122 (futuro Enterprise) | Bearer → `:2087/api/*` |

---

## 2. FOSSBilling — API e perfis staff

**Base URL:** `https://financeiro.ligbox.com.br/api/admin/`  
**Auth:** HTTP Basic — username `admin`, password = **API key** (FOSS Admin → perfil staff → API key)

**Padrão endpoint:** `/api/admin/{module}/{action}`

### Grupos staff FOSS (criar no Admin → Staff → Groups)

| ID grupo (criar) | Nome | Função Desk mapeada |
|------------------|------|---------------------|
| `ligbox-finance-admin` | Financeiro Admin | `finance`, `super_admin` |
| `ligbox-sales-admin` | Sales Admin (Gerente) | `sales_admin` |
| `ligbox-sales-support` | Sales Support (Analista) | `sales_support` |
| `ligbox-marketing` | Marketing Produtos | `marketing` |
| `ligbox-dev-api` | Developer API | `developer`, `api_service` |

### Criar staff via API

```http
POST /api/admin/staff/create
Authorization: Basic base64(admin:FOSS_ADMIN_API_KEY)
Content-Type: application/json

{
  "email": "gerente.comercial@ligbox.com.br",
  "password": "<gerado>",
  "name": "Gerente Comercial",
  "admin_group_id": <id ligbox-sales-admin>,
  "status": "active"
}
```

### Permissões por função — módulos FOSS

| Módulo FOSS | sales_admin | sales_support | finance | marketing | developer |
|-------------|:-----------:|:-------------:|:-------:|:---------:|:---------:|
| `client` (CRUD) | ✅ | ✅ sem delete | ✅ | 🔒 | ⚙️ API |
| `order` (criar/pedidos) | ✅ | ✅ | 🔒 | ❌ | ⚙️ |
| `invoice` | ✅ | 🔒 | ✅ | ❌ | ❌ |
| `product` / `service` | ✅ | 🔒 | 🔒 | ✅ | ⚙️ |
| `staff` / `extension` settings | ❌ | ❌ | 🔒 | ❌ | ⚙️ |
| `support` (tickets FOSS) | ✅ | ✅ | 🔒 | ❌ | ❌ |
| Hosting OpenPanel module | ✅ | ✅ provision | 🔒 | ❌ | ⚙️ |

### Endpoints Desk → FOSS (Fase 3)

| Acção Desk | Endpoint FOSS |
|------------|---------------|
| Abrir ficha cliente | `GET /api/admin/client/get?id={id}` |
| Listar clientes domínio | `GET /api/admin/client/get_list` + filtro email |
| Criar pedido site CMS | `POST /api/admin/order/create` + produto `ligbox-site-cms` |
| Estado assinatura | `GET /api/admin/invoice/get_list` |
| Provisionar OpenPanel | módulo hosting → bridge (Spec 024) |

---

## 3. Odoo 16 — API e grupos

**Base URL:** `https://financeiro.ligbox.com.br/odoo`  
**DB:** `ligbox`  
**Protocolo:** XML-RPC (v16)

```python
# Autenticação
common.authenticate(db, login, api_key, {})
# Operações
models.execute_kw(db, uid, api_key, 'res.partner', 'search_read', [[('email','=','...')]], {'fields': ['name','vat']})
```

### Grupos Odoo (Settings → Users → Groups — criar ou usar standard)

> **Estado VM123 (2026-06-19):** ✅ Apps instaladas via `install-odoo-apps.sh`:
> `crm`, `sale`, `sale_management`, `account`, `contacts` (+ dependências, 61 módulos).
> Grupos standard disponíveis para provisionamento Desk.

| XML ID Odoo (standard / custom) | Função Desk |
|---------------------------------|-------------|
| `sales_team.group_sale_salesman` | `sales_support`, `marketing` (CRM leads) |
| `sales_team.group_sale_manager` | `sales_admin` |
| `account.group_account_invoice` | `finance` |
| `account.group_account_manager` | `finance` + `super_admin` |
| `base.group_system` | `super_admin` apenas |

### Criar / actualizar utilizador Odoo via API

```python
# Obter group id
gid = models.execute_kw(db, uid, key, 'res.groups', 'search', [[('name','=','Sales / Manager')]])

models.execute_kw(db, uid, key, 'res.users', 'create', [{
    'name': 'Gerente Comercial',
    'login': 'gerente.comercial@ligbox.com.br',
    'email': 'gerente.comercial@ligbox.com.br',
    'groups_id': [(6, 0, gid)],
}])
```

### Permissões por função — apps Odoo

| App Odoo | sales_admin | sales_support | finance | marketing |
|----------|:-----------:|:-------------:|:-------:|:---------:|
| CRM / Sales | ✅ manager | ✅ user | 🔒 | 🔒 leads |
| Invoicing | 🔒 | 🔒 | ✅ | ❌ |
| Contacts (res.partner) | ✅ | ✅ | ✅ | 🔒 |
| Accounting | ❌ | ❌ | ✅ | ❌ |
| Website / eCommerce | 🔒 | ❌ | ❌ | ✅ |

**Nota:** Odoo é **ERP interno Ligbox** — não expor ao cliente final (Spec 024).

---

## 4. OpenPanel — API e perfis

### Edição actual: Community + Bridge

| Componente | URL | Auth |
|------------|-----|------|
| OpenAdmin UI | `https://admin.openpanel.ligbox.com.br:2087` | user/pass |
| Bridge Ligbox | `http://10.10.10.123:18087` | Bearer `BRIDGE_TOKEN` |
| FOSS → OpenPanel | FOSS chama bridge `:18087` | Spec 024 |

**OpenAdmin API Enterprise** (`POST :2087/api/` → JWT) — disponível após upgrade Enterprise. Até lá, Desk usa **bridge** + OpenAdmin UI manual.

### Roles OpenAdmin (nativos)

| Role OpenPanel | Função Desk mapeada |
|----------------|---------------------|
| Super Admin | `super_admin`, `devops` |
| Admin | `sales_admin`, `devops` (limitado) |
| Reseller | futuro revendedor — não usar no MVP |
| User (hosting) | cliente final — **não** é staff Ligbox |

### Bridge API (Community — já em produção)

| Método | Path | Uso |
|--------|------|-----|
| `POST` | `/api` | Obter `access_token` (user/pass admin API) |
| `POST` | `/api/users` | Criar conta hosting (`username`, `password`, `email`, `plan_name`) |
| `PATCH` | `/api/users/{username}` | `suspend` / `unsuspend` / password |
| `DELETE` | `/api/users/{username}` | Remover conta |

Implementação: `deploy/vm123-finance-stack/openpanel-community-bridge/bridge.py`

### Permissões por função — OpenPanel

| Acção | sales_admin | sales_support | marketing | seo | content_editor | devops |
|-------|:-----------:|:-------------:|:---------:|:---:|:--------------:|:------:|
| OpenAdmin login | 🔗 Admin | ❌ | 🔗 limitado | 🔗 | 🔗 | ✅ |
| Criar user hosting (API) | ⚙️ via Desk | ⚙️ via Desk | ⚙️ | ❌ | ⚙️ | ✅ |
| Suspend/unsuspend | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
| CONNECT autologin cliente | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Plans / server config | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |

**CONNECT autologin** (Enterprise API): `CONNECT /api/users/{username}` — Desk gera link temporário para `sales_support` ver site do cliente sem password.

---

## 5. Tabela mestre — Função Desk → Produto VM123

| Função Desk | FOSSBilling group | Odoo groups | OpenPanel |
|-------------|-------------------|-------------|-----------|
| `super_admin` | Full admin | `base.group_system` | Super Admin |
| `finance` | `ligbox-finance-admin` | Account Manager + Invoice | 🔒 read OpenAdmin |
| `sales_admin` | `ligbox-sales-admin` | Sales Manager | Admin (ou API only) |
| `sales_support` | `ligbox-sales-support` | Salesman | CONNECT autologin |
| `marketing` | `ligbox-marketing` | — | User sites / campanhas |
| `seo` | — | — | CONNECT + DNS externo |
| `content_editor` | — | — | CONNECT + edit site |
| `developer` | `ligbox-dev-api` | — | bridge API |
| `api_service` | API key M2M | API key M2M | bridge token |

---

## 6. Fluxo provisionamento (Fase 3 — ao aprovar utilizador Desk)

```mermaid
sequenceDiagram
    participant R as root Desk
    participant D as Desk API VM122
    participant F as FOSSBilling
    participant O as Odoo
    participant P as OpenPanel bridge

    R->>D: PATCH /auth/users approve role=sales_support
    D->>F: POST /api/admin/staff/create
    D->>O: res.users create + groups_id
    Note over D,P: OpenPanel só se função precisa hosting
    D->>P: POST /api/users (opcional plano demo)
    D->>R: Email credenciais + deep-links
```

**Regra:** `sales_support` **não** recebe OpenAdmin — só FOSS staff + Odoo salesman + autologin clientes.

---

## 7. Endpoints Desk novos (proposta Fase 3)

| Método | Path | Role |
|--------|------|------|
| `GET` | `/api/v1/vm123/foss/client/{domain}` | finance, sales_admin, sales_support |
| `POST` | `/api/v1/vm123/foss/order` | sales_admin, sales_support |
| `GET` | `/api/v1/vm123/odoo/partner?email=` | finance, sales_admin, sales_support |
| `POST` | `/api/v1/vm123/openpanel/autologin/{username}` | sales_admin, sales_support, content_editor, seo |
| `POST` | `/api/v1/provision/user` | super_admin (dispara fluxo §6) |

---

## 8. Referências

- FOSSBilling API: https://docs.fossbilling.org/developing-fossbilling/api/
- Odoo 16 External API: https://www.odoo.com/documentation/16.0/developer/reference/external_api.html
- OpenAdmin API: https://openpanel.com/docs/articles/dev-experience/openadmin-api/
- Bridge Community: `deploy/vm123-finance-stack/openpanel-community-bridge/bridge.py`
- Spec 024: stack VM123
- Spec 023: card billing Desk
