{
  "name": "Generate invoice or packing slip PDFs from JSON orders with HTML to PDF",
  "id": "pdfops-html-to-pdf-webhook",
  "active": false,
  "nodes": [
    {
      "parameters": {
        "content": "## Generate invoice or packing slip PDFs from JSON orders with HTML to PDF\n\nPOST an order as JSON and get a PDF: an invoice or a packing slip, returned straight in the response or saved to Google Drive and emailed with the link in the reply. For teams that need a branded PDF from data without running a browser or PDF library.\n\n### How it works\n- **Order Webhook** needs a Header Auth secret. **Validate Order Payload** bounds every field and answers 400 with the exact issues.\n- **Choose Layout** picks the invoice or packing-slip HTML. Money is rounded half up in the currency's minor units.\n- **Render HTML to PDF** (PDFops) is retried once, only when the renderer reports it is busy.\n- delivery download returns the PDF. delivery link stores it in Drive and emails it.\n- If Drive saved the file but Gmail failed, the reply says so and includes the link. Other failures alert Slack and answer 502 without upstream details.\n\n### Setup\n1. Install the PDFops community node (n8n-nodes-pdfops 0.5.0 or newer) and add a PDFops API credential.\n2. Add Header Auth and Slack credentials (the alert runs on every failure path). Delivery link also needs Google Drive and Gmail.\n3. Edit **Set Document Options**.\n4. POST orderId, customer (name, email), currency, taxRate, layout, delivery and items (description, quantity, unitPrice).\n\n### Good to know\nHTML rendering counts for more of your PDFops quota than other operations (see pdfops.dev/docs/html-to-pdf). A caller retry is not idempotent: the same orderId can store a second file.",
        "width": 700,
        "height": 880
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -800,
        -80
      ],
      "id": "note-01",
      "name": "Overview"
    },
    {
      "parameters": {
        "content": "## 1. Receive and validate\nThe webhook needs a Header Auth secret. A bad payload gets a 400 listing the issues, before any PDF is rendered or quota used.",
        "width": 780,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -80
      ],
      "id": "note-02",
      "name": "Section 1"
    },
    {
      "parameters": {
        "content": "## 2. Choose a layout\nEdit company name, colour, page size and alert channel in one place. The switch builds an invoice or a packing slip; amounts are rounded half up to the currency.",
        "width": 780,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        760,
        -80
      ],
      "id": "note-03",
      "name": "Section 2"
    },
    {
      "parameters": {
        "content": "## 3. Render and deliver\nPDFops renders the HTML. If the renderer reports it is busy, one retry follows a short pause. Delivery download answers with the PDF; delivery link stores it in Drive and emails it.",
        "width": 2000,
        "height": 700,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1560,
        -80
      ],
      "id": "note-04",
      "name": "Section 3"
    },
    {
      "parameters": {
        "content": "## Error paths\nInvalid payloads end in a 400. A failed render, upload or email alerts Slack. If the file was already stored, the reply still carries its link.",
        "width": 3600,
        "height": 520,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        700
      ],
      "id": "note-05",
      "name": "Error paths"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "html-to-pdf-order",
        "responseMode": "responseNode",
        "options": {},
        "authentication": "headerAuth"
      },
      "id": "node-06",
      "name": "Order Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        200
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "",
          "name": "Header Auth account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const input = $input.first().json;\nconst body = input.body && typeof input.body === 'object' && !Array.isArray(input.body) ? input.body : {};\nconst errors = [];\n// control and format characters (zero-width, bidi overrides such as the right-to-left override) and line separators\nconst BAD = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/u;\n// names, descriptions and notes may carry U+200C and U+200D (Persian and Indic scripts, emoji sequences); ids and emails may not\nconst BAD_TEXT = /(?![\\u200c\\u200d])[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/u;\nconst text = (v, max, bad = BAD_TEXT) => typeof v === 'string' && v.trim().length > 0 && v.length <= max && !bad.test(v);\nconst optText = (v, max) => v === undefined || v === null || v === '' || (typeof v === 'string' && v.length <= max && !BAD_TEXT.test(v.replace(/[\\r\\n\\t]/g, ' ')));\nconst num = (v) => typeof v === 'number' && Number.isFinite(v);\nconst realDate = (d) => {\n  if (typeof d !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}$/.test(d)) return false;\n  try { return new Date(d + 'T00:00:00Z').toISOString().slice(0, 10) === d; } catch (e) { return false; }\n};\nconst decStr = (x) => { let s = String(x); if (/e/i.test(s)) s = x.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 20 }); return s; };\nconst decimals = (x) => (decStr(x).split('.')[1] || '').length;\nlet ISO = null;\ntry { ISO = new Set(Intl.supportedValuesOf('currency')); } catch (e) { ISO = null; }\nconst FALLBACK = 'USD EUR GBP JPY CHF CAD AUD NZD SEK NOK DKK PLN CZK HUF RON BGN CNY HKD SGD INR BRL MXN ZAR TRY KRW AED SAR ILS THB IDR MYR PHP KWD BHD OMR'.split(' ');\nconst LAYOUTS = ['invoice', 'packing-slip'];\nconst DELIVERIES = ['link', 'download'];\nif (!text(body.orderId, 60, BAD)) errors.push('orderId must be a non-empty string of at most 60 characters without control or format characters');\nconst customer = body.customer && typeof body.customer === 'object' ? body.customer : {};\nif (!text(customer.name, 200)) errors.push('customer.name is required (at most 200 characters, no control or format characters)');\nconst email = typeof customer.email === 'string' ? customer.email.trim() : '';\nif (!text(email, 254, BAD) || !/^[^\\s@,;<>()]+@[^\\s@,;<>()]+\\.[^\\s@,;<>()]+$/.test(email) || /\\.\\./.test(email) || /^\\.|\\.@|@\\./.test(email)) errors.push('customer.email must be one valid email address');\nif (!optText(customer.address, 500)) errors.push('customer.address must be at most 500 characters without control characters');\nif (!optText(body.notes, 500)) errors.push('notes must be at most 500 characters without control characters');\nconst currency = body.currency === undefined ? 'USD' : body.currency;\nlet digits = 2;\nif (typeof currency !== 'string' || !/^[A-Za-z]{3}$/.test(currency) || !(ISO ? ISO.has(currency.toUpperCase()) : FALLBACK.includes(currency.toUpperCase()))) {\n  errors.push('currency must be a real ISO 4217 code such as USD or EUR');\n} else {\n  try { digits = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency.toUpperCase() }).resolvedOptions().maximumFractionDigits; } catch (e) { digits = 2; }\n}\nconst taxRate = body.taxRate === undefined ? 0 : body.taxRate;\nif (!num(taxRate) || taxRate < 0 || taxRate > 100) errors.push('taxRate must be a number from 0 to 100');\nconst layout = body.layout === undefined ? 'invoice' : body.layout;\nif (!LAYOUTS.includes(layout)) errors.push('layout must be one of: ' + LAYOUTS.join(', '));\nconst delivery = body.delivery === undefined ? 'link' : body.delivery;\nif (!DELIVERIES.includes(delivery)) errors.push('delivery must be one of: ' + DELIVERIES.join(', '));\nif (body.issueDate !== undefined && !realDate(body.issueDate)) errors.push('issueDate must be a real date in the form YYYY-MM-DD');\nconst items = Array.isArray(body.items) ? body.items : [];\nif (items.length < 1 || items.length > 200) errors.push('items must be an array of 1 to 200 line items');\nlet subtotalEstimate = 0;\nitems.slice(0, 200).forEach((it, i) => {\n  const ok = it && typeof it === 'object';\n  if (!ok || !text(it.description, 500)) errors.push('items[' + i + '].description is required (at most 500 characters, no control characters)');\n  if (!ok || !num(it.quantity) || it.quantity <= 0 || it.quantity > 1000000) errors.push('items[' + i + '].quantity must be a number above 0 and at most 1000000');\n  else if (decimals(it.quantity) > 6) errors.push('items[' + i + '].quantity may have at most 6 decimal places');\n  const priceOptional = layout === 'packing-slip' && ok && it.unitPrice === undefined;\n  if (!priceOptional && (!ok || !num(it.unitPrice) || it.unitPrice < 0 || it.unitPrice > 1000000000)) errors.push('items[' + i + '].unitPrice must be a number from 0 to 1000000000');\n  else if (ok && num(it.unitPrice) && decimals(it.unitPrice) > digits) errors.push('items[' + i + '].unitPrice has more than ' + digits + ' decimal places, which ' + String(currency).toUpperCase() + ' does not have');\n  if (ok && num(it.quantity) && num(it.unitPrice)) subtotalEstimate += it.quantity * it.unitPrice;\n});\nif (subtotalEstimate * (1 + (num(taxRate) ? taxRate : 0) / 100) > 1e12) errors.push('the order total after tax is too large (limit 1000000000000)');\nif (errors.length) return [{ json: { valid: false, errors: errors.slice(0, 10), errorCount: errors.length, showing: errors.length > 10 ? 'first 10 of ' + errors.length : 'all ' + errors.length } }];\nconst issueDate = body.issueDate === undefined ? new Date().toISOString().slice(0, 10) : body.issueDate;\nconst safeId = body.orderId.trim().replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 40);\nreturn [{ json: { valid: true, errors: [], order: {\n  orderId: body.orderId.trim(),\n  issueDate,\n  currency: currency.toUpperCase(),\n  taxRate,\n  layout,\n  delivery,\n  fileName: (layout === 'packing-slip' ? 'packing-slip-' : 'order-') + safeId + '.pdf',\n  customer: { name: customer.name.trim(), email, address: typeof customer.address === 'string' ? customer.address.trim() : '' },\n  notes: typeof body.notes === 'string' ? body.notes : '',\n  items: items.map((it) => ({ description: it.description.trim(), quantity: it.quantity, unitPrice: num(it.unitPrice) ? it.unitPrice : 0 })),\n} } }];"
      },
      "id": "node-07",
      "name": "Validate Order Payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        200
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-08",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-09",
      "name": "Payload Valid?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        480,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'invalid_payload', showing: $json.showing || null, errorCount: $json.errorCount || null, errors: $json.errors || ['The request could not be read as an order.'], expected: { orderId: 'string', customer: { name: 'string', email: 'string' }, currency: 'USD', taxRate: 0, layout: 'invoice | packing-slip', delivery: 'link | download', items: [{ description: 'string', quantity: 1, unitPrice: 10 }] } }) }}",
        "options": {
          "responseCode": 400
        }
      },
      "id": "node-10",
      "name": "Respond With Validation Errors",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        480,
        880
      ]
    },
    {
      "parameters": {
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "as-11",
              "name": "companyName",
              "value": "Your Company",
              "type": "string"
            },
            {
              "id": "as-12",
              "name": "accentColor",
              "value": "#1f4e79",
              "type": "string"
            },
            {
              "id": "as-13",
              "name": "pageSize",
              "value": "letter",
              "type": "string"
            },
            {
              "id": "as-14",
              "name": "emailSubject",
              "value": "Your order document",
              "type": "string"
            },
            {
              "id": "as-15",
              "name": "alertChannel",
              "value": "#ops-alerts",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "node-16",
      "name": "Set Document Options",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        800,
        200
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "cond-17",
                    "leftValue": "={{ $json.order.layout }}",
                    "rightValue": "invoice",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Invoice"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "cond-18",
                    "leftValue": "={{ $json.order.layout }}",
                    "rightValue": "packing-slip",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Packing slip"
            }
          ]
        },
        "options": {}
      },
      "id": "node-19",
      "name": "Choose Layout",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1040,
        200
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "jsCode": "const { order } = $input.first().json;\nconst opts = $('Set Document Options').first().json;\nconst esc = (s) => String(s === undefined || s === null ? '' : s)\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\nlet digits = 2;\ntry { digits = new Intl.NumberFormat('en-US', { style: 'currency', currency: order.currency }).resolvedOptions().maximumFractionDigits; } catch (e) { digits = 2; }\nconst factor = Math.pow(10, digits);\n// Money is handled in integer minor units (BigInt) from the decimal text of each number, rounded half up,\n// so 1.005 is 1.01 and 0.1 + 0.2 is 0.3 whatever the binary float says.\nconst decStr = (x) => { let s = String(x); if (/e/i.test(s)) s = x.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 20 }); return s; };\nconst splitDec = (x) => { const parts = decStr(x).split('.'); return [parts[0], parts[1] || '']; };\nconst toMinor = (x) => {\n  const [ip, fp] = splitDec(x);\n  const pad = (fp + '0'.repeat(digits + 1)).slice(0, digits + 1);\n  let n = BigInt(ip + pad.slice(0, digits));\n  if (pad[digits] >= '5') n += 1n;\n  return n;\n};\nconst mulDec = (minor, x) => {\n  const [ip, fp] = splitDec(x);\n  const scale = 10n ** BigInt(fp.length);\n  return (BigInt(ip + fp) * minor * 2n + scale) / (2n * scale);\n};\nconst toNum = (minor) => Number(minor) / factor;\nconst money = (n) => {\n  try { return new Intl.NumberFormat('en-US', { style: 'currency', currency: order.currency }).format(n); }\n  catch (e) { return order.currency + ' ' + n.toFixed(digits); }\n};\nconst sumDec = (xs) => {\n  const parts = xs.map(splitDec);\n  const w = Math.max(0, ...parts.map((p) => p[1].length));\n  const total = parts.reduce((s, p) => s + BigInt(p[0] + p[1].padEnd(w, '0')), 0n);\n  const str = total.toString().padStart(w + 1, '0');\n  const out = w ? str.slice(0, -w) + '.' + str.slice(-w) : str;\n  return out.includes('.') ? out.replace(/\\.?0+$/, '') : out;\n};\nconst accent = /^#[0-9a-fA-F]{6}$/.test(opts.accentColor) ? opts.accentColor : '#1f4e79';\nconst lines = order.items.map((it) => {\n  const unitMinor = toMinor(it.unitPrice);\n  return { description: it.description, quantity: it.quantity, unitMinor, amountMinor: mulDec(unitMinor, it.quantity) };\n});\nconst subtotalMinor = lines.reduce((s, l) => s + l.amountMinor, 0n);\nconst [rateI, rateF] = splitDec(order.taxRate);\nconst rateScale = 10n ** BigInt(rateF.length) * 100n;\nconst taxMinor = (BigInt(rateI + rateF) * subtotalMinor * 2n + rateScale) / (2n * rateScale);\nconst totalMinor = subtotalMinor + taxMinor;\nconst baseCss = 'body{font-family:Arial,Helvetica,sans-serif;color:#222;font-size:12px}' +\n  'h1{color:' + accent + ';font-size:24px;margin:0 0 4px}.meta{color:#555;margin-bottom:24px}' +\n  'table{width:100%;border-collapse:collapse}th{background:' + accent + ';color:#fff;text-align:left;padding:8px}' +\n  'td{padding:8px;border-bottom:1px solid #ddd}tr:nth-child(even) td{background:#f5f7fa}.num{text-align:right}' +\n  '.totals{margin-top:16px;width:45%;margin-left:55%}.totals td{border:0;padding:4px 8px}' +\n  '.grand td{font-weight:bold;font-size:14px;border-top:2px solid ' + accent + '}.notes{margin-top:28px;color:#555}' +\n  '.box{display:inline-block;width:14px;height:14px;border:1px solid #444}';\nconst head = '<!doctype html><html><head><meta charset=\"utf-8\"><style>' + baseCss + '</style></head><body>';\nconst notes = order.notes ? '<div class=\"notes\">' + esc(order.notes) + '</div>' : '';\nconst rows = lines.map((l) => '<tr><td>' + esc(l.description) + '</td><td class=\"num\">' + esc(l.quantity) +\n  '</td><td class=\"num\">' + money(toNum(l.unitMinor)) + '</td><td class=\"num\">' + money(toNum(l.amountMinor)) + '</td></tr>').join('');\nconst html = head +\n  '<h1>' + esc(opts.companyName) + '</h1>' +\n  '<div class=\"meta\">Invoice for order ' + esc(order.orderId) + ' &middot; ' + esc(order.issueDate) + '<br>Prepared for ' + esc(order.customer.name) +\n  (order.customer.address ? '<br>' + esc(order.customer.address) : '') + '</div>' +\n  '<table><thead><tr><th>Description</th><th class=\"num\">Qty</th><th class=\"num\">Unit price</th><th class=\"num\">Amount</th></tr></thead><tbody>' + rows + '</tbody></table>' +\n  '<table class=\"totals\"><tr><td>Subtotal</td><td class=\"num\">' + money(toNum(subtotalMinor)) + '</td></tr>' +\n  '<tr><td>Tax (' + esc(order.taxRate) + '%)</td><td class=\"num\">' + money(toNum(taxMinor)) + '</td></tr>' +\n  '<tr class=\"grand\"><td>Total</td><td class=\"num\">' + money(toNum(totalMinor)) + '</td></tr></table>' + notes + '</body></html>';\nreturn [{ json: { order, html, subtotal: toNum(subtotalMinor), tax: toNum(taxMinor), total: toNum(totalMinor), lineCount: lines.length, layout: 'invoice' } }];"
      },
      "id": "node-20",
      "name": "Build Invoice HTML",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        60
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "const { order } = $input.first().json;\nconst opts = $('Set Document Options').first().json;\nconst esc = (s) => String(s === undefined || s === null ? '' : s)\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\nlet digits = 2;\ntry { digits = new Intl.NumberFormat('en-US', { style: 'currency', currency: order.currency }).resolvedOptions().maximumFractionDigits; } catch (e) { digits = 2; }\nconst factor = Math.pow(10, digits);\n// Money is handled in integer minor units (BigInt) from the decimal text of each number, rounded half up,\n// so 1.005 is 1.01 and 0.1 + 0.2 is 0.3 whatever the binary float says.\nconst decStr = (x) => { let s = String(x); if (/e/i.test(s)) s = x.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 20 }); return s; };\nconst splitDec = (x) => { const parts = decStr(x).split('.'); return [parts[0], parts[1] || '']; };\nconst toMinor = (x) => {\n  const [ip, fp] = splitDec(x);\n  const pad = (fp + '0'.repeat(digits + 1)).slice(0, digits + 1);\n  let n = BigInt(ip + pad.slice(0, digits));\n  if (pad[digits] >= '5') n += 1n;\n  return n;\n};\nconst mulDec = (minor, x) => {\n  const [ip, fp] = splitDec(x);\n  const scale = 10n ** BigInt(fp.length);\n  return (BigInt(ip + fp) * minor * 2n + scale) / (2n * scale);\n};\nconst toNum = (minor) => Number(minor) / factor;\nconst money = (n) => {\n  try { return new Intl.NumberFormat('en-US', { style: 'currency', currency: order.currency }).format(n); }\n  catch (e) { return order.currency + ' ' + n.toFixed(digits); }\n};\nconst sumDec = (xs) => {\n  const parts = xs.map(splitDec);\n  const w = Math.max(0, ...parts.map((p) => p[1].length));\n  const total = parts.reduce((s, p) => s + BigInt(p[0] + p[1].padEnd(w, '0')), 0n);\n  const str = total.toString().padStart(w + 1, '0');\n  const out = w ? str.slice(0, -w) + '.' + str.slice(-w) : str;\n  return out.includes('.') ? out.replace(/\\.?0+$/, '') : out;\n};\nconst accent = /^#[0-9a-fA-F]{6}$/.test(opts.accentColor) ? opts.accentColor : '#1f4e79';\nconst lines = order.items.map((it) => {\n  const unitMinor = toMinor(it.unitPrice);\n  return { description: it.description, quantity: it.quantity, unitMinor, amountMinor: mulDec(unitMinor, it.quantity) };\n});\nconst subtotalMinor = lines.reduce((s, l) => s + l.amountMinor, 0n);\nconst [rateI, rateF] = splitDec(order.taxRate);\nconst rateScale = 10n ** BigInt(rateF.length) * 100n;\nconst taxMinor = (BigInt(rateI + rateF) * subtotalMinor * 2n + rateScale) / (2n * rateScale);\nconst totalMinor = subtotalMinor + taxMinor;\nconst baseCss = 'body{font-family:Arial,Helvetica,sans-serif;color:#222;font-size:12px}' +\n  'h1{color:' + accent + ';font-size:24px;margin:0 0 4px}.meta{color:#555;margin-bottom:24px}' +\n  'table{width:100%;border-collapse:collapse}th{background:' + accent + ';color:#fff;text-align:left;padding:8px}' +\n  'td{padding:8px;border-bottom:1px solid #ddd}tr:nth-child(even) td{background:#f5f7fa}.num{text-align:right}' +\n  '.totals{margin-top:16px;width:45%;margin-left:55%}.totals td{border:0;padding:4px 8px}' +\n  '.grand td{font-weight:bold;font-size:14px;border-top:2px solid ' + accent + '}.notes{margin-top:28px;color:#555}' +\n  '.box{display:inline-block;width:14px;height:14px;border:1px solid #444}';\nconst head = '<!doctype html><html><head><meta charset=\"utf-8\"><style>' + baseCss + '</style></head><body>';\nconst notes = order.notes ? '<div class=\"notes\">' + esc(order.notes) + '</div>' : '';\nconst totalUnits = sumDec(lines.map((l) => l.quantity));\nconst rows = lines.map((l, i) => '<tr><td>' + (i + 1) + '</td><td>' + esc(l.description) + '</td><td class=\"num\">' + esc(l.quantity) +\n  '</td><td><span class=\"box\"></span></td></tr>').join('');\nconst html = head +\n  '<h1>' + esc(opts.companyName) + ' &middot; Packing slip</h1>' +\n  '<div class=\"meta\">Order ' + esc(order.orderId) + ' &middot; ' + esc(order.issueDate) + '<br>Ship to ' + esc(order.customer.name) +\n  (order.customer.address ? '<br>' + esc(order.customer.address) : '') + '</div>' +\n  '<table><thead><tr><th>#</th><th>Item</th><th class=\"num\">Qty</th><th>Packed</th></tr></thead><tbody>' + rows + '</tbody></table>' +\n  '<p>Total lines: ' + lines.length + '. Total units: ' + esc(totalUnits) + '.</p>' + notes + '</body></html>';\nreturn [{ json: { order, html, lineCount: lines.length, totalUnits, layout: 'packing-slip' } }];"
      },
      "id": "node-21",
      "name": "Build Packing Slip HTML",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        340
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "convert",
        "operation": "htmlToPdf",
        "html": "={{ $json.html }}",
        "htmlOptions": {
          "page_size": "={{ $('Set Document Options').first().json.pageSize }}",
          "margin": 36,
          "print_background": true
        },
        "outputBinaryPropertyName": "data",
        "fileName": "={{ $('Set Document Options').first().json.order.fileName }}"
      },
      "id": "node-22",
      "name": "Render HTML to PDF",
      "type": "n8n-nodes-pdfops.pdfops",
      "typeVersion": 2,
      "position": [
        1600,
        200
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-23",
              "leftValue": "={{ /renderer_busy/i.test(String(($json.error && ($json.error.message || $json.error)) || '')) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-24",
      "name": "Renderer Busy?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1600,
        440
      ]
    },
    {
      "parameters": {
        "resume": "timeInterval",
        "amount": 3,
        "unit": "seconds"
      },
      "id": "node-25",
      "name": "Pause Before Retry",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        1840,
        440
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "resource": "convert",
        "operation": "htmlToPdf",
        "html": "={{ $('Build Invoice HTML').isExecuted ? $('Build Invoice HTML').first(0).json.html : $('Build Packing Slip HTML').first(0).json.html }}",
        "htmlOptions": {
          "page_size": "={{ $('Set Document Options').first().json.pageSize }}",
          "margin": 36,
          "print_background": true
        },
        "outputBinaryPropertyName": "data",
        "fileName": "={{ $('Set Document Options').first().json.order.fileName }}"
      },
      "id": "node-26",
      "name": "Retry Render HTML to PDF",
      "type": "n8n-nodes-pdfops.pdfops",
      "typeVersion": 2,
      "position": [
        2080,
        440
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-27",
              "leftValue": "={{ $('Set Document Options').first().json.order.delivery === 'download' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-28",
      "name": "Return PDF Directly?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2320,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "binary",
        "responseDataSource": "set",
        "inputFieldName": "data",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/pdf"
              },
              {
                "name": "Content-Disposition",
                "value": "={{ 'attachment; filename=\"' + $('Set Document Options').first().json.order.fileName + '\"' }}"
              }
            ]
          }
        }
      },
      "id": "node-29",
      "name": "Respond With PDF",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2560,
        60
      ]
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "upload",
        "inputDataFieldName": "data",
        "name": "={{ $('Set Document Options').first().json.order.fileName }}",
        "driveId": {
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "mode": "list",
          "value": "root",
          "cachedResultName": "/ (Root folder)"
        },
        "options": {}
      },
      "id": "node-30",
      "name": "Store PDF in Drive",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2560,
        340
      ],
      "onError": "continueErrorOutput",
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "",
          "name": "Google Drive account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Store PDF in Drive returns only the file's metadata. The PDF itself is on the item that left the false output of Return PDF Directly?.\nreturn $input.all().map((it, i) => ({ json: it.json, binary: $('Return PDF Directly?').itemMatching(i).binary, pairedItem: it.pairedItem }));"
      },
      "id": "node-31",
      "name": "Attach PDF to Drive Result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2800,
        200
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $('Set Document Options').first().json.order.customer.email }}",
        "subject": "={{ $('Set Document Options').first().json.emailSubject + ' ' + $('Set Document Options').first().json.order.orderId }}",
        "emailType": "text",
        "message": "={{ 'Hello ' + $('Set Document Options').first().json.order.customer.name + ', your document for order ' + $('Set Document Options').first().json.order.orderId + ' is attached.' }}",
        "options": {
          "attachmentsUi": {
            "attachmentsBinary": [
              {
                "property": "data"
              }
            ]
          }
        }
      },
      "id": "node-32",
      "name": "Email PDF with Gmail",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        3040,
        200
      ],
      "onError": "continueErrorOutput",
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'ok', orderId: $('Set Document Options').first().json.order.orderId, file: $('Set Document Options').first().json.order.fileName, pages: ($('Retry Render HTML to PDF').isExecuted ? $('Retry Render HTML to PDF').first(0).json.pages : $('Render HTML to PDF').first(0).json.pages) || null, link: $('Store PDF in Drive').first(0).json.webViewLink || ('https://drive.google.com/file/d/' + $('Store PDF in Drive').first(0).json.id + '/view'), emailed: true }) }}",
        "options": {}
      },
      "id": "node-33",
      "name": "Respond Success",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        3280,
        200
      ]
    },
    {
      "parameters": {
        "includeOtherFields": false,
        "assignments": {
          "assignments": [
            {
              "id": "as-34",
              "name": "stage",
              "value": "={{ ({ 'Build Invoice HTML': 'html build', 'Build Packing Slip HTML': 'html build', 'Render HTML to PDF': 'pdf render', 'Renderer Busy?': 'pdf render', 'Retry Render HTML to PDF': 'pdf render', 'Store PDF in Drive': 'drive upload', 'Attach PDF to Drive Result': 'email', 'Email PDF with Gmail': 'email' })[$prevNode.name] || $prevNode.name }}",
              "type": "string"
            },
            {
              "id": "as-35",
              "name": "reason",
              "value": "={{ ($json.error && ($json.error.message || String($json.error))) || $json.message || 'unknown error' }}",
              "type": "string"
            },
            {
              "id": "as-36",
              "name": "orderId",
              "value": "={{ $('Set Document Options').first().json.order.orderId }}",
              "type": "string"
            },
            {
              "id": "as-37",
              "name": "orderIdSlack",
              "value": "={{ ((s, n) => '`' + String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/`/g, \"'\").replace(/\\s+/g, ' ').slice(0, n) + '`')($('Set Document Options').first().json.order.orderId, 80) }}",
              "type": "string"
            },
            {
              "id": "as-38",
              "name": "reasonSlack",
              "value": "={{ ((s, n) => '`' + String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/`/g, \"'\").replace(/\\s+/g, ' ').slice(0, n) + '`')(($json.error && ($json.error.message || String($json.error))) || $json.message || 'unknown error', 300) }}",
              "type": "string"
            },
            {
              "id": "as-39",
              "name": "fileStored",
              "value": "={{ ['Email PDF with Gmail', 'Attach PDF to Drive Result'].includes($prevNode.name) }}",
              "type": "boolean"
            }
          ]
        },
        "options": {}
      },
      "id": "node-40",
      "name": "Describe Failure",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1600,
        880
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "mode": "name",
          "value": "={{ $('Set Document Options').first().json.alertChannel }}"
        },
        "text": "={{ ':warning: PDF order ' + $json.orderIdSlack + ' failed at ' + $json.stage + ' (execution ' + $execution.id + '): ' + $json.reasonSlack }}",
        "otherOptions": {}
      },
      "id": "node-41",
      "name": "Alert in Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1840,
        880
      ],
      "onError": "continueRegularOutput",
      "credentials": {
        "slackApi": {
          "id": "",
          "name": "Slack account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cond-42",
              "leftValue": "={{ $('Describe Failure').first().json.fileStored }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-43",
      "name": "Was the File Stored?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2080,
        880
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'stored_not_emailed', orderId: $('Describe Failure').first().json.orderId, file: $('Set Document Options').first().json.order.fileName, link: $('Store PDF in Drive').first(0).json.webViewLink || ('https://drive.google.com/file/d/' + $('Store PDF in Drive').first(0).json.id + '/view'), emailed: false, alerted: !$('Alert in Slack').first().json.error }) }}",
        "options": {}
      },
      "id": "node-44",
      "name": "Respond File Stored Without Email",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2320,
        820
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'error', stage: $('Describe Failure').first().json.stage, orderId: $('Describe Failure').first().json.orderId, alerted: !$('Alert in Slack').first().json.error, message: $('Alert in Slack').first().json.error ? 'The PDF could not be completed. Alerting the team also failed, so please report it.' : 'The PDF could not be completed. The team has been alerted.' }) }}",
        "options": {
          "responseCode": 502
        }
      },
      "id": "node-45",
      "name": "Respond With Server Error",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2320,
        1020
      ]
    }
  ],
  "connections": {
    "Order Webhook": {
      "main": [
        [
          {
            "node": "Validate Order Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Order Payload": {
      "main": [
        [
          {
            "node": "Payload Valid?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Payload Valid?": {
      "main": [
        [
          {
            "node": "Set Document Options",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond With Validation Errors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Document Options": {
      "main": [
        [
          {
            "node": "Choose Layout",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Choose Layout": {
      "main": [
        [
          {
            "node": "Build Invoice HTML",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Packing Slip HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Invoice HTML": {
      "main": [
        [
          {
            "node": "Render HTML to PDF",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Packing Slip HTML": {
      "main": [
        [
          {
            "node": "Render HTML to PDF",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Render HTML to PDF": {
      "main": [
        [
          {
            "node": "Return PDF Directly?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Renderer Busy?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Renderer Busy?": {
      "main": [
        [
          {
            "node": "Pause Before Retry",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pause Before Retry": {
      "main": [
        [
          {
            "node": "Retry Render HTML to PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Retry Render HTML to PDF": {
      "main": [
        [
          {
            "node": "Return PDF Directly?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Return PDF Directly?": {
      "main": [
        [
          {
            "node": "Respond With PDF",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Store PDF in Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store PDF in Drive": {
      "main": [
        [
          {
            "node": "Attach PDF to Drive Result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email PDF with Gmail": {
      "main": [
        [
          {
            "node": "Respond Success",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Describe Failure": {
      "main": [
        [
          {
            "node": "Alert in Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert in Slack": {
      "main": [
        [
          {
            "node": "Was the File Stored?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Was the File Stored?": {
      "main": [
        [
          {
            "node": "Respond File Stored Without Email",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond With Server Error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Attach PDF to Drive Result": {
      "main": [
        [
          {
            "node": "Email PDF with Gmail",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Describe Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
