{
  "name": "Extract key terms from a contract PDF",
  "nodes": [
    {
      "parameters": {
        "content": "## Extract key terms from a contract PDF\n\nPortfolio demo only. This workflow is an original example for demonstration. It is not client work and it does not represent a deployment for any customer.\n\nRun **Run demo** to execute the offline rules engine. The live branch is used only when the incoming item sets `demo` to false and the placeholder credentials have been replaced.",
        "height": 220,
        "width": 520,
        "color": 4
      },
      "id": "cd37830a-f7fe-41e2-86dc-4fcce32e9930",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "b08592ec-b679-485d-9682-7cdad72d73b6",
      "name": "Run demo",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        40,
        280
      ],
      "notes": "CLI and the n8n editor start here. An empty manual run loads the bundled sample.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "contract-key-terms",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "fd6ba4bb-936b-4798-8b17-260cb6fca0c1",
      "name": "Inbound webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        40,
        460
      ],
      "notes": "POST JSON to this path. Include demo:false only after credentials are connected.",
      "notesInFlow": true,
      "webhookId": "919a0a5d-e3d4-4af9-9f8f-9307c51f31ee"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "event": "messageReceived",
        "simple": true
      },
      "id": "c499a98f-2b48-4c02-ad7c-bf5d28639555",
      "name": "Gmail trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        40,
        640
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER_GMAILOAUTH2",
          "name": "Gmail account"
        }
      },
      "notes": "Polls the mailbox once credentials replace the placeholder. Tests do not call Gmail.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"from\": \"legal@harbor.example\",\n  \"filename\": \"harbor-msa.pdf\",\n  \"vendor\": \"Harbor & Co\",\n  \"invoiceNumber\": \"MSA-12\",\n  \"subtotal\": 24000,\n  \"tax\": 0,\n  \"total\": 24000,\n  \"dueDate\": \"2027-01-01\",\n  \"text\": \"Vendor: Harbor & Co\\nInvoice MSA-12\\nSubtotal 24000.00\\nTax 0.00\\nTotal 24000.00\\nDue 2027-01-01\\n\"\n};\nconst incoming = $input.first()?.json ?? {};\nconst provided = Object.keys(incoming).filter((key) => incoming[key] !== undefined && incoming[key] !== null && incoming[key] !== '');\nconst base = provided.length ? { ...sample, ...incoming } : { ...sample };\nconst flag = incoming.demo;\nbase.demo = !(flag === false || flag === 'false' || flag === 0 || flag === '0');\nreturn [{ json: base }];\n"
      },
      "id": "c9977d1b-725d-474e-813b-d1c8dac9179d",
      "name": "Normalize input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        340,
        360
      ],
      "notes": "Merges the request over the bundled sample. demo stays true unless the caller explicitly turns it off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nconst produced = (() => {\n\nconst text = String(item.text || item.body || '');\nconst vendor = item.vendor || (text.match(/vendor[:\\s]+([^\\n]+)/i) || [])[1] || 'Unknown vendor';\nconst invoiceNumber = item.invoiceNumber || (text.match(/inv(?:oice)?\\s*#?\\s*([A-Z0-9-]+)/i) || [])[1] || 'UNKNOWN';\nconst currency = item.currency || 'USD';\nconst total = Number(item.total ?? matchAmount(text, 'total') ?? 0);\nconst tax = Number(item.tax ?? matchAmount(text, 'tax') ?? 0);\nconst subtotal = Number(item.subtotal ?? matchAmount(text, 'subtotal') ?? (total - tax));\nconst dueDate = item.dueDate || (text.match(/due[:\\s]+(\\d{4}-\\d{2}-\\d{2})/i) || [])[1] || '';\nconst expected = Math.round((subtotal + tax) * 100) / 100;\nconst balanced = Math.abs(expected - total) <= Math.max(0.5, total * 0.02);\nconst record = {\n  vendor: String(vendor).trim(),\n  invoiceNumber,\n  currency,\n  subtotal,\n  tax,\n  total,\n  dueDate,\n  balanced,\n  mailbox: item.from || '',\n  filename: item.filename || 'invoice.pdf',\n  destination: 'Contract register',\n};\nreturn {\n  summary: record.vendor + ' ' + invoiceNumber + ' for ' + total + ' ' + currency + (balanced ? ' balances.' : ' does not balance.'),\n  route: balanced ? 'post' : 'review',\n  record,\n  slackText: (balanced ? 'Post' : 'Review') + ' invoice ' + invoiceNumber + ' from ' + record.vendor + ' (' + total + ' ' + currency + ').',\n  actions: [{ app: 'Contract register', operation: balanced ? 'create' : 'flag', payload: record }],\n};\nfunction matchAmount(source, label) {\n  const pattern = new RegExp(label + '[:\\\\s]*\\\\$?([0-9,]+(?:\\\\.[0-9]{2})?)', 'i');\n  const found = source.match(pattern);\n  return found ? Number(found[1].replace(/,/g, '')) : null;\n}\n\n})();\nif (!produced || typeof produced.summary !== 'string' || !produced.summary.trim()) {\n  throw new Error('Apply rules must return a summary string');\n}\nreturn [{\n  json: {\n    ...item,\n    ...produced,\n    demo: item.demo !== false,\n  },\n}];\n"
      },
      "id": "70d319d5-1aa8-417c-9330-692598b21b76",
      "name": "Apply rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        620,
        360
      ],
      "notes": "Deterministic stand-in for the model or enrichment API. Replace or precede this with a live model node when you turn demo mode off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "e86705e6-45ee-45ea-9c47-e347766852ea",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "08885a26-6dd0-47c7-997a-024ecb3e1a2d",
      "name": "Demo mode?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        900,
        360
      ],
      "notes": "True: package the offline result. False: run the credentialed apps.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nreturn [{\n  json: {\n    demo: true,\n    status: 'demo_ready',\n    workflow: 'contract-key-terms',\n    summary: item.summary,\n    route: item.route ?? null,\n    record: item.record ?? {},\n    actions: item.actions ?? [],\n    slackText: item.slackText ?? item.summary,\n    notes: 'Demo mode did not call external apps. Send {\"demo\": false} after placeholder credentials are replaced.',\n  },\n}];\n"
      },
      "id": "9cf2ee7e-523e-4b28-b0bb-aec5472b6130",
      "name": "Package demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1180,
        180
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Contracts"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "f8faa9ec-cd38-4803-8506-8a705908f705",
      "name": "Append Contracts",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1180,
        760
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "PLACEHOLDER_GOOGLESHEETSOAUTH2API",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "#legal-ops"
        },
        "text": "={{ $json.slackText || $json.summary }}",
        "otherOptions": {}
      },
      "id": "ab580eb8-2729-40a2-896f-c6a5e1b939c5",
      "name": "Post #legal-ops",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        1460,
        760
      ],
      "credentials": {
        "slackOAuth2Api": {
          "id": "PLACEHOLDER_SLACKOAUTH2API",
          "name": "Slack account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Live path\n\nReplace every `PLACEHOLDER_*` credential, then POST the sample with `\"demo\": false`.\n\nThe nodes on this branch use the `record` and `actions` fields produced by Apply rules.",
        "height": 180,
        "width": 420,
        "color": 6
      },
      "id": "beda1574-4670-438c-b676-a882cfd931a1",
      "name": "Live path",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1120,
        520
      ]
    }
  ],
  "connections": {
    "Run demo": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inbound webhook": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail trigger": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize input": {
      "main": [
        [
          {
            "node": "Apply rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply rules": {
      "main": [
        [
          {
            "node": "Demo mode?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Demo mode?": {
      "main": [
        [
          {
            "node": "Package demo result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Append Contracts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Contracts": {
      "main": [
        [
          {
            "node": "Post #legal-ops",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Contract text is scanned for the commercial numbers that legal and finance both ask for, and the row is flagged when the total does not match the stated subtotal."
  },
  "active": false
}
