{
  "name": "Weekly client handoff",
  "nodes": [
    {
      "id": "a5779a7d-9813-4ce5-b46e-6b0448609d79",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -730,
        -100
      ],
      "parameters": {
        "content": "## Weekly client handoff\nEach week it drafts one status email per active client from your Trello board and Drive, and saves the same snapshot in Notion.\n\n### You need\n- Notion databases for clients and weekly snapshots, a Trello board and Drive folders\n- Notion, Google Drive, Gmail, Google Sheets and Trello logins\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Start with a blank Google Sheet. The first run makes its own tabs.\n2. Fill **Pack settings**: sheet ID, clients and snapshots data source IDs, snapshot title field, Trello board ID.\n3. Add each login where a step asks. Use the same one in every step for that app. 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- Click Test workflow with **Run the review now** picked.\n- Each active client gets a Notion snapshot and a Gmail draft. Nothing is sent for you.",
        "height": 754,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "6ee7bf9f-ca0b-5727-b25e-91cb29311e19",
      "name": "Scheduled review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 30
            }
          ]
        }
      }
    },
    {
      "id": "5aa108d4-9675-512a-819b-f7da0e3b8ceb",
      "name": "Run the review now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        210
      ],
      "parameters": {}
    },
    {
      "id": "a7628944-2c7d-53af-8c9d-f972dbe17ff4",
      "name": "Pack settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        230,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "cf8beb1f-55b2-5371-bf6f-0f9e5151a703",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "aff12637-aa1f-5f53-ab09-2b24c3289add",
              "name": "Clients data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "5ed2a584-b99c-55e9-94f1-38db95d4138d",
              "name": "Snapshots data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "8f361598-e8ff-560e-bcf8-8b265198f668",
              "name": "Notion snapshot title property",
              "type": "string",
              "value": "Name"
            },
            {
              "id": "8acdd3d2-7358-5dbc-8697-a3ab9e0c4f88",
              "name": "Trello board ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "47f28aac-da39-5548-8d93-391b830bb8d0",
              "name": "Digest recipient (optional)",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "d3ec5efc-c77a-5b7d-9e2a-095c20cc31d1",
      "name": "Check pack settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const required = [\"Spreadsheet ID\", \"Clients data source ID\", \"Snapshots data source ID\", \"Trello board ID\"];\nconst raw = $input.first().json;\nconst config = Object.fromEntries(Object.entries(raw).map(([key, value])=>[key,typeof value==='string'?value.trim():value]));\nconst missing = required.filter(key=>!config[key]);\nif (missing.length) throw new Error('Fill in Pack settings: '+missing.join(', '));\nfor(const key of ['Spreadsheet ID','Trello board ID','Trello work list ID','Drive root folder ID']){\n  if(config[key]&&!/^[A-Za-z0-9_-]+$/.test(config[key])) throw new Error(key+' must be an ID, without a URL.');\n}\nfor(const [key,value] of Object.entries(config)){\n  if(key.endsWith('data source ID')&&value&&!/^(?:[a-f0-9]{32}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/i.test(value)) throw new Error(key+' must be a Notion data source ID.');\n}\nif(config['Shopify shop domain']&&!/^[a-z0-9][a-z0-9-]*\\.myshopify\\.com$/i.test(config['Shopify shop domain'])) throw new Error('Use your shop-name.myshopify.com domain.');\nif(config['Digest recipient (optional)']&&!/^[^@\\s,]+@[^@\\s,]+\\.[^@\\s,]+$/.test(config['Digest recipient (optional)'])) throw new Error('Use one internal digest email address.');\nfor(const key of ['Stall after days','Review window days','Reminder lead days']){\n  if(config[key]!==undefined&&(!Number.isInteger(config[key])||config[key]<1||config[key]>59))throw new Error(key+' must be a whole number from 1 to 59.');\n}\nreturn [{json:config}];"
      }
    },
    {
      "id": "5b755b39-d2eb-55bb-9079-c25ba6d308ce",
      "name": "Inspect the workbook tabs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        690,
        0
      ],
      "parameters": {
        "url": "={{ 'https://sheets.googleapis.com/v4/spreadsheets/'+$(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "sheets(properties(sheetId,title))"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "91575149-1b9e-5a8b-942e-a4d66c3b8ec3",
      "name": "Plan missing tabs and headers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const tabs = {\"Weekly Client Handoff Ledger\": [\"Work Key\", \"Title\", \"State\", \"Details\", \"Due\", \"Source URL\", \"Card ID\", \"Card URL\", \"Checked At\", \"Client\", \"Completed Tasks\", \"Pending Tasks\", \"Overdue Tasks\", \"Snapshot URL\", \"Draft Message ID\"], \"Weekly Client Handoff Report\": [\"Report Date\", \"Completed\", \"Pending\", \"Blocked\", \"Overdue\", \"Attention\", \"Summary\", \"Checked At\"]};\nconst existing=$input.first().json.sheets;\nif(!Array.isArray(existing)) throw new Error('Sheets did not return a readable workbook.');\nconst titles=new Set(existing.map(s=>s.properties?.title));\nconst ids=new Set(existing.map(s=>s.properties?.sheetId));\nconst requests=[];\nlet id=621100;\nfor(const [title,columns] of Object.entries(tabs)){\n  if(titles.has(title)) continue;\n  while(ids.has(id)) id++;\n  const sheetId=id++;\n  requests.push({addSheet:{properties:{title,sheetId,gridProperties:{frozenRowCount:1,columnCount:Math.max(26,columns.length)}}}});\n  requests.push({updateCells:{start:{sheetId,rowIndex:0,columnIndex:0},rows:[{values:columns.map(stringValue=>({userEnteredValue:{stringValue},userEnteredFormat:{textFormat:{bold:true}}}))}],fields:'userEnteredValue,userEnteredFormat'}});\n}\nreturn [{json:{requests}}];"
      }
    },
    {
      "id": "5ae5ddaf-2b08-5fda-969a-8382ce6e82c9",
      "name": "Workbook needs tabs",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1150,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "22710c18-0dc3-52e5-9ebb-9383800d4a2d",
              "leftValue": "={{ $json.requests.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "6427a0c9-cc84-54d2-a6b2-f5cc6cab0090",
      "name": "Create tabs and headers together",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1380,
        -100
      ],
      "parameters": {
        "url": "={{ 'https://sheets.googleapis.com/v4/spreadsheets/'+$(\"Check pack settings\").first().json[\"Spreadsheet ID\"]+':batchUpdate' }}",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {requests:$json.requests} }}"
      }
    },
    {
      "id": "4e9d5fc0-e921-53d3-9194-8abe8c0d4839",
      "name": "Read the saved ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        0,
        520
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Weekly Client Handoff Ledger"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "106204a9-edec-5b09-a2c2-30f823f9ae37",
      "name": "Set up the source",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1070,
        305
      ],
      "parameters": {
        "content": "## Set up the source\n\nNotion Clients needs **Active** checkbox, **Trello List ID**, **Drive Folder ID** text, **Email** email/text. Optional **Done List ID** text. Cards in a shared done list need a line “Client: [Notion page UUID]” in the description. Limit one active client to each working list.",
        "width": 966,
        "height": 145,
        "color": 4
      }
    },
    {
      "id": "f62903ab-04ee-5fe2-bff5-73bc9c37359d",
      "name": "Read Notion client workspaces",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        230,
        520
      ],
      "parameters": {
        "url": "={{ 'https://api.notion.com/v1/data_sources/'+$(\"Check pack settings\").first().json[\"Clients data source ID\"]+'/query' }}",
        "method": "POST",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "body",
                    "name": "start_cursor",
                    "value": "={{ $response.body?.next_cursor || undefined }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ $response.body.has_more !== true }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "notionApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {page_size:100} }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "2025-09-03"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "cba3af36-42b4-53f1-bb6f-237a9f6d6baa",
      "name": "Read existing weekly Notion snapshots",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        460,
        520
      ],
      "parameters": {
        "url": "={{ 'https://api.notion.com/v1/data_sources/'+$(\"Check pack settings\").first().json[\"Snapshots data source ID\"]+'/query' }}",
        "method": "POST",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "body",
                    "name": "start_cursor",
                    "value": "={{ $response.body?.next_cursor || undefined }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ $response.body.has_more !== true }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "notionApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {page_size:100} }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "2025-09-03"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "b9a0e5b7-fd5a-5c47-96be-c24742431c43",
      "name": "Read cards from the client board",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        690,
        520
      ],
      "parameters": {
        "url": "={{ 'https://api.trello.com/1/boards/'+$(\"Check pack settings\").first().json[\"Trello board ID\"]+'/cards/all' }}",
        "method": "GET",
        "options": {
          "timeout": 45000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": false
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "trelloApi",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name,desc,idList,due,dueComplete,closed,shortUrl"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "9eadc044-8ac6-50ae-b78d-bce32a9d53de",
      "name": "Build the configured client folder list",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        520
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const pages=$(\"Read Notion client workspaces\").all().map(i=>i.json);\nif(!pages.length||pages.at(-1).has_more)throw new Error('Notion returned an incomplete folder list.');\nconst folders=[...new Set(pages.flatMap(i=>i.results||[]).filter(p=>!p.archived&&!p.in_trash&&(p.properties?.Active?.checkbox===true)).flatMap(p=>[\n  (p.properties?.[\"Drive Folder ID\"]?.rich_text||[]).map(t=>t.plain_text??t.text?.content??'').join('').trim()\n]).filter(id=>/^[A-Za-z0-9_-]+$/.test(id)))];\nif(folders.length>35)throw new Error('This pack supports up to 35 client folders per workflow instance.');\nreturn [{json:{folders}}];"
      }
    },
    {
      "id": "3951295e-7d99-5d37-89da-be90991911b7",
      "name": "There are configured client folders",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1150,
        520
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "fc48f6b8-cc21-57fb-8117-0d71fd13e58a",
              "leftValue": "={{ $json.folders.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "43c0262d-64c8-5a0a-a1d1-e704474e8fc6",
      "name": "Read the client folders",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1380,
        520
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "method": "GET",
        "options": {
          "timeout": 45000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "qs",
                    "name": "pageToken",
                    "value": "={{ $response.body?.nextPageToken || undefined }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !$response.body.nextPageToken }}",
              "limitPagesFetched": true,
              "maxRequests": 20,
              "requestInterval": 400
            }
          }
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ 'trashed = false and (' + $json.folders.map(id=>\"'\"+id+\"' in parents\").join(' or ') + ')' }}"
            },
            {
              "name": "pageSize",
              "value": "1000"
            },
            {
              "name": "fields",
              "value": "nextPageToken,incompleteSearch,files(id,name,mimeType,webViewLink,parents,md5Checksum,appProperties,description,trashed)"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            },
            {
              "name": "includeItemsFromAllDrives",
              "value": "true"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "0a3fe50b-39ac-5719-8702-6c8f4b9fb18b",
      "name": "Continue to client review",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{ready:true}}];"
      }
    },
    {
      "id": "17481af3-41c6-5cbf-86c0-f746b74d8eab",
      "name": "Decide which work needs attention",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        230,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const config=$('Check pack settings').first().json;\nconst today=$now.toISODate();\nconst stamp=$now.toISO();\nconst str=value=>String(value??'').trim();\nconst lower=value=>str(value).toLowerCase();\nconst rows=(name,key)=>$(name).all().map(x=>x.json).filter(x=>x[key]!==undefined && str(x[key])!=='');\nconst yes=value=>['true','yes','1','approved'].includes(lower(value));\nconst validId=value=>/^[A-Za-z0-9_-]+$/.test(str(value));\nconst publicUrl=value=>/^https:\\/\\/[a-z0-9][\\w.-]*\\.[a-z]{2,}(?:[:/?#]|$)/i.test(str(value))?str(value):'';\nconst email=value=>/^[^@\\s,]+@[^@\\s,]+\\.[^@\\s,]+$/.test(str(value))?str(value):'';\nconst prior=new Map(rows('Read the saved ledger','Work Key').map(row=>[str(row['Work Key']),row]));\nfunction unique(values,label){\n  const keys=values.map(lower);\n  if(new Set(keys).size!==keys.length) throw new Error(label+' must be unique.');\n}\nfunction notion(name){\n  const pages=$(name).all().map(i=>i.json);\n  if(!pages.length||pages.some(p=>!Array.isArray(p.results))||pages.at(-1).has_more) throw new Error('Notion read was incomplete. Try again before updating work.');\n  return pages.flatMap(p=>p.results).filter(p=>p.object==='page'&&!p.archived&&!p.in_trash);\n}\nfunction property(page,key){\n  const p=page.properties?.[key];\n  if(!p)return '';\n  const v=p[p.type];\n  if(p.type==='title'||p.type==='rich_text') return (v||[]).map(t=>t.plain_text??t.text?.content??'').join('');\n  if(p.type==='select'||p.type==='status') return v?.name??'';\n  if(p.type==='date') return v?.start??'';\n  return v??'';\n}\nfunction titleOf(page){\n  const title=Object.keys(page.properties||{}).find(key=>page.properties[key].type==='title');\n  return str(property(page,title))||'Untitled';\n}\nfunction drive(name){\n  const pages=$(name).all().map(i=>i.json);\n  if(!pages.length||pages.some(p=>p.incompleteSearch||!Array.isArray(p.files))||pages.at(-1).nextPageToken) throw new Error('Drive returned an incomplete listing.');\n  return pages.flatMap(p=>p.files);\n}\nfunction shop(name){\n  const pages=$(name).all().map(i=>i.json);\n  const error=pages.find(p=>p.errors?.length);\n  if(error) throw new Error('Shopify GraphQL: '+error.errors.map(x=>x.message).join(', '));\n  if(!pages.length||pages.some(p=>!p.data?.connection||!Array.isArray(p.data.connection.nodes))||pages.at(-1).data.connection.pageInfo?.hasNextPage) throw new Error('Shopify returned an incomplete list.');\n  return pages.flatMap(p=>p.data.connection.nodes);\n}\nconst dueDate=value=>/^\\d{4}-\\d{2}-\\d{2}/.test(str(value))?str(value).slice(0,10):'';\nconst driveLink=f=>f?.webViewLink||(f?.id?'https://drive.google.com/open?id='+encodeURIComponent(f.id):'');\nconst money=(n,c)=>Number.isFinite(n)?n.toFixed(2)+' '+c:'';\nconst shopLink=(resource,id)=>'https://'+config['Shopify shop domain']+'/admin/'+resource+'/'+str(id).split('/').at(-1);\nfunction job(key,title,state,details,due='',url='',extra={},track=true){\n  return {key:str(key),title:str(title),state,details:str(details),due:str(due),url:str(url),extra,track};\n}\nconst result=(jobs,summary='',more={})=>[{json:{jobs,summary,...more}}];\n\nconst clients=notion('Read Notion client workspaces').filter(p=>property(p,'Active')===true);\nunique(clients.map(p=>property(p,'Trello List ID')).filter(Boolean),'Active client Trello lists');\nunique(clients.map(p=>property(p,'Drive Folder ID')).filter(Boolean),'Active client Drive folders');\nconst published=notion('Read existing weekly Notion snapshots');\nconst cards=$('Read cards from the client board').first().json.body;\nif(!Array.isArray(cards))throw new Error('Expected the full Trello card list.');\nconst assets=$('Read the client folders').isExecuted?drive('Read the client folders'):[];\nconst jobs=[],candidates=[];\nconst monday=$now.startOf('week').toISODate();\nfor(const p of clients){\n  const id=p.id, key=monday+'-'+id, old=prior.get(key)||{};\n  const list=str(property(p,'Trello List ID')), doneList=str(property(p,'Done List ID'));\n  const folder=str(property(p,'Drive Folder ID')), address=email(property(p,'Email'));\n  const marker='[Handoff '+key+']', name=titleOf(p);\n  const matches=published.filter(page=>titleOf(page).startsWith(marker+' '));\n  if(matches.length>1)throw new Error('Duplicate Notion snapshots for '+key);\n  const snapshot=matches[0];\n  const track=cards.filter(c=>!c.closed&&(c.idList===list||(doneList&&c.idList===doneList&&typeof c.desc==='string'&&c.desc.split('\\n').some(x=>x.trim()==='Client: '+id))));\n  const completed=track.filter(c=>c.dueComplete||(doneList&&c.idList===doneList));\n  const pending=track.filter(c=>!completed.includes(c));\n  const overdue=pending.filter(c=>c.due&&c.due.slice(0,10)<today);\n  const attachments=assets.filter(f=>f.parents?.includes(folder)&&f.mimeType!=='application/vnd.google-apps.folder').slice(0,12);\n  const valid=validId(list)&&validId(folder)&&Boolean(address);\n  const draft=old['Draft Message ID']||'';\n  const state=!valid?'Blocked':snapshot&&draft?'Completed':'Pending';\n  const summary='Completed '+completed.length+' · Pending '+pending.length+' · Overdue '+overdue.length;\n  const body=[summary,'Completed',...completed.slice(0,15).map(c=>'- '+c.name),'Pending',...pending.slice(0,15).map(c=>'- '+c.name+(overdue.includes(c)?' (overdue)':'')),\n    'Deliverables',...attachments.map(f=>'- '+f.name+' · '+driveLink(f))].join('\\n');\n  jobs.push(job(key,name,state,valid?summary:'Set a Trello list ID, Drive folder ID and email', '',p.url,\n    {'Client':name,'Completed Tasks':completed.length,'Pending Tasks':pending.length,'Overdue Tasks':overdue.length,\n     'Snapshot URL':snapshot?.url||'','Draft Message ID':draft}));\n  if(valid&&state==='Pending')candidates.push({key,marker,title:name,subject:'Weekly update for '+name+' [handoff-'+key+']',\n    email:address,body:'Hi,\\n\\nHere is your current weekly update.\\n\\n'+body,snapshot:snapshot||null,draft});\n}\nreturn result(jobs,jobs.length+' active client workspaces. Each week gets its own snapshot and draft.',{candidate:candidates[0]||null});"
      }
    },
    {
      "id": "8540f96d-320e-5513-93de-e89c455ced14",
      "name": "A client needs this week’s snapshot",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        460,
        770
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "796c45b3-209a-5eb6-bd5b-9814e742b303",
              "leftValue": "={{ Boolean($json.candidate && !$json.candidate.snapshot) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "671eee61-191a-587a-ba14-25a02083922e",
      "name": "Write the weekly Notion snapshot",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        690,
        770
      ],
      "parameters": {
        "url": "https://api.notion.com/v1/pages",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "notionApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ ({parent:{type:'data_source_id',data_source_id:$(\"Check pack settings\").first().json[\"Snapshots data source ID\"]},properties:{[$(\"Check pack settings\").first().json[\"Notion snapshot title property\"]]:{title:[{type:'text',text:{content:($json.candidate.marker+' '+$json.candidate.title).slice(0,200)} }]} },children:(($json.candidate.body).match(/[\\s\\S]{1,1700}/g)?.slice(0,9) ?? []).map(content=>({type:'paragraph',paragraph:{rich_text:[{type:'text',text:{content} }]} }))}) }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "2025-09-03"
            }
          ]
        }
      }
    },
    {
      "id": "75b22ef7-39ff-574b-a333-2d179cec4ced",
      "name": "Prepare the client handoff draft",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Decide which work needs attention\").first().json;\nif(data.candidate){\n const c=data.candidate, work=data.jobs.find(j=>j.key===c.key);\n if($('Write the weekly Notion snapshot').isExecuted){\n  c.snapshot=$('Write the weekly Notion snapshot').first().json;\n  if(!c.snapshot.id)throw new Error('Notion did not return a snapshot ID.');\n }\n c.existingDraft=c.draft;\n work.extra['Snapshot URL']=c.snapshot.url;\n if(c.existingDraft)work.state='Completed';\n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "da344968-77d5-5225-940e-f895858b6606",
      "name": "A client draft is due",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1150,
        770
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5c18a115-29c4-566f-a342-86c727c4a8ea",
              "leftValue": "={{ Boolean($json.candidate?.email && !$json.candidate?.existingDraft) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "26a3e393-8d28-5675-a1f6-76c28b7adce2",
      "name": "Find an existing client draft",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1380,
        770
      ],
      "parameters": {
        "url": "https://gmail.googleapis.com/gmail/v1/users/me/messages",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "gmailOAuth2",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ '(in:drafts OR in:sent) subject:\"'+($(\"Prepare the client handoff draft\").first().json[\"candidate\"].subject).replace(/\"/g,'')+'\"' }}"
            },
            {
              "name": "maxResults",
              "value": "2"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "78b7d3ae-cfcd-5e2d-88e8-3c133df6a524",
      "name": "Gmail draft is new",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        0,
        1020
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "89f64d2c-7efe-5476-8ca5-d7e0198d03cc",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "593b461c-92ed-51c1-a917-f2e0f2ca8717",
      "name": "Create the Gmail draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        230,
        1020
      ],
      "parameters": {
        "resource": "draft",
        "operation": "create",
        "subject": "={{ $(\"Prepare the client handoff draft\").first().json[\"candidate\"].subject }}",
        "emailType": "text",
        "message": "={{ $(\"Prepare the client handoff draft\").first().json[\"candidate\"].body }}",
        "options": {
          "sendTo": "={{ $(\"Prepare the client handoff draft\").first().json[\"candidate\"].email }}"
        }
      }
    },
    {
      "id": "2ace7135-3022-5e96-a0ae-f6cfffb864e5",
      "name": "Record the client handoff draft",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        1020
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Prepare the client handoff draft\").first().json;\nif($('Find an existing client draft').isExecuted){\n const found=$('Find an existing client draft').first().json.messages||[];\n if(found.length>1)throw new Error('More than one Gmail record matched this client draft.');\n const created=$('Create the Gmail draft').isExecuted?$('Create the Gmail draft').first().json:null;\n const id=created?.message?.id||found[0]?.id;\n if(!id)throw new Error('Gmail did not return a message ID for the draft.');\n const work=data.jobs.find(j=>j.key===data.candidate.key);\n if(!work)throw new Error('Could not match the draft to an active work record.');\n work.extra['Draft Message ID']=id;\n work.state='Completed';\n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "282221ce-b59b-5692-aa23-3c0a96fcec9a",
      "name": "Prepare tracker updates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const decisionNode = \"Record the client handoff draft\";\nconst prefix = \"[sprkly:weekly-client-handoff:\";\nconst cardsNode = \"\";\nconst data=$(decisionNode).first().json;\nconst config=$('Check pack settings').first().json;\nconst prior=new Map($('Read the saved ledger').all().filter(i=>i.json['Work Key']).map(i=>[String(i.json['Work Key']),i.json]));\nconst cards=cardsNode?$(cardsNode).first().json.body:[];\nif(!Array.isArray(cards)) throw new Error('Trello did not return a card list.');\nconst byId=new Map(cards.map(c=>[c.id,c]));\nconst byMark=new Map();\nfor(const c of cards){\n  const text=String(c.desc||'');\n  if(c.idList!==config['Trello work list ID']&&!text.includes(prefix))continue;\n  const marker=text.split('\\n').find(line=>line.startsWith(prefix)&&line.endsWith(']'));\n  if(!marker)continue;\n  if(byMark.has(marker)) throw new Error('Two Trello cards share '+marker+'. Keep one workflow marker.');\n  byMark.set(marker,c);\n}\nconst writes=[], records=[];\nconst seen=new Set();\nfor(const j of data.jobs){\n  if(!j.key||seen.has(j.key)) throw new Error('Duplicate or missing work key: '+j.key);\n  seen.add(j.key);\n  const old=prior.get(j.key)||{};\n  const marker=prefix+encodeURIComponent(j.key)+']';\n  const finish='[/sprkly-work]';\n  let card=byId.get(old['Card ID'])||byMark.get(marker);\n  const done=j.cardDone??j.state==='Completed';\n  const changes={};\n  if(j.track&&cardsNode&&(card||j.forceCard||(!done&&['Pending','Blocked'].includes(j.state)))){\n    if(!card&&old['Card ID']) throw new Error('Previously tracked Trello card was not found for '+j.key+'. Check the board or restore the card.');\n    const title=j.title.slice(0,240);\n    const block=[marker,'State: '+j.state,j.details.slice(0,2500),j.url,finish].filter(Boolean).join('\\n');\n    const oldDesc=String(card?.desc||'');\n    const start=oldDesc.indexOf(marker);\n    const end=start>=0?oldDesc.indexOf(finish,start):-1;\n    const desc=start>=0&&end>=0?oldDesc.slice(0,start)+block+oldDesc.slice(end+finish.length):(oldDesc?oldDesc+'\\n\\n':'')+block;\n    const date=/^\\d{4}-\\d{2}-\\d{2}$/.test(j.due)?j.due+'T17:00:00.000Z':j.due;\n    const due=date&&Number.isFinite(Date.parse(date))?new Date(date).toISOString():null;\n    if(!card)Object.assign(changes,{name:title,desc,idList:config['Trello work list ID'],dueComplete:done,...(due?{due}:{})});\n    else if(!card.closed){\n      if(card.desc!==desc)changes.desc=desc;\n      if(j.cardDone!==false&&!!card.dueComplete!==done)changes.dueComplete=done;\n      if(due&&Date.parse(card.due)!==Date.parse(due))changes.due=due;\n    }\n    if(Object.keys(changes).length) writes.push({key:j.key,cardId:card?.id||'',payload:changes});\n  }\n  records.push({job:j,cardId:card?.id||old['Card ID']||'',cardUrl:card?.shortUrl||old['Card URL']||'',marker});\n}\nreturn [{json:{...data,writes,records}}];"
      }
    },
    {
      "id": "9be6de74-cb7a-5749-b6ef-f9f4cf8e3300",
      "name": "Prepare ledger rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        1380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const plan=$('Prepare tracker updates').first().json;\nconst changed=new Map();\nif(plan.writes.length){\n  const responses=$input.all().map(i=>i.json);\n  for(const card of responses){\n    if(!card.id)throw new Error('A Trello update did not return a card ID.');\n    const rec=plan.records.find(r=>r.cardId===card.id||(card.desc||'').includes(r.marker));\n    if(!rec)throw new Error('Could not match updated Trello card '+card.id+' to a work record.');\n    changed.set(rec.job.key,card);\n  }\n  if(changed.size!==plan.writes.length)throw new Error('Trello returned fewer cards than planned.');\n}\nconst rows=plan.records.map(r=>{\n  const j=r.job, card=changed.get(j.key);\n  return {'Work Key':j.key,Title:j.title,State:j.state,Details:j.details,Due:j.due,'Source URL':j.url,\n    'Card ID':card?.id||r.cardId,'Card URL':card?.shortUrl||r.cardUrl,'Checked At':$now.toISO(),...j.extra};\n});\nreturn [{json:{rows,summary:plan.summary}}];"
      }
    },
    {
      "id": "14712b68-75bb-5138-ac89-81feab1bdbf5",
      "name": "Ledger has work records",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        1380
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "478defae-2f50-5753-9918-58662f86f7b1",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "b4db5fa5-5abe-5360-aaf5-5325109022f8",
      "name": "Expand work records",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        1270
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.rows.map(json=>({json}));"
      }
    },
    {
      "id": "e5f720f0-ea62-5819-9282-fb5f5117c651",
      "name": "Update the work ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1540,
        1270
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {
          "cellFormat": "RAW",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Weekly Client Handoff Ledger"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Work Key": "={{ $json[\"Work Key\"] ?? \"\" }}",
            "Title": "={{ $json[\"Title\"] ?? \"\" }}",
            "State": "={{ $json[\"State\"] ?? \"\" }}",
            "Details": "={{ $json[\"Details\"] ?? \"\" }}",
            "Due": "={{ $json[\"Due\"] ?? \"\" }}",
            "Source URL": "={{ $json[\"Source URL\"] ?? \"\" }}",
            "Card ID": "={{ $json[\"Card ID\"] ?? \"\" }}",
            "Card URL": "={{ $json[\"Card URL\"] ?? \"\" }}",
            "Checked At": "={{ $json[\"Checked At\"] ?? \"\" }}",
            "Client": "={{ $json[\"Client\"] ?? \"\" }}",
            "Completed Tasks": "={{ $json[\"Completed Tasks\"] ?? \"\" }}",
            "Pending Tasks": "={{ $json[\"Pending Tasks\"] ?? \"\" }}",
            "Overdue Tasks": "={{ $json[\"Overdue Tasks\"] ?? \"\" }}",
            "Snapshot URL": "={{ $json[\"Snapshot URL\"] ?? \"\" }}",
            "Draft Message ID": "={{ $json[\"Draft Message ID\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Work Key"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "68eade8b-c86e-55fe-89cb-6ad58736da63",
      "name": "Summarize completed and pending work",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1700
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const title = \"Weekly Client Handoff\";\nconst data=$('Prepare ledger rows').first().json;\nconst today=$now.toISODate();\nconst completed=data.rows.filter(r=>r.State==='Completed').length;\nconst pending=data.rows.filter(r=>r.State==='Pending').length;\nconst blocked=data.rows.filter(r=>r.State==='Blocked').length;\nconst overdue=data.rows.filter(r=>r.State!=='Completed'&&r.Due&&r.Due.slice(0,10)<today).length;\nconst attention=data.rows.filter(r=>r.State==='Blocked'||(r.State==='Pending'&&r.Due&&r.Due.slice(0,10)<today));\nconst lines=attention.slice(0,20).map(r=>'- '+r.Title+' · '+r.Details+(r['Card URL']?'\\n  '+r['Card URL']:''));\nconst summary='Completed '+completed+' · Pending '+pending+' · Blocked '+blocked+' · Overdue '+overdue;\nreturn [{json:{'Report Date':today,Completed:completed,Pending:pending,Blocked:blocked,Overdue:overdue,Attention:attention.length,Summary:data.summary||summary,\n  'Checked At':$now.toISO(),digestSubject:title+' ['+today+']',digestBody:[summary,data.summary,...lines].filter(Boolean).join('\\n\\n')}}];"
      }
    },
    {
      "id": "03c0d796-63c5-58bc-bb1e-6ab2ccdcf19b",
      "name": "Save the dated work report",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        220,
        1700
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $(\"Check pack settings\").first().json[\"Spreadsheet ID\"] }}"
        },
        "options": {
          "cellFormat": "RAW",
          "useAppend": true
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Weekly Client Handoff Report"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Report Date": "={{ $json[\"Report Date\"] ?? \"\" }}",
            "Completed": "={{ $json[\"Completed\"] ?? \"\" }}",
            "Pending": "={{ $json[\"Pending\"] ?? \"\" }}",
            "Blocked": "={{ $json[\"Blocked\"] ?? \"\" }}",
            "Overdue": "={{ $json[\"Overdue\"] ?? \"\" }}",
            "Attention": "={{ $json[\"Attention\"] ?? \"\" }}",
            "Summary": "={{ $json[\"Summary\"] ?? \"\" }}",
            "Checked At": "={{ $json[\"Checked At\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Report Date"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "21272ad8-069b-51ef-972a-cfeec6725646",
      "name": "A digest recipient is set",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        440,
        1700
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "e2124fd0-5242-52f5-bb74-e7af61e4b89c",
              "leftValue": "={{ Boolean($(\"Check pack settings\").first().json[\"Digest recipient (optional)\"]) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "29c8dd6f-a38c-5ac4-b059-154ba79428dc",
      "name": "Check Gmail for today’s digest",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        1700
      ],
      "parameters": {
        "url": "https://gmail.googleapis.com/gmail/v1/users/me/messages",
        "method": "GET",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "gmailOAuth2",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ 'in:sent subject:\"'+ $('Summarize completed and pending work').first().json.digestSubject+'\"' }}"
            },
            {
              "name": "maxResults",
              "value": "1"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "eba0e695-da2f-5ef3-93ea-24e6935fc772",
      "name": "Today’s digest is new",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        880,
        1700
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "0eb91915-71a2-5049-bfa2-f1706ebbd150",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "c8495cc9-6d60-5fba-9dcf-6ae5170bc510",
      "name": "Email the internal work digest",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1100,
        1700
      ],
      "parameters": {
        "resource": "message",
        "operation": "send",
        "sendTo": "={{ $(\"Check pack settings\").first().json[\"Digest recipient (optional)\"] }}",
        "subject": "={{ $('Summarize completed and pending work').first().json.digestSubject }}",
        "emailType": "text",
        "message": "={{ $('Summarize completed and pending work').first().json.digestBody }}",
        "options": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "27efd990-ccf3-5935-9766-2fb5f5ecded2",
      "name": "Work ledger and daily report",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -90,
        1555
      ],
      "parameters": {
        "content": "## Work ledger and daily report\n\nThe ledger records completed, pending and blocked work with source links. The report stores one snapshot per day. An optional Gmail digest uses one subject per workflow per day.",
        "width": 1315,
        "height": 117,
        "color": 6
      }
    },
    {
      "id": "1b8d3037-b0ee-4377-bd9b-a6bcfdd7c34a",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -690,
        734
      ],
      "parameters": {}
    },
    {
      "id": "d5ee1ed1-5415-494e-9b67-4dedc8a3a42d",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -470,
        734
      ],
      "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": "f4e946a4-769e-4375-a532-a26bc954f860",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -250,
        734
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Scheduled review": {
      "main": [
        [
          {
            "node": "Pack settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pack settings": {
      "main": [
        [
          {
            "node": "Check pack settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check pack settings": {
      "main": [
        [
          {
            "node": "Inspect the workbook tabs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inspect the workbook tabs": {
      "main": [
        [
          {
            "node": "Plan missing tabs and headers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Plan missing tabs and headers": {
      "main": [
        [
          {
            "node": "Workbook needs tabs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run the review now": {
      "main": [
        [
          {
            "node": "Pack settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workbook needs tabs": {
      "main": [
        [
          {
            "node": "Create tabs and headers together",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read the saved ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create tabs and headers together": {
      "main": [
        [
          {
            "node": "Read the saved ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the saved ledger": {
      "main": [
        [
          {
            "node": "Read Notion client workspaces",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Notion client workspaces": {
      "main": [
        [
          {
            "node": "Read existing weekly Notion snapshots",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read existing weekly Notion snapshots": {
      "main": [
        [
          {
            "node": "Read cards from the client board",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read cards from the client board": {
      "main": [
        [
          {
            "node": "Build the configured client folder list",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build the configured client folder list": {
      "main": [
        [
          {
            "node": "There are configured client folders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "There are configured client folders": {
      "main": [
        [
          {
            "node": "Read the client folders",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Continue to client review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the client folders": {
      "main": [
        [
          {
            "node": "Continue to client review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Continue to client review": {
      "main": [
        [
          {
            "node": "Decide which work needs attention",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide which work needs attention": {
      "main": [
        [
          {
            "node": "A client needs this week’s snapshot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "A client needs this week’s snapshot": {
      "main": [
        [
          {
            "node": "Write the weekly Notion snapshot",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare the client handoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the weekly Notion snapshot": {
      "main": [
        [
          {
            "node": "Prepare the client handoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare the client handoff draft": {
      "main": [
        [
          {
            "node": "A client draft is due",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "A client draft is due": {
      "main": [
        [
          {
            "node": "Find an existing client draft",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record the client handoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find an existing client draft": {
      "main": [
        [
          {
            "node": "Gmail draft is new",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail draft is new": {
      "main": [
        [
          {
            "node": "Create the Gmail draft",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record the client handoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the Gmail draft": {
      "main": [
        [
          {
            "node": "Record the client handoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Record the client handoff draft": {
      "main": [
        [
          {
            "node": "Prepare tracker updates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare tracker updates": {
      "main": [
        [
          {
            "node": "Prepare ledger rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare ledger rows": {
      "main": [
        [
          {
            "node": "Ledger has work records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ledger has work records": {
      "main": [
        [
          {
            "node": "Expand work records",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Summarize completed and pending work",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand work records": {
      "main": [
        [
          {
            "node": "Update the work ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update the work ledger": {
      "main": [
        [
          {
            "node": "Summarize completed and pending work",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Summarize completed and pending work": {
      "main": [
        [
          {
            "node": "Save the dated work report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save the dated work report": {
      "main": [
        [
          {
            "node": "A digest recipient is set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "A digest recipient is set": {
      "main": [
        [
          {
            "node": "Check Gmail for today’s digest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Gmail for today’s digest": {
      "main": [
        [
          {
            "node": "Today’s digest is new",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Today’s digest is new": {
      "main": [
        [
          {
            "node": "Email the internal work digest",
            "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",
    "saveDataSuccessExecution": "none",
    "saveManualExecutions": false
  },
  "pinData": {}
}
