{
  "name": "Flowgrammer Canada — invoice-review",
  "nodes": [
    {
      "id": "fg-1",
      "name": "Test manually",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        300
      ],
      "parameters": {}
    },
    {
      "id": "fg-2",
      "name": "Weekdays at 9 Toronto",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        260,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 * * 1-5"
            }
          ]
        }
      }
    },
    {
      "id": "fg-3",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        520,
        300
      ],
      "parameters": {
        "mode": "raw",
        "jsonOutput": "{\"client_id\":\"demo-client\",\"client_name\":\"Demo client\",\"business_display_name\":\"Your business\",\"idempotency_namespace\":\"CHANGE-TO-UNIQUE-CLIENT-UUID\",\"timezone\":\"America/Toronto\",\"locale\":\"en-CA\",\"currency\":\"CAD\",\"province\":\"ON\",\"tax_regime\":\"HST-ON\",\"tax_components\":[[\"HST\",0.13]],\"tax_inclusive\":false,\"rates_valid_from\":\"2026-01-01\",\"rates_valid_through\":\"2026-12-31\",\"dry_run\":true,\"dispatch_enabled\":false,\"batch_size\":10,\"wait_seconds_between_sends\":5,\"amount_tolerance_cents\":1,\"variance_pct_threshold\":20,\"reminder_days\":[3,7,14],\"max_reminders\":3,\"deadline_notice_days\":14,\"max_file_mb\":10,\"max_pages\":20,\"allowed_file_types\":[\"application/pdf\",\"image/png\",\"image/jpeg\"],\"quickbooks_sandbox\":true,\"quickbooks_realm_id\":\"\",\"quickbooks_item_id\":\"\",\"quickbooks_tax_code\":\"\",\"xero_tenant_id\":\"\",\"xero_account_code\":\"\",\"xero_tax_type\":\"\",\"error_notify_to\":\"configure-internal-alert@example.com\",\"from_email\":\"configure-sender@example.com\"}",
        "options": {}
      }
    },
    {
      "id": "fg-4",
      "name": "Load unhandled inputs",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        780,
        300
      ],
      "parameters": {
        "operation": "executeQuery",
        "query": "select * from fg_finance.pending($1,$2,$3,$4);",
        "options": {
          "queryReplacement": "={{ [$('Settings').first().json.client_id, 'invoice-review', $('Settings').first().json.dry_run, $('Settings').first().json.batch_size] }}"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "fg-5",
      "name": "Validate and prepare each record",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        300
      ],
      "parameters": {
        "jsCode": "function prepare(kind, record, settings, today) {\n  const r = record;\n  const s = settings;\n  const need = (ok, message) => { if (!ok) throw new Error(message); };\n  const money = (v) => { need(typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1e9, 'Invalid monetary amount'); return Math.round((v + Number.EPSILON) * 100); };\n  const date = (v) => { need(typeof v === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(v) && new Date(v).toISOString().slice(0, 10) === v, 'Invalid calendar date'); return Date.parse(v); };\n  const days = (v) => Math.floor((date(today) - date(v)) / 86400000);\n  need(r && typeof r === 'object', 'Missing input');\n  need(s.currency === 'CAD' && s.timezone === 'America/Toronto', 'Use CAD and America/Toronto');\n  need(typeof s.dry_run === 'boolean' && typeof s.tax_inclusive === 'boolean', 'Settings flags must be booleans');\n  need(r.currency === undefined || r.currency === 'CAD', 'Non-CAD record: resolve exchange rate separately');\n  const result = { kind, action: 'review', currency: 'CAD', as_of: today, source_id: r.source_id, source_revision: r.revision };\n  const email = (recipient, subject, text) => {\n    need(typeof recipient === 'string' && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(recipient), 'Invalid recipient');\n    return { ...result, action: 'email', recipient, subject, text };\n  };\n  if (kind === 'invoice-review') {\n    need(r.tax_treatment === 'standard', 'Exempt, zero-rated, mixed and special supplies require a separate accountant review');\n    need(r.place_of_supply_confirmed === true && r.province === s.province, 'Confirm transaction place of supply and matching settings');\n    date(r.date);\n    need(r.date >= s.rates_valid_from && r.date <= s.rates_valid_through, 'Transaction outside reviewed rate window');\n    need(Array.isArray(r.lines) && r.lines.length > 0 && r.lines.length <= 100, 'Require 1–100 invoice lines');\n    if (r.file) {\n      need(Number.isInteger(r.file.bytes) && r.file.bytes > 0 && r.file.bytes <= s.max_file_mb * 1024 * 1024, 'File size limit');\n      need(s.allowed_file_types.includes(r.file.mime) && Number.isInteger(r.file.pages) && r.file.pages > 0 && r.file.pages <= s.max_pages, 'File type or page limit');\n      need(r.file.extraction_reviewed === true, 'Review extracted fields against original document');\n    }\n    const rates = s.tax_components;\n    const regimes = { ON: [['HST', 0.13]], NS: [['HST', 0.14]], NB: [['HST', 0.15]], NL: [['HST', 0.15]], PE: [['HST', 0.15]], QC: [['GST', 0.05], ['QST', 0.09975]], AB: [['GST', 0.05]], NT: [['GST', 0.05]], NU: [['GST', 0.05]], YT: [['GST', 0.05]] };\n    need(JSON.stringify(rates) === JSON.stringify(regimes[s.province]), 'Unsupported province or unreviewed tax components; PST provinces require custom review');\n    const rate = rates.reduce((sum, [, v]) => sum + v, 0);\n    const lines = r.lines.map(l => {\n      need(typeof l.description === 'string' && l.description.length > 0 && l.description.length <= 500, 'Missing line description');\n      const amount = money(l.amount);\n      const net = s.tax_inclusive ? Math.round(amount / (1 + rate)) : amount;\n      const taxes = rates.map(([name, v]) => ({ name, cents: Math.round(net * v) }));\n      const total = net + taxes.reduce((sum, t) => sum + t.cents, 0);\n      need(!s.tax_inclusive || Math.abs(total - amount) <= s.amount_tolerance_cents, 'Inclusive tax rounding requires review');\n      return { description: l.description, input_cents: amount, net_cents: net, taxes, total_cents: total };\n    });\n    const total = lines.reduce((sum, l) => sum + l.total_cents, 0);\n    need(Math.abs(total - money(r.document_total)) <= s.amount_tolerance_cents, 'Calculated total does not match source document');\n    need(['review', 'quickbooks', 'xero'].includes(r.destination), 'Invalid ledger destination');\n    const output = { ...result, lines, total_cents: total, province: s.province, tax_inclusive: s.tax_inclusive, action: r.destination };\n    if (r.destination === 'quickbooks') {\n      need(/^\\d+$/.test(s.quickbooks_realm_id) && /^[A-Za-z0-9_-]+$/.test(r.customer_id || '') && s.quickbooks_tax_code && s.quickbooks_item_id, 'Map QuickBooks realm, customer, item and Canadian tax code');\n      return { ...output, realm_id: s.quickbooks_realm_id, sandbox: s.quickbooks_sandbox === true, body: { CustomerRef: { value: r.customer_id }, CurrencyRef: { value: 'CAD' }, TxnDate: r.date, GlobalTaxCalculation: s.tax_inclusive ? 'TaxInclusive' : 'TaxExcluded', Line: lines.map(l => ({ Amount: l.input_cents / 100, Description: l.description, DetailType: 'SalesItemLineDetail', SalesItemLineDetail: { ItemRef: { value: s.quickbooks_item_id }, TaxCodeRef: { value: s.quickbooks_tax_code } } })) } };\n    }\n    if (r.destination === 'xero') {\n      need(/^[a-f0-9-]{36}$/i.test(s.xero_tenant_id) && /^[a-f0-9-]{36}$/i.test(r.contact_id || '') && s.xero_tax_type && s.xero_account_code, 'Map Xero tenant, contact, account and Canadian tax type');\n      return { ...output, tenant_id: s.xero_tenant_id, body: { Invoices: [{ Type: 'ACCREC', Status: 'DRAFT', Contact: { ContactID: r.contact_id }, CurrencyCode: 'CAD', Date: r.date, LineAmountTypes: s.tax_inclusive ? 'Inclusive' : 'Exclusive', LineItems: lines.map(l => ({ Description: l.description, Quantity: 1, UnitAmount: l.input_cents / 100, AccountCode: s.xero_account_code, TaxType: s.xero_tax_type })) }] } };\n    }\n    return output;\n  }\n  if (kind === 'overdue-reminders') {\n    need(r.disputed === false && r.do_not_contact === false, 'Disputed or suppressed invoice requires review');\n    const age = days(r.due_date);\n    const balance = money(r.balance);\n    if (age < s.reminder_days[0] || balance === 0) return { ...result, action: 'skip', reason: 'Not overdue or already paid' };\n    need(Number.isInteger(r.reminders_sent) && r.reminders_sent >= 0, 'Missing reminder history');\n    const stages = s.reminder_days.filter(d => age >= d);\n    if (r.reminders_sent >= Math.min(stages.length, s.max_reminders)) return { ...result, action: 'skip', reason: 'Reminder cadence already handled' };\n    return { ...email(r.email, `Invoice ${r.invoice_number}: payment reminder`, `Our records show CAD ${(balance / 100).toFixed(2)} outstanding on invoice ${r.invoice_number}, due ${r.due_date}. Please reply if payment has already been made or you need to discuss the invoice.`), stage: stages.length, final_notice: stages.length === s.reminder_days.length };\n  }\n  if (kind === 'missing-documents') {\n    need(Number.isInteger(r.tax_year) && r.tax_year >= 2000 && r.tax_year <= Number(today.slice(0, 4)), 'Confirm tax year');\n    need(Array.isArray(r.approved_checklist) && Array.isArray(r.received_documents), 'Require approved checklist and received documents');\n    const missing = r.approved_checklist.filter(x => !r.received_documents.includes(x));\n    if (!missing.length) return { ...result, action: 'skip', reason: 'Documents complete' };\n    need(r.secure_upload_url && /^https:\\/\\//.test(r.secure_upload_url), 'Use secure client upload URL');\n    return email(r.email, `Documents requested for ${r.tax_year}`, `Please upload the following confirmed checklist items for ${r.tax_year}: ${missing.join(', ')}. Use your secure portal: ${r.secure_upload_url}. Do not email SINs or banking details.`);\n  }\n  if (kind === 'reconciliation') {\n    need(Array.isArray(r.bank) && Array.isArray(r.ledger), 'Require bank and ledger exports');\n    const bankIds = r.bank.map(x => x.id), ledgerIds = r.ledger.map(x => x.id);\n    need(bankIds.every(Boolean) && ledgerIds.every(Boolean) && new Set(bankIds).size === bankIds.length && new Set(ledgerIds).size === ledgerIds.length, 'Duplicate or missing transaction IDs');\n    return { ...result, matches: r.bank.map(b => { const candidates = r.ledger.filter(l => l.reference === b.reference && l.date === b.date && Math.abs(money(l.amount) - money(b.amount)) <= s.amount_tolerance_cents); return { bank_id: b.id, status: candidates.length === 1 ? 'proposed-match' : 'exception', ledger_ids: candidates.map(x => x.id) }; }) };\n  }\n  if (kind === 'payroll-checks') {\n    need(Array.isArray(r.employees), 'Require employee export');\n    const counts = new Map();\n    for (const e of r.employees) counts.set(e.id, (counts.get(e.id) || 0) + 1);\n    return { ...result, exceptions: r.employees.flatMap(e => {\n      const issues = [];\n      if (!e.id || counts.get(e.id) > 1) issues.push('duplicate-or-missing-employee-id');\n      const pay = money(e.gross_pay), previous = money(e.previous_gross_pay);\n      if (typeof e.hours !== 'number' || e.hours < 0 || (e.hours === 0 && pay > 0)) issues.push('hours-review');\n      if ((previous === 0 && pay > 0) || (previous > 0 && Math.abs(pay - previous) / previous * 100 > s.variance_pct_threshold)) issues.push('pay-variance');\n      return issues.length ? [{ employee_id: e.id, issues }] : [];\n    }), note: 'Review only. Does not calculate statutory deductions or release payroll.' };\n  }\n  if (kind === 'financial-report') {\n    need(Array.isArray(r.rows), 'Require period rows');\n    const totals = { revenue_cents: 0, expense_cents: 0, tax_collected_cents: 0, tax_paid_cents: 0, budget_cents: 0 };\n    for (const row of r.rows) { need(row.currency === 'CAD', 'Mixed currency report requires conversion'); for (const key of Object.keys(totals)) totals[key] += money(row[key.replace('_cents', '')]); }\n    return { ...result, ...totals, operating_result_cents: totals.revenue_cents - totals.expense_cents, tax_reserve_estimate_cents: totals.tax_collected_cents - totals.tax_paid_cents, budget_variance_cents: totals.expense_cents - totals.budget_cents, note: 'Operational estimate from reviewed inputs; not a tax return, ITC eligibility assessment, or cash-flow forecast.' };\n  }\n  if (kind === 'deadline-alerts') {\n    need(r.deadline_confirmed === true && /^https:\\/\\//.test(r.authority_url || ''), 'Require reviewer-confirmed deadline and authority URL');\n    const remaining = -days(r.due_date);\n    if (remaining > s.deadline_notice_days) return { ...result, action: 'skip', reason: 'Outside notice window' };\n    return email(r.email, `Review deadline: ${r.label}`, `Confirmed deadline: ${r.due_date}. Days remaining: ${remaining}. Source: ${r.authority_url}. Review client filing frequency and any holiday or extension rules.`);\n  }\n  if (kind === 'timesheet-reminders') {\n    need(r.active === true && typeof r.submitted === 'boolean', 'Require active employee and submission status');\n    date(r.period_end);\n    if (r.submitted || days(r.period_end) < 0) return { ...result, action: 'skip', reason: 'Submitted or period not closed' };\n    return email(r.email, `Timesheet for period ending ${r.period_end}`, `Please submit or correct your timesheet for the period ending ${r.period_end} through the usual approved system.`);\n  }\n  throw new Error('Unknown workflow kind');\n}\nconst s = $('Settings').first().json;\nconst today = $now.setZone(s.timezone).toISODate();\nreturn $input.all().map((item, index) => {\nconst r = item.json; let result;\ntry { result = prepare('invoice-review', {...r.payload, source_id:r.source_id, revision:r.revision}, s, today); }\ncatch (error) { result = {kind:'invoice-review',action:'exception',reason:String(error.message),source_id:r.source_id}; }\nreturn {json:{input_id:r.id,client_id:r.client_id,dry_run:s.dry_run,result},pairedItem:{item:index}};\n});"
      }
    },
    {
      "id": "fg-6",
      "name": "Save immutable decision and audit",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        1300,
        300
      ],
      "parameters": {
        "operation": "executeQuery",
        "query": "select fg_finance.record($1,$2,$3,$4::jsonb) as decision_id;",
        "options": {
          "queryReplacement": "={{ [$json.input_id, $json.client_id, $json.dry_run, JSON.stringify($json.result)] }}"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "fg-7",
      "name": "Signal saved exceptions",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        300
      ],
      "parameters": {
        "jsCode": "const count = $('Validate and prepare each record').all().filter(x => x.json.result.action === 'exception').length; if (count) throw new Error(count + ' finance inputs need review. Valid decisions and exceptions were saved; inspect the private review queue.'); return $input.all();"
      }
    },
    {
      "id": "fg-8",
      "name": "Read setup guide first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1820,
        -100
      ],
      "parameters": {
        "content": "## Setup required\nOriginal Flowgrammer workflow. Import queue.sql into a separate private PostgreSQL database. Connect least-privilege Postgres credentials to every database node. Configure Settings; keep dry_run=true for testing. Import 12-error-alert.json and select it under Workflow Settings > Error workflow (IDs are instance-specific). No OCR/AI or source-app connectors included: load normalized records using the documented input contract. Human reviewer uses separate database login. See README.md.",
        "height": 380,
        "width": 520
      }
    }
  ],
  "connections": {
    "Test manually": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Weekdays at 9 Toronto": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Load unhandled inputs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Load unhandled inputs": {
      "main": [
        [
          {
            "node": "Validate and prepare each record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate and prepare each record": {
      "main": [
        [
          {
            "node": "Save immutable decision and audit",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save immutable decision and audit": {
      "main": [
        [
          {
            "node": "Signal saved exceptions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Toronto",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "none",
    "executionTimeout": 300
  },
  "pinData": {},
  "tags": []
}
