{
  "name": "facturai: CRM deal to E-Rechnung, email and storage",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "facturai-crm-deal-invoice",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "facturai-deal-webhook",
      "name": "Deal won webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        220,
        320
      ],
      "webhookId": "facturai-crm-deal-invoice"
    },
    {
      "parameters": {
        "jsCode": "const deal = $input.first().json.body ?? $input.first().json;\nconst today = new Date().toISOString().slice(0, 10);\nconst dueDate = new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);\nconst rawAddress = deal.customer_address ?? {};\nconst address = typeof rawAddress === 'object' && rawAddress !== null ? rawAddress : {};\nconst lineItems = Array.isArray(deal.line_items) && deal.line_items.length > 0\n  ? deal.line_items\n  : [\n      {\n        name: deal.product_name || deal.title || 'Leistung',\n        description: deal.description ?? null,\n        quantity: deal.quantity || 1,\n        unit: deal.unit || 'C62',\n        unit_price: deal.unit_price ?? deal.value ?? deal.amount ?? '0.00',\n        vat_rate: deal.vat_rate ?? '19.00'\n      }\n    ];\nconst dealId = String(deal.id || deal.deal_id || Date.now());\nconst customerEmail = deal.customer_email || deal.email || deal.buyer?.contact_email || null;\nconst numberPrefix = deal.number_prefix || `RE-${new Date().getFullYear()}`;\n\nreturn [\n  {\n    json: {\n      deal_id: dealId,\n      customer_email: customerEmail,\n      storage_file_name: `facturai-${numberPrefix}-${dealId}.pdf`,\n      invoice_input: {\n        invoice_date: deal.invoice_date || today,\n        due_date: deal.due_date || dueDate,\n        currency: deal.currency || 'EUR',\n        buyer: {\n          name: deal.customer_name || deal.company_name || deal.buyer?.name,\n          address: {\n            line_one: address.line_one || deal.customer_address_line_one || deal.customer_street,\n            postcode: address.postcode || deal.customer_postcode,\n            city: address.city || deal.customer_city,\n            country: address.country || deal.customer_country || 'DE'\n          },\n          vat_id: deal.customer_vat_id ?? deal.buyer?.vat_id ?? null,\n          buyer_reference: deal.buyer_reference ?? deal.purchase_order ?? null,\n          contact_email: customerEmail\n        },\n        lines: lineItems.map((item) => ({\n          name: item.name || item.title || 'Leistung',\n          description: item.description ?? null,\n          quantity: String(item.quantity ?? 1),\n          unit: item.unit || 'C62',\n          unit_price: String(item.unit_price ?? item.price ?? item.amount ?? '0.00'),\n          vat_rate: String(item.vat_rate ?? '19.00')\n        })),\n        allowances: Array.isArray(deal.allowances) ? deal.allowances : [],\n        charges: Array.isArray(deal.charges) ? deal.charges : [],\n        number_prefix: numberPrefix\n      }\n    }\n  }\n];"
      },
      "id": "facturai-map-deal",
      "name": "Map deal to Facturai input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        320
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://fakturai.de/api/v1/invoices",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-API-Key",
              "value": "={{ $env.FACTURAI_API_KEY || 'replace-with-your-api-key' }}"
            },
            {
              "name": "Accept",
              "value": "application/pdf"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.invoice_input) }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file",
              "outputPropertyName": "data"
            }
          },
          "retry": {
            "enabled": true,
            "maxTries": 3
          }
        }
      },
      "id": "facturai-create-deal-invoice",
      "name": "Create E-Rechnung PDF",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        740,
        320
      ]
    },
    {
      "parameters": {
        "jsCode": "const item = $input.first();\nconst fileName = $('Map deal to Facturai input').item.json.storage_file_name;\n\nif (item.binary?.data) {\n  item.binary.data.fileName = fileName;\n  item.binary.data.mimeType = 'application/pdf';\n}\n\nreturn [item];"
      },
      "id": "facturai-set-pdf-filename",
      "name": "Set PDF filename",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1000,
        320
      ]
    },
    {
      "parameters": {
        "fromEmail": "={{ $env.FACTURAI_FROM_EMAIL || 'rechnung@example.com' }}",
        "toEmail": "={{ $('Map deal to Facturai input').item.json.customer_email }}",
        "subject": "=Ihre E-Rechnung zum Auftrag {{ $('Map deal to Facturai input').item.json.deal_id }}",
        "emailType": "text",
        "message": "=Guten Tag,\n\nim Anhang erhalten Sie die EN 16931-konforme E-Rechnung zu Auftrag {{ $('Map deal to Facturai input').item.json.deal_id }}.\n\nViele Gruesse",
        "attachments": "data",
        "options": {}
      },
      "id": "facturai-send-email",
      "name": "Send invoice email",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1260,
        220
      ],
      "notes": "Connect your SMTP, Gmail, SendGrid, or other n8n email credential before activating."
    },
    {
      "parameters": {
        "fileName": "=/tmp/{{ $('Map deal to Facturai input').item.json.storage_file_name }}"
      },
      "id": "facturai-store-pdf",
      "name": "Store PDF locally",
      "type": "n8n-nodes-base.writeBinaryFile",
      "typeVersion": 1,
      "position": [
        1260,
        420
      ],
      "notes": "For production, replace this node with Google Drive, S3, Dropbox, or your document management system."
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={ \"status\": \"ok\", \"deal_id\": \"{{ $('Map deal to Facturai input').item.json.deal_id }}\", \"file\": \"{{ $('Map deal to Facturai input').item.json.storage_file_name }}\" }"
      },
      "id": "facturai-respond-ok",
      "name": "Respond OK",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1500,
        320
      ]
    }
  ],
  "connections": {
    "Deal won webhook": {
      "main": [
        [
          {
            "node": "Map deal to Facturai input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map deal to Facturai input": {
      "main": [
        [
          {
            "node": "Create E-Rechnung PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create E-Rechnung PDF": {
      "main": [
        [
          {
            "node": "Set PDF filename",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set PDF filename": {
      "main": [
        [
          {
            "node": "Store PDF locally",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send invoice email": {
      "main": [
        [
          {
            "node": "Respond OK",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store PDF locally": {
      "main": [
        [
          {
            "node": "Send invoice email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {
    "Deal won webhook": [
      {
        "json": {
          "id": "4812",
          "company_name": "Acme GmbH",
          "customer_email": "buchhaltung@example.com",
          "customer_address_line_one": "Beispielweg 42",
          "customer_postcode": "80331",
          "customer_city": "Muenchen",
          "customer_country": "DE",
          "customer_vat_id": "DE123456789",
          "line_items": [
            {
              "name": "Software development",
              "description": "Implementation work",
              "quantity": 8,
              "unit": "HUR",
              "unit_price": "150.00",
              "vat_rate": "19.00"
            }
          ],
          "currency": "EUR",
          "number_prefix": "RE-2026"
        }
      }
    ]
  },
  "meta": {
    "templateId": "facturai-crm-deal-email-storage-v1",
    "description": "Maps CRM/deal data to the public FacturaiInvoiceInput schema, generates an EN 16931 / ZUGFeRD PDF, emails it, and stores a PDF copy."
  },
  "_readme": {
    "setup": [
      "Import this workflow into n8n.",
      "Set FACTURAI_API_KEY in the n8n environment, or replace the X-API-Key header value in the HTTP Request node.",
      "Connect an email credential and replace the local storage node with your preferred storage provider if needed.",
      "Adapt the mapping node to your CRM field names before activating."
    ],
    "api_docs": "https://fakturai.de/docs/api",
    "schema_ref": "https://fakturai.de/schemas/invoice-input/v1.json"
  }
}
