{
  "name": "Facturas de Gmail a Google Sheets con IA y revisión TPS/TVQ (FluxLogic SI)",
  "nodes": [
    {
      "id": "7c0a1e01-2026-4160-866c-00c0b9e1919e",
      "name": "Derechos de autor",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -420,
        -560
      ],
      "parameters": {
        "content": "## Derechos de autor\n\n© 2026 FluxLogic SI. Uso libre en su empresa; no se permite revenderla ni redistribuirla como propia.",
        "height": 140,
        "width": 880,
        "color": 7
      }
    },
    {
      "id": "542e1df7-cfe1-54d3-8949-de72b80da6a1",
      "name": "Qué hace",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -420,
        -360
      ],
      "parameters": {
        "content": "## Qué hace\n1. Revisa Gmail cada hora y toma los correos con PDF que no tengan la etiqueta facturas-procesadas.\n2. Lee el texto del PDF y la IA saca proveedor, fecha, montos y números TPS/TVQ.\n3. Una regla fija revisa las sumas y los números de inscripción.\n4. Guarda una fila en Google Sheets y etiqueta el correo.\n\nNada se paga ni se envía: solo se anota. Revise a mano las filas marcadas REVISAR.",
        "height": 320,
        "width": 420,
        "color": 4
      }
    },
    {
      "id": "2a8dde24-f66f-5129-8bfe-54d3ca4f74b7",
      "name": "Antes de activar",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        40,
        -360
      ],
      "parameters": {
        "content": "## Antes de activar\n1. Conecte sus cuentas de Gmail, Google Sheets y OpenAI (credenciales).\n2. Cree en Gmail la etiqueta facturas-procesadas y elíjala en el último nodo.\n3. Cree una hoja con una pestaña llamada Facturas y pegue su URL en el nodo de Google Sheets.\n4. Pruebe con 3 o 4 facturas reales y compare a mano.\n\nGuía completa: fluxlogicsi.com",
        "height": 320,
        "width": 420,
        "color": 3
      }
    },
    {
      "id": "66d6d13c-a710-5135-b22b-9af7a485b5a9",
      "name": "Gmail: correos con factura PDF",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        -420,
        100
      ],
      "parameters": {
        "simple": false,
        "filters": {
          "q": "has:attachment filename:pdf -label:facturas-procesadas"
        },
        "options": {
          "downloadAttachments": true
        },
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        }
      }
    },
    {
      "id": "a5f8be1f-cd30-5258-a3d9-9752e44949e0",
      "name": "Separar PDFs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -200,
        100
      ],
      "parameters": {
        "jsCode": "// One item per PDF attachment. Non-PDF attachments are ignored.\nconst out = [];\nfor (const item of $input.all()) {\n  const bin = item.binary || {};\n  for (const key of Object.keys(bin)) {\n    const f = bin[key];\n    const isPdf = f.mimeType === 'application/pdf' || /\\.pdf$/i.test(f.fileName || '');\n    if (!isPdf) continue;\n    out.push({\n      json: {\n        email_id: item.json.id,\n        from: (item.json.from && (item.json.from.text || (item.json.from.value && item.json.from.value[0] && item.json.from.value[0].address))) || '',\n        subject: item.json.subject || '',\n        received: item.json.date || '',\n        file_name: f.fileName || key,\n      },\n      binary: { data: f },\n    });\n  }\n}\nreturn out;"
      }
    },
    {
      "id": "e402dc89-36d6-5533-9e44-080c0798fa48",
      "name": "Leer texto del PDF",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1,
      "position": [
        20,
        100
      ],
      "parameters": {
        "operation": "pdf",
        "binaryPropertyName": "data",
        "options": {}
      }
    },
    {
      "id": "7e278567-ca28-507f-ace7-b355de535517",
      "name": "¿El PDF tiene texto?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        240,
        100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "c646bbcf-4d17-5929-aeb3-2630c9e4e3a8",
              "leftValue": "={{ ($json.text || '').trim().length }}",
              "rightValue": 40,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "5ed1061c-d6a8-5a7a-94f6-abd82c30ed21",
      "name": "IA: extraer datos de la factura",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.5,
      "position": [
        480,
        0
      ],
      "parameters": {
        "promptType": "define",
        "hasOutputParser": true,
        "text": "=Eres un asistente de cuentas por pagar en Quebec. Lee el texto de la factura entre las etiquetas <factura>.\nExtrae SOLO lo que está escrito. Si un dato no aparece, déjalo vacío (null). No inventes ni calcules nada que no esté en la factura.\n- Montos como números, sin símbolo de moneda (ejemplo: 1234.56).\n- tps = TPS/GST/TVH cobrada. tvq = TVQ/QST cobrada.\n- numero_tps_proveedor y numero_tvq_proveedor tal como aparecen (ejemplo: 123456789 RT0001, 1234567890 TQ0001).\n- fecha_factura en formato AAAA-MM-DD.\n\n<factura>\n{{ $json.text }}\n</factura>"
      }
    },
    {
      "id": "be16995f-9b99-5800-bb79-e6467204d97c",
      "name": "Modelo OpenAI",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        440,
        220
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {
          "temperature": 0
        }
      }
    },
    {
      "id": "6274941a-b5f6-5a7a-8b0b-46df1785cea7",
      "name": "Formato de salida",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.2,
      "position": [
        640,
        220
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"proveedor\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"numero_factura\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"fecha_factura\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"facturado_a\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"subtotal\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"tps\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"tvq\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"total\": {\n      \"type\": [\n        \"number\",\n        \"null\"\n      ]\n    },\n    \"moneda\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"numero_tps_proveedor\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    },\n    \"numero_tvq_proveedor\": {\n      \"type\": [\n        \"string\",\n        \"null\"\n      ]\n    }\n  },\n  \"required\": [\n    \"proveedor\",\n    \"total\"\n  ]\n}"
      }
    },
    {
      "id": "adf2cbeb-5456-5e55-b7dc-a269b288a849",
      "name": "Revisar montos y números TPS/TVQ",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        860,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Fixed rules, no AI: sums, tax rates and supplier registration numbers.\nconst d = $json.output || {};\nconst src = $('Separar PDFs').item.json;\nconst n = (v) => (typeof v === 'number' && isFinite(v)) ? v : (v === null || v === undefined || v === '' ? null : (isFinite(Number(v)) ? Number(v) : null));\nconst sub = n(d.subtotal), tps = n(d.tps), tvq = n(d.tvq), tot = n(d.total);\nconst r = [];\nconst near = (a, b) => Math.abs(a - b) <= Math.max(0.05, Math.abs(b) * 0.01);\nif (tot === null) r.push(\"Falta el total\");\nif (sub !== null && tot !== null && !near(sub + (tps || 0) + (tvq || 0), tot)) r.push(\"Subtotal + TPS + TVQ no da el total\");\nif (sub !== null && tps !== null && tps > 0 && !near(tps, sub * 0.05)) r.push(\"La TPS no da 5 % del subtotal (verifique si hay artículos exentos)\");\nif (sub !== null && tvq !== null && tvq > 0 && !near(tvq, sub * 0.09975)) r.push(\"La TVQ no da 9,975 % del subtotal (verifique si hay artículos exentos)\");\nconst gst = String(d.numero_tps_proveedor || '').toUpperCase().replace(/[\\s-]/g, '');\nconst qst = String(d.numero_tvq_proveedor || '').toUpperCase().replace(/[\\s-]/g, '');\nif (tps > 0 && !/^\\d{9}RT\\d{4}$/.test(gst)) r.push(\"Cobra TPS pero falta un número TPS válido del proveedor (9 dígitos + RT + 4)\");\nif (/^NR\\d{8}$/.test(qst)) r.push(\"Número TVQ tipo NR: esa TVQ no da derecho a RTI\");\nelse if (tvq > 0 && !/^\\d{10}TQ\\d{4}$/.test(qst)) r.push(\"Cobra TVQ pero falta un número TVQ válido del proveedor (10 dígitos + TQ + 4)\");\nif (!d.facturado_a) r.push(\"No se ve a nombre de quién está la factura\");\nreturn { json: {\n  'fecha_recepcion': src.received, 'remitente': src.from, 'archivo': src.file_name,\n  'proveedor': d.proveedor || '', 'numero_factura': d.numero_factura || '', 'fecha_factura': d.fecha_factura || '',\n  'facturado_a': d.facturado_a || '', 'subtotal': sub, 'tps': tps, 'tvq': tvq, 'total': tot,\n  'moneda': d.moneda || '', 'numero_tps_proveedor': d.numero_tps_proveedor || '', 'numero_tvq_proveedor': d.numero_tvq_proveedor || '',\n  'estado': r.length ? \"REVISAR\" : \"OK\", 'motivos_revision': r.join(' | '),\n  'enlace_correo': 'https://mail.google.com/mail/u/0/#all/' + src.email_id,\n} };"
      }
    },
    {
      "id": "b1fa4ea9-f3d2-580f-aba2-4253d7c935aa",
      "name": "PDF escaneado: marcar para revisión",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        860,
        400
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// No text to read: we do not send it to the AI (it would guess). Flag it for a person.\nconst src = $('Separar PDFs').item.json;\nreturn { json: {\n  'fecha_recepcion': src.received, 'remitente': src.from, 'archivo': src.file_name,\n  'proveedor': '', 'numero_factura': '', 'fecha_factura': '', 'facturado_a': '', 'subtotal': null, 'tps': null, 'tvq': null, 'total': null,\n  'moneda': '', 'numero_tps_proveedor': '', 'numero_tvq_proveedor': '',\n  'estado': \"REVISAR\", 'motivos_revision': \"PDF sin texto (escaneado o imagen): revisar a mano\",\n  'enlace_correo': 'https://mail.google.com/mail/u/0/#all/' + src.email_id,\n} };"
      }
    },
    {
      "id": "75a40957-8dfd-5baf-9a58-b72844a81154",
      "name": "Agregar fila en Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1100,
        100
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "PEGA_AQUI_LA_URL_DE_TU_HOJA_DE_GOOGLE"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Facturas"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "509cc45c-024a-5713-afcb-d758c5404e22",
      "name": "Gmail: etiquetar como procesada",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1320,
        100
      ],
      "parameters": {
        "operation": "addLabels",
        "messageId": "={{ $('Separar PDFs').item.json.email_id }}",
        "labelIds": [
          "ELIGE_LA_ETIQUETA_facturas-procesadas"
        ]
      }
    }
  ],
  "connections": {
    "Gmail: correos con factura PDF": {
      "main": [
        [
          {
            "node": "Separar PDFs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Separar PDFs": {
      "main": [
        [
          {
            "node": "Leer texto del PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Leer texto del PDF": {
      "main": [
        [
          {
            "node": "¿El PDF tiene texto?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿El PDF tiene texto?": {
      "main": [
        [
          {
            "node": "IA: extraer datos de la factura",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "PDF escaneado: marcar para revisión",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Modelo OpenAI": {
      "ai_languageModel": [
        [
          {
            "node": "IA: extraer datos de la factura",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Formato de salida": {
      "ai_outputParser": [
        [
          {
            "node": "IA: extraer datos de la factura",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "IA: extraer datos de la factura": {
      "main": [
        [
          {
            "node": "Revisar montos y números TPS/TVQ",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Revisar montos y números TPS/TVQ": {
      "main": [
        [
          {
            "node": "Agregar fila en Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PDF escaneado: marcar para revisión": {
      "main": [
        [
          {
            "node": "Agregar fila en Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Agregar fila en Google Sheets": {
      "main": [
        [
          {
            "node": "Gmail: etiquetar como procesada",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}