diff --git a/ligbox-ops-platform/_sidebar.md b/ligbox-ops-platform/_sidebar.md new file mode 100644 index 0000000..52e9473 --- /dev/null +++ b/ligbox-ops-platform/_sidebar.md @@ -0,0 +1,213 @@ +# Ligbox Spec Kit +- [🏠 Hub](/) +- [📋 Inventário VMs](docs/vms/README.md) +- [📜 Constitution](.specify/memory/constitution.md) +- [📌 Backlog](BACKLOG.md) +--- +## VM112 — Onboard / Mail +- **001-webhook-vm112-integration** + - [📄 spec.md](specs/001-webhook-vm112-integration/spec.md) + - [plan.md](specs/001-webhook-vm112-integration/plan.md) + - [tasks.md](specs/001-webhook-vm112-integration/tasks.md) + - [quickstart.md](specs/001-webhook-vm112-integration/quickstart.md) + - [research.md](specs/001-webhook-vm112-integration/research.md) + - [data-model.md](specs/001-webhook-vm112-integration/data-model.md) + - **contracts/** + - [webhook-onboard](specs/001-webhook-vm112-integration/contracts/webhook-onboard.md) + - **checklists/** + - [requirements](specs/001-webhook-vm112-integration/checklists/requirements.md) +- **017-vm112-domain-orchestration** + - [📄 spec.md](specs/017-vm112-domain-orchestration/spec.md) +- **022-carbonio-account-exists-release** + - [📄 spec.md](specs/022-carbonio-account-exists-release/spec.md) + - [tasks.md](specs/022-carbonio-account-exists-release/tasks.md) +- **025-wizard-onboarding-continuity** + - [📄 spec.md](specs/025-wizard-onboarding-continuity/spec.md) + - [tasks.md](specs/025-wizard-onboarding-continuity/tasks.md) +- **026-purge-traefik-validation** + - [📄 spec.md](specs/026-purge-traefik-validation/spec.md) +- **010-desk-assist-takeover** + - [📄 spec.md](specs/010-desk-assist-takeover/spec.md) + - [tasks.md](specs/010-desk-assist-takeover/tasks.md) + - [quickstart.md](specs/010-desk-assist-takeover/quickstart.md) +## VM122 — Ops Desk +- **003-desk-auth-rbac** + - [📄 spec.md](specs/003-desk-auth-rbac/spec.md) + - [plan.md](specs/003-desk-auth-rbac/plan.md) + - [tasks.md](specs/003-desk-auth-rbac/tasks.md) + - [quickstart.md](specs/003-desk-auth-rbac/quickstart.md) + - [research.md](specs/003-desk-auth-rbac/research.md) + - [data-model.md](specs/003-desk-auth-rbac/data-model.md) + - **contracts/** + - [auth-api](specs/003-desk-auth-rbac/contracts/auth-api.md) + - **checklists/** + - [requirements](specs/003-desk-auth-rbac/checklists/requirements.md) +- **004-desk-account-management** + - [📄 spec.md](specs/004-desk-account-management/spec.md) + - [tasks.md](specs/004-desk-account-management/tasks.md) + - [quickstart.md](specs/004-desk-account-management/quickstart.md) +- **004-onboard-funnel-events** + - [📄 spec.md](specs/004-onboard-funnel-events/spec.md) + - [plan.md](specs/004-onboard-funnel-events/plan.md) + - [tasks.md](specs/004-onboard-funnel-events/tasks.md) + - [research.md](specs/004-onboard-funnel-events/research.md) + - [cloudflare-zone-provision.md](specs/004-onboard-funnel-events/cloudflare-zone-provision.md) + - **contracts/** + - [webhook-funnel-events](specs/004-onboard-funnel-events/contracts/webhook-funnel-events.md) + - **checklists/** + - [requirements](specs/004-onboard-funnel-events/checklists/requirements.md) +- **009-ops-audit-overview** + - [📄 spec.md](specs/009-ops-audit-overview/spec.md) + - [plan.md](specs/009-ops-audit-overview/plan.md) + - [tasks.md](specs/009-ops-audit-overview/tasks.md) + - [research.md](specs/009-ops-audit-overview/research.md) + - **contracts/** + - [audit-api](specs/009-ops-audit-overview/contracts/audit-api.md) + - **checklists/** + - [requirements](specs/009-ops-audit-overview/checklists/requirements.md) +- **010-admin-domain-validation** + - [📄 spec.md](specs/010-admin-domain-validation/spec.md) + - [correcao-vm112.md](specs/010-admin-domain-validation/correcao-vm112.md) +- **012-abandoned-onboarding-lead** + - [📄 spec.md](specs/012-abandoned-onboarding-lead/spec.md) + - [tasks.md](specs/012-abandoned-onboarding-lead/tasks.md) + - [quickstart.md](specs/012-abandoned-onboarding-lead/quickstart.md) +- **015-desk-module-registry** + - [📄 spec.md](specs/015-desk-module-registry/spec.md) +- **027-desk-rbac-function-matrix** + - [📄 spec.md](specs/027-desk-rbac-function-matrix/spec.md) + - [quickstart.md](specs/027-desk-rbac-function-matrix/quickstart.md) + - [data-model.md](specs/027-desk-rbac-function-matrix/data-model.md) + - [ui-access-matrix.md](specs/027-desk-rbac-function-matrix/ui-access-matrix.md) + - **contracts/** + - [vm123-product-roles](specs/027-desk-rbac-function-matrix/contracts/vm123-product-roles.md) +## VM123 — Finance / Console +- **019-ops-console-active-operations** + - [📄 spec.md](specs/019-ops-console-active-operations/spec.md) + - [plan.md](specs/019-ops-console-active-operations/plan.md) + - [tasks.md](specs/019-ops-console-active-operations/tasks.md) + - [README.md](specs/019-ops-console-active-operations/README.md) + - **contracts/** + - [chamados-api](specs/019-ops-console-active-operations/contracts/chamados-api.md) + - **design/** + - [navigation-ia](specs/019-ops-console-active-operations/design/navigation-ia.md) +- **023-billing-recurrence-desk-visibility** + - [📄 spec.md](specs/023-billing-recurrence-desk-visibility/spec.md) + - [tasks.md](specs/023-billing-recurrence-desk-visibility/tasks.md) +- **024-openpanel-fossbilling** + - [📄 spec.md](specs/024-openpanel-fossbilling/spec.md) + - [tasks.md](specs/024-openpanel-fossbilling/tasks.md) + - [PROVISIONING_CLIENT_CARD.md](specs/024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md) +- **019-email-migration-vm122-execution** + - [📄 spec.md](specs/019-email-migration-vm122-execution/spec.md) + - [tasks.md](specs/019-email-migration-vm122-execution/tasks.md) +## VM104 — Wazuh +- **002-wazuh-integration** + - [📄 spec.md](specs/002-wazuh-integration/spec.md) + - [plan.md](specs/002-wazuh-integration/plan.md) + - [tasks.md](specs/002-wazuh-integration/tasks.md) +## CT130 — Spec Hub +- **031-spec-hub-portal** + - [📄 spec.md](specs/031-spec-hub-portal/spec.md) +## Outras specs +- **007-mobile-push-notifications** + - [📄 spec.md](specs/007-mobile-push-notifications/spec.md) + - [tasks.md](specs/007-mobile-push-notifications/tasks.md) + - [quickstart.md](specs/007-mobile-push-notifications/quickstart.md) +- **011-integration-otrs** + - [📄 spec.md](specs/011-integration-otrs/spec.md) +- **011-mail-tls-wizard-validation** + - [📄 spec.md](specs/011-mail-tls-wizard-validation/spec.md) + - [README.md](specs/011-mail-tls-wizard-validation/README.md) +- **013-email-server-migration** + - [📄 spec.md](specs/013-email-server-migration/spec.md) + - [plan.md](specs/013-email-server-migration/plan.md) + - [tasks.md](specs/013-email-server-migration/tasks.md) + - [quickstart.md](specs/013-email-server-migration/quickstart.md) + - [research.md](specs/013-email-server-migration/research.md) + - [data-model.md](specs/013-email-server-migration/data-model.md) + - [infrastructure.md](specs/013-email-server-migration/infrastructure.md) +- **014-funnel-phase-timing** + - [📄 spec.md](specs/014-funnel-phase-timing/spec.md) +- **016-onboard-self-service-prefill** + - [📄 spec.md](specs/016-onboard-self-service-prefill/spec.md) + - [tasks.md](specs/016-onboard-self-service-prefill/tasks.md) + - [BACKLOG-2FA-BACKUP-EXPORT.md](specs/016-onboard-self-service-prefill/BACKLOG-2FA-BACKUP-EXPORT.md) +- **018-service-orchestration** + - [📄 spec.md](specs/018-service-orchestration/spec.md) +- **020-purge-history-desk** + - [📄 spec.md](specs/020-purge-history-desk/spec.md) +- **021-wizard-cybersecurity-telemetry** + - [📄 spec.md](specs/021-wizard-cybersecurity-telemetry/spec.md) + - [tasks.md](specs/021-wizard-cybersecurity-telemetry/tasks.md) +- **028-openpanel-ce-ligbox-reengineering** + - [📄 spec.md](specs/028-openpanel-ce-ligbox-reengineering/spec.md) + - [tasks.md](specs/028-openpanel-ce-ligbox-reengineering/tasks.md) + - [quickstart.md](specs/028-openpanel-ce-ligbox-reengineering/quickstart.md) + - [CONFIRMACAO-TESTE-API.md](specs/028-openpanel-ce-ligbox-reengineering/CONFIRMACAO-TESTE-API.md) + - [DNS53_OPENPANEL_PORTA53.md](specs/028-openpanel-ce-ligbox-reengineering/DNS53_OPENPANEL_PORTA53.md) + - **contracts/** + - [foss-bridge-api](specs/028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md) +- **029-agentic-ops-runbooks** + - [📄 spec.md](specs/029-agentic-ops-runbooks/spec.md) + - [tasks.md](specs/029-agentic-ops-runbooks/tasks.md) + - [quickstart.md](specs/029-agentic-ops-runbooks/quickstart.md) + - [agents-roster.md](specs/029-agentic-ops-runbooks/agents-roster.md) + - **contracts/** + - [agent-platform-api](specs/029-agentic-ops-runbooks/contracts/agent-platform-api.md) +- **029-tickets-workspace** + - [📄 spec.md](specs/029-tickets-workspace/spec.md) + - [ARCHITECTURE.md](specs/029-tickets-workspace/ARCHITECTURE.md) + - [CORRETIVO-20260619-tickets-rebuild.md](specs/029-tickets-workspace/CORRETIVO-20260619-tickets-rebuild.md) +- **030-agentic-ops-ui** + - [📄 spec.md](specs/030-agentic-ops-ui/spec.md) + - [tasks.md](specs/030-agentic-ops-ui/tasks.md) + - **contracts/** + - [agentic-ui-api](specs/030-agentic-ops-ui/contracts/agentic-ui-api.md) + - **design/** + - [wireframes](specs/030-agentic-ops-ui/design/wireframes.md) +- **032-purge-domain-extra-auth** + - [📄 spec.md](specs/032-purge-domain-extra-auth/spec.md) +- **033-desk-infra-console-ui** + - [📄 spec.md](specs/033-desk-infra-console-ui/spec.md) +- **034-nextcloud-carbonio-vm112-integration** + - [📄 spec.md](specs/034-nextcloud-carbonio-vm112-integration/spec.md) + - [tasks.md](specs/034-nextcloud-carbonio-vm112-integration/tasks.md) + - [quickstart.md](specs/034-nextcloud-carbonio-vm112-integration/quickstart.md) + - [infrastructure.md](specs/034-nextcloud-carbonio-vm112-integration/infrastructure.md) + - [034-console-process-ui.md](specs/034-nextcloud-carbonio-vm112-integration/034-console-process-ui.md) + - **contracts/** + - [nextcloud-provisioning-api](specs/034-nextcloud-carbonio-vm112-integration/contracts/nextcloud-provisioning-api.md) +- **035-ligbox-mail-bundles-foss-openpanel** + - [📄 spec.md](specs/035-ligbox-mail-bundles-foss-openpanel/spec.md) + - [tasks.md](specs/035-ligbox-mail-bundles-foss-openpanel/tasks.md) + - [domain-manager-console-ui.md](specs/035-ligbox-mail-bundles-foss-openpanel/domain-manager-console-ui.md) + - [foss-products.md](specs/035-ligbox-mail-bundles-foss-openpanel/foss-products.md) + - [ligbox-console-shell.md](specs/035-ligbox-mail-bundles-foss-openpanel/ligbox-console-shell.md) + - [ligbox-system-admin-ui.md](specs/035-ligbox-mail-bundles-foss-openpanel/ligbox-system-admin-ui.md) + - [user-self-service-ui.md](specs/035-ligbox-mail-bundles-foss-openpanel/user-self-service-ui.md) +- **035-ligbox-watchman** + - [📄 spec.md](specs/035-ligbox-watchman/spec.md) + - [tasks.md](specs/035-ligbox-watchman/tasks.md) + - [quickstart.md](specs/035-ligbox-watchman/quickstart.md) + - **contracts/** + - [status-snapshot](specs/035-ligbox-watchman/contracts/status-snapshot.md) +- **036-backstage-techdocs-speckit-companion** + - [📄 spec.md](specs/036-backstage-techdocs-speckit-companion/spec.md) + - [tasks.md](specs/036-backstage-techdocs-speckit-companion/tasks.md) + - [quickstart.md](specs/036-backstage-techdocs-speckit-companion/quickstart.md) +- **037-dns-multi-cloudflare-orchestration** + - [📄 spec.md](specs/037-dns-multi-cloudflare-orchestration/spec.md) + - [tasks.md](specs/037-dns-multi-cloudflare-orchestration/tasks.md) + - [cf-agents-sdk-architecture.md](specs/037-dns-multi-cloudflare-orchestration/cf-agents-sdk-architecture.md) + - [client-cf-account-lifecycle.md](specs/037-dns-multi-cloudflare-orchestration/client-cf-account-lifecycle.md) + - [implementation-phases.md](specs/037-dns-multi-cloudflare-orchestration/implementation-phases.md) + - [project-email-identity.md](specs/037-dns-multi-cloudflare-orchestration/project-email-identity.md) + - [wizard-validation-checklist.md](specs/037-dns-multi-cloudflare-orchestration/wizard-validation-checklist.md) +- **043-desk-client-activation-sync** ⭐ mapa Wizard→FOSS→OpenPanel→Odoo + - [📄 spec.md](specs/043-desk-client-activation-sync/spec.md) + - [tasks.md](specs/043-desk-client-activation-sync/tasks.md) + - [ROLLBACK.md](specs/043-desk-client-activation-sync/ROLLBACK.md) + - **contracts/** + - [activation-field-mapping.md](specs/043-desk-client-activation-sync/contracts/activation-field-mapping.md) — **fonte única** + - [desk-activate-account-api.md](specs/043-desk-client-activation-sync/contracts/desk-activate-account-api.md) diff --git a/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/spec.md b/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/spec.md index 1b6a9b3..3f14bf2 100644 --- a/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/spec.md +++ b/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/spec.md @@ -7,7 +7,7 @@ **Sistemas:** Wizard VM112 · Desk VM122 · Motor de cobrança (fase 2) **Módulo Desk:** `billing-recurrence` (novo — Spec 015) **Depende de:** Spec 012 (tickets onboarding), Spec 018 (Serviços / clientes), Spec 021 (webhooks) -**Relacionado:** Card wizard «Dados da empresa e cobrança» (imagem Roger, 2026-06-17) +**Relacionado:** Card wizard «Dados da empresa e cobrança» (imagem Roger, 2026-06-17) · **[Spec 043 — mapa campos FOSS/OP/Odoo](../043-desk-client-activation-sync/contracts/activation-field-mapping.md)** --- diff --git a/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/tasks.md b/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/tasks.md index 6fe09aa..fa35bfb 100644 --- a/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/tasks.md +++ b/ligbox-ops-platform/specs/023-billing-recurrence-desk-visibility/tasks.md @@ -20,7 +20,7 @@ - [x] Deploy api + frontend VM122 ## Fase 2 — Odoo cobrança -- [ ] Cliente Odoo `res.partner` a partir de `company_profile` +- [ ] Cliente Odoo `res.partner` a partir de `company_profile` — ver [Spec 043 §6](../043-desk-client-activation-sync/contracts/activation-field-mapping.md) - [ ] Produto/plano assinatura e-mail tenant - [ ] Integração ASAAS/Iugu - [ ] Webhook pagamento → `billing_state` diff --git a/ligbox-ops-platform/specs/024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md b/ligbox-ops-platform/specs/024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md index 2c10868..215855a 100644 --- a/ligbox-ops-platform/specs/024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md +++ b/ligbox-ops-platform/specs/024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md @@ -1,6 +1,7 @@ # Spec 024 — Card cliente → FOSS → OpenPanel (provisionamento) -**Roger · 2026-06-17** +**Roger · 2026-06-17** +**Mapa completo (mail + Odoo):** [Spec 043 activation-field-mapping.md](../043-desk-client-activation-sync/contracts/activation-field-mapping.md) ## O teu raciocínio está correto diff --git a/ligbox-ops-platform/specs/024-openpanel-fossbilling/spec.md b/ligbox-ops-platform/specs/024-openpanel-fossbilling/spec.md index 3919a47..deec132 100644 --- a/ligbox-ops-platform/specs/024-openpanel-fossbilling/spec.md +++ b/ligbox-ops-platform/specs/024-openpanel-fossbilling/spec.md @@ -5,7 +5,7 @@ **Status:** ✅ Concluída (v1 piloto) — 2026-06-17 **Prioridade:** P1 **Decisão:** **FOSSBilling** + **OpenPanel** + **Odoo V16** · gateway pagamento fase futura -**Relacionado:** Spec 023 (Desk 💳), Spec 018 (Serviços) +**Relacionado:** Spec 023 (Desk 💳), Spec 018 (Serviços) · **[Spec 043 — mapa activação cliente](../043-desk-client-activation-sync/contracts/activation-field-mapping.md)** --- diff --git a/ligbox-ops-platform/specs/028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md b/ligbox-ops-platform/specs/028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md new file mode 100644 index 0000000..cd8dc83 --- /dev/null +++ b/ligbox-ops-platform/specs/028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md @@ -0,0 +1,55 @@ +# Contrato — Bridge FOSS ↔ OpenPanel (Ligbox v2) + +**Base URL:** `http://10.10.10.123:18087` +**Auth:** Bearer token (obtido via POST `/api` com credenciais OpenAdmin) + +## POST /api — login + +**Request:** +```json +{"username": "ligboxadmin", "password": "LbOpen805353"} +``` + +**Response 200:** +```json +{"access_token": "ligbox-community-bridge-token"} +``` + +## POST /api/users — provisionar + +**Headers:** `Authorization: Bearer ` + +**Request:** +```json +{ + "username": "string [a-z][a-z0-9]{2,15}", + "password": "string", + "email": "string", + "plan_name": "ligbox-site-cms", + "domain": "string (opcional mas recomendado)" +} +``` + +**Response 200:** +```json +{ + "success": true, + "response": { + "message": "Successfully added user ...\nDomain ... added successfully", + "username": "cliente1", + "domain": "cliente1.com" + } +} +``` + +## Compatibilidade FOSSBilling OpenPanel.php + +O módulo oficial envia `username`, `password`, `email`, `plan_name`. +Patch Ligbox adiciona `domain` via `$account->getDomain()`. + +FOSS considera sucesso se `success: true` OU mensagem contém `Successfully added user`. + +## SLA operacional + +- Timeout recomendado: **180s** por request (provisionamento Docker) +- Retry: não automático — idempotência parcial (user exists → erro) diff --git a/ligbox-ops-platform/specs/028-openpanel-ce-ligbox-reengineering/spec.md b/ligbox-ops-platform/specs/028-openpanel-ce-ligbox-reengineering/spec.md new file mode 100644 index 0000000..36a1b90 --- /dev/null +++ b/ligbox-ops-platform/specs/028-openpanel-ce-ligbox-reengineering/spec.md @@ -0,0 +1,291 @@ +# Spec 028 — OpenPanel CE Ligbox Re-engenharia (Enterprise Local) + +**Criado:** 2026-06-19 +**Solicitado por:** Roger +**Status:** ✅ Implementado (VM123) — E2E FOSS validado +**Prioridade:** P0 (hosting comercial sem licença Enterprise paga) +**VM alvo:** **VM123** (`10.10.10.123`) +**Relacionado:** Spec **024** (FOSS+OpenPanel), Spec **027** (RBAC Desk), Spec **018** (Serviços) · **[Spec 043 — mapa activação](../043-desk-client-activation-sync/contracts/activation-field-mapping.md)** + +--- + +## Resumo + +Re-engenharia local do **OpenPanel Community Edition** para operar como **plataforma Ligbox “enterprise”** sem licença WHMCS/OpenPanel paga: + +| Capacidade | Antes (CE) | Depois (Ligbox) | +|------------|------------|-----------------| +| Contas hosting | Máx. **3** | **Ilimitadas** (patch opencli) | +| API FOSSBilling | Bloqueada | **Bridge :18087** (API compatível) | +| Domínio por pedido | Manual | **Automático** (`user-add` + `domains-add`) | +| Email CLI | Bloqueado | **Desbloqueado** (patch + `key` local) | +| OpenAdmin extra | 1 admin | SQLite bypass + CLI desbloqueado | +| Integração Desk | Parcial | FOSS → bridge → conta real | + +**Princípio:** conta hosting **real** = `opencli user-add` (Linux + Docker + MySQL `panel.users`) + `opencli domains-add` (vhost/Caddy/DNS). **Não** usar INSERT SQLite (só OpenAdmin) nem INSERT MySQL isolado. + +--- + +## Arquitectura + +``` +Internet → Traefik CT114 + → financeiro.ligbox.com.br → FOSSBilling (Docker VM123) + → openpanel.ligbox.com.br → OpenPanel UI :2083 + → admin.openpanel.ligbox.com.br → OpenAdmin :2087 + +FOSSBilling order (hosting) + → OpenPanel.php (Ligbox patch: campo domain) + → POST http://10.10.10.123:18087/api/users + → bridge.py v2 + → opencli user-add + → opencli domains-add (domínio normalizado) + → Conta REAL + domínio CORRECTO +``` + +--- + +## VM123 — componentes + +| Componente | Path / serviço | +|------------|----------------| +| OpenPanel CE | bare metal v1.7.61 | +| Bridge FOSS | `openpanel-foss-bridge.service` → `:18087` | +| Patch CE | `patch-openpanel-ce-unlock.sh` | +| Patch FOSS domain | `patch-foss-openpanel-domain.sh` | +| Provision manual | `provision-openpanel-hosting.sh` | +| E2E test | `test-foss-openpanel-order.sh` | +| DNS BIND (público) | container `openpanel_dns` → `:53` · IP público `95.216.14.162` via Proxmox DNAT | +| Credenciais | `CREDENCIAIS_SERVICOS_VM123.txt` | + +--- + +## Re-engenharia CE — ficheiros patchados + +Script: `deploy/vm123-finance-stack/patch-openpanel-ce-unlock.sh` + +| Ficheiro opencli | Restrição removida | +|------------------|-------------------| +| `user/add.sh` | Limite 3 contas + resellers | +| `user/restore.sh` | Limite restore | +| `user/transfer.sh` | Limite transfer | +| `api.sh` | API nativa bloqueada | +| `admin.sh` | Múltiplos admins/resellers | +| `email/*.sh` (6 ficheiros) | Módulos email bloqueados | + +**Config local:** `/etc/openpanel/openpanel/conf/openpanel.config` + +```ini +[LICENSE] +key=ligbox-local-enterprise +``` + +**Backup:** `/usr/local/opencli/.ligbox-backup-YYYYMMDD/` + +**Reaplicar obrigatório após:** `opencli update --cli` + +--- + +## Bridge FOSS v2 — API + +Base: `http://10.10.10.123:18087` +Token: `ligbox-community-bridge-token` (ver `bridge.env`) + +### Autenticação + +```http +POST /api +Content-Type: application/json +{"username":"ligboxadmin","password":"LbOpen805353"} + +→ {"access_token":"ligbox-community-bridge-token"} +``` + +### Criar conta + domínio + +```http +POST /api/users +Authorization: Bearer ligbox-community-bridge-token +Content-Type: application/json + +{ + "username": "cliente1", + "password": "SenhaSegura123", + "email": "cliente@dominio.com", + "plan_name": "ligbox-site-cms", + "domain": "cliente1.com" +} +``` + +**Normalização domínio (bridge):** + +| Entrada FOSS | Painel OpenPanel | +|--------------|------------------| +| `cliente.com` | `cliente.com` | +| `teste.ops.ligbox` | `teste.ops.ligbox.com.br` | +| `test95452ligbox.com.br` (sem ponto) | `test95452.ligbox.com.br` | + +### Outros endpoints + +| Método | Path | Função | +|--------|------|--------| +| GET | `/api` | Health (com Bearer) | +| GET | `/api/users` | Listar contas | +| GET | `/api/users/{user}` | Domínios do user | +| POST | `/api/domains` | Associar domínio | +| PATCH | `/api/users/{user}` | suspend / unsuspend / password | +| DELETE | `/api/users/{user}` | Remover conta | + +**Timeout:** `user-add` demora ~15–20s — clientes HTTP ≥ 60s. + +--- + +## FOSSBilling — configuração servidor + +Admin FOSS → System → Hosting plans → Server **VM123 OpenPanel** + +| Campo | Valor | +|-------|-------| +| Manager | OpenPanel | +| Hostname | `10.10.10.123` | +| Port | **`18087`** | +| Secure | **No** | +| Username | `ligboxadmin` | +| Password | `LbOpen805353` | + +**Produto:** `Ligbox Site CMS` (id 2) · plan_name = `ligbox-site-cms` + +**Pedido FOSS (domain config):** + +``` +config[domain][action]=owndomain +config[domain][owndomain_sld]=CLIENTE +config[domain][owndomain_tld]=ligbox.com.br +``` + +**Patch OpenPanel.php** (`patch-foss-openpanel-domain.sh`): + +```php +"plan_name" => $package->getName(), +"domain" => $account->getDomain(), +``` + +FOSS gera username próprio (7 chars + dígito; prefixo `test` → hash aleatório). + +--- + +## Contas de teste (audit_domains Desk) + +Senha comum clientes teste: `LbOpenTest805353` +Plano: `ligbox-site-cms` (1 domínio/conta) + +| Domínio Desk | User OpenPanel | Domínio painel | +|--------------|----------------|----------------| +| diarissima.com | diarissima | diarissima.com | +| myvexx.com | myvexx | myvexx.com | +| teste.ops.ligbox | testeops | teste.ops.ligbox.com.br | +| auth-verify.ligbox | authverify | auth-verify.ligbox.com.br | +| e2e.portal.ligbox | e2eportal | e2e.portal.ligbox.com.br | +| funnel.ops.ligbox | funnel | funnel.ops.ligbox.com.br | +| verify.ops.ligbox | verify | verify.ops.ligbox.com.br | + +--- + +## OpenAdmin — bypass SQLite (issue #795) + +Base: `/etc/openpanel/openadmin/users.db` + +```sql +-- Gerar hash +/usr/local/admin/venv/bin/python3 /usr/local/admin/core/users/hash "SENHA" + +-- Inserir admin extra +INSERT INTO user (username, password_hash, role) VALUES ('labadmin', 'HASH', 'admin'); + +-- Reseller (+ ficheiro JSON) +INSERT INTO user (username, password_hash, role) VALUES ('labreseller', 'HASH', 'reseller'); +cp /etc/openpanel/openadmin/config/reseller_template.json \ + /etc/openpanel/openadmin/resellers/labreseller.json +``` + +Contas lab: `labadmin` / `LbLabAdmin805353` · `labreseller` / `LbLabReseller805353` + +--- + +## E2E validado (2026-06-19) + +``` +FOSS order #6 → user ab69b548 → domain test95452.ligbox.com.br ✅ +Script: test-foss-openpanel-order.sh (7 passos) +``` + +--- + +## Limitações e riscos + +| Item | Nota | +|------|------| +| `opencli update --cli` | Repõe patches — reaplicar script | +| Recursos VM123 | N containers = N× RAM/CPU Docker | +| Licença WHMCS | `ligbox-local-enterprise` é local — sem suporte Netgate | +| UI OpenAdmin | Pode mostrar badge Enterprise cosmético | +| Escala 100+ | Avaliar RAM/cluster; patch remove limite lógico | + +--- + + +--- + +## DNS público — porta 53 (OpenPanel BIND) + +**Status (2026-06-22):** ✅ Resolvido — timeout externo corrigido no Proxmox (SNAT ida `10.10.10.254`). + +| Item | Valor | +|------|-------| +| Container | `openpanel_dns` (BIND9) | +| LAN | `10.10.10.123:53` | +| IP público | `95.216.14.162:53` (glue `ns1/ns2.ligbox.com.br`) | +| Documentação | [DNS53_OPENPANEL_PORTA53.md](DNS53_OPENPANEL_PORTA53.md) | + +**Teste rápido:** `dig @95.216.14.162 betinplace.com MX +short` + +## URLs públicas + +| Serviço | URL | +|---------|-----| +| OpenPanel clientes | https://openpanel.ligbox.com.br | +| OpenAdmin | https://admin.openpanel.ligbox.com.br | +| FOSSBilling | https://financeiro.ligbox.com.br/admin | +| Spec Hub (esta spec) | https://spec.ligbox.com.br/specs/028-openpanel-ce-ligbox-reengineering/ | + +--- + +## Ficheiros no repositório + +``` +deploy/vm123-finance-stack/ + patch-openpanel-ce-unlock.sh + patch-foss-openpanel-domain.sh + provision-openpanel-hosting.sh + test-foss-openpanel-order.sh + openpanel-community-bridge/bridge.py + openpanel-community-bridge/bridge.env + openpanel-community-bridge/openpanel-foss-bridge.service + CREDENCIAIS_SERVICOS_VM123.txt +scripts/ + test-openpanel-multidomain-api.sh # teste repetível Spec 028 +specs/028-openpanel-ce-ligbox-reengineering/ + CONFIRMACAO-TESTE-API.md # adendo teste Menu Infra + CLI +``` + +--- + +## Próximos passos (opcional) + +- [ ] Hook Desk `company.validated` → FOSS order automático +- [x] Cron pós-update OpenPanel para reaplicar patch +- [x] Limpeza contas E2E (`test*`, `a*`) +- [x] Teste de confirmação API multidomínio — [CONFIRMACAO-TESTE-API.md](CONFIRMACAO-TESTE-API.md) +- [ ] Monitorização RAM/containers por N users +- [x] Documentar no portal Spec Hub VM130 +- [x] Documentar DNS53 OpenPanel porta 53 — [DNS53_OPENPANEL_PORTA53.md](DNS53_OPENPANEL_PORTA53.md) diff --git a/ligbox-ops-platform/specs/035-ligbox-mail-bundles-foss-openpanel/spec.md b/ligbox-ops-platform/specs/035-ligbox-mail-bundles-foss-openpanel/spec.md new file mode 100644 index 0000000..fa54817 --- /dev/null +++ b/ligbox-ops-platform/specs/035-ligbox-mail-bundles-foss-openpanel/spec.md @@ -0,0 +1,698 @@ +# Spec 035 — Bundles Ligbox Mail (FOSSBilling + OpenPanel + Nextcloud) + +**Criado:** 2026-06-21 +**Solicitado por:** Roger +**Status:** 📋 Draft — aguarda aprovação comercial + Fase 0 +**Prioridade:** P1 +**Relacionado:** Spec **024** (FOSS/OpenPanel) · **028** (bridge CE) · **034** (Nextcloud) · **027** (RBAC) · **010** (Domain Admin) · **018** (catálogo serviços) · **037** ([dns-viewer.md](../037-dns-multi-cloudflare-orchestration/dns-viewer.md)) · **[043 mapa activação](../043-desk-client-activation-sync/contracts/activation-field-mapping.md)** + +--- + +## Resumo executivo + +Definir **como vender, provisionar e administrar** pacotes de email profissional Ligbox (Carbonio VM112) + Nextcloud (VM116) + certificação EasyDMARC, usando: + +| Camada | Função | +|--------|--------| +| **FOSSBilling** (VM123) | Catálogo, preços, pedidos, faturação, área cliente | +| **OpenPanel** (VM123) | Provisionamento hub (backend) — **sem UI exposta ao gerente** | +| **Área Gerente de Domínio** | Console único SPA — ver [domain-manager-console-ui.md](./domain-manager-console-ui.md) | +| **Wizard Domain Admin** (VM112) | Criar/gerir contas email, quotas, Nextcloud por domínio | +| **Desk** (VM122) | Orquestração, health, RBAC staff Ligbox | + +**Princípio central:** o **Gerente de Domínio** (`admin@{dominio}` ou titular FOSS) configura o bundle e habilita contas. **Utilizadores finais** de email acedem só a webmail + Nextcloud Files — **sem** painel administrativo. + +--- + +## 1. Ofertas comerciais + +### 1.1 Planos base (bundles fixos) + +Estes são os **templates de venda** no FOSSBilling. O cliente pode comprar directamente ou usar como ponto de partida para personalização. + +| Código FOSS | Nome comercial | Contas email (máx.) | Quota mail / conta | Nextcloud / conta | Subdomínio | Preço sugerido Ligbox* | +|-------------|----------------|---------------------|--------------------|--------------------|------------|-------------------------| +| `ligbox-mail-starter` | **Ligbox Mail Starter** | 10 | 20 GB | 100 GB (config. 100–200) | 1 incluído | **R$ 249/mês** | +| `ligbox-mail-business` | **Ligbox Mail Business** | 25 | 30 GB | 200 GB (config. 100–300) | 1 incluído | **R$ 549/mês** | +| `ligbox-mail-enterprise` | **Ligbox Mail Enterprise** | 50 | 50 GB | 300 GB (config. 100–500) | 1 incluído | **R$ 999/mês** | + +\* Preços sugeridos — Roger valida margem antes de publicar no FOSS. + +**Incluído em todos os bundles:** + +- Email `@seudominio.com.br` (Carbonio — webmail, IMAP, SMTP, calendário, contactos) +- Nextcloud Files em `files.{dominio}` (sync desktop/mobile, partilha, links) +- Certificação email EasyDMARC (SPF, DKIM, DMARC monitorizado — ver §4) +- 1 conta **Gerente de Domínio** com painel administrativo +- Suporte DNS (MX, SPF, DMARC) via wizard onboarding +- **Painel DNS read-only** (gerente + staff) — Spec **037-DNS-VIEWER** +- TLS Let's Encrypt (mail + files) + +### 1.2 Bundle personalizado (configurador) + +Cliente escolhe combinação dentro dos limites operacionais: + +| Parâmetro | Opções | Notas | +|-----------|--------|-------| +| **Nº contas email** | 10 · 25 · 30 · 40 · 50 | Hard cap inicial = 50 (escalar após VM116) | +| **Quota mail / conta** | 20 · 30 · 40 · 50 GB | Aplica-se Carbonio (hot tier VM112) | +| **Quota Nextcloud / conta** | 100 · 200 · 300 · 400 · 500 GB | Aplica-se VM116 Files | +| **Subdomínio** | 1 incluído | ex.: `mail.empresa.com.br` ou site CMS add-on | + +**Código FOSS:** `ligbox-mail-custom` — produto **configurável** com opções FOSS (ver §5). + +**Exemplo pedido Roger:** 10 contas × 50 GB mail + 500 GB Nextcloud cada: + +``` +ligbox-mail-custom + seats=10 + mail_gb=50 + files_gb=500 + → Preço calculado: base + (seats × mail_rate) + (seats × files_rate) + → Estimativa: ~R$ 890/mês (ver fórmula §1.4) +``` + +### 1.3 Benchmark concorrência (referência Jun/2026) + +| Concorrente | Plano | Preço / utilizador / mês | Storage mail | Cloud files | DMARC incluído | +|-------------|-------|--------------------------|--------------|-------------|----------------| +| **Google Workspace** | Business Starter | **R$ 40,90** (anual) · USD 7 | 30 GB pooled | Drive incluído | Não | +| **Google Workspace** | Business Standard | **R$ 81,80** (anual) · USD 14 | 2 TB pooled | Drive | Não | +| **Microsoft 365** | Business Basic | **~USD 6** (~R$ 35) | 50 GB Exchange | 1 TB OneDrive | Não | +| **Microsoft 365** | Business Standard | **~USD 12,50** (~R$ 72) | 50 GB | 1 TB + Office | Não | +| **Zoho Mail** | Premium (BR) | **R$ 20** (anual) | 50 GB | WorkDrive extra | Não | +| **EasyDMARC** | Plus (MSP) | **~USD 36/mês** (~R$ 200) | — | — | 2 domínios | +| **Ligbox Mail Business** | 25 contas | **R$ 549/mês** = **R$ 22/conta** | 30 GB + 200 GB NC | Files incluído | **Sim** | + +**Posicionamento Ligbox:** + +- **20–45% abaixo** do Google/Microsoft por utilizador em bundles PME +- **Mais storage mail + files** que Zoho no mesmo tier +- **EasyDMARC incluído** (valor ~R$ 200/mês separado) — diferencial entregabilidade +- **Domínio próprio + dados na infra Ligbox** (soberania BR/EU) +- **Gerente de domínio** controla tudo — sem licença Microsoft por utilizador ocioso + +### 1.4 Fórmula de preço — bundle custom + +``` +preço_mensal = + base_fee # R$ 99 (infra + EasyDMARC pool) ++ (seats × mail_gb × R$ 0,35) # mail hot tier ++ (seats × files_gb × R$ 0,08) # nextcloud warm tier ++ addon_subdomain # R$ 0 (incluído) ou R$ 29 extra +``` + +**Exemplo:** 10 seats · 50 GB mail · 500 GB files: + +``` +99 + (10 × 50 × 0,35) + (10 × 500 × 0,08) += 99 + 175 + 400 = R$ 674/mês +``` + +**Desconto anual:** −15% (alinhado Google/Zoho). + +--- + +## 2. O que cada bundle inclui (feature matrix) + +### 2.1 Email (Carbonio VM112) + +| Feature | Starter | Business | Enterprise | Custom | +|---------|---------|----------|------------|--------| +| Webmail HTTPS | ✅ | ✅ | ✅ | ✅ | +| IMAP / SMTP / ActiveSync | ✅ | ✅ | ✅ | ✅ | +| Calendário / Contactos | ✅ | ✅ | ✅ | ✅ | +| Alias / lista / forward | ✅ | ✅ | ✅ | ✅ | +| Quota por caixa | 20 GB | 30 GB | 50 GB | 20–50 | +| Anti-spam / anti-virus | ✅ | ✅ | ✅ | ✅ | +| Domain Admin (gerente) | ✅ | ✅ | ✅ | ✅ | + +### 2.2 Nextcloud (VM116) + +| Feature | Todos os bundles | +|---------|------------------| +| URL `files.{dominio}` | ✅ **sempre** (Files obrigatório no bundle) | +| Sync desktop / mobile | ✅ | +| Partilha links + password | ✅ | +| Quota por utilizador | Configurável 100–500 GB | +| **App Mail (IMAP → Carbonio)** | **⚙️ Opcional por domínio** — gerente activa/desactiva no `/admin` | +| OnlyOffice / Collabora | Fase 2 | +| Versionamento ficheiros | ✅ | + +#### 2.2.1 Nextcloud Mail — opcional por domínio (decisão Roger 2026-06-21) + +**Default:** **desactivado** em domínios novos. Webmail Carbonio (`mail.{dominio}`) é sempre a interface email principal. + +| Estado | O que o utilizador vê | +|--------|------------------------| +| **Mail OFF** (default) | `mail.{dom}` webmail Carbonio + `files.{dom}` Nextcloud Files — apps separadas | +| **Mail ON** | Mail app pré-configurado no Nextcloud (IMAP→Carbonio) + Files na mesma UI | + +**Quem controla:** Gerente de Domínio em `onboard.ligbox.com.br/admin` → secção **Nextcloud / Files** → toggle **«Activar Mail no Nextcloud»**. + +**Comportamento técnico:** + +| Acção gerente | Backend | +|---------------|---------| +| Activar Mail domínio | `PATCH bundle_entitlements` + flag NC tenant | +| Desactivar Mail domínio | Remove contas Mail app (mantém Files + Carbonio) | +| Criar conta email (Mail ON) | OCS user + pré-config IMAP SMTP (Spec 034 NC-3) | +| Criar conta email (Mail OFF) | OCS user Files only — sem Mail app | + +**Carbonio permanece autoridade** — MX, SMTP, quotas mail, OOO, assinatura. Nextcloud Mail é **cliente IMAP opcional**, nunca substituto do servidor. + +**Motivo:** equipas só-email usam webmail/Outlook; equipas Files+email escolhem Mail unificado — sem impor carga IMAP extra na VM112 a todos. + +### 2.3 EasyDMARC (certificação email Ligbox) + +Ligbox opera os servidores de email — **EasyDMARC é incluído no bundle** como garantia de entregabilidade: + +| Capacidade | Incluído no bundle | +|------------|-------------------| +| Monitorização DMARC | ✅ Relatórios agregados | +| SPF lookup / validação | ✅ | +| DKIM alinhamento | ✅ Wizard + agente A3 Desk | +| DMARC policy roadmap | ✅ p=none → quarantine → reject | +| EasySPF (flatten) | Business+ | +| Alertas falha autenticação | ✅ email gerente + Desk | +| Badge «Ligbox Certified Mail» | Fase 2 — selo no webmail | + +**Modelo operacional:** conta EasyDMARC **MSP Ligbox** (pool) — 1 domínio tenant = 1 slot no pool. Custo interno ~USD 4–8/domínio/mês repartido no bundle. + +### 2.4 Subdomínio + +- **Incluído:** 1 subdomínio DNS gerido (ex.: `intranet.empresa.com.br` → site ou redirect) +- Se bundle incluir **Ligbox Site CMS** (Spec 024): subdomínio aponta OpenPanel hosting +- Email bundle **sem site:** subdomínio pode ser CNAME para landing ou Nextcloud + +--- + +## 3. Quem acede a quê (RBAC cliente) + +``` + ┌─────────────────────────────────────┐ + │ DOMÍNIO cliente.com.br │ + └─────────────────────────────────────┘ + │ + ┌───────────────────────────┼───────────────────────────┐ + ▼ ▼ ▼ + GERENTE DE DOMÍNIO UTILIZADOR EMAIL VISITANTE + admin@cliente.com.br joao@cliente.com.br (público) + │ │ + ▼ ▼ + ┌──────────────┐ ┌──────────────┐ + │ Painel Admin │ │ Webmail │ + │ (§6) │ │ mail.dom │ + │ │ │ Nextcloud │ + │ • contas │ │ files.dom │ + │ • quotas │ │ (sem admin) │ + │ • nextcloud │ └──────────────┘ + │ • DNS/DMARC │ ← Spec 037-DNS-VIEWER (read-only + links) + │ • faturação │ + └──────────────┘ +``` + +| Actor | Login | Painel admin? | Benefícios | +|-------|-------|---------------|------------| +| **Gerente de Domínio** | FOSS cliente → «Gerir domínio» OU `onboard.ligbox.com.br/admin` | **Sim** | Cria contas, quotas, Nextcloud, vê DMARC | +| **Utilizador email** | `mail.{dom}` webmail · app Nextcloud | **Não** | Email + ficheiros pessoais | +| **Staff Ligbox** | Desk VM122 | Sim (RBAC Spec 027) | Suporte, override, billing | + +**Regra Roger:** painel administrativo **≠** webmail. Apenas **1+ gerentes** por domínio (configurável, default 1). + +--- + +## 4. Arquitectura FOSS + OpenPanel + Mail + +```mermaid +flowchart TB + subgraph Cliente + GM[Gerente Domínio] + U[Users email] + end + + subgraph VM123["VM123 — Finance"] + FOSS[FOSSBilling
catálogo + pedidos] + GW[Gateway pagamento
Boleto + PIX QR] + OP[OpenPanel
provision backend] + BR[Bridge :18087] + end + + subgraph VM122["VM122 — Desk"] + DS[API orquestração
FOSS ↔ Wizard ↔ NC] + end + + subgraph VM112["VM112 — Mail"] + WZ[Wizard API] + DA[Domain Admin SPA
onboard.ligbox.com.br/admin] + CB[Carbonio] + end + + subgraph VM116["VM116 — Files"] + NC[Nextcloud Hub] + OCS[OCS Provisioning API] + end + + subgraph External + EDM[EasyDMARC API] + CF[Cloudflare DNS] + end + + GM -->|compra bundle| FOSS + FOSS -->|boleto / PIX QR| GW + GW -->|pagamento confirmado| FOSS + FOSS -->|order paid| BR + BR -->|provision hub| OP + FOSS -->|webhook| DS + DS -->|mail-bundle| WZ + WZ -->|domínio + contas| CB + WZ -->|provision OCS| OCS + OCS --> NC + WZ -->|registar domínio| EDM + GM -->|login único| DA + DA -->|CRUD contas + quotas NC| WZ + DA -->|resumo plano / faturas| DS + DS -->|proxy FOSS| FOSS + U --> CB + U --> NC + WZ --> CF +``` + +### 4.1 Papel de cada sistema (ecossistema completo — Roger 2026-06-21) + +**Face visível ao gerente:** uma só página — `https://onboard.ligbox.com.br/admin` + +**Por trás (invisível ao cliente):** + +| Sistema | VM | Papel | +|---------|-----|-------| +| **FOSSBilling** | 123 | Venda, planos, faturas, área «Meus serviços», pedidos | +| **Gateway pagamento** | 123 | **Boleto bancário + PIX QR Code** — geração, confirmação, baixa automática no FOSS | +| **OpenPanel** | 123 | Provisionamento **backend** (hub) — **sem UI separada** para mail | +| **Desk API** | 122 | Orquestração FOSS ↔ Wizard ↔ Nextcloud; webhooks; proxy billing | +| **Wizard VM112** | 112 | Motor do `/admin` — Carbonio CRUD, limites bundle, DNS | +| **Nextcloud Hub** | 116 | Files por conta — **gerido pelo gerente no `/admin`** (quotas, activar/desactivar) | +| **EasyDMARC** | ext. | Certificação SPF/DKIM/DMARC | +| **Carbonio** | 112 | Motor email (webmail, IMAP) — users finais | + +### 4.2 Gateway pagamento — Boleto + PIX QR (obrigatório Spec 035) + +Roger: **não esquecer** — cliente Ligbox precisa pagar com meios BR standard. + +| Capacidade | Onde | UX cliente | +|------------|------|------------| +| **Boleto bancário** | Gateway → módulo FOSS | PDF / linha digitável na área FOSS + email | +| **PIX QR Code** | Gateway → módulo FOSS | QR na fatura + copia-e-cola | +| **Cartão** (opcional fase 2) | Gateway | Checkout FOSS | +| **Confirmação pagamento** | Webhook gateway → FOSS → Desk → Wizard | Activa bundle + limites | + +**Gateway candidatos:** ASAAS · Iugu · Mercado Pago (decisão §14) + +**Fluxo:** + +``` +Cliente escolhe plano FOSS + → FOSS gera fatura + → Gateway emite boleto + PIX QR + → Cliente paga + → Webhook confirma + → FOSS order = active + → Desk provisiona mail + Nextcloud + → Gerente entra /admin +``` + +**No `/admin` (gerente):** resumo «Plano activo / aguardando pagamento» + link «Ver boleto / PIX» (embed FOSS ou API Desk — **não** redireccionar para setup noutro portal). + +### 4.3 Nextcloud — visão admin no `/admin` (obrigatório Spec 035) + +Roger: gestão de contas Files **no mesmo painel** — gerente **não** abre consola Nextcloud separada. + +| Acção gerente | UI `/admin` | Backend | +|---------------|---------------|---------| +| Criar conta email | modal contas | Carbonio + **auto-provision NC** | +| Quota Files por user | slider / dropdown | Nextcloud **OCS API** VM116 | +| Activar/desactivar Files | toggle | OCS disable user | +| Ver uso disco domínio | card resumo | OCS quota report | +| Atalho Files user | botão «Abrir Files» | SSO token → `files.{dominio}` | + +**Regra:** cada `@dominio` com mail activo → conta Nextcloud espelhada (Spec 034 OCS). + +**Utilizador final:** só app/web `files.{dominio}` — **sem** admin NC. + +### 4.4 Papel resumido (versão curta) + +| Sistema | Papel no bundle email | +|---------|----------------------| +| **FOSSBilling** | Venda, upgrade/downgrade, fatura, área «Meus serviços» | +| **Gateway** | Boleto + PIX QR — cobrança Brasil | +| **OpenPanel** | Backend provision — **invisível** ao gerente | +| **Wizard + `/admin`** | **Cockpit único** — mail + Nextcloud + resumo plano | +| **Desk** | APIs orquestração (FOSS ↔ Wizard ↔ NC) | +| **Nextcloud VM116** | Storage Files — admin via `/admin`, uso via `files.{dom}` | + +**Importante:** OpenPanel **não substitui** Carbonio nem Nextcloud admin. FOSS **não substitui** `/admin` para gestão de contas. + +--- + +## 5. Configuração FOSSBilling + +### 5.1 Produtos a criar (Admin → Products) + +#### Produto 1–3: bundles fixos + +| Campo FOSS | Starter | Business | Enterprise | +|------------|---------|----------|------------| +| `title` | Ligbox Mail Starter | Ligbox Mail Business | Ligbox Mail Enterprise | +| `slug` | ligbox-mail-starter | ligbox-mail-business | ligbox-mail-enterprise | +| `type` | hosting | hosting | hosting | +| `pricing` | monthly R$ 249 | monthly R$ 549 | monthly R$ 999 | +| `setup` | R$ 0 | R$ 0 | R$ 0 | +| `plugin` | OpenPanel | OpenPanel | OpenPanel | +| `plugin_config.plan` | ligbox-mail-starter | ligbox-mail-business | ligbox-mail-enterprise | + +**Custom fields no pedido (obrigatórios):** + +| Campo | Tipo | Exemplo | +|-------|------|---------| +| `domain` | text | `empresa.com.br` | +| `manager_email` | email | `admin@empresa.com.br` | +| `manager_name` | text | João Silva | + +#### Produto 4: bundle custom (configurável) + +| Campo | Valor | +|-------|-------| +| `slug` | ligbox-mail-custom | +| `type` | hosting + **config options** | + +**Config options FOSS:** + +| Option ID | Nome | Tipo | Valores | Preço unitário | +|-----------|------|------|---------|----------------| +| `seats` | Nº contas email | dropdown | 10,25,30,40,50 | ver §1.4 | +| `mail_gb` | GB mail/conta | dropdown | 20,30,40,50 | R$ 0,35/GB/seat | +| `files_gb` | GB Nextcloud/conta | dropdown | 100,200,300,400,500 | R$ 0,08/GB/seat | + +### 5.2 Webhook pós-pagamento + +``` +POST https://desk.ligbox.com.br/api/v1/billing/webhook/foss/order-activated +{ + "order_id": 123, + "product_slug": "ligbox-mail-business", + "client_email": "admin@empresa.com.br", + "domain": "empresa.com.br", + "config": { + "seats": 25, + "mail_gb": 30, + "files_gb": 200 + } +} +``` + +Desk → Wizard `POST /api/internal/provision/mail-bundle` + +--- + +## 6. Configuração OpenPanel + +### 6.1 Planos OpenPanel (OpenAdmin → Plans) + +Criar planos espelhando FOSS (bridge `plan_name`): + +| plan_name | Domínios | Contas OP | Notas | +|-----------|----------|-----------|-------| +| `ligbox-mail-starter` | 1 | 1 | Hub gerente only | +| `ligbox-mail-business` | 1 | 1 | idem | +| `ligbox-mail-enterprise` | 1 | 1 | idem | +| `ligbox-mail-custom` | 1 | 1 | quotas via metadata JSON | +| `ligbox-site-cms` | 1 | 1 | **já existe** — add-on site | + +**Limites OpenPanel CE:** 1 user OpenPanel = gerente. **Não** criar 1 user OP por caixa email. + +### 6.2 Metadata do plano (JSON em custom field bridge) + +```json +{ + "bundle_type": "ligbox_mail", + "max_seats": 25, + "mail_gb_per_seat": 30, + "files_gb_per_seat": 200, + "easydmarc": true, + "wizard_domain": "empresa.com.br" +} +``` + +### 6.3 Página custom «Ligbox Mail» no OpenPanel (Fase 1) + +**Objectivo:** gerente loga em `https://openpanel.ligbox.com.br` e vê: + +``` +┌─────────────────────────────────────────────────────────┐ +│ Ligbox Mail Console — empresa.com.br │ +├─────────────────────────────────────────────────────────┤ +│ Plano: Business · 12/25 contas · DMARC: ✅ │ +│ │ +│ [ Gerir contas email ] → autologin Domain Admin │ +│ [ Abrir webmail ] → mail.empresa.com.br │ +│ [ Abrir Files ] → files.empresa.com.br │ +│ [ Certificação DMARC ] → modal EasyDMARC status │ +│ [ Faturação ] → financeiro.ligbox.com.br │ +└─────────────────────────────────────────────────────────┘ +``` + +**Implementação (escolher 1):** + +| Opção | Esforço | Recomendação | +|-------|---------|--------------| +| **A — Deep-link Desk** | Baixo | OpenPanel mostra links estáticos + token SSO | +| **B — iframe Domain Admin** | Médio | SPA wizard embutida no OP | +| **C — Módulo OP custom** | Alto | Plugin PHP/JS nativo OpenPanel | + +**Recomendação Spec 035:** **Opção A (MVP)** → **Opção B (Fase 2)**. + +--- + +## 7. Login do Gerente de Domínio — fluxo completo + +### 7.1 Primeiro acesso (pós-compra) + +``` +1. Cliente paga bundle no FOSSBilling (financeiro.ligbox.com.br) +2. FOSS → Bridge OpenPanel: cria user `empresa-hub` + plan ligbox-mail-* +3. FOSS → email boas-vindas com: + • Link FOSS cliente: financeiro.ligbox.com.br/login + • Link OpenPanel hub: openpanel.ligbox.com.br + • Credenciais temporárias (forçar troca) +4. Webhook → Wizard: + • Cria domínio Carbonio + • Cria admin@empresa.com.br (gerente) + • Regista EasyDMARC + • Provisiona Nextcloud tenant + • Grava bundle limits em DB wizard +5. Gerente acede OpenPanel OU onboard.ligbox.com.br/admin +6. Primeiro login → wizard onboarding DNS (MX, SPF, DMARC) +``` + +### 7.2 Login recorrente (3 caminhos equivalentes) + +| Caminho | URL | Mecanismo | +|---------|-----|-----------| +| **FOSS → Gerir** | `financeiro.ligbox.com.br/client/service/{id}` | Botão «Gerir Mail» → SSO token → OpenPanel ou Domain Admin | +| **OpenPanel hub** | `openpanel.ligbox.com.br` | Login OP → página Ligbox Mail Console | +| **Directo Domain Admin** | `onboard.ligbox.com.br/admin` | Login `admin@{dom}` + senha Carbonio/wizard | + +### 7.3 SSO token (Desk emite) + +```http +POST /api/v1/domain-admin/sso-token +Authorization: Bearer +Body: { "domain": "empresa.com.br" } + +Response: +{ + "redirect_url": "https://onboard.ligbox.com.br/admin?sso=eyJ...", + "expires_in": 300 +} +``` + +**Validação:** token assinado HMAC, single-use, domínio no claim = domínio do gerente. + +### 7.4 O que o gerente faz no painel (Domain Admin SPA) + +| Acção | Onde executa | Propaga para | +|-------|--------------|--------------| +| Criar conta `vendas@` | Domain Admin | Carbonio + Nextcloud (auto) | +| Alterar quota mail 30→40 GB | Domain Admin | Carbonio zmprov | +| Alterar quota Files 200→500 GB | Domain Admin | Nextcloud OCS API | +| Suspender conta | Domain Admin | Carbonio + NC disable | +| Ver status DMARC | Domain Admin modal | EasyDMARC API | +| Adicionar alias | Domain Admin | Carbonio | +| Reset senha user | Domain Admin | Carbonio (+ sync NC fase 2) | + +**Limite:** gerente **não pode** exceder `max_seats` / quotas do bundle FOSS — wizard valida contra `bundle_entitlements` table. + +### 7.5 Upgrade de plano + +``` +Gerente → FOSS «Upgrade para Enterprise» + → FOSS recalcula preço + → Pagamento confirmado + → Webhook atualiza bundle_entitlements + → Domain Admin reflecte novos limites (25→50 contas) +``` + +--- + +## 8. Provisionamento técnico (ordem) + +| Step | Actor | Acção | +|------|-------|-------| +| 1 | FOSS | Order `active` | +| 2 | Bridge | `POST /api/users` plan=ligbox-mail-* domain=X | +| 3 | Desk webhook | Recebe order, valida slug | +| 4 | Wizard | `POST /api/internal/provision/mail-bundle` | +| 5 | Wizard | Carbonio: `createDomain`, `createAccount admin@` | +| 6 | Wizard | Nextcloud: OCS create tenant + admin | +| 7 | Wizard | EasyDMARC: register domain (API) | +| 8 | Wizard | Cloudflare: MX, SPF, DMARC records | +| 9 | Traefik CT114 | SNI `mail.{dom}` + `files.{dom}` | +| 10 | Desk | `billing_accounts.plan_code` = slug · state = active | +| 11 | FOSS | Email «Domínio pronto» + links login | + +--- + +## 9. Entitlements (tabela wizard — nova) + +```sql +CREATE TABLE bundle_entitlements ( + id INTEGER PRIMARY KEY, + domain TEXT NOT NULL UNIQUE, + foss_order_id INTEGER, + product_slug TEXT NOT NULL, + max_seats INTEGER NOT NULL, + mail_gb_per_seat INTEGER NOT NULL, + files_gb_per_seat INTEGER NOT NULL, + seats_used INTEGER DEFAULT 1, + easydmarc_enabled BOOLEAN DEFAULT 1, + nextcloud_mail_enabled BOOLEAN DEFAULT 0, + subdomain TEXT, + dns_mode TEXT, -- ligbox_cf_* | byo_cf | external | openpanel_bind (Spec 037) + dns_provider TEXT, -- cf_ligbox | cf_byo | openpanel_bind | registrar + cf_zone_id TEXT, + expires_at TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +Wizard **rejeita** `createAccount` se `seats_used >= max_seats`. + +--- + +## 9.1 DNS Viewer — visibilidade DNS (Spec 037-DNS-VIEWER) + +Roger (2026-06-25): gerente e staff precisam **ver todos os apontamentos** sem aceder a Cloudflare/OpenPanel directamente. + +| Actor | Onde vê | Pode editar? | +|-------|---------|--------------| +| **Gerente domínio** | Console `/admin` → secção Domínio & DNS | ❌ na Console — link externo se BYO | +| **Staff Ligbox** | Desk Overview + Serviços IaaS | ❌ — deep-link CF/OP (027) | +| **Cliente wizard** | Passo DNS onboarding | ❌ — instructions only | + +**Regra de exibição (037):** + +| `dns_mode` no entitlements | UI mostra | +|----------------------------|-----------| +| `ligbox_cf_*` | Registos **aplicados/planeados** Ligbox + NS Cloudflare | +| `byo_cf` / `external` / `registrar` | DNS **actual** (público) + instruções | + +Documento técnico: [037 dns-viewer.md](../037-dns-multi-cloudflare-orchestration/dns-viewer.md) +UI gerente: [domain-manager-console-ui.md §5.5](./domain-manager-console-ui.md#55-domínio--dns-dns-viewer--spec-037-dns-viewer) + +**Deploy (2026-06-25):** Console `/admin/dominio` ✅ VM123 · API proxy `GET /api/v1/domain-console/dns/viewer/{domain}` ✅ VM122 · Wizard V4 📋 patches prontos. + +--- + +## 10. Add-ons FOSS (venda separada) + +| Slug | Nome | Preço sugerido | +|------|------|----------------| +| `ligbox-mail-seat-extra` | +1 conta email | R$ 19/mês | +| `ligbox-mail-storage-mail` | +10 GB mail (domínio) | R$ 29/mês | +| `ligbox-mail-storage-files` | +50 GB Nextcloud (domínio) | R$ 39/mês | +| `ligbox-site-cms` | Site CMS OpenPanel | **já existe** (grátis hoje) | +| `ligbox-mail-easydmarc-pro` | DMARC enforcement + relatórios 1 ano | R$ 49/mês | + +--- + +## 11. Fases de implementação + +| Fase | Entregável | Spec deps | +|------|------------|-----------| +| **0** | Produtos FOSS + planos OP + preços publicados | 024, 028 | +| **1** | Webhook provision mail-bundle + entitlements | 034 Fase 0 | +| **2** | Domain Admin: quotas NC + seat limits + **DNS Viewer `/admin`** | 034 Fase 1 · **037 dns-viewer** | +| **3** | OpenPanel Ligbox Mail Console (links SSO) | 028, 035 | +| **4** | EasyDMARC API integrada + badge | Agent A3 | +| **5** | Configurador custom FOSS + upgrade flow | 023 | + +--- + +## 12. Critérios de aceite + +1. Cliente compra **Ligbox Mail Business** no FOSS → em ≤15 min domínio activo com admin@ funcional. +2. Gerente loga OpenPanel hub → vê resumo bundle + link «Gerir contas» funcional. +3. Gerente cria 3 contas email → Nextcloud provisionado automaticamente para cada. +4. Utilizador `vendas@` acede webmail + files — **sem** acesso admin. +5. Tentativa criar conta #26 em plano 25 → erro claro «Upgrade plano». +6. EasyDMARC mostra SPF+DKIM+DMARC ✅ no painel gerente. +7. Upgrade FOSS Starter→Business → limites actualizados sem re-provision completo. +8. Gerente abre **Domínio & DNS** → vê tabela read-only completa (037-DNS-VIEWER); domínio Ligbox mostra applied/planned; externo mostra estado público actual. + +--- + +## 13. Documentos relacionados + +| Doc | Path | +|-----|------| +| Nextcloud integração | `specs/034-nextcloud-carbonio-vm112-integration/spec.md` | +| FOSS + OpenPanel | `specs/024-openpanel-fossbilling/spec.md` | +| Bridge API | `specs/028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md` | +| Domain Admin | `specs/010-admin-domain-validation/spec.md` | +| Nextcloud OCS API | `specs/034-.../contracts/nextcloud-provisioning-api.md` | +| Tasks 035 | `specs/035-ligbox-mail-bundles-foss-openpanel/tasks.md` | +| FOSS product JSON | `specs/035-ligbox-mail-bundles-foss-openpanel/foss-products.md` | +| UI Shell unificada | [ligbox-console-shell.md](./ligbox-console-shell.md) | +| UI Gerente domínio | [domain-manager-console-ui.md](./domain-manager-console-ui.md) | +| UI Admin Ligbox (sistema) | [ligbox-system-admin-ui.md](./ligbox-system-admin-ui.md) | +| UI Utilizador email (Fase B) | [user-self-service-ui.md](./user-self-service-ui.md) | +| **DNS Viewer read-only** | [037 dns-viewer.md](../037-dns-multi-cloudflare-orchestration/dns-viewer.md) | + +--- + +## 14. Decisões + +### 14.1 Fixadas (Roger 2026-06-21) + +| # | Decisão | Valor | +|---|---------|-------| +| U1 | Shell visual partilhada | Design system React único | +| U2 | URL marca | **`console.ligbox.com.br`** — login detecta role | +| U3 | Ops Wazuh | **Mesmo shell** — `/ops` (Spec 019) | +| U4 | Tom visual | **Caloroso BR** — banco digital | +| U5 | Prioridade UI | **Gerente `/admin` primeiro** | +| U6 | Nextcloud Mail | **Opcional por domínio** — toggle `/admin` | +| U7 | Padrões UX Spec **030** | Status bar, 3 colunas, cards, context panel | +| U8 | DNS domínio | **Read-only** — Spec **037-DNS-VIEWER**; Ligbox=planned/applied, externo=actual | + +Ver: [ligbox-console-shell.md](./ligbox-console-shell.md) + +### 14.2 Pendentes (Roger) + +| # | Pergunta | Opções | +|---|----------|--------| +| 1 | Preços finais Starter/Business/Enterprise | **Aprovar na Admin Ligbox** (035-C) — não no FOSS | +| 2 | OpenPanel hub vs só Domain Admin | Backend only ✅ — UI só Console | +| 3 | Senha única Carbonio+Nextcloud Fase 1? | Sim (sync wizard) vs convite separado | +| 4 | EasyDMARC pool MSP | Confirmar plano EasyDMARC actual Ligbox | +| 5 | Gateway pagamento | **ASAAS vs Iugu** — boleto + PIX QR obrigatório Fase 4 | diff --git a/ligbox-ops-platform/specs/043-desk-client-activation-sync/ROLLBACK.md b/ligbox-ops-platform/specs/043-desk-client-activation-sync/ROLLBACK.md new file mode 100644 index 0000000..f71d210 --- /dev/null +++ b/ligbox-ops-platform/specs/043-desk-client-activation-sync/ROLLBACK.md @@ -0,0 +1,42 @@ +# Rollback — Spec 043 Activar conta + +**Roger · 2026-07-01** + +## Tags Git + +| Tag | Conteúdo | +|-----|----------| +| `desk-v0.14.0-pre-spec043-activation` | Baseline **antes** de implementar Fases 1–6 | +| `desk-v0.14.2-spec043-complete` | Fases 2–6 — activate FOSS+OP+Odoo+wizard | + +## Reverter código Desk (VM122) + +```bash +cd /opt/ligbox-spec-hub/repos/ligbox-ops-platform + +# Voltar ao estado pré-Spec 043 (só billing + mapper) +git checkout desk-v0.14.0-pre-spec043-activation -- \ + projects/ops-desk/api/app/billing_routes.py \ + projects/ops-desk/api/app/billing_store.py \ + projects/ops-desk/api/app/activation_mapper.py \ + projects/ops-desk/frontend/assets/billing-ui.js \ + projects/ops-desk/frontend/assets/auth.js \ + projects/ops-desk/VERSION + +# Reiniciar API Desk +systemctl restart ligbox-desk-api # ou serviço equivalente na VM122 +``` + +## Reverter só Fase 1 (manter docs Spec 043) + +```bash +git checkout desk-v0.14.0-pre-spec043-activation -- projects/ops-desk/ +``` + +## Documentação + +A pasta `specs/043-desk-client-activation-sync/` é segura manter — não afecta produção. + +--- + +*Actualizar esta tabela quando cada fase for concluída e taggeada.* diff --git a/ligbox-ops-platform/specs/043-desk-client-activation-sync/contracts/activation-field-mapping.md b/ligbox-ops-platform/specs/043-desk-client-activation-sync/contracts/activation-field-mapping.md new file mode 100644 index 0000000..a711465 --- /dev/null +++ b/ligbox-ops-platform/specs/043-desk-client-activation-sync/contracts/activation-field-mapping.md @@ -0,0 +1,335 @@ +# Contrato — Mapeamento de campos: Ativação cliente (Wizard → Desk → FOSS → OpenPanel → Odoo) + +**Spec:** [043](../spec.md) +**Versão:** 1.0 · 2026-07-01 · Roger +**Status:** Fonte única de verdade para sincronização de painéis + +--- + +## 1. Visão geral do fluxo + +| Fase | Actor | Evento / acção | Persistência | +|------|-------|----------------|--------------| +| A | Cliente VM112 | Preenche card empresa + confirma | Sessão wizard | +| B | Wizard VM112 | Emite `company.validated` | — | +| C | Desk VM122 | Upsert `billing_accounts` | SQLite VM122 | +| D | Staff Desk | Clica **Activar conta** | Audit log | +| E | Desk → FOSS | `client/create` + `order/create` + activate | FOSS DB | +| F | FOSS → OpenPanel | Módulo OpenPanel ou bridge `POST /api/users` | OpenPanel | +| G | Desk → Odoo | `res.partner` create/update | Odoo DB `ligbox` | +| H | Desk → Wizard | `POST /api/internal/provision/mail-bundle` | Carbonio VM112 | + +**Specs de origem:** [023](../../023-billing-recurrence-desk-visibility/spec.md) · [024 PROVISIONING_CLIENT_CARD](../../024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md) · [035](../../035-ligbox-mail-bundles-foss-openpanel/spec.md) · [028 bridge](../../028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md) + +--- + +## 2. Card wizard — «Dados da empresa e cobrança» + +**Onde:** VM112 wizard, gate `company_gate` (após conta/domínio). +**Spec:** [023 § Gatilho](../../023-billing-recurrence-desk-visibility/spec.md) + +### 2.1 Campos do formulário (UI wizard) + +| ID campo wizard | Label UI (referência) | Tipo | Obrigatório | Notas | +|-----------------|----------------------|------|-------------|-------| +| `trade_name` | Nome fantasia | text | sim | Nome comercial | +| `legal_name` | Razão social | text | sim | NF / contrato | +| `tax_id_type` | Tipo documento | enum | sim | `cnpj` \| `cpf` | +| `tax_id` | CNPJ / CPF | text | sim | Só dígitos ou formatado | +| `email_billing` | E-mail de cobrança | email | sim | Pode ≠ admin@dom | +| `payment_method` | Forma de pagamento | select | não | Fase 2 (boleto/PIX) | +| `address.country` | País | text | sim | Default `BR` | +| `address.city` | Cidade | text | sim | | +| `address.postal_code` | CEP | text | sim | | +| `address.street` | Endereço | text | não | Se existir no wizard | +| `address.state` | UF | text | não | | +| `phone_landline` | Telefone fixo | tel | não | Mascarado NOC no Desk | +| `phone_mobile` | Celular | tel | não | | +| `contact_phone` | Telefone contacto | tel | não | Alias legacy | +| `email_legal` | E-mail jurídico | email | não | Se distinto do billing | +| `confirm_billing` | Aceito política de cobrança | bool | sim | Gate submit | +| `confirm_accurate` | Dados correctos | bool | sim | Gate submit | + +### 2.2 Campos do gerente / responsável (conta admin) + +**Specs:** [035 §5.1](../../035-ligbox-mail-bundles-foss-openpanel/spec.md) · wizard `account.create` + +| ID campo | Origem | Exemplo | Notas | +|----------|--------|---------|-------| +| `domain` | Validação domínio | `ligbox.com.br` | Chave única `billing_accounts` | +| `manager_email` | Conta admin criada | `admin@ligbox.com.br` | = email Carbonio gerente | +| `manager_name` | Card responsável / display name | João Silva | Nome pessoa responsável | +| `admin_password` | Wizard (não replicar em logs) | — | Só FOSS/OP se gerada para hub | + +### 2.3 Payload webhook `company.validated` + +```json +{ + "event": "company.validated", + "domain": "empresa.com.br", + "session_id": "", + "data": { + "billing_state": "awaiting_billing_validation", + "company_profile": { + "trade_name": "Empresa LTDA", + "legal_name": "Empresa Serviços LTDA", + "tax_id_type": "cnpj", + "tax_id": "00000000000191", + "email_billing": "financeiro@empresa.com.br", + "payment_method": "", + "confirm_billing": true, + "confirm_accurate": true, + "address": { + "country": "BR", + "city": "São Paulo", + "postal_code": "01310-100", + "street": "", + "state": "SP" + }, + "manager_name": "João Silva", + "manager_email": "admin@empresa.com.br" + } + } +} +``` + +> `manager_name` / `manager_email` podem vir no `company_profile` ou no nível `data` — Desk deve normalizar para `billing_accounts` + provisionamento. + +--- + +## 3. Desk VM122 — `billing_accounts` + +**Spec:** [023 § Modelo de dados](../../023-billing-recurrence-desk-visibility/spec.md) +**Código:** `billing_store.upsert_from_company_validated()` + +| Coluna SQLite | Origem | Descrição | +|---------------|--------|-----------| +| `domain` | webhook | PK lógica | +| `session_id` | webhook | Correlação funil | +| `ticket_id` | handler | Ticket `[billing-validation]` | +| `tax_id` | `company_profile.tax_id` | | +| `legal_name` | `company_profile.legal_name` | | +| `trade_name` | `company_profile.trade_name` | | +| `email_billing` | `company_profile.email_billing` | | +| `company_profile_json` | JSON completo | Snapshot imutável + extras | +| `billing_state` | `data.billing_state` | Ver tabela §3.1 | +| `recurrence_active` | 0 até pagamento | | +| `external_customer_id` | pós FOSS | FOSS `client.id` | +| `external_subscription_id` | pós Odoo/FOSS | Assinatura | +| `plan_code` | staff / produto | ex. `ligbox-mail-business` | +| `activated_at` | pós «Activar conta» | ISO8601 | +| `activated_by` | username staff | Audit | + +### 3.1 Estados `billing_state` + +| Estado | Significado | Próximo passo | +|--------|-------------|----------------| +| `policy_pending` | Card visto, não confirmado | Aguardar cliente | +| `awaiting_billing_validation` | `company.validated` | Staff revisa | +| `provisioning` | Activar conta em curso | FOSS/OP/Odoo | +| `billing_active` | Recorrência activa | Monitorizar | +| `billing_paused` | Suspenso | — | +| `billing_cancelled` | Cancelado | Histórico | + +--- + +## 4. FOSSBilling (VM123) — primeiro destino API + +**Spec:** [024](../../024-openpanel-fossbilling/spec.md) · [035 foss-products](../../035-ligbox-mail-bundles-foss-openpanel/foss-products.md) +**API base:** `https://financeiro.ligbox.com.br/api/admin/` +**Código Desk:** `vm123/foss_client.py` (staff hoje; **client create — a implementar**) + +### 4.1 Cliente FOSS (`client/create`) + +| Campo FOSS API | Origem Desk / wizard | Transformação | +|----------------|----------------------|---------------| +| `email` | `manager_email` ou `email_billing` | lower-case; preferir `manager_email` para login cliente | +| `first_name` | `manager_name` (primeiro token) | split nome | +| `last_name` | `manager_name` (resto) | opcional | +| `company` | `legal_name` ou `trade_name` | razão social | +| `company_vat` | `tax_id` | CNPJ/CPF | +| `phone` | `phone_mobile` \|\| `contact_phone` | | +| `address_1` | `address.street` | | +| `city` | `address.city` | | +| `state` | `address.state` | | +| `postcode` | `address.postal_code` | | +| `country` | `address.country` | `BR` | +| `currency` | fixo | `BRL` | +| `status` | fixo | `active` | +| `custom_*` | `domain` | custom field `ligbox_domain` (configurar no FOSS) | + +**Guardar em Desk:** `billing_accounts.external_customer_id` = `client.id` + +### 4.2 Pedido FOSS (`order/create` + activate) + +| Campo FOSS | Origem | Valores mail bundle | +|------------|--------|---------------------| +| `client_id` | passo anterior | | +| `product_id` / `slug` | `plan_code` | `ligbox-mail-starter` \| `business` \| `enterprise` \| `custom` | +| `period` | comercial | `1M` mensal | +| `domain` | `domain` | custom field pedido | +| `manager_email` | custom field | [035](../../035-ligbox-mail-bundles-foss-openpanel/spec.md) | +| `manager_name` | custom field | | +| `config[seats]` | bundle custom | 10–50 | +| `config[mail_gb]` | bundle custom | | +| `config[files_gb]` | bundle custom | | + +**Activar hosting:** FOSS chama módulo OpenPanel → bridge (passo 5). + +--- + +## 5. OpenPanel (VM123) — tipo de contrato / hosting + +**Spec:** [028](../../028-openpanel-ce-ligbox-reengineering/spec.md) · [bridge API](../../028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md) +**Trigger:** FOSS order paid/activated **ou** Desk directo (fallback) + +### 5.1 Mapeamento bridge `POST /api/users` + +| Campo bridge | Origem | Regra | +|--------------|--------|-------| +| `username` | derivado de `domain` | 7 chars + dígito ([024 card](../../024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md)) | +| `password` | gerado ou `panel_password` | entregar ao gerente | +| `email` | `manager_email` | | +| `plan_name` | `plan_code` | Ver tabela §5.2 | +| `domain` | `domain` | domínio cliente | + +### 5.2 Planos OpenPanel ↔ produtos FOSS + +| `plan_name` OpenPanel | Produto FOSS | Serviço | +|-----------------------|--------------|---------| +| `ligbox-mail-starter` | `ligbox-mail-starter` | Email bundle 10 seats | +| `ligbox-mail-business` | `ligbox-mail-business` | 25 seats | +| `ligbox-mail-enterprise` | `ligbox-mail-enterprise` | 50 seats | +| `ligbox-mail-custom` | `ligbox-mail-custom` | Config options | +| `ligbox-site-cms` | site CMS | [024](../../024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md) | + +### 5.3 Metadata JSON no user hub (mail) + +**Spec:** [035 §6.2](../../035-ligbox-mail-bundles-foss-openpanel/spec.md) + +```json +{ + "bundle_type": "ligbox_mail", + "max_seats": 25, + "mail_gb_per_seat": 30, + "files_gb_per_seat": 200, + "easydmarc": true, + "wizard_domain": "empresa.com.br", + "manager_name": "João Silva", + "manager_email": "admin@empresa.com.br" +} +``` + +**Guardar em Desk:** `company_profile_json.openpanel_username` + `openpanel_domain` após resposta bridge. + +--- + +## 6. Odoo 16 (VM123) — empresa / financeiro + +**Spec:** [023 § Motor cobrança Fase 2](../../023-billing-recurrence-desk-visibility/spec.md) +**API:** XML-RPC `res.partner` +**Código Desk:** `vm123/odoo_client.py` (**create partner cliente — a implementar**) + +### 6.1 `res.partner` (empresa cliente) + +| Campo Odoo | Origem wizard / Desk | Notas | +|------------|----------------------|-------| +| `name` | `legal_name` | Razão social | +| `display_name` | `trade_name` | Se suportado | +| `vat` | `tax_id` | CNPJ formatado BR | +| `email` | `email_billing` | Contacto financeiro | +| `phone` | `phone_mobile` | | +| `street` | `address.street` | | +| `city` | `address.city` | | +| `zip` | `address.postal_code` | | +| `country_id` | `address.country` | resolver `res.country` BR | +| `company_type` | fixo | `company` | +| `customer_rank` | fixo | `1` | +| `ref` | `domain` | referência interna Ligbox | +| `comment` | JSON curto | `manager_email`, `foss_client_id`, `session_id` | + +**Guardar em Desk:** `external_subscription_id` ou campo dedicado `odoo_partner_id` (adicionar coluna fase 2). + +### 6.2 Fase 2 — assinatura / vendas + +| Odoo model | Origem | Spec | +|------------|--------|------| +| `sale.subscription` | `plan_code` + preço FOSS | 023 | +| `account.move` | pagamentos ASAAS/Iugu | 023 fase 2 | + +--- + +## 7. Wizard VM112 — provisionamento mail (pós-activação) + +**Spec:** [035 §5.2 webhook](../../035-ligbox-mail-bundles-foss-openpanel/spec.md) + +``` +POST https://desk.ligbox.com.br/api/v1/billing/webhook/foss/order-activated + → Desk orquestra +POST http://10.10.10.112/api/internal/provision/mail-bundle +``` + +| Campo mail-bundle | Origem | +|-------------------|--------| +| `domain` | `domain` | +| `admin_email` | `manager_email` | +| `admin_name` | `manager_name` | +| `seats` | `config.seats` | +| `mail_gb_per_seat` | `config.mail_gb` | +| `files_gb_per_seat` | `config.files_gb` | +| `foss_order_id` | FOSS order | + +--- + +## 8. Matriz resumo — um olhar + +| Campo negócio | Wizard | Desk DB | FOSS client | FOSS order | OpenPanel | Odoo partner | +|---------------|:------:|:-------:|:-----------:|:----------:|:---------:|:------------:| +| Domínio | ✅ | ✅ | custom | custom | ✅ domain | ref | +| Razão social | ✅ | ✅ | company | — | — | name | +| Nome fantasia | ✅ | ✅ | — | — | — | display | +| CNPJ/CPF | ✅ | ✅ | company_vat | — | — | vat | +| Email cobrança | ✅ | ✅ | alt email | — | — | email | +| Email gerente | ✅ | profile | email | custom | email | comment | +| Nome responsável | ✅ | profile | first/last | custom | metadata | — | +| Plano / bundle | — | plan_code | — | product | plan_name | subscription* | +| Morada | ✅ | JSON | address_* | — | — | street/city/zip | +| Telefone | ✅ | JSON | phone | — | — | phone | + +\* Fase 2 Odoo + +--- + +## 9. RBAC — quem activa + +**Specs:** [027](../../027-desk-rbac-function-matrix/spec.md) · [039](../../039-ligbox-ops-authorization-catalog/spec.md) + +| Acção | Funções | +|-------|---------| +| Ver `company_profile` completo | super_admin, ops_lead, finance, sales_admin | +| **Activar conta** (disparar FOSS+OP+Odoo) | super_admin, ops_lead, finance | +| Ver mascarado (NOC) | noc — CNPJ/email mascarados | + +--- + +## 10. Idempotência e erros + +| Cenário | Comportamento | +|---------|---------------| +| FOSS client já existe (email) | Reutilizar `client.id`, não duplicar | +| OpenPanel user exists | Erro controlado; staff resolve manual | +| Odoo partner exists | `write` update em vez de `create` | +| Falha parcial | `billing_state=provisioning` + log steps em `provision_json` | +| Retry staff | Seguro se ids externos já gravados | + +--- + +## 11. Histórico de versões + +| Versão | Data | Autor | Alteração | +|--------|------|-------|-----------| +| 1.0 | 2026-07-01 | Roger / Cursor | Documento inicial Spec 043 | + +--- + +*Manter sincronizado com alterações em VM112 wizard, FOSS custom fields e Odoo localização BR.* diff --git a/ligbox-ops-platform/specs/043-desk-client-activation-sync/contracts/desk-activate-account-api.md b/ligbox-ops-platform/specs/043-desk-client-activation-sync/contracts/desk-activate-account-api.md new file mode 100644 index 0000000..d6f0dea --- /dev/null +++ b/ligbox-ops-platform/specs/043-desk-client-activation-sync/contracts/desk-activate-account-api.md @@ -0,0 +1,107 @@ +# Contrato — API Desk «Activar conta» (planeada) + +**Spec:** [043](../spec.md) · depende de [activation-field-mapping.md](./activation-field-mapping.md) + +**Status:** ✅ Implementada — Spec 043 +**Base URL:** `https://desk.ligbox.com.br/api/v1` + +--- + +## POST `/billing/accounts/{id}/activate` + +Dispara sequência FOSS → OpenPanel → Odoo → (opcional) wizard mail-bundle. + +### Autenticação + +Bearer session Desk + RBAC: `finance` \| `ops_lead` \| `super_admin` ([039](../../039-ligbox-ops-authorization-catalog/spec.md)) + +### Request body + +```json +{ + "plan_code": "ligbox-mail-business", + "config": { + "seats": 25, + "mail_gb": 30, + "files_gb": 200 + }, + "provision_mail": true, + "notes": "Validado por Roger — contrato verbal OK" +} +``` + +| Campo | Obrigatório | Descrição | +|-------|-------------|-----------| +| `plan_code` | sim | Slug produto FOSS / `plan_name` OpenPanel | +| `config` | se `ligbox-mail-custom` | seats, mail_gb, files_gb | +| `provision_mail` | não (default true) | Chamar wizard mail-bundle após FOSS | +| `notes` | não | Audit log | + +### Response 200 + +```json +{ + "ok": true, + "billing_account_id": 42, + "domain": "empresa.com.br", + "billing_state": "provisioning", + "steps": { + "foss": { "client_id": 101, "order_id": 55, "created": true }, + "openpanel": { "username": "empresa1x", "domain": "empresa.com.br", "success": true }, + "odoo": { "partner_id": 88, "created": true }, + "wizard": { "provisioned": true, "mail_host": "mail.empresa.com.br" } + }, + "activated_at": "2026-07-01T12:00:00Z", + "activated_by": "roger" +} +``` + +### Response 207 (parcial) + +```json +{ + "ok": false, + "billing_state": "provisioning", + "steps": { + "foss": { "client_id": 101, "order_id": 55 }, + "openpanel": { "error": "user already exists" }, + "odoo": { "partner_id": 88 } + }, + "message": "OpenPanel falhou — FOSS e Odoo OK" +} +``` + +### Erros + +| HTTP | Condição | +|------|----------| +| 400 | `plan_code` inválido ou `billing_state` não permite activação | +| 403 | RBAC insuficiente | +| 404 | `billing_account` não existe | +| 409 | Já `billing_active` | +| 502 | FOSS/Odoo indisponível | + +--- + +## GET `/billing/accounts/{id}/activation-preview` + +Devolve payload **read-only** com mapeamento que será enviado a FOSS/OP/Odoo (para UI staff antes de confirmar). + +### Response 200 + +```json +{ + "domain": "empresa.com.br", + "company_profile": { "...": "..." }, + "mapped": { + "foss_client": { "email": "admin@empresa.com.br", "company": "...", "company_vat": "..." }, + "openpanel": { "plan_name": "ligbox-mail-business", "domain": "empresa.com.br" }, + "odoo_partner": { "name": "...", "vat": "...", "email": "..." } + }, + "billing_state": "awaiting_billing_validation" +} +``` + +--- + +*Implementar em `projects/ops-desk/api/app/billing_routes.py` + `vm123/client_provision.py`* diff --git a/ligbox-ops-platform/specs/043-desk-client-activation-sync/spec.md b/ligbox-ops-platform/specs/043-desk-client-activation-sync/spec.md new file mode 100644 index 0000000..7e11acc --- /dev/null +++ b/ligbox-ops-platform/specs/043-desk-client-activation-sync/spec.md @@ -0,0 +1,104 @@ +# Spec 043 — Sincronização Cliente: Wizard → Desk → FOSS → OpenPanel → Odoo + +**Criado:** 2026-07-01 +**Solicitado por:** Roger +**Status:** ✅ **Implementação completa (Fases 1–6 código)** — aguarda teste E2E Roger na VM122 +**Prioridade:** P0 (orquestração comercial Ligbox) +**Sistemas:** VM112 Wizard · VM122 Desk · VM123 FOSS/Odoo/OpenPanel + +--- + +## Resumo + +Esta spec **unifica e documenta** o mapeamento de dados desde o card **«Dados da empresa e cobrança»** no wizard (VM112) até aos três painéis financeiros/hosting na VM123: + +1. **FOSSBilling** — cliente + pedido + activação hosting (primeiro destino API) +2. **OpenPanel** — tipo de contrato / plano / domínio hub (via bridge ou módulo FOSS) +3. **Odoo 16** — empresa (`res.partner`) e fluxo financeiro + +O Desk (VM122) é o **orquestrador**: recebe `company.validated`, persiste `billing_accounts`, e expõe acção staff **«Activar conta»** que dispara a sequência documentada. + +**Documento mestre de campos:** [contracts/activation-field-mapping.md](./contracts/activation-field-mapping.md) + +--- + +## Specs relacionadas (leitura obrigatória) + +| Spec | Relação | +|------|---------| +| [023](../023-billing-recurrence-desk-visibility/spec.md) | Card empresa, `company.validated`, `billing_accounts`, estados | +| [024](../024-openpanel-fossbilling/spec.md) | Stack VM123, FOSS+Odoo+OpenPanel | +| [024 PROVISIONING_CLIENT_CARD](../024-openpanel-fossbilling/PROVISIONING_CLIENT_CARD.md) | Campos card → FOSS → OP (site CMS) | +| [028](../028-openpanel-ce-ligbox-reengineering/spec.md) | Bridge `:18087`, re-engenharia CE | +| [028 foss-bridge-api](../028-openpanel-ce-ligbox-reengineering/contracts/foss-bridge-api.md) | Contrato API bridge | +| [035](../035-ligbox-mail-bundles-foss-openpanel/spec.md) | Bundles mail, `manager_name`, webhook `order-activated` | +| [001](../001-webhook-vm112-integration/spec.md) | Webhooks VM112 → Desk | +| [004](../004-onboard-funnel-events/spec.md) | Funil onboarding | +| [027](../027-desk-rbac-function-matrix/spec.md) | Quem pode activar conta | +| [039](../039-ligbox-ops-authorization-catalog/spec.md) | `vm123_foss.*`, `vm123_openpanel.*`, Odoo | +| [040](../040-desk-design-system-v013/spec.md) | UI staff Access Control Hub | + +--- + +## Arquitectura + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ VM112 — Wizard / Domain Admin (onboard.ligbox.com.br) │ +│ Card «Dados da empresa e cobrança» + conta admin@{domínio} │ +└───────────────────────────────┬─────────────────────────────────────────┘ + │ webhook company.validated (+ account.created) + ▼ +┌─────────────────────────────────────────────────────────────────────────┐ +│ VM122 — Ligbox Ops Desk │ +│ billing_accounts · ticket [billing-validation] · UI «Activar conta» │ +└───────────────────────────────┬─────────────────────────────────────────┘ + │ sequência staff (Spec 043) + ┌─────────────────────┼─────────────────────┐ + ▼ ▼ ▼ + FOSSBilling :8092 Bridge :18087 Odoo :8069 + (cliente+order) (OpenPanel user) (res.partner) + │ │ │ + └─────────────────────┴─────────────────────┘ + │ + ▼ + Wizard provision mail-bundle (VM112 Carbonio) +``` + +--- + +## Entregáveis desta spec + +| Artefacto | Path | +|-----------|------| +| **Mapa de campos** | [contracts/activation-field-mapping.md](./contracts/activation-field-mapping.md) | +| **API Desk (planeada)** | [contracts/desk-activate-account-api.md](./contracts/desk-activate-account-api.md) | +| **Tasks implementação** | [tasks.md](./tasks.md) | + +--- + +## Código de referência (VM122) + +| Módulo | Path | +|--------|------| +| Billing store | `projects/ops-desk/api/app/billing_store.py` ou `legacy-app/billing_store.py` | +| Webhook ingress | `projects/ops-desk/api/app/main.py` (`company.validated`) | +| FOSS client | `projects/ops-desk/api/app/vm123/foss_client.py` | +| Odoo client | `projects/ops-desk/api/app/vm123/odoo_client.py` | +| OpenPanel client | `projects/ops-desk/api/app/vm123/openpanel_client.py` | +| UI ficha cliente | `projects/ops-desk/frontend/assets/billing-ui.js` | + +--- + +## Regras de negócio (Roger) + +1. Wizard **não cobra** no card empresa — só recolhe e valida ([023](../023-billing-recurrence-desk-visibility/spec.md)). +2. **FOSS recebe primeiro** os dados do cliente (create client + order). +3. **OpenPanel** reflecte o **tipo de serviço** (`plan_name` + metadata mail). +4. **Odoo** recebe a **empresa** para gestão financeira (`res.partner`). +5. Um **gerente** por domínio: `admin@{domínio}` + `manager_name` / `manager_email`. +6. Staff activa após revisão OPS — não automático sem RBAC ([027](../027-desk-rbac-function-matrix/spec.md)). + +--- + +*Roger · Spec 043 · documentação viva — actualizar quando campos wizard ou APIs VM123 mudarem* diff --git a/ligbox-ops-platform/specs/043-desk-client-activation-sync/tasks.md b/ligbox-ops-platform/specs/043-desk-client-activation-sync/tasks.md new file mode 100644 index 0000000..b274b46 --- /dev/null +++ b/ligbox-ops-platform/specs/043-desk-client-activation-sync/tasks.md @@ -0,0 +1,41 @@ +# Spec 043 — Tasks + +## Documentação +- [x] Spec índice `spec.md` +- [x] Contrato `activation-field-mapping.md` +- [x] Contrato API `desk-activate-account-api.md` +- [x] Ligações cruzadas specs 023/024/028/035 +- [x] Registo em `SPEC-REGISTRY.md` +- [x] `ROLLBACK.md` com tags Git + +## Fase 1 — Desk preview UI +- [x] `GET /billing/accounts/{id}/activation-preview` +- [x] Botão **Activar conta** em `billing-ui.js` (só roles autorizados) +- [x] Modal confirmação com 3 colunas FOSS / OpenPanel / Odoo +- [ ] Deploy VM122 + validação Roger (teste manual) + +## Fase 2 — FOSS client + order +- [x] `foss_client.create_client()` conforme mapa §4 +- [x] `foss_client.create_order()` + activate hosting +- [x] Custom fields FOSS via `config` (domain, manager_*) +- [x] Persistir `external_customer_id` + `external_subscription_id` + +## Fase 3 — OpenPanel +- [x] Bridge directo (`provision_user_safe`) + metadata JSON +- [x] Persistir `openpanel_username` em `company_profile_json` +- [x] Idempotência user exists + +## Fase 4 — Odoo empresa +- [x] `odoo_client.upsert_customer_partner()` conforme mapa §6 +- [x] Coluna `odoo_partner_id` em `billing_accounts` +- [x] Deep-link Odoo na ficha cliente + +## Fase 5 — Wizard mail-bundle +- [x] `POST /billing/accounts/{id}/activate` com `provision_mail` +- [x] Webhook `POST /billing/webhook/foss/order-activated` +- [x] `wizard_client.provision_mail_bundle()` → VM112 + +## Fase 6 — Testes +- [x] Unit: `test_activation_mapper_043.py` (3) +- [x] Unit: `test_client_activation_043.py` (4) — happy path, idempotência FOSS, reject active +- [ ] E2E Roger: domínio teste wizard → activate → FOSS+OP+Odoo diff --git a/ligbox-ops-platform/specs/SPEC-REGISTRY.md b/ligbox-ops-platform/specs/SPEC-REGISTRY.md new file mode 100644 index 0000000..95cd1da --- /dev/null +++ b/ligbox-ops-platform/specs/SPEC-REGISTRY.md @@ -0,0 +1,12 @@ +# Registo de Specs — Ligbox Ops Platform + +| Spec | Pasta | Escopo | Versão Desk | +|------|-------|--------|-------------| +| 027 | `027-desk-rbac-function-matrix/` | Matriz RBAC | — | +| 039 | `039-ligbox-ops-authorization-catalog/` | Catálogo acções | — | +| **040** | **`040-desk-design-system-v013/`** | **UserWizard + Access Control Hub + Governance API** | **0.13.1-ac-hub-ui-aprovado-roger** | +| **041** | **`041-desk-operational-feed/`** | **Central Operacional (ex-Mensagens) + ops-inbox API** | **0.13.0** | +| **042** | **`042-ligbox-nettools-portal/`** | **NetTools — 23 ferramentas OSS em nettools.ligbox.com.br** | — | +| **043** | **`043-desk-client-activation-sync/`** | **Mapa campos Wizard→Desk→FOSS→OpenPanel→Odoo + API Activar conta** | — | + +Atualizado: 2026-07-01 · Roger · Spec 043 mapeamento activação cliente