{ "name": "[1604][Monte Providencia] Sincronización de Contactos - Sucursal a Marca - Crear Contacto", "nodes": [ { "parameters": { "content": "# De Sucursal a Marca", "color": 5 }, "type": "n8n-nodes-base.stickyNote", "position": [ -720, -16 ], "typeVersion": 1, "id": "bbc867b4-5b4c-4a67-8cd8-da5789f2b86a", "name": "Sticky Note3" }, { "parameters": { "httpMethod": "POST", "path": "56c4c1a9-0271-48e5-8915-e25e18666dce", "options": {} }, "type": "n8n-nodes-base.webhook", "typeVersion": 2.1, "position": [ -448, 0 ], "id": "252b4629-34b1-4b02-bb26-6153eed0370f", "name": "Crear Contacto", "webhookId": "56c4c1a9-0271-48e5-8915-e25e18666dce" }, { "parameters": { "method": "POST", "url": "=https://services.leadconnectorhq.com/contacts", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={\n \"firstName\": \"{{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.firstName }}\",\n \"lastName\": \"{{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.lastName }}\",\n \"name\": \"{{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.firstName }} {{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.lastName }}\",\n \"email\": \"{{ $('DATOS CUENTA OBJETIVO').item.json.Contacto.email }}\",\n \"phone\": \"{{ $('DATOS CUENTA OBJETIVO').item.json.Contacto['Teléfono'] }}\",\n \"locationId\": \"{{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}\",\n \"country\": \"MX\",\n \"tags\": [\"sucursal\"]\n}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 7200, 768 ], "id": "8ef40825-1c08-43b0-a71c-c7c259879cb5", "name": "Crear Contacto - Cuenta Objetivo - SUCURSAL1" }, { "parameters": { "method": "PUT", "url": "=https://services.leadconnectorhq.com/contacts/{{ $('Obtener Contacto Cuenta objetivo - SUCURSAL').item.json.contact.id }}", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ $json.body }}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 6368, -368 ], "id": "c9ecb29a-3c27-4aa8-9b6b-f8026571b648", "name": "Actualizar Contacto Cuenta Objetivo - SUCURSAL" }, { "parameters": { "method": "POST", "url": "https://services.leadconnectorhq.com/opportunities/", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={\n \"locationId\": \"{{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}\",\n \"contactId\": \"{{ $('Crear Contacto - Cuenta Objetivo - SUCURSAL').item.json.contact.id }}\",\n \"name\": \"{{ $('Datos de Lead').item.json.Cliente['Nombre Completo'] }}\",\n \"pipelineId\": \"{{ $json.pipelines[0].id }}\",\n \"pipelineStageId\": \"{{ $json.pipelines[0].stages[0].id }}\",\n \"status\": \"open\",\n \"monetaryValue\": 0\n}", "options": {} }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 6816, -240 ], "id": "f23f1cf1-3bbb-4c18-badf-76b56a58fd9a", "name": "Crear Oportunidad" }, { "parameters": { "url": "https://services.leadconnectorhq.com/opportunities/pipelines", "sendQuery": true, "queryParameters": { "parameters": [ { "name": "locationId", "value": "={{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}" } ] }, "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "bodyParameters": { "parameters": [ {} ] }, "options": {} }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 6608, -240 ], "id": "7bfe660c-93e4-47ea-9e50-2c45417c2d01", "name": "Obtener Pipelines" }, { "parameters": { "method": "POST", "url": "https://services.leadconnectorhq.com/contacts", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "Bearer $TOKEN" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ $json.body }}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 6112, -976 ], "id": "f86b4860-06e2-4a1e-b324-1398a0ea2e52", "name": "Crear Contacto1" }, { "parameters": { "content": "# CUENTA ORIGEN", "height": 240, "width": 1344 }, "type": "n8n-nodes-base.stickyNote", "position": [ 384, -352 ], "typeVersion": 1, "id": "af4bbbc9-7b58-44e6-af94-904a060c6fc4", "name": "Sticky Note" }, { "parameters": { "content": "", "height": 176, "width": 608, "color": 7 }, "type": "n8n-nodes-base.stickyNote", "position": [ 912, -304 ], "typeVersion": 1, "id": "252eedcc-8f6b-477d-8e1e-37f30b82e55a", "name": "Sticky Note1" }, { "parameters": { "content": "# CUENTA OBJETIVO", "height": 240, "width": 384 }, "type": "n8n-nodes-base.stickyNote", "position": [ 2352, -352 ], "typeVersion": 1, "id": "5a42084e-7607-41c2-8ac9-87e44ca82dd3", "name": "Sticky Note2" }, { "parameters": { "content": "# REVISIÓN SIEMPRE", "height": 240, "width": 352, "color": 3 }, "type": "n8n-nodes-base.stickyNote", "position": [ 1984, -352 ], "typeVersion": 1, "id": "811dbcc5-5ee0-4544-8fc6-536ec32780b0", "name": "Sticky Note5" }, { "parameters": { "content": "# BÚSQUEDA EN CASCADA\n## phone → email → nombre\n## Validación: contacts.length == 1", "height": 480, "width": 1900, "color": 6 }, "type": "n8n-nodes-base.stickyNote", "position": [ 2784, -480 ], "typeVersion": 1, "id": "ad1a9809-b6cb-4d4e-8b74-f5d3de07a604", "name": "Sticky Note Busqueda" }, { "parameters": { "content": "# Crear Contacto", "height": 288, "width": 816, "color": 4 }, "type": "n8n-nodes-base.stickyNote", "position": [ 4800, -144 ], "typeVersion": 1, "id": "b52d74d7-ac0d-4d95-b8bc-45f53ff3d95a", "name": "Sticky Note6" }, { "parameters": { "content": "# Actualizar Contacto", "height": 240, "width": 1392, "color": 7 }, "type": "n8n-nodes-base.stickyNote", "position": [ 4784, -672 ], "typeVersion": 1, "id": "9a48adc1-522e-4772-a996-4ca76f163f8d", "name": "Sticky Note4" }, { "parameters": { "assignments": { "assignments": [ { "id": "8a998fd4-2de6-4895-ab3d-e052e823d1b8", "name": "Cliente.Fuente Posible Cliente", "value": "={{ $json.body['Fuente de Posible cliente'] }}", "type": "string" }, { "id": "938c6fec-ae16-4e7a-ba2a-f450794fa40d", "name": "Cliente.Fecha de creación", "value": "={{ $json.body.date_created }}", "type": "string" }, { "id": "b56a1939-2608-47c8-85ad-b60b557d2a27", "name": "Cliente.Sucursal.Sucursal", "value": "={{ $json.body.Sucursal }}", "type": "string" }, { "id": "0d07b9c9-4450-497b-ab81-3baa441787fb", "name": "Vehiculo.Versión.Versión", "value": "={{ $json.body['Version del Vehiculo'] }}", "type": "string" }, { "id": "75e3f337-00d1-429d-8d5b-85ec18e6c5e4", "name": "Vehiculo.Marca.Marca", "value": "={{ $json.body['Marca del Vehiculo'] }}", "type": "string" }, { "id": "cb09c536-fe84-4598-aaae-aa79f2eda61b", "name": "Vehiculo.Marca.fieldKey", "value": "=contact.marca_del_vehiculo", "type": "string" }, { "id": "17d36409-4c54-48dd-8100-f7f667fd2415", "name": "Vehiculo.Año.Año", "value": "={{ $json.body['Año del Vehículo'] }}", "type": "string" }, { "id": "a1886afc-b0af-4950-9752-f8bfff594896", "name": "Vehiculo.Modalidad.Modalidad", "value": "={{ $json.body['¿Qué modalidad prefieres?'] }}", "type": "string" }, { "id": "33b2c28a-1ad3-4c74-917f-3cd718a3a709", "name": "Cliente.Nombre", "value": "={{ $json.body.first_name }}", "type": "string" }, { "id": "b36131ac-2d88-41f8-8f0f-7640cdb02b57", "name": "Cliente.Apellido", "value": "={{ $json.body.last_name }}", "type": "string" }, { "id": "f1f1f1f1-aaaa-bbbb-cccc-111111111111", "name": "Cliente.Información Adicional", "value": "={{ $json.body['Información Adicional'] }}", "type": "string" }, { "id": "ae252c8f-f0a1-41d9-a21d-04ca949f01c8", "name": "Cliente.Nombre Completo", "value": "={{ $json.body.full_name }}", "type": "string" }, { "id": "342a9377-0ded-4f23-b93b-1f76e57c0cbd", "name": "Cliente.Email", "value": "={{ $json.body.email }}", "type": "string" }, { "id": "cf1b7058-96c2-4c73-9250-719a88b68673", "name": "Cliente.Telefono", "value": "={{ $json.body.phone }}", "type": "string" }, { "id": "0b916193-15e8-4a91-9ff2-0a6f262b3c38", "name": "Cliente.Contact ID", "value": "={{ $json.body.contact_id }}", "type": "string" }, { "id": "67eeaa9b-f703-4521-82af-9d2797131edc", "name": "Cliente.Sucursal.fieldKey", "value": "contact.sucursal", "type": "string" }, { "id": "b05ea7bb-bbaa-467b-8247-eabb162ff029", "name": "Vehiculo.Versión.fieldKey", "value": "contact.version_del_vehiculo", "type": "string" }, { "id": "9891b919-ef4c-46bd-8414-6d916565d896", "name": "Vehiculo.Año.fieldKey", "value": "contact.ano_del_vehiculo", "type": "string" }, { "id": "0b6bf582-49c1-41de-9c2e-6ae85c4e41e8", "name": "Vehiculo.Modalidad.fieldKey", "value": "contact.que_modalidad_prefieres", "type": "string" }, { "id": "57199999-2d9b-41c7-8269-5a8183ca8132", "name": "Cliente.Cuándo necesitas el dinero", "value": "={{ $json.body[\"¿Cuándo necesitas el dinero?\"] }}", "type": "string" }, { "id": "8060d06e-b1da-4a65-8a0a-3c21d237d77e", "name": "Sucursal.Cuenta Bucéfalo", "value": "={{ $json.body.location.name }}", "type": "string" } ] }, "options": {} }, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [ -208, -272 ], "id": "ecded6ac-c2a5-4ae9-bc37-d8d56868dd18", "name": "Datos de Lead" }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "44d54b9e-d192-4b54-bf0c-156b79afc6e2", "leftValue": "={{ $json.Cliente.Email }}", "rightValue": "@ezcorp.com", "operator": { "type": "string", "operation": "notContains" } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2.3, "position": [ -32, -272 ], "id": "3473ecc3-42b1-4261-b83f-1b11d455055d", "name": "Omitir @ezcorp.com" }, { "parameters": { "databaseId": 63, "tableId": 749, "additionalOptions": { "filters": { "fields": [ { "field": 7235, "value": "={{ $('Datos de Lead').item.json.Sucursal['Cuenta Bucéfalo'] }}" } ] } } }, "type": "n8n-nodes-base.baserow", "typeVersion": 1, "position": [ 448, -288 ], "id": "727100e5-61a5-42c5-ab78-f70f0185f47c", "name": "Obtener Info de cuenta origen - SUCURSAL", "credentials": { "baserowApi": { "id": "LZztQ3WMpzXjSTIH", "name": "Baserow account" } } }, { "parameters": { "url": "=https://services.leadconnectorhq.com/contacts/{{ $('Datos de Lead').item.json.Cliente['Contact ID'] }}", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $json.API_token }}" } ] }, "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 960, -288 ], "id": "d06dd04f-f8bd-4a82-aff0-b2c396398a70", "name": "Obtener Contacto Cuenta Origen - SUCURSAL" }, { "parameters": { "url": "=https://services.leadconnectorhq.com/locations/{{ $json.contact.locationId }}/customFields", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Obtener Info de cuenta origen - SUCURSAL').item.json.API_token }}" } ] }, "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 1136, -288 ], "id": "be834d45-2a5b-48eb-be23-a1661023aa16", "name": "Conseguir Custom Cuenta Origen- SUCURSAL" }, { "parameters": { "jsCode": "// Inputs\nconst contactData = $('Obtener Contacto Cuenta Origen - SUCURSAL').first().json.contact;\nconst allCustomFieldItems = $('Conseguir Custom Cuenta Origen- SUCURSAL').all();\n\n// Consolidar TODOS los customFields de todos los items del nodo\nconst allFieldDefs = [];\nfor (const item of allCustomFieldItems) {\n const fields = item.json.customFields || [];\n allFieldDefs.push(...fields);\n}\n\n// Crear mapa id -> definición completa\nconst fieldKeyMap = {};\nfor (const field of allFieldDefs) {\n fieldKeyMap[field.id] = {\n fieldKey: field.fieldKey,\n name: field.name,\n dataType: field.dataType\n };\n}\n\n// Enriquecer los customFields del contacto con su fieldKey\nconst enrichedCustomFields = [];\nfor (const cf of contactData.customFields) {\n const def = fieldKeyMap[cf.id];\n if (def) {\n enrichedCustomFields.push({\n id: cf.id,\n fieldKey: def.fieldKey,\n name: def.name,\n dataType: def.dataType,\n value: cf.value\n });\n } else {\n enrichedCustomFields.push({\n id: cf.id,\n fieldKey: null,\n name: null,\n dataType: null,\n value: cf.value\n });\n }\n}\n\nconst contactoOrigen = {\n id: contactData.id,\n firstName: contactData.firstName,\n lastName: contactData.lastName,\n email: contactData.email,\n country: contactData.country,\n locationId: contactData.locationId,\n type: contactData.type,\n tags: contactData.tags,\n dateAdded: contactData.dateAdded,\n dateUpdated: contactData.dateUpdated,\n additionalEmails: contactData.additionalEmails,\n additionalPhones: contactData.additionalPhones,\n customFields: enrichedCustomFields\n};\n\nreturn [{ json: contactoOrigen }];" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1328, -288 ], "id": "bc00413e-9137-4976-8b54-bb1cf1b09d5d", "name": "Obtener datos completos de Contacto origen - SUCURSAL" }, { "parameters": { "jsCode": "const contact = $input.first().json;\n\nconst contactoOrigen = {\n id: contact.id,\n firstName: contact.firstName,\n lastName: contact.lastName,\n email: contact.email,\n country: contact.country,\n locationId: contact.locationId,\n type: contact.type,\n tags: contact.tags,\n dateAdded: contact.dateAdded,\n dateUpdated: contact.dateUpdated,\n additionalEmails: contact.additionalEmails,\n additionalPhones: contact.additionalPhones,\n};\n\nfor (const cf of contact.customFields) {\n contactoOrigen[cf.fieldKey] = cf.value;\n}\n\nreturn [{ json: contactoOrigen }];" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1568, -288 ], "id": "e42366ec-c70a-4931-a27f-7ddde267cc80", "name": "Mapear Custom Fields Cuenta Origen - SUCURSAL" }, { "parameters": { "assignments": { "assignments": [ { "id": "c9958fbd-2f2a-4bab-94b4-cb6a6525257d", "name": "Cuenta Objetivo", "value": "Monte Providencia", "type": "string" }, { "id": "61d28849-1504-476d-b754-1ae255fc9a12", "name": "Contacto.Nombre", "value": "={{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.firstName }}", "type": "string" }, { "id": "096deddd-c321-42b6-a36c-94271101a41c", "name": "Contacto.Apellidos", "value": "={{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.lastName }}", "type": "string" }, { "id": "9171bd91-7d9c-4f44-8fd4-0a18c738a205", "name": "Contacto.email", "value": "={{ $('Obtener datos completos de Contacto origen - SUCURSAL').item.json.email }}", "type": "string" }, { "id": "13a56235-9c5a-4b13-94fe-44c4bf92d053", "name": "Name Location", "value": "={{ $('Crear Contacto').item.json.body.location.name }}", "type": "string" }, { "id": "c986998a-abb9-44c7-a5de-c3a796c60006", "name": "Contacto.Teléfono", "value": "={{ $('Datos de Lead').item.json.Cliente.Telefono }}", "type": "string" }, { "id": "e19f43bf-6668-4752-a2c2-815d9cb09c1c", "name": "contact.sucursal", "value": "={{ $json['contact.sucursal'] }}", "type": "string" } ] }, "options": {} }, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [ 2112, -288 ], "id": "1f1ea13e-937f-411a-9d44-1b3acfeec2e8", "name": "DATOS CUENTA OBJETIVO" }, { "parameters": { "databaseId": 63, "tableId": 749, "additionalOptions": { "filters": { "fields": [ { "field": 7235, "value": "={{ $json['Cuenta Objetivo'] }}" } ] } } }, "type": "n8n-nodes-base.baserow", "typeVersion": 1, "position": [ 2400, -288 ], "id": "9cc3fcbc-8bbe-479c-9b83-1508dfee0740", "name": "Obtener Info de cuenta objetivo - MARCA", "credentials": { "baserowApi": { "id": "LZztQ3WMpzXjSTIH", "name": "Baserow account" } } }, { "parameters": { "assignments": { "assignments": [ { "id": "55ff7d12-17b9-4bec-a324-e633020b131d", "name": "Name Location", "value": "={{ $('Obtener Info de cuenta objetivo - MARCA').item.json.Nombre }}", "type": "string" }, { "id": "d877c8cd-db32-4c16-96dd-4eeb2dc48efe", "name": "Location ID", "value": "={{ $('Obtener Info de cuenta objetivo - MARCA').item.json.Location_ID }}", "type": "string" }, { "id": "7698f395-5db8-415b-919e-3ad61c6566f8", "name": "Token/API", "value": "={{ $('Obtener Info de cuenta objetivo - MARCA').item.json.API_token }}", "type": "string" } ] }, "options": {} }, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [ 2592, -288 ], "id": "4c0e2b00-48ba-49ca-850e-95d2757cee60", "name": "Datos API Cuenta objetivo - MARCA" }, { "parameters": { "method": "POST", "url": "https://services.leadconnectorhq.com/contacts/search", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={\n \"locationId\": \"{{ $json['Location ID'] }}\",\n \"pageLimit\": 20,\n \"query\":\"{{ $('DATOS CUENTA OBJETIVO').item.json.Contacto['Teléfono'] }}\"\n}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 2832, -288 ], "id": "b036ee0c-487a-4015-b80f-eb0aa7e68e9f", "name": "Buscar Contacto Objetivo - MARCA (phone)" }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "p1111111-1111-4111-8111-111111111111", "leftValue": "={{ $json.contacts.length }}", "rightValue": 1, "operator": { "type": "number", "operation": "equals" } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2.3, "position": [ 3040, -288 ], "id": "8446e60e-c571-4161-b8da-740ec07f98b3", "name": "¿Phone match único?", "notes": "TRUE: contacts.length == 1 -> tomar contacts[0].id. FALSE: 0 o >1 -> probar email." }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "e1111111-1111-4111-8111-111111111111", "leftValue": "={{ $('DATOS CUENTA OBJETIVO').item.json.Contacto.email }}", "rightValue": "", "operator": { "type": "string", "operation": "notEmpty", "singleValue": true } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2.3, "position": [ 3344, -240 ], "id": "2fa28071-f922-4938-98f6-9a8212e5daa3", "name": "¿Hay email?", "notes": "Si el contacto no tiene email, saltar al fallback de nombre directamente." }, { "parameters": { "method": "POST", "url": "https://services.leadconnectorhq.com/contacts/search", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={\n \"locationId\": \"{{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}\",\n \"pageLimit\": 20,\n \"query\":\"{{ $('DATOS CUENTA OBJETIVO').item.json.Contacto.email }}\"\n}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 3552, -256 ], "id": "fb97973c-62da-47c3-8be5-64a8d7576048", "name": "Buscar Contacto Objetivo - MARCA (email)" }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "p2222222-2222-4222-8222-222222222222", "leftValue": "={{ $json.contacts.length }}", "rightValue": 1, "operator": { "type": "number", "operation": "equals" } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2.3, "position": [ 3792, -256 ], "id": "42c2e33d-064d-4f49-b7be-39b0c66133a2", "name": "¿Email match único?", "notes": "TRUE: contacts.length == 1 -> tomar contacts[0].id. FALSE: probar nombre." }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "n1111111-1111-4111-8111-111111111111", "leftValue": "={{ ($('Datos de Lead').item.json.Cliente['Nombre Completo'] || '').trim().split(/\\s+/).filter(s => s.length > 0).length }}", "rightValue": 2, "operator": { "type": "number", "operation": "gte" } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2.3, "position": [ 4016, -208 ], "id": "c7c27004-f31e-4318-92b0-5df2f293f7e5", "name": "¿Nombre válido?", "notes": "Solo busca por nombre si tiene al menos nombre + apellido. Si no, va directo a crear." }, { "parameters": { "method": "POST", "url": "https://services.leadconnectorhq.com/contacts/search", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={\n \"locationId\": \"{{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}\",\n \"pageLimit\": 20,\n \"query\": \"{{ $('Datos de Lead').item.json.Cliente['Nombre Completo'] }}\"\n}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 4240, -224 ], "id": "a0523efd-6cde-4419-a309-f50570d4e6bc", "name": "Buscar Contacto Objetivo - MARCA (nombre)", "disabled": true }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "p3333333-3333-4333-8333-333333333333", "leftValue": "={{ $json.contacts.length }}", "rightValue": 1, "operator": { "type": "number", "operation": "equals" } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2.3, "position": [ 4416, -224 ], "id": "a9bafd98-b68c-4e7f-8c05-25b8493efb5f", "name": "¿Nombre match único?", "notes": "TRUE: tomar contacts[0].id -> actualizar. FALSE: 0 o >1 -> crear contacto nuevo." }, { "parameters": { "assignments": { "assignments": [ { "id": "found001-1111-4111-8111-111111111111", "name": "matchedContactId", "value": "={{ $json.contacts[0].id }}", "type": "string" } ] }, "options": {} }, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [ 4864, -592 ], "id": "4d286b26-396a-4e4f-90ba-50029f9d0a0d", "name": "Capturar ID Match" }, { "parameters": { "url": "=https://services.leadconnectorhq.com/contacts/{{ $json.matchedContactId }}", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.4, "position": [ 5072, -592 ], "id": "480ef47f-03c9-43cd-bec7-1d3f3c2fdb46", "name": "Obtener Contacto Cuenta objetivo - MARCA" }, { "parameters": { "url": "=https://services.leadconnectorhq.com/locations/{{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}/customFields", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 5296, -592 ], "id": "4c544dea-4414-42fb-89a1-545e5eb9470c", "name": "Conseguir Custom Cuenta objetivo - MARCA" }, { "parameters": { "jsCode": "const contactData = $('Obtener Contacto Cuenta objetivo - MARCA').first().json.contact;\nconst allCustomFieldItems = $('Conseguir Custom Cuenta objetivo - MARCA').all();\n\nconst allFieldDefs = [];\nfor (const item of allCustomFieldItems) {\n const fields = item.json.customFields || [];\n allFieldDefs.push(...fields);\n}\n\nconst existingValueMap = {};\nfor (const cf of contactData.customFields) {\n existingValueMap[cf.id] = cf.value;\n}\n\nconst enrichedCustomFields = [];\nfor (const field of allFieldDefs) {\n enrichedCustomFields.push({\n id: field.id,\n fieldKey: field.fieldKey,\n name: field.name,\n dataType: field.dataType,\n value: existingValueMap[field.id] !== undefined ? existingValueMap[field.id] : null\n });\n}\n\nconst contactoObjetivo = {\n id: contactData.id,\n firstName: contactData.firstName,\n lastName: contactData.lastName,\n email: contactData.email,\n country: contactData.country,\n locationId: contactData.locationId,\n type: contactData.type,\n tags: contactData.tags,\n dateAdded: contactData.dateAdded,\n dateUpdated: contactData.dateUpdated,\n additionalEmails: contactData.additionalEmails,\n additionalPhones: contactData.additionalPhones,\n customFields: enrichedCustomFields\n};\n\nreturn [{ json: contactoObjetivo }];" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 5504, -592 ], "id": "1dad0c4d-005d-4d7a-92cc-4db119981d76", "name": "Obtener datos completos de Contacto objetivo - MARCA" }, { "parameters": { "jsCode": "var origenData = $('Obtener datos completos de Contacto origen - SUCURSAL').first().json;\nvar objetivoData = $('Obtener datos completos de Contacto objetivo - MARCA').first().json;\nvar origenCustomFields = origenData.customFields;\nvar objetivoCustomFields = objetivoData.customFields;\n\nif (!Array.isArray(origenCustomFields) || !Array.isArray(objetivoCustomFields)) {\n return [{ json: { body: JSON.stringify({\n firstName: origenData.firstName,\n lastName: origenData.lastName,\n email: origenData.email,\n country: origenData.country,\n tags: origenData.tags,\n customFields: []\n }) } }];\n}\n\n// Detección de duplicados de name en la cuenta objetivo (alerta en logs)\nvar nameCount = {};\nfor (var k = 0; k < objetivoCustomFields.length; k++) {\n var n = (objetivoCustomFields[k].name || '').trim();\n if (!n) continue;\n nameCount[n] = (nameCount[n] || 0) + 1;\n}\nfor (var nm in nameCount) {\n if (nameCount[nm] > 1) {\n console.log('[WARN] Custom field con nombre duplicado en cuenta objetivo: \"' + nm + '\" (' + nameCount[nm] + ' veces). El primer match gana.');\n }\n}\n\nvar customFields = [];\nfor (var i = 0; i < origenCustomFields.length; i++) {\n var campoOrigen = origenCustomFields[i];\n if (!campoOrigen.name) continue;\n\n var campoObjetivo = null;\n for (var j = 0; j < objetivoCustomFields.length; j++) {\n if (objetivoCustomFields[j].name.trim() === campoOrigen.name.trim()) {\n campoObjetivo = objetivoCustomFields[j];\n break;\n }\n }\n\n if (!campoObjetivo) continue;\n\n var rawValue = campoOrigen.value;\n var fieldValue = Array.isArray(rawValue) ? rawValue : (rawValue !== undefined ? rawValue : null);\n\n customFields.push({\n id: campoObjetivo.id,\n key: campoObjetivo.fieldKey,\n field_value: fieldValue\n });\n}\n\n\n// === FASE 1: inyectar CF id_contacto_sucursal (defensive) ===\nvar __linkId = 'E6lI9ykWhqpj7Pmi7Qd3';\ncustomFields = customFields.filter(function(c){ return c.id !== __linkId; });\nif (origenData && origenData.id) {\n customFields.push({ id: __linkId, key: 'contact.id_contacto_sucursal', field_value: origenData.id });\n}\nvar body = {\n firstName: origenData.firstName,\n lastName: origenData.lastName,\n email: origenData.email,\n country: origenData.country,\n tags: origenData.tags,\n customFields: customFields\n};\n\nreturn [{ json: { body: JSON.stringify(body) } }];" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 5728, -592 ], "id": "fb1fd8da-5396-45fc-8809-e53e1e21838c", "name": "Obtener Body para Actualizar Contacto Objetivo - MARCA" }, { "parameters": { "method": "PUT", "url": "=https://services.leadconnectorhq.com/contacts/{{ $('Capturar ID Match').item.json.matchedContactId }}", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ $json.body }}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 6000, -592 ], "id": "231f5fd4-1617-42d9-9f77-1cbb1a714021", "name": "Actualizar Contacto Cuenta Objetivo - MARCA" }, { "parameters": { "url": "=https://services.leadconnectorhq.com/locations/{{ $('Obtener Info de cuenta objetivo - MARCA').item.json.Location_ID }}/customFields", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 4880, -48 ], "id": "542ee2be-da88-4d14-adc2-576a1425a307", "name": "Conseguir Custom Cuenta objetivo - CREAR" }, { "parameters": { "jsCode": "var origenData = $('Obtener Contacto Cuenta Origen - SUCURSAL').first().json.contact;\nvar marcaCustomDefs = $('Conseguir Custom Cuenta objetivo - CREAR').first().json.customFields;\nvar origenDefs = $('Conseguir Custom Cuenta Origen- SUCURSAL').first().json.customFields;\nvar locationId = $('Datos API Cuenta objetivo - MARCA').first().json['Location ID'];\n\n// Mapa id -> name desde las definiciones del origen\nvar idToName = {};\nfor (var i = 0; i < origenDefs.length; i++) {\n idToName[origenDefs[i].id] = (origenDefs[i].name || '').trim();\n}\n\n// Mapa name -> value desde el contacto origen\nvar valoresPorName = {};\nfor (var i = 0; i < origenData.customFields.length; i++) {\n var cf = origenData.customFields[i];\n var nm = idToName[cf.id];\n if (nm) valoresPorName[nm] = cf.value;\n}\n\n// Detección de duplicados de name en la cuenta objetivo\nvar nameCount = {};\nfor (var k = 0; k < marcaCustomDefs.length; k++) {\n var n = (marcaCustomDefs[k].name || '').trim();\n if (!n) continue;\n nameCount[n] = (nameCount[n] || 0) + 1;\n}\nfor (var nm2 in nameCount) {\n if (nameCount[nm2] > 1) {\n console.log('[WARN] Custom field duplicado en cuenta objetivo: \"' + nm2 + '\" (' + nameCount[nm2] + ' veces).');\n }\n}\n\n// Construir customFields matching por name (no fieldKey, porque entre cuentas distintas los keys no coinciden)\nvar customFields = [];\nvar usados = {};\nfor (var j = 0; j < marcaCustomDefs.length; j++) {\n var def = marcaCustomDefs[j];\n var nameMarca = (def.name || '').trim();\n if (!nameMarca || usados[nameMarca]) continue;\n usados[nameMarca] = true;\n\n var rawValue = valoresPorName[nameMarca];\n if (rawValue !== undefined && rawValue !== null && rawValue !== '') {\n customFields.push({\n id: def.id,\n field_value: rawValue\n });\n }\n}\n\n\n// === FASE 1: garantizar CF contact.id_contacto_sucursal ===\n(function(){\n var origenId = ($('Obtener Contacto Cuenta Origen - SUCURSAL').first().json.contact || {}).id;\n if (!origenId) return;\n // Encontrar el def en Marca por fieldKey.\n var defLink = marcaCustomDefs.find(function(d){ return d.fieldKey === 'contact.id_contacto_sucursal'; });\n if (!defLink) return;\n customFields = customFields.filter(function(c){ return c.id !== defLink.id; });\n customFields.push({ id: defLink.id, field_value: origenId });\n})();\nvar body = {\n firstName: origenData.firstName || null,\n lastName: origenData.lastName || null,\n name: origenData.fullName || ((origenData.firstName || '') + ' ' + (origenData.lastName || '')).trim() || null,\n email: origenData.email || null,\n locationId: locationId,\n phone: origenData.phone || null,\n address1: origenData.address1 || null,\n city: origenData.city || null,\n state: origenData.state || null,\n postalCode: origenData.postalCode || null,\n website: origenData.website || null,\n timezone: origenData.timezone || null,\n country: origenData.country || null,\n tags: origenData.tags && origenData.tags.length > 0 ? origenData.tags : [],\n customFields: customFields\n};\n\n// Limpiar keys con valor null\nvar bodyLimpio = {};\nfor (var key in body) {\n if (body[key] !== null) {\n bodyLimpio[key] = body[key];\n }\n}\n\nreturn [{ json: { body: JSON.stringify(bodyLimpio) } }];" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 5104, -48 ], "id": "4395b0e0-ccd6-45de-bf26-ce62222e4dd6", "name": "Obtener el body para crear Contacto - MARCA" }, { "parameters": { "method": "POST", "url": "=https://services.leadconnectorhq.com/contacts", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Accept", "value": "application/json" }, { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ $json.body }}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 5408, -48 ], "id": "9b2248ca-7176-4693-aab2-3b52e1a8da9e", "name": "Crear Contacto - Cuenta Objetivo - MARCA" }, { "parameters": { "content": "# De Sucursal a Marca", "color": 5 }, "type": "n8n-nodes-base.stickyNote", "position": [ -928, -288 ], "typeVersion": 1, "id": "390a467d-03f5-4b79-8668-7d4844e0fd4f", "name": "Sticky Note7" }, { "parameters": { "method": "POST", "url": "https://services.leadconnectorhq.com/contacts/search", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Version", "value": "2021-07-28" }, { "name": "Authorization", "value": "=Bearer {{ $('Datos API Cuenta objetivo - MARCA').item.json['Token/API'] }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={\n \"locationId\": \"{{ $('Datos API Cuenta objetivo - MARCA').item.json['Location ID'] }}\",\n \"pageLimit\": 5,\n \"filters\": [\n {\n \"group\": \"AND\",\n \"filters\": [\n {\n \"field\": \"customFields.E6lI9ykWhqpj7Pmi7Qd3\",\n \"operator\": \"eq\",\n \"value\": \"{{ $('Crear Contacto').item.json.body.contact_id }}\"\n }\n ]\n }\n ]\n}", "options": { "redirect": { "redirect": {} } } }, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 2832, -496 ], "id": "e8f1857c-abd2-4643-b68c-a386dbadb863", "name": "Buscar Contacto Objetivo - MARCA (id_contacto_sucursal)", "onError": "continueRegularOutput", "alwaysOutputData": true, "notes": "FASE 1 — Match primario por contact.id_contacto_sucursal. Si total==1, el siguiente IF deriva a Capturar ID Match. Si no, sigue a la cascada phone→email→nombre." }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "6678f8c4-a322-49d4-a553-90b17596d4d3", "leftValue": "={{ $json.total }}", "rightValue": 1, "operator": { "type": "number", "operation": "equals" } } ], "combinator": "and" }, "options": {} }, "type": "n8n-nodes-base.if", "typeVersion": 2, "position": [ 3040, -496 ], "id": "ad8059a7-495c-4dc2-95af-63a5f88ff00b", "name": "¿id_contacto_sucursal match único?", "notes": "FASE 1. true → Capturar ID Match. false → cascada phone." } ], "connections": { "Crear Contacto": { "main": [ [ { "node": "Datos de Lead", "type": "main", "index": 0 } ] ] }, "Obtener Pipelines": { "main": [ [ { "node": "Crear Oportunidad", "type": "main", "index": 0 } ] ] }, "Datos de Lead": { "main": [ [ { "node": "Omitir @ezcorp.com", "type": "main", "index": 0 } ] ] }, "Omitir @ezcorp.com": { "main": [ [ { "node": "Obtener Info de cuenta origen - SUCURSAL", "type": "main", "index": 0 } ] ] }, "Obtener Info de cuenta origen - SUCURSAL": { "main": [ [ { "node": "Obtener Contacto Cuenta Origen - SUCURSAL", "type": "main", "index": 0 } ] ] }, "Obtener Contacto Cuenta Origen - SUCURSAL": { "main": [ [ { "node": "Conseguir Custom Cuenta Origen- SUCURSAL", "type": "main", "index": 0 } ] ] }, "Conseguir Custom Cuenta Origen- SUCURSAL": { "main": [ [ { "node": "Obtener datos completos de Contacto origen - SUCURSAL", "type": "main", "index": 0 } ] ] }, "Obtener datos completos de Contacto origen - SUCURSAL": { "main": [ [ { "node": "Mapear Custom Fields Cuenta Origen - SUCURSAL", "type": "main", "index": 0 } ] ] }, "Mapear Custom Fields Cuenta Origen - SUCURSAL": { "main": [ [ { "node": "DATOS CUENTA OBJETIVO", "type": "main", "index": 0 } ] ] }, "DATOS CUENTA OBJETIVO": { "main": [ [ { "node": "Obtener Info de cuenta objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Obtener Info de cuenta objetivo - MARCA": { "main": [ [ { "node": "Datos API Cuenta objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Datos API Cuenta objetivo - MARCA": { "main": [ [ { "node": "Buscar Contacto Objetivo - MARCA (id_contacto_sucursal)", "type": "main", "index": 0 } ] ] }, "Buscar Contacto Objetivo - MARCA (phone)": { "main": [ [ { "node": "¿Phone match único?", "type": "main", "index": 0 } ] ] }, "¿Phone match único?": { "main": [ [ { "node": "Capturar ID Match", "type": "main", "index": 0 } ], [ { "node": "¿Hay email?", "type": "main", "index": 0 } ] ] }, "¿Hay email?": { "main": [ [ { "node": "Buscar Contacto Objetivo - MARCA (email)", "type": "main", "index": 0 } ], [ { "node": "¿Nombre válido?", "type": "main", "index": 0 } ] ] }, "Buscar Contacto Objetivo - MARCA (email)": { "main": [ [ { "node": "¿Email match único?", "type": "main", "index": 0 } ] ] }, "¿Email match único?": { "main": [ [ { "node": "Capturar ID Match", "type": "main", "index": 0 } ], [ { "node": "¿Nombre válido?", "type": "main", "index": 0 } ] ] }, "¿Nombre válido?": { "main": [ [ { "node": "Buscar Contacto Objetivo - MARCA (nombre)", "type": "main", "index": 0 } ], [ { "node": "Conseguir Custom Cuenta objetivo - CREAR", "type": "main", "index": 0 } ] ] }, "Buscar Contacto Objetivo - MARCA (nombre)": { "main": [ [ { "node": "¿Nombre match único?", "type": "main", "index": 0 } ] ] }, "¿Nombre match único?": { "main": [ [ { "node": "Capturar ID Match", "type": "main", "index": 0 } ], [ { "node": "Conseguir Custom Cuenta objetivo - CREAR", "type": "main", "index": 0 } ] ] }, "Capturar ID Match": { "main": [ [ { "node": "Obtener Contacto Cuenta objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Obtener Contacto Cuenta objetivo - MARCA": { "main": [ [ { "node": "Conseguir Custom Cuenta objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Conseguir Custom Cuenta objetivo - MARCA": { "main": [ [ { "node": "Obtener datos completos de Contacto objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Obtener datos completos de Contacto objetivo - MARCA": { "main": [ [ { "node": "Obtener Body para Actualizar Contacto Objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Obtener Body para Actualizar Contacto Objetivo - MARCA": { "main": [ [ { "node": "Actualizar Contacto Cuenta Objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Conseguir Custom Cuenta objetivo - CREAR": { "main": [ [ { "node": "Obtener el body para crear Contacto - MARCA", "type": "main", "index": 0 } ] ] }, "Obtener el body para crear Contacto - MARCA": { "main": [ [ { "node": "Crear Contacto - Cuenta Objetivo - MARCA", "type": "main", "index": 0 } ] ] }, "Buscar Contacto Objetivo - MARCA (id_contacto_sucursal)": { "main": [ [ { "node": "¿id_contacto_sucursal match único?", "type": "main", "index": 0 } ] ] }, "¿id_contacto_sucursal match único?": { "main": [ [ { "node": "Capturar ID Match", "type": "main", "index": 0 } ], [ { "node": "Buscar Contacto Objetivo - MARCA (phone)", "type": "main", "index": 0 } ] ] } }, "settings": { "executionOrder": "v1" } }