Pharmacy inventory alerts for low stock & expiring medicine with Google Sheets
This n8n workflow monitors pharmacy inventory stored in a Google Sheet, checks daily for low stock or near-expiry medicines, and sends alerts to the pharmacist via email, ensuring timely restocking and waste prevention.
Why Use It
This workflow automates inventory management for pharmacies, reducing the risk of stockouts or expired medicines, saving time, minimizing losses, and ensuring compliance with safety standards by providing proactive alerts.
How to Import It
- Download the Workflow JSON: Obtain the workflow file from the n8n template or create it based on this document.
- Import into n8n: In your n8n instance, go to "Workflows," click the three dots, select "Import from File," and upload the JSON.
- Configure Credentials: Set up Google Sheets, email (e.g., SMTP), and optional SMS (e.g., Twilio) credentials in n8n.
- Run the Workflow: Activate the scheduled trigger and test with a sample Google Sheet.
System Architecture
- Daily Stock Check (9 AM): Automated trigger to monitor inventory levels
- Fetch Stock Data: Retrieves current medicine data from Google Sheets
- Wait For All Data: Ensures complete data retrieval before processing
- Check Expiry Date and Low Stock: Analyzes inventory for alerts
- Update Google Sheet: Records alert status and timestamps
- Send Email Alert: Notifies pharmacist of low stock and expiry issues
Google Sheet File Structure
- Sheet Name:
PharmacyInventory - Range:
A1:E20(or adjust based on needs)
| A | B | C | D | E | |------------|---------------|------------|---------------|---------------| | medicine_name | stock_quantity | expiry_date | alert_status | last_checked | | Paracetamol | 15 | 2025-09-15 | Notified | 2025-08-08 | | Aspirin | 5 | 2025-08-20 | Pending | 2025-08-07 | | Ibuprofen | 20 | 2026-01-10 | - | 2025-08-08 |
- Columns:
medicine_name: Name of the medicine.stock_quantity: Current stock level (e.g., number of units).expiry_date: Expiry date of the medicine (e.g., YYYY-MM-DD).alert_status: Status of the alert (e.g., Pending, Notified, - for no alert).last_checked: Date of the last inventory check.
Customization Ideas
- Adjust Thresholds: Change the low stock threshold (e.g., from 10 to 5) or expiry window (e.g., from 30 to 15 days).
- Add SMS Alerts: Integrate Twilio or another SMS service for additional notifications.
- Incorporate Barcode Scanning: Add a node to import inventory updates via barcode scanners.
- Dashboard Integration: Connect to a dashboard (e.g., Google Data Studio) for real-time inventory tracking.
- Automated Restock Orders: Add logic to generate purchase orders for low stock items.
Requirements to Run This Workflow
- Google Sheets Account: For storing and managing inventory data.
- Email Service: Gmail, SMTP, or similar for email alerts.
- n8n Instance: With Google Sheets and email connectors configured.
- Cron Service: For scheduling the daily trigger.
- Internet Connection: To access Google Sheets and email APIs.
- Optional SMS Service: Twilio or similar for SMS alerts (requires additional credentials).
Want a tailored workflow for your business? Our experts can craft it quickly Contact our team
n8n Workflow: Pharmacy Inventory Alerts for Low Stock & Expiring Medicine
This n8n workflow helps pharmacies proactively manage their inventory by regularly checking for low stock and expiring medicine and sending email alerts. It automates the process of monitoring critical inventory levels, ensuring that pharmacists and staff are informed in a timely manner to prevent stockouts and the use of expired products.
What it does
- Schedules Daily Check: The workflow is triggered daily by a Cron node, initiating a regular check of the inventory.
- Retrieves Inventory Data: It connects to a Google Sheet to fetch the latest inventory data, including product names, stock levels, and expiration dates.
- Processes Data (Placeholder): A "Code" node is included, serving as a placeholder for custom logic. This node is intended for processing the retrieved inventory data to identify items that are low in stock or nearing their expiration date.
- Sends Email Alerts: Based on the processing logic, the workflow sends email alerts to designated recipients. These emails would typically contain details about the low-stock items or expiring medicines.
- Includes a Wait Step (Placeholder): A "Wait" node is present, which could be used to introduce a delay in the workflow, for example, before sending a follow-up alert or performing another action.
- Provides Documentation (Placeholder): A "Sticky Note" node is included, likely for adding inline documentation or notes within the workflow itself.
Prerequisites/Requirements
- n8n Instance: A running instance of n8n.
- Google Sheets Account: A Google Sheets account with a spreadsheet containing your pharmacy inventory data. The sheet should ideally have columns for product name, current stock, and expiration date.
- Email Service: Access to an SMTP server or an email service configured in n8n (e.g., Gmail, Outlook, SendGrid) to send alert emails.
Setup/Usage
- Import the Workflow: Import the provided JSON into your n8n instance.
- Configure Cron Trigger:
- Open the "Cron" node.
- Set the desired schedule for the inventory checks (e.g., daily at a specific time).
- Configure Google Sheets Node:
- Open the "Google Sheets" node.
- Select or create a Google Sheets credential.
- Specify the Spreadsheet ID and the Sheet Name where your inventory data is located.
- Ensure the operation is set to "Read" and "Get All Rows" to fetch the entire inventory.
- Implement Logic in Code Node:
- Open the "Code" node.
- Write JavaScript code to:
- Access the data from the "Google Sheets" node.
- Define your "low stock" threshold.
- Define your "expiring soon" threshold (e.g., items expiring within 30 days).
- Filter the inventory data to identify items that meet these criteria.
- Format the output for the email alert.
- Example (conceptual, requires full implementation):
const inventory = $input.item.json.data; // Assuming data is in 'data' property const lowStockThreshold = 10; const expirationThresholdDays = 30; const today = new Date(); const lowStockAlerts = []; const expiringSoonAlerts = []; for (const item of inventory) { // Assuming 'Stock' and 'Expiration Date' are column headers if (item.Stock <= lowStockThreshold) { lowStockAlerts.push(`${item.Product} is low in stock (${item.Stock} left).`); } const expirationDate = new Date(item['Expiration Date']); const diffTime = expirationDate.getTime() - today.getTime(); const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); if (diffDays > 0 && diffDays <= expirationThresholdDays) { expiringSoonAlerts.push(`${item.Product} expires in ${diffDays} days (${item['Expiration Date']}).`); } } // Combine alerts or send separately let emailBody = ""; if (lowStockAlerts.length > 0) { emailBody += "--- Low Stock Alerts ---\n" + lowStockAlerts.join("\n") + "\n\n"; } if (expiringSoonAlerts.length > 0) { emailBody += "--- Expiring Medicine Alerts ---\n" + expiringSoonAlerts.join("\n") + "\n\n"; } if (emailBody === "") { return [{ json: { message: "No alerts needed." } }]; } else { return [{ json: { subject: "Pharmacy Inventory Alerts", body: emailBody } }]; }
- Configure Send Email Node:
- Open the "Send Email" node.
- Select or create an email credential.
- Set the To recipient(s) (e.g.,
pharmacy_manager@example.com). - Set the Subject using an expression to pull from the Code node's output (e.g.,
{{ $json.subject }}). - Set the Body using an expression to pull from the Code node's output (e.g.,
{{ $json.body }}). - Add conditional logic (e.g., an IF node before Send Email) if you only want to send an email when alerts are actually generated.
- Activate the Workflow: Save and activate the workflow.
Related Templates
Two-way property repair management system with Google Sheets & Drive
This workflow automates the repair request process between tenants and building managers, keeping all updates organized in a single spreadsheet. It is composed of two coordinated workflows, as two separate triggers are required — one for new repair submissions and another for repair updates. A Unique Unit ID that corresponds to individual units is attributed to each request, and timestamps are used to coordinate repair updates with specific requests. General use cases include: Property managers who manage multiple buildings or units. Building owners looking to centralize tenant repair communication. Automation builders who want to learn multi-trigger workflow design in n8n. --- ⚙️ How It Works Workflow 1 – New Repair Requests Behind the Scenes: A tenant fills out a Google Form (“Repair Request Form”), which automatically adds a new row to a linked Google Sheet. Steps: Trigger: Google Sheets rowAdded – runs when a new form entry appears. Extract & Format: Collects all relevant form data (address, unit, urgency, contacts). Generate Unit ID: Creates a standardized identifier (e.g., BUILDING-UNIT) for tracking. Email Notification: Sends the building manager a formatted email summarizing the repair details and including a link to a Repair Update Form (which activates Workflow 2). --- Workflow 2 – Repair Updates Behind the Scenes:\ Triggered when the building manager submits a follow-up form (“Repair Update Form”). Steps: Lookup by UUID: Uses the Unit ID from Workflow 1 to find the existing row in the Google Sheet. Conditional Logic: If photos are uploaded: Saves each image to a Google Drive folder, renames files consistently, and adds URLs to the sheet. If no photos: Skips the upload step and processes textual updates only. Merge & Update: Combines new data with existing repair info in the same spreadsheet row — enabling a full repair history in one place. --- 🧩 Requirements Google Account (for Forms, Sheets, and Drive) Gmail/email node connected for sending notifications n8n credentials configured for Google API access --- ⚡ Setup Instructions (see more detail in workflow) Import both workflows into n8n, then copy one into a second workflow. Change manual trigger in workflow 2 to a n8n Form node. Connect Google credentials to all nodes. Update spreadsheet and folder IDs in the corresponding nodes. Customize email text, sender name, and form links for your organization. Test each workflow with a sample repair request and a repair update submission. --- 🛠️ Customization Ideas Add Slack or Telegram notifications for urgent repairs. Auto-create folders per building or unit for photo uploads. Generate monthly repair summaries using Google Sheets triggers. Add an AI node to create summaries/extract relevant repair data from repair request that include long submissions.
Automate invoice processing with OCR, GPT-4 & Salesforce opportunity creation
PDF Invoice Extractor (AI) End-to-end pipeline: Watch Drive ➜ Download PDF ➜ OCR text ➜ AI normalize to JSON ➜ Upsert Buyer (Account) ➜ Create Opportunity ➜ Map Products ➜ Create OLI via Composite API ➜ Archive to OneDrive. --- Node by node (what it does & key setup) 1) Google Drive Trigger Purpose: Fire when a new file appears in a specific Google Drive folder. Key settings: Event: fileCreated Folder ID: google drive folder id Polling: everyMinute Creds: googleDriveOAuth2Api Output: Metadata { id, name, ... } for the new file. --- 2) Download File From Google Purpose: Get the file binary for processing and archiving. Key settings: Operation: download File ID: ={{ $json.id }} Creds: googleDriveOAuth2Api Output: Binary (default key: data) and original metadata. --- 3) Extract from File Purpose: Extract text from PDF (OCR as needed) for AI parsing. Key settings: Operation: pdf OCR: enable for scanned PDFs (in options) Output: JSON with OCR text at {{ $json.text }}. --- 4) Message a model (AI JSON Extractor) Purpose: Convert OCR text into strict normalized JSON array (invoice schema). Key settings: Node: @n8n/n8n-nodes-langchain.openAi Model: gpt-4.1 (or gpt-4.1-mini) Message role: system (the strict prompt; references {{ $json.text }}) jsonOutput: true Creds: openAiApi Output (per item): $.message.content → the parsed JSON (ensure it’s an array). --- 5) Create or update an account (Salesforce) Purpose: Upsert Buyer as Account using an external ID. Key settings: Resource: account Operation: upsert External Id Field: taxid_c External Id Value: ={{ $json.message.content.buyer.tax_id }} Name: ={{ $json.message.content.buyer.name }} Creds: salesforceOAuth2Api Output: Account record (captures Id) for downstream Opportunity. --- 6) Create an opportunity (Salesforce) Purpose: Create Opportunity linked to the Buyer (Account). Key settings: Resource: opportunity Name: ={{ $('Message a model').item.json.message.content.invoice.code }} Close Date: ={{ $('Message a model').item.json.message.content.invoice.issue_date }} Stage: Closed Won Amount: ={{ $('Message a model').item.json.message.content.summary.grand_total }} AccountId: ={{ $json.id }} (from Upsert Account output) Creds: salesforceOAuth2Api Output: Opportunity Id for OLI creation. --- 7) Build SOQL (Code / JS) Purpose: Collect unique product codes from AI JSON and build a SOQL query for PricebookEntry by Pricebook2Id. Key settings: pricebook2Id (hardcoded in script): e.g., 01sxxxxxxxxxxxxxxx Source lines: $('Message a model').first().json.message.content.products Output: { soql, codes } --- 8) Query PricebookEntries (Salesforce) Purpose: Fetch PricebookEntry.Id for each Product2.ProductCode. Key settings: Resource: search Query: ={{ $json.soql }} Creds: salesforceOAuth2Api Output: Items with Id, Product2.ProductCode (used for mapping). --- 9) Code in JavaScript (Build OLI payloads) Purpose: Join lines with PBE results and Opportunity Id ➜ build OpportunityLineItem payloads. Inputs: OpportunityId: ={{ $('Create an opportunity').first().json.id }} Lines: ={{ $('Message a model').first().json.message.content.products }} PBE rows: from previous node items Output: { body: { allOrNone:false, records:[{ OpportunityLineItem... }] } } Notes: Converts discount_total ➜ per-unit if needed (currently commented for standard pricing). Throws on missing PBE mapping or empty lines. --- 10) Create Opportunity Line Items (HTTP Request) Purpose: Bulk create OLIs via Salesforce Composite API. Key settings: Method: POST URL: https://<your-instance>.my.salesforce.com/services/data/v65.0/composite/sobjects Auth: salesforceOAuth2Api (predefined credential) Body (JSON): ={{ $json.body }} Output: Composite API results (per-record statuses). --- 11) Update File to One Drive Purpose: Archive the original PDF in OneDrive. Key settings: Operation: upload File Name: ={{ $json.name }} Parent Folder ID: onedrive folder id Binary Data: true (from the Download node) Creds: microsoftOneDriveOAuth2Api Output: Uploaded file metadata. --- Data flow (wiring) Google Drive Trigger → Download File From Google Download File From Google → Extract from File → Update File to One Drive Extract from File → Message a model Message a model → Create or update an account Create or update an account → Create an opportunity Create an opportunity → Build SOQL Build SOQL → Query PricebookEntries Query PricebookEntries → Code in JavaScript Code in JavaScript → Create Opportunity Line Items --- Quick setup checklist 🔐 Credentials: Connect Google Drive, OneDrive, Salesforce, OpenAI. 📂 IDs: Drive Folder ID (watch) OneDrive Parent Folder ID (archive) Salesforce Pricebook2Id (in the JS SOQL builder) 🧠 AI Prompt: Use the strict system prompt; jsonOutput = true. 🧾 Field mappings: Buyer tax id/name → Account upsert fields Invoice code/date/amount → Opportunity fields Product name must equal your Product2.ProductCode in SF. ✅ Test: Drop a sample PDF → verify: AI returns array JSON only Account/Opportunity created OLI records created PDF archived to OneDrive --- Notes & best practices If PDFs are scans, enable OCR in Extract from File. If AI returns non-JSON, keep “Return only a JSON array” as the last line of the prompt and keep jsonOutput enabled. Consider adding validation on parsing.warnings to gate Salesforce writes. For discounts/taxes in OLI: Standard OLI fields don’t support per-line discount amounts directly; model them in UnitPrice or custom fields. Replace the Composite API URL with your org’s domain or use the Salesforce node’s Bulk Upsert for simplicity.
Tax deadline management & compliance alerts with GPT-4, Google Sheets & Slack
AI-Driven Tax Compliance & Deadline Management System Description Automate tax deadline monitoring with AI-powered insights. This workflow checks your tax calendar daily at 8 AM, uses GPT-4 to analyze upcoming deadlines across multiple jurisdictions, detects overdue and critical items, and sends intelligent alerts via email and Slack only when immediate action is required. Perfect for finance teams and accounting firms who need proactive compliance management without manual tracking. 🏛️🤖📊 Good to Know AI-Powered: GPT-4 provides risk assessment and strategic recommendations Multi-Jurisdiction: Handles Federal, State, and Local tax requirements automatically Smart Alerts: Only notifies executives when deadlines are overdue or critical (≤3 days) Priority Classification: Categorizes deadlines as Overdue, Critical, High, or Medium priority Dual Notifications: Critical alerts to leadership + daily summaries to team channel Complete Audit Trail: Logs all checks and deadlines to Google Sheets for compliance records How It Works Daily Trigger - Runs at 8:00 AM every morning Fetch Data - Pulls tax calendar and company configuration from Google Sheets Analyze Deadlines - Calculates days remaining, filters by jurisdiction/entity type, categorizes by priority AI Analysis - GPT-4 provides strategic insights and risk assessment on upcoming deadlines Smart Routing - Only sends alerts if overdue or critical deadlines exist Critical Alerts - HTML email to executives + Slack alert for urgent items Team Updates - Slack summary to finance channel with all upcoming deadlines Logging - Records compliance check results to Google Sheets for audit trail Requirements Google Sheets Structure Sheet 1: TaxCalendar DeadlineID | DeadlineName | DeadlineDate | Jurisdiction | Category | AssignedTo | IsActive FED-Q1 | Form 1120 Q1 | 2025-04-15 | Federal | Income | John Doe | TRUE Sheet 2: CompanyConfig (single row) Jurisdictions | EntityType | FiscalYearEnd Federal, California | Corporation | 12-31 Sheet 3: ComplianceLog (auto-populated) Date | AlertLevel | TotalUpcoming | CriticalCount | OverdueCount 2025-01-15 | HIGH | 12 | 3 | 1 Credentials Needed Google Sheets - Service Account OAuth2 OpenAI - API Key (GPT-4 access required) SMTP - Email account for sending alerts Slack - Bot Token with chat:write permission Setup Steps Import workflow JSON into n8n Add all 4 credentials Replace these placeholders: YOURTAXCALENDAR_ID - Tax calendar sheet ID YOURCONFIGID - Company config sheet ID YOURLOGID - Compliance log sheet ID C12345678 - Slack channel ID tax@company.com - Sender email cfo@company.com - Recipient email Share all sheets with Google service account email Invite Slack bot to channels Test workflow manually Activate the trigger Customizing This Workflow Change Alert Thresholds: Edit "Analyze Deadlines" node: Critical: Change <= 3 to <= 5 for 5-day warning High: Change <= 7 to <= 14 for 2-week notice Medium: Change <= 30 to <= 60 for 2-month lookout Adjust Schedule: Edit "Daily Tax Check" trigger: Change hour/minute for different run time Add multiple trigger times for tax season (8 AM, 2 PM, 6 PM) Add More Recipients: Edit "Send Email" node: To: cfo@company.com, director@company.com CC: accounting@company.com BCC: archive@company.com Customize Email Design: Edit "Format Email" node to change colors, add logo, or modify layout Add SMS Alerts: Insert Twilio node after "Is Critical" for emergency notifications Integrate Task Management: Add HTTP Request node to create tasks in Asana/Jira for critical deadlines Troubleshooting | Issue | Solution | |-------|----------| | No deadlines found | Check date format (YYYY-MM-DD) and IsActive = TRUE | | AI analysis failed | Verify OpenAI API key and account credits | | Email not sending | Test SMTP credentials and check if critical condition met | | Slack not posting | Invite bot to channel and verify channel ID format | | Permission denied | Share Google Sheets with service account email | 📞 Professional Services Need help with implementation or customization? Our team offers: 🎯 Custom workflow development 🏢 Enterprise deployment support 🎓 Team training sessions 🔧 Ongoing maintenance 📊 Custom reporting & dashboards 🔗 Additional API integrations Discover more workflows – Get in touch with us