{
  "name": "Generate invoice PDFs from Google Sheets with Bitavu, Drive and Gmail drafts",
  "nodes": [
    {
      "parameters": {
        "content": "# 1. Try the sample\nRun manually with **useSampleData** enabled. Connect the Bitavu credential, then download `pdf` from **Generate PDF → Binary**. Sample mode does not use Google.",
        "width": 430,
        "height": 230,
        "color": 5
      },
      "id": "abaef3a6-d6e9-4260-b926-583395c9c16f",
      "name": "1. Try the sample",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -150
      ]
    },
    {
      "parameters": {
        "content": "# 2. Read an approved invoice\nImport the companion workbook into Google Sheets. Set the spreadsheet ID and invoice number in **Workflow settings**. Select the same Sheets credential on both readers and all four status updates.",
        "width": 440,
        "height": 230,
        "color": 7
      },
      "id": "a5d765c1-a68d-451f-9ea9-e2a409b4d7ad",
      "name": "2. Read an approved invoice",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        450,
        -150
      ]
    },
    {
      "parameters": {
        "content": "# 3. Archive before drafting\nSelect your Drive and Gmail credentials and set a private My Drive folder ID. A complete row is skipped. If a run stops while a write is pending, reconcile it in Drive or Gmail before retrying.",
        "width": 510,
        "height": 230,
        "color": 4
      },
      "id": "9a7fef31-77bb-418b-a497-20863adb7ed5",
      "name": "3. Archive before drafting",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        960,
        -150
      ]
    },
    {
      "parameters": {},
      "id": "5f270e91-7027-487d-b3c4-296b25319a31",
      "name": "Manual trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        200
      ]
    },
    {
      "parameters": {
        "mode": "raw",
        "jsonOutput": "{\n  \"useSampleData\": true,\n  \"invoiceNumber\": \"INV-1042\",\n  \"spreadsheetId\": \"YOUR_GOOGLE_SPREADSHEET_ID\",\n  \"driveFolderId\": \"YOUR_MY_DRIVE_FOLDER_ID\",\n  \"templateId\": \"invoice\",\n  \"revision\": 1\n}",
        "options": {}
      },
      "id": "3609e605-a22e-4e0a-b9c7-1918c7ef2d9a",
      "name": "Workflow settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.5,
      "position": [
        220,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "017fc7bd-6a4a-4fbe-82b5-a4da322ed65c",
              "leftValue": "={{ $json.useSampleData }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "82223139-ec5e-422c-bf7f-c6f424b98079",
      "name": "Use sample data?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        440,
        200
      ]
    },
    {
      "parameters": {
        "jsCode": "return [{ json: { invoice: {\"invoice_number\":\"INV-1042\",\"status\":\"APPROVED\",\"issue_date\":\"2026-11-12\",\"due_date\":\"2026-12-12\",\"customer_name\":\"Example Design Co.\",\"customer_address\":\"100 Example Avenue, Sample City\",\"customer_email\":\"billing@example.com\",\"approved_total_cents\":116000,\"notes\":\"Sample invoice. Include the invoice number with your payment.\",\"workflow_state\":\"\",\"drive_file_id\":\"\",\"gmail_draft_id\":\"\",\"invoice_fingerprint\":\"\"}, lines: [{\"invoice_number\":\"INV-1042\",\"line_number\":1,\"description\":\"Template design\",\"quantity\":1,\"unit_price_cents\":65000},{\"invoice_number\":\"INV-1042\",\"line_number\":2,\"description\":\"Workflow setup\",\"quantity\":2,\"unit_price_cents\":22000},{\"invoice_number\":\"INV-1042\",\"line_number\":3,\"description\":\"Handoff session\",\"quantity\":1,\"unit_price_cents\":7000}] } }];"
      },
      "id": "176df227-1816-4ccf-b4fa-216075507d05",
      "name": "Load sample rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        130
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.spreadsheetId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "invoice_number",
              "lookupValue": "={{ $('Workflow settings').first().json.invoiceNumber }}"
            }
          ]
        },
        "options": {
          "returnFirstMatch": false
        }
      },
      "id": "5e40575b-7e1e-4a82-9f37-5dc87888e5c5",
      "name": "Read invoice row",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        680,
        340
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "const config = $('Workflow settings').first().json;\nif (!/^[A-Za-z0-9_-]{1,50}$/.test(config.invoiceNumber)) throw new Error('Set an invoice number using letters, numbers, hyphens or underscores.');\nconst rows = $input.all().map(item => item.json).filter(row => row.invoice_number === config.invoiceNumber);\nif (rows.length !== 1) throw new Error('The Invoices tab must contain exactly one matching invoice number.');\nconst invoice = rows[0];\nif (invoice.status !== 'APPROVED') throw new Error('The matching invoice must have APPROVED status.');\nconst state = invoice.workflow_state || '';\nif (state === 'complete' && invoice.drive_file_id && invoice.gmail_draft_id) {\n  return [{ json: { invoice, alreadyComplete: true } }];\n}\nif (state === 'archive_pending' || state === 'draft_pending') {\n  throw new Error('A previous write may have succeeded. Reconcile the pending state using the setup guide before retrying.');\n}\nif (state === 'archived' ? (!invoice.drive_file_id || !invoice.invoice_fingerprint || invoice.gmail_draft_id) : (state !== '' || invoice.drive_file_id || invoice.gmail_draft_id || invoice.invoice_fingerprint)) {\n  throw new Error('The invoice checkpoint columns are inconsistent. Review the row before retrying.');\n}\nreturn [{ json: { invoice, alreadyComplete: false } }];"
      },
      "id": "ea93b0a1-4146-4055-8d29-d5a741bb9515",
      "name": "Check approval and status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        340
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ef1191fe-7b1f-496a-b65c-e28004701ba4",
              "leftValue": "={{ $json.alreadyComplete }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "68af9be7-1888-48ac-b227-e0b89ee49678",
      "name": "Already complete?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1120,
        340
      ]
    },
    {
      "parameters": {
        "jsCode": "const { invoice } = $input.first().json;\nreturn [{ json: { result: 'Already complete', invoice_number: invoice.invoice_number, drive_file_id: invoice.drive_file_id, gmail_draft_id: invoice.gmail_draft_id } }];"
      },
      "id": "2cb552fa-3621-4438-ab9f-be67db1bd13b",
      "name": "Show existing file and draft",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1340,
        270
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.spreadsheetId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Line Items"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "invoice_number",
              "lookupValue": "={{ $('Workflow settings').first().json.invoiceNumber }}"
            }
          ]
        },
        "options": {
          "returnFirstMatch": false
        }
      },
      "id": "f4a37c5c-8070-4585-b933-ae38e0e78f26",
      "name": "Read invoice line items",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1340,
        480
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "const invoice = $('Check approval and status').first().json.invoice;\nreturn [{ json: { invoice, lines: $input.all().map(item => item.json).filter(row => row.invoice_number === invoice.invoice_number) } }];"
      },
      "id": "5d5a28bb-7654-4e08-b0b6-742245f2e2ce",
      "name": "Collect Sheets rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        480
      ]
    },
    {
      "parameters": {
        "jsCode": "const { invoice, lines } = $input.first().json;\nconst config = $('Workflow settings').first().json;\nconst clean = value => String(value ?? '').trim();\nconst integer = (value, label, min) => {\n  const text = clean(value);\n  const n = Number(text);\n  if (!/^\\d+$/.test(text) || !Number.isSafeInteger(n) || n < min) throw new Error('Invalid ' + label);\n  return n;\n};\nconst date = (value, label) => {\n  const text = clean(value);\n  const ms = Date.parse(text);\n  if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(text) || !Number.isFinite(ms) || new Date(ms).toISOString().slice(0, 10) !== text) throw new Error(label + ' must be text in YYYY-MM-DD format.');\n  return text;\n};\nconst issue = date(invoice.issue_date, 'Issue date');\nconst due = date(invoice.due_date, 'Due date');\nif (due < issue) throw new Error('Due date must be on or after the issue date.');\nconst email = clean(invoice.customer_email);\nif (!/^[^\\s,@;<>]+@[^\\s,@;<>]+\\.[^\\s,@;<>]+$/.test(email)) throw new Error('Enter one customer email address.');\nconst client = { name: clean(invoice.customer_name), address: clean(invoice.customer_address) };\nif (!client.name || !client.address || !lines.length) throw new Error('Customer name, billing address and line items are required.');\nconst ordered = lines.map(row => {\n  const description = clean(row.description);\n  if (!description) throw new Error('Every line needs a description.');\n  return { order: integer(row.line_number, 'line number', 1), description, quantity: integer(row.quantity, 'quantity', 1), cents: integer(row.unit_price_cents, 'price in cents', 0) };\n}).sort((a, b) => a.order - b.order);\nif (new Set(ordered.map(row => row.order)).size !== ordered.length) throw new Error('Duplicate line number on this invoice.');\nconst total = ordered.reduce((sum, row) => sum + row.quantity * row.cents, 0);\nif (!Number.isSafeInteger(total) || total !== integer(invoice.approved_total_cents, 'approved total in cents', 0)) throw new Error('Line items must add up to the approved total in cents.');\nif (!clean(config.templateId) || !Number.isSafeInteger(config.revision) || config.revision < 1) throw new Error('Set the Bitavu template ID and a saved numeric revision.');\nif (!config.useSampleData && (!clean(config.driveFolderId) || config.driveFolderId === 'YOUR_MY_DRIVE_FOLDER_ID')) throw new Error('Set the ID of the private archive folder in Workflow settings.');\nconst data = {\n  invoice: { number: invoice.invoice_number, date: issue, due },\n  client, items: ordered.map(({ description, quantity, cents }) => ({ description, quantity, unitPrice: cents / 100 })),\n  notes: clean(invoice.notes),\n};\n// Stable checksum for this example's retry and change detection. It is not an authentication token.\nlet hash = 0xcbf29ce484222325n;\nfor (const char of JSON.stringify([config.spreadsheetId, config.templateId, config.revision, config.driveFolderId, email, data])) {\n  hash = BigInt.asUintN(64, (hash ^ BigInt(char.codePointAt(0))) * 0x100000001b3n);\n}\nconst fingerprint = 'v1-' + hash.toString(16).padStart(16, '0');\nconst driveFileId = clean(invoice.drive_file_id);\nif (driveFileId && invoice.invoice_fingerprint !== fingerprint) throw new Error('The invoice, destination or template version changed after the PDF was stored. Reconcile the existing archive before proceeding.');\nreturn [{ json: { data, email, driveFileId, fingerprint, filename: invoice.invoice_number + '.pdf', sample: config.useSampleData,\n  operationId: config.useSampleData ? '' : 'gs-invoice-' + fingerprint, approved_total_cents: total } }];"
      },
      "id": "893005f4-cc5a-484d-b858-8939691a0802",
      "name": "Build invoice payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1780,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "12a52b0b-686c-4d36-b636-b3429d6ca815",
              "leftValue": "={{ Boolean($json.driveFileId) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "1e0a2ad2-ac69-468a-aa25-998e9f314a21",
      "name": "Already archived?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2000,
        200
      ]
    },
    {
      "parameters": {
        "templateId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.templateId }}"
        },
        "versionSelection": "pinned",
        "revision": {
          "__rl": true,
          "mode": "number",
          "value": "={{ String($('Workflow settings').first().json.revision) }}"
        },
        "data": "={{ $json.data }}",
        "options": {
          "fileName": "={{ $json.filename }}",
          "operationId": "={{ $json.operationId }}",
          "outputField": "pdf"
        }
      },
      "id": "829d989f-0e07-477b-abce-bdfd86c4a8d0",
      "name": "Generate PDF",
      "type": "@bitavu/n8n-nodes-bitavu.bitavu",
      "typeVersion": 1,
      "position": [
        2220,
        360
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "bc1560e2-17c6-49d5-9f2a-3f10f1ac3709",
              "leftValue": "={{ $json.sample }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "d00d677e-ab79-4675-af3c-d8324dfb7fee",
      "name": "Sample PDF only?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2440,
        360
      ]
    },
    {
      "parameters": {
        "jsCode": "const input = $input.first();\nreturn [{ json: { ...input.json, result: 'Sample PDF only' }, binary: input.binary }];"
      },
      "id": "7dbebc16-dadf-43dd-bcd2-ef4982388745",
      "name": "Show sample result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2660,
        290
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.spreadsheetId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "invoice_number": "={{ $('Build invoice payload').first().json.data.invoice.number }}",
            "workflow_state": "archive_pending",
            "invoice_fingerprint": "={{ $('Build invoice payload').first().json.fingerprint }}"
          },
          "matchingColumns": [
            "invoice_number"
          ],
          "schema": [
            {
              "id": "invoice_number",
              "displayName": "invoice_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "workflow_state",
              "displayName": "workflow_state",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            },
            {
              "id": "invoice_fingerprint",
              "displayName": "invoice_fingerprint",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "bee4524b-40ad-444e-b9e0-fb1b74747eb3",
      "name": "Mark archive pending",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        2660,
        510
      ]
    },
    {
      "parameters": {
        "jsCode": "const rendered = $('Generate PDF').first();\nif (!rendered.binary?.pdf) throw new Error('Generate PDF did not return the pdf binary field.');\nreturn [{ json: rendered.json, binary: rendered.binary }];"
      },
      "id": "6e111d22-22f2-4e3c-9148-13f6a71890de",
      "name": "Pass rendered PDF to Drive",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2880,
        510
      ]
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "inputDataFieldName": "pdf",
        "name": "={{ $json.filename }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.driveFolderId }}"
        },
        "options": {}
      },
      "id": "cade3ea1-3679-4026-b3da-27a01415c16a",
      "name": "Upload archived PDF",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        3100,
        510
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.spreadsheetId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "invoice_number": "={{ $('Build invoice payload').first().json.data.invoice.number }}",
            "workflow_state": "archived",
            "drive_file_id": "={{ $json.id || (() => { throw new Error(\"Drive did not return a file ID\"); })() }}"
          },
          "matchingColumns": [
            "invoice_number"
          ],
          "schema": [
            {
              "id": "invoice_number",
              "displayName": "invoice_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "workflow_state",
              "displayName": "workflow_state",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            },
            {
              "id": "drive_file_id",
              "displayName": "drive_file_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "a38af5e4-45a2-46e9-bd33-4964ce4c2009",
      "name": "Save archive file ID",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3320,
        510
      ]
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "download",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Upload archived PDF').isExecuted ? $('Upload archived PDF').first().json.id : $('Build invoice payload').first().json.driveFileId }}"
        },
        "options": {
          "binaryPropertyName": "pdf",
          "fileName": "={{ $('Build invoice payload').first().json.filename }}"
        }
      },
      "id": "e1596094-5ae9-4d12-9770-03f4ff1ee9e8",
      "name": "Download archived PDF",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        3540,
        170
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.spreadsheetId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "invoice_number": "={{ $('Build invoice payload').first().json.data.invoice.number }}",
            "workflow_state": "draft_pending"
          },
          "matchingColumns": [
            "invoice_number"
          ],
          "schema": [
            {
              "id": "invoice_number",
              "displayName": "invoice_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "workflow_state",
              "displayName": "workflow_state",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "354253c0-fdf1-4eb1-9af7-159f8422a867",
      "name": "Mark draft pending",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3760,
        170
      ]
    },
    {
      "parameters": {
        "jsCode": "const { binary } = $('Download archived PDF').first();\nif (!binary?.pdf) throw new Error('The archive did not return a PDF attachment.');\nreturn [{ json: $('Build invoice payload').first().json, binary }];"
      },
      "id": "74dff383-887a-463f-9c21-2915172a81dd",
      "name": "Pass archived PDF to Gmail",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3980,
        170
      ]
    },
    {
      "parameters": {
        "resource": "draft",
        "operation": "create",
        "subject": "={{ 'Invoice ' + $json.data.invoice.number }}",
        "emailType": "text",
        "message": "={{ 'Hello ' + $json.data.client.name + ',\\n\\nPlease find your invoice attached.\\n\\nThank you.' }}",
        "options": {
          "sendTo": "={{ $json.email }}",
          "attachmentsUi": {
            "attachmentsBinary": [
              {
                "property": "pdf"
              }
            ]
          }
        }
      },
      "id": "e66e0c0f-2ddb-437e-b311-b0d14a396c25",
      "name": "Create Gmail draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        4200,
        170
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow settings').first().json.spreadsheetId }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "invoice_number": "={{ $('Build invoice payload').first().json.data.invoice.number }}",
            "workflow_state": "complete",
            "gmail_draft_id": "={{ $json.id || (() => { throw new Error(\"Gmail did not return a draft ID\"); })() }}"
          },
          "matchingColumns": [
            "invoice_number"
          ],
          "schema": [
            {
              "id": "invoice_number",
              "displayName": "invoice_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "workflow_state",
              "displayName": "workflow_state",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            },
            {
              "id": "gmail_draft_id",
              "displayName": "gmail_draft_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "a9e88716-73d9-4379-bb81-441f26535364",
      "name": "Save draft ID and complete",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        4420,
        170
      ]
    }
  ],
  "connections": {
    "Manual trigger": {
      "main": [
        [
          {
            "node": "Workflow settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow settings": {
      "main": [
        [
          {
            "node": "Use sample data?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Use sample data?": {
      "main": [
        [
          {
            "node": "Load sample rows",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read invoice row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Load sample rows": {
      "main": [
        [
          {
            "node": "Build invoice payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build invoice payload": {
      "main": [
        [
          {
            "node": "Already archived?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Already archived?": {
      "main": [
        [
          {
            "node": "Download archived PDF",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Generate PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download archived PDF": {
      "main": [
        [
          {
            "node": "Mark draft pending",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark draft pending": {
      "main": [
        [
          {
            "node": "Pass archived PDF to Gmail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pass archived PDF to Gmail": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Gmail draft": {
      "main": [
        [
          {
            "node": "Save draft ID and complete",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read invoice row": {
      "main": [
        [
          {
            "node": "Check approval and status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check approval and status": {
      "main": [
        [
          {
            "node": "Already complete?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Already complete?": {
      "main": [
        [
          {
            "node": "Show existing file and draft",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read invoice line items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read invoice line items": {
      "main": [
        [
          {
            "node": "Collect Sheets rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect Sheets rows": {
      "main": [
        [
          {
            "node": "Build invoice payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate PDF": {
      "main": [
        [
          {
            "node": "Sample PDF only?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample PDF only?": {
      "main": [
        [
          {
            "node": "Show sample result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Mark archive pending",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark archive pending": {
      "main": [
        [
          {
            "node": "Pass rendered PDF to Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pass rendered PDF to Drive": {
      "main": [
        [
          {
            "node": "Upload archived PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload archived PDF": {
      "main": [
        [
          {
            "node": "Save archive file ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save archive file ID": {
      "main": [
        [
          {
            "node": "Download archived PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
