{
  "name": "NEX Telecom | Fechamento Autom\u00e1tico Inadimpl\u00eancia",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 10
            }
          ]
        }
      },
      "id": "schedule-trigger",
      "name": "A cada 10 min",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        400,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.nextelecom.hubsoft.com.br/oauth/token",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"client_id\": \"70\",\n  \"client_secret\": \"Nh4YkbOzDP7aU1UueabOP9QiGJj2XpoTRTvinZGY\",\n  \"username\": \"pedro@crescentiagroup.com.br\",\n  \"password\": \"Figueiredo@26#\",\n  \"grant_type\": \"password\"\n}",
        "options": {}
      },
      "id": "auth-hubsoft",
      "name": "Autenticar Hubsoft",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        640,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// ============================================================\n// BUSCAR TODOS OS ATENDIMENTOS DO TIPO CORRETO COM PAGINA\u00c7\u00c3O\n// ============================================================\n// Endpoint: /api/v1/integracao/atendimento/todos\n// tipo_atendimento=391 \u2192 TESTE - AUTOMA\u00c7\u00c3O COBRAN\u00c7A POR INADIMPLENCIA (CLISP + CRC)\n// status_atendimento=2 \u2192 Aguardando An\u00e1lise\n// Sem rela\u00e7\u00f5es extras (leve e r\u00e1pido)\n// ============================================================\n\nconst token = $input.first().json.access_token;\nconst hoje = new Date().toISOString().split('T')[0];\n\n// Data inicio: 6 meses atr\u00e1s (pega tudo que pode estar aberto)\nconst d = new Date();\nd.setMonth(d.getMonth() - 6);\nconst dataInicio = d.toISOString().split('T')[0];\n\nreturn [{ json: {\n  token,\n  dataInicio,\n  dataFim: hoje,\n  pagina: 0\n} }];"
      },
      "id": "preparar-busca",
      "name": "Preparar Busca",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        300
      ]
    },
    {
      "parameters": {
        "url": "=https://api.nextelecom.hubsoft.com.br/api/v1/integracao/atendimento/todos?pagina={{ $json.pagina }}&itens_por_pagina=500&data_inicio={{ $json.dataInicio }}&data_fim={{ $json.dataFim }}&tipo_atendimento=391&status_atendimento=2&relacoes=cliente_servico",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.token }}"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          }
        }
      },
      "id": "buscar-atendimentos",
      "name": "Buscar Atendimentos Cobran\u00e7a",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1120,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// ============================================================\n// EXTRAIR ATENDIMENTOS + id_cliente_servico\n// ============================================================\nconst resp = $input.first().json;\nconst token = $('Preparar Busca').first().json.token;\nconst atendimentos = resp.atendimentos || [];\n\nif (atendimentos.length === 0) return [];\n\nreturn atendimentos.map(a => {\n  const cs = a.cliente_servico || {};\n  const cl = cs.cliente || {};\n  return {\n    json: {\n      id_atendimento: a.id_atendimento,\n      protocolo: a.protocolo,\n      id_cliente_servico: a.id_cliente_servico,\n      codigo_cliente: cl.codigo_cliente || null,\n      nome_cliente: cl.nome_razaosocial || cl.display || 'Desconhecido',\n      token\n    }\n  };\n});"
      },
      "id": "extrair-dados",
      "name": "Extrair Dados",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1360,
        300
      ]
    },
    {
      "parameters": {
        "options": {
          "reset": false
        }
      },
      "id": "loop-atendimentos",
      "name": "Loop Atendimentos",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1600,
        300
      ]
    },
    {
      "parameters": {
        "url": "=https://api.nextelecom.hubsoft.com.br/api/v1/integracao/cliente/financeiro?busca=id_cliente_servico&termo_busca={{ $json.id_cliente_servico }}&apenas_pendente=sim",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.token }}"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          }
        }
      },
      "id": "consultar-financeiro",
      "name": "Consultar Financeiro",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1840,
        480
      ]
    },
    {
      "parameters": {
        "jsCode": "// ============================================================\n// VERIFICAR PEND\u00caNCIAS FINANCEIRAS\n// ============================================================\n// Regra: so conta como pendencia se a fatura JA VENCEU.\n// Fatura com vencimento futuro (ex: 20/04 e hoje e 17/04)\n// NAO e pendencia \u2014 cliente ainda tem tempo de pagar.\n// ============================================================\nconst faturas = $input.first().json.faturas || [];\nconst prev = $('Loop Atendimentos').first().json;\nconst hoje = new Date();\nhoje.setHours(0, 0, 0, 0);\n\n// Filtrar apenas faturas VENCIDAS (data_vencimento < hoje)\nconst vencidas = faturas.filter(f => {\n  if (f.quitado) return false;\n  const partes = (f.data_vencimento || '').split('/');\n  if (partes.length !== 3) return false;\n  const venc = new Date(partes[2], partes[1] - 1, partes[0]);\n  return venc < hoje;\n});\n\nif (vencidas.length > 0) {\n  return [{ json: {\n    acao: 'MANTER_ABERTO',\n    motivo: vencidas.length + ' fatura(s) vencida(s)',\n    id_atendimento: prev.id_atendimento,\n    id_cliente_servico: prev.id_cliente_servico,\n    codigo_cliente: prev.codigo_cliente,\n    nome_cliente: prev.nome_cliente,\n    token: prev.token\n  } }];\n}\n\nreturn [{ json: {\n  acao: 'FECHAR',\n  motivo: 'Sem faturas vencidas',\n  id_atendimento: prev.id_atendimento,\n  id_cliente_servico: prev.id_cliente_servico,\n  codigo_cliente: prev.codigo_cliente,\n  nome_cliente: prev.nome_cliente,\n  token: prev.token\n} }];"
      },
      "id": "verificar-pendencias",
      "name": "Verificar Pend\u00eancias",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2080,
        480
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "deve-fechar",
              "leftValue": "={{ $json.acao }}",
              "rightValue": "FECHAR",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-deve-fechar",
      "name": "Deve Fechar?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2320,
        480
      ]
    },
    {
      "parameters": {
        "method": "PUT",
        "url": "=https://api.nextelecom.hubsoft.com.br/api/v1/integracao/atendimento/{{ $json.id_atendimento }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.token }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"fechar_atendimento\": true,\n  \"parametros_fechamento\": {\n    \"descricao_fechamento\": \"TESTE - (CLIESP + CRC) - FINALIZA\u00c7\u00c3O AUTOMATICA POR PAGAMENTO DE FATURA EM ATRASO\"\n  }\n}",
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          }
        }
      },
      "id": "fechar-atendimento",
      "name": "Fechar Atendimento",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2560,
        360
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "1",
              "name": "resultado",
              "value": "=MANTIDO ABERTO | {{ $json.nome_cliente }} ({{ $json.codigo_cliente }}) | Atendimento #{{ $json.id_atendimento }} | {{ $json.motivo }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "log-mantido",
      "name": "Log: Mantido Aberto",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2560,
        600
      ]
    },
    {
      "parameters": {
        "amount": 1
      },
      "id": "wait-rate-limit",
      "name": "Wait 1s",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        2800,
        480
      ]
    }
  ],
  "connections": {
    "A cada 10 min": {
      "main": [
        [
          {
            "node": "Autenticar Hubsoft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Autenticar Hubsoft": {
      "main": [
        [
          {
            "node": "Preparar Busca",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar Busca": {
      "main": [
        [
          {
            "node": "Buscar Atendimentos Cobran\u00e7a",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar Atendimentos Cobran\u00e7a": {
      "main": [
        [
          {
            "node": "Extrair Dados",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extrair Dados": {
      "main": [
        [
          {
            "node": "Loop Atendimentos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Atendimentos": {
      "main": [
        [],
        [
          {
            "node": "Consultar Financeiro",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Consultar Financeiro": {
      "main": [
        [
          {
            "node": "Verificar Pend\u00eancias",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificar Pend\u00eancias": {
      "main": [
        [
          {
            "node": "Deve Fechar?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Deve Fechar?": {
      "main": [
        [
          {
            "node": "Fechar Atendimento",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log: Mantido Aberto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fechar Atendimento": {
      "main": [
        [
          {
            "node": "Wait 1s",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log: Mantido Aberto": {
      "main": [
        [
          {
            "node": "Wait 1s",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait 1s": {
      "main": [
        [
          {
            "node": "Loop Atendimentos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Sao_Paulo"
  },
  "versionId": "hubsoft-v2",
  "tags": []
}