{
  "name": "Nokfi · Facturas de Gmail a Google Sheets",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        },
        "simple": false,
        "filters": {
          "q": "has:attachment (filename:pdf OR filename:jpg OR filename:png)"
        },
        "options": {
          "downloadAttachments": true,
          "dataPropertyAttachmentsPrefixName": "attachment_"
        }
      },
      "id": "ea059d55-0446-5481-ba4f-24a95d58d08b",
      "name": "Correo con facturas",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Convierte los adjuntos (binarios) en lotes de hasta 5 documentos para Nokfi.\nconst TYPES = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'];\nconst docs = [];\nfor (let i = 0; i < $input.all().length; i++) {\n  const item = $input.all()[i];\n  for (const [key, bin] of Object.entries(item.binary || {})) {\n    if (!TYPES.includes(bin.mimeType)) continue;\n    const buffer = await this.helpers.getBinaryDataBuffer(i, key);\n    docs.push({ name: bin.fileName || key, mime: bin.mimeType, data: buffer.toString('base64') });\n  }\n}\nconst batches = [];\nfor (let k = 0; k < docs.length; k += 5) batches.push({ json: { files: docs.slice(k, k + 5) } });\nreturn batches;"
      },
      "id": "12490827-93a5-54d1-b201-49e68b2c4985",
      "name": "Preparar documentos",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://nokfi.app/api/v1/invoices/extract",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ files: $json.files, lang: 'es' }) }}",
        "options": {}
      },
      "id": "f1d58747-380c-56da-b90b-e4ccbd767b5b",
      "name": "Nokfi · Extraer facturas",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ],
      "notes": "Credencial: Bearer Auth con tu clave nk_live_…",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// Una fila por factura, con las comprobaciones de Nokfi en columnas.\nconst rows = [];\nfor (const item of $input.all()) {\n  for (const inv of item.json.invoices || []) {\n    rows.push({ json: {\n      archivo: inv.file_name, emisor: inv.issuer_name, nif_emisor: inv.issuer_nif,\n      numero: inv.invoice_number, fecha: inv.invoice_date, vencimiento: inv.due_date,\n      base: inv.base, tipo_iva: inv.vat_rate, iva: inv.vat_amount, retencion: inv.irpf_amount, total: inv.total,\n      cuadra: inv.checks.totals_ok ? 'sí' : 'NO', nif_valido: inv.checks.nif_valid ? 'sí' : 'NO',\n      avisos: (inv.warnings || []).map(w => w.message).join(' · ')\n    } });\n  }\n}\nreturn rows;"
      },
      "id": "967391d3-9878-5088-910a-149c40199533",
      "name": "Una fila por factura",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        0
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Facturas"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        },
        "options": {}
      },
      "id": "219dc1f6-3048-5b2e-9f7f-c94221cd10ff",
      "name": "Añadir a Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        880,
        0
      ],
      "notes": "Elige tu hoja. La primera fila debe tener los nombres de columna.",
      "notesInFlow": true
    }
  ],
  "connections": {
    "Correo con facturas": {
      "main": [
        [
          {
            "node": "Preparar documentos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar documentos": {
      "main": [
        [
          {
            "node": "Nokfi · Extraer facturas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Nokfi · Extraer facturas": {
      "main": [
        [
          {
            "node": "Una fila por factura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Una fila por factura": {
      "main": [
        [
          {
            "node": "Añadir a Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}