{
  "name": "CDUDU WF03 — Daily CEO KPI Digest (08:00 & 18:00 ICT) Revenue, Overdue AR & SLA",
  "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-wf03-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": "ceo-kpi-digest" },
    { "name": "cron-08-18-ict" }
  ],
  "nodes": [
    {
      "id": "wf03-n1-cron",
      "name": "Cron 08:00 & 18:00 ICT",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [180, 320],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 8,18 * * *"
            }
          ]
        }
      }
    },
    {
      "id": "wf03-n2-query-rev",
      "name": "Query Revenue & Cashflow (Postgres)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [460, 220],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000,
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT COALESCE(SUM(total_vnd) FILTER (WHERE created_at::date = (NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh')::date), 0) AS today_invoiced_vnd, COALESCE(SUM(total_vnd) FILTER (WHERE bank_reconcile_status = 'MATCHED_EXACT' AND created_at::date = (NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh')::date), 0) AS today_collected_vnd, COUNT(*) FILTER (WHERE created_at::date = (NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh')::date) AS today_invoices_count FROM vat_invoices_ledger;"
      },
      "credentials": {
        "postgres": {
          "id": "CREDENTIAL_ID_CDUDU_POSTGRES",
          "name": "Cdudu Analytics Postgres"
        }
      }
    },
    {
      "id": "wf03-n3-query-ar-sla",
      "name": "Query Overdue AR & Pending SLA (Postgres)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [460, 440],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000,
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT COALESCE((SELECT SUM(total_vnd) FROM vat_invoices_ledger WHERE bank_reconcile_status <> 'MATCHED_EXACT' AND created_at < NOW() - INTERVAL '7 days'), 0) AS overdue_ar_vnd, COALESCE((SELECT COUNT(*) FROM crm_leads_sla WHERE first_response_at IS NULL AND created_at < NOW() - INTERVAL '15 minutes'), 0) AS pending_sla_leads, COALESCE((SELECT COUNT(*) FROM crm_leads_sla WHERE created_at::date = (NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh')::date), 0) AS today_total_leads, COALESCE((SELECT COUNT(*) FROM automation_dlq WHERE status = 'dead_requires_human'), 0) AS open_dlq_alerts;"
      },
      "credentials": {
        "postgres": {
          "id": "CREDENTIAL_ID_CDUDU_POSTGRES",
          "name": "Cdudu Analytics Postgres"
        }
      }
    },
    {
      "id": "wf03-n4-merge",
      "name": "Merge KPI Streams",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [740, 320],
      "parameters": {
        "mode": "combine",
        "combineBy": "combineByPosition",
        "options": {}
      }
    },
    {
      "id": "wf03-n5-format-digest",
      "name": "Build 1-Page Executive KPI Digest",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1000, 320],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "function fmtVnd(n) {\n  return Math.round(Number(n || 0)).toLocaleString('vi-VN') + 'đ';\n}\n\nconst out = [];\nfor (const item of $input.all()) {\n  const d = item.json;\n  const invoiced = Number(d.today_invoiced_vnd || 0);\n  const collected = Number(d.today_collected_vnd || 0);\n  const invoicesCount = Number(d.today_invoices_count || 0);\n  const overdueAr = Number(d.overdue_ar_vnd || 0);\n  const pendingSla = Number(d.pending_sla_leads || 0);\n  const totalLeads = Number(d.today_total_leads || 0);\n  const openDlq = Number(d.open_dlq_alerts || 0);\n\n  const collectionRatePct = invoiced > 0 ? Math.round((collected / invoiced) * 1000) / 10 : 100;\n  const slaCompliancePct = totalLeads > 0 ? Math.round(((Math.max(0, totalLeads - pendingSla)) / totalLeads) * 1000) / 10 : 100;\n\n  const anomalies = [];\n  if (overdueAr > 0) anomalies.push('CONG_NO_QUA_HAN_7_NGAY: ' + fmtVnd(overdueAr));\n  if (pendingSla > 0) anomalies.push('LEAD_QUA_HAN_SLA_15P: ' + pendingSla + ' khách hàng chưa phản hồi');\n  if (openDlq > 0) anomalies.push('HOA_DON_LOI_CHO_DUYET_DLQ: ' + openDlq + ' hồ sơ');\n\n  const nowIct = new Date().toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' });\n  const statusBadge = anomalies.length === 0 ? 'ỔN ĐỊNH' : 'CẦN XỬ LÝ (' + anomalies.length + ' cảnh báo)';\n\n  const markdown = [\n    'BÁO CÁO KPI ĐIỀU HÀNH 1 TRANG — ' + nowIct,\n    'Trạng thái tổng thể: ' + statusBadge,\n    '-----------------------------------------',\n    '1. Doanh thu xuất hóa đơn hôm nay: ' + fmtVnd(invoiced) + ' (' + invoicesCount + ' hóa đơn)',\n    '2. Tiền thực thu đối soát VietQR: ' + fmtVnd(collected) + ' (Tỷ lệ thu: ' + collectionRatePct + '%)',\n    '3. Công nợ quá hạn > 7 ngày: ' + fmtVnd(overdueAr),\n    '4. Lead mới hôm nay: ' + totalLeads + ' | Đạt SLA 15p: ' + slaCompliancePct + '% | Tồn quá hạn: ' + pendingSla,\n    '5. Hồ sơ lỗi đang chờ kế toán duyệt (DLQ): ' + openDlq,\n    '-----------------------------------------',\n    anomalies.length > 0 ? ('CẢNH BÁO CẦN SẾP LƯU Ý:\\n- ' + anomalies.join('\\n- ')) : 'Không có cảnh báo bất thường trong kỳ báo cáo.'\n  ].join('\\n');\n\n  out.push({\n    json: {\n      generated_at_ict: nowIct,\n      status_badge: statusBadge,\n      metrics: {\n        today_invoiced_vnd: invoiced,\n        today_collected_vnd: collected,\n        today_invoices_count: invoicesCount,\n        collection_rate_pct: collectionRatePct,\n        overdue_ar_vnd: overdueAr,\n        today_total_leads: totalLeads,\n        pending_sla_leads: pendingSla,\n        sla_compliance_pct: slaCompliancePct,\n        open_dlq_alerts: openDlq\n      },\n      anomalies,\n      digest_text: markdown\n    }\n  });\n}\nreturn out;"
      }
    },
    {
      "id": "wf03-n6-send-chat",
      "name": "Send CEO Digest (Zalo/Telegram)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1280, 220],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_CEO_DIGEST_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ channel: 'executive_digest', text: $json.digest_text, status_badge: $json.status_badge, metrics: $json.metrics }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    },
    {
      "id": "wf03-n7-send-email",
      "name": "Send CEO Digest Email",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1280, 420],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_EMAIL_GATEWAY_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ subject: '[KPI Điều Hành] ' + $json.status_badge + ' — ' + $json.generated_at_ict, text: $json.digest_text }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_EMAIL_AUTH",
          "name": "Cdudu Email Gateway Auth"
        }
      }
    },
    {
      "id": "wf03-n8-error-trigger",
      "name": "Error Trigger",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [180, 660],
      "parameters": {}
    },
    {
      "id": "wf03-n9-error-alert",
      "name": "Alert KPI Digest Failure",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [460, 660],
      "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: 'WF03_CEO_KPI_DIGEST', error: $json.execution && $json.execution.error ? $json.execution.error.message : 'Unknown error' }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    }
  ],
  "connections": {
    "Cron 08:00 & 18:00 ICT": {
      "main": [[
        { "node": "Query Revenue & Cashflow (Postgres)", "type": "main", "index": 0 },
        { "node": "Query Overdue AR & Pending SLA (Postgres)", "type": "main", "index": 0 }
      ]]
    },
    "Query Revenue & Cashflow (Postgres)": {
      "main": [[{ "node": "Merge KPI Streams", "type": "main", "index": 0 }]]
    },
    "Query Overdue AR & Pending SLA (Postgres)": {
      "main": [[{ "node": "Merge KPI Streams", "type": "main", "index": 1 }]]
    },
    "Merge KPI Streams": {
      "main": [[{ "node": "Build 1-Page Executive KPI Digest", "type": "main", "index": 0 }]]
    },
    "Build 1-Page Executive KPI Digest": {
      "main": [[
        { "node": "Send CEO Digest (Zalo/Telegram)", "type": "main", "index": 0 },
        { "node": "Send CEO Digest Email", "type": "main", "index": 0 }
      ]]
    },
    "Error Trigger": {
      "main": [[{ "node": "Alert KPI Digest Failure", "type": "main", "index": 0 }]]
    }
  }
}
