{
  "name": "Daily task report from Google Sheets",
  "nodes": [
    {
      "id": "ec1e9132-313e-4fef-9d08-7446d5f4d79c",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -875,
        375
      ],
      "parameters": {
        "content": "## Daily task report from Google Sheets\nEach morning it reads your Tasks tab and writes one report row: done, pending, overdue and blocked.\n\n### You need\n- A Google Sheets login and one sheet with 2 tabs:\n- Tasks: Task ID, Task, Status, Owner, Due Date, Completed At\n- Reports: Report Date, Period Start, Generated At, Completed, Completed Last 7 Days, Pending, Overdue, Due Today, Blocked, Rows to Review, Report\n- An email login (SMTP), only for the email step\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Pick the same sheet in both Google Sheets steps.\n2. Write due dates as YYYY-MM-DD. Set your time zone in Workflow settings.\n3. Want an email too? Turn on **Optional email summary** and add your email login and addresses.\n4. Failure alert: put your chat ID in **Write the failure alert** and your bot in **Send the failure alert**. Then in Workflow settings, set Error workflow to this workflow.\n\n### Test it\n- Click Test workflow with **Run manually** picked.\n- Reports gets a row for today.",
        "height": 754,
        "width": 560,
        "color": 4
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 9,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "id": "3c328bae-1877-46af-9819-0c30834a4dd0",
      "name": "Every day at 9 AM",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -235,
        375
      ]
    },
    {
      "parameters": {},
      "id": "9cc1732b-dd3a-4095-a1ee-0a45bfd9d04f",
      "name": "Run manually",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -235,
        555
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Tasks",
          "mode": "name"
        },
        "options": {}
      },
      "id": "71a9d877-339d-4818-a632-e9d4030168d2",
      "name": "Read tasks",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        25,
        420
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const now = $now;\nconst reportDate = now.toISODate();\nconst periodStart = now.startOf('day').minus({ days: 6 });\nconst maxListed = 25;\nconst dateOnly = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst zonedTimestamp = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:\\d{2})$/;\nconst statuses = new Map([\n  ['pending', 'Pending'],\n  ['to do', 'Pending'],\n  ['todo', 'Pending'],\n  ['open', 'Pending'],\n  ['in progress', 'In progress'],\n  ['blocked', 'Blocked'],\n  ['waiting', 'Waiting'],\n  ['completed', 'Completed'],\n  ['complete', 'Completed'],\n  ['done', 'Completed'],\n  ['cancelled', 'Cancelled'],\n  ['canceled', 'Cancelled'],\n]);\nconst text = value => String(value ?? '').trim();\n\nfunction display(value, limit) {\n  const singleLine = value.replace(/\\s+/g, ' ');\n  return singleLine.length > limit ? singleLine.slice(0, limit - 1) + '…' : singleLine;\n}\n\nfunction parseDate(value, allowTime = false) {\n  if (!dateOnly.test(value) && !(allowTime && zonedTimestamp.test(value))) return null;\n  const date = DateTime.fromISO(value, { zone: now.zoneName });\n  return date.isValid ? date : null;\n}\n\nconst rows = $input.all().map(item => item.json).filter(row =>\n  Object.entries(row).some(([column, value]) => column !== 'row_number' && text(value))\n);\nconst idCounts = new Map();\nfor (const row of rows) {\n  const id = text(row['Task ID']);\n  if (id) idCounts.set(id, (idCounts.get(id) ?? 0) + 1);\n}\n\nconst pending = [];\nconst recent = [];\nconst issues = [];\nlet completed = 0;\n\nfor (const row of rows) {\n  const id = text(row['Task ID']);\n  const title = text(row.Task);\n  const status = statuses.get(text(row.Status).toLowerCase().replace(/[_-]+|\\s+/g, ' '));\n  const rowLabel = row.row_number ? 'Sheet row ' + row.row_number : 'Task row';\n  const label = id ? display(id, 60) + ' (' + rowLabel + ')' : rowLabel;\n  const problems = [];\n\n  if (!id) problems.push('missing Task ID');\n  if (idCounts.get(id) > 1) problems.push('duplicate Task ID');\n  if (!title) problems.push('missing task name');\n  if (!status) problems.push('unrecognized status: ' + (display(text(row.Status), 60) || 'blank'));\n  if (problems.length) {\n    issues.push(label + ': ' + problems.join(', '));\n    continue;\n  }\n  if (status === 'Cancelled') continue;\n\n  const task = {\n    id,\n    title: display(title, 140),\n    owner: display(text(row.Owner), 80) || 'Unassigned',\n    status,\n  };\n  if (status === 'Completed') {\n    completed += 1;\n    const finished = parseDate(text(row['Completed At']), true);\n    if (!finished || finished.toMillis() > now.toMillis()) {\n      issues.push(label + ': enter a valid completion date or timestamp that has passed');\n    } else if (finished.toMillis() >= periodStart.toMillis()) {\n      recent.push({ ...task, finished });\n    }\n    continue;\n  }\n\n  const dueValue = text(row['Due Date']);\n  const due = parseDate(dueValue);\n  if (dueValue && !due) issues.push(label + ': Due Date must be a valid YYYY-MM-DD date');\n  pending.push({ ...task, due: due?.toISODate() ?? '' });\n}\n\npending.sort((a, b) => (a.due || '9999-12-31').localeCompare(b.due || '9999-12-31') ||\n  a.id.localeCompare(b.id));\nrecent.sort((a, b) => b.finished.toMillis() - a.finished.toMillis() || a.id.localeCompare(b.id));\n\nconst overdue = pending.filter(task => task.due && task.due < reportDate).length;\nconst dueToday = pending.filter(task => task.due === reportDate).length;\nconst blocked = pending.filter(task => task.status === 'Blocked').length;\nconst taskText = task => '[' + display(task.id, 60) + '] ' + task.title + ': ' + task.owner;\n\nfunction section(heading, entries, format) {\n  const lines = entries.slice(0, maxListed).map(entry => '• ' + format(entry));\n  if (entries.length > maxListed) {\n    lines.push('… ' + (entries.length - maxListed) + ' more. See the Tasks tab.');\n  }\n  return [heading + ' (' + entries.length + ')', ...(lines.length ? lines : ['None'])].join('\\n');\n}\n\nconst report = [\n  'Task status as of ' + now.toFormat('yyyy-MM-dd HH:mm ZZZZ') + ' (' + now.zoneName + ')',\n  'Pending: ' + pending.length + ' | Overdue: ' + overdue + ' | Due today: ' + dueToday +\n    ' | Blocked: ' + blocked,\n  section('Pending tasks', pending, task => {\n    const due = task.due ? 'due ' + task.due : 'no due date';\n    const urgent = task.due && task.due < reportDate ? ': OVERDUE' : '';\n    return taskText(task) + ': ' + task.status + ': ' + due + urgent;\n  }),\n  section('Completed since ' + periodStart.toISODate(), recent,\n    task => taskText(task) + ': ' + task.finished.toISODate()),\n  section('Rows to review', issues, issue => issue),\n].join('\\n\\n');\n\nreturn [{ json: {\n  'Report Date': reportDate,\n  'Period Start': periodStart.toISODate(),\n  'Generated At': now.toISO(),\n  'Completed': completed,\n  'Completed Last 7 Days': recent.length,\n  'Pending': pending.length,\n  'Overdue': overdue,\n  'Due Today': dueToday,\n  'Blocked': blocked,\n  'Rows to Review': issues.length,\n  'Report': report,\n} }];"
      },
      "id": "bac1098d-7d3b-4f6c-9db5-947d0551a0f1",
      "name": "Generate task report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        285,
        420
      ]
    },
    {
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Reports",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Report Date": "={{ $json[\"Report Date\"] }}",
            "Period Start": "={{ $json[\"Period Start\"] }}",
            "Generated At": "={{ $json[\"Generated At\"] }}",
            "Completed": "={{ $json[\"Completed\"] }}",
            "Completed Last 7 Days": "={{ $json[\"Completed Last 7 Days\"] }}",
            "Pending": "={{ $json[\"Pending\"] }}",
            "Overdue": "={{ $json[\"Overdue\"] }}",
            "Due Today": "={{ $json[\"Due Today\"] }}",
            "Blocked": "={{ $json[\"Blocked\"] }}",
            "Rows to Review": "={{ $json[\"Rows to Review\"] }}",
            "Report": "={{ $json[\"Report\"] }}"
          },
          "matchingColumns": [
            "Report Date"
          ],
          "schema": [
            {
              "id": "Report Date",
              "displayName": "Report Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Period Start",
              "displayName": "Period Start",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Generated At",
              "displayName": "Generated At",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Completed",
              "displayName": "Completed",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Completed Last 7 Days",
              "displayName": "Completed Last 7 Days",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Pending",
              "displayName": "Pending",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Overdue",
              "displayName": "Overdue",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Due Today",
              "displayName": "Due Today",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Blocked",
              "displayName": "Blocked",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Rows to Review",
              "displayName": "Rows to Review",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Report",
              "displayName": "Report",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "afbde6f8-2474-4ad9-b12b-dd262a41544d",
      "name": "Save today's report",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        545,
        420
      ]
    },
    {
      "parameters": {
        "fromEmail": "",
        "toEmail": "",
        "subject": "={{ \"Task status report for \" + $(\"Generate task report\").first().json[\"Report Date\"] }}",
        "emailFormat": "text",
        "text": "={{ [\"Completed in the last 7 days: \" + $(\"Generate task report\").first().json[\"Completed Last 7 Days\"], \"Pending: \" + $(\"Generate task report\").first().json[\"Pending\"], \"Overdue: \" + $(\"Generate task report\").first().json[\"Overdue\"], \"Due today: \" + $(\"Generate task report\").first().json[\"Due Today\"], \"Blocked: \" + $(\"Generate task report\").first().json[\"Blocked\"], \"Rows to review: \" + $(\"Generate task report\").first().json[\"Rows to Review\"], \"\", \"Open the Reports tab to review tasks and owners.\"].join(\"\\n\") }}",
        "options": {
          "appendAttribution": false
        }
      },
      "id": "4a6f33a6-0eaa-4064-8531-bc5df75d025b",
      "name": "Optional email summary",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        805,
        420
      ],
      "disabled": true
    },
    {
      "id": "5b0e9ed1-5184-4bb5-b004-bc3f6408f4e1",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -835,
        1209
      ],
      "parameters": {}
    },
    {
      "id": "6899181c-bf1b-4ae5-9d38-138db6dc009f",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -615,
        1209
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_TELEGRAM_CHAT_ID"
            },
            {
              "id": "f2",
              "name": "message",
              "type": "string",
              "value": "={{ 'A workflow stopped.\\n\\nWorkflow: ' + (($json.workflow || {}).name || 'unknown') + '\\nFailed step: ' + (($json.execution || {}).lastNodeExecuted || 'unknown') + '\\nWhy: ' + String((($json.execution || {}).error || {}).message || 'n8n did not give a reason.').slice(0, 300) + (($json.execution || {}).url ? '\\nOpen the run: ' + $json.execution.url : '') }}"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      }
    },
    {
      "id": "6e23d103-db24-4750-a036-b4210c90a846",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -395,
        1209
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Every day at 9 AM": {
      "main": [
        [
          {
            "node": "Read tasks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run manually": {
      "main": [
        [
          {
            "node": "Read tasks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read tasks": {
      "main": [
        [
          {
            "node": "Generate task report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate task report": {
      "main": [
        [
          {
            "node": "Save today's report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save today's report": {
      "main": [
        [
          {
            "node": "Optional email summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow fails": {
      "main": [
        [
          {
            "node": "Write the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the failure alert": {
      "main": [
        [
          {
            "node": "Send the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
