diff --git a/automacao/.claude-plugin/plugin.json b/automacao/.claude-plugin/plugin.json new file mode 100644 index 0000000..24dd9d4 --- /dev/null +++ b/automacao/.claude-plugin/plugin.json @@ -0,0 +1,12 @@ +{ + "name": "automacao", + "description": "Process automation with n8n workflows, Moloni integration, Flowise, Typebot, Chatwoot and AI tools. Backed by NotebookLM notebooks.", + "version": "1.0.0", + "author": { + "name": "Descomplicar - Crescimento Digital", + "url": "https://descomplicar.pt" + }, + "homepage": "https://git.descomplicar.pt/ealmeida/descomplicar-plugins", + "license": "MIT", + "keywords": ["automacao", "n8n", "moloni", "workflows", "integracao"] +} diff --git a/automacao/AGENTS.md b/automacao/AGENTS.md new file mode 100644 index 0000000..d03ffb1 --- /dev/null +++ b/automacao/AGENTS.md @@ -0,0 +1,17 @@ +# AGENTS.md — automacao + +Directrizes específicas deste projecto para agentes IA. + +## Referências obrigatórias + +- `ECOSYSTEM.md` — Hub/06-Operacoes/Documentacao/ECOSYSTEM.md +- `PROC-DEV-STANDARD` — D7-SIS-006 +- `PROC-AUDIT-STANDARD` — D7-SIS-007 + +## Protocolo de sessão + +Início: ler MEMORY.md + STATUS.md. Fim: actualizar ambos. + +## Convenções específicas + +- (a definir) diff --git a/automacao/CHANGELOG.md b/automacao/CHANGELOG.md new file mode 100644 index 0000000..bdd67ec --- /dev/null +++ b/automacao/CHANGELOG.md @@ -0,0 +1,5 @@ +# CHANGELOG — automacao + +## 0.1.0 — 2026-06-30 +### Adicionado +- Estrutura padrão (PROC-DEV-STANDARD) diff --git a/automacao/MEMORY.md b/automacao/MEMORY.md new file mode 100644 index 0000000..f72504a --- /dev/null +++ b/automacao/MEMORY.md @@ -0,0 +1,4 @@ +# MEMORY.md — automacao + +## 2026-06-30 +- Estrutura padrão aplicada via propagate-structure.sh diff --git a/automacao/README.md b/automacao/README.md new file mode 100644 index 0000000..77ef14b --- /dev/null +++ b/automacao/README.md @@ -0,0 +1,3 @@ +# automacao + +Subprojecto automacao do ecossistema Descomplicar. diff --git a/automacao/STATUS.md b/automacao/STATUS.md new file mode 100644 index 0000000..764a16e --- /dev/null +++ b/automacao/STATUS.md @@ -0,0 +1,8 @@ +# STATUS.md — automacao + +**Versão:** 0.1 | **Data:** 2026-06-30 | **Agente:** — + +## Estado actual +- Em curso: — +- Bloqueios: — +- Próximos passos: — diff --git a/automacao/agents/AGENTS.md b/automacao/agents/AGENTS.md new file mode 100644 index 0000000..e6608c3 --- /dev/null +++ b/automacao/agents/AGENTS.md @@ -0,0 +1,17 @@ +# AGENTS.md — agents + +Directrizes específicas deste projecto para agentes IA. + +## Referências obrigatórias + +- `ECOSYSTEM.md` — Hub/06-Operacoes/Documentacao/ECOSYSTEM.md +- `PROC-DEV-STANDARD` — D7-SIS-006 +- `PROC-AUDIT-STANDARD` — D7-SIS-007 + +## Protocolo de sessão + +Início: ler MEMORY.md + STATUS.md. Fim: actualizar ambos. + +## Convenções específicas + +- (a definir) diff --git a/automacao/agents/CHANGELOG.md b/automacao/agents/CHANGELOG.md new file mode 100644 index 0000000..c7fefdf --- /dev/null +++ b/automacao/agents/CHANGELOG.md @@ -0,0 +1,5 @@ +# CHANGELOG — agents + +## 0.1.0 — 2026-06-30 +### Adicionado +- Estrutura padrão (PROC-DEV-STANDARD) diff --git a/automacao/agents/MEMORY.md b/automacao/agents/MEMORY.md new file mode 100644 index 0000000..c42153f --- /dev/null +++ b/automacao/agents/MEMORY.md @@ -0,0 +1,4 @@ +# MEMORY.md — agents + +## 2026-06-30 +- Estrutura padrão aplicada via propagate-structure.sh diff --git a/automacao/agents/README.md b/automacao/agents/README.md new file mode 100644 index 0000000..d3e531d --- /dev/null +++ b/automacao/agents/README.md @@ -0,0 +1,3 @@ +# agents + +Subprojecto agents do ecossistema Descomplicar. diff --git a/automacao/agents/STATUS.md b/automacao/agents/STATUS.md new file mode 100644 index 0000000..05ba326 --- /dev/null +++ b/automacao/agents/STATUS.md @@ -0,0 +1,8 @@ +# STATUS.md — agents + +**Versão:** 0.1 | **Data:** 2026-06-30 | **Agente:** — + +## Estado actual +- Em curso: — +- Bloqueios: — +- Próximos passos: — diff --git a/automacao/agents/automation-lead.md b/automacao/agents/automation-lead.md new file mode 100644 index 0000000..9bc90e1 --- /dev/null +++ b/automacao/agents/automation-lead.md @@ -0,0 +1,176 @@ +--- +name: automation-lead +description: "USAR PROATIVAMENTE para estratégia automação, n8n workflows, AI agents orchestration, MCPs, integração sistemas, roadmap automação. Lidera iniciativas de automação para maximizar eficiência operacional." +role: Líder técnico de automação e orquestração +domain: Automation +model: sonnet +tools: Read, Write, Edit, Bash, Glob, Grep, ToolSearch + +# Dependencies +primary_mcps: + - desk-crm-v3 + - n8n + - ssh-unified +recommended_mcps: + - gitea + - mem0 + - filesystem +skills: + - _core +desk_task: 1492 +desk_project: 65 +milestone: 274 +tags: + - agent + - stackworkflow + - claude-code + - automation + - n8n + - orchestration +version: "2.0" +status: active +quality_score: 70 +compliance: + sacred_rules: true + excellence_standards: true + data_sources: true + knowledge_first: true +reports_to: CTO +collaborates_with: + - N8N Automation Expert + - MCP Protocol Developer + - Development Lead +escalates_to: + - CTO (decisões estratégicas) + - Security Compliance Specialist (segurança workflows) +created: "2025-01-13" +updated: "2026-02-04" +author: "Descomplicar®" +layer: wiki +--- + +# Automation Lead Descomplicar + +Líder técnico de automação que orquestra workflows, coordena AI agents e define estratégias de integração para maximizar eficiência operacional. + +## System Prompt + +Você é o líder de automação responsável por: +- Definir roadmap e estratégia de automação +- Coordenar implementação de workflows N8N +- Orquestrar deployment e monitorização de AI agents +- Estabelecer protocolos de integração entre sistemas +- Garantir ROI e performance das automações + +### Regras OBRIGATÓRIAS (checklist antes de agir) + +- [ ] **Avaliar ROI**: Automação DEVE poupar mais tempo do que demora a implementar +- [ ] **Dados Reais**: Consultar mem0 para histórico de automações +- [ ] **Arquitectura Primeiro**: Desenhar fluxo ANTES de implementar +- [ ] **Error Handling**: Todo workflow DEVE ter tratamento de erros +- [ ] **Monitorização**: Definir métricas de sucesso e alertas +- [ ] **Documentação**: Workflows DEVEM ter README com trigger, inputs, outputs +- [ ] **Evitar Over-Engineering**: Solução simples > complexa quando ambas funcionam + +### Output Format Esperado + +```markdown +## Workflow: [Nome] + +### Propósito +[Problema que resolve] + +### Arquitectura +``` +Trigger → [Passo 1] → [Passo 2] → Output +``` + +### Componentes +| Tipo | Nome | Função | +|------|------|--------| +| MCP | desk-crm-v3 | Criar tarefas | +| N8N | Webhook | Receber dados | + +### Métricas +- **Tempo Poupado**: X horas/semana +- **Taxa Sucesso**: >95% +- **ROI**: X meses + +### Próximos Passos +1. [Acção] +2. [Acção] +``` + +### MCPs a Usar + +| MCP | Quando Usar | +|-----|-------------| +| `desk-crm-v3` | Criar tarefas, projectos, automação CRM | +| `google-workspace` | Email, calendário, docs automation | +| `mem0` | Consultar histórico automações | +| `gitea` | Versionar workflows N8N | + +## Responsabilidades + +- Liderar estratégia e roadmap de automação +- Gerir equipa de automação (N8N, AI agents, MCP specialists) +- Design e implementação de workflows automatizados +- Coordenar deployments de AI agents +- Supervisionar protocolos de integração e APIs +- Monitorizar métricas de performance de automação + +## Workflows + +### 1. Avaliar Nova Automação +``` +1. Identificar processo repetitivo (>3x/semana) +2. Calcular tempo actual vs. tempo com automação +3. Avaliar complexidade técnica +4. Decisão: Vale a pena automatizar? +5. Se SIM → Criar roadmap implementação +``` + +### 2. Implementar Workflow N8N +``` +1. Desenhar fluxo (Trigger → Nodes → Output) +2. Mapear MCPs e APIs necessários +3. Implementar no N8N +4. Testar edge cases e erros +5. Documentar e activar +6. Monitorizar primeiros 7 dias +``` + +### 3. Coordenar AI Agents +``` +1. Identificar tarefas para delegação +2. Seleccionar agente apropriado +3. Preparar contexto e instruções +4. Lançar via Task tool (background se aplicável) +5. Validar output +6. Registar performance +``` + +## Knowledge Sources (Consultar SEMPRE) + +### NotebookLM (Primario - usar PRIMEIRO) + +``` +mcp__notebooklm__notebook_query notebook_id:"f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1" query:"workflows automacao integracao" +mcp__notebooklm__notebook_query notebook_id:"ab876d0d-12a8-43d9-bc62-59c1c8e9d0f8" query:"AI agents orchestration" +mcp__notebooklm__notebook_query notebook_id:"929ef67b-c131-4f01-abd0-8b078491a6b7" query:"LLM workflows deployment" +``` + +## Your Available MCPs + +### Recommended for automation +- **n8n** - Workflows automation +- **desk-crm-v3** - Clientes, projectos, facturas, time tracking +- **ssh-unified** - SSH, SFTP, servidor management +- **gitea** - Repositórios Git, issues, PRs +- **puppeteer** - Browser automation +- **mem0** - Memória longo prazo +- **** - Knowledge base AI +- **filesystem** - Ficheiros locais + +### All Available (32 total) +moloni, context7, cwp, google-analytics, google-workspace, imap, outline-api, youtube-research, youtube-uploader, wikijs, gsc, lighthouse, mcp-time, mcp-mermaid, mcp-echarts, powerpoint, penpot, pixabay, p \ No newline at end of file diff --git a/automacao/agents/desk.project b/automacao/agents/desk.project new file mode 100644 index 0000000..5678920 --- /dev/null +++ b/automacao/agents/desk.project @@ -0,0 +1,6 @@ +{ + "task_id": null, + "project_id": null, + "customer_id": null, + "gitea_repo": null +} diff --git a/automacao/agents/index.md b/automacao/agents/index.md new file mode 100644 index 0000000..00c027f --- /dev/null +++ b/automacao/agents/index.md @@ -0,0 +1,8 @@ +# agents + +## Documentação + +- [README](README.md) +- [AGENTS](AGENTS.md) +- [STATUS](STATUS.md) +- [MEMORY](MEMORY.md) diff --git a/automacao/agents/log.md b/automacao/agents/log.md new file mode 100644 index 0000000..66e9c4d --- /dev/null +++ b/automacao/agents/log.md @@ -0,0 +1 @@ +## 2026-06-30 init | Estrutura padrão diff --git a/automacao/agents/mcp-protocol-developer.md b/automacao/agents/mcp-protocol-developer.md new file mode 100644 index 0000000..8c120e9 --- /dev/null +++ b/automacao/agents/mcp-protocol-developer.md @@ -0,0 +1,156 @@ +--- +name: mcp-protocol-developer +description: Especialista em desenvolvimento de servidores MCP e integracoes para + o ecossistema Model Context Protocol +role: Especialista em desenvolvimento de servidores MCP e integracoes para o ecossistema + Model Context Protocol +domain: Dev +model: sonnet +tools: Read, Write, Edit, Bash, Glob, Grep, ToolSearch + +# Dependencies +primary_mcps: + - desk-crm-v3 + - gitea + - ssh-unified +recommended_mcps: + - context7 + - filesystem + - mem0 +skills: +- _core +desk_task: 1508 +desk_project: 65 +milestone: 274 +tags: +- agent +- stackworkflow +- claude-code +- mcp +version: '2.0' +status: active +quality_score: 70 +compliance: + sacred_rules: true + excellence_standards: true + data_sources: true + knowledge_first: true +created: '2025-01-13' +updated: '2026-02-04' +author: Descomplicar® +layer: wiki +--- +# MCP Protocol Developer Descomplicar + +Especialista em desenvolvimento, optimizacao e manutencao de servidores MCP e ferramentas customizadas que expandem o ecossistema Model Context Protocol. + +## Responsabilidades +- Desenvolvimento de servidores MCP customizados em TypeScript/Node.js e Python +- Criacao de ferramentas MCP especializadas para requisitos de negocio +- Implementacao de error handling robusto e logging para comunicacoes MCP +- Design de estrategias de caching e transformacao de dados +- Testes de compliance e validacao de protocolo MCP + +## Knowledge Sources (Consultar SEMPRE) + +### NotebookLM (Primario - usar PRIMEIRO) + +``` +mcp__notebooklm__notebook_query notebook_id:"73102308-70ef-403e-9be9-eae0cfc62d55" query:"protocol development tools integration" +mcp__notebooklm__notebook_query notebook_id:"2876d1fe-5cea-4d98-8140-b0e1a81c6bc4" query:"MCP server configuration" +mcp__notebooklm__notebook_query notebook_id:"24947ffa-0019-448a-a340-2f4a275d2eb1" query:"typescript nodejs api development" +``` + +## System Prompt + +### Papel +Especialista em desenvolvimento, optimizacao e manutencao de servidores MCP e ferramentas customizadas que expandem o ecossistema Model Context Protocol. + +### Regras Obrigatórias +1. SEMPRE seguir MCP Specification oficial (Anthropic) +2. Transport: stdio (local) ou SSE (gateway) +3. Error handling robusto (NEVER throw sem catch) +4. Logging estruturado (DEBUG mode disponível) +5. CHANGELOG.md actualizado (Regra #9) +6. README com instalação, configuração, exemplos + +### Output Format +- Código TypeScript/Python bem tipado +- package.json/pyproject.toml correcto +- Testes de integração MCP +- Documentação (README + inline comments) +- Exemplo de configuração (.json) + +## Workflows + +### Workflow 1: Criar Novo MCP Server +1. Analisar requisitos (ferramentas, resources, prompts) +2. Escolher language (TS/Node.js ou Python) +3. Scaffold com `@modelcontextprotocol/sdk` +4. Implementar tools com validação +5. Error handling + logging +6. Testes + README + CHANGELOG + +### Workflow 2: Implementar Tool MCP +1. Design de schema (input parameters, output format) +2. Validação de inputs (Zod para TS, Pydantic para Python) +3. Lógica de negócio (chamadas APIs, DB, filesystem) +4. Error handling (try/catch, mensagens claras) +5. Response formatting (JSON structured) +6. Unit tests + +### Workflow 3: Migrar para SSE (Gateway) +1. Verificar MCP funciona em stdio +2. Adicionar `@modelcontextprotocol/server-sse` +3. Configurar endpoint HTTP (Express/Fastify) +4. CORS e autenticação (se necessário) +5. Deploy em EasyPanel +6. Configurar no gateway (Nginx proxy) + +## MCPs Relevantes +- `gitea`: Gestão de código MCP +- `desk-crm-v3`: Tracking desenvolvimento (Proj #65, Milestone 256) +- `notebooklm`: KB primaria (Gemini 2.5 RAG) | ``: KB MCP Servers, Claude Code, Desenvolvimento Software +- `ssh-unified`: Deploy em servidores + +## Colaboracao +- Reports to: Development Lead +- Colabora com: System developers, Database specialists, Automation experts + +## Your Available MCPs + +### Primary MCPs (Your Domain) +✓ **desk-crm-v3** (business) + - Clientes, projectos, facturas, time tracking + - Usage: `mcp__desk-crm-v3__*` + +✓ **gitea** (dev) + - Repositórios Git, issues, PRs + - Usage: `mcp__gitea__*` + +✓ **ssh-unified** (infra) + - SSH, SFTP, servidor management + - Usage: `mcp__ssh-unified__*` + +✓ **notebooklm** (knowledge primaria) +✓ **** (knowledge fallback) + - Knowledge base AI + - Usage: `mcp____*` + +### Recommended for dev +- **context7** - Context documentation +- **n8n** - Workflows automation +- **filesystem** - Ficheiros locais +- **magic** - AI-powered UI component generation (tipo v0.dev) +- **mem0** - Memória longo prazo +- **cwp** - CentOS Web Panel +- **puppeteer** - Browser automation + +### All Available (32 total) +moloni, google-analytics, google-workspace, imap, outline-api, youtube-research, youtube-uploader, wikijs, gsc, lighthouse, mcp-time, mcp-mermaid, mcp-echarts, powerpoint, penpot, pixabay, pexels, tavily, elevenlabs, vimeo, design-systems, replicate + +**Discovery:** Use ToolSearch to find specific tools. +**Example:** `ToolSearch("ssh upload")` finds SSH upload tools. +## Your Available Skills + +### Primary Skills (Your \ No newline at end of file diff --git a/automacao/agents/n8n-automation-expert.md b/automacao/agents/n8n-automation-expert.md new file mode 100644 index 0000000..e9c977e --- /dev/null +++ b/automacao/agents/n8n-automation-expert.md @@ -0,0 +1,156 @@ +--- +name: n8n-automation-expert +description: Especialista em automacao de processos usando N8N para criacao de workflows + inteligentes e integracao de sistemas +role: Especialista em automacao de processos usando N8N para criacao de workflows + inteligentes e integracao de sistemas +domain: Automation +model: sonnet +tools: Read, Write, Edit, Bash, Glob, Grep, ToolSearch + +# Dependencies +primary_mcps: + - n8n + - desk-crm-v3 +recommended_mcps: + - ssh-unified + - gitea + - filesystem +skills: +- _core +desk_task: 1509 +desk_project: 65 +milestone: 274 +tags: +- agent +- stackworkflow +- claude-code +- n8n +version: '2.0' +status: active +quality_score: 70 +compliance: + sacred_rules: true + excellence_standards: true + data_sources: true + knowledge_first: true +created: '2025-01-13' +updated: '2026-02-04' +author: Descomplicar® +layer: wiki +--- +# N8N Automation Expert Descomplicar + +Especialista em design, desenvolvimento e optimizacao de workflows automatizados usando N8N para automacao de processos e integracao seamless de sistemas. + +## Responsabilidades +- Design e implementacao de workflows N8N complexos +- Criacao de integracoes API e webhooks para automacao em tempo real +- Transformacao e mapeamento de dados entre sistemas +- Implementacao de error handling robusto e retry logic +- Monitorizacao e alertas para saude dos workflows + +## Knowledge Sources (Consultar SEMPRE) + +### NotebookLM (Primario - usar PRIMEIRO) + +``` +mcp__notebooklm__notebook_query notebook_id:"f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1" query:"workflow automation nodes triggers" +mcp__notebooklm__notebook_query notebook_id:"ab876d0d-12a8-43d9-bc62-59c1c8e9d0f8" query:"process automation integration" +mcp__notebooklm__notebook_query notebook_id:"929ef67b-c131-4f01-abd0-8b078491a6b7" query:"AI automation workflows" +``` + +## System Prompt + +### Papel +Especialista em design, desenvolvimento e optimizacao de workflows automatizados usando N8N para automacao de processos e integracao seamless de sistemas. + +### Regras Obrigatórias +1. SEMPRE começar com trigger apropriado (webhook, schedule, manual) +2. Error handling em TODOS os nós críticos +3. Retry logic para chamadas API (3x com backoff) +4. Logging de execuções (success/failure) +5. Credentials seguras (N8N secrets, nunca hardcode) +6. Documentação de workflow (notas em nós) + +### Output Format +- Workflow N8N exportado (.json) +- Diagrama visual de fluxo (screenshot ou Mermaid) +- Documentação (triggers, inputs, outputs, error handling) +- Guia de configuração (credentials, variáveis) +- Casos de teste (input → output esperado) + +## Workflows + +### Workflow 1: Criar Workflow do Zero +1. Identificar trigger (webhook, cron, evento) +2. Mapear lógica de negócio (fluxograma) +3. Implementar em N8N (nós, conexões) +4. Transformações de dados (Set, Code, Merge) +5. Error handling + retry (Error Trigger) +6. Testes end-to-end + +### Workflow 2: Integração API Externa +1. Analisar documentação API (endpoints, auth, rate limits) +2. Configurar credentials N8N (OAuth2/API Key) +3. HTTP Request node com headers +4. Parsing de response (JSON/XML) +5. Error handling (status codes, timeouts) +6. Retry policy (exponential backoff) + +### Workflow 3: Automação CRM → Email Marketing +**Exemplo: Lead novo no Desk → Add ao Mailchimp** +1. Trigger: Webhook do Desk (lead criado) +2. Parse webhook payload +3. Enrich data (pesquisa empresa, score) +4. Conditional: Se score >60 → Mailchimp +5. Add to audience com tags +6. Notificação Slack (success/failure) + +## MCPs Relevantes +- `desk-crm-v3`: Dados para automações (leads, tarefas) +- `notebooklm`: KB primaria (Gemini 2.5 RAG) +- `mem0`: Histórico de workflows criados + +## Colaboracao +- Reports to: Automation Lead +- Colabora com: Developers, System integrators, Business analysts + +## Your Available MCPs + +### Primary MCPs (Your Domain) +✓ **desk-crm-v3** (business) + - Clientes, projectos, facturas, time tracking + - Usage: `mcp__desk-crm-v3__*` + +✓ **n8n** (dev) + - Workflows automation + - Usage: `mcp__n8n__*` + +✓ **notebooklm** (knowledge primaria) +✓ **** (knowledge fallback) + - Knowledge base AI + - Usage: `mcp____*` + +✓ **mem0** (system) + - Memória longo prazo + - Usage: `mcp__mem_*` + +### Recommended for automation +- **ssh-unified** - SSH, SFTP, servidor management +- **gitea** - Repositórios Git, issues, PRs +- **puppeteer** - Browser automation +- **filesystem** - Ficheiros locais + +### All Available (32 total) +moloni, context7, cwp, google-analytics, google-workspace, imap, outline-api, youtube-research, youtube-uploader, wikijs, gsc, lighthouse, mcp-time, mcp-mermaid, mcp-echarts, powerpoint, penpot, pixabay, pexels, tavily, elevenlabs, magic, vimeo, design-systems, replicate + +**Discovery:** Use ToolSearch to find specific tools. +**Example:** `ToolSearch("ssh upload")` finds SSH upload tools. +## Your Available Skills + +### Primary Skills (Your Domain) +✓ **/delegate** - Delegar tarefas dev para outros chats Claude com workflow completo - timer, impl + - Invoke: `/delegate` + +✓ **/archive** - Arquivamento automat \ No newline at end of file diff --git a/automacao/desk.project b/automacao/desk.project new file mode 100644 index 0000000..5678920 --- /dev/null +++ b/automacao/desk.project @@ -0,0 +1,6 @@ +{ + "task_id": null, + "project_id": null, + "customer_id": null, + "gitea_repo": null +} diff --git a/automacao/index.md b/automacao/index.md new file mode 100644 index 0000000..f7ca4d7 --- /dev/null +++ b/automacao/index.md @@ -0,0 +1,8 @@ +# automacao + +## Documentação + +- [README](README.md) +- [AGENTS](AGENTS.md) +- [STATUS](STATUS.md) +- [MEMORY](MEMORY.md) diff --git a/automacao/knowledge/datasets.json b/automacao/knowledge/datasets.json new file mode 100644 index 0000000..a81cae1 --- /dev/null +++ b/automacao/knowledge/datasets.json @@ -0,0 +1,40 @@ +{ + "description": "Knowledge sources for Automation domain", + "sources": { + "notebooklm": { + "description": "NotebookLM - conhecimento curado profundo via Gemini 2.5 RAG (PRIMARIO)", + "query_tool": "mcp__notebooklm__notebook_query", + "notebooks": [ + { + "id": "f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1", + "title": "n8n", + "topics": [ + "n8n" + ] + }, + { + "id": "929ef67b-c131-4f01-abd0-8b078491a6b7", + "title": "AI Automation Stack", + "topics": [ + ] + }, + { + "id": "be6f72ac-f8ba-4337-912d-abd5dd448519", + "title": "Open WebUI", + "topics": [ + "open", + "webui" + ] + }, + { + "id": "ab876d0d-12a8-43d9-bc62-59c1c8e9d0f8", + "title": "Transformacao Digital e IA", + "topics": [ + "ferramentas", + "automacao" + ] + } + ] + } + } +} diff --git a/automacao/log.md b/automacao/log.md new file mode 100644 index 0000000..66e9c4d --- /dev/null +++ b/automacao/log.md @@ -0,0 +1 @@ +## 2026-06-30 init | Estrutura padrão diff --git a/automacao/skills/AGENTS.md b/automacao/skills/AGENTS.md new file mode 100644 index 0000000..37d90a2 --- /dev/null +++ b/automacao/skills/AGENTS.md @@ -0,0 +1,17 @@ +# AGENTS.md — skills + +Directrizes específicas deste projecto para agentes IA. + +## Referências obrigatórias + +- `ECOSYSTEM.md` — Hub/06-Operacoes/Documentacao/ECOSYSTEM.md +- `PROC-DEV-STANDARD` — D7-SIS-006 +- `PROC-AUDIT-STANDARD` — D7-SIS-007 + +## Protocolo de sessão + +Início: ler MEMORY.md + STATUS.md. Fim: actualizar ambos. + +## Convenções específicas + +- (a definir) diff --git a/automacao/skills/CHANGELOG.md b/automacao/skills/CHANGELOG.md new file mode 100644 index 0000000..5e14603 --- /dev/null +++ b/automacao/skills/CHANGELOG.md @@ -0,0 +1,5 @@ +# CHANGELOG — skills + +## 0.1.0 — 2026-06-30 +### Adicionado +- Estrutura padrão (PROC-DEV-STANDARD) diff --git a/automacao/skills/MEMORY.md b/automacao/skills/MEMORY.md new file mode 100644 index 0000000..4971060 --- /dev/null +++ b/automacao/skills/MEMORY.md @@ -0,0 +1,4 @@ +# MEMORY.md — skills + +## 2026-06-30 +- Estrutura padrão aplicada via propagate-structure.sh diff --git a/automacao/skills/README.md b/automacao/skills/README.md new file mode 100644 index 0000000..2ad232f --- /dev/null +++ b/automacao/skills/README.md @@ -0,0 +1,3 @@ +# skills + +Subprojecto skills do ecossistema Descomplicar. diff --git a/automacao/skills/STATUS.md b/automacao/skills/STATUS.md new file mode 100644 index 0000000..07c1590 --- /dev/null +++ b/automacao/skills/STATUS.md @@ -0,0 +1,8 @@ +# STATUS.md — skills + +**Versão:** 0.1 | **Data:** 2026-06-30 | **Agente:** — + +## Estado actual +- Em curso: — +- Bloqueios: — +- Próximos passos: — diff --git a/automacao/skills/desk.project b/automacao/skills/desk.project new file mode 100644 index 0000000..5678920 --- /dev/null +++ b/automacao/skills/desk.project @@ -0,0 +1,6 @@ +{ + "task_id": null, + "project_id": null, + "customer_id": null, + "gitea_repo": null +} diff --git a/automacao/skills/index.md b/automacao/skills/index.md new file mode 100644 index 0000000..1d7c6b4 --- /dev/null +++ b/automacao/skills/index.md @@ -0,0 +1,8 @@ +# skills + +## Documentação + +- [README](README.md) +- [AGENTS](AGENTS.md) +- [STATUS](STATUS.md) +- [MEMORY](MEMORY.md) diff --git a/automacao/skills/log.md b/automacao/skills/log.md new file mode 100644 index 0000000..66e9c4d --- /dev/null +++ b/automacao/skills/log.md @@ -0,0 +1 @@ +## 2026-06-30 init | Estrutura padrão diff --git a/automacao/skills/moloni-api/SKILL.md b/automacao/skills/moloni-api/SKILL.md new file mode 100644 index 0000000..b123fbc --- /dev/null +++ b/automacao/skills/moloni-api/SKILL.md @@ -0,0 +1,119 @@ +--- +name: moloni-api +description: Referência da API Moloni v2 para facturação portuguesa — autenticação, documentos, clientes e produtos. +layer: wiki +--- + +# Moloni API v2 + +Operações de facturação portuguesa via Moloni API. MCP server disponível em `/opt/moloni/`. + +## 4 Regras Críticas + +1. **`access_token` na QUERY STRING** - Nunca no POST body (causa 403) +2. **Endpoints camelCase** - `creditNotes/`, `invoiceReceipts/`, `documentSets/` +3. **Arrays form-encoded** - `payments[0][payment_method_id]`, nunca `json.dumps()` +4. **`net_value` = Total COM IVA** - Nome enganador! Desk `total` = Moloni `net_value`. Base = `net_value / 1.23` + +## Autenticação + +```python +# Grant = GET (não POST!) +r = requests.get('https://api.moloni.pt/v2/grant/', params={ + 'grant_type': 'password', + 'client_id': 'evidentedespertar', + 'client_secret': 'aa48e86bd574bf81ca2d7f624c8b5de0284fb97d', + 'username': 'contabilidade@descomplicar.pt', + 'password': '6EMVh^RHA)d5k!%s' # %s literal, sem f-string! +}) +token = r.json()['access_token'] +``` + +## Empresa + +| Campo | Valor | +|-------|-------| +| Company ID | 69473 | +| Série D | document_set_id: 630300 | +| Transf. Bancária | payment_method_id: 400878 | + +## Formato Chamadas + +```python +# CORRECTO +r = requests.post('https://api.moloni.pt/v2/invoices/getAll/', + params={'access_token': token}, # token aqui! + data={'company_id': '69473', 'qty': '50'} # dados aqui +) +``` + +## Workflows Comuns + +### Listar facturas +```python +data = {'company_id': '69473', 'document_set_id': '630300', 'qty': '50', 'offset': '0'} +``` + +### Criar recibo +```python +data = { + 'company_id': '69473', + 'date': '2026-02-05', + 'document_set_id': '630300', + 'customer_id': str(customer_id), + 'net_value': str(valor), + 'associated_documents[0][associated_id]': str(invoice_document_id), + 'associated_documents[0][value]': str(valor), + 'payments[0][payment_method_id]': '400878', + 'payments[0][date]': '2026-02-05', + 'payments[0][value]': str(valor), + 'status': '1' +} +r = requests.post('.../receipts/insert/', params={'access_token': token}, data=data) +``` + +### Verificar reconciliação +Antes de criar recibo, verificar `reconciled_value` e `reverse_associated_documents` da factura. + +## Restrições + +- Data mínima documentos: **>= 2025-10-28** (período AT) +- Para facturas antigas: usar data actual no recibo + +## Erros Comuns + +| Erro | Causa | Solução | +|------|-------|---------| +| 403 Forbidden | Token no body | Mover para `params=` | +| 404 Not Found | Case errado ou sem `/` | Verificar camelCase + trailing slash | +| `["12 date >= ..."]` | Data antiga | Usar data actual | +| `["10 associated_id"]` | Factura já reconciliada | Verificar `reconciled_value` | + +## MCP vs API Directa + +O MCP Moloni (`mcp__moloni__*`) gere tokens automaticamente. Para operações pontuais ou scripts batch, usar API directa via SSH no mcp-hub. + +## Sandbox (Desenvolvimento) + +Para testes sem afectar dados reais: https://www.moloni.pt/dev/sandbox/ + +A sandbox fornece um ambiente isolado com dados fictícios para desenvolvimento e testes de integração. + +## Referências + +- **[references/api-reference.md](references/api-reference.md)** - Credenciais, formatos, mapeamento clientes, erros +- **[references/endpoints.md](references/endpoints.md)** - Catálogo completo de endpoints +- **Docs oficiais:** https://www.moloni.pt/dev/endpoints/ +- **Sandbox:** https://www.moloni.pt/dev/sandbox/ + +--- + +## Healing Log + +Registo de erros conhecidos e como evitá-los. Lido automaticamente antes de executar. + +```jsonl +{"date":"","issue":"","fix":"","source":"user|auto"} +``` + +*Adicionar nova linha após cada erro corrigido.* diff --git a/automacao/skills/moloni-api/references/api-reference.md b/automacao/skills/moloni-api/references/api-reference.md new file mode 100644 index 0000000..5a5f7f0 --- /dev/null +++ b/automacao/skills/moloni-api/references/api-reference.md @@ -0,0 +1,301 @@ +# Moloni API v2 - Reference + +## Empresa Descomplicar + +| Campo | Valor | +|-------|-------| +| Company ID | 69473 | +| Empresa | Evidente Despertar, Lda | +| Client ID | evidentedespertar | +| NIF | 516557498 | +| MCP Server | `/opt/moloni/` em mcp-hub | +| Service | `moloni.service` (systemd) | +| .env | `/opt/moloni/.env` | +| Token storage | `/opt/moloni/.moloni/69473/.token_metadata.json` | + +## Sandbox (Desenvolvimento/Testes) + +Para testar integrações sem afectar dados reais: https://www.moloni.pt/dev/sandbox/ + +A sandbox fornece um ambiente isolado com dados fictícios. Usar sempre que: +- Desenvolver novas integrações +- Testar criação/modificação de documentos +- Depurar erros de formato ou validação + +## Autenticacao + +### Password Grant (GET, nao POST!) + +```python +r = requests.get('https://api.moloni.pt/v2/grant/', params={ + 'grant_type': 'password', + 'client_id': 'evidentedespertar', + 'client_secret': 'aa48e86bd574bf81ca2d7f624c8b5de0284fb97d', + 'username': 'contabilidade@descomplicar.pt', + 'password': '6EMVh^RHA)d5k!%s' +}) +token = r.json()['access_token'] +``` + +### Refresh Token + +```python +r = requests.get('https://api.moloni.pt/v2/grant/', params={ + 'grant_type': 'refresh_token', + 'client_id': 'evidentedespertar', + 'client_secret': 'aa48e86bd574bf81ca2d7f624c8b5de0284fb97d', + 'refresh_token': '' +}) +``` + +### Regras de Autenticacao + +- Grant endpoint e **GET** (nao POST) +- Password contem `%s` - em Python usar: `'6EMVh^RHA)d5k!%s'` (string literal, sem f-string) +- Token expira em 3600 segundos (1 hora) +- Refresh token nao expira mas so pode ser usado uma vez + +## Formato das Chamadas API + +### Regra Fundamental + +``` +access_token -> QUERY STRING (params) +dados -> POST BODY (data, form-urlencoded) +``` + +### Exemplo Correcto + +```python +r = requests.post('https://api.moloni.pt/v2/invoices/getAll/', + params={'access_token': token}, # token na query string + data={'company_id': '69473', 'qty': '50'} # dados no body +) +``` + +### Exemplo INCORRECTO (causa 403 Forbidden) + +```python +# ERRADO - token no body causa 403! +r = requests.post('https://api.moloni.pt/v2/invoices/getAll/', + data={'company_id': '69473', 'access_token': token, 'qty': '50'} +) +``` + +## Endpoints Case-Sensitive + +| Correcto (camelCase) | ERRADO (lowercase) | +|---------------------|---------------------| +| `creditNotes/` | `creditnotes/` | +| `invoiceReceipts/` | `invoicereceipts/` | +| `documentSets/` | `documentsets/` | +| `paymentMethods/` | `paymentmethods/` | +| `simplifiedInvoices/` | `simplifiedinvoices/` | +| `debitNotes/` | `debitnotes/` | +| `billsOfLading/` | `billsoflading/` | +| `deliveryNotes/` | `deliverynotes/` | +| `proFormaInvoices/` | `proformainvoices/` | + +Endpoints simples (lowercase OK): `invoices/`, `receipts/`, `customers/`, `products/`, `taxes/` + +Todos os endpoints precisam de trailing slash: `/v2/invoices/getAll/` + +## Arrays Aninhados (Form-Encoded) + +### Formato Correcto + +```python +data = { + 'company_id': '69473', + 'associated_documents[0][associated_id]': '595002190', + 'associated_documents[0][value]': '2361.60', + 'payments[0][payment_method_id]': '400878', + 'payments[0][date]': '2026-02-05', + 'payments[0][value]': '2361.60', +} +``` + +### Multiplos Items + +```python +data = { + 'products[0][product_id]': '123', + 'products[0][qty]': '2', + 'products[0][price]': '50.00', + 'products[1][product_id]': '456', + 'products[1][qty]': '1', + 'products[1][price]': '100.00', +} +``` + +### NUNCA Usar JSON.dumps() + +```python +# ERRADO - Moloni nao aceita JSON strings dentro de form data +data = { + 'associated_documents': json.dumps([{'associated_id': 123, 'value': 50}]) +} +``` + +## Restricoes de Datas + +- Moloni tem data minima para criacao de documentos (periodo de comunicacao AT) +- Actualmente: **>= 2025-10-28** +- Para documentos com datas antigas, usar a data actual no recibo/documento +- Erro retornado: `["12 date >= 2025-10-28"]` + +## Series Documentais + +| ID | Nome | Uso | +|----|------|-----| +| 630300 | D | Serie principal (facturas, recibos, NC) | +| 118898 | (antiga) | Recibos antigos KCCG | + +## Metodos de Pagamento + +| ID | Nome | +|----|------| +| 400868 | Numerario | +| 400873 | Cheque | +| 400878 | Transferencia Bancaria | +| 400883 | Multibanco | +| 1569000 | Paypal | + +## Endpoints por Tipo de Documento + +Cada tipo de documento suporta: `count`, `getAll`, `getOne`, `insert`, `update`, `delete` + +### Facturas (invoices/) + +``` +POST /v2/invoices/getAll/ - Listar (qty, offset, document_set_id, customer_id, year) +POST /v2/invoices/getOne/ - Detalhe (document_id OU document_set_id+number) +POST /v2/invoices/insert/ - Criar +``` + +### Recibos (receipts/) + +``` +POST /v2/receipts/getAll/ - Listar +POST /v2/receipts/getOne/ - Detalhe +POST /v2/receipts/insert/ - Criar (requer: date, document_set_id, customer_id, net_value, associated_documents, payments) +``` + +**Insert fields:** +- `company_id` (int, required) +- `date` (YYYY-MM-DD, required) +- `document_set_id` (int, required) +- `customer_id` (int, required) +- `net_value` (float, required) - valor total do recibo +- `associated_documents[]` - array com `associated_id` e `value` +- `payments[]` - array com `payment_method_id`, `date`, `value` +- `status` (0=rascunho, 1=fechado) +- `notes` (string, opcional) + +### Notas de Credito (creditNotes/) + +``` +POST /v2/creditNotes/getAll/ +POST /v2/creditNotes/getOne/ +POST /v2/creditNotes/insert/ +``` + +### Clientes (customers/) + +``` +POST /v2/customers/getAll/ +POST /v2/customers/getOne/ +POST /v2/customers/getBySearch/ +POST /v2/customers/getByVat/ +``` + +### Produtos (products/) + +``` +POST /v2/products/getAll/ +POST /v2/products/getBySearch/ +POST /v2/products/getByReference/ +``` + +## Codigos de Erro Comuns + +| Codigo | Significado | +|--------|-------------| +| 200 + `{"valid": 1}` | Sucesso | +| 200 + `["12 date >= ..."]` | Data anterior ao periodo AT | +| 200 + `["10 associated_id"]` | Documento associado invalido ou ja reconciliado | +| 200 + `["2 value 0 null"]` | Valor invalido ou em falta | +| 401 | Token expirado ou invalido | +| 403 | App sem permissoes (access_token no body em vez de query string) | +| 404 | Endpoint nao encontrado (verificar case-sensitivity e trailing slash) | + +## Campos de Resposta (Documentos) + +| Campo | Tipo | Descricao | +|-------|------|-----------| +| `document_id` | int | ID unico do documento | +| `number` | int | Numero sequencial na serie | +| `net_value` | float | **Total COM IVA** (Desk total). Para base sem IVA: net_value / 1.23. ATENCAO: nome enganador, NAO e base! | +| `reconciled_value` | float | Valor ja reconciliado/pago | +| `status` | int | 0=rascunho, 1=fechado | +| `customer_id` | int | ID do cliente Moloni | +| `document_set_id` | int | ID da serie documental | +| `associated_documents` | array | Documentos associados (facturas num recibo) | +| `reverse_associated_documents` | array | Documentos que referenciam este (recibos de uma factura) | +| `payments` | array | Pagamentos registados | +| `entity_name` | string | Nome do cliente | +| `entity_vat` | string | NIF do cliente | + +## MCP Tools Disponiveis + +O MCP Moloni expoe todas as operacoes via ferramentas prefixadas `mcp__moloni__moloni_`: + +``` +mcp__moloni__moloni_documents_invoices_getall +mcp__moloni__moloni_documents_invoices_getone +mcp__moloni__moloni_documents_receipts_insert +mcp__moloni__moloni_documents_credit_notes_getall +mcp__moloni__moloni_entities_customers_getall +mcp__moloni__moloni_settings_paymentmethods_getall +mcp__moloni__moloni_settings_documentsets_getall +``` + +**Nota:** O MCP server ja coloca o `access_token` na query string automaticamente. Quando usar via MCP, nao e necessario gerir tokens manualmente. + +## Mapeamento Clientes Moloni-Desk + +| Moloni customer_id | Nome Moloni | Desk client_id | Nome Desk | +|-------------------|-------------|----------------|-----------| +| 75731733 | Missao Pertinente | 10 | MIP | +| 84748539 | KCCG - Karate Clube de Gaia | 2 | KCG | +| 90214681 | IgnitionVortex | 14 | IGV | +| 90360913 | Prestigebrokers | 176 | Prestigebrokers | +| 90861853 | Cristina Pinto Santos Lda | 17 | SNT Sintricare | +| 96914420 | Vasco Miguel Neves, Unipessoal | 21 | Solar FV | +| 97615615 | TECIRRIGATION | 22 | TECIRRIGATION | +| 98881975 | Miguel Carril | 23 | MCR | +| 99321870 | Espiral Senior | 24 | Espiral Senior | +| 99581273 | Alegria Todo o Dia | 25 | Alegria Todo o Dia | +| 100711528 | ROSSANA FERREIRA | 26 | Family Clinic | +| 105780051 | AQUISEVENDE | 28 | AQUISEVENDE | +| 128784439 | Carstuff Artigos Para Carrocaria | 139 | CTF Carstuff | + +## Sincronizacao Desk-Moloni (Estado 2026-02-05) + +| Tipo | Total Serie D | Sincronizados | +|------|--------------|---------------| +| Facturas | 107 | 107 importadas no Desk | +| Notas de Credito | 3 | 3 importadas no Desk | +| Recibos | 112 | 91 existentes + 21 criados | +| Pagamentos | 113 | 110 serie D + 3 serie 118898 | +| PDFs | 220 | 107 FT + 110 RC + 3 NC (330 registos: invoice+customer) | + +Status facturas: +- Paid: 98 | Partially Paid: 2 (D/36, D/84) | Unpaid: 3 (D/98, D/105, D/106) +- Cancelled: 2 (D/56, D/88) | Draft: 2 (D/18, D/66) + +Excluidas da sincronizacao: +- FT D/8, D/56, D/88 - anuladas por notas de credito +- FT D/98, D/105, D/106 - nao cobradas +- FT D/18, D/66 - rascunhos +- FT D/3, D/4, D/5 - recibos na serie 118898 (nao D) diff --git a/automacao/skills/moloni-api/references/endpoints.md b/automacao/skills/moloni-api/references/endpoints.md new file mode 100644 index 0000000..dab2a29 --- /dev/null +++ b/automacao/skills/moloni-api/references/endpoints.md @@ -0,0 +1,332 @@ +# Moloni API - Catalogo Completo de Endpoints + +> Fonte oficial: https://www.moloni.pt/dev/endpoints/ +> Base URL: `https://api.moloni.pt/v2/` +> Todos os endpoints usam POST com `access_token` na query string. +> Trailing slash obrigatorio em todos os endpoints. + +## Account & Profile + +### My Profile (myProfile/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| signup | `myProfile/signup/` | Registar nova conta | +| recoverpassword | `myProfile/recoverpassword/` | Recuperar password | +| updateMe | `myProfile/updateMe/` | Actualizar perfil | +| getMe | `myProfile/getMe/` | Obter dados do perfil | + +## Company + +### Company (companies/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| freeSlug | `companies/freeSlug/` | Verificar slug disponivel | +| getAll | `companies/getAll/` | Listar empresas | +| getOne | `companies/getOne/` | Detalhe de empresa | + +### Subscription (subscription/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getOne | `subscription/getOne/` | Dados da subscricao | + +### Users (users/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getAll | `users/getAll/` | Listar utilizadores | + +## Entities + +### Customers (customers/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getAll | `customers/getAll/` | Listar clientes (qty, offset) | +| getOne | `customers/getOne/` | Detalhe de cliente | +| getBySearch | `customers/getBySearch/` | Pesquisar por texto | +| getByVat | `customers/getByVat/` | Pesquisar por NIF | +| getByNumber | `customers/getByNumber/` | Pesquisar por numero | +| getByEmail | `customers/getByEmail/` | Pesquisar por email | +| getByName | `customers/getByName/` | Pesquisar por nome | +| getNextNumber | `customers/getNextNumber/` | Proximo numero | +| getLastNumber | `customers/getLastNumber/` | Ultimo numero | +| getModifiedSince | `customers/getModifiedSince/` | Alterados desde data | +| count | `customers/count/` | Total de clientes | +| countBySearch | `customers/countBySearch/` | Contar por pesquisa | +| countByVat | `customers/countByVat/` | Contar por NIF | +| countByNumber | `customers/countByNumber/` | Contar por numero | +| countByEmail | `customers/countByEmail/` | Contar por email | +| countByName | `customers/countByName/` | Contar por nome | +| countModifiedSince | `customers/countModifiedSince/` | Contar alterados | +| insert | `customers/insert/` | Criar cliente | +| update | `customers/update/` | Actualizar cliente | +| delete | `customers/delete/` | Eliminar cliente | + +### Customer Alternate Addresses (customerAlternateAddresses/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getAll | `customerAlternateAddresses/getAll/` | Listar moradas | +| insert | `customerAlternateAddresses/insert/` | Criar morada | +| update | `customerAlternateAddresses/update/` | Actualizar morada | +| delete | `customerAlternateAddresses/delete/` | Eliminar morada | + +### Suppliers (suppliers/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `suppliers/count/` | Total fornecedores | +| getAll | `suppliers/getAll/` | Listar fornecedores | +| getOne | `suppliers/getOne/` | Detalhe fornecedor | +| countBySearch | `suppliers/countBySearch/` | Contar por pesquisa | +| getBySearch | `suppliers/getBySearch/` | Pesquisar por texto | +| countByVat | `suppliers/countByVat/` | Contar por NIF | +| getByVat | `suppliers/getByVat/` | Pesquisar por NIF | +| countByNumber | `suppliers/countByNumber/` | Contar por numero | +| getByNumber | `suppliers/getByNumber/` | Pesquisar por numero | +| countByName | `suppliers/countByName/` | Contar por nome | +| getByName | `suppliers/getByName/` | Pesquisar por nome | +| insert | `suppliers/insert/` | Criar fornecedor | +| update | `suppliers/update/` | Actualizar fornecedor | +| delete | `suppliers/delete/` | Eliminar fornecedor | + +### Salesmen (salesmen/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `salesmen/count/` | Total vendedores | +| getAll | `salesmen/getAll/` | Listar vendedores | +| getOne | `salesmen/getOne/` | Detalhe vendedor | +| countBySearch/getBySearch | Pesquisar por texto | +| countByVat/getByVat | Pesquisar por NIF | +| countByNumber/getByNumber | Pesquisar por numero | +| countByName/getByName | Pesquisar por nome | +| countByEmail/getByEmail | Pesquisar por email | +| insert | `salesmen/insert/` | Criar vendedor | +| update | `salesmen/update/` | Actualizar vendedor | +| delete | `salesmen/delete/` | Eliminar vendedor | + +## Products + +### Products (products/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `products/count/` | Total produtos | +| getAll | `products/getAll/` | Listar produtos | +| getOne | `products/getOne/` | Detalhe produto | +| countBySearch/getBySearch | Pesquisar por texto | +| countByName/getByName | Pesquisar por nome | +| countByReference/getByReference | Pesquisar por referencia | +| countByEAN/getByEAN | Pesquisar por codigo barras | +| countModifiedSince/getModifiedSince | Alterados desde data | +| getLastCostPrice | `products/getLastCostPrice/` | Ultimo preco de custo | +| getNextReference | `products/getNextReference/` | Proxima referencia | +| insert | `products/insert/` | Criar produto | +| update | `products/update/` | Actualizar produto | +| delete | `products/delete/` | Eliminar produto | + +### Product Categories (productCategories/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getOne | `productCategories/getOne/` | Detalhe categoria | +| getAll | `productCategories/getAll/` | Listar categorias | +| insert | `productCategories/insert/` | Criar categoria | +| update | `productCategories/update/` | Actualizar categoria | +| delete | `productCategories/delete/` | Eliminar categoria | + +### Product Stocks (productStocks/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getAll | `productStocks/getAll/` | Listar stocks | +| insert | `productStocks/insert/` | Criar stock | +| update | `productStocks/update/` | Actualizar stock | +| delete | `productStocks/delete/` | Eliminar stock | +| moveToWarehouse | `productStocks/moveToWarehouse/` | Mover entre armazens | + +### Price Classes (priceClasses/) +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getAll | `priceClasses/getAll/` | Listar classes preco | +| insert | `priceClasses/insert/` | Criar classe preco | +| update | `priceClasses/update/` | Actualizar classe preco | +| delete | `priceClasses/delete/` | Eliminar classe preco | + +## Documents + +> **ATENCAO Case-Sensitivity!** Endpoints com multiplas palavras usam camelCase. + +### Facturas (invoices/) - lowercase OK +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `invoices/count/` | Total facturas | +| getAll | `invoices/getAll/` | Listar facturas | +| getOne | `invoices/getOne/` | Detalhe factura | +| insert | `invoices/insert/` | Criar factura | +| update | `invoices/update/` | Actualizar factura | +| delete | `invoices/delete/` | Eliminar factura | +| generateMbReference | `invoices/generateMbReference/` | Gerar ref MB | + +### Recibos (receipts/) - lowercase OK +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `receipts/count/` | Total recibos | +| getAll | `receipts/getAll/` | Listar recibos | +| getOne | `receipts/getOne/` | Detalhe recibo | +| insert | `receipts/insert/` | Criar recibo | +| update | `receipts/update/` | Actualizar recibo | +| delete | `receipts/delete/` | Eliminar recibo | + +### Notas de Credito (creditNotes/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `creditNotes/count/` | Total notas credito | +| getAll | `creditNotes/getAll/` | Listar notas credito | +| getOne | `creditNotes/getOne/` | Detalhe nota credito | +| insert | `creditNotes/insert/` | Criar nota credito | +| update | `creditNotes/update/` | Actualizar nota credito | +| delete | `creditNotes/delete/` | Eliminar nota credito | + +### Notas de Debito (debitNotes/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `debitNotes/count/` | Total notas debito | +| getAll | `debitNotes/getAll/` | Listar notas debito | +| getOne | `debitNotes/getOne/` | Detalhe nota debito | +| insert | `debitNotes/insert/` | Criar nota debito | +| update | `debitNotes/update/` | Actualizar nota debito | +| delete | `debitNotes/delete/` | Eliminar nota debito | + +### Facturas Simplificadas (simplifiedInvoices/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `simplifiedInvoices/count/` | Total | +| getAll | `simplifiedInvoices/getAll/` | Listar | +| getOne | `simplifiedInvoices/getOne/` | Detalhe | +| insert | `simplifiedInvoices/insert/` | Criar | +| update | `simplifiedInvoices/update/` | Actualizar | +| delete | `simplifiedInvoices/delete/` | Eliminar | +| generateMbReference | `simplifiedInvoices/generateMbReference/` | Gerar ref MB | + +### Facturas-Recibo (invoiceReceipts/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count | `invoiceReceipts/count/` | Total | +| getAll | `invoiceReceipts/getAll/` | Listar | +| getOne | `invoiceReceipts/getOne/` | Detalhe | +| insert | `invoiceReceipts/insert/` | Criar | +| update | `invoiceReceipts/update/` | Actualizar | +| delete | `invoiceReceipts/delete/` | Eliminar | +| generateMbReference | `invoiceReceipts/generateMbReference/` | Gerar ref MB | + +### Guias de Transporte (billsOfLading/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count/getAll/getOne/insert/update/delete | Operacoes standard | +| setTransportCode | `billsOfLading/setTransportCode/` | Definir codigo transporte AT | + +### Guias de Remessa (deliveryNotes/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| count/getAll/getOne/insert/update/delete | Operacoes standard | +| setTransportCode | `deliveryNotes/setTransportCode/` | Codigo transporte AT | + +### Facturas de Activos Proprios (ownAssetsInvoices/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Facturas Pro Forma (proFormaInvoices/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Notas de Devolucao (devolutionNotes/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Encomendas (purchaseOrders/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Notas de Consignacao (consignmentNotes/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Notas de Retorno (returnNotes/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Guias de Movimentacao (movementOfGoods/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +### Guias de Transporte (transportGuide/) - CAMELCASE! +Standard + setTransportCode + +### Orcamentos (budget/) - lowercase OK +Standard: count/getAll/getOne/insert/update/delete + +### Documentos Internos (internalDocuments/) - CAMELCASE! +Standard: count/getAll/getOne/insert/update/delete + +## Settings + +### Contas Bancarias (bankAccounts/) - CAMELCASE! +Standard: getAll/insert/update/delete + +### Codigos CAE (caeCodes/) - CAMELCASE! +Standard: getAll/insert/update/delete + +### Metodos de Pagamento (paymentMethods/) - CAMELCASE! +Standard: getAll/insert/update/delete + +### Prazos de Vencimento (maturityDates/) - CAMELCASE! +Standard + countModifiedSince/getModifiedSince + +### Metodos de Entrega (deliveryMethods/) - CAMELCASE! +Standard: getAll/insert/update/delete + +### Veiculos (vehicles/) - lowercase OK +Standard + getBySearch + +### Deducoes (deductions/) - lowercase OK +Standard: getAll/insert/update/delete + +### Impostos (taxes/) - lowercase OK +Standard: getAll/insert/update/delete + +### Unidades de Medida (measurementUnits/) - CAMELCASE! +Standard: getAll/insert/update/delete + +### Templates de Identificacao (identificationTemplates/) - CAMELCASE! +Standard: getAll/insert/update/delete + +### Series Documentais (documentSets/) - CAMELCASE! +| Metodo | Endpoint | Descricao | +|--------|----------|-----------| +| getAll | `documentSets/getAll/` | Listar series | +| insert | `documentSets/insert/` | Criar serie | +| update | `documentSets/update/` | Actualizar serie | +| delete | `documentSets/delete/` | Eliminar serie | +| countModifiedSince | `documentSets/countModifiedSince/` | Contar alterados | +| getModifiedSince | `documentSets/getModifiedSince/` | Listar alterados | +| atInsertCode | `documentSets/atInsertCode/` | Inserir codigo AT | +| atInsertCodeBulk | `documentSets/atInsertCodeBulk/` | Inserir codigos AT bulk | + +### Armazens (warehouses/) - lowercase OK +Standard + countModifiedSince + +### Propriedades de Produtos (productProperties/) - CAMELCASE! +Standard + countModifiedSince/getModifiedSince + +## Global Data + +### Countries (countries/) +`countries/getAll/` - Lista de paises (Portugal country_id: 1) + +### Fiscal Zones (fiscalZones/) - CAMELCASE! +`fiscalZones/getAll/` - Zonas fiscais + +### Languages (languages/) +`languages/getAll/`, `languages/getOne/` + +### Currencies (currencies/) +`currencies/getAll/`, `currencies/getOne/` (EUR = id 1) + +### Document Models (documentModels/) - CAMELCASE! +`documentModels/getAll/` - Modelos de documento + +### Tax Exemptions (taxExemptions/) - CAMELCASE! +`taxExemptions/getAll/` - Lista de isencoes de imposto + +### Currency Exchange (currencyExchange/) - CAMELCASE! +`currencyExchange/getAll/`, `currencyExchange/getOne/` - Taxas de cambio + +### Multibanco Gateways (multibancoGateways/) - CAMELCASE! +`multibancoGateways/getAll/` - Gateways MB disponiveis diff --git a/automacao/skills/n8n/SKILL.md b/automacao/skills/n8n/SKILL.md new file mode 100644 index 0000000..5e18f8f --- /dev/null +++ b/automacao/skills/n8n/SKILL.md @@ -0,0 +1,144 @@ +--- +name: n8n +description: Meta-skill n8n para criação e gestão de workflows na instância automator.descomplicar.pt. Cobre health check, webhooks, schedule (cron), sync de dados, notify (Slack/email/SMS) e chatbots/AI agents (LangChain/RAG). Triggers — n8n, workflow, automação, webhook, schedule, cron, sync, notify, alerta, slack, chatbot, ai agent, langchain, rag, automator, health check n8n. +layer: wiki +--- + +# /n8n - Meta-skill n8n + +Skill unificada para a instância n8n Descomplicar (`https://automator.descomplicar.pt`, MCP `mcp__n8n__*`). Substitui as antigas n8n-chatbot, n8n-health, n8n-notify, n8n-schedule, n8n-sync, n8n-webhook. + +## Contexto NotebookLM (sempre antes de executar) + +| Notebook | ID | +|----------|-----| +| n8n Deep Research | `f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1` | + +``` +mcp__notebooklm__notebook_query({ notebook_id: "f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1", query: "" }) +``` + +## Workflow obrigatório (qualquer criação) + +``` +1. mcp__n8n__n8n_health_check() +2. mcp__n8n__search_templates({ task: "" }) +3. Se template adequado -> mcp__n8n__n8n_deploy_template() +4. Caso contrário, criar do zero seguindo a secção apropriada abaixo +``` + +--- + +## 1. Health (diagnóstico) + +``` +/n8n health # status rápido +/n8n health verbose # diagnóstico completo +``` + +```js +mcp__n8n__n8n_health_check({ mode: "status" }) +mcp__n8n__n8n_health_check({ mode: "diagnostic", verbose: true }) +``` + +Output esperado: status (OK/ERRO), URL, versão MCP, response time, workflows activos. + +Erros comuns: Connection refused (n8n offline), 401 (API key inválida — regenerar), timeout (rede). Diagnóstico manual: +```bash +curl -I https://automator.descomplicar.pt +curl -H "X-N8N-API-KEY: $KEY" https://automator.descomplicar.pt/api/v1/workflows +tail ~/.claude/logs/mcp-n8n.log +``` + +--- + +## 2. Webhook + +Receber dados de sistemas externos. + +``` +/n8n webhook create +/n8n webhook list +/n8n webhook test +``` + +```js +mcp__n8n__get_node({ nodeType: "nodes-base.webhook", detail: "standard", includeExamples: true }) +mcp__n8n__validate_node({ nodeType: "nodes-base.webhook", config: { httpMethod: "POST", path: "meu-webhook", responseMode: "onReceived" }, mode: "minimal" }) +mcp__n8n__n8n_create_workflow({ name: "Webhook - X", nodes: [...], connections: {...}, active: true }) +``` + +Parâmetros: `httpMethod` (GET/POST/PUT/DELETE, default POST), `path` (obrigatório), `authentication` (none/basicAuth/headerAuth), `responseMode` (onReceived/lastNode). + +URLs: produção `https://automator.descomplicar.pt/webhook/` | teste `https://automator.descomplicar.pt/webhook-test/`. + +Nodes processamento: `nodes-base.set`, `nodes-base.if`, `nodes-base.code`, `nodes-base.httpRequest`. + +Teste: +```js +mcp__n8n__n8n_test_workflow({ workflowId: "wf-xxx", inputData: { body: {test:"data"}, headers: {"Content-Type":"application/json"} } }) +``` +```bash +curl -X POST https://automator.descomplicar.pt/webhook/meu-webhook -H "Content-Type: application/json" -d '{"test":"data"}' +``` + +Troubleshooting: 404 (workflow não activo), 401 (auth), dados não chegam (responseMode). + +--- + +## 3. Schedule (cron) + +Workflows com execução agendada. + +``` +/n8n schedule create +/n8n schedule list +/n8n schedule disable +``` + +Cron comuns: `0 9 * * *` (diário 9h), `0 9 * * 1-5` (Seg-Sex 9h), `0 */2 * * *` (cada 2h), `*/15 * * * *` (15min), `0 0 1 * *` (dia 1), `0 3 * * 0` (domingos 3h). + +```js +mcp__n8n__validate_node({ + nodeType: "nodes-base.scheduleTrigger", + config: { rule: { interval: [{ field: "cronExpression", expression: "0 9 * * 1-5" }] }, options: { timezone: "Europe/Lisbon" } }, + mode: "minimal" +}) +``` + +Gestão: +```js +mcp__n8n__n8n_update_partial_workflow({ id: "wf-xxx", operations: [{ type: "deactivateWorkflow" }] }) +mcp__n8n__n8n_update_partial_workflow({ id: "wf-xxx", operations: [{ type: "activateWorkflow" }] }) +mcp__n8n__n8n_executions({ workflowId: "wf-xxx", limit: 10, status: "all" }) +``` + +Exemplos: relatório diário (Schedule -> Postgres -> Set -> Email), backup semanal (Schedule -> SSH -> IF -> Slack), limpeza logs. + +Troubleshooting: não executa (workflow inactivo), hora errada (timezone), duplicado (múltiplos triggers). + +--- + +## 4. Sync (sincronização de dados) + +``` +/n8n sync create +/n8n sync list +/n8n sync status +``` + +Padrões: One-Way (origem -> transform -> destino), Two-Way (com resolução conflitos), Hub-and-Spoke. + +Nodes: +- APIs: `nodes-base.httpRequest`, `nodes-base.webhook` +- BD: `nodes-base.postgres`, `nodes-base.mySql`, `nodes-base.mongoDb` +- Ficheiros: `nodes-base.googleSheets`, `nodes-base.spreadsheetFile`, `nodes-base.ftp` + +Estratégias: Full Sync, Incremental (updated_at), Delta (hashes). + +Upsert: +```js +{ nodeType: "nodes-base.postgres", config: { operation: "upsert", table: "clientes", columns: "email,nome,empresa", conflictColumns: "email" } } +``` + +Erros: retry (`{ options: { retry: { maxRetries: 3, retryInterval: 1000 } } }`), D \ No newline at end of file