{
  "name": "Procesamiento Automático de Pedidos con Facturación SRI",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "nuevo-pedido-woocommerce",
        "options": {}
      },
      "id": "b4c5d6e7-0014-4a01-b001-ef1234567001",
      "name": "Webhook - Nuevo Pedido WooCommerce",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "nombreCliente",
              "value": "={{ $json.billing.first_name + ' ' + $json.billing.last_name }}"
            },
            {
              "name": "correoCliente",
              "value": "={{ $json.billing.email }}"
            },
            {
              "name": "telefonoCliente",
              "value": "={{ $json.billing.phone }}"
            },
            {
              "name": "rucCedula",
              "value": "={{ $json.meta_data.find(m => m.key === 'ruc_cedula')?.value || '9999999999999' }}"
            },
            {
              "name": "total",
              "value": "={{ $json.total }}"
            },
            {
              "name": "pedidoId",
              "value": "={{ $json.id }}"
            }
          ],
          "number": [],
          "boolean": []
        },
        "options": {}
      },
      "id": "b4c5d6e7-0014-4a02-b002-ef1234567002",
      "name": "Set - Estructurar Pedido",
      "type": "n8n-nodes-base.set",
      "typeVersion": 2,
      "position": [500, 300]
    },
    {
      "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.rucCedula }}\",\n    \"razon_social\": \"{{ $json.nombreCliente }}\",\n    \"correo\": \"{{ $json.correoCliente }}\"\n  },\n  \"items\": {{ JSON.stringify($json.line_items || []) }},\n  \"totales\": {\n    \"subtotal_12\": \"{{ (parseFloat($json.total) / 1.12).toFixed(2) }}\",\n    \"iva_12\": \"{{ (parseFloat($json.total) - parseFloat($json.total) / 1.12).toFixed(2) }}\",\n    \"total\": \"{{ $json.total }}\"\n  }\n}",
        "options": {}
      },
      "id": "b4c5d6e7-0014-4a03-b003-ef1234567003",
      "name": "HTTP Request - Facturación SRI",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [750, 300]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "byName",
          "value": "Inventario"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "pedido_id": "={{ $json.pedidoId }}",
            "fecha": "={{ $now.toISO() }}",
            "cliente": "={{ $json.nombreCliente }}",
            "total": "={{ $json.total }}",
            "numero_factura": "={{ $json.numero_autorizacion || '' }}",
            "estado": "Facturado"
          }
        },
        "options": {}
      },
      "id": "b4c5d6e7-0014-4a04-b004-ef1234567004",
      "name": "Google Sheets - Actualizar Inventario",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4,
      "position": [1000, 300],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "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.telefonoCliente }}\",\n  \"type\": \"text\",\n  \"text\": {\n    \"body\": \"✅ ¡Hola {{ $json.nombreCliente }}! Tu pedido #{{ $json.pedidoId }} ha sido procesado exitosamente.\\n\\n📄 Factura generada\\n💰 Total: ${{ $json.total }}\\n\\nTe enviaremos la factura electrónica a tu correo. ¡Gracias por tu compra!\"\n  }\n}",
        "options": {}
      },
      "id": "b4c5d6e7-0014-4a05-b005-ef1234567005",
      "name": "WhatsApp - Confirmar Pedido",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [1250, 200]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.correoCliente }}",
        "subject": "=Factura Electrónica - Pedido #{{ $json.pedidoId }}",
        "emailType": "html",
        "message": "=<h2>Factura Electrónica</h2><p>Estimado/a {{ $json.nombreCliente }},</p><p>Adjuntamos la factura electrónica correspondiente a su pedido #{{ $json.pedidoId }}.</p><table border='1' cellpadding='8' style='border-collapse:collapse;'><tr><td><strong>Pedido:</strong></td><td>#{{ $json.pedidoId }}</td></tr><tr><td><strong>Total:</strong></td><td>${{ $json.total }}</td></tr><tr><td><strong>RUC/Cédula:</strong></td><td>{{ $json.rucCedula }}</td></tr></table><p>Gracias por su compra.</p>",
        "options": {}
      },
      "id": "b4c5d6e7-0014-4a06-b006-ef1234567006",
      "name": "Gmail - Enviar Factura",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2,
      "position": [1250, 400],
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "Gmail account"
        }
      }
    }
  ],
  "connections": {
    "Webhook - Nuevo Pedido WooCommerce": {
      "main": [
        [
          {
            "node": "Set - Estructurar Pedido",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set - Estructurar Pedido": {
      "main": [
        [
          {
            "node": "HTTP Request - Facturación SRI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request - Facturación SRI": {
      "main": [
        [
          {
            "node": "Google Sheets - Actualizar Inventario",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets - Actualizar Inventario": {
      "main": [
        [
          {
            "node": "WhatsApp - Confirmar Pedido",
            "type": "main",
            "index": 0
          },
          {
            "node": "Gmail - Enviar Factura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [
    {
      "name": "e-commerce"
    },
    {
      "name": "facturacion"
    },
    {
      "name": "sri"
    }
  ]
}
