{
  "name": "Overdue client decisions to follow-up tasks",
  "nodes": [
    {
      "id": "56ef3f75-dc98-45bd-8b42-2547a370d93f",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1390,
        0
      ],
      "parameters": {
        "content": "## Overdue client decisions to follow-up tasks\nEach morning an overdue client decision becomes a follow-up task. The task closes when the client answers.\n\n### You need\n- A Google Sheets login and one sheet with 2 tabs:\n- Approvals: Approval ID, Client, Job, Owner, Status, Decision Due\n- Tasks: Task ID, Task, Status, Owner, Due Date, Completed At\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Pick the same sheet in all 3 Google Sheets steps.\n2. Write dates as YYYY-MM-DD. Give each approval its own ID.\n3. Set your time zone in Workflow settings.\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- Add an approval with Status Requested and a due date of today. Click Test workflow with **Run manually** picked.\n- A follow-up shows up in Tasks. Set the approval to Approved and run again: the task closes.",
        "height": 702,
        "width": 560,
        "color": 4
      }
    },
    {
      "name": "Check decisions daily",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "id": "636125b3-8578-49e2-91c4-85c346a780f0",
      "position": [
        -750,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 8,
              "triggerAtMinute": 0
            }
          ]
        }
      }
    },
    {
      "name": "Run manually",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "id": "8183bc3d-da7a-44e8-9112-ba7ee2d38e18",
      "position": [
        -750,
        180
      ],
      "parameters": {}
    },
    {
      "name": "Read approvals",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "451045e2-7621-485b-a1d7-6e6b82a7a2c7",
      "position": [
        -510,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Approvals",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true
    },
    {
      "name": "Read current tasks",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "7f61664a-0116-49e4-8d1e-b828b42f1f62",
      "position": [
        -270,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Tasks",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "name": "Create or close follow-ups",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "29b16549-1180-4f34-b105-fcc1a3eabfe7",
      "position": [
        -30,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const now = $now;\nconst today = now.toISODate();\nconst value = entry => String(entry ?? '').trim();\nconst approvals = $('Read approvals').all().map(item => item.json);\nconst tasks = $input.all().map(item => item.json);\nconst taskMap = new Map();\nconst approvalCounts = new Map();\n\nfor (const row of tasks) {\n  const id = value(row['Task ID']);\n  if (id) taskMap.set(id, [...(taskMap.get(id) || []), row]);\n}\nfor (const row of approvals) {\n  const id = value(row['Approval ID']);\n  if (id) approvalCounts.set(id, (approvalCounts.get(id) || 0) + 1);\n}\nconst action = [];\nfor (const approval of approvals) {\n  const id = value(approval['Approval ID']);\n  if (!id) continue;\n  const taskId = 'approval-' + id;\n  const matches = taskMap.get(taskId) || [];\n  if (approvalCounts.get(id) !== 1 || matches.length > 1) {\n    throw new Error('Resolve duplicate approval or follow-up task IDs before updating ' + id);\n  }\n  const existing = matches[0];\n  const status = value(approval.Status).toLowerCase();\n  if (['approved', 'changes requested', 'rejected'].includes(status)) {\n    if (existing && ['pending', 'in progress', 'blocked', 'waiting'].includes(value(existing.Status).toLowerCase())) {\n      action.push({ ...existing, 'Task ID': taskId, Status: 'Completed', 'Completed At': now.toISO() });\n    }\n    continue;\n  }\n  if (status !== 'requested' || existing) continue;\n  const due = value(approval['Decision Due']);\n  const decision = /^\\d{4}-\\d{2}-\\d{2}$/.test(due) ? DateTime.fromISO(due, { zone: now.zoneName }) : null;\n  const job = value(approval.Job);\n  if (!decision?.isValid || !job) throw new Error('Add a valid Decision Due date and Job for approval ' + id);\n  if (decision.toISODate() > today) continue;\n  const client = value(approval.Client);\n  action.push({\n    'Task ID': taskId,\n    Task: 'Follow up on ' + job + (client ? ' (' + client + ')' : ''),\n    Status: 'Pending',\n    Owner: value(approval.Owner),\n    'Due Date': due,\n    'Completed At': '',\n  });\n}\nreturn action.map(json => ({ json }));"
      }
    },
    {
      "name": "Save follow-ups to Tasks",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "58ccbdeb-1385-4768-9123-6c22a1baa298",
      "position": [
        210,
        0
      ],
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Tasks",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Task ID": "={{ $json[\"Task ID\"] }}",
            "Task": "={{ $json[\"Task\"] }}",
            "Status": "={{ $json[\"Status\"] }}",
            "Owner": "={{ $json[\"Owner\"] }}",
            "Due Date": "={{ $json[\"Due Date\"] }}",
            "Completed At": "={{ $json[\"Completed At\"] }}"
          },
          "matchingColumns": [
            "Task ID"
          ],
          "schema": [
            {
              "id": "Task ID",
              "displayName": "Task ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Task",
              "displayName": "Task",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Status",
              "displayName": "Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Owner",
              "displayName": "Owner",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Due Date",
              "displayName": "Due Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Completed At",
              "displayName": "Completed At",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      }
    },
    {
      "id": "dacf93bc-459d-42fe-b420-fa2e56c567ff",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -1350,
        782
      ],
      "parameters": {}
    },
    {
      "id": "78ac16ae-df91-4111-b6c4-a7129d6c5517",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -1130,
        782
      ],
      "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": "19488d64-aaf9-4179-8059-f4784b49cab7",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -910,
        782
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Check decisions daily": {
      "main": [
        [
          {
            "node": "Read approvals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run manually": {
      "main": [
        [
          {
            "node": "Read approvals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read approvals": {
      "main": [
        [
          {
            "node": "Read current tasks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read current tasks": {
      "main": [
        [
          {
            "node": "Create or close follow-ups",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create or close follow-ups": {
      "main": [
        [
          {
            "node": "Save follow-ups to Tasks",
            "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": {}
}
