{
  "name": "Studio Lírio · Atendente de WhatsApp",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "GET",
        "path": "whatsapp-lirio",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "a520d57a-d061-5790-b464-b42a3793dbea",
      "name": "Webhook WhatsApp (verificação)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        -200
      ],
      "webhookId": "3fdae362-e1dd-5399-b9a3-40a49a91a6f9"
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.query['hub.challenge'] }}",
        "options": {}
      },
      "id": "e653307e-5fc2-5c8b-983e-a1762d264f22",
      "name": "Responder desafio da Meta",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        240,
        -200
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-lirio",
        "options": {}
      },
      "id": "b2011952-6b84-5b21-9d55-fbf9d2ddd2e5",
      "name": "Webhook WhatsApp Cloud API",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        100
      ],
      "webhookId": "5338a772-4878-535d-bfe0-8cebd40a1bc7"
    },
    {
      "parameters": {
        "jsCode": "// Normaliza o payload do WhatsApp Cloud API\nconst out = [];\nfor (const item of $input.all()) {\n  const value = item.json.body?.entry?.[0]?.changes?.[0]?.value;\n  const msg = value?.messages?.[0];\n  if (!msg) continue; // status de entrega/leitura: ignora\n  out.push({ json: {\n    telefone: msg.from,\n    nome: value.contacts?.[0]?.profile?.name || '',\n    tipo: msg.type,\n    texto: (msg.text?.body || '').trim(),\n    botaoId: msg.interactive?.button_reply?.id || msg.interactive?.list_reply?.id || '',\n    recebidoEm: new Date(Number(msg.timestamp) * 1000).toISOString()\n  }});\n}\nreturn out;"
      },
      "id": "2e763c2b-a72f-50bf-a298-81262311150f",
      "name": "Extrair mensagem",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        100
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "COLE_AQUI_O_ID_DA_PLANILHA",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Clientes",
          "mode": "name"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "telefone",
              "lookupValue": "={{ $json.telefone }}"
            }
          ]
        },
        "options": {}
      },
      "id": "9e44cc14-1f2d-5c0e-a34b-545413443e35",
      "name": "Buscar cliente na planilha",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        480,
        100
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Sheets - Studio Lírio (configurar)"
        }
      },
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "// Botões têm prioridade; texto livre cai em palavras-chave\nconst msg = $('Extrair mensagem').first().json;\nconst cliente = $input.first().json || {};\nconst t = (msg.texto || '').toLowerCase().normalize('NFD').replace(/[\\u0300-\\u036f]/g, '');\nconst id = msg.botaoId;\nlet intencao = 'menu';\nif (id) intencao = id.split(':')[0];\nelse if (/atendente|humano|pessoa|falar com/.test(t)) intencao = 'atendente';\nelse if (/cancelar|desmarcar|remarcar|mudar.*horario/.test(t)) intencao = 'remarcar';\nelse if (/agendar|marcar|tem horario|reservar/.test(t)) intencao = 'agendar';\nelse if (/quanto|preco|valor|custa|tabela/.test(t)) intencao = 'preco';\nelse if (/abre|aberto|horario|sabado|domingo|onde|endereco|fica|pix|cartao|estaciona/.test(t)) intencao = 'faq';\nreturn [{ json: { ...msg, cliente, intencao, textoNormalizado: t } }];"
      },
      "id": "8560f4eb-819a-5583-aea1-1fe16b58cc31",
      "name": "Detectar intenção",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        100
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intencao }}",
                    "rightValue": "agendar",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Agendar"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intencao }}",
                    "rightValue": "confirmar",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Confirmar horário"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intencao }}",
                    "rightValue": "preco",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Preços"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intencao }}",
                    "rightValue": "faq",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Dúvidas"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intencao }}",
                    "rightValue": "remarcar",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Remarcar/Cancelar"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intencao }}",
                    "rightValue": "atendente",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Atendente"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "Menu"
        }
      },
      "id": "72f9595d-1402-5ffd-a613-36efe7091f7f",
      "name": "Switch por intenção",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        960,
        100
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "value": "studiolirio.agenda@group.calendar.google.com",
          "mode": "id"
        },
        "returnAll": true,
        "timeMin": "={{ $now.startOf('day').toISO() }}",
        "timeMax": "={{ $now.plus({days: 7}).endOf('day').toISO() }}",
        "options": {
          "singleEvents": true,
          "orderBy": "startTime"
        }
      },
      "id": "a302542e-dc82-5ff0-aaee-f4722d116289",
      "name": "Google Agenda: consultar horários",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        1240,
        -160
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Agenda - Studio Lírio (configurar)"
        }
      },
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "// Expediente: ter a sáb, 9h às 19h, grade de 30 min\nconst ocupados = $input.all().map(e => ({ ini: new Date(e.json.start?.dateTime), fim: new Date(e.json.end?.dateTime), prof: e.json.extendedProperties?.private?.profissional }));\nconst pedido = $('Detectar intenção').first().json;\nconst [, servico, profissional, duracao = 60] = (pedido.botaoId || '').split(':');\nconst livres = [];\nfor (let d = 0; d < 7 && livres.length < 6; d++) {\n  const dia = new Date(); dia.setDate(dia.getDate() + d);\n  if (dia.getDay() < 2) continue; // domingo e segunda fechado\n  for (let m = 9 * 60; m + Number(duracao) <= 19 * 60 && livres.length < 6; m += 30) {\n    const ini = new Date(dia); ini.setHours(0, m, 0, 0);\n    const fim = new Date(ini.getTime() + duracao * 60000);\n    if (ini < new Date(Date.now() + 3600000)) continue;\n    const conflito = ocupados.some(o => (!profissional || o.prof === profissional) && ini < o.fim && fim > o.ini);\n    if (!conflito) livres.push({ id: `confirmar:${servico}:${profissional}:${ini.toISOString()}`, title: ini.toLocaleString('pt-BR', { weekday: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) });\n  }\n}\nreturn [{ json: { ...pedido, livres } }];"
      },
      "id": "9a0ba1a0-fb9c-50f3-b8e2-49023a8bab21",
      "name": "Calcular horários livres",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1480,
        -160
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $json.telefone, type: 'interactive', interactive: { type: 'list', body: { text: 'Encontrei estes horários livres. Qual fica melhor para você? 🌷' }, action: { button: 'Ver horários', sections: [{ title: 'Horários', rows: $json.livres }] } } }) }}",
        "options": {}
      },
      "id": "6b645e6f-3c19-5b32-b051-988b4a64b801",
      "name": "WhatsApp: oferecer horários",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1720,
        -160
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "calendar": {
          "__rl": true,
          "value": "studiolirio.agenda@group.calendar.google.com",
          "mode": "id"
        },
        "start": "={{ $json.botaoId.split(':').slice(3).join(':') }}",
        "end": "={{ DateTime.fromISO($json.botaoId.split(':').slice(3).join(':')).plus({minutes: 60}).toISO() }}",
        "additionalFields": {
          "summary": "={{ $json.botaoId.split(':')[1] }} · {{ $json.nome }}",
          "description": "=Agendado pela Lírio (WhatsApp {{ $json.telefone }})"
        }
      },
      "id": "fc296a0a-919b-51c8-a1ca-afae3c241a5c",
      "name": "Google Agenda: criar evento",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        1240,
        40
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Agenda - Studio Lírio (configurar)"
        }
      }
    },
    {
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "COLE_AQUI_O_ID_DA_PLANILHA",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Agendamentos",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "evento_id"
          ],
          "value": {
            "evento_id": "={{ $json.id }}",
            "telefone": "={{ $('Detectar intenção').first().json.telefone }}",
            "nome": "={{ $('Detectar intenção').first().json.nome }}",
            "servico": "={{ $('Detectar intenção').first().json.botaoId.split(':')[1] }}",
            "profissional": "={{ $('Detectar intenção').first().json.botaoId.split(':')[2] }}",
            "inicio": "={{ $json.start.dateTime }}",
            "status": "confirmado",
            "origem": "WhatsApp"
          }
        },
        "options": {}
      },
      "id": "0c11290b-3d5b-51f7-a78f-ad0371c6fda6",
      "name": "Google Sheets: registrar agendamento",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1480,
        40
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Sheets - Studio Lírio (configurar)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $('Detectar intenção').first().json.telefone, type: 'template', template: { name: 'confirmacao_agendamento', language: { code: 'pt_BR' }, components: [{ type: 'body', parameters: [ { type: 'text', text: $('Detectar intenção').first().json.nome }, { type: 'text', text: $('Google Sheets: registrar agendamento').first().json.servico }, { type: 'text', text: DateTime.fromISO($('Google Sheets: registrar agendamento').first().json.inicio).setLocale('pt-BR').toFormat(\"ccc, dd/LL 'às' HH:mm\") } ] }] } }) }}",
        "options": {}
      },
      "id": "9ebf3183-7bd8-56e2-af20-3b4e109c8a77",
      "name": "WhatsApp: enviar confirmação",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1720,
        40
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "resume": "specificTime",
        "dateTime": "={{ DateTime.fromISO($('Google Sheets: registrar agendamento').first().json.inicio).minus({days: 1}).set({hour: 10, minute: 0}).toISO() }}"
      },
      "id": "88c6cf11-1f0b-5ac4-b73a-8c90413ed861",
      "name": "Aguardar até D-1 às 10h",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        1960,
        40
      ],
      "webhookId": "d1785c0c-ae74-512e-bb7e-e6d2e42b2bdb"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $('Detectar intenção').first().json.telefone, type: 'interactive', interactive: { type: 'button', body: { text: 'Oi! Passando para lembrar do seu horário amanhã no Studio Lírio ✨ Podemos confirmar?' }, action: { buttons: [ { type: 'reply', reply: { id: 'presenca:sim', title: 'Confirmar' } }, { type: 'reply', reply: { id: 'remarcar:lembrete', title: 'Remarcar' } } ] } } }) }}",
        "options": {}
      },
      "id": "3ece638f-6890-5432-a01a-e01458fd984f",
      "name": "WhatsApp: lembrete com Confirmar/Remarcar",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2200,
        40
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "resume": "specificTime",
        "dateTime": "={{ DateTime.fromISO($('Google Sheets: registrar agendamento').first().json.inicio).plus({hours: 3}).toISO() }}"
      },
      "id": "a0b498c7-e506-5914-b9c0-e5f744e00d0f",
      "name": "Aguardar fim do atendimento + 2h",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        2440,
        40
      ],
      "webhookId": "d7440954-eda3-5937-9818-75bf5a196023"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $('Detectar intenção').first().json.telefone, type: 'text', text: { preview_url: true, body: 'Obrigada pela visita hoje! 💛 Conta pra gente como foi? Sua avaliação ajuda muito: ' + $env.LIRIO_GOOGLE_REVIEW_URL } }) }}",
        "options": {}
      },
      "id": "aa509296-dfd8-557e-b8d6-3c3ff29a59ee",
      "name": "WhatsApp: pedir avaliação no Google",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2680,
        40
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const t = $json.textoNormalizado;\nconst precos = { peeling: 'Peeling de diamante: R$ 220 (60 min)', microagulhamento: 'Microagulhamento: R$ 350 (90 min)', henna: 'Design com henna: R$ 80 (40 min)', 'lash lifting': 'Lash lifting: R$ 160 (60 min)', lash: 'Lash lifting: R$ 160 (60 min)', escova: 'Escova modelada: R$ 70 (45 min)', corte: 'Corte feminino: R$ 120 (60 min)', coloracao: 'Coloração completa: R$ 280 (120 min)', mechas: 'Mechas/Balayage: R$ 450 (180 min)', hidratacao: 'Hidratação profunda: R$ 110 (50 min)', 'limpeza de pele': 'Limpeza de pele profunda: R$ 180 (75 min)', sobrancelha: 'Design de sobrancelha: R$ 60 (30 min)', cilios: 'Extensão de cílios fio a fio: R$ 230 (120 min)', manicure: 'Manicure: R$ 40 (40 min)', pedicure: 'Pedicure: R$ 50 (50 min)', massagem: 'Massagem relaxante: R$ 170 (60 min)', drenagem: 'Drenagem linfática: R$ 190 (60 min)' };\nlet resposta = 'Posso te ajudar com agendamentos, preços, horários e endereço. É só me dizer 🌷';\nconst achado = Object.keys(precos).find(k => t.includes(k));\nif (achado) resposta = precos[achado] + '. Quer agendar?';\nelse if (/abre|aberto|horario|sabado|domingo/.test(t)) resposta = 'Atendemos de terça a sábado, das 9h às 19h. Sim, abrimos aos sábados!';\nelse if (/onde|endereco|fica/.test(t)) resposta = 'Av. Paulista, 900, sala 12, São Paulo. Pertinho do metrô Trianon-Masp.';\nelse if (/pix|cartao|pagamento/.test(t)) resposta = 'Aceitamos Pix, débito e crédito (até 3x sem juros acima de R$ 300).';\nreturn [{ json: { ...$json, resposta } }];"
      },
      "id": "6fcace04-d809-58f0-8bfb-5b663e310cf8",
      "name": "Montar resposta (preços e dúvidas)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1240,
        240
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $json.telefone, type: 'text', text: { body: $json.resposta } }) }}",
        "options": {}
      },
      "id": "ce591fce-f7ba-57ac-8205-7d6df120909d",
      "name": "WhatsApp: responder dúvida",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1480,
        240
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "COLE_AQUI_O_ID_DA_PLANILHA",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Agendamentos",
          "mode": "name"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "telefone",
              "lookupValue": "={{ $json.telefone }}"
            },
            {
              "lookupColumn": "status",
              "lookupValue": "confirmado"
            }
          ]
        },
        "options": {}
      },
      "id": "330183b9-4e17-5ba3-b03c-ed15b29c7861",
      "name": "Google Sheets: buscar próximo horário",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1240,
        420
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Sheets - Studio Lírio (configurar)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $('Detectar intenção').first().json.telefone, type: 'interactive', interactive: { type: 'button', body: { text: 'Encontrei seu horário: ' + $json.servico + ' em ' + DateTime.fromISO($json.inicio).setLocale('pt-BR').toFormat(\"ccc, dd/LL 'às' HH:mm\") + '. O que você prefere?' }, action: { buttons: [ { type: 'reply', reply: { id: 'agendar:' + $json.servico + ':' + $json.profissional + ':60', title: 'Remarcar' } }, { type: 'reply', reply: { id: 'cancelar:' + $json.evento_id, title: 'Cancelar' } }, { type: 'reply', reply: { id: 'menu', title: 'Manter' } } ] } } }) }}",
        "options": {}
      },
      "id": "99fe9811-bd14-527c-9c6d-62735465b163",
      "name": "WhatsApp: opções Remarcar/Cancelar",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1480,
        420
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $env.LIRIO_RECEPCAO_TELEFONE, type: 'text', text: { body: '🔔 ' + ($json.nome || $json.telefone) + ' pediu atendimento humano no WhatsApp do Studio Lírio. Última mensagem: ' + ($json.texto || $json.botaoId) } }) }}",
        "options": {}
      },
      "id": "91375738-c3c3-517c-a491-45c5bbce0c9d",
      "name": "WhatsApp: avisar a recepção",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1240,
        600
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $('Detectar intenção').first().json.telefone, type: 'text', text: { body: 'Combinado! Já chamei alguém da nossa equipe. Em horário de atendimento respondemos em poucos minutos 💬' } }) }}",
        "options": {}
      },
      "id": "8c83b304-95a3-5ee4-8d4b-f1b2208b4ecd",
      "name": "WhatsApp: avisar a cliente da transferência",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1480,
        600
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $json.telefone, type: 'interactive', interactive: { type: 'list', body: { text: 'Oi' + ($json.cliente?.nome ? ', ' + $json.cliente.nome.split(' ')[0] : '') + '! 🌷 Eu sou a Lírio, assistente do Studio Lírio. Como posso te ajudar?' }, action: { button: 'Ver opções', sections: [{ title: 'Atendimento', rows: [ { id: 'agendar', title: 'Agendar horário' }, { id: 'preco', title: 'Ver preços' }, { id: 'remarcar', title: 'Remarcar ou cancelar' }, { id: 'atendente', title: 'Falar com atendente' } ] }] } } }) }}",
        "options": {}
      },
      "id": "ba1a513f-dbd8-56be-b630-2d52ee2c99ef",
      "name": "WhatsApp: enviar menu",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1240,
        780
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 * * 2-6"
            }
          ]
        }
      },
      "id": "641bcf5d-8c4f-5173-a0e4-932ab31c557c",
      "name": "Todo dia às 9h",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        1000
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "COLE_AQUI_O_ID_DA_PLANILHA",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Clientes",
          "mode": "name"
        },
        "options": {}
      },
      "id": "b4711f86-f06a-53ed-bd30-62ab746449b9",
      "name": "Google Sheets: ler clientes",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        240,
        1000
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Sheets - Studio Lírio (configurar)"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Regras de relacionamento (ajuste por salão)\nconst RETORNO_DIAS = { 'Extensão de cílios fio a fio': 21, 'Coloração completa': 35, 'Mechas/Balayage': 60, 'Design de sobrancelha': 20, 'Alongamento em gel': 21, 'Limpeza de pele profunda': 30 };\nconst hoje = DateTime.now().startOf('day');\nconst out = [];\nfor (const { json: c } of $input.all()) {\n  const ultima = c.ultima_visita ? DateTime.fromISO(c.ultima_visita) : null;\n  const dias = ultima ? Math.round(hoje.diff(ultima.startOf('day'), 'days').days) : null;\n  const nasc = c.aniversario ? DateTime.fromISO(c.aniversario) : null;\n  if (nasc && nasc.day === hoje.day && nasc.month === hoje.month)\n    out.push({ json: { ...c, campanha: 'aniversario', texto: `Feliz aniversário, ${c.nome.split(' ')[0]}! 🎂 Você ganhou R$ 40 de desconto este mês. Cupom: LIRIO-ANIV` } });\n  else if (dias && RETORNO_DIAS[c.ultimo_servico] === dias && !c.proximo_horario)\n    out.push({ json: { ...c, campanha: 'retorno', texto: `Oi, ${c.nome.split(' ')[0]}! Já está na hora da manutenção de ${c.ultimo_servico.toLowerCase()} ✨ Quer que eu veja horários?` } });\n  else if (dias === 45 && !c.proximo_horario)\n    out.push({ json: { ...c, campanha: 'reativacao', texto: `Oi, ${c.nome.split(' ')[0]}! Sentimos sua falta por aqui 🌷 Esta semana a hidratação profunda sai com 15% off para você.` } });\n}\nreturn out;"
      },
      "id": "3a02e654-fabc-515e-aff6-83ec0ebdc889",
      "name": "Separar campanhas do dia",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        1000
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $json.telefone, type: 'template', template: { name: 'lirio_' + $json.campanha, language: { code: 'pt_BR' }, components: [{ type: 'body', parameters: [{ type: 'text', text: $json.nome.split(' ')[0] }] }] } }) }}",
        "options": {}
      },
      "id": "9dee3297-0d7b-51d9-b903-4337552617d7",
      "name": "WhatsApp: enviar campanha",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        720,
        1000
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CONFIGURAR",
          "name": "WhatsApp Cloud API - Bearer (configurar)"
        }
      }
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "COLE_AQUI_O_ID_DA_PLANILHA",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Envios",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "telefone": "={{ $('Separar campanhas do dia').item.json.telefone }}",
            "campanha": "={{ $('Separar campanhas do dia').item.json.campanha }}",
            "enviado_em": "={{ $now.toISO() }}"
          }
        },
        "options": {}
      },
      "id": "1cca1865-4a67-5862-91d4-eabb08079b58",
      "name": "Google Sheets: registrar envio",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        960,
        1000
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "CONFIGURAR",
          "name": "Google Sheets - Studio Lírio (configurar)"
        }
      }
    },
    {
      "parameters": {
        "content": "## Atendente de WhatsApp · Studio Lírio\nRecebe mensagens da WhatsApp Cloud API, identifica a cliente na planilha, entende a intenção (botão ou palavra-chave) e responde.\n\n**Configurar:** credenciais Google e WhatsApp, variáveis `WA_PHONE_NUMBER_ID`, `LIRIO_RECEPCAO_TELEFONE`, `LIRIO_GOOGLE_REVIEW_URL` e o ID da planilha.",
        "height": 260,
        "width": 520,
        "color": 4
      },
      "id": "1bf3af17-27c4-5762-8ac6-0dd71954428b",
      "name": "Nota: atendimento",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -320
      ]
    },
    {
      "parameters": {
        "content": "## Rotinas diárias (ter a sáb, 9h)\nAniversário com cupom, retorno programado por serviço e reativação de clientes sem visita há 45 dias.",
        "height": 300,
        "width": 520,
        "color": 6
      },
      "id": "288d3916-28e8-506c-bb79-a9777e63d1c9",
      "name": "Nota: rotinas diárias",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        880
      ]
    }
  ],
  "connections": {
    "Webhook WhatsApp (verificação)": {
      "main": [
        [
          {
            "node": "Responder desafio da Meta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook WhatsApp Cloud API": {
      "main": [
        [
          {
            "node": "Extrair mensagem",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extrair mensagem": {
      "main": [
        [
          {
            "node": "Buscar cliente na planilha",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar cliente na planilha": {
      "main": [
        [
          {
            "node": "Detectar intenção",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Detectar intenção": {
      "main": [
        [
          {
            "node": "Switch por intenção",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch por intenção": {
      "main": [
        [
          {
            "node": "Google Agenda: consultar horários",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Google Agenda: criar evento",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Montar resposta (preços e dúvidas)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Montar resposta (preços e dúvidas)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Google Sheets: buscar próximo horário",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "WhatsApp: avisar a recepção",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "WhatsApp: enviar menu",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Agenda: consultar horários": {
      "main": [
        [
          {
            "node": "Calcular horários livres",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calcular horários livres": {
      "main": [
        [
          {
            "node": "WhatsApp: oferecer horários",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Agenda: criar evento": {
      "main": [
        [
          {
            "node": "Google Sheets: registrar agendamento",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets: registrar agendamento": {
      "main": [
        [
          {
            "node": "WhatsApp: enviar confirmação",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp: enviar confirmação": {
      "main": [
        [
          {
            "node": "Aguardar até D-1 às 10h",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aguardar até D-1 às 10h": {
      "main": [
        [
          {
            "node": "WhatsApp: lembrete com Confirmar/Remarcar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp: lembrete com Confirmar/Remarcar": {
      "main": [
        [
          {
            "node": "Aguardar fim do atendimento + 2h",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aguardar fim do atendimento + 2h": {
      "main": [
        [
          {
            "node": "WhatsApp: pedir avaliação no Google",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Montar resposta (preços e dúvidas)": {
      "main": [
        [
          {
            "node": "WhatsApp: responder dúvida",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets: buscar próximo horário": {
      "main": [
        [
          {
            "node": "WhatsApp: opções Remarcar/Cancelar",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp: avisar a recepção": {
      "main": [
        [
          {
            "node": "WhatsApp: avisar a cliente da transferência",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Todo dia às 9h": {
      "main": [
        [
          {
            "node": "Google Sheets: ler clientes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets: ler clientes": {
      "main": [
        [
          {
            "node": "Separar campanhas do dia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Separar campanhas do dia": {
      "main": [
        [
          {
            "node": "WhatsApp: enviar campanha",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp: enviar campanha": {
      "main": [
        [
          {
            "node": "Google Sheets: registrar envio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Sao_Paulo",
    "saveManualExecutions": true
  },
  "pinData": {},
  "tags": [],
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": "orbita-estudio-demo"
  }
}