{
  "name": "Generador Automático de Facturas y Seguimiento de Cobros",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "nueva-venta",
        "options": {}
      },
      "id": "f8a9b0c1-0018-4a01-b001-ef1234567001",
      "name": "Webhook - Nueva Venta",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 200]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://api.facturacion-electronica.com/v1/facturas",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"ambiente\": \"produccion\",\n  \"tipo_comprobante\": \"factura\",\n  \"cliente\": {\n    \"identificacion\": \"{{ $json.body.ruc_cedula }}\",\n    \"razon_social\": \"{{ $json.body.cliente }}\",\n    \"correo\": \"{{ $json.body.correo }}\"\n  },\n  \"items\": [\n    {\n      \"descripcion\": \"{{ $json.body.servicio }}\",\n      \"cantidad\": 1,\n      \"precio_unitario\": \"{{ $json.body.monto }}\",\n      \"impuesto\": \"IVA 12%\"\n    }\n  ]\n}",
        "options": {}
      },
      "id": "f8a9b0c1-0018-4a02-b002-ef1234567002",
      "name": "HTTP Request - Generar Factura SRI",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [500, 200]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.body.correo }}",
        "subject": "=Factura Electrónica - {{ $json.body.servicio }}",
        "emailType": "html",
        "message": "=<h2>Factura Electrónica</h2><p>Estimado/a {{ $json.body.cliente }},</p><p>Adjuntamos la factura electrónica por el servicio prestado:</p><table border='1' cellpadding='8' style='border-collapse:collapse;'><tr><td><strong>Servicio:</strong></td><td>{{ $json.body.servicio }}</td></tr><tr><td><strong>Monto:</strong></td><td>${{ $json.body.monto }}</td></tr><tr><td><strong>Fecha:</strong></td><td>{{ $now.format('dd/MM/yyyy') }}</td></tr></table><p>Gracias por confiar en nosotros.</p>",
        "options": {}
      },
      "id": "f8a9b0c1-0018-4a03-b003-ef1234567003",
      "name": "Gmail - Enviar Factura",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2,
      "position": [750, 200],
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "triggerAtHour": 9
            }
          ]
        }
      },
      "id": "f8a9b0c1-0018-4a04-b004-ef1234567004",
      "name": "Schedule Trigger - Cobros Diario",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1,
      "position": [250, 500]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "byName",
          "value": "Facturas"
        },
        "options": {
          "range": "A:I"
        }
      },
      "id": "f8a9b0c1-0018-4a05-b005-ef1234567005",
      "name": "Google Sheets - Leer Facturas Pendientes",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4,
      "position": [500, 500],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "const now = new Date();\nconst results = [];\n\nfor (const item of items) {\n  if (item.json.estado !== 'Pagado') {\n    const fechaFactura = new Date(item.json.fecha_emision);\n    const diasVencido = Math.floor((now - fechaFactura) / (1000 * 60 * 60 * 24));\n    \n    if (diasVencido >= 30) {\n      results.push({\n        json: {\n          ...item.json,\n          diasVencido,\n          tipoRecordatorio: diasVencido >= 60 ? 'whatsapp' : 'email'\n        }\n      });\n    }\n  }\n}\n\nreturn results.length > 0 ? results : [{json: {noVencidas: true}}];"
      },
      "id": "f8a9b0c1-0018-4a06-b006-ef1234567006",
      "name": "Function - Filtrar Vencidas",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [750, 500]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json.tipoRecordatorio }}",
              "operation": "equal",
              "value2": "whatsapp"
            }
          ]
        }
      },
      "id": "f8a9b0c1-0018-4a07-b007-ef1234567007",
      "name": "IF - Más de 60 Días",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [1000, 500]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v17.0/FROM_PHONE_NUMBER_ID/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"messaging_product\": \"whatsapp\",\n  \"to\": \"{{ $json.telefono }}\",\n  \"type\": \"text\",\n  \"text\": {\n    \"body\": \"Estimado/a {{ $json.cliente }}, le recordamos que su factura por ${{ $json.monto }} tiene {{ $json.diasVencido }} días de vencida. Agradeceríamos su pronto pago. ¿Necesita alguna facilidad de pago? Estamos para ayudarle.\"\n  }\n}",
        "options": {}
      },
      "id": "f8a9b0c1-0018-4a08-b008-ef1234567008",
      "name": "WhatsApp - Recordatorio Urgente",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [1250, 400]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.correo }}",
        "subject": "=Recordatorio de Pago - Factura #{{ $json.numero_factura }}",
        "emailType": "html",
        "message": "=<h2>Recordatorio de Pago</h2><p>Estimado/a {{ $json.cliente }},</p><p>Le recordamos que tiene una factura pendiente de pago:</p><table border='1' cellpadding='8' style='border-collapse:collapse;'><tr><td><strong>Factura:</strong></td><td>#{{ $json.numero_factura }}</td></tr><tr><td><strong>Monto:</strong></td><td>${{ $json.monto }}</td></tr><tr><td><strong>Días vencida:</strong></td><td>{{ $json.diasVencido }} días</td></tr></table><p>Agradeceríamos su pronto pago. Si ya realizó el pago, por favor ignore este mensaje.</p>",
        "options": {}
      },
      "id": "f8a9b0c1-0018-4a09-b009-ef1234567009",
      "name": "Gmail - Recordatorio Amable",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2,
      "position": [1250, 600],
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "Gmail account"
        }
      }
    }
  ],
  "connections": {
    "Webhook - Nueva Venta": {
      "main": [
        [
          {
            "node": "HTTP Request - Generar Factura SRI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request - Generar Factura SRI": {
      "main": [
        [
          {
            "node": "Gmail - Enviar Factura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger - Cobros Diario": {
      "main": [
        [
          {
            "node": "Google Sheets - Leer Facturas Pendientes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets - Leer Facturas Pendientes": {
      "main": [
        [
          {
            "node": "Function - Filtrar Vencidas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Filtrar Vencidas": {
      "main": [
        [
          {
            "node": "IF - Más de 60 Días",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF - Más de 60 Días": {
      "main": [
        [
          {
            "node": "WhatsApp - Recordatorio Urgente",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Gmail - Recordatorio Amable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [
    {
      "name": "finance"
    },
    {
      "name": "facturas"
    },
    {
      "name": "cobros"
    },
    {
      "name": "sri"
    }
  ]
}
