{
  "id": "CODWF04DailyDigest",
  "name": "COD · WF-04 Daily Closing Digest",
  "active": false,
  "nodes": [
    {
      "parameters": {
        "content": "## Layer 4 · Daily Closing Digest\nAt 23:59 Cairo time, fetch the system-of-record report, format one bilingual-ready executive digest, and deliver it to the admin Telegram group and owner email.",
        "height": 210,
        "width": 1100,
        "color": 5
      },
      "id": "wf04-note",
      "name": "Layer 4 · Daily Digest",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -660,
        -300
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "59 23 * * *"
            }
          ]
        }
      },
      "id": "wf04-schedule",
      "name": "Daily 23:59 Cairo Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -600,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "wf04-manual",
      "name": "Manual Digest Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -600,
        80
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "test-digest",
        "authentication": "none",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "wf04-test",
      "name": "Test Digest Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -600,
        200
      ],
      "webhookId": "cod-test-digest-v1"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "wf04-enabled",
              "leftValue": "={{ $env.ENABLE_TEST_HOOKS }}",
              "rightValue": "true",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "wf04-key",
              "leftValue": "={{ $json.headers['x-api-key'] || '' }}",
              "rightValue": "={{ $env.ORDER_WEBHOOK_KEY }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "wf04-gate",
      "name": "Digest Test Hook Enabled?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        -380,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { accepted: true } }}",
        "options": {
          "responseCode": 202
        }
      },
      "id": "wf04-accepted",
      "name": "Respond Digest Accepted",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [
        -160,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { error: 'NOT_FOUND' } }}",
        "options": {
          "responseCode": 404
        }
      },
      "id": "wf04-disabled",
      "name": "Respond Digest Unavailable",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [
        -160,
        420
      ]
    },
    {
      "parameters": {
        "url": "={{ $env.INTERNAL_API_URL }}/api/internal/reports/daily",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "date",
              "value": "={{ $now.setZone('Africa/Cairo').toFormat('yyyy-MM-dd') }}"
            }
          ]
        },
        "options": {
          "timeout": 10000
        }
      },
      "id": "wf04-report",
      "name": "Fetch Daily Report",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -120,
        20
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "credentials": {
        "httpHeaderAuth": {
          "id": "cred_internal_api",
          "name": "COD Internal API Bearer"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "let __smartCodRun;\n(() => {\n  // n8n/code/digest.ts\n  function money(value, currency) {\n    return `${Number(value).toFixed(2)} ${currency}`;\n  }\n  function formatDigest(report, language = \"ar\") {\n    const currency = report.currency ?? \"EGP\";\n    const lowStock = report.lowStock.length ? report.lowStock.map((product) => `${product.sku} (${product.available})`).join(\", \") : language === \"ar\" ? \"\\u0644\\u0627 \\u064A\\u0648\\u062C\\u062F\" : \"None\";\n    if (language === \"en\") {\n      return [\n        `\\u{1F4CA} DAILY CLOSING DIGEST (${report.date})`,\n        `Total Orders: ${report.totalOrders}`,\n        `Confirmed: ${report.confirmedOrders} (${report.confirmationRate.toFixed(1)}%)`,\n        `Total Revenue: ${money(report.totalCod, currency)}`,\n        `Blocked: ${report.blockedOrders}`,\n        `Money Saved: ${money(report.moneySaved, currency)}`,\n        `Low Stock: ${lowStock}`\n      ].join(\"\\n\");\n    }\n    return [\n      `\\u{1F4CA} \\u0645\\u0644\\u062E\\u0635 \\u0627\\u0644\\u0625\\u063A\\u0644\\u0627\\u0642 \\u0627\\u0644\\u064A\\u0648\\u0645\\u064A (${report.date})`,\n      `\\u0625\\u062C\\u0645\\u0627\\u0644\\u064A \\u0627\\u0644\\u0637\\u0644\\u0628\\u0627\\u062A: ${report.totalOrders}`,\n      `\\u0627\\u0644\\u0645\\u0624\\u0643\\u062F\\u0629: ${report.confirmedOrders} (${report.confirmationRate.toFixed(1)}\\u066A)`,\n      `\\u0625\\u062C\\u0645\\u0627\\u0644\\u064A \\u0627\\u0644\\u0625\\u064A\\u0631\\u0627\\u062F: ${money(report.totalCod, currency)}`,\n      `\\u0627\\u0644\\u0645\\u062D\\u0638\\u0648\\u0631\\u0629: ${report.blockedOrders}`,\n      `\\u0627\\u0644\\u0648\\u0641\\u0648\\u0631\\u0627\\u062A: ${money(report.moneySaved, currency)}`,\n      `\\u0645\\u062E\\u0632\\u0648\\u0646 \\u0645\\u0646\\u062E\\u0641\\u0636: ${lowStock}`\n    ].join(\"\\n\");\n  }\n  function run(items) {\n    return items.map((item) => {\n      const language = item.json.language === \"en\" ? \"en\" : \"ar\";\n      return { ...item, json: { ...item.json, digest: formatDigest(item.json, language) } };\n    });\n  }\n\n  // digest.bundle-entry.ts\n  __smartCodRun = run;\n})();\nreturn __smartCodRun($input.all(), { now: new Date().toISOString() });"
      },
      "id": "wf04-format",
      "name": "Format Executive Digest",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        120,
        20
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "wf04-audience",
              "name": "audience",
              "value": "admin",
              "type": "string"
            },
            {
              "id": "wf04-channel",
              "name": "channel",
              "value": "auto",
              "type": "string"
            },
            {
              "id": "wf04-template",
              "name": "template",
              "value": "daily_digest",
              "type": "string"
            },
            {
              "id": "wf04-language",
              "name": "language",
              "value": "ar",
              "type": "string"
            },
            {
              "id": "wf04-vars",
              "name": "vars",
              "value": "={{ { date: $json.date, digest: $json.digest } }}",
              "type": "object"
            }
          ]
        },
        "options": {}
      },
      "id": "wf04-payload",
      "name": "Prepare Admin Digest Delivery",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        360,
        20
      ]
    },
    {
      "parameters": {
        "workflowId": {
          "__rl": true,
          "value": "CODWF00SendNotification",
          "mode": "id"
        },
        "mode": "once",
        "options": {
          "waitForSubWorkflow": true
        }
      },
      "id": "wf04-send",
      "name": "Send Digest Telegram + Email",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        20
      ]
    }
  ],
  "connections": {
    "Daily 23:59 Cairo Trigger": {
      "main": [
        [
          {
            "node": "Fetch Daily Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Manual Digest Trigger": {
      "main": [
        [
          {
            "node": "Fetch Daily Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Test Digest Webhook": {
      "main": [
        [
          {
            "node": "Digest Test Hook Enabled?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Digest Test Hook Enabled?": {
      "main": [
        [
          {
            "node": "Fetch Daily Report",
            "type": "main",
            "index": 0
          },
          {
            "node": "Respond Digest Accepted",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond Digest Unavailable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Daily Report": {
      "main": [
        [
          {
            "node": "Format Executive Digest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Executive Digest": {
      "main": [
        [
          {
            "node": "Prepare Admin Digest Delivery",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Admin Digest Delivery": {
      "main": [
        [
          {
            "node": "Send Digest Telegram + Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "errorWorkflow": "CODWF99ErrorHandler",
    "timezone": "Africa/Cairo"
  },
  "versionId": "f0400000-0000-4000-8000-000000000000",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "tags": []
}
