{
  "id": "bill-import-gate-local-demo",
  "name": "Bill Import Gate — two local review cases",
  "active": false,
  "nodes": [
    {
      "id": "manual",
      "name": "Run local tutorial",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "samples",
      "name": "Synthetic bill batches",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        250,
        0
      ],
      "parameters": {
        "jsCode": "return [{\"json\":{\"case\":\"flagged\",\"scopeConfirmed\":true,\"history\":[{\"id\":\"historical-1\",\"entityId\":\"company-a\",\"vendorId\":\"supplier-a\",\"invoiceNumber\":\"INV-101\",\"fiscalPeriod\":\"FY2026\",\"documentType\":\"bill\",\"currency\":\"USD\",\"amountMinor\":12345,\"billDate\":\"2026-11-01\"}],\"incoming\":[{\"id\":\"candidate-1\",\"entityId\":\"company-a\",\"vendorId\":\"supplier-a\",\"invoiceNumber\":\"INV-101\",\"fiscalPeriod\":\"FY2026\",\"documentType\":\"bill\",\"currency\":\"USD\",\"amountMinor\":12345,\"billDate\":\"2026-11-01\"},{\"id\":\"candidate-2\",\"entityId\":\"company-a\",\"vendorId\":\"supplier-a\",\"invoiceNumber\":\"inv / 101\",\"fiscalPeriod\":\"FY2026\",\"documentType\":\"bill\",\"currency\":\"USD\",\"amountMinor\":12345,\"billDate\":\"2026-11-01\"},{\"id\":\"candidate-3\",\"entityId\":\"company-a\",\"vendorId\":\"supplier-b\",\"invoiceNumber\":\"INV-101\",\"fiscalPeriod\":\"FY2026\",\"documentType\":\"bill\",\"currency\":\"USD\",\"amountMinor\":12345,\"billDate\":\"2026-11-01\"}]}},{\"json\":{\"case\":\"clean\",\"scopeConfirmed\":true,\"history\":[{\"id\":\"historical-1\",\"entityId\":\"company-a\",\"vendorId\":\"supplier-a\",\"invoiceNumber\":\"INV-101\",\"fiscalPeriod\":\"FY2026\",\"documentType\":\"bill\",\"currency\":\"USD\",\"amountMinor\":12345,\"billDate\":\"2026-11-01\"}],\"incoming\":[{\"id\":\"candidate-3\",\"entityId\":\"company-a\",\"vendorId\":\"supplier-b\",\"invoiceNumber\":\"INV-101\",\"fiscalPeriod\":\"FY2026\",\"documentType\":\"bill\",\"currency\":\"USD\",\"amountMinor\":12345,\"billDate\":\"2026-11-01\"}]}}];"
      }
    },
    {
      "id": "review",
      "name": "Local bill preflight",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        0
      ],
      "parameters": {
        "jsCode": "const MAX_ROWS = 5000;\nconst MAX_FINDINGS = 1000;\nconst text = (v, label) => {\n  if (typeof v !== 'string' || !v.trim() || v.length > 160 || /[\\x00-\\x1f]/.test(v)) throw new Error(`${label}: nonempty text up to 160 characters required`);\n  return v.trim();\n};\nfunction rows(input, source) {\n  if (!Array.isArray(input) || input.length > MAX_ROWS) throw new Error(`${source}: array of at most ${MAX_ROWS} rows required`);\n  const ids = new Set();\n  return input.map((r, i) => {\n    if (!r || typeof r !== 'object' || Array.isArray(r)) throw new Error(`${source}[${i}]: object required`);\n    const out = {source, row: i + 1};\n    for (const k of ['id','entityId','vendorId','invoiceNumber','fiscalPeriod']) out[k] = text(r[k],`${source}[${i}].${k}`);\n    if (ids.has(out.id)) throw new Error(`${source}: repeated row id ${out.id}`);\n    ids.add(out.id);\n    if (!['bill','credit_note'].includes(r.documentType)) throw new Error('documentType: bill or credit_note required');\n    out.documentType = r.documentType;\n    if (typeof r.currency !== 'string' || !/^[A-Z]{3}$/.test(r.currency)) throw new Error('currency: uppercase three-letter code required');\n    out.currency = r.currency;\n    if (!Number.isSafeInteger(r.amountMinor) || r.amountMinor < 0) throw new Error('amountMinor: nonnegative safe integer required; no floating point amounts');\n    out.amountMinor = r.amountMinor;\n    if (typeof r.billDate !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}$/.test(r.billDate) || !Number.isFinite(Date.parse(r.billDate)) || new Date(r.billDate).toISOString().slice(0,10) !== r.billDate) throw new Error('billDate: real ISO date required');\n    out.billDate = r.billDate;\n    return out;\n  });\n}\nconst scope = r => [r.entityId,r.vendorId,r.documentType,r.fiscalPeriod];\nconst exact = r => JSON.stringify([...scope(r),r.invoiceNumber]);\n// Used ONLY for a review candidate, never to merge references or block a bill.\nconst loose = r => r.invoiceNumber.normalize('NFKC').toUpperCase().replace(/[\\s\\-_/\\.]/g,'');\nconst candidate = r => JSON.stringify([...scope(r),loose(r),r.currency,r.amountMinor,r.billDate]);\nfunction inspectBills(input) {\n  if (!input || input.scopeConfirmed !== true) throw new Error('scopeConfirmed must be true: stable entity/vendor IDs and fiscal periods must be mapped by the operator');\n  const history = rows(input.history,'history'), incoming = rows(input.incoming,'incoming');\n  if (incoming.length === 0) throw new Error('incoming: at least one row required');\n  const exactIndex = new Map(), candidateIndex = new Map();\n  const findings = []; let total = 0, blocking = 0;\n  const add = finding => { total++; if (finding.severity === 'block') blocking++; if (findings.length < MAX_FINDINGS) findings.push(finding); };\n  const index = r => {\n    for (const [map,key] of [[exactIndex,exact(r)],[candidateIndex,candidate(r)]]) {\n      // One representative bounds output and avoids quadratic pair generation.\n      if (!map.has(key)) map.set(key,r);\n    }\n  };\n  for (const r of history) index(r);\n  for (const r of incoming) {\n    const prev = exactIndex.get(exact(r));\n    if (prev) {\n      const sameAmount = prev.currency === r.currency && prev.amountMinor === r.amountMinor;\n      add({code:sameAmount?'repeated_bill_identity':'bill_identity_amount_conflict',severity:sameAmount?'block':'review',row:r.row,id:r.id,matchedSource:prev.source,matchedRow:prev.row,matchedId:prev.id,reason:sameAmount?'Same entity, vendor, document type, fiscal period, exact reference, currency and amount. Review before import.':'Same scoped reference but amount or currency differs. Resolve identity; this is not proof of a duplicate payment.'});\n    } else {\n      const similar = loose(r) && candidateIndex.get(candidate(r));\n      if (similar) add({code:'similar_reference_candidate',severity:'review',row:r.row,id:r.id,matchedSource:similar.source,matchedRow:similar.row,matchedId:similar.id,reason:'Reference differs but normalized form, scope, date, currency and amount match. Human review only.'});\n    }\n    index(r);\n  }\n  return {version:'0.1.0',decision:total?'hold_for_review':'no_supported_flags',counts:{history:history.length,incoming:incoming.length,findings:total,blocking,review:total-blocking},findings,truncated:total>findings.length,scope:'Explicit entity/vendor/document type/fiscal period; exact references remain case-sensitive.',limitations:['Flags are import-review candidates, not proof of duplicate payment.','No bank, vendor identity, tax or actual payment verification. No writeback, deletion or payment.','History completeness and stable IDs are operator responsibilities. Different vendor IDs are not merged.','No fuzzy vendor matching, OCR, currency conversion or amount tolerance.']};\n}\n\nreturn $input.all().map(item => ({json:{case:item.json.case,...inspectBills(item.json)}}));"
      }
    }
  ],
  "connections": {
    "Run local tutorial": {
      "main": [
        [
          {
            "node": "Synthetic bill batches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Synthetic bill batches": {
      "main": [
        [
          {
            "node": "Local bill preflight",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}