{
  "name": "Tool - Cambiar Turno",
  "nodes": [
    {
      "id": "ch-trigger",
      "name": "Recibir Datos",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1,
      "position": [
        240,
        300
      ],
      "parameters": {}
    },
    {
      "id": "ch-leer-turnos",
      "name": "Leer Turnos",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        460,
        300
      ],
      "alwaysOutputData": true,
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "1vK8h8c8prheB8_KE7nwl6e4SblGoeALs_jE-vkgv5ho",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Turnos",
          "mode": "name"
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "ch-preparar",
      "name": "Preparar Cambio",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        300
      ],
      "parameters": {
        "jsCode": "const raw = $('Recibir Datos').first().json;\nconst d = raw.telefono != null ? raw : JSON.parse(raw.query || '{}');\nconst valido = v => v != null && String(v).trim() !== '' && String(v) !== 'undefined' && String(v) !== 'null';\nif (!valido(d.telefono) || !valido(d.fecha_actual) || !valido(d.fecha_nueva) || !valido(d.hora_nueva)) {\n  throw new Error('Datos incompletos para cambiar turno. Necesito: telefono, fecha_actual (del turno a cambiar), fecha_nueva y hora_nueva.');\n}\nconst normTel = t => { let s = String(t).replace(/\\D/g, ''); if (s.startsWith('54')) s = s.slice(2); if (s.startsWith('9') && s.length >= 10) s = s.slice(1); return s; };\nconst normHora = h => { const s = String(h).trim(); if (/^\\d{1,2}$/.test(s)) return s.padStart(2, '0') + ':00'; if (/^\\d{1,2}:\\d{2}$/.test(s)) return s.padStart(5, '0'); return s; };\nconst telefono = normTel(d.telefono);\nconst horaNueva = normHora(d.hora_nueva);\nconst fechaHoy = new Date().toISOString().split('T')[0];\nif (d.fecha_nueva < fechaHoy) {\n  throw new Error('La nueva fecha ' + d.fecha_nueva + ' ya pas\u00f3. Eleg\u00ed una fecha futura.');\n}\nconst busyStates = ['PENDIENTE','CONFIRMADO','RECORDATORIO_ENVIADO'];\nconst turnos = $('Leer Turnos').all();\nconst turnoViejo = turnos.find(i => {\n  if (!i.json.turno_id) return false;\n  const p = i.json.turno_id.split('_');\n  return normTel(p[0]) === telefono && p[1] === d.fecha_actual && busyStates.includes(i.json.estado_turno);\n});\nif (!turnoViejo) {\n  throw new Error('No encontr\u00e9 un turno activo para el ' + d.fecha_actual + '. Verific\u00e1 la fecha del turno actual con el paciente.');\n}\nconst slotOcupado = turnos.some(i => i.json.fecha === d.fecha_nueva && i.json.hora === horaNueva && busyStates.includes(i.json.estado_turno));\nif (slotOcupado) {\n  throw new Error('El horario ' + horaNueva + ' del ' + d.fecha_nueva + ' ya est\u00e1 ocupado. Llam\u00e1 a ver_disponibilidad para ver horarios libres.');\n}\nconst turno_id_viejo = turnoViejo.json.turno_id;\nconst turno_id_nuevo = telefono + '_' + d.fecha_nueva + '_' + horaNueva;\nconst servicio = valido(d.servicio) ? d.servicio : (turnoViejo.json.servicio || 'Consulta general');\nconst nombre = valido(d.nombre) ? d.nombre : (turnoViejo.json.nombre || '');\nreturn [{ json: { telefono, nombre, fecha_actual: d.fecha_actual, fecha_nueva: d.fecha_nueva, hora_nueva: horaNueva, servicio, turno_id_viejo, turno_id_nuevo, fechaHoy } }];"
      }
    },
    {
      "id": "ch-cancelar-viejo",
      "name": "Cancelar Turno Viejo",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        900,
        300
      ],
      "alwaysOutputData": true,
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "1vK8h8c8prheB8_KE7nwl6e4SblGoeALs_jE-vkgv5ho",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Turnos",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "turno_id": "={{ $json.turno_id_viejo }}",
            "estado_turno": "CANCELADO"
          },
          "matchingColumns": [
            "turno_id"
          ],
          "schema": [
            {
              "id": "turno_id",
              "displayName": "turno_id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "estado_turno",
              "displayName": "estado_turno",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "ch-crear-nuevo",
      "name": "Crear Turno Nuevo",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1120,
        300
      ],
      "alwaysOutputData": true,
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "1vK8h8c8prheB8_KE7nwl6e4SblGoeALs_jE-vkgv5ho",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Turnos",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "turno_id": "={{ $('Preparar Cambio').first().json.turno_id_nuevo }}",
            "telefono": "={{ $('Preparar Cambio').first().json.telefono }}",
            "nombre": "={{ $('Preparar Cambio').first().json.nombre }}",
            "fecha": "={{ $('Preparar Cambio').first().json.fecha_nueva }}",
            "hora": "={{ $('Preparar Cambio').first().json.hora_nueva }}",
            "servicio": "={{ $('Preparar Cambio').first().json.servicio }}",
            "estado_turno": "CONFIRMADO"
          },
          "matchingColumns": [
            "turno_id"
          ],
          "schema": [
            {
              "id": "turno_id",
              "displayName": "turno_id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "telefono",
              "displayName": "telefono",
              "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": "fecha",
              "displayName": "fecha",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "hora",
              "displayName": "hora",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "servicio",
              "displayName": "servicio",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "estado_turno",
              "displayName": "estado_turno",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "ch-actualizar-paciente",
      "name": "Actualizar Paciente",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1340,
        300
      ],
      "alwaysOutputData": true,
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "1vK8h8c8prheB8_KE7nwl6e4SblGoeALs_jE-vkgv5ho",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Pacientes",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "telefono": "={{ $('Preparar Cambio').first().json.telefono }}",
            "nombre": "={{ $('Preparar Cambio').first().json.nombre }}",
            "proximoTurno": "={{ $('Preparar Cambio').first().json.fecha_nueva + ' ' + $('Preparar Cambio').first().json.hora_nueva }}",
            "estado": "CONFIRMADO",
            "fechaUltimoContacto": "={{ $('Preparar Cambio').first().json.fechaHoy }}"
          },
          "matchingColumns": [
            "telefono"
          ],
          "schema": [
            {
              "id": "telefono",
              "displayName": "telefono",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "nombre",
              "displayName": "nombre",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "proximoTurno",
              "displayName": "proximoTurno",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            },
            {
              "id": "estado",
              "displayName": "estado",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            },
            {
              "id": "fechaUltimoContacto",
              "displayName": "fechaUltimoContacto",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "ch-respuesta",
      "name": "Construir Respuesta",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        300
      ],
      "parameters": {
        "jsCode": "const d = $('Preparar Cambio').first().json;\nreturn [{ json: { resultado: 'Turno cambiado correctamente. Nuevo turno: *' + d.fecha_nueva + ' a las ' + d.hora_nueva + 'hs* (' + d.servicio + '). El turno del ' + d.fecha_actual + ' fue cancelado.' } }];"
      }
    }
  ],
  "connections": {
    "Recibir Datos": {
      "main": [
        [
          {
            "node": "Leer Turnos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Leer Turnos": {
      "main": [
        [
          {
            "node": "Preparar Cambio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar Cambio": {
      "main": [
        [
          {
            "node": "Cancelar Turno Viejo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cancelar Turno Viejo": {
      "main": [
        [
          {
            "node": "Crear Turno Nuevo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Crear Turno Nuevo": {
      "main": [
        [
          {
            "node": "Actualizar Paciente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Actualizar Paciente": {
      "main": [
        [
          {
            "node": "Construir Respuesta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}