{
  "name": "Projeto IAIE",
  "nodes": [
    {
      "parameters": {
        "jsCode": "// 1. Aceder \u00e0 lista de resultados que vem do n\u00f3 anterior (SAP)\n// A estrutura baseia-se na imagem: body -> d -> results\nconst outputSAP = $input.first().json.body.d.results;\n\n// 2. Mapear (transformar) cada cliente para o novo formato\nconst dadosFormatados = outputSAP.map(cliente => {\n  return {\n    json: {\n      Nome: cliente.FirstName,\n      Apelido: cliente.LastName,\n      NIF: cliente.SearchTerm1,\n      Pais: cliente.SearchTerm2\n    }\n  };\n});\n\nreturn dadosFormatados;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        192,
        176
      ],
      "id": "42d0aa66-f2c8-4a83-ab43-f507fe0fffa5",
      "name": "Transformar Dados"
    },
    {
      "parameters": {
        "path": "obter-clientes",
        "responseMode": "responseNode",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        176
      ],
      "id": "af27eeab-0788-417b-a1d2-be7eb3d507de",
      "name": "Obter Clientes"
    },
    {
      "parameters": {
        "path": "login",
        "responseMode": "responseNode",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        400
      ],
      "id": "fae46a7e-64dc-44a5-87bc-d4867f6f2a01",
      "name": "Login"
    },
    {
      "parameters": {
        "url": "https://s20.gb.ucc.cit.tum.de/sap/opu/odata/sap/MD_BUSINESSPARTNER_SRV/C_BusinessPartner",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "sap-client",
              "value": "305"
            },
            {
              "name": "$format",
              "value": "json"
            },
            {
              "name": "$filter",
              "value": "CreatedByUser eq 'LEARN-696'"
            },
            {
              "name": "$select",
              "value": "BusinessPartnerCategory,FirstName,LastName,SearchTerm1,SearchTerm2"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-CSRF-Token",
              "value": "Fetch"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "fullResponse": true
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -16,
        176
      ],
      "id": "c61206ed-cac9-4d95-af27-2fea9dc4977c",
      "name": "Get BP",
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "url": "https://s20.gb.ucc.cit.tum.de/sap/opu/odata/sap/MD_BUSINESSPARTNER_SRV/C_BusinessPartner",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "sap-client",
              "value": "305"
            },
            {
              "name": "$format",
              "value": "json"
            },
            {
              "name": "$filter",
              "value": "CreatedByUser eq 'LEARN-696'"
            },
            {
              "name": "$select",
              "value": "BusinessPartnerCategory,FirstName,LastName,SearchTerm1,SearchTerm2"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-CSRF-Token",
              "value": "Fetch"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "fullResponse": true
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -16,
        400
      ],
      "id": "1ab8c956-7996-4dab-b8b9-c62ce86feb7a",
      "name": "Get BP1",
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// 1. Capturar o Input do utilizador (NIF)\n// Nota: Garante que o n\u00f3 anterior se chama 'Webhook' ou ajusta o nome abaixo\nlet nifInput = \"\";\ntry {\n    // Tenta ir buscar ao query (GET)\n    nifInput = $('Login').first().json.query.nif;\n} catch (e) {\n    // Se falhar, tenta ir buscar ao body (POST) ou define vazio\n    nifInput = \"\";\n}\n\n// 2. Capturar a resposta do SAP (N\u00f3 anterior) de forma SEGURA\nconst dadosSAP = $input.first().json;\nlet listaClientes = [];\n\n// Verifica\u00e7\u00e3o de seguran\u00e7a: S\u00f3 tentamos ler se a estrutura existir\nif (dadosSAP.body && dadosSAP.body.d && dadosSAP.body.d.results) {\n    listaClientes = dadosSAP.body.d.results;\n} else if (Array.isArray(dadosSAP)) {\n    // Caso o SAP devolva logo um array direto\n    listaClientes = dadosSAP;\n}\n\n// 3. L\u00f3gica de Procura\nlet clienteEncontrado = null;\n\nif (nifInput && listaClientes.length > 0) {\n    clienteEncontrado = listaClientes.find(cliente => cliente.SearchTerm1 == nifInput);\n}\n\n// 4. Preparar a Resposta\nif (clienteEncontrado) {\n  return {\n    json: {\n      existe: true,\n      status: \"Sucesso\",\n      \n      // Mapeamento IMPORTANTE (min\u00fasculas para o site ler bem)\n      nome: clienteEncontrado.FirstName,\n      apelido: clienteEncontrado.LastName,\n      pais: clienteEncontrado.SearchTerm2,\n      nif: clienteEncontrado.SearchTerm1,\n      \n      // Debug (opcional)\n      mensagem: \"Cliente encontrado.\"\n    }\n  };\n} else {\n  return {\n    json: {\n      existe: false,\n      status: \"Erro\",\n      mensagem: \"Conta n\u00e3o encontrada para o NIF: \" + nifInput\n    }\n  };\n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        192,
        400
      ],
      "id": "d0dda4cf-5211-4e10-b7a5-1d6349e28758",
      "name": "Verificar Cliente"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "7db01592-2cc3-4fa1-9a86-cc48f8214699",
              "leftValue": "={{ $json.existe }}",
              "rightValue": "=True",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        400,
        400
      ],
      "id": "e9b1ca6c-a91b-4a20-8a91-339b29e0943b",
      "name": "If"
    },
    {
      "parameters": {
        "respondWith": "allIncomingItems",
        "options": {
          "responseCode": 200,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        400,
        176
      ],
      "id": "b9f1cb2b-2863-449a-8b5b-e64941caded8",
      "name": "Clientes Obtidos"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={\n  \"status\": \"Sucesso\", \"cliente\": \"{{ $json.nome }} {{ $json.apelido }}\"\n}",
        "options": {
          "responseCode": 200,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        656,
        320
      ],
      "id": "5b2e00fc-7202-4a3a-ad1a-6317d7d78825",
      "name": "Conta Existe"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n\"status\": \"Erro\", \"mensagem\": \"NIF n\u00e3o encontrado\"\n}",
        "options": {
          "responseCode": 400,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        656,
        480
      ],
      "id": "edae15c2-5bd6-47d3-bf01-62363ecd949a",
      "name": "Conta nao existe",
      "alwaysOutputData": false
    },
    {
      "parameters": {
        "url": "https://s20.gb.ucc.cit.tum.de/sap/opu/odata/sap/MD_BUSINESSPARTNER_SRV/C_BusinessPartner",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "sap-client",
              "value": "305"
            },
            {
              "name": "$format",
              "value": "json"
            },
            {
              "name": "$filter",
              "value": "CreatedByUser eq 'LEARN-696'"
            },
            {
              "name": "$select",
              "value": "BusinessPartnerCategory,FirstName,LastName,SearchTerm1,SearchTerm2"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-CSRF-Token",
              "value": "Fetch"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "fullResponse": true
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -16,
        720
      ],
      "id": "4e0681bc-fda4-448c-9e65-92167095ede8",
      "name": "Get BP2",
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "2bb9e39d-5925-43f2-aa8b-af9ed6d781d2",
              "leftValue": "={{ $json.jaExiste }}",
              "rightValue": "=True",
              "operator": {
                "type": "boolean",
                "operation": "exists",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        400,
        720
      ],
      "id": "b6d3fa2a-7f71-4d39-beb6-d43b0af861d2",
      "name": "If1"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n\"status\": \"Erro\", \"mensagem\": \"Conta j\u00e1 existe\"\n}",
        "options": {
          "responseCode": 400
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        656,
        800
      ],
      "id": "c83f76df-8cca-405e-b441-64854a6e9c51",
      "name": "Conta j\u00e1 Existe"
    },
    {
      "parameters": {
        "url": "https://s20.gb.ucc.cit.tum.de/sap/opu/odata/sap/MD_BUSINESSPARTNER_SRV/C_BusinessPartner",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "sap-client",
              "value": "305"
            },
            {
              "name": "$format",
              "value": "json"
            },
            {
              "name": "$filter",
              "value": "CreatedByUser eq 'LEARN-696'"
            },
            {
              "name": "$select",
              "value": "BusinessPartnerCategory,FirstName,LastName,SearchTerm1,SearchTerm2"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-CSRF-Token",
              "value": "Fetch"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "fullResponse": true
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        656,
        656
      ],
      "id": "d3e7e758-0be1-4eb5-a16c-ba934c4281e7",
      "name": "Get BP3",
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "path": "criar-conta",
        "responseMode": "responseNode",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        720
      ],
      "id": "b66331d5-352b-49a4-ba79-01e157307365",
      "name": "Criar Conta"
    },
    {
      "parameters": {
        "jsCode": "// 1. Capturar os dados que vieram do Webhook \"Criar Conta\"\n// (Mant\u00e9m-se igual, pois est\u00e1s a chamar pelo nome do n\u00f3)\nconst novoUser = $('Criar Conta').first().json.query;\n\nconst novoNIF = novoUser.nif; \nconst novoNome = novoUser.nome;\nconst novoApelido = novoUser.apelido;\nconst novoPais = novoUser.pais;\n\n// 2. Capturar a lista atual de clientes do SAP (do n\u00f3 anterior)\n// CORRE\u00c7\u00c3O AQUI: Troc\u00e1mos 'items[0]' por '$input.first()'\nconst listaExistente = $input.first().json.body.d.results;\n\n// 3. Verificar se o NIF j\u00e1 existe na lista\n// (Certifica-te que SearchTerm1 \u00e9 exatamente onde guardas o NIF no SAP)\nconst existe = listaExistente.some(cliente => cliente.SearchTerm1 === novoNIF);\n\n// 4. Preparar os dados para o pr\u00f3ximo passo\nreturn {\n  json: {\n    jaExiste: existe,\n    dadosParaCriar: {\n      FirstName: novoNome,\n      LastName: novoApelido,\n      SearchTerm1: novoNIF,\n      SearchTerm2: novoPais,\n      BusinessPartnerCategory: \"1\"\n    }\n  }\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        192,
        720
      ],
      "id": "3616ae3c-4c1e-4d6e-907a-dc192b9064f6",
      "name": "Verificar Conta"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"status\": \"Sucesso\", \"mensagem\": \"A conta foi criada\"\n}",
        "options": {
          "responseCode": 200,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        1104,
        656
      ],
      "id": "f959c8e4-c8dc-4d2e-8a2d-ee09f3601c2d",
      "name": "Conta Criada"
    },
    {
      "parameters": {
        "respondWith": "allIncomingItems",
        "options": {
          "responseCode": 200,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        512,
        976
      ],
      "id": "68bbdab8-14a6-4d16-8837-ca24f23e8e02",
      "name": "Respond to Webhook1"
    },
    {
      "parameters": {
        "path": "carregar-produtos",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        976
      ],
      "id": "6dce3faf-aa71-4fa6-a734-c974e425d50f",
      "name": "Carregar Produtos",
      "executeOnce": false
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/products/getAll/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            }
          ]
        },
        "options": {
          "response": {
            "response": {}
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        32,
        976
      ],
      "id": "17a29330-8bf3-4914-a0c1-cc384a10491d",
      "name": "Obter Produtos"
    },
    {
      "parameters": {
        "jsCode": "// 1. Receber TODOS os itens que vieram do n\u00f3 anterior\n// Usamos o map para extrair a parte 'json' de cada item\nconst todosOsProdutos = $input.all().map(item => item.json);\n\n// 2. Lista de IDs a ignorar\nconst produtosAIgnorar = [217084858, 217084863];\n\n// 3. Processar a lista\nconst produtosLimpos = todosOsProdutos\n  .filter(p => {\n    // FILTRO\n    // Verifica se p.product_id existe antes de comparar\n    if (!p.product_id) return false;\n    \n    if (produtosAIgnorar.includes(p.product_id)) return false;\n    if (p.name && p.name.includes(\"Servi\u00e7o ou artigo exemplo\")) return false;\n    return true;\n  })\n  .map(p => {\n    // TRANSFORMA\u00c7\u00c3O\n    // Garante que o nome existe para n\u00e3o dar erro no split\n    const nomeOriginal = p.name || \"Produto Sem Nome\";\n    const partesNome = nomeOriginal.split('|').map(s => s.trim());\n    \n    const nomeProduto = partesNome[0] || nomeOriginal;\n    const corProduto = partesNome[1] || \"N/A\";\n    const tamanhoProduto = partesNome[2] || \"\u00danico\";\n    \n    // Tenta ir buscar o nome da categoria, protege contra falhas se for null\n    const nomeCategoria = (p.category && p.category.name) ? p.category.name : \"Sem Categoria\";\n\n    return {\n      json: {\n        id: p.product_id,\n        Nome: nomeProduto,\n        Cor: corProduto,\n        Tamanho: tamanhoProduto,\n        Categoria: nomeCategoria, \n        Descricao: p.summary,\n        Referencia: p.reference,\n        Preco: p.price,\n        Stock: p.stock\n      }\n    };\n  });\n\n// 4. Devolver os dados limpos\nreturn produtosLimpos;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        976
      ],
      "id": "0c4c90ba-5fd9-4812-981e-a55446052d94",
      "name": "Formatar Dados"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://s20.gb.ucc.cit.tum.de/sap/opu/odata/sap/MD_BUSINESSPARTNER_SRV/C_BusinessPartner",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "sap-client",
              "value": "305"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-CSRF-Token",
              "value": "={{ $json.headers['x-csrf-token'] }}"
            },
            {
              "name": "Cookie",
              "value": "={{ $json.headers['set-cookie'].join('; ')}}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{\n  {\n    \"BusinessPartnerCategory\": \"1\",\n    \"FirstName\": $('Verificar Conta').item.json.dadosParaCriar.FirstName,\n    \"LastName\": $('Verificar Conta').item.json.dadosParaCriar.LastName,\n    \"SearchTerm1\": $('Verificar Conta').item.json.dadosParaCriar.SearchTerm1,\n    \"SearchTerm2\": $('Verificar Conta').item.json.dadosParaCriar.SearchTerm2\n  }\n}}",
        "options": {
          "response": {
            "response": {
              "fullResponse": true
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        864,
        656
      ],
      "id": "72b8d990-0d4d-4626-a70c-a99cbbb2a4dc",
      "name": "Post BP",
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/customers/insert/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            },
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "human_errors",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "vat",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.nif }}"
            },
            {
              "name": "name",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.nome }}"
            },
            {
              "name": "address",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.morada }}"
            },
            {
              "name": "zip_code",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.codigo_postal }}"
            },
            {
              "name": "phone",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.telemovel }}"
            },
            {
              "name": "language_id",
              "value": "1"
            },
            {
              "name": "country_id",
              "value": "1"
            },
            {
              "name": "maturity_date_id",
              "value": "1"
            },
            {
              "name": "payment_method_id",
              "value": "1"
            },
            {
              "name": "delivery_method_id",
              "value": "1"
            },
            {
              "name": "salesman_id",
              "value": "0"
            },
            {
              "name": "payment_day",
              "value": "0"
            },
            {
              "name": "discount",
              "value": "0"
            },
            {
              "name": "credit_limit",
              "value": "0"
            },
            {
              "name": "number",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.nif.toString().substring(0, 5) }}"
            }
          ]
        },
        "options": {}
      },
      "id": "0c169049-ab16-4965-acef-13a8a0a1d5f6",
      "name": "Criar Cliente Moloni1",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        496,
        1152
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/customers/getByVat/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            },
            {
              "name": "human_errors",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "vat",
              "value": "={{ $('Criar Fatura').first().json.body.cliente.nif }}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        144,
        1248
      ],
      "id": "1a062013-b4bd-483e-aab9-fc25d54ee18f",
      "name": "Obter clientes moloni3",
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "79d032d4-f87a-4033-94bd-dbd5d0972469",
              "leftValue": "=.toString({{ $json[\"customer_id\"] }})",
              "rightValue": 0,
              "operator": {
                "type": "string",
                "operation": "empty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        304,
        1248
      ],
      "id": "ccde0010-1278-4e77-866b-7409c6606654",
      "name": "If3",
      "alwaysOutputData": false
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        688,
        1248
      ],
      "id": "45efcca2-26b1-4b53-b69e-79fb5d364b36",
      "name": "Merge1"
    },
    {
      "parameters": {
        "jsCode": "// 1. Ler os itens que v\u00eam do Webhook (do n\u00f3 \"Criar Fatura\")\nconst itens = $(\"Criar Fatura\").first().json.body.itens;\n\n// 2. Transformar cada item para o formato que o Moloni exige\nconst linhas = itens.map(item => {\n  return {\n    \"product_id\": item.product_id,\n    \"name\": item.produto,\n    \"summary\": `${item.cor} - ${item.tamanho}`, // Detalhes na descri\u00e7\u00e3o\n    \"qty\": item.quantidade || 1,\n    \"price\": item.preco,\n  }\n});\n\n// 3. Devolver a lista preparada\nreturn { linhas };"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -32,
        1248
      ],
      "id": "7795d979-12e6-49d7-8cd1-56a83f48bdfd",
      "name": "Preparar Produtos1"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "criar-fatura",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "c1ff75b7-6de9-4bc4-9441-20a4d150755a",
      "name": "Criar Fatura",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        1248
      ]
    },
    {
      "parameters": {
        "jsCode": "// 1. Obter o ID do Cliente diretamente do n\u00f3 \"Merge1\"\nconst customerId = $('Merge1').first().json.customer_id;\n\n// 2. Obter a lista de produtos original\nconst produtosOriginais = $('Preparar Produtos1').first().json.linhas;\n\n// 3. Configura\u00e7\u00f5es Fixas\nconst companyId = 368796;    \nconst documentSetId = 873868; \nconst warehouseId = 475443; \nconst taxId = 3709603;        \n\n// 4. Calcular datas\nconst today = new Date();\nconst dateString = today.toISOString().split('T')[0];\n\nconst expireDate = new Date();\nexpireDate.setDate(today.getDate() + 30);\nconst expireDateString = expireDate.toISOString().split('T')[0];\n\n// 5. Mapear produtos (Cen\u00e1rio: O pre\u00e7o J\u00c1 TRAZ IVA e queremos extrair a base)\nconst products = produtosOriginais.map(item => {\n  \n  // A. Calcular valores totais\n  const totalPagoPeloCliente = item.price * item.qty; // Ex: 24.60\n  \n  // B. Extrair o Pre\u00e7o Base (retirar os 23%)\n  // Dividimos por 1.23 para encontrar o valor sem imposto\n  const totalLiquido = totalPagoPeloCliente / 1.23; // Ex: 20.00\n  \n  // C. Calcular o valor do IVA (Diferen\u00e7a entre o total e a base)\n  const valorDoIva = totalPagoPeloCliente - totalLiquido; // Ex: 4.60\n  \n  // D. Calcular o Pre\u00e7o Unit\u00e1rio Base (para preencher o campo 'price')\n  const precoUnitarioBase = item.price / 1.23;\n\n  return {\n    \"product_id\": item.product_id,\n    \"name\": item.name,\n    \"summary\": item.summary,\n    \"qty\": item.qty,\n    \n    // O Moloni quer o pre\u00e7o unit\u00e1rio SEM imposto. \n    // Usamos 4 casas decimais para garantir precis\u00e3o matem\u00e1tica.\n    \"price\": parseFloat(precoUnitarioBase.toFixed(4)),\n    \n    \"warehouse_id\": warehouseId,\n    \"taxes\": [\n      {\n        \"tax_id\": taxId,\n        \"value\": parseFloat(valorDoIva.toFixed(2)), // O valor monet\u00e1rio do imposto\n        \"order\": 1,\n        \"cumulative\": 0\n      }\n    ]\n  }\n});\n\n// 6. Retornar o resultado\nreturn {\n    json: {\n        \"company_id\": companyId,\n        \"date\": dateString,\n        \"expiration_date\": expireDateString,\n        \"document_set_id\": documentSetId,\n        \"customer_id\": customerId,\n        \"entity_vat\": $('Merge1').first().json.vat,\n        \"entity_name\": $('Merge1').first().json.name,\n        \"your_reference\": \"REF_AUTO_\" + Math.floor(Math.random() * 10000),\n        \"status\": 1, \n        \"products\": products\n    }\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        848,
        1248
      ],
      "id": "3e9a06f2-7776-4a9a-a50a-57d9a14d361b",
      "name": "Payload"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/internalDocuments/insert/?json=true",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1008,
        1248
      ],
      "id": "511b281a-e837-4a8e-892c-edf1683e66cd",
      "name": "Emitir Documento Interno1"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/documents/getPDFLink/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            },
            {
              "name": "json",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "document_id",
              "value": "={{ $('Emitir Documento Interno1').first().json.document_id }}"
            }
          ]
        },
        "options": {}
      },
      "id": "2df93b3d-4a84-4bba-9bf4-6fa6345e168c",
      "name": "Obter Link PDF",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1504,
        1248
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $('Obter Link PDF').first().json }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "b2b2aac9-37ca-410c-8916-d2bdfcdf002f",
      "name": "Respond to Webhook2",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        1648,
        1248
      ]
    },
    {
      "parameters": {
        "jsCode": "// 1. Ir buscar os itens que foram comprados (do n\u00f3 Preparar Produtos1)\nconst itens = $('Preparar Produtos1').first().json.linhas;\n\n// 2. Ir buscar o ID do documento criado (para associar o movimento ao documento)\nconst docId = $('Emitir Documento Interno1').first().json.document_id;\n\n// 3. Defini\u00e7\u00f5es\nconst warehouseId = 475443; // O mesmo ID de armaz\u00e9m que usaste antes\nconst companyId = 368796;   // O teu ID de empresa\n\n// 4. Gerar a data/hora atual\nconst now = new Date().toISOString().replace('T', ' ').substring(0, 19);\n\n// 5. Criar um movimento para cada item\nconst movimentos = itens.map(item => {\n  return {\n    json: {\n      company_id: companyId,\n      date: now,\n      document_id: docId,       // Opcional, mas FANT\u00c1STICO para rastreabilidade\n      product_id: item.product_id,\n      warehouse_id: warehouseId,\n      qty: -Math.abs(item.qty), // Importante: Valor NEGATIVO para sair stock\n      notes: \"Venda Loja Online (Via n8n)\"\n    }\n  }\n});\n\nreturn movimentos;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1168,
        1248
      ],
      "id": "7997442e-2dc4-4c77-ad52-7af691e9694e",
      "name": "Preparar Movimento"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/stockMovements/insert/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            },
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "json",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json) }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1344,
        1248
      ],
      "id": "fb5c1943-4509-4c79-82fc-99967f8ddca2",
      "name": "Atualizar Stock"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/stockMovements/insert/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            },
            {
              "name": "company_id",
              "value": "368796"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "date",
              "value": "={{ new Date().toISOString().slice(0, 19).replace('T', ' ') }}"
            },
            {
              "name": "product_id",
              "value": "={{ $json.body.id }}"
            },
            {
              "name": "warehouse_id",
              "value": "475443"
            },
            {
              "name": "qty",
              "value": "={{ $json.body.quantidade_adicional }}"
            },
            {
              "name": "notes",
              "value": "Entrada de Stock (Via Admin Painel)"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        16,
        1648
      ],
      "id": "11235154-f45d-4da5-b5a8-47cfae692719",
      "name": "Moloni: Adicionar Stock"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"status\": \"Sucesso\",\n  \"message\": \"Stock atualizado com sucesso\"\n}",
        "options": {
          "responseCode": 200,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        240,
        1648
      ],
      "id": "de422c0f-27a0-465d-8ddc-c89fefbf5375",
      "name": "Confirmar Stock"
    },
    {
      "parameters": {
        "url": "https://s20.gb.ucc.cit.tum.de/sap/opu/odata/sap/MD_BUSINESSPARTNER_SRV/C_BusinessPartner",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "sap-client",
              "value": "305"
            },
            {
              "name": "$format",
              "value": "json"
            },
            {
              "name": "$select",
              "value": "BusinessPartnerCategory,FirstName,LastName,SearchTerm1,SearchTerm2"
            },
            {
              "name": "$filter",
              "value": "CreatedByUser eq 'LEARN-696'"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-CSRF-Token",
              "value": "Fetch"
            }
          ]
        },
        "options": {
          "response": {
            "response": {}
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        16,
        1440
      ],
      "id": "1401d985-4a98-4d3d-9a7e-daac8c72ad05",
      "name": "SAP: Obter Todos Clientes",
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Normalizar dados para a tabela do Admin\nconst results = $input.first().json.d.results || [];\n\nreturn results.map(c => ({\n  json: {\n    // Tenta encontrar o nome (Seja Cliente criado pelo n8n ou SAP nativo)\n    cliente: c.FirstName ? `${c.FirstName} ${c.LastName || ''}` : (c.OrganizationBPName1 || 'Sem Nome'),\n    // Usa SearchTerm1 como NIF (igual ao login)\n    nif: c.SearchTerm1 || 'N/A',\n    // Usa SearchTerm2 como Pa\u00eds\n    pais: c.SearchTerm2 || 'PT'\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        1440
      ],
      "id": "871f745c-3218-471c-9575-991236454090",
      "name": "Formatar Lista"
    },
    {
      "parameters": {
        "respondWith": "allIncomingItems",
        "options": {
          "responseCode": 200,
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        464,
        1440
      ],
      "id": "c93c56de-d875-49e2-960e-89477f251b54",
      "name": "Resposta Clientes"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/productCategories/getAll/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "parent_id",
              "value": "0"
            }
          ]
        },
        "options": {}
      },
      "id": "e39a373d-5035-4b0b-81ba-aa188ac57700",
      "name": "Moloni: Get Categorias",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        16,
        1856
      ]
    },
    {
      "parameters": {
        "jsCode": "// 1. Obter todos os dados que entraram no n\u00f3\nlet dados = $input.all().map(i => i.json);\n\n// 2. Verifica\u00e7\u00e3o inteligente:\n// Se o n8n agrupou tudo num \u00fanico array no primeiro item, extra\u00edmos esse array.\n// Se o n8n j\u00e1 separou os itens (split), usamos a lista \"dados\" como est\u00e1.\nif (dados.length === 1 && Array.isArray(dados[0])) {\n    dados = dados[0];\n} else if (dados.length === 1 && dados[0].d && dados[0].d.results) {\n    // Caso venha do SAP ou estrutura similar\n    dados = dados[0].d.results;\n}\n\n// 3. Filtrar e Formatar\n// Garantimos que s\u00f3 passamos itens que tenham ID e Nome\nconst listaLimpa = dados\n    .filter(c => c && (c.category_id || c.product_id)) // Seguran\u00e7a extra\n    .map(c => ({\n        json: {\n            category_id: c.category_id,\n            name: c.name\n        }\n    }));\n\nreturn listaLimpa;"
      },
      "id": "7b62f304-3845-4ee1-8cfc-c5475d4ad236",
      "name": "Formatar Categorias",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        1856
      ]
    },
    {
      "parameters": {
        "respondWith": "allIncomingItems",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "id": "dee4d81a-82fb-40fc-acf7-383ed83ef79f",
      "name": "Responder Lista",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        464,
        1856
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/productCategories/insert/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "parent_id",
              "value": "0"
            },
            {
              "name": "name",
              "value": "={{ $json.body.nome }}"
            },
            {
              "name": "description",
              "value": "={{ $json.body.descricao }}"
            }
          ]
        },
        "options": {}
      },
      "id": "fcb9e6fc-9985-43ad-a6e2-d503e5d50d27",
      "name": "Moloni: Insert Categoria",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        16,
        2048
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"status\": \"Sucesso\",\n  \"mensagem\": \"Categoria criada\"\n}",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "id": "f02f7e6e-4b66-435c-adea-ba67354d0112",
      "name": "Responder Categoria",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        240,
        2048
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.moloni.pt/v1/products/insert/",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "4e3afd668e26a6d8a321752d040e599198d134f1"
            }
          ]
        },
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "company_id",
              "value": "368796"
            },
            {
              "name": "category_id",
              "value": "={{ $json.body.categoria_id }}"
            },
            {
              "name": "type",
              "value": "1"
            },
            {
              "name": "name",
              "value": "={{ $json.body.nome }}"
            },
            {
              "name": "reference",
              "value": "={{ $json.body.referencia }}"
            },
            {
              "name": "price",
              "value": "={{ $json.body.preco }}"
            },
            {
              "name": "unit_id",
              "value": "2643729"
            },
            {
              "name": "has_stock",
              "value": "1"
            },
            {
              "name": "stock",
              "value": "={{ $json.body.stock }}"
            },
            {
              "name": "warehouse_id",
              "value": "475443"
            },
            {
              "name": "taxes",
              "value": "[{\"tax_id\": 3709603, \"value\": 23, \"order\": 1, \"cumulative\": 0}]"
            },
            {
              "name": "summary",
              "value": "={{ $json.body.descricao }}"
            },
            {
              "name": "exemption_reason",
              "value": "M01"
            }
          ]
        },
        "options": {}
      },
      "id": "f1b96ef6-5148-49a6-92bf-83a38708888e",
      "name": "Moloni: Insert Produto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        16,
        2272
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"status\": \"Sucesso\",\n  \"mensagem\": \"Produto criado\"\n}",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Access-Control-Allow-Origin",
                "value": "*"
              }
            ]
          }
        }
      },
      "id": "338e72ff-b76e-492c-aa20-1da2aa4325b6",
      "name": "Responder Produto",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        240,
        2272
      ]
    },
    {
      "parameters": {
        "path": "listar-clientes",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        1440
      ],
      "id": "422a55d6-e8fa-4ce8-a509-1b1579148ea4",
      "name": "Listar Clientes"
    },
    {
      "parameters": {
        "path": "listar-categorias",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "077b13ec-acfe-4667-940f-ca10db605de3",
      "name": "Listar Categorias",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -208,
        1856
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "criar-categoria",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "38bea7ee-f478-461d-b8f1-89a287e5fd2e",
      "name": "Criar Categoria",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -208,
        2048
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "criar-produto",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "fc45d88c-4fa0-481d-9cca-b7cb3e0f5802",
      "name": "Criar Produto",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -208,
        2272
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "atualizar-stock",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -208,
        1648
      ],
      "id": "34437394-6e8a-4860-9aff-e8521ae95c7b",
      "name": "Atualiza\u00e7\u00e3o Stock"
    }
  ],
  "connections": {
    "Transformar Dados": {
      "main": [
        [
          {
            "node": "Clientes Obtidos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obter Clientes": {
      "main": [
        [
          {
            "node": "Get BP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Login": {
      "main": [
        [
          {
            "node": "Get BP1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get BP": {
      "main": [
        [
          {
            "node": "Transformar Dados",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get BP1": {
      "main": [
        [
          {
            "node": "Verificar Cliente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificar Cliente": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If": {
      "main": [
        [
          {
            "node": "Conta Existe",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Conta nao existe",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get BP2": {
      "main": [
        [
          {
            "node": "Verificar Conta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If1": {
      "main": [
        [
          {
            "node": "Get BP3",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Conta j\u00e1 Existe",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get BP3": {
      "main": [
        [
          {
            "node": "Post BP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Conta": {
      "main": [
        [
          {
            "node": "Get BP2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificar Conta": {
      "main": [
        [
          {
            "node": "If1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Carregar Produtos": {
      "main": [
        [
          {
            "node": "Obter Produtos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obter Produtos": {
      "main": [
        [
          {
            "node": "Formatar Dados",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Formatar Dados": {
      "main": [
        [
          {
            "node": "Respond to Webhook1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post BP": {
      "main": [
        [
          {
            "node": "Conta Criada",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Cliente Moloni1": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obter clientes moloni3": {
      "main": [
        [
          {
            "node": "If3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If3": {
      "main": [
        [
          {
            "node": "Criar Cliente Moloni1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge1": {
      "main": [
        [
          {
            "node": "Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar Produtos1": {
      "main": [
        [
          {
            "node": "Obter clientes moloni3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Fatura": {
      "main": [
        [
          {
            "node": "Preparar Produtos1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Payload": {
      "main": [
        [
          {
            "node": "Emitir Documento Interno1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Emitir Documento Interno1": {
      "main": [
        [
          {
            "node": "Preparar Movimento",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obter Link PDF": {
      "main": [
        [
          {
            "node": "Respond to Webhook2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar Movimento": {
      "main": [
        [
          {
            "node": "Atualizar Stock",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Atualizar Stock": {
      "main": [
        [
          {
            "node": "Obter Link PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Moloni: Adicionar Stock": {
      "main": [
        [
          {
            "node": "Confirmar Stock",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SAP: Obter Todos Clientes": {
      "main": [
        [
          {
            "node": "Formatar Lista",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Formatar Lista": {
      "main": [
        [
          {
            "node": "Resposta Clientes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Moloni: Get Categorias": {
      "main": [
        [
          {
            "node": "Formatar Categorias",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Formatar Categorias": {
      "main": [
        [
          {
            "node": "Responder Lista",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Moloni: Insert Categoria": {
      "main": [
        [
          {
            "node": "Responder Categoria",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Moloni: Insert Produto": {
      "main": [
        [
          {
            "node": "Responder Produto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Listar Clientes": {
      "main": [
        [
          {
            "node": "SAP: Obter Todos Clientes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Listar Categorias": {
      "main": [
        [
          {
            "node": "Moloni: Get Categorias",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Categoria": {
      "main": [
        [
          {
            "node": "Moloni: Insert Categoria",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Produto": {
      "main": [
        [
          {
            "node": "Moloni: Insert Produto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Atualiza\u00e7\u00e3o Stock": {
      "main": [
        [
          {
            "node": "Moloni: Adicionar Stock",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "34719fbe-a3b6-4174-848a-2627599ea449",
  "id": "0tdDejfY3vtbL4BU",
  "tags": []
}