{
  "name": "Relat\u00f3rio Facebook Ads copy",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": "={{ 7 }}",
              "triggerAtMinute": "={{ 0 }}"
            }
          ]
        }
      },
      "id": "42fd6beb-f180-4c9c-9fd9-fc1d39f0d169",
      "name": "Gatilho por Hor\u00e1rio",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        80,
        300
      ]
    },
    {
      "parameters": {
        "graphApiVersion": "v17.0",
        "node": "=act_{{ $json.metaAct }}",
        "edge": "insights",
        "allowUnauthorizedCerts": true,
        "options": {
          "queryParameters": {
            "parameter": [
              {
                "name": "time_increment",
                "value": "1"
              },
              {
                "name": "level",
                "value": "ad"
              },
              {
                "name": "fields",
                "value": "=campaign_id,\ncampaign_name,\nadset_id,\nadset_name,\nad_id,\nad_name,\nspend,\nimpressions,\nclicks,\ncpc,\ncpm,\ncpp,\nctr,\nobjective,\nreach,\nactions"
              },
              {
                "name": "limit",
                "value": "3000"
              },
              {
                "name": "date_preset",
                "value": "=last_7d"
              }
            ]
          }
        }
      },
      "id": "2ca0c5f5-d170-4a23-a8b5-000dd9644b1b",
      "name": "Buscar Dados no Meta",
      "type": "n8n-nodes-base.facebookGraphApi",
      "position": [
        600,
        300
      ],
      "typeVersion": 1,
      "credentials": {
        "facebookGraphApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "let totalSpend = 0;\nlet totalLeads = 0;\nlet sumCPM = 0;\nlet sumCPP = 0;\nlet sumCTR = 0;\nlet totalClicks = 0;\nlet countCPM = 0;\nlet countCPP = 0;\nlet countCTR = 0;\n\n// Fun\u00e7\u00e3o para converter string de valores para float, tratando v\u00edrgula, espa\u00e7os e quebras de linha\nfunction convertToFloat(value) {\n    if (!value || value.trim() === \"\") return 0;\n    return parseFloat(value.replace(',', '.').replace(/\\n/g, '').trim()) || 0;\n}\n\n// Itera sobre cada item (registro de campanha)\nitems.forEach(item => {\n    const jsonData = item.json;\n\n    // Acumula o valor de investimento total\n    if (jsonData.total_investido !== undefined) {\n        totalSpend += convertToFloat(jsonData.total_investido);\n    }\n\n    // Acumula o total de cliques (corre\u00e7\u00e3o: usar \"total_clicks\" do input)\n    if (jsonData.total_clicks !== undefined) {\n        totalClicks += parseInt(jsonData.total_clicks.replace(/\\n/g, '').trim(), 10) || 0;\n    }\n\n    // Acumula mensagens iniciadas (supondo que representa leads)\n    if (jsonData.menssagens_iniciadas !== undefined) {\n        totalLeads += parseInt(jsonData.menssagens_iniciadas.replace(/\\n/g, '').trim(), 10) || 0;\n    }\n\n    // Acumula os valores de cpc, ctr para calcular a m\u00e9dia\n    if (jsonData.cpc !== undefined) {\n        sumCPP += convertToFloat(jsonData.cpc);\n        countCPP++;\n    }\n    if (jsonData.ctr !== undefined) {\n        sumCTR += convertToFloat(jsonData.ctr);\n        countCTR++;\n    }\n});\n\n// Calcula as m\u00e9dias\nconst avgCPC = totalClicks > 0 ? (totalSpend / totalClicks) : 0;\nconst avgCPP = countCPP > 0 ? (sumCPP / countCPP) : 0;\nconst avgCTR = countCTR > 0 ? (sumCTR / countCTR) : 0;\nconst cpl = totalLeads > 0 ? (totalSpend / totalLeads) : 0;  // Calcula o CPL\n\n// Retorna os dados acumulados e formatados corretamente\nreturn [\n    {\n        json: {\n            totalSpend: totalSpend.toFixed(2).replace('.', ','),\n            totalLeads: totalLeads,\n            totalClicks: totalClicks,\n            avgCPC: avgCPC.toFixed(2).replace('.', ','),\n            avgCPP: avgCPP.toFixed(2).replace('.', ','),\n            avgCTR: avgCTR.toFixed(2).replace('.', ','),\n            cpl: cpl.toFixed(2).replace('.', ',')\n        }\n    }\n];\n"
      },
      "id": "a97e11d4-680d-402b-88cc-5f6afd14123e",
      "name": "Script de C\u00e1lculo",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        300
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "bf0e3fda-5877-49bc-8b48-062cdb365c5a",
              "name": "campanha",
              "value": "={{ $json.data[0,1,2,3,4,5,6,7].campaign_name }}",
              "type": "string"
            },
            {
              "id": "7e5a5dea-d0cd-41f4-81e0-ca9817add1a1",
              "name": "total_clicks",
              "value": "={{ $json.data.reduce((sum, entry) => sum + (parseInt(entry.clicks, 10) || 0), 0) }}\n",
              "type": "string"
            },
            {
              "id": "4163b43e-6f99-4b25-ab55-3e6cc986d4e5",
              "name": "cpc",
              "value": "={{ $json.data.reduce((sum, entry) => sum + (parseInt(entry.cpc, 10) || 0), 0) }}",
              "type": "string"
            },
            {
              "id": "bc1bf727-262f-4766-83db-b988d135c88e",
              "name": "ctr",
              "value": "={{ $json.data.reduce((sum, entry) => sum + (parseInt(entry.ctr, 10) || 0), 0) }}",
              "type": "string"
            },
            {
              "id": "50f8d7f2-bd1d-44e2-b552-da6f07d88ed0",
              "name": "total_investido",
              "value": "={{ $json.data.reduce((sum, entry) => sum + (parseInt(entry.spend, 10) || 0), 0) }}",
              "type": "string"
            },
            {
              "id": "86f64309-6c37-4c68-bbd5-c33355a03447",
              "name": "menssagens_iniciadas",
              "value": "={{ $json.data.reduce((sum, entry) => {\n  const action = entry.actions?.find(action => action.action_type === \"onsite_conversion.total_messaging_connection\");\n  const value = action?.value?.toString().trim() || \"0\"; // Garante que seja string, remove espa\u00e7os/vazios e usa \"0\" se necess\u00e1rio\n  return sum + (parseInt(value, 10) || 0);\n}, 0) }}",
              "type": "string"
            },
            {
              "id": "1d47b0c5-8640-4e45-8bb0-28ab663cd705",
              "name": "Engajamento",
              "value": "={{ $json.data.reduce((sum, entry) => {\n  const action = entry.actions?.find(action => action.action_type === \"post_engagement\");\n  const value = action?.value?.toString().trim() || \"0\"; // Garante que seja string, remove espa\u00e7os/vazios e usa \"0\" se necess\u00e1rio\n  return sum + (parseInt(value, 10) || 0);\n}, 0) }}\n",
              "type": "string"
            },
            {
              "id": "c7926028-6f42-46e3-b2ca-3e0591c8171a",
              "name": "Data_inicio",
              "value": "={{ $('Set Vari\u00e1veis').item.json.desde }}",
              "type": "string"
            },
            {
              "id": "fea5617c-a01d-487f-a207-7c7882511d81",
              "name": "data_final",
              "value": "={{ $('Set Vari\u00e1veis').item.json['at\u00e9'] }}",
              "type": "string"
            },
            {
              "id": "42a730b2-4013-4a6c-a8d4-af0ae4ee852d",
              "name": "Impress\u00f5es",
              "value": "={{ $json.data.reduce((sum, entry) => sum + (parseInt(entry.impressions, 10) || 0), 0) }}",
              "type": "string"
            },
            {
              "id": "bbb3bf61-9a33-4403-9f70-ed500d938958",
              "name": "Alcance",
              "value": "={{ $json.data.reduce((sum, entry) => sum + (parseInt(entry.reach, 10) || 0), 0) }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "606b0683-5c1d-460a-a2db-b3c9d6d2103b",
      "name": "Edit Fields",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        820,
        300
      ]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1qpvJ_-5_sD-LqF8gKGUCDi1mmX8FQ-SAAYPEDNjL1jY",
          "mode": "list",
          "cachedResultName": "Clientes Tr\u00e1fego Pago Feejo",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1qpvJ_-5_sD-LqF8gKGUCDi1mmX8FQ-SAAYPEDNjL1jY/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "P\u00e1gina1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1qpvJ_-5_sD-LqF8gKGUCDi1mmX8FQ-SAAYPEDNjL1jY/edit#gid=0"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        40,
        -1320
      ],
      "id": "92956610-61eb-4198-8c95-76a46648127f",
      "name": "Google Sheets1",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        280,
        -1320
      ],
      "id": "d10a7d9d-b44c-4e7c-8361-306bf2ea4944",
      "name": "Loop Over Items"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "18df9941-85bc-4990-8b08-575a4fee231d",
              "name": "metaAct",
              "value": "=ID DA CONTA DO CLIENTE",
              "type": "string"
            },
            {
              "id": "7807acae-82fc-4c7d-8913-44a6c697d510",
              "name": "grupocliente",
              "value": "=",
              "type": "string"
            },
            {
              "id": "fe2eac3e-db11-4a7b-9a6e-6c7cab970f27",
              "name": "desde",
              "value": "={{$today.minus({days: 7}).toFormat('yyyy-MM-dd')}}",
              "type": "string"
            },
            {
              "id": "3087bf5e-938c-4a74-8313-bc02c38226a5",
              "name": "at\u00e9",
              "value": "={{$today.minus({days: 1}).toFormat('yyyy-MM-dd')}}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "b3df4ab2-f20c-47a3-862b-5c807f436f25",
      "name": "Set Vari\u00e1veis",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        360,
        300
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=<systemData>\nData de hoje: {{ $now.weekdayLong }}, {{ $now.format('dd/MM/yyyy') }}, {{ $now.hour.toString().padStart(2, '0') }}:{{ $now.minute.toString().padStart(2, '0') }}\n</systemData>\n\n<Agent>\n\n  <Name>Max</Name>\n  <Description>Gestor de tr\u00e1fego pago e Analista de dados da Feejo</Description>\n  <Language>Portugu\u00eas Brasileiro</Language>\n\n  <Personality>\n    Inteligente, prestativo e amig\u00e1vel, com tom de comunica\u00e7\u00e3o informal e foco na resolu\u00e7\u00e3o eficiente das necessidades dos clientes.\n  </Personality>\n\n  <CommunicationStyle>\n    <Style>Amig\u00e1vel e Descontraido</Style>\n    <Guide>\n      [\n        \"Seja sempre cordial e educado.\",\n        \"Responda de forma clara e concisa.\",\n        \"Adapte sua comunica\u00e7\u00e3o ao n\u00edvel de entendimento do cliente.\",\n        \"Evite jarg\u00f5es t\u00e9cnicos e explique termos complexos, quando necess\u00e1rio.\",\n        \"Se n\u00e3o souber a resposta, ofere\u00e7a alternativas e encaminhe para atendimento humano.\",\n        \"Responda com agilidade e sem atrasos desnecess\u00e1rios.\"\n      ]\n    </Guide>\n  </CommunicationStyle>\n\n  <Functionalities>\n    - Apresenta\u00e7\u00e3o inicial (sauda\u00e7\u00e3o, identifica\u00e7\u00e3o do cliente).\n    - Relat\u00f3rio de m\u00e9tricas e coment\u00e1rio sobre resultados.\n  </Functionalities>\n\n  <Flow>\n    1. **Sauda\u00e7\u00e3o e Recep\u00e7\u00e3o do Cliente:**\n       - \"Ol\u00e1, tudo bem? Sou o Max, assistente virtual da Feejo. Vou te passar os resultados dos an\u00fancios no Meta Ads dos \u00faltimos 7 dias do {{ $('Loop Over Items').item.json.Nome_Negocio }}\"\n  \n\n    2. **Apresenta\u00e7\u00e3o dos Resultados:**\n       - item por item, Valor gasto {{ $json.totalSpend }}, Impress\u00f5es {{ $('Edit Fields').item.json['Impress\u00f5es'] }}, Alcance {{ $('Edit Fields').item.json.Alcance }}, Total de leads {{ $json.totalLeads }},Total de Cliques{{ $json.totalClicks }}, Custo por Clique {{ $json.avgCPC }}, {{ $json.avgCPP }},{{ $json.avgCTR }}, {{ $json.cpl }}, Engajamento {{ $('Edit Fields').item.json.Engajamento }}, Data de In\u00edcio {{ $('Edit Fields').item.json.Data_inicio }}, Data de Fim {{ $('Edit Fields').item.json.data_final }}     dos \u00faltimos 7 dias.\n\n \n\n\n\n  <Rules>\n    - Sempre baseie as respostas em dados dispon\u00edveis.\n    - Evite adivinhar ou fazer suposi\u00e7\u00f5es.\n    - Se o dado for igual a zero, n\u00e3o mensione ele.\n    - Seja transparente caso n\u00e3o tenha uma resposta imediata.\n    - N\u00e3o forne\u00e7a informa\u00e7\u00f5es sens\u00edveis ou inventadas.\n    - Use linguagem amig\u00e1vel e acess\u00edvel.\n    - Forne\u00e7a um coment\u00e1rio que anime o cliente sobre os resultados, por\u00e9m sem inventar dados.\n    - N\u00e3o converse nada al\u00e9m de enviar os dados e coment\u00e1rio.\n  </Rules>\n\n</Agent>",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1380,
        300
      ],
      "id": "62f2442c-ee1f-4404-94d5-e6f5d519abb6",
      "name": "AI Agent"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.1,
      "position": [
        1320,
        480
      ],
      "id": "7569745a-c001-4118-9223-175eb1c17a29",
      "name": "OpenAI Chat Model",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "name": "Replace Me",
      "typeVersion": 1,
      "position": [
        460,
        -1480
      ],
      "id": "78fd28c2-fd17-4c79-9714-2bdb521bc734"
    },
    {
      "parameters": {
        "resource": "messages-api",
        "instanceName": "SUA INSTANCIA AQUI",
        "remoteJid": "=NUMERO DO CLIENTE AQUI",
        "messageText": "={{ $json.output }}",
        "options_message": {}
      },
      "type": "n8n-nodes-evolution-api.evolutionApi",
      "typeVersion": 1,
      "position": [
        2080,
        300
      ],
      "id": "aab6802e-11b2-4c91-b5a2-a0d56bf975b6",
      "name": "Envia para cliente",
      "credentials": {
        "evolutionApi": {
          "name": "<your credential>"
        }
      },
      "disabled": true
    },
    {
      "parameters": {
        "content": "",
        "height": 540,
        "width": 1240,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -40,
        60
      ],
      "typeVersion": 1,
      "id": "e0aaed98-6df0-469a-a87b-f7cf57911789",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "",
        "height": 540,
        "width": 600,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1220,
        60
      ],
      "typeVersion": 1,
      "id": "d4a91360-102c-4e72-99d0-8860f1be0ad2",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "content": "",
        "height": 540,
        "width": 600,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1840,
        60
      ],
      "typeVersion": 1,
      "id": "a8c6d351-d302-4d2c-849a-6d6628e4cb6d",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "",
        "height": 540,
        "width": 600,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1840,
        620
      ],
      "typeVersion": 1,
      "id": "79ab1a9d-c5c5-4917-b9d2-e31e2023c160",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "content": "## Seleciona a conta e os dados",
        "height": 80,
        "width": 360,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        100
      ],
      "typeVersion": 1,
      "id": "426efd0f-516d-48d2-add6-aecde4a693ac",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "content": "## Analista de dados",
        "height": 80,
        "width": 360,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1240,
        80
      ],
      "typeVersion": 1,
      "id": "3197a364-c7b4-4220-9b71-bfead3950304",
      "name": "Sticky Note5"
    },
    {
      "parameters": {
        "content": "## Envia relat\u00f3rio para o cliente",
        "height": 80,
        "width": 360,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1860,
        80
      ],
      "typeVersion": 1,
      "id": "bff4abc6-9fbe-45f5-8a2d-0b59631f938c",
      "name": "Sticky Note6"
    },
    {
      "parameters": {
        "content": "## Envia relat\u00f3rio para o head",
        "height": 80,
        "width": 360,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1860,
        640
      ],
      "typeVersion": 1,
      "id": "5c2c01e0-d627-4bb4-9e49-70a8217038c4",
      "name": "Sticky Note7"
    },
    {
      "parameters": {
        "resource": "messages-api",
        "instanceName": "SUA INSTANCIA AQUI",
        "remoteJid": "=SEU WHATSAPP AQUI",
        "messageText": "={{ $json.output }}",
        "options_message": {}
      },
      "type": "n8n-nodes-evolution-api.evolutionApi",
      "typeVersion": 1,
      "position": [
        2100,
        860
      ],
      "id": "91cb1a9a-17c0-4363-b94c-4fc05e3e6c31",
      "name": "Envia para Head",
      "credentials": {
        "evolutionApi": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Gatilho por Hor\u00e1rio": {
      "main": [
        [
          {
            "node": "Set Vari\u00e1veis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar Dados no Meta": {
      "main": [
        [
          {
            "node": "Edit Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Script de C\u00e1lculo": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields": {
      "main": [
        [
          {
            "node": "Script de C\u00e1lculo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets1": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "Replace Me",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Set Vari\u00e1veis": {
      "main": [
        [
          {
            "node": "Buscar Dados no Meta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Envia para Head",
            "type": "main",
            "index": 0
          },
          {
            "node": "Envia para cliente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Replace Me": {
      "main": [
        []
      ]
    },
    "Envia para cliente": {
      "main": [
        []
      ]
    },
    "Envia para Head": {
      "main": [
        []
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Sao_Paulo",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "3001dea0-1057-4e1c-b98a-732ede1baf0e",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "LWFJ4BdtKqcuZvL8",
  "tags": [
    {
      "createdAt": "2025-03-19T12:39:27.300Z",
      "updatedAt": "2025-03-19T12:39:27.300Z",
      "id": "3pTKcTWatyor7M1B",
      "name": "Facebook Ads"
    },
    {
      "createdAt": "2025-03-19T12:39:22.776Z",
      "updatedAt": "2025-03-19T12:39:22.776Z",
      "id": "XLwoiIjbZaO89jN1",
      "name": "Envio Relat\u00f3rio"
    },
    {
      "createdAt": "2025-03-19T12:36:30.810Z",
      "updatedAt": "2025-03-19T12:36:30.810Z",
      "id": "weqmPMAq11V4xrAU",
      "name": "Jony AI"
    },
    {
      "createdAt": "2025-03-19T12:36:54.225Z",
      "updatedAt": "2025-03-19T12:36:54.225Z",
      "id": "x8qne3XmLh3KLjxc",
      "name": "Feejo"
    }
  ]
}