{
  "name": "Quote to job kickoff",
  "nodes": [
    {
      "id": "98a15524-fd70-40c9-8f41-513949a07341",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -870,
        -100
      ],
      "parameters": {
        "content": "## Quote to job kickoff\nAn approved quote gets a private Drive folder, a Notion job, a Trello card and a Gmail draft to the client.\n\n### You need\n- Notion databases for clients and jobs, a Drive folder and a Trello board\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 jobs data source IDs, jobs title field, Drive folder ID, Trello board and list IDs.\n3. Fill the **Approved Quotes** tab: Quote ID, Client ID, Job Title, Due, Approved.\n4. Add each login where a step asks. Use the same one in every step for that app. Set your time zone in Workflow settings.\n5. 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. Run it again after you add a quote.\n- The quote gets a folder, a Notion job, a card and a Gmail draft. Nothing is sent for you.",
        "height": 832,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "33a69934-948e-5793-aacd-5ffa50a5d9fe",
      "name": "Scheduled review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 30
            }
          ]
        }
      }
    },
    {
      "id": "f5b64e19-2baf-5ec7-8606-a418b40c589d",
      "name": "Run the review now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        210
      ],
      "parameters": {}
    },
    {
      "id": "e3f42e01-0de8-509c-8c8e-0e5051ad6c0e",
      "name": "Pack settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        230,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "aa60b230-1750-5eb9-b47f-15b1f7ee8cbd",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "91932f65-560d-52ce-a3df-2b048f285fde",
              "name": "Clients data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "56aab35a-c86f-5a36-8752-718a095dec44",
              "name": "Jobs data source ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "65f4800c-40e2-52b5-b0e4-0b6e3b1b7ba4",
              "name": "Notion jobs title property",
              "type": "string",
              "value": "Name"
            },
            {
              "id": "e6c3cd97-ac55-5da7-8302-ed55a6f655f9",
              "name": "Drive root folder ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "18e28caf-f6aa-5d61-b059-0cf5ebf83bb9",
              "name": "Trello board ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "563c6939-f913-5984-ba00-e3696d019c3c",
              "name": "Trello work list ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "4a5e6a54-5e94-562b-b15e-bbfa84e3d657",
              "name": "Digest recipient (optional)",
              "type": "string",
              "value": ""
            }
          ]
        },
        "options": {}
      },
      "executeOnce": true
    },
    {
      "id": "e884efb4-fbe1-5c22-8532-ac14dba97ba5",
      "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\", \"Jobs data source ID\", \"Drive root folder ID\", \"Trello board ID\", \"Trello work list 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": "1720def1-029d-569e-93b3-bda1be16eeae",
      "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": "a7f3c783-e14d-5a5f-a517-6386c4fd9416",
      "name": "Plan missing tabs and headers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const tabs = {\"Approved Quotes\": [\"Quote ID\", \"Client ID\", \"Job Title\", \"Due\", \"Approved\"], \"Quote to Job Kickoff Ledger\": [\"Work Key\", \"Title\", \"State\", \"Details\", \"Due\", \"Source URL\", \"Card ID\", \"Card URL\", \"Checked At\", \"Quote ID\", \"Client ID\", \"Drive URL\", \"Notion Job URL\", \"Draft Message ID\"], \"Quote to Job Kickoff 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": "230101b1-0644-570d-906d-a316b23b6604",
      "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": "005ced22-1d57-5406-b8b0-1d7df6318d16",
              "leftValue": "={{ $json.requests.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "fb23cb41-9bfa-5ed8-b83e-dd0335fe8d1c",
      "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": "bbc9cfca-d353-5051-8f54-4d69398d1b5f",
      "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": "Quote to Job Kickoff Ledger"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "fbef7693-6f32-5fe6-a9f4-89f1504cc1ee",
      "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 **Client ID** text and **Email** email/text. Use a separate Notion Jobs data source with a title property. Set **Approved** to Yes or use a checkbox in Sheets. Drive folders inherit access from the configured parent.",
        "width": 966,
        "height": 145,
        "color": 4
      }
    },
    {
      "id": "fc0a6eff-caef-5378-8230-01f9d23ef950",
      "name": "Read Approved Quotes",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        230,
        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": "Approved Quotes"
        }
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "id": "6fc17bcb-1db0-5657-8d02-405bbe4feeab",
      "name": "Read Notion clients",
      "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[\"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": "4fd0ce57-f2fd-5c3c-bd5c-76f024819ea6",
      "name": "Read existing Notion job pages",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        690,
        520
      ],
      "parameters": {
        "url": "={{ 'https://api.notion.com/v1/data_sources/'+$(\"Check pack settings\").first().json[\"Jobs 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": "ca6e4623-5549-5a64-8730-db1c2739ac07",
      "name": "Find existing kickoff folders",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        920,
        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": "={{ \"'\"+$(\"Check pack settings\").first().json[\"Drive root folder ID\"]+\"' in parents and trashed = false and mimeType = 'application/vnd.google-apps.folder'\" }}"
            },
            {
              "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": "0043c421-13ba-57a8-92ad-17de6c84cd2a",
      "name": "Decide which work needs attention",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1150,
        520
      ],
      "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 quotes=rows('Read Approved Quotes','Quote ID').filter(q=>yes(q.Approved));\nunique(quotes.map(q=>q['Quote ID']),'Approved quote IDs');\nconst clients=notion('Read Notion clients');\nconst open=notion('Read existing Notion job pages');\nconst folders=drive('Find existing kickoff folders');\nconst jobs=[], candidates=[];\nfor(const q of quotes){\n  const key=str(q['Quote ID']);\n  if(!validId(key)||key.length>64)throw new Error('Quote ID must use up to 64 letters, numbers, hyphens or underscores.');\n  const old=prior.get(key)||{};\n  const clientId=str(q['Client ID']), hits=clients.filter(p=>str(property(p,'Client ID'))===clientId&&clientId), client=hits[0];\n  const marker='[Quote '+key+']', name=str(q['Job Title'])||'Quote '+key;\n  const existing=open.filter(p=>titleOf(p).startsWith(marker+' '));\n  const created=folders.filter(f=>f.appProperties?.sprklyQuoteKey===key);\n  if(existing.length>1||created.length>1)throw new Error('Duplicate recovery records for quote '+key);\n  const folder=created[0], page=existing[0], due=dueDate(q.Due);\n  const address=email(property(client||{},'Email'));\n  const draft=old['Draft Message ID']||'';\n  const missing=[hits.length!==1?'a unique Notion client with this Client ID':'',!address?'a valid client email':'',!str(q['Job Title'])?'job title':''].filter(Boolean);\n  const status=missing.length?'Blocked':draft&&page&&folder?'Completed':'Pending';\n  const extra={'Quote ID':key,'Client ID':clientId,'Drive URL':driveLink(folder),'Notion Job URL':page?.url||'','Draft Message ID':draft};\n  jobs.push(job(key,name,status,missing.length?'Missing '+missing.join(', '):status==='Completed'?'Kickoff ready for review':'Set up folder, Notion job, Trello card and Gmail draft',due,client?.url||'',extra));\n  if(!missing.length&&status!=='Completed')candidates.push({key,title:name,marker,due,folder:folder||null,page:page||null,email:address,client:titleOf(client),clientUrl:client.url||'',draft});\n}\nreturn result(jobs,'Approved quotes create one private workspace and one kickoff draft.',{candidate:candidates[0]||null});"
      }
    },
    {
      "id": "7b65bf7c-068e-5f50-a720-0cbb8a44cda2",
      "name": "An approved quote needs a folder",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1380,
        520
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "e1602b8f-0c23-5513-a84c-762a3490db4f",
              "leftValue": "={{ Boolean($json.candidate && !$json.candidate.folder) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "bda11a52-374d-568c-9175-fef0fa744b9f",
      "name": "Create a Drive folder for the quote",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        0,
        770
      ],
      "parameters": {
        "url": "https://www.googleapis.com/drive/v3/files",
        "method": "POST",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ ({name:$json.candidate.title+' ['+$json.candidate.key+']',mimeType:'application/vnd.google-apps.folder',parents:[$(\"Check pack settings\").first().json[\"Drive root folder ID\"]],appProperties:{sprklyQuoteKey:$json.candidate.key} }) }}",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "supportsAllDrives",
              "value": "true"
            },
            {
              "name": "fields",
              "value": "id,name,webViewLink,appProperties"
            }
          ]
        }
      }
    },
    {
      "id": "8077dafa-3465-5c87-9395-a3399a86d205",
      "name": "Record the quote folder",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        230,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Decide which work needs attention\").first().json;\nif($('Create a Drive folder for the quote').isExecuted){\n const folder=$('Create a Drive folder for the quote').first().json;\n if(!folder.id)throw new Error('Drive did not return a folder ID.');\n data.candidate.folder=folder;\n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "9689db36-6afb-5305-a664-71c61c47f404",
      "name": "An approved quote needs a job page",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        460,
        770
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "75c2f8fa-c1cc-513e-b100-81c73a225994",
              "leftValue": "={{ Boolean($json.candidate && !$json.candidate.page) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "3f7bc5ff-a4fd-5996-9b1e-285c8eb79749",
      "name": "Create the linked Notion job",
      "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[\"Jobs data source ID\"]},properties:{[$(\"Check pack settings\").first().json[\"Notion jobs title property\"]]:{title:[{type:'text',text:{content:($json.candidate.marker+' '+$json.candidate.title).slice(0,200)} }]} },children:(('Approved quote: '+$json.candidate.key+'\\nClient: '+$json.candidate.client+' · '+$json.candidate.clientUrl+'\\nDrive: https://drive.google.com/drive/folders/'+$json.candidate.folder.id).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": "17365d06-64f1-5f72-89f9-758b2089291f",
      "name": "Prepare the quote kickoff draft",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        770
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Record the quote folder\").first().json;\nif(data.candidate){\n const c=data.candidate, work=data.jobs.find(j=>j.key===c.key);\n if($('Create the linked Notion job').isExecuted){\n   c.page=$('Create the linked Notion job').first().json;\n   if(!c.page.id)throw new Error('Notion did not return a job ID.');\n }\n const drive='https://drive.google.com/drive/folders/'+c.folder.id;\n work.extra['Drive URL']=drive;\n work.extra['Notion Job URL']=c.page.url;\n work.url=c.page.url;\n c.existingDraft=c.draft;c.subject='Kickoff for '+c.title+' [quote-'+c.key+']';\n c.body='Hi '+c.client+',\\n\\nThanks for approving '+c.title+'. We’re setting up your project. Please reply with any kickoff constraints or questions.\\n\\n'+(c.due?'Current target date: '+c.due+'\\n':'')+'\\nThanks!';\n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "11c46802-dae9-5a12-beb9-ec4dc3d4d690",
      "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": "3136bc8b-a6de-5117-a1fe-9f406e853df5",
              "leftValue": "={{ Boolean($json.candidate?.email && !$json.candidate?.existingDraft) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "d2ff2357-58b9-5ad5-a894-52874d718d42",
      "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 quote kickoff draft\").first().json[\"candidate\"].subject).replace(/\"/g,'')+'\"' }}"
            },
            {
              "name": "maxResults",
              "value": "2"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "26043e14-70a3-5938-b86d-67a5bfbbcf1a",
      "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": "1e9847eb-0092-5694-bc7d-e7c0267b580b",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "29c2c1b8-78d4-5973-ba9d-515dac758d4f",
      "name": "Create the Gmail draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        230,
        1020
      ],
      "parameters": {
        "resource": "draft",
        "operation": "create",
        "subject": "={{ $(\"Prepare the quote kickoff draft\").first().json[\"candidate\"].subject }}",
        "emailType": "text",
        "message": "={{ $(\"Prepare the quote kickoff draft\").first().json[\"candidate\"].body }}",
        "options": {
          "sendTo": "={{ $(\"Prepare the quote kickoff draft\").first().json[\"candidate\"].email }}"
        }
      }
    },
    {
      "id": "9e3b6572-c807-5e54-8f1f-873195972d6e",
      "name": "Record the kickoff draft",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        1020
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$(\"Prepare the quote kickoff 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 \n work.state='Completed';work.forceCard=true;work.cardDone=false;\n work.details='Kickoff draft ready. Job checklist\\n- [ ] Confirm scope and timing\\n- [ ] Collect client files\\n- [ ] Deliver and request sign-off';\n \n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "b8f9028a-ddba-5e6c-b77e-65853deed85b",
      "name": "Preserve the job tracker checklist",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        690,
        1020
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const data=$input.first().json;\nfor(const work of data.jobs){\n if(work.state!=='Completed')continue;\n work.forceCard=true;work.cardDone=false;work.url=work.extra['Notion Job URL']||work.url;\n work.details='Kickoff draft ready. Job checklist\\n- [ ] Confirm scope and timing\\n- [ ] Collect client files\\n- [ ] Deliver and request sign-off';\n}\nreturn [{json:data}];"
      }
    },
    {
      "id": "f516e82f-288a-5e6c-b931-46c61736c3b8",
      "name": "Prepare tracker updates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const decisionNode = \"Preserve the job tracker checklist\";\nconst prefix = \"[sprkly:quote-to-job-kickoff:\";\nconst cardsNode = \"Read the Trello board\";\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": "712a40d0-9e4e-532e-b62a-9cde88006271",
      "name": "Read the Trello board",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -230,
        1380
      ],
      "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": "5ef55012-9aeb-59c4-b9de-c6e5d7ebcc40",
      "name": "Trello needs changes",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        220,
        1380
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "da56db0a-58de-516c-9d10-3ec77f060da1",
              "leftValue": "={{ $json.writes.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "29a0c2cd-e494-554a-a8ae-2b1bf79d79e8",
      "name": "Expand changed cards",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        1270
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $json.writes.map(json=>({json}));"
      }
    },
    {
      "id": "d79b0838-23f3-597d-9c1f-0b6b4143441d",
      "name": "Create or update work cards",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        1270
      ],
      "parameters": {
        "url": "={{ 'https://api.trello.com/1/cards'+($json.cardId?'/'+$json.cardId:'') }}",
        "method": "={{ $json.cardId?'PUT':'POST' }}",
        "options": {
          "timeout": 45000
        },
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "trelloApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.payload }}"
      }
    },
    {
      "id": "027dfe42-364b-5e1c-ac28-42527c550e06",
      "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": "e57826e6-1694-56bb-857d-b3a362d8ca04",
      "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": "abfbc50e-8971-5f54-8655-6acacef808e9",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "705eaef6-64fb-5081-b711-8ebec91338c7",
      "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": "ead4d654-3726-5cb2-b76d-76ad67fd549d",
      "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": "Quote to Job Kickoff 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\"] ?? \"\" }}",
            "Quote ID": "={{ $json[\"Quote ID\"] ?? \"\" }}",
            "Client ID": "={{ $json[\"Client ID\"] ?? \"\" }}",
            "Drive URL": "={{ $json[\"Drive URL\"] ?? \"\" }}",
            "Notion Job URL": "={{ $json[\"Notion Job URL\"] ?? \"\" }}",
            "Draft Message ID": "={{ $json[\"Draft Message ID\"] ?? \"\" }}"
          },
          "matchingColumns": [
            "Work Key"
          ],
          "schema": []
        }
      },
      "alwaysOutputData": true
    },
    {
      "id": "45dd6be1-68ff-5c34-a919-60ba6d6b5aa9",
      "name": "Summarize completed and pending work",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        1700
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const title = \"Quote to Job Kickoff\";\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": "a25ede45-184c-5e5a-9caf-ad2d94394988",
      "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": "Quote to Job Kickoff 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": "f3642e7b-7c3d-5d01-8413-d7247188ea84",
      "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": "e9780eba-e69e-5db6-9f4c-e4c26d329fd0",
              "leftValue": "={{ Boolean($(\"Check pack settings\").first().json[\"Digest recipient (optional)\"]) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "6b75d06f-d2ad-5f7f-aefd-58e8d021a59d",
      "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": "1be96f77-eb58-54fc-8acc-5079cdb2436f",
      "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": "9de1e511-5ffc-5b6f-8116-d08085f2317d",
              "leftValue": "={{ !$json.messages?.length }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "f42b1bc1-a885-5276-8dfe-c525b844a23b",
      "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": "cc59e9a6-b132-5fc7-8316-2137aad8f4aa",
      "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. Trello cards are matched by stable work key. Existing descriptions outside the workflow section stay editable. An optional Gmail digest uses one subject per workflow per day.",
        "width": 1315,
        "height": 117,
        "color": 6
      }
    },
    {
      "id": "643f7fdd-9819-4286-a8f0-c313a78e261c",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -830,
        812
      ],
      "parameters": {}
    },
    {
      "id": "8ecaf2c2-85b9-4345-9e2a-ddc4f077b0ec",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -610,
        812
      ],
      "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": "9bcffa9d-787f-47d8-94dc-c5d64f9a613b",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -390,
        812
      ],
      "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 Approved Quotes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Approved Quotes": {
      "main": [
        [
          {
            "node": "Read Notion clients",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Notion clients": {
      "main": [
        [
          {
            "node": "Read existing Notion job pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read existing Notion job pages": {
      "main": [
        [
          {
            "node": "Find existing kickoff folders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find existing kickoff folders": {
      "main": [
        [
          {
            "node": "Decide which work needs attention",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide which work needs attention": {
      "main": [
        [
          {
            "node": "An approved quote needs a folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "An approved quote needs a folder": {
      "main": [
        [
          {
            "node": "Create a Drive folder for the quote",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Record the quote folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a Drive folder for the quote": {
      "main": [
        [
          {
            "node": "Record the quote folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Record the quote folder": {
      "main": [
        [
          {
            "node": "An approved quote needs a job page",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "An approved quote needs a job page": {
      "main": [
        [
          {
            "node": "Create the linked Notion job",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare the quote kickoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the linked Notion job": {
      "main": [
        [
          {
            "node": "Prepare the quote kickoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare the quote kickoff 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 kickoff 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 kickoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the Gmail draft": {
      "main": [
        [
          {
            "node": "Record the kickoff draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Record the kickoff draft": {
      "main": [
        [
          {
            "node": "Preserve the job tracker checklist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preserve the job tracker checklist": {
      "main": [
        [
          {
            "node": "Read the Trello board",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the Trello board": {
      "main": [
        [
          {
            "node": "Prepare tracker updates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare tracker updates": {
      "main": [
        [
          {
            "node": "Trello needs changes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trello needs changes": {
      "main": [
        [
          {
            "node": "Expand changed cards",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare ledger rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Expand changed cards": {
      "main": [
        [
          {
            "node": "Create or update work cards",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create or update work cards": {
      "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": {}
}
