{
  "id": "tlSpKOkePu86NbpC",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Send Automated Medication Reminders to Patients",
  "tags": [],
  "nodes": [
    {
      "id": "9d32e6a7-23c6-4b7f-962f-0c89922dab7d",
      "name": "New Sent Prescriptions",
      "type": "n8n-nodes-base.filter",
      "position": [
        80,
        0
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "caseSensitive": true
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "1",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.prescription_status }}",
              "rightValue": "sent"
            },
            {
              "id": "2",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              },
              "leftValue": "={{ $json.reminders_created }}",
              "rightValue": "yes"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "5d442586-a4b6-4598-a18a-b37b0df3c937",
      "name": "Create Reminder Schedule",
      "type": "n8n-nodes-base.code",
      "position": [
        300,
        0
      ],
      "parameters": {
        "jsCode": "// Create simple reminder schedule\nconst items = $input.all();\n\nreturn items.map(item => {\n  const data = item.json;\n  \n  // Parse frequency (default 3 times daily)\n  const timesPerDay = parseInt(data.times_per_day) || 3;\n  const durationDays = parseInt(data.duration_days) || 7;\n  \n  // Standard time slots\n  const timeSlots = {\n    1: ['09:00'],\n    2: ['09:00', '21:00'], \n    3: ['08:00', '14:00', '20:00'],\n    4: ['08:00', '12:00', '16:00', '20:00']\n  };\n  \n  const slots = timeSlots[timesPerDay] || timeSlots[3];\n  const startDate = new Date(data.start_date || new Date());\n  \n  // Create reminders for each day and time\n  const reminders = [];\n  for (let day = 0; day < durationDays; day++) {\n    slots.forEach(time => {\n      const reminderDate = new Date(startDate);\n      reminderDate.setDate(startDate.getDate() + day);\n      const [hours, minutes] = time.split(':');\n      reminderDate.setHours(hours, minutes, 0, 0);\n      \n      if (reminderDate > new Date()) {\n        reminders.push({\n          prescription_id: data.prescription_id,\n          patient_name: data.patient_name,\n          patient_phone: data.patient_phone,\n          patient_email: data.patient_email,\n          medication: data.medication,\n          dosage: data.dosage,\n          reminder_time: reminderDate.toISOString(),\n          day_number: day + 1,\n          time_slot: time,\n          status: 'scheduled'\n        });\n      }\n    });\n  }\n  \n  return {\n    json: {\n      ...data,\n      reminders: reminders,\n      total_reminders: reminders.length\n    }\n  };\n});"
      },
      "typeVersion": 2
    },
    {
      "id": "cf6ec37b-dc06-4b43-9c3d-710e0fc6559c",
      "name": "Save Reminders",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        520,
        0
      ],
      "parameters": {
        "columns": {
          "value": {},
          "schema": [],
          "mappingMode": "autoMapInputData",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "appendOrUpdate",
        "sheetName": "Reminders",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "=0987654e3rtyhujhgfdsa"
        },
        "authentication": "serviceAccount"
      },
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4
    },
    {
      "id": "90bc4f7d-a268-401b-a396-a558cd1b69c9",
      "name": "Mark as Processed",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        740,
        0
      ],
      "parameters": {
        "columns": {
          "value": {},
          "schema": [],
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "prescription_id"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "update",
        "sheetName": "Prescriptions",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_GOOGLE_SHEET_ID"
        },
        "authentication": "serviceAccount"
      },
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4
    },
    {
      "id": "6c79fccb-2341-4691-883d-bb15cd535c7a",
      "name": "Check Every 10 Minutes",
      "type": "n8n-nodes-base.cron",
      "position": [
        -140,
        360
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "5f7038d6-ee04-405a-8fe8-56ed35788e48",
      "name": "Get All Reminders",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        80,
        360
      ],
      "parameters": {
        "options": {},
        "sheetName": "Reminders",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "=YOUR_GOOGLE_SHEET_ID"
        },
        "authentication": "serviceAccount"
      },
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4
    },
    {
      "id": "5f896001-4438-45f5-836d-f64f1db05ad4",
      "name": "Find Due Reminders",
      "type": "n8n-nodes-base.code",
      "position": [
        300,
        360
      ],
      "parameters": {
        "jsCode": "// Find reminders due now\nconst items = $input.all();\nconst now = new Date();\nconst bufferMinutes = 10;\n\nconst dueReminders = items.filter(item => {\n  const data = item.json;\n  \n  if (data.status !== 'scheduled') return false;\n  \n  const reminderTime = new Date(data.reminder_time);\n  const timeDiff = (now - reminderTime) / (1000 * 60);\n  \n  return timeDiff >= 0 && timeDiff <= bufferMinutes;\n});\n\nreturn dueReminders.map(reminder => ({\n  json: {\n    ...reminder.json,\n    message: `\ud83d\udc8a Medication Reminder\\n\\nHi ${reminder.json.patient_name}!\\n\\nTime for: ${reminder.json.medication}\\nDosage: ${reminder.json.dosage}\\nTime: ${reminder.json.time_slot}\\nDay ${reminder.json.day_number}\\n\\nReply 'TAKEN' to confirm.`\n  }\n}));"
      },
      "typeVersion": 2
    },
    {
      "id": "5b988a29-b3c0-49c6-8945-f88c4aab8226",
      "name": "Send WhatsApp",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        520,
        260
      ],
      "parameters": {
        "textBody": "Hello [Patient Name],  This is a friendly reminder for your prescribed medication schedule:  Medicine: [Medicine Name] Dosage: [Dosage] Time: [Time Slot]  Please take your medicine as per the prescribed timings to ensure the best results for your treatment. If you\u2019ve already taken your dose, you can ignore this reminder.  Stay well, [Your Clinic/Hospital Name]",
        "operation": "send",
        "phoneNumberId": "=+9199999999999999",
        "additionalFields": {},
        "recipientPhoneNumber": "=+9199888777777"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "7bef3271-5c4e-4762-bf33-37934232553b",
      "name": "Mark as Sent",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        740,
        360
      ],
      "parameters": {
        "columns": {
          "value": {},
          "schema": [],
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "prescription_id",
            "reminder_time"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "update",
        "sheetName": "Reminders",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_GOOGLE_SHEET_ID"
        },
        "authentication": "serviceAccount"
      },
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4
    },
    {
      "id": "71ac37e9-cc85-486b-a4c9-3602a348ccc2",
      "name": "Watch Sheet For Trigger",
      "type": "n8n-nodes-base.googleSheetsTrigger",
      "position": [
        -140,
        0
      ],
      "parameters": {
        "event": "rowUpdate",
        "options": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        },
        "sheetName": {
          "__rl": true,
          "mode": "id",
          "value": "=xdfr8iujhnb"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "=nju7tfr32"
        }
      },
      "credentials": {
        "googleSheetsTriggerOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "8a3e2ccf-311c-49b4-bf70-c09bab6960ee",
      "name": "Send email",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        520,
        460
      ],
      "parameters": {
        "text": "Hello [Patient Name],\n\nThis is a friendly reminder for your prescribed medication schedule:\n\nMedicine: [Medicine Name]\nDosage: [Dosage]\nTime: [Time Slot]\n\nPlease take your medicine as per the prescribed timings to ensure the best results for your treatment.\nIf you\u2019ve already taken your dose, you can ignore this reminder.\n\nStay well,\n[Your Clinic/Hospital Name]",
        "options": {},
        "subject": "\ud83d\udc8a Medication Reminder",
        "toEmail": "={{ $json.patient_email }}",
        "fromEmail": "user@example.com"
      },
      "credentials": {
        "smtp": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2
    },
    {
      "id": "e99dc597-81f4-4d4d-80db-39d7978ab3cd",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -660,
        -40
      ],
      "parameters": {
        "width": 600,
        "height": 180,
        "content": "### **Part 1: Schedule Creation**\n1. **Watch Sheet** \u2192 Monitors for \"sent\" prescriptions\n2. **Filter New** \u2192 Only processes unscheduled prescriptions  \n3. **Create Schedule** \u2192 Generates reminder times automatically\n4. **Save Reminders** \u2192 Stores schedule in sheet\n5. **Mark Processed** \u2192 Prevents duplicate scheduling\n"
      },
      "typeVersion": 1
    },
    {
      "id": "8df6854b-7213-45a4-88b0-f2c0d456c313",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -660,
        320
      ],
      "parameters": {
        "color": 3,
        "width": 540,
        "content": "### **Part 2: Send Reminders** \n6. **Cron Timer** \u2192 Checks every 10 minutes\n7. **Get Reminders** \u2192 Retrieves all scheduled reminders\n8. **Find Due** \u2192 Identifies reminders due now\n9. **Send Messages** \u2192 WhatsApp + Email simultaneously\n10. **Mark Sent** \u2192 Updates status to prevent duplicates"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "d53eb734-8931-4951-a88e-b898f3963191",
  "connections": {
    "Send email": {
      "main": [
        [
          {
            "node": "Mark as Sent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send WhatsApp": {
      "main": [
        [
          {
            "node": "Mark as Sent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Reminders": {
      "main": [
        [
          {
            "node": "Mark as Processed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get All Reminders": {
      "main": [
        [
          {
            "node": "Find Due Reminders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Due Reminders": {
      "main": [
        [
          {
            "node": "Send WhatsApp",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Every 10 Minutes": {
      "main": [
        [
          {
            "node": "Get All Reminders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New Sent Prescriptions": {
      "main": [
        [
          {
            "node": "Create Reminder Schedule",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Watch Sheet For Trigger": {
      "main": [
        [
          {
            "node": "New Sent Prescriptions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Reminder Schedule": {
      "main": [
        [
          {
            "node": "Save Reminders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}