{
  "name": "Blueprint: faktury kosztowe z poczty na Dysk i do arkusza",
  "nodes": [
    {
      "parameters": {
        "content": "## Faktury kosztowe z poczty\nOpis i konfiguracja krok po kroku: strona tego blueprintu (sekcja Blueprinty, „faktury-z-poczty”).\n\n1. Najlepiej osobna skrzynka albo alias na faktury (np. faktury@ w domenie firmy).\n2. W węźle **Ustawienia** wpisać ID folderu na Dysku, ID arkusza i słowa, po których poznać fakturę.\n3. **Test z przykładowymi danymi**: przy `trybTestowy = true` nic nie trafia na Dysk ani do arkusza.\n4. Podpiąć konta: IMAP, Google (Dysk i Arkusze), SMTP. Potem `trybTestowy = false` i włączyć workflow.",
        "height": 320,
        "width": 460,
        "color": 7
      },
      "id": "28635acc-6e5e-4cd2-a62f-7049e16d3838",
      "name": "Jak zacząć",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -760,
        -420
      ]
    },
    {
      "parameters": {},
      "id": "8a399f51-ebb6-454e-a7d9-649730b552f4",
      "name": "Test z przykładowymi danymi",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -760,
        200
      ]
    },
    {
      "parameters": {
        "mailbox": "INBOX",
        "postProcessAction": "read",
        "format": "simple",
        "downloadAttachments": true,
        "dataPropertyAttachmentsPrefixName": "attachment_",
        "options": {
          "customEmailConfig": "[\"UNSEEN\"]"
        }
      },
      "id": "c22ec123-1557-4961-a9b6-72e1685aae04",
      "name": "Poczta: nowe maile z fakturami",
      "type": "n8n-nodes-base.emailReadImap",
      "typeVersion": 2.2,
      "position": [
        -760,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Dane poglądowe: trzy maile w kształcie z węzła IMAP (format simple, załączniki attachment_N).\nconst pdf = (tekst) => ({ data: Buffer.from(`%PDF-1.4\\n% ${tekst}\\n%%EOF\\n`).toString('base64'), mimeType: 'application/pdf' });\nconst obraz = { data: Buffer.from('logo').toString('base64'), mimeType: 'image/png', fileName: 'logo.png' };\nreturn [\n  { json: { from: 'Hurtownia Przykładowa <faktury@example.com>', subject: 'Faktura FV/2026/11/014', date: '2026-11-16T09:12:00+01:00' },\n    binary: { attachment_0: { ...pdf('faktura 14 (dane poglądowe)'), fileName: 'FV_2026_11_014.pdf' }, attachment_1: obraz } },\n  // Ten sam plik przysłany drugi raz (przypomnienie od dostawcy): deduplikacja po skrócie ma go pominąć.\n  { json: { from: 'Hurtownia Przykładowa <faktury@example.com>', subject: 'Przypomnienie: Faktura FV/2026/11/014', date: '2026-11-17T08:00:00+01:00' },\n    binary: { attachment_0: { ...pdf('faktura 14 (dane poglądowe)'), fileName: 'FV_2026_11_014.pdf' } } },\n  // Mail bez faktury (newsletter z PDF-em cennika): odpada na filtrze słów w temacie i nazwie pliku.\n  { json: { from: 'Newsletter <news@example.com>', subject: 'Nowości w ofercie', date: '2026-11-17T10:00:00+01:00' },\n    binary: { attachment_0: { ...pdf('cennik'), fileName: 'cennik-2027.pdf' } } },\n];\n"
      },
      "id": "d9b07327-31ff-403b-a71d-2e8254c4680c",
      "name": "Przykładowe dane",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -520,
        200
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "76825dc0-a53a-4abc-a2ef-59834b8f59cc",
              "name": "trybTestowy",
              "value": true,
              "type": "boolean"
            },
            {
              "id": "272db8ea-66cc-4c46-a787-98607cf3ad57",
              "name": "folderFakturId",
              "value": "WPISZ_ID_FOLDERU_NA_DYSKU",
              "type": "string"
            },
            {
              "id": "7f44c458-499e-48c8-ac9c-cd77fbb0d2c9",
              "name": "arkuszId",
              "value": "WPISZ_ID_ARKUSZA",
              "type": "string"
            },
            {
              "id": "efe7ef3d-1e9b-48de-a83c-eda2cb8047bf",
              "name": "zakladka",
              "value": "Faktury",
              "type": "string"
            },
            {
              "id": "2a1d9e0a-8d75-4fc6-a5c2-53ee9b1f7643",
              "name": "slowaFaktury",
              "value": "faktur,fv,invoice,rachunek",
              "type": "string"
            },
            {
              "id": "e42da1f1-6cae-4308-a508-db169dcf7faf",
              "name": "adresNadawcy",
              "value": "automatyzacje@example.com",
              "type": "string"
            },
            {
              "id": "fa363c88-6f45-40ae-a8e5-b93add7fcbf1",
              "name": "adresAlertow",
              "value": "ksiegowosc@example.com",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "37d2f7fa-8f98-469d-a4c8-61a6ff1f697f",
      "name": "Ustawienia",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.5,
      "position": [
        -280,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Jeden element na każdy załącznik PDF, który wygląda na fakturę. Plik zostaje jako binary.data.\nconst ust = $('Ustawienia').first().json;\nconst slowa = String(ust.slowaFaktury ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);\nconst wynik = [];\n$input.all().forEach((item, indeks) => {\n  const j = item.json;\n  const nadawca = String(j.from?.text ?? j.from ?? '').trim();\n  const temat = String(j.subject ?? '').trim();\n  let data = DateTime.fromISO(String(j.date ?? ''), { zone: 'Europe/Warsaw' });\n  if (!data.isValid) data = DateTime.fromJSDate(new Date(j.date ?? Date.now())).setZone('Europe/Warsaw');\n  if (!data.isValid) data = DateTime.now().setZone('Europe/Warsaw');\n  for (const [klucz, plik] of Object.entries(item.binary ?? {})) {\n    const nazwa = String(plik.fileName ?? `${klucz}.pdf`);\n    if (plik.mimeType !== 'application/pdf' && !/\\.pdf$/i.test(nazwa)) continue;\n    const opis = `${temat} ${nazwa}`.toLowerCase();\n    if (slowa.length && !slowa.some((s) => opis.includes(s))) continue;\n    // Numer z tematu albo nazwy pliku (FV/2026/11/014, FA_12_2026). Tylko podpowiedź, księgowość sprawdza w PDF.\n    const numer = (`${temat} ${nazwa}`.match(/\\b(?:FV|FA|FS|F)[\\s/_-]*\\d+(?:[/_-]\\d+){1,3}\\b/i)?.[0] ?? '').replace(/_/g, '/');\n    wynik.push({\n      json: { nadawca, temat, dataMaila: data.toISODate(), miesiac: data.toFormat('yyyy-LL'), nazwaPliku: nazwa, numerFaktury: numer },\n      binary: { data: plik },\n      pairedItem: { item: indeks },\n    });\n  }\n});\nreturn wynik;\n"
      },
      "id": "bc8eadfb-122e-4f47-ae5e-1dd3460663bf",
      "name": "Załączniki PDF",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -40,
        0
      ]
    },
    {
      "parameters": {
        "action": "hash",
        "binaryData": true,
        "binaryPropertyName": "data",
        "type": "SHA256",
        "dataPropertyName": "skrot",
        "encoding": "hex"
      },
      "id": "6dade57d-ab2f-491b-ade8-761acab11196",
      "name": "Skrót pliku (SHA-256)",
      "type": "n8n-nodes-base.crypto",
      "typeVersion": 2,
      "position": [
        200,
        0
      ]
    },
    {
      "parameters": {
        "operation": "removeDuplicateInputItems",
        "compare": "selectedFields",
        "fieldsToCompare": "skrot",
        "options": {}
      },
      "id": "1d7f3c53-ccb4-4bf9-a5f2-93e967a9e77f",
      "name": "Bez powtórek w jednej partii",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        440,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 4
          },
          "conditions": [
            {
              "id": "d324d612-170b-49ed-a65f-3fa03adbf58f",
              "leftValue": "={{ $('Ustawienia').first().json.trybTestowy }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "id": "3cc664f2-e3c0-4158-a75d-99e945fe6ca3",
      "name": "Tryb testowy?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.4,
      "position": [
        680,
        0
      ]
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "dedupeValue": "={{ $json.skrot }}",
        "options": {}
      },
      "id": "f2048486-3190-46aa-a8f6-c43b56c5c322",
      "name": "Bez faktur już zapisanych",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        920,
        100
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b1",
              "name": "plikNaDysku",
              "value": "={{ $json.miesiac }}_{{ $json.nazwaPliku }}",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "df700048-ffcf-45c5-a87c-dced179b6769",
      "name": "Wynik testu: co trafiłoby do arkusza",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.5,
      "position": [
        920,
        -200
      ]
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "inputDataFieldName": "data",
        "name": "={{ $json.miesiac }}_{{ $json.nazwaPliku }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Ustawienia').first().json.folderFakturId }}"
        },
        "options": {}
      },
      "id": "be5d9189-32ae-4a00-a7d4-6cc7d1ae77ee",
      "name": "PDF na Dysk Google",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1160,
        100
      ],
      "onError": "continueErrorOutput",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "w1",
              "name": "Data maila",
              "value": "={{ $('Bez faktur już zapisanych').item.json.dataMaila }}",
              "type": "string"
            },
            {
              "id": "w2",
              "name": "Nadawca",
              "value": "={{ $('Bez faktur już zapisanych').item.json.nadawca }}",
              "type": "string"
            },
            {
              "id": "w3",
              "name": "Temat",
              "value": "={{ $('Bez faktur już zapisanych').item.json.temat }}",
              "type": "string"
            },
            {
              "id": "w4",
              "name": "Numer (z nazwy pliku)",
              "value": "={{ $('Bez faktur już zapisanych').item.json.numerFaktury }}",
              "type": "string"
            },
            {
              "id": "w5",
              "name": "Plik",
              "value": "={{ $json.name }}",
              "type": "string"
            },
            {
              "id": "w6",
              "name": "ID pliku na Dysku",
              "value": "={{ $json.id }}",
              "type": "string"
            },
            {
              "id": "w7",
              "name": "Skrót SHA-256",
              "value": "={{ $('Bez faktur już zapisanych').item.json.skrot }}",
              "type": "string"
            },
            {
              "id": "w8",
              "name": "Status",
              "value": "do zaksięgowania",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      },
      "id": "c329803d-c9ce-40e5-a629-f90a4a78642b",
      "name": "Wiersz do arkusza",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.5,
      "position": [
        1400,
        0
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Ustawienia').first().json.arkuszId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Ustawienia').first().json.zakladka }}"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        },
        "options": {}
      },
      "id": "52e4a3bc-5720-4cdb-a62b-1fbad769ddca",
      "name": "Wiersz w arkuszu księgowości",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1640,
        0
      ],
      "onError": "continueErrorOutput",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "fromEmail": "={{ $('Ustawienia').first().json.adresNadawcy }}",
        "toEmail": "={{ $('Ustawienia').first().json.adresAlertow }}",
        "subject": "=Faktura nie zapisała się automatycznie: {{ $('Bez faktur już zapisanych').item.json.nazwaPliku }}",
        "emailFormat": "text",
        "text": "=Plik „{{ $('Bez faktur już zapisanych').item.json.nazwaPliku }}” z maila od {{ $('Bez faktur już zapisanych').item.json.nadawca }} ({{ $('Bez faktur już zapisanych').item.json.dataMaila }}) nie zapisał się na Dysku albo w arkuszu.\n\nBłąd: {{ $json.error?.message ?? $json.error ?? 'brak opisu' }}\n\nMail jest w skrzynce, plik trzeba zapisać ręcznie.",
        "options": {
          "appendAttribution": false
        }
      },
      "id": "d27fcb92-b35b-47e4-a363-ab47f1d32d9e",
      "name": "Błąd zapisu: mail do księgowości",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1640,
        300
      ]
    },
    {
      "parameters": {},
      "id": "0edfa2be-d5c8-47b0-a687-580d8fc0bee1",
      "name": "Awaria workflowu",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -760,
        520
      ]
    },
    {
      "parameters": {
        "fromEmail": "automatyzacje@example.com",
        "toEmail": "alerty@example.com",
        "subject": "=Awaria workflowu: {{ $json.workflow.name }}",
        "emailFormat": "text",
        "text": "=Workflow „{{ $json.workflow.name }}” zatrzymał się z błędem.\n\nWęzeł: {{ $json.execution.lastNodeExecuted }}\nBłąd: {{ $json.execution.error.message }}\nWykonanie nr: {{ $json.execution.id }}\n\nSzczegóły w n8n: Executions.",
        "options": {
          "appendAttribution": false
        }
      },
      "id": "e676a8f6-3e1a-4987-a10c-cdb841547114",
      "name": "Mail o awarii",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        -520,
        520
      ]
    }
  ],
  "connections": {
    "Poczta: nowe maile z fakturami": {
      "main": [
        [
          {
            "node": "Ustawienia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Test z przykładowymi danymi": {
      "main": [
        [
          {
            "node": "Przykładowe dane",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Przykładowe dane": {
      "main": [
        [
          {
            "node": "Ustawienia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ustawienia": {
      "main": [
        [
          {
            "node": "Załączniki PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Załączniki PDF": {
      "main": [
        [
          {
            "node": "Skrót pliku (SHA-256)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skrót pliku (SHA-256)": {
      "main": [
        [
          {
            "node": "Bez powtórek w jednej partii",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Bez powtórek w jednej partii": {
      "main": [
        [
          {
            "node": "Tryb testowy?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tryb testowy?": {
      "main": [
        [
          {
            "node": "Wynik testu: co trafiłoby do arkusza",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Bez faktur już zapisanych",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Bez faktur już zapisanych": {
      "main": [
        [
          {
            "node": "PDF na Dysk Google",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PDF na Dysk Google": {
      "main": [
        [
          {
            "node": "Wiersz do arkusza",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Błąd zapisu: mail do księgowości",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wiersz do arkusza": {
      "main": [
        [
          {
            "node": "Wiersz w arkuszu księgowości",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wiersz w arkuszu księgowości": {
      "main": [
        [],
        [
          {
            "node": "Błąd zapisu: mail do księgowości",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Awaria workflowu": {
      "main": [
        [
          {
            "node": "Mail o awarii",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Warsaw",
    "saveManualExecutions": true,
    "callerPolicy": "workflowsFromSameOwner"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
