{
  "name": "Firma lui Dan EP4: facturi din e-mail în Google Drive",
  "nodes": [
    {
      "id": "7bb41b1a-0520-4c58-8635-e15f09756af4",
      "name": "Gmail: facturi noi",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        -1600,
        0
      ],
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyX",
              "value": 5,
              "unit": "minutes"
            }
          ]
        },
        "simple": false,
        "filters": {
          "q": "has:attachment (filename:pdf OR filename:xml)"
        },
        "options": {
          "downloadAttachments": true,
          "dataPropertyAttachmentsPrefixName": "attachment_"
        }
      },
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "2622062e-766c-46b3-9173-0f80135495a7",
      "name": "Test: trimite facturi",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -1600,
        220
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "firma-lui-dan-facturi-test",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {
          "binaryPropertyName": "data"
        }
      },
      "webhookId": "25b70aff-6384-40a3-8c35-75c31e44a50b"
    },
    {
      "id": "fdc3fe86-0339-43a5-9c93-6f71be99da6a",
      "name": "Setări",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -1380,
        100
      ],
      "parameters": {
        "mode": "manual",
        "assignments": {
          "assignments": [
            {
              "id": "11e3485f-7861-4576-a512-a67963e7eb10",
              "name": "folderRadacinaId",
              "value": "PUNE_AICI_ID_FOLDER_FACTURI",
              "type": "string"
            },
            {
              "id": "ab637894-ac47-47e0-b31e-33f9a8d375ba",
              "name": "folderDeVerificatId",
              "value": "PUNE_AICI_ID_FOLDER_DE_VERIFICAT",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {
          "includeBinary": true
        }
      }
    },
    {
      "id": "a22e95fa-8afe-47b7-b733-e24877cd3980",
      "name": "Separă atașamentele",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -1160,
        100
      ],
      "parameters": {
        "jsCode": "// Un rând pentru fiecare atașament PDF sau XML din e-mail (sau din testul prin webhook).\nconst out = [];\nconst items = $input.all();\nfor (let i = 0; i < items.length; i++) {\n  const it = items[i];\n  const j = it.json || {};\n  const body = j.body || {};\n  const deLa = (j.from && (j.from.text || (j.from.value && j.from.value[0] && j.from.value[0].address))) || body.de_la || '';\n  const meta = {\n    sursa: j.webhookUrl ? 'test' : 'gmail',\n    email_id: j.id || '',\n    de_la: deLa,\n    subiect: j.subject || body.subiect || '',\n  };\n  for (const [key, bin] of Object.entries(it.binary || {})) {\n    const nume = bin.fileName || key;\n    const ext = (bin.fileExtension || nume.split('.').pop() || '').toLowerCase();\n    if (ext !== 'pdf' && ext !== 'xml') continue;\n    out.push({ json: { ...meta, fisier_original: nume, tip: ext }, binary: { data: bin }, pairedItem: i });\n  }\n}\nreturn out;\n"
      }
    },
    {
      "id": "7bd383ab-20d1-44eb-8d38-f5bf0c470d46",
      "name": "PDF sau XML?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        -940,
        100
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "e9968b3a-4ec0-454a-b472-ed0918fcd05b",
                    "leftValue": "={{ $json.tip }}",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "rightValue": "xml"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "XML (e-Factura)"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "83fe8735-8afd-4ec3-9e63-2f91e97da158",
                    "leftValue": "={{ $json.tip }}",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "rightValue": "pdf"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "PDF"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "8cbf8d54-3f08-4c49-ad56-522b996b3fa1",
      "name": "Citește e-Factura (XML)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -700,
        -60
      ],
      "parameters": {
        "jsCode": "// Citește direct câmpurile din XML-ul e-Factura (UBL), fără AI.\nconst items = $input.all();\nconst out = [];\nconst val = (src, tag) => {\n  const m = src.match(new RegExp('<(?:[\\\\w-]+:)?' + tag + '(?:\\\\s[^>]*)?>([^<]*)</(?:[\\\\w-]+:)?' + tag + '>'));\n  return m ? m[1].trim() : '';\n};\nconst block = (src, tag) => {\n  const m = src.match(new RegExp('<(?:[\\\\w-]+:)?' + tag + '(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</(?:[\\\\w-]+:)?' + tag + '>'));\n  return m ? m[1] : '';\n};\nfor (let i = 0; i < items.length; i++) {\n  const buf = await this.helpers.getBinaryDataBuffer(i, 'data');\n  const xml = buf.toString('utf8');\n  const esteFactura = /<(?:[\\w-]+:)?(Invoice|CreditNote)[\\s>]/.test(xml);\n  const furnizorBloc = block(xml, 'AccountingSupplierParty');\n  const totaluri = block(xml, 'LegalMonetaryTotal');\n  const taxe = block(xml, 'TaxTotal');\n  const cui = val(block(furnizorBloc, 'PartyTaxScheme'), 'CompanyID') || val(block(furnizorBloc, 'PartyLegalEntity'), 'CompanyID');\n  out.push({\n    json: {\n      ...items[i].json,\n      metoda: 'xml',\n      este_factura: esteFactura,\n      furnizor: val(furnizorBloc, 'RegistrationName') || val(block(furnizorBloc, 'PartyName'), 'Name'),\n      cui_furnizor: cui,\n      numar: val(xml, 'ID'),\n      data: val(xml, 'IssueDate'),\n      total_fara_tva: val(totaluri, 'TaxExclusiveAmount'),\n      tva: val(taxe, 'TaxAmount'),\n      total: val(totaluri, 'TaxInclusiveAmount') || val(totaluri, 'PayableAmount'),\n      moneda: val(xml, 'DocumentCurrencyCode'),\n    },\n    binary: items[i].binary,\n    pairedItem: i,\n  });\n}\nreturn out;\n"
      }
    },
    {
      "id": "ee3d3f74-6b2f-44af-a924-4a494daa30eb",
      "name": "Extrage text din PDF",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1,
      "position": [
        -700,
        200
      ],
      "parameters": {
        "operation": "pdf",
        "binaryPropertyName": "data",
        "options": {
          "keepSource": "both"
        }
      }
    },
    {
      "id": "4a0af591-3012-45c7-85b1-2574cc30613b",
      "name": "Citește factura (AI)",
      "type": "@n8n/n8n-nodes-langchain.informationExtractor",
      "typeVersion": 1.2,
      "position": [
        -480,
        200
      ],
      "parameters": {
        "text": "={{ ($json.text || '').trim() ? $json.text.slice(0, 15000) : 'DOCUMENT FARA TEXT' }}",
        "schemaType": "manual",
        "inputSchema": "{\n \"type\": \"object\",\n \"properties\": {\n  \"este_factura\": {\n   \"type\": \"boolean\",\n   \"description\": \"true doar dacă documentul este o factură fiscală sau o notă de credit (nu ofertă, proformă, contract sau newsletter)\"\n  },\n  \"furnizor\": {\n   \"type\": \"string\",\n   \"description\": \"Denumirea furnizorului (emitentul facturii)\"\n  },\n  \"cui_furnizor\": {\n   \"type\": \"string\",\n   \"description\": \"CUI/CIF-ul furnizorului, doar cifrele, fără RO\"\n  },\n  \"numar\": {\n   \"type\": \"string\",\n   \"description\": \"Seria și numărul facturii, ex. ABC 1234\"\n  },\n  \"data\": {\n   \"type\": \"string\",\n   \"description\": \"Data emiterii în format YYYY-MM-DD\"\n  },\n  \"total_fara_tva\": {\n   \"type\": \"number\",\n   \"description\": \"Total fără TVA\"\n  },\n  \"tva\": {\n   \"type\": \"number\",\n   \"description\": \"Valoarea TVA (0 dacă nu există)\"\n  },\n  \"total\": {\n   \"type\": \"number\",\n   \"description\": \"Total de plată, cu TVA\"\n  },\n  \"moneda\": {\n   \"type\": \"string\",\n   \"description\": \"Moneda, ex. RON sau EUR\"\n  }\n },\n \"required\": [\n  \"este_factura\",\n  \"furnizor\",\n  \"cui_furnizor\",\n  \"numar\",\n  \"data\",\n  \"total_fara_tva\",\n  \"tva\",\n  \"total\",\n  \"moneda\"\n ]\n}",
        "options": {
          "systemPromptTemplate": "Extragi date din facturi românești. Răspunzi doar cu valori care apar în document. Dacă un câmp lipsește, întorci text gol sau 0. Nu inventa nimic."
        }
      }
    },
    {
      "id": "7613cf6e-2372-4c01-ab8a-b19cb2b82fa7",
      "name": "Model AI (OpenAI)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        -480,
        420
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4.1-mini",
          "mode": "list",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {
          "temperature": 0
        }
      },
      "credentials": {
        "openAiApi": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "0423a127-9c63-46b7-92f1-1f1bc63677f8",
      "name": "Combină rezultatul AI",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -260,
        200
      ],
      "parameters": {
        "jsCode": "// Pune rezultatul AI lângă fișierul original.\nconst sursa = $('Extrage text din PDF').all();\nreturn $input.all().map((it, i) => {\n  const s = sursa[i];\n  const json = { ...s.json };\n  const lungime = String(json.text || '').trim().length;\n  delete json.text;\n  delete json.info;\n  delete json.metadata;\n  return {\n    json: { ...json, ...(it.json.output || {}), metoda: 'pdf', lungime_text: lungime },\n    binary: s.binary,\n    pairedItem: i,\n  };\n});\n"
      }
    },
    {
      "id": "d9aa4fb8-42fd-4d11-b307-686095dbe8f5",
      "name": "Adună XML și PDF",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        -40,
        100
      ],
      "parameters": {}
    },
    {
      "id": "9e215587-3d14-45cf-9048-6c8006fc9f5f",
      "name": "Verificări",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        180,
        100
      ],
      "parameters": {
        "jsCode": "// Verificările de bază, înainte ca factura să ajungă în Drive.\nconst LUNI = ['Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'];\n\n// CUI românesc: cifra de control cu cheia 753217532.\nconst cuiValid = (raw) => {\n  const c = String(raw || '').toUpperCase().replace(/^RO/, '').replace(/[^0-9]/g, '');\n  if (c.length < 2 || c.length > 10) return false;\n  const cifre = c.split('').map(Number);\n  const control = cifre.pop();\n  const cheie = [7, 5, 3, 2, 1, 7, 5, 3, 2];\n  const pad = Array(9 - cifre.length).fill(0).concat(cifre);\n  let s = 0;\n  for (let k = 0; k < 9; k++) s += pad[k] * cheie[k];\n  let r = (s * 10) % 11;\n  if (r === 10) r = 0;\n  return r === control;\n};\n\n// Numere scrise „1.234,56”, „1234.56” sau deja numere.\nconst numar = (v) => {\n  if (typeof v === 'number') return v;\n  let s = String(v || '').replace(/[^0-9,.-]/g, '');\n  if (!s) return null;\n  if (s.includes(',') && s.includes('.')) s = s.lastIndexOf(',') > s.lastIndexOf('.') ? s.replace(/\\./g, '').replace(',', '.') : s.replace(/,/g, '');\n  else if (s.includes(',')) s = s.replace(',', '.');\n  const n = parseFloat(s);\n  return isNaN(n) ? null : n;\n};\n\nconst curat = (s, max) => String(s || '').replace(/[\\/\\\\:*?\"<>|]+/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, max);\n\nreturn $input.all().map((it, i) => {\n  const f = it.json;\n  const motive = [];\n  const net = numar(f.total_fara_tva);\n  const tva = numar(f.tva) || 0;\n  const total = numar(f.total);\n  const data = String(f.data || '').slice(0, 10);\n  const dataOk = /^\\d{4}-\\d{2}-\\d{2}$/.test(data) && !isNaN(Date.parse(data));\n\n  if (f.metoda === 'pdf' && f.lungime_text < 30) motive.push('PDF fara text (scanat)');\n  if (!f.este_factura) motive.push('Nu pare factura');\n  if (!f.numar) motive.push('Lipseste numarul');\n  if (!dataOk) motive.push('Data lipsa sau invalida');\n  if (!f.furnizor) motive.push('Lipseste furnizorul');\n  if (!cuiValid(f.cui_furnizor)) motive.push('CUI invalid');\n  if (!total || total <= 0) motive.push('Total lipsa');\n  else if (net !== null && Math.abs(net + tva - total) > 0.05) motive.push('Totalul nu se potriveste');\n\n  const an = dataOk ? data.slice(0, 4) : '';\n  const lunaNr = dataOk ? data.slice(5, 7) : '';\n  const furnizor = curat(f.furnizor, 60);\n  const nr = curat(f.numar, 40).replace(/\\s+/g, '-');\n  const ext = f.tip || 'pdf';\n\n  return {\n    json: {\n      ...f,\n      total_fara_tva: net,\n      tva,\n      total,\n      data,\n      cui_furnizor: String(f.cui_furnizor || '').toUpperCase().replace(/^RO/, '').replace(/[^0-9]/g, ''),\n      status: motive.length ? 'de_verificat' : 'ok',\n      motive,\n      an,\n      luna_folder: dataOk ? lunaNr + ' ' + LUNI[Number(lunaNr) - 1] : '',\n      furnizor_folder: furnizor,\n      nume_fisier: data + '_' + furnizor + '_' + nr + '.' + ext,\n      nume_verificare: (motive[0] || 'Verificare') + ' - ' + f.fisier_original,\n    },\n    binary: it.binary,\n    pairedItem: i,\n  };\n});\n"
      }
    },
    {
      "id": "1365107b-e588-41f8-bdcc-eb816cf19913",
      "name": "Pe rând",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        400,
        100
      ],
      "parameters": {
        "options": {}
      }
    },
    {
      "id": "2792bb2c-7d7c-4f4a-a958-321ae800258f",
      "name": "E în regulă?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        620,
        120
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "416ccd34-44e3-4033-a76d-201362ec21e1",
              "leftValue": "={{ $json.status }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "rightValue": "ok"
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "f5672524-915e-4470-921a-f81e9e79926d",
      "name": "Caută anul",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        840,
        0
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"name = '\" + $('Pe rând').first().json.an.replace(/'/g, \"\\\\'\") + \"' and '\" + ($('Setări').first().json.folderRadacinaId) + \"' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name)"
            },
            {
              "name": "pageSize",
              "value": "1"
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "abe2499d-3c69-4a6f-b4d3-a1cc8621c885",
      "name": "Există anul?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1040,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "2907c434-83c2-4e7a-9100-3946686c496c",
              "leftValue": "={{ ($json.files || []).length }}",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "rightValue": 0
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "3ac30e16-28b1-455e-9caa-850b4ed7fab5",
      "name": "Creează anul",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1240,
        120
      ],
      "parameters": {
        "resource": "folder",
        "name": "={{ $('Pe rând').first().json.an }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Setări').first().json.folderRadacinaId }}"
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "d2249d08-5571-4f6a-b230-a8943c8fc81e",
      "name": "Folder an",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1440,
        0
      ],
      "parameters": {
        "jsCode": "const it = $input.first().json;\nconst id = (it.files && it.files.length) ? it.files[0].id : it.id;\nreturn [{ json: { id }, pairedItem: 0 }];"
      }
    },
    {
      "id": "84af109d-4121-4c58-8d65-8195ee5a19f0",
      "name": "Caută luna",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1640,
        0
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"name = '\" + $('Pe rând').first().json.luna_folder.replace(/'/g, \"\\\\'\") + \"' and '\" + ($json.id) + \"' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name)"
            },
            {
              "name": "pageSize",
              "value": "1"
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "23d6efff-1942-4495-b8ed-0e58ebcffd66",
      "name": "Există luna?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1840,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "a536bebc-c86b-4e0f-9c57-213f91c57418",
              "leftValue": "={{ ($json.files || []).length }}",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "rightValue": 0
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "fbe6e930-6c36-4935-8451-7d063ec2c44d",
      "name": "Creează luna",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2040,
        120
      ],
      "parameters": {
        "resource": "folder",
        "name": "={{ $('Pe rând').first().json.luna_folder }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Folder an').first().json.id }}"
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "a0d2c772-b654-424f-8dee-ae577a5850b4",
      "name": "Folder lună",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2240,
        0
      ],
      "parameters": {
        "jsCode": "const it = $input.first().json;\nconst id = (it.files && it.files.length) ? it.files[0].id : it.id;\nreturn [{ json: { id }, pairedItem: 0 }];"
      }
    },
    {
      "id": "6d16c71a-4ca2-4741-a85b-4b5788ff60f3",
      "name": "Caută furnizorul",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2440,
        0
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"name = '\" + $('Pe rând').first().json.furnizor_folder.replace(/'/g, \"\\\\'\") + \"' and '\" + ($json.id) + \"' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name)"
            },
            {
              "name": "pageSize",
              "value": "1"
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "4287d2ef-535c-42f3-9320-0ea31a64dd5c",
      "name": "Există furnizorul?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2640,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "e3ec8f8b-835d-49b4-86f0-331add4bfd66",
              "leftValue": "={{ ($json.files || []).length }}",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "rightValue": 0
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "350e0a49-a572-499c-a4f3-38f217db69de",
      "name": "Creează furnizorul",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2840,
        120
      ],
      "parameters": {
        "resource": "folder",
        "name": "={{ $('Pe rând').first().json.furnizor_folder }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Folder lună').first().json.id }}"
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "afd3559b-4964-4272-b364-ccb782a430f7",
      "name": "Folderul final",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3040,
        0
      ],
      "parameters": {
        "jsCode": "const it = $input.first().json;\nconst folderId = (it.files && it.files.length) ? it.files[0].id : it.id;\nreturn [{ json: { folderId }, pairedItem: 0 }];"
      }
    },
    {
      "id": "35ebd4eb-b415-4d9f-9b36-e5ce239c155e",
      "name": "Există deja factura?",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3240,
        0
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"name = '\" + $('Pe rând').first().json.nume_fisier.replace(/'/g, \"\\\\'\") + \"' and '\" + $json.folderId + \"' in parents and trashed = false\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name)"
            },
            {
              "name": "pageSize",
              "value": "1"
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "7e5c5f4c-2c10-47ba-9bf2-f7ca52e06b17",
      "name": "E duplicat?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3440,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "6c5dda3b-a108-440e-9214-962ec5bfd743",
              "leftValue": "={{ ($json.files || []).length }}",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "rightValue": 0
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "015d09ad-bbb4-4a97-939d-3c7998d6399f",
      "name": "Rezultat: duplicat",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3660,
        -120
      ],
      "parameters": {
        "jsCode": "const f = $('Pe rând').first().json;\nreturn [{ json: { status: 'duplicat', fisier_original: f.fisier_original, nume_fisier: f.nume_fisier, motiv: 'Există deja în folderul furnizorului' }, pairedItem: 0 }];"
      }
    },
    {
      "id": "7d58f15d-7952-4cca-9483-9249edabca2f",
      "name": "Reatașează fișierul",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3660,
        80
      ],
      "parameters": {
        "jsCode": "const f = $('Pe rând').first();\nreturn [{ json: { ...f.json, folderId: $('Folderul final').first().json.folderId }, binary: f.binary, pairedItem: 0 }];"
      }
    },
    {
      "id": "c544c050-3a03-44fb-8489-ed281852bea1",
      "name": "Încarcă factura",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        3880,
        80
      ],
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "name": "={{ $json.nume_fisier }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.folderId }}"
        },
        "inputDataFieldName": "data",
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "ab912ded-0165-43e7-8d82-86b1e480c4c3",
      "name": "Rezultat: arhivată",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4100,
        80
      ],
      "parameters": {
        "jsCode": "const f = $('Pe rând').first().json;\nreturn [{ json: { status: 'ok', fisier_original: f.fisier_original, nume_fisier: f.nume_fisier, cale: f.an + '/' + f.luna_folder + '/' + f.furnizor_folder, link: $input.first().json.webViewLink || '' }, pairedItem: 0 }];"
      }
    },
    {
      "id": "95621c87-ca72-4c5a-ac43-ea68e3a5dbfe",
      "name": "Pregătește verificarea",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        840,
        360
      ],
      "parameters": {
        "jsCode": "const f = $('Pe rând').first();\nreturn [{ json: { ...f.json }, binary: f.binary, pairedItem: 0 }];"
      }
    },
    {
      "id": "b9eb9107-7af8-4549-a0ed-d6790f2773e1",
      "name": "Încarcă în De verificat",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1060,
        360
      ],
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "name": "={{ $json.nume_verificare }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Setări').first().json.folderDeVerificatId }}"
        },
        "inputDataFieldName": "data",
        "options": {}
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "De conectat"
        }
      }
    },
    {
      "id": "78a8e165-7403-472b-a96a-9e1663d6940b",
      "name": "Rezultat: de verificat",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        360
      ],
      "parameters": {
        "jsCode": "const f = $('Pe rând').first().json;\nreturn [{ json: { status: 'de_verificat', fisier_original: f.fisier_original, nume_fisier: f.nume_verificare, motiv: f.motive.join('; ') }, pairedItem: 0 }];"
      }
    },
    {
      "id": "7bc4c6ce-b285-49c0-9280-c869b2b0eb78",
      "name": "Rezumat",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        620,
        -160
      ],
      "parameters": {
        "jsCode": "const r = $input.all().map(i => i.json);\nreturn [{ json: {\n  procesate: r.length,\n  arhivate: r.filter(x => x.status === 'ok').length,\n  duplicate: r.filter(x => x.status === 'duplicat').length,\n  de_verificat: r.filter(x => x.status === 'de_verificat').length,\n  detalii: r,\n} }];"
      }
    },
    {
      "id": "59593f19-1798-4919-805b-88878f8b34fb",
      "name": "Notă",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1660,
        -420
      ],
      "parameters": {
        "width": 620,
        "height": 360,
        "content": "## Facturi din e-mail în Google Drive (Firma lui Dan, EP4)\n\n**Ce face:** ia facturile PDF și XML (e-Factura) din e-mail, le verifică și le pune în Drive pe **an / lună / furnizor**, cu nume de forma `2026-11-03_Furnizor_SERIE-123.pdf`.\n\n**Verificări:** e factură? CUI valid (cifra de control)? total fără TVA + TVA = total? există deja în folder? Ce nu trece ajunge în folderul **De verificat**, cu motivul în nume.\n\n**Configurare (5 minute):**\n1. Conectează Gmail, Google Drive și OpenAI (sau alt model AI).\n2. În **Setări** pune ID-ul folderului rădăcină și al folderului De verificat (din linkul folderului).\n3. Activează workflow-ul.\n\nXML-ul e-Factura e citit direct, fără AI. AI-ul citește doar PDF-urile.\n\n**Test fără e-mail:** trimite fișiere prin POST (multipart) la webhook-ul „Test: trimite facturi”.\n"
      }
    }
  ],
  "connections": {
    "Gmail: facturi noi": {
      "main": [
        [
          {
            "node": "Setări",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Test: trimite facturi": {
      "main": [
        [
          {
            "node": "Setări",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Setări": {
      "main": [
        [
          {
            "node": "Separă atașamentele",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Separă atașamentele": {
      "main": [
        [
          {
            "node": "PDF sau XML?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PDF sau XML?": {
      "main": [
        [
          {
            "node": "Citește e-Factura (XML)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Extrage text din PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extrage text din PDF": {
      "main": [
        [
          {
            "node": "Citește factura (AI)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Model AI (OpenAI)": {
      "ai_languageModel": [
        [
          {
            "node": "Citește factura (AI)",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Citește factura (AI)": {
      "main": [
        [
          {
            "node": "Combină rezultatul AI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Citește e-Factura (XML)": {
      "main": [
        [
          {
            "node": "Adună XML și PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Combină rezultatul AI": {
      "main": [
        [
          {
            "node": "Adună XML și PDF",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Adună XML și PDF": {
      "main": [
        [
          {
            "node": "Verificări",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificări": {
      "main": [
        [
          {
            "node": "Pe rând",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pe rând": {
      "main": [
        [
          {
            "node": "Rezumat",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "E în regulă?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "E în regulă?": {
      "main": [
        [
          {
            "node": "Caută anul",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Pregătește verificarea",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Caută anul": {
      "main": [
        [
          {
            "node": "Există anul?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Există anul?": {
      "main": [
        [
          {
            "node": "Folder an",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Creează anul",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Creează anul": {
      "main": [
        [
          {
            "node": "Folder an",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Folder an": {
      "main": [
        [
          {
            "node": "Caută luna",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Caută luna": {
      "main": [
        [
          {
            "node": "Există luna?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Există luna?": {
      "main": [
        [
          {
            "node": "Folder lună",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Creează luna",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Creează luna": {
      "main": [
        [
          {
            "node": "Folder lună",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Folder lună": {
      "main": [
        [
          {
            "node": "Caută furnizorul",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Caută furnizorul": {
      "main": [
        [
          {
            "node": "Există furnizorul?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Există furnizorul?": {
      "main": [
        [
          {
            "node": "Folderul final",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Creează furnizorul",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Creează furnizorul": {
      "main": [
        [
          {
            "node": "Folderul final",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Folderul final": {
      "main": [
        [
          {
            "node": "Există deja factura?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Există deja factura?": {
      "main": [
        [
          {
            "node": "E duplicat?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "E duplicat?": {
      "main": [
        [
          {
            "node": "Rezultat: duplicat",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reatașează fișierul",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reatașează fișierul": {
      "main": [
        [
          {
            "node": "Încarcă factura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Încarcă factura": {
      "main": [
        [
          {
            "node": "Rezultat: arhivată",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rezultat: duplicat": {
      "main": [
        [
          {
            "node": "Pe rând",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rezultat: arhivată": {
      "main": [
        [
          {
            "node": "Pe rând",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pregătește verificarea": {
      "main": [
        [
          {
            "node": "Încarcă în De verificat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Încarcă în De verificat": {
      "main": [
        [
          {
            "node": "Rezultat: de verificat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rezultat: de verificat": {
      "main": [
        [
          {
            "node": "Pe rând",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Bucharest"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "pinData": {}
}