{
  "name": "FlowPantry - Log business miles from Google Calendar jobs (Maps + Sheets)",
  "nodes": [
    {
      "id": "dd39474f-e080-41bc-a724-93fed207d2c7",
      "name": "Schedule: end of day",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 18
            }
          ]
        }
      }
    },
    {
      "id": "410c923d-138e-4d60-8a41-15d93c1af4af",
      "name": "Your settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        300
      ],
      "parameters": {
        "mode": "manual",
        "assignments": {
          "assignments": [
            {
              "id": "bc8790bc-0eb7-4238-a4bd-7443dd7ccc14",
              "name": "BUSINESS_NAME",
              "value": "YOUR BUSINESS",
              "type": "string"
            },
            {
              "id": "7c106c1c-75ac-498e-9142-c8d736d802b6",
              "name": "OWNER_EMAIL",
              "value": "you@yourdomain.com",
              "type": "string"
            },
            {
              "id": "22b96221-009a-4cee-9185-3ce3b805291f",
              "name": "FROM_EMAIL",
              "value": "Mileage bot <mileage@yourdomain.com>",
              "type": "string"
            },
            {
              "id": "3f3b7108-b432-45e4-a889-4b4f6ab125df",
              "name": "HOME_BASE",
              "value": "YOUR SHOP ADDRESS, City, ST ZIP",
              "type": "string"
            },
            {
              "id": "4875eb75-26fb-4a8e-b2c0-e713fa92c5d2",
              "name": "TRIP_MODE",
              "value": "round_trip",
              "type": "string"
            },
            {
              "id": "e7a4cfba-326c-42b5-a0fc-d736de22ddc4",
              "name": "SKIP_KEYWORDS",
              "value": "personal,pto,vacation,holiday,ooo,out of office",
              "type": "string"
            },
            {
              "id": "2e3b75fa-d3df-46a9-b05c-81ea9eaf1e4a",
              "name": "MAPS_API_KEY",
              "value": "YOUR_GOOGLE_MAPS_API_KEY",
              "type": "string"
            },
            {
              "id": "7b90f9ea-12fe-4b5a-b8e9-cb4aba99faf2",
              "name": "RATE_H1",
              "value": 0.725,
              "type": "number"
            },
            {
              "id": "a27e8706-99c6-4570-83aa-8ecd27a54a6e",
              "name": "RATE_H2",
              "value": 0.76,
              "type": "number"
            },
            {
              "id": "26f02a18-49f3-4e9c-b2e3-9d8f092c7d0e",
              "name": "RATE_CUTOVER",
              "value": "2026-07-01",
              "type": "string"
            },
            {
              "id": "4c39c835-076d-4074-9374-6870e488188f",
              "name": "REVIEW_OVER_MILES",
              "value": 200,
              "type": "number"
            }
          ]
        },
        "includeOtherFields": true,
        "include": "all",
        "options": {}
      }
    },
    {
      "id": "01292121-0f9a-44bf-8c71-7bb5b93365b1",
      "name": "Get today's calendar events",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        480,
        300
      ],
      "parameters": {
        "resource": "event",
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "list",
          "value": "primary"
        },
        "returnAll": true,
        "timeMin": "={{ $now.startOf('day').toISO() }}",
        "timeMax": "={{ $now.endOf('day').toISO() }}",
        "options": {
          "recurringEventHandling": "expand"
        }
      }
    },
    {
      "id": "082fe4e8-6b9a-4462-8c3e-66206739b7d4",
      "name": "Pick job stops",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// Keep calendar events that look like job stops, then emit one driving leg per stop.\n// TRIP_MODE: round_trip (home→job→home), one_way (home→job), chain (home→job1→job2→…→home).\nconst s = $('Your settings').first().json;\nconst home = String(s.HOME_BASE || '').trim();\nconst mode = String(s.TRIP_MODE || 'round_trip').toLowerCase();\nconst skip = String(s.SKIP_KEYWORDS || 'personal,pto,vacation,holiday,ooo,out of office')\n  .split(',').map(x => x.trim().toLowerCase()).filter(Boolean);\nconst events = $input.all().map(i => i.json);\n\nfunction loc(e) {\n  if (!e) return '';\n  if (typeof e.location === 'string') return e.location.trim();\n  if (e.location && typeof e.location === 'object') return String(e.location.displayName || e.location.value || '').trim();\n  return '';\n}\nfunction startMs(e) {\n  const raw = (e.start && (e.start.dateTime || e.start.date)) || e.start || '';\n  const t = Date.parse(raw);\n  return Number.isFinite(t) ? t : 0;\n}\nfunction dateYmd(e) {\n  const raw = (e.start && (e.start.dateTime || e.start.date)) || '';\n  if (!raw) return new Date().toISOString().slice(0, 10);\n  return String(raw).slice(0, 10);\n}\n\nconst stops = [];\nfor (const e of events) {\n  if (!e || e.status === 'cancelled') continue;\n  const place = loc(e);\n  if (!place) continue;\n  const title = String(e.summary || e.title || '').trim();\n  const hay = (title + ' ' + place + ' ' + String(e.description || '')).toLowerCase();\n  if (skip.some(k => hay.includes(k))) continue;\n  if (!home) continue;\n  stops.push({\n    event_id: String(e.id || e.iCalUID || `${title}|${place}|${dateYmd(e)}`),\n    title: title || 'Job',\n    location: place,\n    purpose: title || 'Business trip',\n    trip_date: dateYmd(e),\n    start_iso: (e.start && (e.start.dateTime || e.start.date)) || '',\n    end_iso: (e.end && (e.end.dateTime || e.end.date)) || '',\n    html_link: e.htmlLink || '',\n    _ms: startMs(e),\n  });\n}\nstops.sort((a, b) => a._ms - b._ms);\n\nconst out = [];\nif (mode === 'chain') {\n  let prev = home;\n  for (let i = 0; i < stops.length; i++) {\n    const st = stops[i];\n    out.push({ json: { ...st, origin: prev, destination: st.location, leg: 'to_job', trip_mode: mode, home_base: home } });\n    prev = st.location;\n  }\n  if (stops.length) {\n    const last = stops[stops.length - 1];\n    out.push({ json: {\n      event_id: last.event_id + '|return',\n      title: last.title + ' (return home)',\n      location: home,\n      purpose: 'Return to base after ' + last.title,\n      trip_date: last.trip_date,\n      start_iso: last.end_iso || last.start_iso,\n      end_iso: '',\n      html_link: last.html_link,\n      origin: last.location,\n      destination: home,\n      leg: 'return_home',\n      trip_mode: mode,\n      home_base: home,\n    }});\n  }\n} else if (mode === 'one_way') {\n  for (const st of stops) {\n    out.push({ json: { ...st, origin: home, destination: st.location, leg: 'to_job', trip_mode: mode, home_base: home } });\n  }\n} else { // round_trip\n  for (const st of stops) {\n    out.push({ json: { ...st, origin: home, destination: st.location, leg: 'round_trip', trip_mode: 'round_trip', home_base: home } });\n  }\n}\nreturn out;"
      }
    },
    {
      "id": "a17d7ca0-6eda-4c6a-bfd4-6d1bac80953e",
      "name": "Get driving distance",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        960,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "https://routes.googleapis.com/directions/v2:computeRoutes",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "X-Goog-Api-Key",
              "value": "={{ $('Your settings').first().json.MAPS_API_KEY }}"
            },
            {
              "name": "X-Goog-FieldMask",
              "value": "routes.distanceMeters,routes.duration"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ origin: { address: $json.origin }, destination: { address: $json.destination }, travelMode: 'DRIVE', routingPreference: 'TRAFFIC_UNAWARE', units: 'IMPERIAL' }) }}",
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "d7d5f8c2-9ca5-42b8-b3f3-6fba42db84f2",
      "name": "Apply IRS rate",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        300
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "language": "javaScript",
        "jsCode": "// Turn Routes API meters into IRS-rate miles and a sheet row.\nconst s = $('Your settings').first().json;\nconst trip = $('Pick job stops').item.json;\nconst resp = $input.item.json;\n\nconst route = ((resp.routes || [])[0]) || null;\nconst meters = (route && route.distanceMeters != null) ? Number(route.distanceMeters) : NaN;\nconst apiErr = (resp.error && (resp.error.message || resp.error.status)) || resp.message || '';\nlet status = 'OK';\nif (!Number.isFinite(meters)) {\n  status = apiErr ? String(apiErr).slice(0, 120) : (resp.error ? 'API_ERROR' : 'NO_ROUTE');\n}\nlet oneWayMiles = Number.isFinite(meters) ? Math.round((meters / 1609.344) * 10) / 10 : null;\nlet miles;\nlet miles_note;\nif (trip.leg === 'round_trip' && oneWayMiles != null) {\n  miles = Math.round(oneWayMiles * 2 * 10) / 10;\n  miles_note = 'one_way=' + oneWayMiles + '; logged as round trip';\n} else {\n  miles = oneWayMiles;\n  miles_note = trip.leg || '';\n}\n\nconst cutover = String(s.RATE_CUTOVER || '2026-07-01');\nconst rateH1 = Number(s.RATE_H1 != null ? s.RATE_H1 : 0.725);\nconst rateH2 = Number(s.RATE_H2 != null ? s.RATE_H2 : 0.76);\nconst maxMiles = Number(s.REVIEW_OVER_MILES != null ? s.REVIEW_OVER_MILES : 200);\nconst rate = (trip.trip_date >= cutover) ? rateH2 : rateH1;\nconst deduction = (miles != null) ? Math.round(miles * rate * 100) / 100 : null;\n\nconst reasons = [];\nif (status !== 'OK') reasons.push('maps: ' + status);\nif (miles == null) reasons.push('no distance');\nif (miles != null && miles <= 0) reasons.push('zero miles');\nif (miles != null && miles > maxMiles) reasons.push('over ' + maxMiles + ' miles — check address');\nif (!trip.location) reasons.push('missing destination');\nconst rateYear = cutover.slice(0, 4);\nif (String(trip.trip_date).slice(0, 4) !== rateYear) reasons.push('rates in Your settings are for ' + rateYear + ' — update RATE_H1/RATE_H2/RATE_CUTOVER');\nconst rowStatus = reasons.length ? 'needs_review' : 'auto';\n\nreturn {\n  json: {\n    'Trip Date': trip.trip_date,\n    'Event': trip.title,\n    'Purpose': trip.purpose,\n    'Origin': trip.origin,\n    'Destination': trip.destination,\n    'Leg': trip.leg,\n    'Miles': miles,\n    'Rate': rate,\n    'Deduction': deduction,\n    'Status': rowStatus,\n    'Review Notes': reasons.join('; '),\n    'Trip Mode': trip.trip_mode,\n    'Miles Note': miles_note,\n    'Maps Status': status,\n    'Event ID': trip.event_id,\n    'Calendar Link': trip.html_link || '',\n  }\n};\n"
      }
    },
    {
      "id": "b5be19ae-58d2-4f10-83f2-74402e2e3075",
      "name": "Skip repeat event legs",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        1440,
        300
      ],
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "dedupeValue": "={{ $json['Event ID'] }}",
        "options": {}
      }
    },
    {
      "id": "d1ac843a-196e-44a1-8bd2-3b76a278da7b",
      "name": "Add to mileage sheet",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1680,
        300
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "3dd8146b-8aa9-4607-8b7a-39e1a8068932",
      "name": "Needs review?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1920,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "405f897f-4eee-4c86-a82c-2d4a2d0b66eb",
              "leftValue": "={{ $json.Status }}",
              "rightValue": "needs_review",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "f03cebba-e97d-4372-9dcd-f619ef2237ca",
      "name": "Email me: mileage to check",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2160,
        200
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.resend.com/emails",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ from: $('Your settings').first().json.FROM_EMAIL, to: $('Your settings').first().json.OWNER_EMAIL, subject: 'Check mileage: ' + ($json.Event || 'trip') + ' (' + ($json.Miles == null ? '?' : $json.Miles) + ' mi)', text: 'A mileage row was logged as needs_review.\\n\\nWhy: ' + $json['Review Notes'] + '\\n\\nDate: ' + $json['Trip Date'] + '\\nEvent: ' + $json.Event + '\\nFrom: ' + $json.Origin + '\\nTo: ' + $json.Destination + '\\nMiles: ' + $json.Miles + '\\nRate: $' + $json.Rate + '/mi\\nDeduction: $' + $json.Deduction + '\\n\\nCalendar: ' + $json['Calendar Link'] + '\\n\\nFix the row in your mileage sheet (correct miles or delete it) and set Status to reviewed.' }) }}",
        "options": {}
      }
    }
  ],
  "connections": {
    "Schedule: end of day": {
      "main": [
        [
          {
            "node": "Your settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Your settings": {
      "main": [
        [
          {
            "node": "Get today's calendar events",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get today's calendar events": {
      "main": [
        [
          {
            "node": "Pick job stops",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pick job stops": {
      "main": [
        [
          {
            "node": "Get driving distance",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply IRS rate": {
      "main": [
        [
          {
            "node": "Skip repeat event legs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip repeat event legs": {
      "main": [
        [
          {
            "node": "Add to mileage sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add to mileage sheet": {
      "main": [
        [
          {
            "node": "Needs review?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Needs review?": {
      "main": [
        [
          {
            "node": "Email me: mileage to check",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Get driving distance": {
      "main": [
        [
          {
            "node": "Apply IRS rate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "versionId": "dc7f2416-5940-42a2-adf5-a3c23c9b804e",
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
