{
  "id": "B6o7xmIU5skzYTOf",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "MR Daily Visit Automation & Report",
  "tags": [],
  "nodes": [
    {
      "id": "eb7a600c-01d4-46bc-9963-065e690f8437",
      "name": "Fetch MR Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        224,
        304
      ],
      "parameters": {
        "options": {},
        "filtersUI": {
          "values": [
            {
              "lookupValue": "Pending",
              "lookupColumn": "Status"
            }
          ]
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit?usp=drivesdk",
          "cachedResultName": "MRPlanWork"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.4
    },
    {
      "id": "e4966a5f-518d-46c5-a96d-85db4aa1e0f3",
      "name": "Send Plan Email to MR",
      "type": "n8n-nodes-base.gmail",
      "position": [
        448,
        304
      ],
      "parameters": {
        "sendTo": "={{ $json.Email }}",
        "message": "=Hello {{ $json.MR_Name }},\n\n<br><br>\n\nHere is your visit plan for today:\n\n<ul>\n  <li><b>Doctor:</b> {{ $json.Visit_Doctor }}</li>\n  <li><b>Location:</b> {{ $json.Visit_Location }}</li>\n</ul>\n\nPlease update your visit status here:\n\n<a href=\"{{ $json.Form_Link }}\">Google Form</a>\n\n<br><br>\n\nHave a productive day!<br>\n- MR Automation System {{ $json.MR_Name }}",
        "options": {},
        "subject": "=Your Visit Plan for Today \u2013 {{ $json.MR_Name }}"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "b1a148ef-ac76-40f6-b1d0-2e8111004d07",
      "name": "Fetch Pending Records",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        144,
        688
      ],
      "parameters": {
        "options": {},
        "filtersUI": {
          "values": [
            {
              "lookupValue": "Pending",
              "lookupColumn": "Status"
            }
          ]
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit?usp=drivesdk",
          "cachedResultName": "MRPlanWork"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.4
    },
    {
      "id": "4fb11931-4d3b-4e57-8344-a79db509a211",
      "name": "Send Reminder Email",
      "type": "n8n-nodes-base.gmail",
      "position": [
        368,
        688
      ],
      "parameters": {
        "sendTo": "={{ $json.Email }}",
        "message": "Hello {{ $json.MR_Name }},\n\n<br><br>\n\nThis is a friendly reminder to update your visit status in the Google Form before the day ends.\n\n<br>\n\n<a href=\"{{ $json.Form_Link || 'https://forms.google.com/...' }}\">Update Visit Status</a>\n\n<br><br>\n\nThank you,<br>\nMR Automation System",
        "options": {},
        "subject": "Reminder \u2013 Please Update Today's Visit Status"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "e88a4910-1596-4553-b5b4-52940d14973e",
      "name": "Fetch Form Responses",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        80,
        1088
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": 2027534892,
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit#gid=2027534892",
          "cachedResultName": "Form Responses 1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit?usp=drivesdk",
          "cachedResultName": "MRPlanWork"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.4
    },
    {
      "id": "ef0aa4f9-5b08-47ec-a04d-1a5669d1b5e2",
      "name": "Send Summary to Manager",
      "type": "n8n-nodes-base.gmail",
      "position": [
        656,
        1088
      ],
      "parameters": {
        "sendTo": "user@example.com",
        "message": "={{\n(() => {\n  // Helper: safe JSON parse\n  function tryParseJson(s) {\n    try {\n      return JSON.parse(s);\n    } catch (e) {\n      return null;\n    }\n  }\n\n  // 1) get raw output (handles array node, direct node, or nested)\n  const candidateSources = [\n    // n8n common shapes\n    Array.isArray($json) && $json[0] ? $json[0] : null,\n    $json,\n  ];\n\n  let raw = null;\n  for (const cs of candidateSources) {\n    if (!cs) continue;\n    if (typeof cs.output === 'string' && cs.output.trim()) { raw = cs.output; break; }\n    if (cs.email_body_html || cs.email_body_plain || cs.subject) { raw = cs; break; }\n    // sometimes the node returns the JSON string in a field named 'summary' or 'text'\n    if (typeof cs.summary === 'string' && cs.summary.trim()) { raw = cs.summary; break; }\n    if (typeof cs.text === 'string' && cs.text.trim()) { raw = cs.text; break; }\n  }\n\n  // 2) If raw is a string that contains a fenced JSON block, extract it\n  let parsed = null;\n  if (typeof raw === 'string') {\n    // extract code-fenced JSON ```json ... ```\n    const fenceMatch = raw.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/i);\n    const jsonCandidate = fenceMatch ? fenceMatch[1].trim() : raw.trim();\n\n    // try parse directly if it looks like JSON; otherwise try to find first { ... }\n    parsed = tryParseJson(jsonCandidate);\n    if (!parsed) {\n      const firstBrace = jsonCandidate.indexOf('{');\n      const lastBrace = jsonCandidate.lastIndexOf('}');\n      if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {\n        const possible = jsonCandidate.slice(firstBrace, lastBrace + 1);\n        parsed = tryParseJson(possible);\n      }\n    }\n  } else if (typeof raw === 'object' && raw !== null) {\n    parsed = raw;\n  }\n\n  // If we still don't have parsed JSON, try $json directly\n  if (!parsed) parsed = ($json && Object.keys($json).length ? $json : null);\n\n  // 3) If parsing failed entirely, produce a simple fallback email\n  if (!parsed) {\n    const fallbackText = String(raw || 'Summary not available').replace(/\\n{2,}/g, '\\n\\n');\n    const htmlFallback = `<p>Hello Manager,</p><p>Here is the MR summary (unparsed):</p><pre style=\"white-space:pre-wrap;border:1px solid #ddd;padding:10px;border-radius:6px;\">${escapeHtml(fallbackText)}</pre><p>Regards,<br/>MR Automation System</p>`;\n    return htmlFallback;\n  }\n\n  // 4) If parsed already contains email_body_html or full HTML, use it directly\n  if (parsed.email_body_html && String(parsed.email_body_html).trim()) {\n    return String(parsed.email_body_html);\n  }\n\n  // 5) Build content from fields (subject, headline, bullets, details, actions, urgency)\n  const subject = parsed.subject || parsed.title || `MR Update${parsed.MR || parsed['MR name'] ? `: ${parsed['MR name'] || parsed.MR}` : ''}`;\n  const headline = parsed.headline || '';\n  const bullets = Array.isArray(parsed.summary_bullets) ? parsed.summary_bullets : (parsed.summary ? (Array.isArray(parsed.summary) ? parsed.summary : String(parsed.summary).split('\\n').filter(Boolean)) : []);\n  const details = parsed.details_paragraph || parsed.details || parsed.email_body_plain || '';\n  const actions = Array.isArray(parsed.action_items) ? parsed.action_items : (parsed.action_items ? [parsed.action_items] : []);\n  const urgency = parsed.urgency || parsed.Urgency || '';\n  const mrName = parsed['MR name'] || parsed.MR || parsed.MR_ID || '';\n  const rawFields = Array.isArray(parsed.raw_fields_used) ? parsed.raw_fields_used : (parsed.raw_fields_used ? [parsed.raw_fields_used] : []);\n  const inferred = parsed.inferred_fields || {};\n\n  // Helper: escape html\n  function escapeHtml(s) {\n    return String(s || '').replace(/[&<>\"']/g, function (m) {\n      return ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'})[m];\n    });\n  }\n\n  // Build HTML\n  let html = '';\n  html += `<div style=\"font-family:Arial,Helvetica,sans-serif;color:#111;line-height:1.45\">`;\n  html += `<p>Hello Manager,</p>`;\n  html += `<h3 style=\"margin:6px 0 8px 0;font-size:16px\">${escapeHtml(subject)}</h3>`;\n  if (headline) html += `<p style=\"margin:4px 0 12px 0\"><strong>${escapeHtml(headline)}</strong></p>`;\n\n  // urgency badge\n  if (urgency) {\n    const color = urgency.toLowerCase() === 'high' ? '#d9534f' : (urgency.toLowerCase() === 'medium' ? '#f0ad4e' : '#5cb85c');\n    html += `<p style=\"margin:6px 0\"><strong>Urgency:</strong> <span style=\"display:inline-block;padding:4px 8px;border-radius:12px;background:${color};color:#fff;font-weight:600;font-size:12px\">${escapeHtml(urgency)}</span></p>`;\n  }\n\n  // bullets\n  if (bullets && bullets.length) {\n    html += `<ul style=\"margin:8px 0 12px 18px\">`;\n    for (const b of bullets) {\n      html += `<li style=\"margin:6px 0\">${escapeHtml(String(b))}</li>`;\n    }\n    html += `</ul>`;\n  }\n\n  // details paragraph\n  if (details) {\n    html += `<div style=\"margin:8px 0 12px 0\">${escapeHtml(String(details)).replace(/\\n/g,'<br/>')}</div>`;\n  }\n\n  // action items\n  if (actions && actions.length) {\n    html += `<p style=\"margin:6px 0 6px 0\"><strong>Action Items:</strong></p>`;\n    html += `<ol style=\"margin:6px 0 12px 22px\">`;\n    for (const a of actions) html += `<li style=\"margin:6px 0\">${escapeHtml(String(a))}</li>`;\n    html += `</ol>`;\n  }\n\n  // metadata table (MR, timestamp, raw fields)\n  html += `<table style=\"border-collapse:collapse;font-size:13px;margin-top:8px\">`;\n  if (mrName) {\n    html += `<tr><td style=\"padding:6px 10px 6px 0;font-weight:600\">MR</td><td style=\"padding:6px 10px\">${escapeHtml(mrName)}</td></tr>`;\n  }\n  if (parsed.Timestamp || parsed.Normalized_Timestamp || inferred.Normalized_Timestamp) {\n    const ts = parsed.Normalized_Timestamp || parsed.Timestamp || inferred.Normalized_Timestamp;\n    html += `<tr><td style=\"padding:6px 10px 6px 0;font-weight:600\">Timestamp</td><td style=\"padding:6px 10px\">${escapeHtml(ts)}</td></tr>`;\n  }\n  if (rawFields && rawFields.length) {\n    html += `<tr><td style=\"padding:6px 10px 6px 0;font-weight:600;vertical-align:top\">Fields used</td><td style=\"padding:6px 10px\">${escapeHtml(rawFields.join(', '))}</td></tr>`;\n  }\n  // inferred fields\n  if (inferred && Object.keys(inferred).length) {\n    html += `<tr><td style=\"padding:6px 10px 6px 0;font-weight:600;vertical-align:top\">Inferred</td><td style=\"padding:6px 10px\">${escapeHtml(Object.entries(inferred).map(([k,v])=>k+': '+v).join('<br/>'))}</td></tr>`;\n  }\n  html += `</table>`;\n\n  // signature\n  html += `<p style=\"margin-top:18px\">Regards,<br/>MR Automation System${mrName ? `<br/><small>Reported by ${escapeHtml(mrName)}</small>` : ''}</p>`;\n  html += `</div>`;\n\n  // 6) Also create a plain-text fallback (optional but useful)\n  // We return html only because many email nodes use the node output as html body.\n  return html;\n})()\n}}\n",
        "options": {
          "appendAttribution": false
        },
        "subject": "MR Daily Summary Report \u2013 {{ $now.toFormat('dd MMM yyyy') }}"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "48461e38-d7ed-453c-9ea4-bd95394b5bf4",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        304,
        1088
      ],
      "parameters": {
        "text": "=You are an assistant that converts one MR visit record (JSON) into a concise manager update ready to send by email.\n\nInput: a single JSON object with fields like:\n  \"row_number\",\"Timestamp\",\"MR name\",\"Date\",\"Doctor Name\",\"Visit Status\",\"Outcome(Rx Count)\",\"Samples Given\",\n  \"Notes (Doctor Visit)\",\"Product Name\",\"Samples Distributed (Qty)\",\"Promotional Materials Used\",\"Remarks (Samples/Product)\",\n  \"Total Doctor Calls Made Today\",\"Total Chemist Calls Made Today\",\"New Doctors Added Today\",\"Feedback Type\",\n  \"Feedback Details\",\"CRM Updated?\",\"Samples Stock Updated?\",\"Daily Call Report Completed?\",\"Any support required from manager?\",\n  \"Visit Status [Not Completed]\"\n\nInstructions:\n1. Read and normalize fields. If a value clearly belongs to another field (e.g., \"Date\" contains a person name), try to infer correct mapping and note the correction in \"raw_fields_used\".\n2. Infer doctor speciality from \"Visit Status\" and \"Notes (Doctor Visit)\". If you cannot infer, set speciality to \"Not specified\".\n3. Extract key facts:\n   - MR_ID (from \"MR name\")\n   - Timestamp (use \"Timestamp\" raw value; also convert to ISO YYYY-MM-DD HH:MM:SS if possible)\n   - Doctor name and location/hospital (from \"Doctor Name\" and related fields)\n   - Doctor speciality(s)\n   - Key discussion topics and doctor interest (explicitly call out \"bulk order\" or \"product interest\" if present)\n   - Outcome metrics (Rx Count, Samples Given, Samples Distributed)\n   - CRM / Samples stock / Daily report status\n   - Any manager support requested\n4. Determine urgency:\n   - High: manager support requested OR bulk order confirmed & immediate approval/logistics needed.\n   - Medium: doctor expressed interest (e.g., potential bulk order) but details missing.\n   - Low: routine visit, no follow-up required.\n5. Produce ONE valid JSON object (no extra text) with these keys:\n{\n  \"subject\": \"<one-line email subject>\",\n  \"to\": \"<optional placeholder, e.g. manager@example.com>\",\n  \"headline\": \"<one-line headline>\",\n  \"summary_bullets\": [\"<short bullet 1>\", \"<short bullet 2>\", \"...\"],\n  \"details_paragraph\": \"<1-2 short paragraphs, 40-80 words total>\",\n  \"action_items\": [\"<concrete action item 1>\", \"...\"],\n  \"urgency\": \"<Low|Medium|High>\",\n  \"email_body_plain\": \"<full plain-text email body ready to send (include subject at top if needed)>\",\n  \"email_body_html\": \"<optional short HTML version suitable for email clients (basic tags only)>\",\n  \"raw_fields_used\": [\"list of input field names used\"],\n  \"inferred_fields\": {\"Doctor_Speciality\":\"...\", \"Normalized_Timestamp\":\"...\"} \n}\n6. Formatting rules:\n   - subject: max 10 words, include MR ID and Doctor name.\n   - headline: 8\u201312 words.\n   - summary_bullets: 3\u20134 bullets, each \u2264 25 words.\n   - details_paragraph: 1\u20132 paragraphs total \u2264 80 words explaining context and next steps.\n   - action_items: 1\u20134 short, concrete steps, each imperative (e.g., \"MR to confirm quantity\").\n   - email_body_plain: include a 1-line subject, the headline, bullets, details, and action items; close with \"Regards,\\n[MR Name]\" if MR name available.\n   - If fields are missing, explicitly state which fields were missing inside \"details_paragraph\".\n7. Special flags:\n   - If \"Visit Status\" or notes mention \"bulk order\", add action item: \"Confirm bulk order quantity & preferred SKUs\" and set urgency to at least Medium.\n   - If \"CRM Updated?\" or \"Samples Stock Updated?\" is \"No\" or blank, add action item: \"Update CRM and Samples Stock\" and mark it in summary_bullets.\n   - If \"Any support required from manager?\" is non-empty, include it verbatim as a top action item and set urgency to High unless text indicates otherwise.\n8. Output must be valid JSON only. Do not add any commentary or additional text.\n9. Use actual input field values when present (they will be referenced as {{$json[\"FIELD_NAME\"]}} in this environment); if a field is blank, omit it from \"raw_fields_used\".\n\nEnd of instructions.\n",
        "options": {},
        "promptType": "define"
      },
      "typeVersion": 3
    },
    {
      "id": "02e6f15b-f88a-46ca-a014-fd58877d8116",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        384,
        1312
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "d43feee7-beaf-43e3-9bb1-899ef7fc0280",
      "name": "Update row in sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        672,
        304
      ],
      "parameters": {
        "columns": {
          "value": {
            "id": "={{ $('Fetch MR Sheet').item.json.id }}",
            "Date": "={{ $('Fetch MR Sheet').item.json.Date }}",
            "Email": "={{ $('Fetch MR Sheet').item.json.Email }}",
            "Status": "Assigned",
            "MR_Name": "={{ $('Fetch MR Sheet').item.json.MR_Name }}",
            "Form_Link": "={{ $('Fetch MR Sheet').item.json.Form_Link }}",
            "Visit_Doctor": "={{ $('Fetch MR Sheet').item.json.Visit_Doctor }}",
            "Visit_Location": "={{ $('Fetch MR Sheet').item.json.Visit_Location }}"
          },
          "schema": [
            {
              "id": "id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "MR_Name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "MR_Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Email",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Email",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Visit_Doctor",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Visit_Doctor",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Visit_Location",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Visit_Location",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Form_Link",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Form_Link",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "row_number",
              "type": "number",
              "display": true,
              "removed": true,
              "readOnly": true,
              "required": false,
              "displayName": "row_number",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "id"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "update",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit?usp=drivesdk",
          "cachedResultName": "MRPlanWork"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "24db74c3-ef2d-4115-b9da-07cc4b0b9125",
      "name": "Schedule To Assign Work",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        0,
        304
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 9
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "90e39a29-8b34-4b92-92ab-a93099449b6a",
      "name": "Schedule For Remind Pending work",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -80,
        688
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 18
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "dbb1366f-09ef-40b5-ab22-44113e668e28",
      "name": "Schedule for Summary Update",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -144,
        1088
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 23
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "07f6d282-a7c6-430a-8941-6c726fdb5b68",
      "name": "Update row in sheet1",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        592,
        688
      ],
      "parameters": {
        "columns": {
          "value": {
            "id": "={{ $('Fetch Pending Records').item.json.id }}",
            "Date": "={{ $('Fetch Pending Records').item.json.Date }}",
            "Email": "={{ $('Fetch Pending Records').item.json.Email }}",
            "Status": "Assigned",
            "MR_Name": "={{ $('Fetch Pending Records').item.json.MR_Name }}",
            "Reminder": "Yes",
            "Form_Link": "={{ $('Fetch Pending Records').item.json.Form_Link }}",
            "VisitType": "={{ $('Fetch Pending Records').item.json.VisitType }}",
            "Speciality": "={{ $('Fetch Pending Records').item.json.Speciality }}",
            "Doctor name": "={{ $('Fetch Pending Records').item.json[\"Doctor name\"] }}",
            "Clinic/Hospital": "={{ $('Fetch Pending Records').item.json[\"Clinic/Hospital\"] }}",
            "Expected Outcome": "={{ $('Fetch Pending Records').item.json[\"Expected Outcome\"] }}",
            "Objective To Visit": "={{ $('Fetch Pending Records').item.json[\"Objective To Visit\"] }}"
          },
          "schema": [
            {
              "id": "id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "MR_Name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "MR_Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Email",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Email",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Doctor name",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Doctor name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Speciality",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Speciality",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Clinic/Hospital",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Clinic/Hospital",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "VisitType",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "VisitType",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Objective To Visit",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Objective To Visit",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Expected Outcome",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Expected Outcome",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Form_Link",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Form_Link",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Reminder",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Reminder",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "row_number",
              "type": "number",
              "display": true,
              "removed": true,
              "readOnly": true,
              "required": false,
              "displayName": "row_number",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "id"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "update",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VQD8qUpEv28IF7MUo9D8c9lTkI6csF_3jffTxpOXpPs/edit?usp=drivesdk",
          "cachedResultName": "MRPlanWork"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "cda49ce5-48e6-43ba-b2a2-acf124239c1e",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -832,
        368
      ],
      "parameters": {
        "width": 464,
        "height": 592,
        "content": "## How it works\nThis workflow helps teams automate the daily routine of assigning doctor visits to Medical Representatives (MRs), collecting their updates, and sending a clean end-of-day summary to managers. Each morning, it reads the MR plan from Google Sheets and emails every MR their visit list along with a Google Form link for reporting. In the evening, it checks who hasn\u2019t submitted their form yet and sends a reminder. At night, it pulls all the form responses, runs them through an AI prompt to create short, structured summaries, and finally sends a consolidated report to the manager.\n\nThe goal is to reduce manual coordination, make reporting consistent, and ensure managers always receive timely, well-formatted updates.\n\n## Setup steps\nConnect Google Sheets and link your MR Plan sheet + Form Responses sheet.\nUpdate the sheet IDs/GIDs inside the workflow nodes.\nAdd your Gmail or Outlook credentials for sending emails.\nInsert your Google Form link into the MR Plan sheet.\nAdd your OpenAI credentials in the AI Agent node.\nAdjust the three Schedule nodes to match your working hours.\nTest the workflow once end-to-end before publishing."
      },
      "typeVersion": 1
    },
    {
      "id": "6a3f3e1b-2623-43c2-b989-47e732b1d7e9",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -240,
        128
      ],
      "parameters": {
        "width": 1296,
        "height": 320,
        "content": "## Daily Work Assignment\n**Every morning, a scheduled trigger starts the workflow at the defined time. It first reads the MR work allocation sheet and collects all rows where the visit plan is still marked as \u201cPending.\u201d For each of these entries, the workflow sends a personalized email to the respective MR, containing their assigned doctor visit details and the Google Form link for submitting updates. After each email is successfully sent, the workflow updates that specific row in the Google Sheet by changing the status from \u201cPending\u201d to \u201cAssigned,\u201d ensuring the same task is not reassigned and preparing the sheet for reminder and reporting steps later in the day.** "
      },
      "typeVersion": 1
    },
    {
      "id": "7384b445-f7b9-4203-a8f9-d047fd1e7ded",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -256,
        512
      ],
      "parameters": {
        "width": 1312,
        "height": 336,
        "content": "## Reminder Flow\n**Each evening, a scheduled trigger starts the reminder workflow at the set time. It reads the work allocation sheet and identifies all records where the visit is still marked as \u201cPending,\u201d meaning the MR has not yet submitted their daily update. For every pending entry, the workflow sends a reminder email to the respective MR with the same Google Form link, encouraging them to complete their visit report before the end of the day. After sending the reminder, the workflow updates that row in the Google Sheet by marking \u201cReminder Sent,\u201d helping supervisors track who was notified and ensuring the same MR isn\u2019t reminded multiple times.** "
      },
      "typeVersion": 1
    },
    {
      "id": "ec2df301-3ae2-4a2b-8761-2a992afc49e0",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -256,
        944
      ],
      "parameters": {
        "width": 1312,
        "height": 496,
        "content": "## Reporting and Summary\n**At the end of the day, a scheduled trigger starts the summary workflow at the designated time. It retrieves all Google Form responses submitted by the MRs throughout the day, capturing details of their doctor visits and activity updates. Each response is then processed by the AI agent, which converts the raw form data into a clean, structured summary based on a predefined template\u2014highlighting key points, outcomes, concerns, and urgency. Once all entries are processed, the workflow compiles the summaries and sends a detailed completion email to the manager, giving a clear overview of the work assigned for the day and the status of each MR\u2019s visit.** "
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "f3562aee-cf2c-4126-8c1d-9ab64d3cae21",
  "connections": {
    "AI Agent": {
      "main": [
        [
          {
            "node": "Send Summary to Manager",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch MR Sheet": {
      "main": [
        [
          {
            "node": "Send Plan Email to MR",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Send Reminder Email": {
      "main": [
        [
          {
            "node": "Update row in sheet1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Form Responses": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Pending Records": {
      "main": [
        [
          {
            "node": "Send Reminder Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Plan Email to MR": {
      "main": [
        [
          {
            "node": "Update row in sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule To Assign Work": {
      "main": [
        [
          {
            "node": "Fetch MR Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule for Summary Update": {
      "main": [
        [
          {
            "node": "Fetch Form Responses",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule For Remind Pending work": {
      "main": [
        [
          {
            "node": "Fetch Pending Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}