{
  "name": "CDUDU WF01 — VAT Invoice XML/JSON Parser, Deterministic Validator & VietQR Reconcile",
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "Asia/Ho_Chi_Minh",
    "saveManualExecutions": true,
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "all",
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": "CDUDU_GLOBAL_DLQ_ERROR_WORKFLOW"
  },
  "versionId": "cdudu-wf01-v2026.12.02",
  "meta": {
    "instanceId": "cdudu-enterprise-n8n-2x",
    "templateCredsSetupCompleted": false,
    "author": "Công ty Giải Pháp và Công Nghệ Cdudu (https://cdudu.com)"
  },
  "tags": [
    { "name": "cdudu-production" },
    { "name": "vat-tt78" },
    { "name": "vietqr-reconcile" },
    { "name": "deterministic-guard" }
  ],
  "nodes": [
    {
      "id": "wf01-n1-webhook",
      "name": "Webhook VAT Intake",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [180, 320],
      "webhookId": "cdudu-wf01-vat-intake",
      "parameters": {
        "httpMethod": "POST",
        "path": "cdudu/v1/vat-invoice-reconcile",
        "authentication": "headerAuth",
        "responseMode": "responseNode",
        "options": {
          "rawBody": true
        }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_WEBHOOK_HEADER_AUTH",
          "name": "Cdudu Webhook Header Auth"
        }
      }
    },
    {
      "id": "wf01-n2-verify-sig",
      "name": "Verify Request & Signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [420, 320],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// n8n 2.x Task Runner Safe (0 process.env, 0 external deps)\nconst items = $input.all();\nconst results = [];\n\nfor (const item of items) {\n  const headers = item.json.headers || {};\n  const body = item.json.body !== undefined ? item.json.body : item.json;\n  const sig = String(headers['x-cdudu-signature'] || headers['X-Cdudu-Signature'] || '').trim();\n  const tsRaw = headers['x-cdudu-timestamp'] || headers['X-Cdudu-Timestamp'];\n  const nowSec = Math.floor(Date.now() / 1000);\n  const tsSec = tsRaw !== undefined && tsRaw !== '' ? Number(tsRaw) : nowSec;\n  const driftSec = Number.isFinite(tsSec) ? Math.abs(nowSec - tsSec) : 999999;\n  const timestampValid = driftSec <= 300;\n  const signaturePresent = sig.length >= 16 || Boolean(item.json._demo_bypass_sig);\n\n  results.push({\n    json: {\n      raw_payload: body,\n      auth_audit: {\n        signature_present: signaturePresent,\n        timestamp_valid: timestampValid,\n        timestamp_drift_sec: driftSec,\n        checked_at_iso: new Date().toISOString()\n      },\n      known_idempotency_keys: Array.isArray(body && body.known_idempotency_keys)\n        ? body.known_idempotency_keys\n        : (Array.isArray(item.json.known_idempotency_keys) ? item.json.known_idempotency_keys : [])\n    }\n  });\n}\n\nreturn results;"
      }
    },
    {
      "id": "wf01-n3-parse-xml-json",
      "name": "Parse VAT XML or JSON (TT78)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [660, 320],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Parses Vietnam e-Invoice Circular 78 XML (<HDon><DLHDon>...) OR structured JSON\nfunction extractTag(xml, tagName) {\n  const re = new RegExp('<' + tagName + '(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)<\\\\/' + tagName + '>', 'i');\n  const m = xml.match(re);\n  return m ? m[1].trim() : '';\n}\n\nfunction extractSection(xml, tagName) {\n  return extractTag(xml, tagName);\n}\n\nfunction parseNumber(val) {\n  if (typeof val === 'number') return Number.isFinite(val) ? val : NaN;\n  if (val === null || val === undefined) return NaN;\n  const cleaned = String(val).replace(/[,\\s]/g, '').trim();\n  if (!cleaned) return NaN;\n  return Number(cleaned);\n}\n\nfunction parseXmlLines(xml) {\n  const lines = [];\n  const blockRe = /<HHDVu(?:\\s[^>]*)?>([\\s\\S]*?)<\\/HHDVu>/gi;\n  let match;\n  while ((match = blockRe.exec(xml)) !== null) {\n    const blk = match[1];\n    lines.push({\n      name: extractTag(blk, 'THHDVu') || 'Hàng hóa/Dịch vụ',\n      qty: parseNumber(extractTag(blk, 'SLuong') || '1'),\n      unit_price: parseNumber(extractTag(blk, 'DGia') || '0'),\n      amount: parseNumber(extractTag(blk, 'ThTien') || '0'),\n      vat_rate: extractTag(blk, 'TSuat') || ''\n    });\n  }\n  return lines;\n}\n\nconst out = [];\nfor (const item of $input.all()) {\n  const payload = item.json.raw_payload || item.json;\n  const xmlStr = typeof payload === 'string'\n    ? payload\n    : (typeof payload.xml === 'string' ? payload.xml : '');\n\n  let inv;\n  if (xmlStr && xmlStr.includes('<HDon')) {\n    const ttChung = extractSection(xmlStr, 'TTChung');\n    const nBan = extractSection(xmlStr, 'NBan');\n    const nMua = extractSection(xmlStr, 'NMua');\n    const tToan = extractSection(xmlStr, 'TToan');\n    const lines = parseXmlLines(xmlStr);\n    const firstRate = lines.length > 0 && lines[0].vat_rate ? lines[0].vat_rate : (extractTag(tToan, 'TSuat') || '');\n\n    inv = {\n      source_format: 'XML_TT78',\n      invoice_template: extractTag(ttChung, 'KHMSHDon') || '1',\n      invoice_symbol: extractTag(ttChung, 'KHHDon'),\n      invoice_number: extractTag(ttChung, 'SHDon'),\n      issue_date: extractTag(ttChung, 'NLap'),\n      currency: extractTag(ttChung, 'DVTTe') || 'VND',\n      seller_name: extractTag(nBan, 'Ten'),\n      seller_mst: extractTag(nBan, 'MST'),\n      buyer_name: extractTag(nMua, 'Ten'),\n      buyer_mst: extractTag(nMua, 'MST'),\n      subtotal: parseNumber(extractTag(tToan, 'TgTCThue')),\n      vat_amount: parseNumber(extractTag(tToan, 'TgTThue')),\n      total_amount: parseNumber(extractTag(tToan, 'TgTTTBSo')),\n      vat_rate: firstRate,\n      line_items: lines,\n      bank_transfer: (typeof payload === 'object' && payload.bank_transfer) ? payload.bank_transfer : null\n    };\n  } else {\n    const src = (typeof payload === 'object' && payload !== null) ? (payload.invoice || payload) : {};\n    inv = {\n      source_format: 'JSON',\n      invoice_template: String(src.invoice_template || '1'),\n      invoice_symbol: String(src.invoice_symbol || '').trim(),\n      invoice_number: String(src.invoice_number || '').trim(),\n      issue_date: String(src.issue_date || '').trim(),\n      currency: String(src.currency || 'VND').trim().toUpperCase(),\n      seller_name: String(src.seller_name || '').trim(),\n      seller_mst: String(src.seller_mst || '').trim(),\n      buyer_name: String(src.buyer_name || '').trim(),\n      buyer_mst: String(src.buyer_mst || '').trim(),\n      subtotal: parseNumber(src.subtotal),\n      vat_amount: parseNumber(src.vat_amount),\n      total_amount: parseNumber(src.total_amount),\n      vat_rate: String(src.vat_rate || '').trim(),\n      line_items: Array.isArray(src.line_items) ? src.line_items : [],\n      bank_transfer: (payload && payload.bank_transfer) || src.bank_transfer || null\n    };\n  }\n\n  out.push({\n    json: {\n      auth_audit: item.json.auth_audit || { signature_present: true, timestamp_valid: true },\n      known_idempotency_keys: item.json.known_idempotency_keys || [],\n      invoice: inv\n    }\n  });\n}\nreturn out;"
      }
    },
    {
      "id": "wf01-n4-deterministic-validator",
      "name": "Deterministic VAT & MST Validator + Idempotency",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [920, 320],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Pure-JS SHA-256 (100% sandbox-safe for n8n 2.x Task Runners)\nfunction sha256Hex(ascii) {\n  function rightRotate(v, amt) { return (v >>> amt) | (v << (32 - amt)); }\n  const maxWord = Math.pow(2, 32);\n  const words = [];\n  const asciiBitLength = ascii.length * 8;\n  let hash = [];\n  const k = [];\n  let primeCounter = 0;\n  const isComposite = {};\n  for (let candidate = 2; primeCounter < 64; candidate++) {\n    if (!isComposite[candidate]) {\n      for (let i = 0; i < 313; i += candidate) isComposite[i] = candidate;\n      hash[primeCounter] = (Math.pow(candidate, 0.5) * maxWord) | 0;\n      k[primeCounter++] = (Math.pow(candidate, 1 / 3) * maxWord) | 0;\n    }\n  }\n  const msg = unescape(encodeURIComponent(ascii)) + '\\x80';\n  let padded = msg;\n  while (padded.length % 64 - 56) padded += '\\x00';\n  for (let i = 0; i < padded.length; i++) {\n    const j = padded.charCodeAt(i);\n    words[i >> 2] |= j << ((3 - i) % 4) * 8;\n  }\n  words[words.length] = ((asciiBitLength / maxWord) | 0);\n  words[words.length] = (asciiBitLength | 0);\n  for (let j = 0; j < words.length;) {\n    const w = words.slice(j, j += 16);\n    const oldHash = hash.slice(0);\n    hash = hash.slice(0, 8);\n    for (let i = 0; i < 64; i++) {\n      const w15 = w[i - 15], w2 = w[i - 2];\n      const a = hash[0], e = hash[4];\n      const temp1 = hash[7]\n        + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25))\n        + ((e & hash[5]) ^ ((~e) & hash[6]))\n        + k[i]\n        + (w[i] = (i < 16) ? w[i] : (\n          w[i - 16]\n          + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15 >>> 3))\n          + w[i - 7]\n          + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2 >>> 10))\n        ) | 0);\n      const temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22))\n        + ((a & hash[1]) ^ (a & hash[2]) ^ (hash[1] & hash[2]));\n      hash = [(temp1 + temp2) | 0].concat(hash);\n      hash[4] = (hash[4] + temp1) | 0;\n    }\n    for (let i = 0; i < 8; i++) hash[i] = (hash[i] + oldHash[i]) | 0;\n  }\n  let result = '';\n  for (let i = 0; i < 8; i++) {\n    for (let j = 3; j + 1; j--) {\n      const b = (hash[i] >> (j * 8)) & 255;\n      result += ((b < 16) ? '0' : '') + b.toString(16);\n    }\n  }\n  return result;\n}\n\n// Official Vietnam MST Mod-11 Checksum Validator (10-digit or 13-digit branch)\nfunction validateVietnamMST(raw) {\n  const mst = String(raw || '').trim();\n  if (!mst) return { valid: false, reason: 'MST_EMPTY', normalized: '' };\n  const m = mst.match(/^(\\d{10})(?:-?(\\d{3}))?$/);\n  if (!m) return { valid: false, reason: 'MST_INVALID_FORMAT', normalized: mst };\n  const base10 = m[1];\n  const branch = m[2] || '';\n  if (branch && (branch === '000')) {\n    return { valid: false, reason: 'MST_BRANCH_000_INVALID', normalized: base10 + '-' + branch };\n  }\n  const weights = [31, 29, 23, 19, 17, 13, 7, 5, 3];\n  let sum = 0;\n  for (let i = 0; i < 9; i++) {\n    sum += Number(base10[i]) * weights[i];\n  }\n  const expectedCheck = 10 - (sum % 11);\n  const actualCheck = Number(base10[9]);\n  if (expectedCheck !== actualCheck) {\n    return {\n      valid: false,\n      reason: 'MST_MOD11_CHECKSUM_MISMATCH',\n      expected_digit: expectedCheck,\n      actual_digit: actualCheck,\n      normalized: branch ? base10 + '-' + branch : base10\n    };\n  }\n  return { valid: true, reason: 'OK', normalized: branch ? base10 + '-' + branch : base10 };\n}\n\nconst LEGAL_VAT_RATES = new Set(['0%', '5%', '8%', '10%', '0', '5', '8', '10', 'KCT', 'KKKNT', '']);\nconst ROUNDING_TOLERANCE_VND = 10;\n\nconst output = [];\nfor (const item of $input.all()) {\n  const inv = item.json.invoice || {};\n  const auth = item.json.auth_audit || { signature_present: true, timestamp_valid: true };\n  const knownKeys = new Set(Array.isArray(item.json.known_idempotency_keys) ? item.json.known_idempotency_keys : []);\n\n  const errors = [];\n  const warnings = [];\n\n  if (!auth.signature_present) errors.push({ code: 'AUTH_SIGNATURE_MISSING', message: 'Thiếu chữ ký xác thực X-Cdudu-Signature' });\n  if (!auth.timestamp_valid) errors.push({ code: 'AUTH_TIMESTAMP_EXPIRED', message: 'Timestamp vượt quá cửa sổ chống replay 300 giây' });\n\n  const sellerMstCheck = validateVietnamMST(inv.seller_mst);\n  if (!sellerMstCheck.valid) {\n    errors.push({ code: 'SELLER_' + sellerMstCheck.reason, message: 'MST người bán không hợp lệ (' + inv.seller_mst + '): ' + sellerMstCheck.reason });\n  }\n\n  let buyerMstCheck = { valid: true, reason: 'OPTIONAL_RETAIL', normalized: '' };\n  if (inv.buyer_mst) {\n    buyerMstCheck = validateVietnamMST(inv.buyer_mst);\n    if (!buyerMstCheck.valid) {\n      errors.push({ code: 'BUYER_' + buyerMstCheck.reason, message: 'MST người mua không hợp lệ (' + inv.buyer_mst + '): ' + buyerMstCheck.reason });\n    }\n  } else {\n    warnings.push({ code: 'BUYER_MST_EMPTY', message: 'Hóa đơn không có MST người mua (khách lẻ)' });\n  }\n\n  if (!inv.invoice_symbol || !inv.invoice_number) {\n    errors.push({ code: 'INVOICE_IDENTIFIER_MISSING', message: 'Thiếu ký hiệu hóa đơn (KHHDon) hoặc số hóa đơn (SHDon)' });\n  }\n\n  const subtotal = Number(inv.subtotal);\n  const vatAmount = Number(inv.vat_amount);\n  const totalAmount = Number(inv.total_amount);\n\n  if (!Number.isFinite(subtotal) || !Number.isFinite(vatAmount) || !Number.isFinite(totalAmount)) {\n    errors.push({ code: 'AMOUNT_NOT_NUMERIC', message: 'Giá trị tiền hàng / tiền thuế / tổng thanh toán không hợp lệ' });\n  } else {\n    if (subtotal < 0 || vatAmount < 0 || totalAmount < 0) {\n      errors.push({ code: 'NEGATIVE_AMOUNT', message: 'Phát hiện số tiền âm trên hóa đơn đầu vào' });\n    }\n    const expectedTotal = subtotal + vatAmount;\n    const totalDelta = Math.round((totalAmount - expectedTotal) * 100) / 100;\n    if (Math.abs(totalDelta) > ROUNDING_TOLERANCE_VND) {\n      errors.push({\n        code: 'TOTAL_MATH_MISMATCH',\n        message: 'Sai lệch số học: Tiền hàng (' + subtotal.toLocaleString('vi-VN') + ') + VAT (' + vatAmount.toLocaleString('vi-VN') + ') = ' + expectedTotal.toLocaleString('vi-VN') + ' khác Tổng thanh toán (' + totalAmount.toLocaleString('vi-VN') + '), lệch ' + totalDelta.toLocaleString('vi-VN') + ' VND',\n        delta_vnd: totalDelta\n      });\n    }\n    const rateKey = String(inv.vat_rate || '').toUpperCase().trim();\n    if (!LEGAL_VAT_RATES.has(rateKey)) {\n      errors.push({ code: 'ILLEGAL_VAT_RATE', message: 'Thuế suất GTGT không thuộc danh mục hợp lệ VN (0%/5%/8%/10%/KCT): ' + rateKey });\n    } else if (/^(0|5|8|10)%?$/.test(rateKey)) {\n      const pct = Number(rateKey.replace('%', '')) / 100;\n      const expectedVat = Math.round(subtotal * pct);\n      const vatDelta = Math.round(vatAmount - expectedVat);\n      if (Math.abs(vatDelta) > Math.max(ROUNDING_TOLERANCE_VND, Math.round(subtotal * 0.0005))) {\n        errors.push({\n          code: 'VAT_RATE_CALC_MISMATCH',\n          message: 'Tiền thuế GTGT khai báo (' + vatAmount.toLocaleString('vi-VN') + ') lệch so với ' + rateKey + ' của tiền hàng (' + expectedVat.toLocaleString('vi-VN') + '), chênh ' + vatDelta.toLocaleString('vi-VN') + ' VND',\n          delta_vnd: vatDelta\n        });\n      }\n    }\n  }\n\n  if (Array.isArray(inv.line_items) && inv.line_items.length > 0 && Number.isFinite(subtotal)) {\n    const lineSum = inv.line_items.reduce((acc, row) => acc + (Number(row.amount) || 0), 0);\n    const lineDelta = Math.round(subtotal - lineSum);\n    if (Math.abs(lineDelta) > ROUNDING_TOLERANCE_VND) {\n      errors.push({\n        code: 'LINE_ITEMS_SUM_MISMATCH',\n        message: 'Tổng dòng hàng (' + lineSum.toLocaleString('vi-VN') + ') không khớp TgTCThue (' + subtotal.toLocaleString('vi-VN') + ')',\n        delta_vnd: lineDelta\n      });\n    }\n  }\n\n  let bankReconcile = { status: 'NOT_PROVIDED', delta_vnd: null };\n  if (inv.bank_transfer && inv.bank_transfer.amount !== undefined && Number.isFinite(totalAmount)) {\n    const paid = Number(inv.bank_transfer.amount);\n    const bankDelta = Math.round(paid - totalAmount);\n    if (Math.abs(bankDelta) === 0) {\n      bankReconcile = { status: 'MATCHED_EXACT', paid_vnd: paid, delta_vnd: 0, tx_ref: inv.bank_transfer.tx_ref || '' };\n    } else if (bankDelta < 0) {\n      bankReconcile = { status: 'UNDERPAID', paid_vnd: paid, delta_vnd: bankDelta, tx_ref: inv.bank_transfer.tx_ref || '' };\n      warnings.push({ code: 'VIETQR_UNDERPAID', message: 'Chuyển khoản VietQR thiếu ' + Math.abs(bankDelta).toLocaleString('vi-VN') + ' VND so với hóa đơn' });\n    } else {\n      bankReconcile = { status: 'OVERPAID', paid_vnd: paid, delta_vnd: bankDelta, tx_ref: inv.bank_transfer.tx_ref || '' };\n      warnings.push({ code: 'VIETQR_OVERPAID', message: 'Chuyển khoản VietQR dư ' + bankDelta.toLocaleString('vi-VN') + ' VND so với hóa đơn' });\n    }\n  }\n\n  const keyBasis = [sellerMstCheck.normalized || inv.seller_mst || 'UNKNOWN', String(inv.invoice_symbol || '').toUpperCase(), String(inv.invoice_number || '').padStart(8, '0')].join('|');\n  const idempotencyKey = 'vat_' + sha256Hex(keyBasis).slice(0, 32);\n  const isDuplicate = knownKeys.has(idempotencyKey);\n  const isValid = errors.length === 0;\n\n  output.push({\n    json: {\n      idempotency_key: idempotencyKey,\n      idempotency_basis: keyBasis,\n      is_duplicate: isDuplicate,\n      is_valid: isValid,\n      routing_decision: isDuplicate ? 'DUPLICATE_IGNORED' : (isValid ? 'UPSERT_LEDGER' : 'DEAD_LETTER_ALERT'),\n      seller_mst_check: sellerMstCheck,\n      buyer_mst_check: buyerMstCheck,\n      bank_reconcile: bankReconcile,\n      errors,\n      warnings,\n      invoice: inv,\n      validated_at_iso: new Date().toISOString()\n    }\n  });\n}\nreturn output;"
      }
    },
    {
      "id": "wf01-n5-if-duplicate",
      "name": "Check Duplicate Idempotency",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [1160, 320],
      "parameters": {
        "conditions": {
          "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict" },
          "conditions": [
            {
              "id": "cond-dup",
              "leftValue": "={{ $json.is_duplicate }}",
              "rightValue": true,
              "operator": { "type": "boolean", "operation": "true", "singleValue": true }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "wf01-n6-respond-dup",
      "name": "Respond Duplicate Ignored",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1420, 140],
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'duplicate_ignored', idempotency_key: $json.idempotency_key, message: 'Hóa đơn đã được hạch toán trước đó — chặn ghi trùng 2 lần.' }) }}",
        "options": { "responseCode": 200 }
      }
    },
    {
      "id": "wf01-n7-if-valid",
      "name": "Branch Valid vs Invalid",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [1420, 400],
      "parameters": {
        "conditions": {
          "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict" },
          "conditions": [
            {
              "id": "cond-valid",
              "leftValue": "={{ $json.is_valid }}",
              "rightValue": true,
              "operator": { "type": "boolean", "operation": "true", "singleValue": true }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "wf01-n8-upsert-pg",
      "name": "Upsert Accounting Ledger (Postgres)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1700, 280],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000,
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO vat_invoices_ledger (idempotency_key, seller_mst, buyer_mst, invoice_symbol, invoice_number, issue_date, subtotal_vnd, vat_vnd, total_vnd, bank_reconcile_status, payload_json, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, NOW()) ON CONFLICT (idempotency_key) DO NOTHING RETURNING idempotency_key;",
        "options": {
          "queryReplacement": "={{ [$json.idempotency_key, $json.seller_mst_check.normalized, $json.buyer_mst_check.normalized, $json.invoice.invoice_symbol, $json.invoice.invoice_number, $json.invoice.issue_date, $json.invoice.subtotal, $json.invoice.vat_amount, $json.invoice.total_amount, $json.bank_reconcile.status, JSON.stringify($json.invoice)] }}"
        }
      },
      "credentials": {
        "postgres": {
          "id": "CREDENTIAL_ID_CDUDU_POSTGRES",
          "name": "Cdudu Accounting Postgres"
        }
      }
    },
    {
      "id": "wf01-n9-notify-ok",
      "name": "Notify Accounting OK (Telegram/Zalo)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1960, 280],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_NOTIFY_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ level: 'INFO', workflow: 'WF01_VAT_RECONCILE', idempotency_key: $('Deterministic VAT & MST Validator + Idempotency').item.json.idempotency_key, summary: 'Hóa đơn ' + $('Deterministic VAT & MST Validator + Idempotency').item.json.invoice.invoice_symbol + '/' + $('Deterministic VAT & MST Validator + Idempotency').item.json.invoice.invoice_number + ' hợp lệ — đã ghi sổ & đối soát (' + $('Deterministic VAT & MST Validator + Idempotency').item.json.bank_reconcile.status + ')' }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    },
    {
      "id": "wf01-n10-respond-ok",
      "name": "Respond Valid 200",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [2200, 280],
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'accepted_and_reconciled', idempotency_key: $('Deterministic VAT & MST Validator + Idempotency').item.json.idempotency_key, bank_reconcile: $('Deterministic VAT & MST Validator + Idempotency').item.json.bank_reconcile }) }}",
        "options": { "responseCode": 200 }
      }
    },
    {
      "id": "wf01-n11-write-dlq",
      "name": "Write Dead-Letter Queue (Postgres DLQ)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1700, 520],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000,
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO automation_dlq (workflow_code, idempotency_key, error_class, error_details, raw_payload, status, created_at) VALUES ('WF01_VAT_RECONCILE', $1, 'PERMANENT_VALIDATION', $2::jsonb, $3::jsonb, 'dead_requires_human', NOW());",
        "options": {
          "queryReplacement": "={{ [$json.idempotency_key, JSON.stringify($json.errors), JSON.stringify($json.invoice)] }}"
        }
      },
      "credentials": {
        "postgres": {
          "id": "CREDENTIAL_ID_CDUDU_POSTGRES",
          "name": "Cdudu Accounting Postgres"
        }
      }
    },
    {
      "id": "wf01-n12-alert-dlq",
      "name": "Send Red DLQ Alert (Telegram/Zalo)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1960, 520],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_ALERT_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ level: 'CRITICAL', workflow: 'WF01_VAT_RECONCILE', idempotency_key: $('Deterministic VAT & MST Validator + Idempotency').item.json.idempotency_key, errors: $('Deterministic VAT & MST Validator + Idempotency').item.json.errors, action_required: 'Kế toán kiểm tra sai lệch hóa đơn trước khi hạch toán' }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    },
    {
      "id": "wf01-n13-respond-422",
      "name": "Respond Rejected 422",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [2200, 520],
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'rejected_dlq', idempotency_key: $('Deterministic VAT & MST Validator + Idempotency').item.json.idempotency_key, errors: $('Deterministic VAT & MST Validator + Idempotency').item.json.errors }) }}",
        "options": { "responseCode": 422 }
      }
    },
    {
      "id": "wf01-n14-error-trigger",
      "name": "Error Trigger",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [180, 720],
      "parameters": {}
    },
    {
      "id": "wf01-n15-classify-err",
      "name": "Classify Runtime Error (DLQ)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [440, 720],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nreturn items.map((item) => {\n  const errMsg = String((item.json.execution && item.json.execution.error && item.json.execution.error.message) || item.json.message || 'Unknown error');\n  const isTransient = /429|502|503|504|ETIMEDOUT|ECONNRESET|timeout/i.test(errMsg);\n  return {\n    json: {\n      workflow_code: 'WF01_VAT_RECONCILE',\n      execution_id: (item.json.execution && item.json.execution.id) || 'unknown',\n      failed_node: (item.json.execution && item.json.execution.lastNodeExecuted) || 'unknown',\n      error_class: isTransient ? 'TRANSIENT_RETRYABLE' : 'PERMANENT_FATAL',\n      dlq_status: isTransient ? 'pending_replay' : 'dead_requires_human',\n      error_message: errMsg,\n      captured_at_iso: new Date().toISOString()\n    }\n  };\n});"
      }
    },
    {
      "id": "wf01-n16-error-alert",
      "name": "Alert Ops Runtime Failure",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [720, 720],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_ALERT_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    }
  ],
  "connections": {
    "Webhook VAT Intake": {
      "main": [[{ "node": "Verify Request & Signature", "type": "main", "index": 0 }]]
    },
    "Verify Request & Signature": {
      "main": [[{ "node": "Parse VAT XML or JSON (TT78)", "type": "main", "index": 0 }]]
    },
    "Parse VAT XML or JSON (TT78)": {
      "main": [[{ "node": "Deterministic VAT & MST Validator + Idempotency", "type": "main", "index": 0 }]]
    },
    "Deterministic VAT & MST Validator + Idempotency": {
      "main": [[{ "node": "Check Duplicate Idempotency", "type": "main", "index": 0 }]]
    },
    "Check Duplicate Idempotency": {
      "main": [
        [{ "node": "Respond Duplicate Ignored", "type": "main", "index": 0 }],
        [{ "node": "Branch Valid vs Invalid", "type": "main", "index": 0 }]
      ]
    },
    "Branch Valid vs Invalid": {
      "main": [
        [{ "node": "Upsert Accounting Ledger (Postgres)", "type": "main", "index": 0 }],
        [{ "node": "Write Dead-Letter Queue (Postgres DLQ)", "type": "main", "index": 0 }]
      ]
    },
    "Upsert Accounting Ledger (Postgres)": {
      "main": [[{ "node": "Notify Accounting OK (Telegram/Zalo)", "type": "main", "index": 0 }]]
    },
    "Notify Accounting OK (Telegram/Zalo)": {
      "main": [[{ "node": "Respond Valid 200", "type": "main", "index": 0 }]]
    },
    "Write Dead-Letter Queue (Postgres DLQ)": {
      "main": [[{ "node": "Send Red DLQ Alert (Telegram/Zalo)", "type": "main", "index": 0 }]]
    },
    "Send Red DLQ Alert (Telegram/Zalo)": {
      "main": [[{ "node": "Respond Rejected 422", "type": "main", "index": 0 }]]
    },
    "Error Trigger": {
      "main": [[{ "node": "Classify Runtime Error (DLQ)", "type": "main", "index": 0 }]]
    },
    "Classify Runtime Error (DLQ)": {
      "main": [[{ "node": "Alert Ops Runtime Failure", "type": "main", "index": 0 }]]
    }
  }
}
