{
  "name": "Cotizador IA · Taller de carrocería y pintura (WhatsApp)",
  "nodes": [
    {
      "parameters": {
        "updates": [
          "messages"
        ],
        "options": {}
      },
      "id": "4262e553-c070-451e-a11f-faa21b65ef6d",
      "name": "WhatsApp Trigger",
      "type": "n8n-nodes-base.whatsAppTrigger",
      "typeVersion": 1,
      "position": [
        0,
        400
      ],
      "webhookId": "a231ef88-2158-4849-a230-24ee625510f3"
    },
    {
      "parameters": {
        "mode": "manual",
        "assignments": {
          "assignments": [
            {
              "id": "63bd65c6-992e-4265-a77e-380201e63004",
              "name": "taller",
              "value": "Taller Ejemplo · Carrocería y pintura",
              "type": "string"
            },
            {
              "id": "e1b14c12-129c-421c-ad41-3dee57397070",
              "name": "direccion",
              "value": "Av. Ejemplo 456, Tu ciudad",
              "type": "string"
            },
            {
              "id": "f4be3db6-7a48-474c-abd0-83c1ac3c46ba",
              "name": "latitud",
              "value": 19.4326,
              "type": "number"
            },
            {
              "id": "cb2ff827-991e-4771-a8db-9d49db2d3875",
              "name": "longitud",
              "value": -99.1332,
              "type": "number"
            },
            {
              "id": "5274700f-1d7f-4328-a641-285257cbca73",
              "name": "zonaHoraria",
              "value": "America/Mexico_City",
              "type": "string"
            },
            {
              "id": "5eec9281-6d87-4d2d-a10b-4dd4faa06131",
              "name": "horario",
              "value": "Lunes a viernes de 9:00 a 18:00 y sábados de 9:00 a 14:00.",
              "type": "string"
            },
            {
              "id": "10200836-fb8b-4bf4-a113-26f5386cf1b3",
              "name": "horasRevision",
              "value": "10:00, 12:00, 16:00",
              "type": "string"
            },
            {
              "id": "815d6ffa-58ee-49d7-a93e-d7076269b908",
              "name": "horasRevisionSabado",
              "value": "10:00, 12:00",
              "type": "string"
            },
            {
              "id": "4c111c8a-b463-4320-a346-8c3d6fa457ee",
              "name": "diasRevision",
              "value": "1,2,3,4,5,6",
              "type": "string"
            },
            {
              "id": "55c7439f-6294-423e-ab55-fa181035947f",
              "name": "minutosRevision",
              "value": 20,
              "type": "number"
            },
            {
              "id": "3431311a-02d2-4ed6-a00d-af055417d424",
              "name": "moneda",
              "value": "USD",
              "type": "string"
            },
            {
              "id": "768c4ed9-cac0-47d4-aab9-320a26bb35de",
              "name": "telefonoDueno",
              "value": "5215500000000",
              "type": "string"
            },
            {
              "id": "7447c667-0c79-4a91-a4e8-bdbf091819a7",
              "name": "idiomaPlantillas",
              "value": "es",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "a179ed7e-574b-4c0f-af85-3738389b62d9",
      "name": "Datos del taller",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        220,
        400
      ]
    },
    {
      "parameters": {
        "jsCode": "// One clean item per incoming WhatsApp message. Status updates (sent, delivered, read) are dropped here.\nconst out = [];\n$input.all().forEach((item, index) => {\n  const raw = item.json;\n  const v = raw.messages ? raw : (raw.entry?.[0]?.changes?.[0]?.value ?? raw);\n  const msg = v.messages?.[0];\n  if (!msg) return;\n\n  const contacto = v.contacts?.[0] ?? {};\n  let tipo = 'texto';\n  let texto = '';\n  let datos = {};\n\n  if (msg.type === 'image') {\n    tipo = 'foto';\n    texto = msg.image?.caption ?? '';\n  } else if (msg.type === 'text') {\n    texto = msg.text?.body ?? '';\n  } else if (msg.type === 'interactive') {\n    const r = msg.interactive?.button_reply ?? msg.interactive?.list_reply ?? {};\n    texto = r.title ?? '';\n    // our buttons carry their data in the id: {\"a\": \"agendar\" | \"cita\", ...}\n    try {\n      const p = JSON.parse(r.id);\n      if (p && (p.a === 'agendar' || p.a === 'cita')) { tipo = p.a; datos = p; }\n    } catch (e) {}\n  } else if (msg.type === 'button') {\n    texto = msg.button?.text ?? '';\n  } else {\n    texto = `[El cliente envió un mensaje de tipo \"${msg.type}\". Por ahora solo se leen textos y fotos]`;\n  }\n\n  out.push({\n    json: {\n      tipo,\n      texto,\n      telefono: msg.from,\n      nombre: datos.n || contacto.profile?.name || '',\n      phoneNumberId: v.metadata?.phone_number_id,\n      imagenId: msg.image?.id ?? null,\n      // carried by the buttons, from the quote to the booking\n      resumen: datos.r ?? '',\n      rango: datos.p ?? '',\n      fotoId: datos.m ?? '',\n      inicio: datos.i ?? null,\n    },\n    pairedItem: { item: index },\n  });\n});\nreturn out;"
      },
      "id": "ef63cba6-efa5-4f90-ad17-3463908b2868",
      "name": "Lee el mensaje",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        400
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "d37a7216-f911-46f1-ae8e-43a55f451807",
                    "leftValue": "={{ $json.tipo }}",
                    "rightValue": "foto",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Foto"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "0b076cf9-7596-48c7-ad89-88d0d76005d9",
                    "leftValue": "={{ $json.tipo }}",
                    "rightValue": "agendar",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Quiere agendar"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "45b7be60-0456-4cd0-af6a-460d9a2cdc9b",
                    "leftValue": "={{ $json.tipo }}",
                    "rightValue": "cita",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Eligió horario"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "Texto"
        }
      },
      "id": "46705185-81b8-4e42-afb0-801aef76de0c",
      "name": "Tipo de mensaje",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        660,
        400
      ]
    },
    {
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $json.imagenId }}"
      },
      "id": "66ad8440-a1ce-445d-a0b2-7373553177f9",
      "name": "Obtén la foto",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        900,
        200
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.url }}",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        }
      },
      "id": "ab2f7cd6-04f9-4625-ac57-d9ade23afd46",
      "name": "Descarga la foto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1120,
        200
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Fecha y hora en el taller: {{ $now.setZone($('Datos del taller').first().json.zonaHoraria).setLocale('es').toFormat(\"cccc d 'de' LLLL, HH:mm\") }}\nCliente: {{ $('Lee el mensaje').item.json.nombre || 'sin nombre' }} (WhatsApp +{{ $('Lee el mensaje').item.json.telefono }})\n{{ $('Lee el mensaje').item.json.tipo === 'foto' ? 'El cliente mandó la foto adjunta' + ($('Lee el mensaje').item.json.texto ? ' con el texto: ' + $('Lee el mensaje').item.json.texto : '.') : 'Mensaje: ' + $('Lee el mensaje').item.json.texto }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "=Eres el cotizador de {{ $('Datos del taller').first().json.taller }}, un taller de carrocería y pintura. Atiendes por WhatsApp a cualquier hora a personas que te mandan fotos de su carro golpeado.\n\nDatos del taller\n- Dirección: {{ $('Datos del taller').first().json.direccion }}\n- Horario: {{ $('Datos del taller').first().json.horario }}\n- Moneda: {{ $('Datos del taller').first().json.moneda }}\n\nCuando llega una foto\n1. Identifica cada pieza dañada y el tipo de daño. Usa los nombres de pieza que aparecen en la tabla de precios: cada taller usa los de su país (parachoques = defensa = bumper; guardafango = salpicadera = aleta; direccional = cuarto = intermitente; capó = cofre; maletero = cajuela; luz trasera = calavera). Tipos de daño: rayón, abolladura, rota, desprendida, pintura.\n2. Califica la gravedad general: leve, media o grave.\n3. Consulta la herramienta \"Precios\" (la tabla de precios del taller) y elige, para cada daño, la fila que corresponde. Copia exactamente sus valores Mínimo y Máximo. Nunca inventes ni ajustes precios.\n4. Si un daño no está en la tabla, o no se ve bien en la foto, no lo cotices: agrégalo a fuera_de_tabla para revisarlo en persona.\n5. Si la foto no permite ver el daño (oscura, lejana, borrosa), pide otra con accion=\"pedir_foto\".\n\nOtros mensajes\n- Si piden presupuesto sin foto, pide una foto del golpe (accion=\"pedir_foto\").\n- Preguntas de horario o ubicación: contéstalas (accion=\"responder\").\n- Seguros, reclamaciones o algo que no puedes resolver: accion=\"derivar\" y diles que un asesor les escribe en horario de atención.\n\nEstilo: como un mensaje de WhatsApp en español neutro, que se entienda en cualquier país. Breve (1 o 2 frases), cálido y sin formato markdown. En \"respuesta\" no escribas montos: el sistema agrega el presupuesto con los números de la tabla.\n\nCampos\n- respuesta: el mensaje para el cliente.\n- accion: \"cotizar\" (hay foto y al menos un daño en la tabla), \"pedir_foto\", \"responder\" o \"derivar\".\n- piezas: solo con accion=\"cotizar\". Una entrada por daño cotizado: pieza, dano, minimo y maximo (números de la tabla).\n- gravedad: \"leve\", \"media\", \"grave\" o \"no_aplica\".\n- resumen: las piezas dañadas en pocas palabras (máximo 45 caracteres), por ejemplo \"Guardafango, direccional y parachoques\".\n- fuera_de_tabla: daños vistos que no se cotizan, si hay.",
          "maxIterations": 5,
          "passthroughBinaryImages": true
        }
      },
      "id": "e63eb3b1-04a4-4fdb-aeef-5bb28dc57398",
      "name": "Cotizador IA",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        1600,
        400
      ]
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-opus-5-5"
        },
        "options": {
          "maxTokensToSample": 4096,
          "thinkingMode": "adaptive",
          "effort": "medium",
          "promptCaching": "5m"
        }
      },
      "id": "938a9dca-92d3-49ae-a51c-cbcbe1dac15f",
      "name": "Claude",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "typeVersion": 1.6,
      "position": [
        1440,
        660
      ]
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Lee el mensaje').item.json.telefono }}",
        "contextWindowLength": 10
      },
      "id": "509d91d7-dd39-4919-ae4e-b85a6e74880e",
      "name": "Memoria",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.4,
      "position": [
        1600,
        660
      ]
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Devuelve la tabla de precios del taller: una fila por pieza y tipo de daño, con Mínimo y Máximo en la moneda del taller. Úsala antes de cotizar.",
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "Precios",
          "mode": "name"
        },
        "filtersUI": {},
        "options": {}
      },
      "id": "12a37951-621a-4793-a613-0c03ebc2f5c9",
      "name": "Precios",
      "type": "n8n-nodes-base.googleSheetsTool",
      "typeVersion": 4.7,
      "position": [
        1760,
        660
      ]
    },
    {
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"respuesta\": {\n      \"type\": \"string\"\n    },\n    \"accion\": {\n      \"type\": \"string\",\n      \"enum\": [\n        \"cotizar\",\n        \"pedir_foto\",\n        \"responder\",\n        \"derivar\"\n      ]\n    },\n    \"piezas\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"pieza\": {\n            \"type\": \"string\"\n          },\n          \"dano\": {\n            \"type\": \"string\"\n          },\n          \"minimo\": {\n            \"type\": \"number\"\n          },\n          \"maximo\": {\n            \"type\": \"number\"\n          }\n        },\n        \"required\": [\n          \"pieza\",\n          \"dano\",\n          \"minimo\",\n          \"maximo\"\n        ]\n      }\n    },\n    \"gravedad\": {\n      \"type\": \"string\",\n      \"enum\": [\n        \"leve\",\n        \"media\",\n        \"grave\",\n        \"no_aplica\"\n      ]\n    },\n    \"resumen\": {\n      \"type\": \"string\"\n    },\n    \"fuera_de_tabla\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"string\"\n      }\n    }\n  },\n  \"required\": [\n    \"respuesta\",\n    \"accion\"\n  ]\n}"
      },
      "id": "5113af40-a519-4677-ae47-77db8f33ad5f",
      "name": "Formato de respuesta",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        1920,
        660
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// The model picks the rows; the totals and the message are computed here, so the numbers always add up.\nconst ctx = $('Lee el mensaje').item.json;\nconst cfg = $('Datos del taller').first().json;\nconst o = $json.output ?? {};\nconst corta = (s, n) => String(s ?? '').replace(/\\s+/g, ' ').trim().slice(0, n);\nconst dinero = (n) => '$' + Math.round(n).toLocaleString('en-US');\n\nconst piezas = (Array.isArray(o.piezas) ? o.piezas : []).filter(\n  (p) => p && Number.isFinite(Number(p.minimo)) && Number.isFinite(Number(p.maximo)) && Number(p.maximo) >= Number(p.minimo) && Number(p.minimo) > 0,\n);\nlet accion = o.accion || 'responder';\nif (accion === 'cotizar' && (ctx.tipo !== 'foto' || piezas.length === 0)) accion = 'pedir_foto';\n\nconst min = piezas.reduce((s, p) => s + Number(p.minimo), 0);\nconst max = piezas.reduce((s, p) => s + Number(p.maximo), 0);\nconst rango = accion === 'cotizar' ? `${dinero(min)} – ${dinero(max)} ${cfg.moneda}` : '';\nconst resumen = corta(o.resumen || piezas.map((p) => p.pieza).join(', '), 45);\nconst fuera = (Array.isArray(o.fuera_de_tabla) ? o.fuera_de_tabla : []).map((s) => corta(s, 40)).filter(Boolean);\n\nlet texto = corta(o.respuesta, 600) || 'Gracias por escribirnos.';\nif (accion === 'cotizar') {\n  const lista = piezas.map((p) => `• ${corta(p.pieza, 30)} (${corta(p.dano, 30)}): ${dinero(p.minimo)} – ${dinero(p.maximo)}`).join('\\n');\n  texto = [\n    texto,\n    lista,\n    `*Presupuesto estimado: ${rango}*`,\n    fuera.length ? `Esto lo revisamos en persona: ${fuera.join(', ')}.` : '',\n    'El precio final te lo confirmamos en la revisión, sin costo.',\n  ].filter(Boolean).join('\\n\\n').slice(0, 1000);\n}\n\nconst salida = {\n  json: { accion, texto, rango, resumen, gravedad: o.gravedad ?? 'no_aplica', telefono: ctx.telefono, phoneNumberId: ctx.phoneNumberId, nombre: corta(ctx.nombre, 30) },\n};\n// the photo travels on to be uploaded once, so the owner's alert can show it later\nif (accion === 'cotizar') salida.binary = $('Descarga la foto').item.binary;\nreturn salida;"
      },
      "id": "380ce140-cf4c-4563-a49a-f0e87cac13d3",
      "name": "Prepara el presupuesto",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1960,
        400
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "747635ee-56fc-4248-af75-bba9582308f2",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "cotizar",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Cotiza"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "Responde"
        }
      },
      "id": "e5f29e8f-1716-4192-ac68-2b557497cb32",
      "name": "¿Qué hace?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        2180,
        400
      ]
    },
    {
      "parameters": {
        "resource": "media",
        "operation": "mediaUpload",
        "phoneNumberId": "={{ $json.phoneNumberId }}",
        "mediaPropertyName": "data",
        "additionalFields": {}
      },
      "id": "b820ad91-70bf-4242-ae1d-ee865766d01c",
      "name": "Sube la foto",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        2400,
        260
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v23.0/{{ $('Prepara el presupuesto').item.json.phoneNumberId }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', recipient_type: 'individual', to: $('Prepara el presupuesto').item.json.telefono, type: 'interactive', interactive: { type: 'button', body: { text: $('Prepara el presupuesto').item.json.texto }, action: { buttons: [{ type: 'reply', reply: { id: JSON.stringify({ a: 'agendar', r: $('Prepara el presupuesto').item.json.resumen, p: $('Prepara el presupuesto').item.json.rango, m: $json.id, n: $('Prepara el presupuesto').item.json.nombre }).slice(0, 256), title: 'Agendar revisión' } }] } } }) }}",
        "options": {}
      },
      "id": "6c345f4a-cab5-47e0-a8bb-5ae3b331861c",
      "name": "Envía presupuesto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2620,
        260
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "phoneNumberId": "={{ $json.phoneNumberId }}",
        "recipientPhoneNumber": "={{ $json.telefono }}",
        "textBody": "={{ $json.texto }}",
        "additionalFields": {}
      },
      "id": "af4263b3-71cc-4e6d-a6f6-06c768c46cf6",
      "name": "Responde",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        2400,
        520
      ]
    },
    {
      "parameters": {
        "resource": "event",
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "returnAll": true,
        "timeMin": "={{ $now.toISO() }}",
        "timeMax": "={{ $now.plus({ days: 5 }).toISO() }}",
        "options": {
          "orderBy": "startTime"
        }
      },
      "id": "81e3150d-71af-431c-a088-ef8ae4a366c6",
      "name": "Citas próximas",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        900,
        760
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "// Up to 3 free review times in the next working days, avoiding existing events.\nconst cfg = $('Datos del taller').first().json;\nconst ctx = $('Lee el mensaje').first().json;\nconst zona = cfg.zonaHoraria;\nconst dur = Number(cfg.minutosRevision) || 20;\nconst lista = (s) => String(s ?? '').split(',').map((h) => h.trim()).filter(Boolean);\nconst horas = lista(cfg.horasRevision);\nconst horasSabado = cfg.horasRevisionSabado ? lista(cfg.horasRevisionSabado) : horas;\nconst dias = String(cfg.diasRevision).split(',').map(Number);\n\nconst ocupado = $input.all()\n  .map((i) => i.json)\n  .filter((e) => e.start?.dateTime && e.end?.dateTime)\n  .map((e) => [DateTime.fromISO(e.start.dateTime), DateTime.fromISO(e.end.dateTime)]);\n\nconst libres = [];\nconst desde = $now.setZone(zona).plus({ hours: 2 });\nfor (let d = 0; d < 7 && libres.length < 3; d++) {\n  const dia = $now.setZone(zona).plus({ days: d }).startOf('day');\n  if (!dias.includes(dia.weekday)) continue;\n  for (const h of dia.weekday === 6 ? horasSabado : horas) {\n    const [hh, mm] = h.split(':').map(Number);\n    const ini = dia.set({ hour: hh, minute: mm || 0 });\n    const fin = ini.plus({ minutes: dur });\n    if (ini < desde) continue;\n    if (ocupado.some(([a, b]) => ini < b && fin > a)) continue;\n    libres.push(ini);\n    if (libres.length === 3) break;\n  }\n}\n\nconst botones = libres.map((ini) => ({\n  type: 'reply',\n  reply: {\n    id: JSON.stringify({ a: 'cita', i: ini.toISO({ suppressMilliseconds: true }), r: ctx.resumen, p: ctx.rango, m: ctx.fotoId, n: ctx.nombre }).slice(0, 256),\n    title: ini.setLocale('es').toFormat(\"ccc d · HH:mm\").replace(/^./, (c) => c.toUpperCase()).slice(0, 20),\n  },\n}));\nreturn [{\n  json: {\n    telefono: ctx.telefono,\n    phoneNumberId: ctx.phoneNumberId,\n    botones,\n    texto: botones.length ? '¡Va! ¿Qué horario te queda para la revisión? Dura unos ' + dur + ' minutos.' : 'Esta semana ya no tenemos horarios libres. Un asesor te escribe para buscar uno.',\n  },\n}];"
      },
      "id": "ff9b4639-0777-4aa7-afe2-ffacc3947671",
      "name": "Busca horarios",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1120,
        760
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "47b24d36-05b2-4af1-a09c-7906a880f9d6",
              "leftValue": "={{ $json.botones.length }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "2013f1a1-4efc-4d21-a636-2fc703e1f8b3",
      "name": "¿Hay horarios?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1340,
        760
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v23.0/{{ $json.phoneNumberId }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', recipient_type: 'individual', to: $json.telefono, type: 'interactive', interactive: { type: 'button', body: { text: $json.texto }, action: { buttons: $json.botones } } }) }}",
        "options": {}
      },
      "id": "353dd003-1bee-4868-a78d-80ea1921117e",
      "name": "Envía horarios",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1560,
        700
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "phoneNumberId": "={{ $json.phoneNumberId }}",
        "recipientPhoneNumber": "={{ $json.telefono }}",
        "textBody": "={{ $json.texto }}",
        "additionalFields": {}
      },
      "id": "d94ddb47-a1d6-4761-a2c8-12529af508a7",
      "name": "Sin horarios",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        1560,
        880
      ]
    },
    {
      "parameters": {
        "mode": "manual",
        "assignments": {
          "assignments": [
            {
              "id": "5936b210-417d-493e-acde-f31252167b94",
              "name": "telefono",
              "value": "={{ $json.telefono }}",
              "type": "string"
            },
            {
              "id": "427ff9ac-f75b-4972-a7d5-0c8bedefe752",
              "name": "phoneNumberId",
              "value": "={{ $json.phoneNumberId }}",
              "type": "string"
            },
            {
              "id": "2b5d5d57-2504-44d4-a33f-172f19d27d29",
              "name": "nombre",
              "value": "={{ $json.nombre || 'Cliente' }}",
              "type": "string"
            },
            {
              "id": "5e70d5e8-f1bf-4a4b-a604-7fee1761619f",
              "name": "resumen",
              "value": "={{ $json.resumen || 'Revisión de carrocería' }}",
              "type": "string"
            },
            {
              "id": "93258860-9ff4-462b-a8d6-13ab6884f294",
              "name": "rango",
              "value": "={{ $json.rango || 'por definir' }}",
              "type": "string"
            },
            {
              "id": "d2ccd124-97d1-40b4-ae39-67330eff0035",
              "name": "fotoId",
              "value": "={{ $json.fotoId }}",
              "type": "string"
            },
            {
              "id": "7e8bd6b2-e339-4d13-a559-42cf8e1f208a",
              "name": "inicio",
              "value": "={{ DateTime.fromISO($json.inicio, { setZone: true }).toISO() }}",
              "type": "string"
            },
            {
              "id": "10d8d6d5-6b31-4023-a5fd-260a4f938f4a",
              "name": "fin",
              "value": "={{ DateTime.fromISO($json.inicio, { setZone: true }).plus({ minutes: Number($('Datos del taller').first().json.minutosRevision) || 20 }).toISO() }}",
              "type": "string"
            },
            {
              "id": "f163e9d1-a32c-4338-afcb-f56f35aa1d15",
              "name": "inicioLegible",
              "value": "={{ DateTime.fromISO($json.inicio, { setZone: true }).setLocale('es').toFormat(\"cccc d 'de' LLLL 'a las' HH:mm\") }}",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      },
      "id": "463c1a20-fa9b-44fd-a4fd-b0a12ddfb3ba",
      "name": "Datos de la cita",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        900,
        1080
      ]
    },
    {
      "parameters": {
        "resource": "calendar",
        "operation": "availability",
        "calendar": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "timeMin": "={{ $json.inicio }}",
        "timeMax": "={{ $json.fin }}",
        "options": {
          "outputFormat": "availability"
        }
      },
      "id": "ca396a57-649d-44d5-ab02-77d873f2d67e",
      "name": "¿Sigue libre?",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        1120,
        1080
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "9bc22f64-0f8d-457b-a4cf-1f7c77340a8f",
              "leftValue": "={{ $json.available }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c45defd0-23fa-4f1b-a311-6d89bb6d7939",
      "name": "¿Libre?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1340,
        1080
      ]
    },
    {
      "parameters": {
        "resource": "event",
        "operation": "create",
        "calendar": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "start": "={{ $('Datos de la cita').item.json.inicio }}",
        "end": "={{ $('Datos de la cita').item.json.fin }}",
        "additionalFields": {
          "summary": "=🔧 Revisión · {{ $('Datos de la cita').item.json.nombre }} · {{ $('Datos de la cita').item.json.resumen }}",
          "description": "=Cliente: {{ $('Datos de la cita').item.json.nombre }}\nWhatsApp: +{{ $('Datos de la cita').item.json.telefono }}\nDaño: {{ $('Datos de la cita').item.json.resumen }}\nPresupuesto estimado: {{ $('Datos de la cita').item.json.rango }}\nAgendada por el Cotizador IA",
          "location": "={{ $('Datos del taller').first().json.direccion }}"
        }
      },
      "id": "3e6d76e1-0f45-4b55-aea8-90472be1db8e",
      "name": "Agenda revisión",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        1560,
        1000
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "phoneNumberId": "={{ $('Datos de la cita').item.json.phoneNumberId }}",
        "recipientPhoneNumber": "={{ $('Datos de la cita').item.json.telefono }}",
        "textBody": "=¡Listo, {{ $('Datos de la cita').item.json.nombre }}! ✅ Te esperamos el {{ $('Datos de la cita').item.json.inicioLegible }} para revisar tu carro. Te mando la ubicación.",
        "additionalFields": {}
      },
      "id": "0ec2782c-cf7b-4b8a-a4e8-c12d12405b1d",
      "name": "Confirma la cita",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        1800,
        900
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "phoneNumberId": "={{ $('Datos de la cita').item.json.phoneNumberId }}",
        "recipientPhoneNumber": "={{ $('Datos de la cita').item.json.telefono }}",
        "messageType": "location",
        "longitude": "={{ $('Datos del taller').first().json.longitud }}",
        "latitude": "={{ $('Datos del taller').first().json.latitud }}"
      },
      "id": "cfe1316a-bc46-412d-a25c-6acea98e210e",
      "name": "Envía ubicación",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        2020,
        900
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "Clientes",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Registrado": "={{ $now.toISO() }}",
            "Nombre": "={{ $('Datos de la cita').item.json.nombre }}",
            "WhatsApp": "={{ $('Datos de la cita').item.json.telefono }}",
            "Daño": "={{ $('Datos de la cita').item.json.resumen }}",
            "Presupuesto": "={{ $('Datos de la cita').item.json.rango }}",
            "Revisión": "={{ $('Datos de la cita').item.json.inicio }}",
            "Evento": "={{ $json.id }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Registrado",
              "displayName": "Registrado",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Nombre",
              "displayName": "Nombre",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "WhatsApp",
              "displayName": "WhatsApp",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Daño",
              "displayName": "Daño",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Presupuesto",
              "displayName": "Presupuesto",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Revisión",
              "displayName": "Revisión",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Evento",
              "displayName": "Evento",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "c99b865a-53e0-4e32-ab38-09c4c420c3bb",
      "name": "Guarda cliente",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1800,
        1080
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "phoneNumberId": "={{ $('Datos de la cita').item.json.phoneNumberId }}",
        "recipientPhoneNumber": "={{ $('Datos de la cita').item.json.telefono }}",
        "textBody": "=Uy, ese horario se acaba de ocupar 😅 Toca otra vez \"Agendar revisión\" y te muestro los siguientes.",
        "additionalFields": {}
      },
      "id": "fd4d0ba0-5eaf-4414-a0bb-9bbb2ce60fcf",
      "name": "Horario ocupado",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        1560,
        1200
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v23.0/{{ $('Datos de la cita').item.json.phoneNumberId }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $('Datos del taller').first().json.telefonoDueno, type: 'template', template: { name: 'nuevo_cliente', language: { code: $('Datos del taller').first().json.idiomaPlantillas }, components: [].concat($('Datos de la cita').item.json.fotoId ? [{ type: 'header', parameters: [{ type: 'image', image: { id: $('Datos de la cita').item.json.fotoId } }] }] : [], [{ type: 'body', parameters: [{ type: 'text', text: $('Datos de la cita').item.json.nombre + ' (+' + $('Datos de la cita').item.json.telefono + ')' }, { type: 'text', text: $('Datos de la cita').item.json.resumen }, { type: 'text', text: $('Datos de la cita').item.json.rango }, { type: 'text', text: $('Datos de la cita').item.json.inicioLegible }] }]) } }) }}",
        "options": {}
      },
      "id": "8beffc9e-46e6-4a89-a8ac-01ac8fbe03d7",
      "name": "Aviso al dueño",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1800,
        1260
      ]
    },
    {
      "parameters": {
        "content": "## 1 · Recibe\nEntra el mensaje de WhatsApp. Si es una foto, se descarga para que la IA la vea. Los botones (\"Agendar revisión\" y los horarios) llevan sus datos y van directo a su paso.",
        "height": 520,
        "width": 1540,
        "color": 5
      },
      "id": "870043c6-984a-4eac-ae22-2a50e99bf251",
      "name": "Nota 1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -80,
        80
      ]
    },
    {
      "parameters": {
        "content": "## 2 · Analiza\nEl Cotizador IA (Claude con visión) identifica piezas, daño y gravedad, y toma los precios de TU tabla. Los totales se calculan aparte para que siempre cuadren.",
        "height": 740,
        "width": 700,
        "color": 3
      },
      "id": "4517e754-9d07-4399-a6d8-4c284158334f",
      "name": "Nota 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1400,
        80
      ]
    },
    {
      "parameters": {
        "content": "## 3 · Cotiza\nManda el presupuesto con el botón \"Agendar revisión\". La foto se sube a WhatsApp una vez para usarla en el aviso al dueño.",
        "height": 740,
        "width": 740,
        "color": 4
      },
      "id": "d1750453-fd5c-4060-aa97-1d4fef8ac1fb",
      "name": "Nota 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2120,
        80
      ]
    },
    {
      "parameters": {
        "content": "## Agenda y avisa\nAl tocar \"Agendar revisión\" se ofrecen los siguientes horarios libres. Al elegir uno: se verifica, se crea la cita, se confirma con ubicación, se guarda el cliente y el dueño recibe el aviso con la foto, el daño y el presupuesto.",
        "height": 760,
        "width": 2320,
        "color": 6
      },
      "id": "ec96741a-d9e3-4808-aa50-ebed122579dd",
      "name": "Nota 4",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -80,
        640
      ]
    },
    {
      "parameters": {
        "content": "## Antes de activar\n1. Llena **Datos del taller** (dirección, horarios de revisión, WhatsApp del dueño).\n2. Credenciales: WhatsApp (API de Cloud de Meta) en los nodos de WhatsApp y en los HTTP Request; Anthropic en *Claude*; Google en Calendar y Sheets.\n3. Google Sheet con dos pestañas: **Precios** (Pieza, Daño, Mínimo, Máximo, Notas) y **Clientes** (Registrado, Nombre, WhatsApp, Daño, Presupuesto, Revisión, Evento). Hay una tabla de ejemplo en precios-ejemplo.csv.\n4. Elige el calendario en *Citas próximas*, *¿Sigue libre?* y *Agenda revisión*.\n5. Crea y aprueba en Meta la plantilla *nuevo_cliente* (el texto está en la página donde descargaste el flujo).\n6. Publica el flujo (**Publish**): n8n registra solo el webhook en tu app de Meta con la credencial WhatsApp OAuth.",
        "height": 460,
        "width": 1000,
        "color": 7
      },
      "id": "5ba8105d-f64a-4f27-ad58-a87494628b19",
      "name": "Nota configuración",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -80,
        -420
      ]
    }
  ],
  "connections": {
    "WhatsApp Trigger": {
      "main": [
        [
          {
            "node": "Datos del taller",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Datos del taller": {
      "main": [
        [
          {
            "node": "Lee el mensaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lee el mensaje": {
      "main": [
        [
          {
            "node": "Tipo de mensaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tipo de mensaje": {
      "main": [
        [
          {
            "node": "Obtén la foto",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Citas próximas",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Datos de la cita",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Cotizador IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obtén la foto": {
      "main": [
        [
          {
            "node": "Descarga la foto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Descarga la foto": {
      "main": [
        [
          {
            "node": "Cotizador IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude": {
      "ai_languageModel": [
        [
          {
            "node": "Cotizador IA",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Memoria": {
      "ai_memory": [
        [
          {
            "node": "Cotizador IA",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Precios": {
      "ai_tool": [
        [
          {
            "node": "Cotizador IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Formato de respuesta": {
      "ai_outputParser": [
        [
          {
            "node": "Cotizador IA",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Cotizador IA": {
      "main": [
        [
          {
            "node": "Prepara el presupuesto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepara el presupuesto": {
      "main": [
        [
          {
            "node": "¿Qué hace?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Qué hace?": {
      "main": [
        [
          {
            "node": "Sube la foto",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Responde",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sube la foto": {
      "main": [
        [
          {
            "node": "Envía presupuesto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Citas próximas": {
      "main": [
        [
          {
            "node": "Busca horarios",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Busca horarios": {
      "main": [
        [
          {
            "node": "¿Hay horarios?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Hay horarios?": {
      "main": [
        [
          {
            "node": "Envía horarios",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Sin horarios",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Datos de la cita": {
      "main": [
        [
          {
            "node": "¿Sigue libre?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Sigue libre?": {
      "main": [
        [
          {
            "node": "¿Libre?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Libre?": {
      "main": [
        [
          {
            "node": "Agenda revisión",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Horario ocupado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Agenda revisión": {
      "main": [
        [
          {
            "node": "Confirma la cita",
            "type": "main",
            "index": 0
          },
          {
            "node": "Guarda cliente",
            "type": "main",
            "index": 0
          },
          {
            "node": "Aviso al dueño",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confirma la cita": {
      "main": [
        [
          {
            "node": "Envía ubicación",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Mexico_City",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
