{
  "name": "Fill PDF forms in bulk from Google Sheets rows, then email and archive each copy",
  "id": "pdfops-sheets-bulk-fill",
  "nodes": [
    {
      "parameters": {
        "content": "## Fill PDF forms in bulk from Google Sheets rows, then email and archive each copy\n\nEach pending sheet row becomes one filled, flattened PDF that is saved to Google Drive and emailed to the recipient. The sheet records the outcome of every row.\n\nOne bad column header would fail every row, so it is checked once, with one Inspect call, before any fill. The run does nothing and spends nothing when no rows are pending.\n\n### How it works\n- **Schedule Hourly** starts the run. **Set Batch Config** holds every setting, including the sheet.\n- **Select Pending Rows** keeps rows with a blank status, up to maxRowsPerRun. With none, the run ends.\n- **Download Blank Form** and **Inspect PDF Fields** read the template once. **Preflight Batch** stops the batch on an unknown header or an unsupported field, and flags bad rows.\n- **Loop Over Rows** takes one row at a time: fill, save to Drive, write status \"sending\", then email.\n- **Mark Row Done**, **Mark Row Failed** and **Mark Email Failed** write the outcome. **Post Run Summary** posts counts read back from the sheet.\n\nIf a fill or Drive save hits a rate limit or outage, the status stays blank so the next run retries. Status \"sending\" means the outcome is unknown, so clear it to resend. Clear an error status to retry.\n\n### Setup\n1. Install `n8n-nodes-pdfops` from Settings > Community nodes. Add its credential to BOTH PDFops nodes: **Inspect PDF Fields** and **Fill Form for Row**.\n2. Connect Google Sheets, Google Drive, Gmail and Slack.\n3. Edit **Set Batch Config**: template URL, sheet URL, sheet name, email column, Slack channel.\n4. Sheet columns: the PDF field names plus status, pdf_link and the email column. Don't sort during a run.\n5. Set an error workflow, so a failed run alerts you too.",
        "width": 560,
        "height": 1500
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -840,
        -60
      ],
      "id": "note-overview",
      "name": "Overview"
    },
    {
      "parameters": {
        "content": "## 1. Select and inspect\nRead the sheet, keep rows with a blank status, and inspect the blank form once.",
        "width": 1360,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -200,
        -60
      ],
      "id": "note-section-1",
      "name": "Section 1"
    },
    {
      "parameters": {
        "content": "## 2. Preflight\nCheck headers and every row. A bad header stops the batch and alerts Slack.",
        "width": 700,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1180,
        -60
      ],
      "id": "note-section-2",
      "name": "Section 2"
    },
    {
      "parameters": {
        "content": "## 3. One row at a time\nFill, save, mark \"sending\", email, then write the outcome. Failures are recorded and the loop continues.",
        "width": 2100,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1900,
        -60
      ],
      "id": "note-section-3",
      "name": "Section 3"
    },
    {
      "parameters": {
        "content": "## 4. Summary\nRead the sheet again and post what it really says.",
        "width": 1000,
        "height": 360,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1900,
        700
      ],
      "id": "note-section-4",
      "name": "Section 4"
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "id": "trigger-schedule",
      "name": "Schedule Hourly",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -120,
        180
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "cfg-0",
              "name": "templateUrl",
              "value": "https://pdfops.dev/invoice-template.pdf",
              "type": "string"
            },
            {
              "id": "cfg-1",
              "name": "flatten",
              "value": true,
              "type": "boolean"
            },
            {
              "id": "cfg-2",
              "name": "fileNameColumn",
              "value": "customer_name",
              "type": "string"
            },
            {
              "id": "cfg-3",
              "name": "emailColumn",
              "value": "email",
              "type": "string"
            },
            {
              "id": "cfg-4",
              "name": "maxRowsPerRun",
              "value": 50,
              "type": "number"
            },
            {
              "id": "cfg-5",
              "name": "slackChannel",
              "value": "#pdf-ops",
              "type": "string"
            },
            {
              "id": "cfg-6",
              "name": "spreadsheetUrl",
              "value": "https://docs.google.com/spreadsheets/d/REPLACE_WITH_YOUR_SHEET_ID/edit",
              "type": "string"
            },
            {
              "id": "cfg-7",
              "name": "sheetName",
              "value": "Sheet1",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      },
      "id": "set-batch-config",
      "name": "Set Batch Config",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        100,
        180
      ]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('Set Batch Config').first().json.spreadsheetUrl }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.sheetName }}"
        },
        "options": {
          "outputFormatting": {
            "values": {
              "general": "FORMATTED_VALUE",
              "date": "FORMATTED_STRING"
            }
          }
        }
      },
      "id": "sheets-read",
      "name": "Read Sheet Rows",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        320,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Select Pending Rows: keep rows with a blank status, capped at maxRowsPerRun.\nconst config = $('Set Batch Config').first().json;\nconst maxRows = Number(config.maxRowsPerRun) || 50;\nconst all = $input.all().map((i) => i.json);\n\nconst columns = [];\nfor (const r of all) {\n  for (const k of Object.keys(r)) {\n    if (!columns.includes(k)) columns.push(k);\n  }\n}\n\nconst rows = all\n  .filter((r) => String(r.status === undefined || r.status === null ? '' : r.status).trim() === '')\n  .slice(0, maxRows);\n\n// No pending rows: end the run here, with no metered call and no Slack message.\nif (rows.length === 0) return [];\nreturn [{ json: { rows, columns } }];"
      },
      "id": "code-select",
      "name": "Select Pending Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        540,
        180
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "url": "={{ $('Set Batch Config').first().json.templateUrl }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file",
              "outputPropertyName": "data"
            }
          }
        }
      },
      "id": "http-download",
      "name": "Download Blank Form",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "operation": "inspect",
        "binaryPropertyName": "data"
      },
      "id": "pdfops-inspect",
      "name": "Inspect PDF Fields",
      "type": "n8n-nodes-pdfops.pdfops",
      "typeVersion": 1,
      "position": [
        980,
        180
      ],
      "credentials": {
        "pdfopsApi": {
          "id": "",
          "name": "PDFops account"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Preflight Batch: checks the whole batch once, then each row, before any fill call.\nconst config = $('Set Batch Config').first().json;\nconst selected = $('Select Pending Rows').first().json;\nconst inspect = $input.first().json || {};\nconst blankBinary = $('Download Blank Form').first().binary;\n\nconst emailCol = config.emailColumn || 'email';\nconst nameCol = config.fileNameColumn || 'customer_name';\nconst reserved = new Set(['row_number', 'status', 'pdf_link', emailCol, nameCol]);\n\nconst fieldList = Array.isArray(inspect.fields) ? inspect.fields : [];\nconst fieldMap = new Map();\nfor (const f of fieldList) fieldMap.set(f.name, f);\nconst validNames = fieldList.map((f) => f.name);\n\nconst stop = (reason) => [{ json: { stopReason: reason } }];\n\n// Hybrid XFA forms fill fine, so hasXFA is deliberately not a stop condition.\nif (fieldList.length === 0) {\n  return stop('The PDF template has zero fillable form fields, so there is nothing to fill.');\n}\n\nconst columns = Array.isArray(selected.columns) ? selected.columns : [];\n\n// Without these the status writes match nothing, and a row is never marked.\nconst missing = ['status', 'pdf_link', emailCol].filter((c) => !columns.includes(c));\nif (missing.length > 0) {\n  return stop('The sheet is missing required columns: ' + missing.join(', ') + '. Add them to the header row.');\n}\n\n// A truncated field list is incomplete, so an unknown header cannot be proven bad.\nif (inspect.truncated !== true) {\n  const badHeaders = columns.filter((h) => !reserved.has(h) && !fieldMap.has(h));\n  if (badHeaders.length > 0) {\n    return stop(\n      'These sheet columns match no PDF form field: ' + badHeaders.join(', ') +\n      '. Valid field names are: ' + validNames.join(', ') + '.'\n    );\n  }\n}\n\nconst unsupported = columns.filter((h) => fieldMap.has(h) && fieldMap.get(h).type === 'unsupported');\nif (unsupported.length > 0) {\n  return stop(\n    'These sheet columns match PDF fields of an unsupported type (signature or button): ' +\n    unsupported.join(', ') + '. Remove those columns.'\n  );\n}\n\nconst isBlank = (v) => v === undefined || v === null || String(v).trim() === '';\nconst emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst out = [];\n\nfor (const row of selected.rows || []) {\n  const errors = [];\n  const fields = {};\n\n  for (const key of Object.keys(row)) {\n    if (!fieldMap.has(key)) {\n      // Past Inspect's field cap a column may still be a real field: send it and let the API rule.\n      if (inspect.truncated === true && !reserved.has(key) && !isBlank(row[key])) fields[key] = String(row[key]);\n      continue;\n    }\n    const raw = row[key];\n    if (isBlank(raw)) continue;\n    const def = fieldMap.get(key);\n\n    if (def.type === 'checkbox') {\n      const s = String(raw).trim().toLowerCase();\n      if (['true', 'yes', '1'].includes(s)) fields[key] = 'true';\n      else if (['false', 'no', '0'].includes(s)) fields[key] = 'false';\n      else errors.push('Field \"' + key + '\": invalid checkbox value \"' + raw + '\" (use true/false, yes/no or 1/0)');\n    } else if (def.type === 'dropdown' || def.type === 'radio' || def.type === 'optionlist') {\n      const s = String(raw);\n      fields[key] = s;\n      // Inspect caps options at 500, so a longer list cannot rule a value out.\n      if (Array.isArray(def.options) && def.options.length > 0 && def.options.length < 500 && !def.options.includes(s)) {\n        errors.push('Field \"' + key + '\": value \"' + s + '\" is not in the allowed options [' + def.options.join(', ') + ']');\n      }\n    } else {\n      const s = String(raw);\n      fields[key] = s;\n      if (typeof def.maxLength === 'number' && s.length > def.maxLength) {\n        errors.push('Field \"' + key + '\": length ' + s.length + ' exceeds maxLength ' + def.maxLength);\n      }\n    }\n  }\n\n  if (Object.keys(fields).length === 0) {\n    errors.push('Row has no non-blank values for any PDF field');\n  }\n\n  const recipient = isBlank(row[emailCol]) ? '' : String(row[emailCol]).trim();\n  if (!recipient || !emailRegex.test(recipient)) {\n    errors.push('Missing or invalid email address \"' + recipient + '\" in column \"' + emailCol + '\"');\n  }\n\n  const rawName = isBlank(row[nameCol]) ? 'row-' + row.row_number : String(row[nameCol]);\n  const safe = rawName.replace(/[^A-Za-z0-9._-]+/g, '-');\n  const fileName = safe.toLowerCase().endsWith('.pdf') ? safe : safe + '.pdf';\n\n  out.push({\n    json: {\n      row_number: row.row_number,\n      fields,\n      recipient,\n      fileName,\n      rowError: errors.length > 0 ? errors.join('; ') : null,\n    },\n    binary: blankBinary,\n  });\n}\n\nreturn out;"
      },
      "id": "code-preflight",
      "name": "Preflight Batch",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1220,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "if-batch-stopped-cond",
              "leftValue": "={{ !!$json.stopReason }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-batch-stopped",
      "name": "Batch Stopped?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1440,
        180
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.slackChannel }}"
        },
        "text": "={{ ':warning: Batch PDF fill aborted: ' + ($json.stopReason || (typeof $json.error === 'string' ? $json.error : ($json.error && $json.error.message)) || $json.message || 'unknown failure') + (typeof $json.error === 'string' && $json.message ? ': ' + $json.message : '') }}",
        "otherOptions": {}
      },
      "id": "slack-alert-aborted",
      "name": "Alert Batch Aborted",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1660,
        420
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {}
      },
      "id": "loop-rows",
      "name": "Loop Over Rows",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1940,
        180
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Current Row: Loop Over Rows runs with batch size 1, so .first() downstream is the current row.\nreturn $input.all();"
      },
      "id": "code-current",
      "name": "Current Row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2160,
        180
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "if-row-error-cond",
              "leftValue": "={{ !!$json.rowError }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-row-error",
      "name": "Row Has Error?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2380,
        180
      ]
    },
    {
      "parameters": {
        "operation": "fill",
        "binaryPropertyName": "data",
        "fields": "={{ $json.fields }}",
        "flatten": "={{ $('Set Batch Config').first().json.flatten }}",
        "outputBinaryPropertyName": "data",
        "fileName": "={{ $json.fileName }}"
      },
      "id": "pdfops-fill",
      "name": "Fill Form for Row",
      "type": "n8n-nodes-pdfops.pdfops",
      "typeVersion": 1,
      "position": [
        2600,
        180
      ],
      "credentials": {
        "pdfopsApi": {
          "id": "",
          "name": "PDFops account"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "inputDataFieldName": "data",
        "name": "={{ $binary.data.fileName }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive",
          "cachedResultName": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "list",
          "value": "root",
          "cachedResultName": "/ (Root folder)"
        },
        "options": {}
      },
      "id": "drive-upload",
      "name": "Save Filled PDF to Drive",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2820,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('Set Batch Config').first().json.spreadsheetUrl }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.sheetName }}"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $('Current Row').first().json.row_number }}",
            "status": "sending",
            "pdf_link": "={{ $json.webViewLink || ('https://drive.google.com/file/d/' + $json.id + '/view') }}"
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": [
            {
              "id": "row_number",
              "displayName": "row_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "readOnly": true,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "pdf_link",
              "displayName": "pdf_link",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "sheets-sending",
      "name": "Mark Row Sending",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3040,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Restore PDF: the Sheets and Drive nodes drop binary data, so rebuild the item for Gmail.\nconst row = $('Current Row').first().json;\nconst binary = $('Fill Form for Row').first().binary;\nreturn [{ json: row, binary }];"
      },
      "id": "code-restore",
      "name": "Restore PDF",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3260,
        180
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $('Current Row').first().json.recipient }}",
        "subject": "Your completed form",
        "emailType": "text",
        "message": "Attached is your completed PDF form.",
        "options": {
          "attachmentsUi": {
            "attachmentsBinary": [
              {
                "property": "data"
              }
            ]
          }
        }
      },
      "id": "gmail-send",
      "name": "Email Filled PDF",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        3480,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('Set Batch Config').first().json.spreadsheetUrl }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.sheetName }}"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $('Current Row').first().json.row_number }}",
            "status": "done"
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": [
            {
              "id": "row_number",
              "displayName": "row_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "readOnly": true,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "pdf_link",
              "displayName": "pdf_link",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "sheets-done",
      "name": "Mark Row Done",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3700,
        180
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('Set Batch Config').first().json.spreadsheetUrl }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.sheetName }}"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $('Current Row').first().json.row_number }}",
            "status": "={{ !$json.rowError && /^rate_limited|rate limit|too many requests|^(gateway timed out|bad gateway|service unavailable|the service was not able)|ECONN|ETIMEDOUT/i.test(String((typeof $json.error === 'string' ? $json.error : ($json.error && $json.error.message) || $json.message || ''))) ? '' : 'error: ' + String($json.rowError || ((typeof $json.error === 'string' ? $json.error : ($json.error && $json.error.message) || $json.message || 'unknown error') + (typeof $json.error === 'string' && $json.message ? ': ' + $json.message : ''))).slice(0, 300) }}"
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": [
            {
              "id": "row_number",
              "displayName": "row_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "readOnly": true,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "pdf_link",
              "displayName": "pdf_link",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "sheets-failed",
      "name": "Mark Row Failed",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        2600,
        420
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('Set Batch Config').first().json.spreadsheetUrl }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.sheetName }}"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $('Current Row').first().json.row_number }}",
            "status": "={{ 'error: email failed: ' + String(((typeof $json.error === 'string' ? $json.error : ($json.error && $json.error.message) || $json.message || 'unknown error') + (typeof $json.error === 'string' && $json.message ? ': ' + $json.message : ''))).slice(0, 300) }}"
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": [
            {
              "id": "row_number",
              "displayName": "row_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "readOnly": true,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "pdf_link",
              "displayName": "pdf_link",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "sheets-email-failed",
      "name": "Mark Email Failed",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        3480,
        420
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('Set Batch Config').first().json.spreadsheetUrl }}"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.sheetName }}"
        },
        "options": {
          "outputFormatting": {
            "values": {
              "general": "FORMATTED_VALUE",
              "date": "FORMATTED_STRING"
            }
          }
        }
      },
      "id": "sheets-final",
      "name": "Read Final Status",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1940,
        820
      ],
      "onError": "stopWorkflow",
      "executeOnce": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Count Results: reports what the sheet says now, for the rows this run selected.\nconst sheet = new Map();\nfor (const item of $input.all()) sheet.set(String(item.json.row_number), item.json);\n\nconst planned = $('Preflight Batch').all();\nlet done = 0;\nlet failed = 0;\nlet sending = 0;\nlet unprocessed = 0;\nconst errors = [];\n\nfor (const p of planned) {\n  const row = sheet.get(String(p.json.row_number));\n  const status = row ? String(row.status === undefined || row.status === null ? '' : row.status).trim() : '';\n  if (status === 'done') done++;\n  else if (status.startsWith('error')) {\n    failed++;\n    if (errors.length < 3) errors.push('row ' + p.json.row_number + ': ' + status.slice(0, 160));\n  } else if (status === 'sending') sending++;\n  else unprocessed++;\n}\n\n// Rows left on \"sending\" by any earlier run need a person, so keep saying so.\nconst stuck = [...sheet.values()].filter((r) => String(r.status === undefined || r.status === null ? '' : r.status).trim() === 'sending').length;\n\nlet summary = 'PDF fill run finished: ' + done + ' done, ' + failed + ' failed, ' + sending + ' sending (outcome unknown), ' + unprocessed + ' not processed, of ' + planned.length + ' rows.';\nif (errors.length > 0) summary += ' First errors: ' + errors.join(' | ');\nif (stuck > 0) summary += ' ' + stuck + ' row(s) in the sheet are on status \"sending\": check they were emailed, then set done or clear them.';\n\nreturn [{ json: { done, failed, sending, unprocessed, total: planned.length, summary } }];"
      },
      "id": "code-count",
      "name": "Count Results",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2160,
        820
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "mode": "name",
          "value": "={{ $('Set Batch Config').first().json.slackChannel }}"
        },
        "text": "={{ $json.summary }}",
        "otherOptions": {}
      },
      "id": "slack-summary",
      "name": "Post Run Summary",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        2380,
        820
      ],
      "onError": "stopWorkflow"
    }
  ],
  "connections": {
    "Schedule Hourly": {
      "main": [
        [
          {
            "node": "Set Batch Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Batch Config": {
      "main": [
        [
          {
            "node": "Read Sheet Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Sheet Rows": {
      "main": [
        [
          {
            "node": "Select Pending Rows",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Batch Aborted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Select Pending Rows": {
      "main": [
        [
          {
            "node": "Download Blank Form",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download Blank Form": {
      "main": [
        [
          {
            "node": "Inspect PDF Fields",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Batch Aborted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inspect PDF Fields": {
      "main": [
        [
          {
            "node": "Preflight Batch",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Batch Aborted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preflight Batch": {
      "main": [
        [
          {
            "node": "Batch Stopped?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Batch Aborted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Batch Stopped?": {
      "main": [
        [
          {
            "node": "Alert Batch Aborted",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Loop Over Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Rows": {
      "main": [
        [
          {
            "node": "Read Final Status",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Current Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Current Row": {
      "main": [
        [
          {
            "node": "Row Has Error?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Row Has Error?": {
      "main": [
        [
          {
            "node": "Mark Row Failed",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fill Form for Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fill Form for Row": {
      "main": [
        [
          {
            "node": "Save Filled PDF to Drive",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Mark Row Failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Filled PDF to Drive": {
      "main": [
        [
          {
            "node": "Mark Row Sending",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Mark Row Failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark Row Sending": {
      "main": [
        [
          {
            "node": "Restore PDF",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Mark Row Failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Restore PDF": {
      "main": [
        [
          {
            "node": "Email Filled PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Filled PDF": {
      "main": [
        [
          {
            "node": "Mark Row Done",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Mark Email Failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark Row Done": {
      "main": [
        [
          {
            "node": "Loop Over Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark Email Failed": {
      "main": [
        [
          {
            "node": "Loop Over Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark Row Failed": {
      "main": [
        [
          {
            "node": "Loop Over Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Final Status": {
      "main": [
        [
          {
            "node": "Count Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Count Results": {
      "main": [
        [
          {
            "node": "Post Run Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}
