{
  "name": "Sistema de Notificaciones WhatsApp con Baileys",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "value": "*/1 * * * *"
            }
          ]
        }
      },
      "id": "1",
      "name": "Monitor cada minuto",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        300
      ]
    },
    {
      "parameters": {
        "resource": "rows",
        "operation": "get",
        "tableId": "system_notifications",
        "filterType": "manual",
        "matchType": "allFilters",
        "filters": {
          "conditions": [
            {
              "keyName": "delivery_method",
              "condition": "equals",
              "keyValue": "whatsapp"
            },
            {
              "keyName": "status",
              "condition": "equals",
              "keyValue": "pending"
            },
            {
              "keyName": "scheduled_for",
              "condition": "lessOrEqual",
              "keyValue": "={{ new Date().toISOString() }}"
            }
          ]
        },
        "sort": {
          "fields": [
            {
              "keyName": "created_at",
              "order": "ascending"
            }
          ]
        },
        "limit": 50
      },
      "id": "2",
      "name": "Obtener notificaciones pendientes",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        460,
        300
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "leftValue": "={{ $json.length }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ]
        }
      },
      "id": "3",
      "name": "\u00bfHay notificaciones?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        680,
        300
      ]
    },
    {
      "parameters": {
        "fieldToSplitOut": "",
        "options": {}
      },
      "id": "4",
      "name": "Procesar una por una",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        900,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "leftValue": "={{ $json.metadata?.phone_number }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "isNotEmpty"
              }
            }
          ]
        }
      },
      "id": "5",
      "name": "\u00bfTiene tel\u00e9fono?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1120,
        200
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "={{ $vars.BAILEYS_WEBHOOK_URL }}/get-status",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $vars.BAILEYS_API_KEY }}"
            }
          ]
        },
        "options": {
          "timeout": 10000,
          "retry": {
            "enabled": true,
            "maxRetries": 2
          }
        }
      },
      "id": "6",
      "name": "Verificar estado WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        100
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "leftValue": "={{ $json.status }}",
              "rightValue": "connected",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ]
        }
      },
      "id": "7",
      "name": "\u00bfWhatsApp conectado?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1560,
        100
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.BAILEYS_WEBHOOK_URL }}/initialize",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $vars.BAILEYS_API_KEY }}"
            }
          ]
        },
        "options": {
          "timeout": 30000
        }
      },
      "id": "8",
      "name": "Inicializar WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1780,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "leftValue": "={{ $('Procesar una por una').item.json.metadata?.use_template }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equal"
              }
            },
            {
              "leftValue": "={{ $('Procesar una por una').item.json.notification_type }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "isNotEmpty"
              }
            }
          ],
          "combineOperation": "all"
        }
      },
      "id": "9",
      "name": "\u00bfUsar plantilla?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1560,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.BAILEYS_WEBHOOK_URL }}/send-template",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Authorization",
              "value": "Bearer {{ $vars.BAILEYS_API_KEY }}"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "to",
              "value": "={{ $('Procesar una por una').item.json.metadata.phone_number }}"
            },
            {
              "name": "template",
              "value": "={{ $('Procesar una por una').item.json.notification_type }}_template"
            },
            {
              "name": "variables",
              "value": "={{ JSON.stringify($('Procesar una por una').item.json.metadata.template_variables || {}) }}"
            }
          ]
        },
        "options": {
          "timeout": 15000,
          "retry": {
            "enabled": true,
            "maxRetries": 3
          }
        }
      },
      "id": "10",
      "name": "Enviar con plantilla",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1780,
        400
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.BAILEYS_WEBHOOK_URL }}/send-message",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Authorization",
              "value": "Bearer {{ $vars.BAILEYS_API_KEY }}"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "to",
              "value": "={{ $('Procesar una por una').item.json.metadata.phone_number }}"
            },
            {
              "name": "message",
              "value": "={{ $('Procesar una por una').item.json.message }}"
            },
            {
              "name": "type",
              "value": "text"
            }
          ]
        },
        "options": {
          "timeout": 15000,
          "retry": {
            "enabled": true,
            "maxRetries": 3
          }
        }
      },
      "id": "11",
      "name": "Enviar mensaje directo",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1780,
        500
      ]
    },
    {
      "parameters": {
        "resource": "rows",
        "operation": "update",
        "tableId": "system_notifications",
        "updateKey": "id",
        "fieldsToSend": "defined",
        "fields": {
          "status": "sent",
          "sent_at": "={{ new Date().toISOString() }}",
          "updated_at": "={{ new Date().toISOString() }}",
          "metadata": "={{ JSON.stringify({...($('Procesar una por una').item.json.metadata || {}), whatsapp_sent: true, sent_timestamp: new Date().toISOString()}) }}"
        },
        "where": "id=eq.{{ $('Procesar una por una').item.json.id }}"
      },
      "id": "12",
      "name": "Marcar como enviado",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        2000,
        400
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "resource": "rows",
        "operation": "update",
        "tableId": "system_notifications",
        "updateKey": "id",
        "fieldsToSend": "defined",
        "fields": {
          "status": "failed",
          "updated_at": "={{ new Date().toISOString() }}",
          "metadata": "={{ JSON.stringify({...($('Procesar una por una').item.json.metadata || {}), error: $json.error || 'Error desconocido', error_timestamp: new Date().toISOString(), retry_count: (($('Procesar una por una').item.json.metadata?.retry_count || 0) + 1)}) }}"
        },
        "where": "id=eq.{{ $('Procesar una por una').item.json.id }}"
      },
      "id": "13",
      "name": "Marcar como fallido",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        2000,
        600
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "resource": "rows",
        "operation": "update",
        "tableId": "system_notifications",
        "updateKey": "id",
        "fieldsToSend": "defined",
        "fields": {
          "status": "failed",
          "updated_at": "={{ new Date().toISOString() }}",
          "metadata": "={{ JSON.stringify({...($('Procesar una por una').item.json.metadata || {}), error: 'N\u00famero de tel\u00e9fono no proporcionado', error_timestamp: new Date().toISOString()}) }}"
        },
        "where": "id=eq.{{ $('Procesar una por una').item.json.id }}"
      },
      "id": "14",
      "name": "Error: Sin tel\u00e9fono",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1340,
        400
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "15",
      "name": "Esperar 2 segundos",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        2000,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "leftValue": "={{ $('Procesar una por una').context.noItemsLeft }}",
              "rightValue": false,
              "operator": {
                "type": "boolean",
                "operation": "equal"
              }
            }
          ]
        }
      },
      "id": "16",
      "name": "\u00bfM\u00e1s elementos?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        2220,
        300
      ]
    },
    {
      "parameters": {
        "amount": 1,
        "unit": "seconds"
      },
      "id": "17",
      "name": "Pausa entre reintentos",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        1780,
        300
      ]
    }
  ],
  "connections": {
    "Monitor cada minuto": {
      "main": [
        [
          {
            "node": "Obtener notificaciones pendientes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obtener notificaciones pendientes": {
      "main": [
        [
          {
            "node": "\u00bfHay notificaciones?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\u00bfHay notificaciones?": {
      "main": [
        [
          {
            "node": "Procesar una por una",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Procesar una por una": {
      "main": [
        [
          {
            "node": "\u00bfTiene tel\u00e9fono?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\u00bfTiene tel\u00e9fono?": {
      "main": [
        [
          {
            "node": "Verificar estado WhatsApp",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Error: Sin tel\u00e9fono",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificar estado WhatsApp": {
      "main": [
        [
          {
            "node": "\u00bfWhatsApp conectado?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\u00bfWhatsApp conectado?": {
      "main": [
        [
          {
            "node": "\u00bfUsar plantilla?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Inicializar WhatsApp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inicializar WhatsApp": {
      "main": [
        [
          {
            "node": "Pausa entre reintentos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\u00bfUsar plantilla?": {
      "main": [
        [
          {
            "node": "Enviar con plantilla",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Enviar mensaje directo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar con plantilla": {
      "main": [
        [
          {
            "node": "Marcar como enviado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar mensaje directo": {
      "main": [
        [
          {
            "node": "Marcar como enviado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Marcar como enviado": {
      "main": [
        [
          {
            "node": "Esperar 2 segundos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Esperar 2 segundos": {
      "main": [
        [
          {
            "node": "\u00bfM\u00e1s elementos?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\u00bfM\u00e1s elementos?": {
      "main": [
        [
          {
            "node": "Procesar una por una",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pausa entre reintentos": {
      "main": [
        [
          {
            "node": "\u00bfUsar plantilla?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Error: Sin tel\u00e9fono": {
      "main": [
        [
          {
            "node": "Esperar 2 segundos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true,
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": {
      "errorWorkflow": "",
      "executeInErrorWorkflow": "all"
    }
  },
  "staticData": null,
  "tags": [
    {
      "createdAt": "2025-06-23T00:00:00.000Z",
      "updatedAt": "2025-06-23T00:00:00.000Z",
      "id": "1",
      "name": "whatsapp"
    },
    {
      "createdAt": "2025-06-23T00:00:00.000Z",
      "updatedAt": "2025-06-23T00:00:00.000Z",
      "id": "2",
      "name": "notifications"
    }
  ],
  "triggerCount": 1,
  "updatedAt": "2025-06-23T00:00:00.000Z",
  "versionId": "1"
}