Fluxo recomendado — integração ERP

Do tipo de conexão à ativação — API-first, revisão humana nos mapeamentos.

  1. Passo 1

    Escolher modo

    cloud_db (recomendado), cloud_api ou agent on-premise.

    Ver modos
  2. Passo 2

    Testar credenciais

    POST /erp-connections/{id}/test antes de gerar mapeamentos.

    API Explorer
  3. Passo 3

    Validar e ativar

    generate → validate → PATCH status active + sync_interval.

    Wizard referência /admin/settings/erp-connection

Princípios

ERP no aranduOS = API wizard + plugins custom. SSOT: docs/erp-integration.md

RegraDetalhe
API-firstTeste, mapeamento e validação via REST — não só UI
Plugin por clienteERP complexo → extensions/ no repo cliente (Mirá implementa)
Credenciais segurasPassword/token só no body wizard; nunca reemitidos na API
LLM via LiteLLMGeração de templates — llm.mira-dev.tech; fallback heurístico
Um ERP por tenantMember isolado; platform monitora rede

Modos de conexão

ModoValor APIQuando usar
Cloud — banco de dadoscloud_dbPostgreSQL, MySQL ou SQL Server (recomendado)
Cloud — API RESTcloud_apiERP com REST/OpenAPI documentado
Agent on-premiseagentERP na rede cliente — conexão de saída apenas

Introspecção SQL live + amostra de dados: PostgreSQL, MySQL e SQL Server.

Wizard — quatro passos

PassoUXAPI
1 — Tipocloud_db / cloud_api / agentPOST /erp-connections
2 — CredenciaisHost, DB, API URL, agent tokenPOST …/test
3 — MapeamentoIA + edição manualPOST …/mappings/generate · …/validate
4 — AtivaçãoIntervalo syncPATCH …/{id} status active
  • components/member/ERPWizard.tsx

    Wizard multi-step (referência UX)

  • app/(member)/admin/settings/erp-connection

    Member — configuração própria

  • app/(platform)/admin/settings/erp-connection

    Platform — conta mãe

  • app/(platform)/admin/external-data

    Monitoramento rede ERP

Operações mapeadas

OperaçãoUso no commerce
get_pricePreço externo (external_data)
get_stockDisponibilidade / inventário
create_orderPush pedido confirmado → ERP
update_orderAtualização pós-workflow
get_order_statusReconciliação / polling

Cada linha: template SQL ou REST · confidence high/medium/low/manual · source_type sql|rest

Endpoints REST

MétodoPathNotas
GET/erp-connectionsinventory:read · platform ?tenant_id=
POST/erp-connectionsCriar conexão + mappings
GET/PATCH/erp-connections/{id}Detalhe / ativar
POST/erp-connections/{id}/testCredenciais no body (wizard)
POST/erp-connections/{id}/mappings/generateDescoberta + LiteLLM
POST/erp-connections/{id}/mappings/validateExecuta templates live

Fluxo API

POST /v1/erp-connections
{ "mode": "cloud_db", "db_type": "postgres", "sync_interval": 60 }

POST /v1/erp-connections/{id}/test
{ "connection_type": "cloud_db", "host": "…", "password": "…", "ssl_enabled": true }

POST /v1/erp-connections/{id}/mappings/generate
→ { data: [...], meta: { used_llm, discovery_source, discovery_summary } }

POST /v1/erp-connections/{id}/mappings/validate
{ "rows": [...], "credentials": { … } }

PATCH /v1/erp-connections/{id}
{ "status": "active", "sync_interval": 300 }

Descoberta de schema

discovery_sourceOrigem
live_introspectionSQL real (Postgres information_schema)
openapiOpenAPI do api_base_url
inferredHeurística por modo/db
heuristicFallback sem credenciais live

SDK TypeScript

@mira/commerce-client-sdk
import {
  createErpConnection,
  testErpConnection,
  generateErpMappings,
  validateErpMappings,
} from "@mira/commerce-client-sdk"

const { data: conn } = await createErpConnection({
  client,
  body: { mode: "cloud_db", db_type: "postgres", sync_interval: 60 },
})

await testErpConnection({
  client,
  path: { connection_id: conn.id },
  body: { connection_type: "cloud_db", host: "…", password: "…" },
})

Facade: lib/commerce-client/domains/live/erp.ts · Catálogo SDK: /dev/experience/sdk

Extensão avançada (Fase 2b+)

SAP, TOTVS, Protheus ou regras fiscais → plugin Go no repo cliente.

IntegrationAdapter — ARCHITECTURE § Peça 1
capabilities:
  integrations:
    - erp.inventory_sync
  hooks:
    - integration.transform_outbound
    - integration.transform_inbound

// SyncInventory · SyncPrices · PushOrder · PushOrderStatus
// Protocolo: commerce.mira.dev/integration/erp/v1

Customização backend ERP: sempre equipe Mirá — ver extensibility-model.md

Estado de implementação

ComponenteDocumentadoCódigoNotas
REST wizard (test / generate / validate)
Documentado
Documentado
internal/erp/
Wizard UX member + platform
Documentado
Documentado
ERPWizard.tsx
Introspecção SQL live + amostra (PG/MySQL/SQL Server)
Documentado
Documentado
catalog.go
Mapeamento LiteLLM
Documentado
Protótipo
Fallback heurístico sem LLM_API_URL
Motor sync / PushOrder plugin
Documentado
Documentado
IntegrationAdapter ligado: estoque/preço aplicados no catálogo + telemetria real
Agent on-premise (binário)
Protótipo
Planejado
UX protótipo; agent real backlog

Anti-patterns

EvitarPreferir
Credenciais ERP no front-endWizard server-side + secrets cluster
SQL ad-hoc no ReactTemplates validados via API + plugin
Fork core para SAPPlugin extensions/ + pin LTS
OPENAI direto no mappingLLM_API_URL → llm.mira-dev.tech
Ativar sem validatevalidate verde + sync_interval conservador

Checklist delivery

  1. Modo cloud_db se DB acessível (readonly + allowlist)
  2. test verde → generate → revisar confidence low
  3. validate verde em staging
  4. PATCH active com sync_interval ≥ 300s inicialmente
  5. Monitorar /admin/external-data e alertas member
  6. ERP complexo → ADR + plugin no repo cliente
API ExplorerWizard referência (painel) /admin/settings/erp-connectionMonitoramento ERP /admin/external-dataExtensibilidade (plugins)