by Abdulrahman Alhalabi
NGO TPM Request Management System Benefits For Beneficiaries: 24/7 Accessibility** - Submit requests anytime via familiar Telegram interface Language Flexibility** - Communicate in Arabic through text or voice messages Instant Acknowledgment** - Receive immediate confirmation that requests are logged No Technical Barriers** - Works on basic smartphones without special apps For TPM Teams: Centralized Tracking** - All requests automatically logged with timestamps and user details Smart Prioritization** - AI categorizes issues by urgency and type for efficient response Action Guidance** - Specific recommended actions generated for each request type Performance Analytics** - Track response patterns and common issues over time For NGO Operations: Cost Reduction** - Automated intake reduces manual processing overhead Data Quality** - Standardized categorization ensures consistent reporting Audit Trail** - Complete record of all beneficiary interactions for compliance Scalability** - Handle high volumes without proportional staff increases How it Works Multi-Input Reception - Accepts both text messages and voice recordings via Telegram Voice Transcription - Uses OpenAI Whisper to convert Arabic voice messages to text AI Categorization - GPT-4 analyzes requests and categorizes issues (aid distribution, logistics, etc.) Action Planning - AI generates specific recommended actions for TPM team in Arabic Data Logging - Records all requests, categories, and actions in Google Sheets with user details Confirmation Feedback - Sends acknowledgment message back to users via Telegram Set up Steps Setup Time: ~20 minutes Create Telegram Bot - Get bot token from @BotFather and configure webhook Configure APIs - Set up OpenAI (transcription + chat) and Google Sheets credentials Customize AI Prompts - Adjust system messages for your NGO's specific operations Set Up Spreadsheet - Link Google Sheets for request tracking and reporting Test Workflows - Verify both text and voice message processing paths Detailed Arabic language configuration and TPM-specific categorization examples are included as sticky notes within the workflow. What You'll Need: Telegram Bot Token (free from @BotFather) OpenAI API key (Whisper + GPT-4) Google Sheets API credentials Google Spreadsheet for logging requests Sample Arabic text/voice messages for testing Key Features: Dual input support (text + voice messages) Arabic language processing and responses Structured data extraction (category + recommended action) Complete audit trail with user information Real-time confirmation messaging TPM team-specific workflow optimization
by Rahul Joshi
Description Automate your weekly social media analytics with this end-to-end AI reporting workflow. 📊🤖 This system collects real-time Twitter (X) and Facebook metrics, merges and validates data, formats it with JavaScript, generates an AI-powered HTML report via GPT-4o, saves structured insights in Notion, and shares visual summaries via Slack and Gmail. Perfect for marketing teams tracking engagement trends and performance growth. 🚀💬 What This Template Does 1️⃣ Starts manually or on-demand to fetch the latest analytics data. 🕹️ 2️⃣ Retrieves follower, engagement, and post metrics from both X (Twitter) and Facebook APIs. 🐦📘 3️⃣ Merges and validates responses to ensure clean, complete datasets. 🔍 4️⃣ Runs custom JavaScript to normalize and format metrics into a unified JSON structure. 🧩 5️⃣ Uses Azure OpenAI GPT-4o to generate a visually rich HTML performance report with tables, emojis, and insights. 🧠📈 6️⃣ Saves the processed analytics into a Notion “Growth Chart” database for centralized trend tracking. 🗂️ 7️⃣ Sends an email summary report to the marketing team, complete with formatted HTML insights. 📧 8️⃣ Posts a concise Slack update comparing platform performance and engagement deltas. 💬 9️⃣ Logs any validation or API errors automatically into Google Sheets for debugging and traceability. 🧾 Key Benefits ✅ Centralizes all social metrics into a single automated flow. ✅ Delivers AI-generated HTML reports ready for email and dashboard embedding. ✅ Reduces manual tracking with Notion and Slack syncs. ✅ Ensures data reliability with built-in validation and error logging. ✅ Gives instant, visual insights for weekly marketing reviews. Features Multi-platform analytics integration (Twitter X + Facebook Graph API). JavaScript node for dynamic data normalization. Azure OpenAI GPT-4o for HTML report generation. Notion database update for long-term trend storage. Slack and Gmail nodes for instant sharing and communication. Automated error capture to Google Sheets for workflow reliability. Visual, emoji-enhanced reporting with HTML formatting and insights. Requirements Twitter OAuth2 API credentials for access to public metrics. Facebook Graph API access token for page insights. Azure OpenAI API key for GPT-4o report generation. Notion API credentials with write access to “Growth Chart” database. Gmail OAuth2 credentials for report dispatch. Slack Bot Token with chat:write permission for posting analytics summaries. Google Sheets OAuth2 credentials for maintaining the error log. Environment Variables TWITTER_API_KEY FACEBOOK_ACCESS_TOKEN AZURE_OPENAI_API_KEY NOTION_GROWTH_DB_ID GMAIL_REPORT_RECIPIENTS SLACK_REPORT_CHANNEL_ID GOOGLE_SHEET_ERROR_LOG_ID Target Audience 📈 Marketing and growth teams tracking cross-platform performance 💡 Social media managers needing automated reporting 🧠 Data analysts compiling weekly engagement metrics 💬 Digital agencies managing multiple brand accounts 🧾 Operations and analytics teams monitoring performance KPIs Step-by-Step Setup Instructions 1️⃣ Connect all API credentials (Twitter, Facebook, Notion, Gmail, Slack, and Sheets). 2️⃣ Paste your Facebook Page ID and Twitter handle in respective API nodes. 3️⃣ Verify your Azure OpenAI GPT-4o connection and prompt text for HTML report generation. 4️⃣ Update your Notion database structure to match “Growth Chart” property names. 5️⃣ Add your marketing email in the Gmail node and test delivery. 6️⃣ Specify the Slack channel ID where summaries will be posted. 7️⃣ Optionally, connect a Google Sheet tab for error tracking (error_id, message). 8️⃣ Execute the workflow once manually to validate data flow. 9️⃣ Activate or schedule it for weekly or daily analytics automation. ✅
by Yaron Been
This workflow automatically analyzes sales territory performance, comparing revenue, win rates, and activity across regions. Remove the guesswork from territory planning and drive balanced growth. Overview On a weekly schedule, the workflow pulls CRM data for each territory, merges it with demographic and market size info scraped via Bright Data, and feeds everything into OpenAI for performance benchmarking. Outliers—both high and low performers—are highlighted in a Google Data Studio dashboard and summarized in a Slack message. Tools Used n8n** – Orchestrates data collection and analysis CRM API** – Source of sales metrics by territory Bright Data** – Scrapes external market indicators (population, GDP, etc.) OpenAI** – Normalizes and benchmarks territories Google Sheets / Data Studio** – Stores and visualizes results Slack** – Sends the weekly summary How to Install Import the Workflow into n8n. Connect Your CRM API credentials. Configure Bright Data credentials. Set Up OpenAI API key. Authorize Google services & Slack. Customize Territory Definitions in the Set node. Use Cases Sales Leadership**: Rebalance territories based on potential. Revenue Operations**: Identify underserved regions. Financial Planning**: Allocate resources where ROI is highest. Incentive Design**: Reward reps fairly based on potential. Connect with Me Website**: https://www.nofluff.online YouTube**: https://www.youtube.com/@YaronBeen/videos LinkedIn**: https://www.linkedin.com/in/yaronbeen/ Get Bright Data**: https://get.brightdata.com/1tndi4600b25 (Using this link supports my free workflows with a small commission) #n8n #automation #territorymanagement #salesanalytics #brightdata #openai #n8nworkflow #nocode #revenueops
by Sk developer
Automation Flow: Image to Image Using GPT Sora This flow automates the process of generating images using a provided prompt and reference image via the Sora GPT Image API from RapidAPI. The generated images are stored in Google Drive, and details are logged in Google Sheets. Nodes Overview 1. On Form Submission Type**: n8n-nodes-base.formTrigger Description**: This node triggers when a user submits the form containing the prompt and image URL. It ensures the form fields are filled in and ready for processing. Form Fields: Prompt: A text description of the desired image. Image URL: The URL of the reference image to be used. Webhook ID: Unique identifier for form submission. 2. HTTP Request to Sora GPT Image API Type**: n8n-nodes-base.httpRequest Description: Sends the prompt and image URL to the **Sora GPT Image API to generate a new image based on the provided inputs. API Endpoint: Sora GPT Image API (via RapidAPI) Method: POST Body Parameters: Prompt: User-provided text. Image URL: The reference image URL. Width & Height: Image size is set to 1024x1024. 3. Code (Base64 Conversion) Type**: n8n-nodes-base.code Description**: This node processes the base64-encoded image data returned from the API. It decodes and formats the image to be uploaded to Google Drive. Output: Converts the base64 string into a binary JPEG file. 4. Upload Image to Google Drive Type**: n8n-nodes-base.googleDrive Description: Uploads the generated image to **Google Drive, storing it in a designated folder. Authentication: Google Service Account. File Name: The image file name is dynamically set from the previous node. 5. Log Details to Google Sheets Type**: n8n-nodes-base.googleSheets Description: This node logs the **Prompt, Generated Image, and Generation Date into a Google Sheets document for tracking and auditing purposes. Columns Mapped: Prompt: The user’s input text. Image: The name of the generated image file. Generated Date: Date and time of image generation. Flow Summary User Submits Form: Triggered when the form with the prompt and image URL is submitted. Image Generation: The data is sent to the Sora GPT Image API from RapidAPI to generate the image. Image Processing: The generated image (base64 format) is decoded and saved as a file. Google Drive Upload: The image is uploaded to Google Drive for storage. Google Sheets Logging: All relevant details (Prompt, Image, Date) are saved in Google Sheets. Benefits Automated Image Creation: Quickly generate images using AI based on a simple prompt and reference image via **RapidAPI. Efficient Workflow**: The entire process from form submission to image generation and storage is automated, saving time and reducing manual work. Centralized Storage: Generated images are stored in **Google Drive, ensuring easy access and organization. Audit Trail: The details of each generated image are logged in **Google Sheets, making it easy to track, review, and manage past creations. Scalable and Reusable**: Can be adapted to multiple use cases, such as creative design, marketing materials, or social media content generation. Problems Solved Manual Image Editing**: Eliminates the need for manual image manipulation and creation, allowing for automatic generation based on user inputs. Disorganized File Storage: With automatic uploads to **Google Drive, the images are stored in a centralized and organized manner. Lack of Record-Keeping: By logging image generation details in **Google Sheets, there's always a record of past creations, improving tracking and management. Time-Consuming Processes**: The automation drastically reduces the time spent on manual tasks, allowing users to focus on other aspects of their work or creative processes. This flow simplifies the process of creating AI-generated images based on user inputs, leveraging the power of the Sora GPT Image API via RapidAPI, making it a powerful tool for creative, design, and marketing purposes.
by khaled
What Problem Does It Solve? Business owners, managers, and accountants waste valuable time manually entering daily expenses, supplier payments, and employee advances into Odoo. Getting quick balance reports usually requires logging into the ERP, navigating multiple menus, and generating complex reports. Managing post-dated checks often relies on manual tracking, leading to missed due dates. This workflow solves these by: -- Allowing users to record financial transactions simply by sending a natural language message (e.g., via Telegram or Botpress). -- Automatically fetching real-time account balances and supplier statements, returning them instantly in the chat. -- Setting up automated calendar reminders for post-dated check due dates. -- Handling the entire double-entry accounting process in the background without human intervention. How to Configure It Chat Platform Setup** -- Add the webhook URL from this workflow to your Telegram Bot, Botpress, or preferred chat interface. Odoo Setup** -- Connect your Odoo credentials in n8n. -- Open the "Build [X] Entry" code nodes and replace the placeholder journal_id and currency_id with your actual Odoo system IDs. AI Setup** -- Add your OpenAI API key (or swap the node for Google Gemini/Anthropic). -- Open the "AI Financial Agent" node and update the # ACCOUNT MAPPING section with your specific Odoo Chart of Accounts codes. Calendar Setup (Optional)** -- Connect your Google Calendar credentials if you want the workflow to automatically schedule reminders for check due dates. How It Works Webhook catches the new text message from your chat platform. An AI Agent analyzes the Arabic natural language and extracts the intent, amount, date, check details, and specific account categories. Routing: -- For Expenses, Payments, or Advances → The workflow searches Odoo for the correct IDs, builds a balanced double-entry journal record, creates it, and posts it. -- For Post-Dated Checks → Extracts the due date and creates a Google Calendar event before posting the entry to Odoo. -- For Balance Inquiries → Fetches the relevant ledger lines, calculates total debits/credits, and formats a clean Arabic text summary. A success confirmation or the requested financial report is instantly sent back to the user in the chat. Customization Ideas Expand the AI prompt and routing switch to handle Customer Invoices or internal Petty Cash transfers. Add an approval step (e.g., sending a Slack/Email button) before the workflow officially "posts" large transactions in Odoo. Change the AI prompt to support multiple languages or different regional dialects. Log a backup of all financial chat requests into Google Sheets or a Notion database for auditing. For more info Contact Me
by Arnaud MARIE
Replicate Line Items on New Deal in HubSpot Workflow Use Case This workflow solves the problem of manually copying line items from one deal to another in HubSpot, reducing manual work and minimizing errors. What this workflow does Triggers** upon receiving a webhook with deal IDs. Retrieves** the IDs of the won and created deals. Fetches** line items associated with the won deal. Extracts** product SKUs from the retrieved line items. Fetches** product details based on SKUs. Creates** new line items for the created deal and associates them. Sends** a Slack notification with success details. Step up steps Create a HubSpot Deal Workflow 1.1 Set up your trigger (ex: when deal stage = Won) 1.2 Add step : Create Record (deal) 1.3 Add Step : Send webhook. The webhook should be a Get to your n8n first trigger. Set two query parameter : deal_id_won as the Record ID of the deal triggering the HubSpot Workflow deal_id_create as the Record ID of the deal created above. Click Insert Data -> The created object Set up your HubSpot App token in HubSpot -> Settings -> Integration -> Private Apps Set up your HubSpot Token integration using the predefined model. Set up your Slack connection Add an error Workflow to monitor errors
by Oneclick AI Squad
This guide details the setup and functionality of an automated workflow designed to monitor the health, uptime, and SLA compliance of travel supplier APIs, specifically the Amadeus Flight API and Booking.com Hotel API. The workflow runs every 10 minutes, processes health and SLA data, and sends alerts or logs based on the status. What It Monitors API Health**: UP/DOWN status with health indicators. Uptime Tracking**: Real-time availability percentage. SLA Compliance**: Automatic breach detection and alerts. Performance Rating**: Classified as EXCELLENT, GOOD, AVERAGE, or POOR. Features Runs every 10 minutes automatically. Monitors the Amadeus Flight API with a 99.5% SLA target. Monitors the Booking.com Hotel API with a 99.0% SLA target. Smart Alerts that notify via WhatsApp only on SLA breaches. Logging of results for both breaches and normal status. Workflow Steps Monitor Schedule**: Triggers the workflow every 10 minutes automatically. Amadeus Flight API**: Tests the Amadeus Flight API (GET: https://api.amadeus.com) simultaneously. Booking Hotel API**: Tests the Booking.com Hotel API (GET: https://distribution-xml.booking.com) simultaneously. Calculate Health & SLA**: Processes health, uptime, and SLA data. Alert Check**: Routes to appropriate responses based on breach status. SLA Breach Alert**: Sends an alert with throwError if an SLA breach occurs. Normal Status Log**: Records results with throwError for healthy status. Send Message**: Sends a WhatsApp message for breach alerts. How to Use Copy the JSON configuration of the workflow. Import it into your n8n workspace. Activate the workflow. Monitor results in the execution logs and WhatsApp notifications. The workflow will automatically start tracking your travel suppliers and alert you via WhatsApp only when SLA thresholds are breached. Please double-check responses to ensure accuracy. Requirements n8n account and instance setup. API credentials for Amadeus Flight API (e.g., https://api.amadeus.com). API credentials for Booking.com Hotel API (e.g., https://distribution-xml.booking.com). WhatsApp integration for sending alerts. Customizing this Workflow Adjust the Monitor Schedule interval to change the frequency (e.g., every 5 or 15 minutes). Modify SLA targets in the Calculate Health & SLA node to align with your service agreements (e.g., 99.9% for Amadeus). Update API endpoints or credentials in the Amadeus Flight API and Booking Hotel API nodes for different suppliers. Customize the Send Message node to integrate with other messaging platforms (e.g., Slack, email). Enhance the Normal Status Log to include additional metrics or export logs to a database.
by Omar Akoudad
The workflow is well-designed for CRM analysis with a robust quality control mechanism. The dual-AI approach ensures reliable results, while the webhook integration makes it production-ready for real-time CRM data processing. Dual-AI Architecture: Uses DeepSeek Reasoner for analysis and DeepSeek Chat for verification. Flexible Input: Supports both manual testing and production webhook integration. Quality Assurance: Built-in verification system to ensure report accuracy. Comprehensive Analysis: Covers lead conversion, upsell metrics, agent ranking, and more. Professional Output: Generates structured markdown reports with actionable insights
by oka hironobu
Quick Overview This workflow checks a specified web page every 6 hours, stores snapshots in Google Sheets, and when the page text changes it uses Google Gemini to summarise what changed and posts the summary to a Slack channel. How it works Runs every 6 hours on a schedule. Fetches the configured URL via HTTP and posts a Slack alert if the page cannot be retrieved. Strips the HTML down to cleaned plain text (limited to 6,000 characters) for comparison. Reads the last stored snapshot from Google Sheets and compares it to the current cleaned text. If this is the first run, saves the current text as a baseline snapshot in Google Sheets. If the text changed, sends the previous and current versions to Google Gemini to generate a 2–3 sentence change summary. Posts the change summary and page link to Slack, then updates the snapshot in Google Sheets so the same change is only reported once. Setup Add credentials for Google Sheets OAuth, Google Gemini (PaLM) API, and Slack OAuth. Update the label, URL, and CSS selector in the page configuration to match the page section you want to monitor. Select your Google Sheets document and ensure a “Snapshots” sheet exists with a column for stored page text (for example, “Text”). Choose the target Slack channel (for example, #monitoring) for both change notifications and fetch-failure alerts.
by WeblineIndia
Quick overview This workflow runs hourly to analyze warehouse receiving logs from Google Sheets, calculates per-user performance and compliance metrics, enriches results with department data, uses Google Gemini to generate recommendations for flagged users, emails managers via Gmail when escalation is needed, and appends results to an analytics dashboard sheet. How it works Runs every hour on a schedule trigger. Reads receiving log rows from Google Sheets and normalizes key fields like duration, errors, and compliance. Aggregates the log data by user_id and computes performance status, severity score, and alert tier based on time, errors, and compliance rate. Looks up each user’s department and manager email in a Google Sheets “Departments” tab and attaches this context to the analysis. For users not rated “good,” sends the metrics to Google Gemini to generate structured root-cause and action-step recommendations. If the alert tier is not “none,” sends an info/warning or critical escalation email via Gmail (using manager_email when available). Appends the final per-user analysis (metrics, issues, recommendations, and whether an email was sent) to a Google Sheets “AnalyticsDashboard” tab. Setup Connect Google Sheets OAuth2 credentials and set the spreadsheet and tab IDs for ReceivingLogs, Departments, and AnalyticsDashboard. Ensure ReceivingLogs includes user_id, duration, errors, and compliance columns, and ensure user_id matches the Departments sheet. Populate the Departments sheet with user_id, department, and manager_email values for routing alerts. Add Google Gemini (PaLM) API credentials for the recommendation step. Add Gmail OAuth2 credentials and confirm the recipient behavior (manager_email fallback address) and email content meet your escalation requirements. Requirements n8n instance (self-hosted or cloud) Google Sheets account with: ReceivingLogs sheet, Departments sheet, AnalyticsDashboard sheet Google Gemini API credentials Gmail account (for sending emails) Structured data with the following fields: user_id, duration, errors, compliance Customization Schedule Node**: Change frequency (e.g., daily instead of hourly) Performance Thresholds (Code Node)**: Adjust Duration limit (default: 15 min), Error threshold (default: 5) and Compliance threshold (default: 90%) AI Prompt**: Modify tone, format, or output structure Email Content**: Customize subject lines, messaging and Add CC/BCC recipients Google Sheets Mapping**: Add more fields or modify column mappings Additional info Who’s It For Warehouse and logistics managers Procurement and operations teams Process improvement analysts Businesses using Google Sheets for operational tracking Organizations looking to automate performance monitoring Add-Ons & Enhancements Slack or Microsoft Teams alerts Dashboard visualization (Power BI / Looker Studio) Historical trend analysis Auto task creation in tools like Jira or Trello Role-based escalation (multi-level approvals) Use Case Examples Monitor warehouse staff performance in real-time Detect compliance violations in procurement processes Identify employees with frequent operational errors Automate manager notifications for performance issues Build a performance analytics dashboard for leadership There can be many more use cases depending on your business workflow and data structure. Troubleshooting Guide | Issue | Possible Cause | Solution | |------|--------------|---------| | No data fetched | Incorrect Google Sheets connection | Verify credentials and sheet ID | | Incorrect calculations | Data format mismatch | Ensure numeric fields are properly formatted | | AI not generating output | Gemini API issue | Check API key and quota | | Emails not sent | Gmail credentials missing | Reconnect Gmail OAuth | | Missing department info | user_id mismatch | Ensure consistent IDs across sheets | | Workflow not triggering | Schedule misconfigured | Verify trigger interval | Need Help? If you need assistance setting up this workflow, customizing it for your business or adding advanced features, feel free to reach out. WeblineIndia can help you: Customize workflows to fit your operations Integrate additional tools and platforms Build scalable automation solutions Add advanced analytics and reporting Get in touch to turn your business processes into efficient, automated systems.
by Jitesh Dugar
Automated Customer Statement Generator with Risk Analysis & Credit Monitoring Transform account statement management from hours to minutes - automatically compile transaction histories, calculate aging analysis, monitor credit limits, assess payment risk, and deliver professional PDF statements while syncing with accounting systems and alerting your team about high-risk accounts. What This Workflow Does Revolutionizes customer account management with intelligent statement generation, credit monitoring, and risk assessment: Webhook-Triggered Generation** - Automatically creates statements from accounting systems, CRM updates, or scheduled monthly triggers Smart Data Validation** - Verifies transaction data, validates account information, and ensures statement accuracy before generation Running Balance Calculation** - Automatically computes running balances through all transactions with opening and closing balance tracking Comprehensive Aging Analysis** - Calculates outstanding balances by age buckets (Current, 31-60 days, 61-90 days, 90+ days) Overdue Detection & Highlighting** - Automatically identifies overdue amounts with visual color-coded alerts on statements Professional HTML Design** - Creates beautifully branded statements with modern layouts, aging breakdowns, and payment information PDF Conversion** - Transforms HTML into print-ready, professional-quality PDF statements with preserved formatting Automated Email Delivery** - Sends branded emails to customers with PDF attachments and account summary details Google Drive Archival** - Automatically saves statements to organized folders with searchable filenames by account Credit Limit Monitoring** - Tracks credit utilization, detects over-limit accounts, and generates alerts at 75%, 90%, and 100%+ thresholds Risk Scoring System** - Calculates 0-100 risk scores based on payment behavior, aging, credit utilization, and overdue patterns Payment Behavior Analysis** - Tracks days since last payment, average payment time, and payment reliability trends Automated Recommendations** - Generates prioritized action items like "escalate to collections" or "suspend new credit" Accounting System Integration** - Syncs statement delivery, balance updates, and risk assessments to QuickBooks, Xero, or FreshBooks Conditional Team Notifications** - Different Slack alerts for overdue accounts (urgent) vs current accounts (standard) with risk metrics Transaction History Table** - Detailed itemization of all charges, payments, and running balances throughout statement period Multiple Payment Options** - Includes bank details, online payment links, and account manager contact information Key Features Automatic Statement Numbering**: Generates unique sequential statement numbers with format STMT-YYYYMM-AccountNumber for easy tracking and reference Aging Bucket Analysis**: Breaks down outstanding balances into current (0-30 days), 31-60 days, 61-90 days, and 90+ days overdue categories Credit Health Dashboard**: Visual indicators show credit utilization percentage, available credit, and over-limit warnings in statement Risk Assessment Engine**: Analyzes multiple factors including overdue amounts, credit utilization, payment frequency to calculate comprehensive risk score Payment Behavior Tracking**: Monitors days since last payment, identifies patterns like "Excellent - Pays on Time" or "Poor - Chronic Late Payment" Intelligent Recommendations**: Automatically generates prioritized action items based on account status, risk level, and payment history Transaction Running Balance**: Shows balance after each transaction so customers can verify accuracy and reconcile their records Over-Limit Detection**: Immediate alerts when accounts exceed credit limits with escalation recommendations to suspend new charges Good Standing Indicators**: Visual green checkmarks and positive messaging for accounts with no overdue balances Account Manager Details**: Includes dedicated contact person for questions, disputes, and payment arrangements Dispute Process Documentation**: Clear instructions on how customers can dispute transactions within required timeframe Multi-Currency Support**: Handles USD, EUR, GBP, INR with proper currency symbols and formatting throughout statement Accounting System Sync**: Logs statement delivery, balance updates, and risk assessments in QuickBooks, Xero, FreshBooks, or Wave Conditional Workflow Routing**: Different automation paths for high-risk overdue accounts vs healthy current accounts Activity Notes Generation**: Creates detailed CRM notes with account summary, recommendations, and delivery confirmation Print-Optimized PDFs**: A4 format with proper margins and color preservation for professional printing and digital distribution Perfect For B2B Companies with Trade Credit** - Manufacturing, wholesale, distribution businesses offering net-30 or net-60 payment terms Professional Services Firms** - Consulting, legal, accounting firms with monthly retainer clients and time-based billing Subscription Services (B2B)** - SaaS platforms, software companies, membership organizations with recurring monthly charges Equipment Rental Companies** - Construction equipment, party rentals, medical equipment with ongoing rental agreements Import/Export Businesses** - International traders managing accounts receivable across multiple customers and currencies Healthcare Billing Departments** - Medical practices, clinics, hospitals tracking patient account balances and payment plans Educational Institutions** - Private schools, universities, training centers with tuition payment plans and installments Telecommunications Providers** - Phone, internet, cable companies sending monthly account statements to business customers Utilities & Energy Companies** - Electric, gas, water utilities managing commercial account statements and collections Property Management Companies** - Real estate firms tracking tenant charges, rent payments, and maintenance fees Credit Card Companies & Lenders** - Financial institutions providing detailed account activity and payment due notifications Wholesale Suppliers** - Distributors supplying restaurants, retailers, contractors on credit terms with monthly settlements Commercial Insurance Agencies** - Agencies tracking premium payments, policy charges, and outstanding balances Construction Contractors** - General contractors billing for progress payments, change orders, and retention releases What You Will Need Required Integrations HTML to PDF API - PDF conversion service (API key required) - supports HTML/CSS to PDF API, PDFShift, or similar providers (approximately 1-5 cents per statement) Gmail or SMTP - Email delivery service for sending statements to customers (OAuth2 or SMTP credentials) Google Drive - Cloud storage for statement archival and compliance record-keeping (OAuth2 credentials required) Optional Integrations Slack Webhook** - Team notifications for overdue and high-risk accounts (free incoming webhook) Accounting Software Integration** - QuickBooks, Xero, FreshBooks, Zoho Books API for automatic statement logging and balance sync CRM Integration** - HubSpot, Salesforce, Pipedrive for customer activity tracking and collections workflow triggers Payment Gateway** - Stripe, PayPal, Square payment links for one-click online payment from statements Collections Software** - Integrate with collections management platforms for automatic escalation of high-risk accounts SMS Notifications** - Twilio integration for payment due reminders and overdue alerts via text message Quick Start Import Template - Copy JSON workflow and import into your n8n instance Configure PDF Service - Add HTML to PDF API credentials in the "HTML to PDF" node Setup Gmail - Connect Gmail OAuth2 credentials in "Send Email to Customer" node and update sender email Connect Google Drive - Add Google Drive OAuth2 credentials and set folder ID for statement archival Customize Company Info - Edit "Enrich with Company Data" node to add company name, address, contact details, bank information Configure Credit Limits - Set default credit limits and payment terms for your customer base Adjust Risk Thresholds - Modify risk scoring logic in "Credit Limit & Risk Analysis" node based on your policies Update Email Template - Customize email message in Gmail node with your branding and messaging Configure Slack - Add Slack webhook URLs in both notification nodes (overdue and current accounts) Connect Accounting System - Replace code in "Update Accounting System" node with actual API call to QuickBooks/Xero/FreshBooks Test Workflow - Submit sample transaction data via webhook to verify PDF generation, email delivery, and notifications Schedule Monthly Run - Set up scheduled trigger for automatic end-of-month statement generation for all customers Customization Options Custom Aging Buckets** - Modify aging periods to match your business (e.g., 0-15, 16-30, 31-45, 46-60, 60+ days) Industry-Specific Templates** - Create different statement designs for different customer segments or business units Multi-Language Support** - Translate statement templates for international customers (Spanish, French, German, Mandarin) Dynamic Credit Terms** - Configure different payment terms by customer type (VIP net-45, standard net-30, new customers due on receipt) Late Fee Calculation** - Add automatic late fee calculation and inclusion for overdue balances Payment Plan Tracking** - Track installment payment plans with remaining balance and next payment due Interest Charges** - Calculate and add interest charges on overdue balances based on configurable rates Partial Payment Allocation** - Show how partial payments were applied across multiple invoices Customer Portal Integration** - Generate secure links for customers to view statements and make payments online Batch Processing** - Process statements for hundreds of customers simultaneously with bulk email delivery White-Label Branding** - Create different branded templates for multiple companies or subsidiaries Custom Risk Models** - Adjust risk scoring weights based on your industry and historical payment patterns Collections Workflow Integration** - Automatically create tasks in collections software for high-risk accounts Early Payment Incentives** - Highlight early payment discounts or prompt payment benefits on statements Dispute Management** - Track disputed transactions and adjust balances accordingly with audit trail Expected Results 90% time savings** - Reduce statement creation from 2-3 hours to 5 minutes per customer 100% accuracy** - Eliminate calculation errors and missing transactions through automated processing 50% faster payment collection** - Professional statements with clear aging drive faster customer payments Zero filing time** - Automatic Google Drive organization with searchable filenames by account 30% reduction in overdue accounts** - Proactive credit monitoring and risk alerts prevent bad debt Real-time risk visibility** - Instant identification of high-risk accounts before they become uncollectible Automated compliance** - Complete audit trail with timestamped statement delivery and accounting sync Better customer communication** - Professional statements improve customer satisfaction and reduce disputes Reduced bad debt write-offs** - Early warning system catches payment issues before they escalate Improved cash flow** - Faster statement delivery and payment reminders accelerate cash collection Pro Tips Schedule Monthly Batch Generation** - Run workflow automatically on last day of month to generate statements for all customers simultaneously Customize Aging Thresholds** - Adjust credit alert levels (75%, 90%, 100%) based on your risk tolerance and industry norms Segment Customer Communications** - Use different email templates for VIP customers vs standard customers vs delinquent accounts Track Payment Patterns** - Monitor days-to-pay metrics by customer to identify chronic late payers proactively Integrate with Collections** - Connect workflow to collections software to automatically escalate 90+ day accounts Include Payment Portal Links** - Add unique payment links to each statement for one-click online payment Automate Follow-Up Reminders** - Build workflow extension to send payment reminders 7 days before due date Create Executive Dashboards** - Export risk scores and aging data to business intelligence tools for trend analysis Document Dispute Resolutions** - Log all disputed transactions in accounting system with resolution notes Test with Sample Data First** - Validate aging calculations with known test data before processing real customer accounts Archive Statements for Compliance** - Maintain 7-year archive in Google Drive organized by year and customer Monitor Credit Utilization Trends** - Track credit utilization changes month-over-month to predict cash flow needs Benchmark Against Industry** - Compare your DSO and bad debt ratios to industry averages to identify improvement areas Personalize Account Manager Info** - Assign dedicated contacts to customers and include their direct phone and email Use Descriptive Transaction Details** - Ensure transaction descriptions clearly explain charges to reduce disputes Business Impact Metrics Track these key metrics to measure workflow success: Statement Generation Time** - Measure average minutes from trigger to delivered statement (target: under 5 minutes) Statement Volume Capacity** - Count monthly statements generated through automation (expect 10-20x increase in capacity) Aging Calculation Accuracy** - Track statements with aging errors (target: 0% error rate) Days Sales Outstanding (DSO)** - Monitor average days to collect payment (expect 15-30% reduction) Bad Debt Write-Offs** - Track uncollectible accounts as percentage of revenue (expect 30-50% reduction) Collection Rate** - Monitor percentage of invoices collected within terms (expect 10-20% improvement) Customer Disputes** - Count statement disputes and billing inquiries (expect 50-70% reduction) Over-Limit Accounts** - Track number of accounts exceeding credit limits (early detection prevents losses) High-Risk Account Identification** - Measure days between risk detection and collection action (target: within 48 hours) Cash Flow Improvement** - Calculate working capital improvement from faster collections (typical: 20-35% improvement) Template Compatibility Compatible with n8n version 1.0 and above Works with n8n Cloud and Self-Hosted instances Requires HTML to PDF API service subscription (1-5 cents per statement) No coding required for basic setup Fully customizable for industry-specific requirements Integrates with major accounting platforms via API Multi-currency and multi-language ready Supports batch processing for large customer bases Compliant with financial record-keeping regulations Ready to transform your account receivables management? Import this template and start generating professional statements with credit monitoring, risk assessment, and automated collections alerts - improving your cash flow, reducing bad debt, and freeing your accounting team to focus on strategic financial management!
by Vigh Sandor
Workflow Overview This advanced n8n workflow provides intelligent email automation with AI-generated responses. It combines four core functions: Monitors incoming emails via IMAP (e.g., SOGo) Sends instant Telegram notifications for all new emails Uses AI (Ollama LLM) to generate contextual, personalized auto-replies Sends confirmation notifications when auto-replies are sent Unlike traditional auto-responders, this workflow analyzes email content and creates unique, relevant responses for each message. Setup Instructions Prerequisites Before setting up this workflow, ensure you have: An n8n instance (self-hosted or cloud) with AI/LangChain nodes enabled IMAP email account credentials (e.g., SOGo, Gmail, Outlook) SMTP server access for sending emails Telegram Bot API credentials Telegram Chat ID where notifications will be sent Ollama installed locally or accessible via network (for AI model) The llama3.1 model downloaded in Ollama Step 1: Install and Configure Ollama Local Installation Install Ollama on your system: Visit https://ollama.ai and download the installer for your OS Follow installation instructions for your platform Download the llama3.1 model: ollama pull llama3.1 Verify the model is available: ollama list Start Ollama service (if not already running): ollama serve Test the model: ollama run llama3.1 "Hello, world!" Remote Ollama Instance If using a remote Ollama server: Note the server URL (e.g., http://192.168.1.100:11434) Ensure network connectivity between n8n and Ollama server Verify firewall allows connections on port 11434 Step 2: Configure IMAP Credentials Navigate to n8n Credentials section Create a new IMAP credential with the following information: Host: Your IMAP server address Port: Usually 993 for SSL/TLS Username: Your email address Password: Your email password or app-specific password Enable SSL/TLS: Yes (recommended) Security: Use STARTTLS or SSL/TLS Step 3: Configure SMTP Credentials Create a new SMTP credential in n8n Enter the following details: Host: Your SMTP server address (e.g., Postfix server) Port: Usually 587 (STARTTLS) or 465 (SSL) Username: Your email address Password: Your email password or app-specific password Secure connection: Enable based on your server configuration Allow unauthorized certificates: Enable if using self-signed certificates Step 4: Configure Telegram Bot Create a Telegram bot via BotFather: Open Telegram and search for @BotFather Send /newbot command Follow instructions to create your bot Save the API token provided by BotFather Obtain your Chat ID: Method 1: Send a message to your bot, then visit: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates Method 2: Use a Telegram Chat ID bot like @userinfobot Method 3: For group chats, add the bot to the group and check the updates Note: Group chat IDs are negative numbers (e.g., -1234567890123) Add Telegram API credential in n8n: Credential Type: Telegram API Access Token: Your bot token from BotFather Step 5: Configure Ollama API Credential In n8n Credentials section, create a new Ollama API credential Configure based on your setup: For local Ollama: Base URL is usually http://localhost:11434 For remote Ollama: Enter the server URL (e.g., http://192.168.1.100:11434) Test the connection to ensure n8n can reach Ollama Step 6: Import and Configure Workflow Import the workflow JSON into your n8n instance Update the following nodes with your specific information: Check Incoming Emails Node Verify IMAP credentials are connected Configure polling interval (optional): Default behavior checks on workflow trigger schedule Can be set to check every N minutes Set mailbox folder if needed (default is INBOX) Send Notification from Incoming Email Node Update chatId parameter with your Telegram Chat ID Replace -1234567890123 with your actual chat ID Customize notification message template if desired Current format includes: Sender, Subject, Date-Time Dedicate Filtering As No-Response Node Review spam filter conditions: Blocks emails from addresses containing "noreply" or "no-reply" Blocks emails with "newsletter" in subject line (case-insensitive) Add additional filtering rules as needed: Block specific domains Filter by keywords Whitelist/blacklist specific senders Ollama Model Node Verify Ollama API credential is connected Confirm model name: llama3.1:bf230501 (or adjust to your installed version) Context window set to 4096 tokens (sufficient for most emails) Can be adjusted based on your needs and hardware capabilities Basic LLM Chain Node Review the AI prompt engineering (pre-configured but customizable) Current prompt instructs the AI to: Read the email content Identify main topic in 2-4 words Generate a professional acknowledgment response Keep responses consistent and concise Modify prompt if you want different response styles Send Auto-Response in SMTP Node Verify SMTP credentials are connected Check fromEmail uses correct email address: Currently set to {{ $('Check Incoming Emails - IMAP (example: SOGo)').item.json.to }} This automatically uses the recipient address (your mailbox) Subject automatically includes "Re: " prefix with original subject Message text comes from AI-generated content Send Notification from Response Node Update chatId parameter (same as first notification node) This sends confirmation that auto-reply was sent Includes original email details and the AI-generated response text Step 7: Test the Workflow Perform initial configuration test: Test Ollama connectivity: curl http://localhost:11434/api/tags Verify all credentials are properly configured Check n8n has access to required network endpoints Execute a test run: Click "Execute Workflow" button in n8n Send a test email to your monitored inbox Use a clear subject and body for better AI response Verify workflow execution: First Telegram notification received (incoming email alert) AI processes the email content Auto-reply is sent to the original sender Second Telegram notification received (confirmation with AI response) Check n8n execution log for any errors Verify email delivery: Check if auto-reply arrived at sender's inbox Verify it's not marked as spam Review AI-generated content for appropriateness Step 8: Fine-Tune AI Responses Send various types of test emails: Different topics (inquiry, complaint, information request) Various email lengths (short, medium, long) Different languages if applicable Review AI-generated responses: Check if topic identification is accurate Verify response appropriateness Ensure tone is professional Adjust the prompt if needed: Modify topic word count (currently 2-4 words) Change response template Add language-specific instructions Include custom sign-offs or branding Step 9: Activate the Workflow Once testing is successful and AI responses are satisfactory: Toggle the workflow to "Active" state The workflow will now run automatically on the configured schedule Monitor initial production runs: Review first few auto-replies carefully Check Telegram notifications for any issues Verify SMTP delivery rates Set up monitoring: Enable n8n workflow error notifications Monitor Ollama resource usage Check email server logs periodically How to Use Normal Operation Once activated, the workflow operates fully automatically: Email Monitoring: The workflow continuously checks your IMAP inbox for new messages based on the configured polling interval or trigger schedule. Immediate Incoming Notification: When a new email arrives, you receive an instant Telegram notification containing: Sender's email address Email subject line Date and time received Note indicating it's from IMAP mailbox Intelligent Filtering: The workflow evaluates each email against spam filter criteria: Emails from "noreply" or "no-reply" addresses are filtered out Emails with "newsletter" in the subject line are filtered out Filtered emails receive notification but no auto-reply Legitimate emails proceed to AI response generation AI Response Generation: For emails that pass the filter: The AI reads the full email content Analyzes the main topic or purpose Generates a personalized acknowledgment Creates a professional response that: Thanks the sender References the specific topic Promises a personal follow-up Maintains professional tone Automatic Reply Delivery: The AI-generated response is sent via SMTP to the original sender with: Subject line: "Re: [Original Subject]" From address: Your monitored mailbox Body: AI-generated contextual message Response Confirmation: After the auto-reply is sent, you receive a second Telegram notification showing: Original email details (sender, subject, date) The complete AI-generated response text Confirmation of successful delivery Understanding AI Response Generation The AI analyzes emails intelligently: Example 1: Business Inquiry Incoming Email: "I'm interested in your consulting services for our Q4 project..." AI Topic Identification: "consulting services" Generated Response: "Dear Correspondent! Thank you for your message regarding consulting services. I will respond with a personal message as soon as possible. Have a nice day!" Example 2: Technical Support Incoming Email: "We're experiencing issues with the API integration..." AI Topic Identification: "API integration issues" Generated Response: "Dear Correspondent! Thank you for your message regarding API integration issues. I will respond with a personal message as soon as possible. Have a nice day!" Example 3: General Question Incoming Email: "Could you provide more information about pricing?" AI Topic Identification: "pricing information" Generated Response: "Dear Correspondent! Thank you for your message regarding pricing information. I will respond with a personal message as soon as possible. Have a nice day!" Customizing Filter Rules To modify which emails receive AI-generated auto-replies: Open the "Dedicate Filtering As No-Response" node Modify existing conditions or add new ones: Block specific domains: {{ $json.from.value[0].address }} Operation: does not contain Value: @spam-domain.com Whitelist VIP senders (only respond to specific people): {{ $json.from.value[0].address }} Operation: contains Value: @important-client.com Filter by subject keywords: {{ $json.subject.toLowerCase() }} Operation: does not contain Value: unsubscribe Combine multiple conditions: Use AND logic (all must be true) for stricter filtering Use OR logic (any can be true) for more permissive filtering Customizing AI Prompt To change how the AI generates responses: Open the "Basic LLM Chain" node Modify the prompt text in the "text" parameter Current structure: Context setting (read email, identify topic) Output format specification Rules for AI behavior Example modifications: Add company branding: Return only this response, filling in the [TOPIC]: Dear Correspondent! Thank you for reaching out to [Your Company Name] regarding [TOPIC]. I will respond with a personal message as soon as possible. Best regards, [Your Name] [Your Company Name] Make it more casual: Return only this response, filling in the [TOPIC]: Hi there! Thanks for your email about [TOPIC]. I'll get back to you personally soon. Cheers! Add urgency classification: Read the email and classify urgency (Low/Medium/High). Identify the main topic. Return: Dear Correspondent! Thank you for your message regarding [TOPIC]. Priority: [URGENCY] I will respond with a personal message as soon as possible. Customizing Telegram Notifications Incoming Email Notification: Open "Send Notification from Incoming Email" node Modify the "text" parameter Available variables: {{ $json.from }} - Full sender info {{ $json.from.value[0].address }} - Sender email only {{ $json.from.value[0].name }} - Sender name (if available) {{ $json.subject }} - Email subject {{ $json.date }} - Date received {{ $json.textPlain }} - Email body (use cautiously for privacy) {{ $json.to }} - Recipient address Response Confirmation Notification: Open "Send Notification from Response" node Modify to include additional information Reference AI response: {{ $('Basic LLM Chain').item.json.text }} Monitoring and Maintenance Daily Monitoring Check Telegram Notifications**: Review incoming email alerts and response confirmations Verify AI Quality**: Spot-check AI-generated responses for appropriateness Email Delivery**: Confirm auto-replies are being delivered (not caught in spam) Weekly Maintenance Review Execution Logs**: Check n8n execution history for errors or warnings Ollama Performance**: Monitor resource usage (CPU, RAM, disk space) Filter Effectiveness**: Assess if spam filters are working correctly Response Quality**: Review multiple AI responses for consistency Monthly Maintenance Update Ollama Model**: Check for new llama3.1 versions or alternative models Prompt Optimization**: Refine AI prompt based on response quality observations Credential Rotation**: Update passwords and API tokens for security Backup Configuration**: Export workflow and credentials (securely) Advanced Usage Multi-Language Support If you receive emails in multiple languages: Modify the AI prompt to detect language: Detect the email language. Generate response in the SAME language as the email. If English: [English template] If Hungarian: [Hungarian template] If German: [German template] Or use language-specific conditions in the filtering node Priority-Based Responses Generate different responses based on sender importance: Add an IF node after filtering to check sender domain Route VIP emails to a different LLM chain with priority messaging Standard emails use the normal AI chain Response Logging To maintain a record of all AI interactions: Add a database node (PostgreSQL, MySQL, etc.) after the auto-reply node Store: timestamp, sender, subject, AI response, delivery status Use for compliance, analytics, or training data A/B Testing AI Prompts Test different prompt variations: Create multiple LLM Chain nodes with different prompts Use a randomizer or round-robin approach Compare response quality and user feedback Optimize based on results Troubleshooting Notifications Not Received Problem: Telegram notifications not appearing Solutions: Verify Chat ID is correct (positive for personal chats, negative for groups) Check if bot has permissions to send messages Ensure bot wasn't blocked or removed from group Test Telegram API credential independently Review n8n execution logs for Telegram API errors AI Responses Not Generated Problem: Auto-replies sent but content is empty or error messages Solutions: Check Ollama service is running: ollama list Verify llama3.1 model is downloaded: ollama list Test Ollama directly: ollama run llama3.1 "Test message" Review Ollama API credential URL in n8n Check network connectivity between n8n and Ollama Increase context window if emails are very long Monitor Ollama logs for errors Poor Quality AI Responses Problem: AI generates irrelevant or inappropriate responses Solutions: Review and refine the prompt engineering Add more specific rules and constraints Provide examples in the prompt of good vs bad responses Adjust topic word count (increase from 2-4 to 3-6 words) Test with different Ollama models (e.g., llama3.1:70b for better quality) Ensure email content is being passed correctly to AI Auto-Replies Not Sent Problem: Workflow executes but emails not delivered Solutions: Verify SMTP credentials and server connectivity Check fromEmail address is correct Review SMTP server logs for errors Test SMTP sending independently Ensure "Allow unauthorized certificates" is enabled if needed Check if emails are being filtered by spam filters Verify SPF/DKIM records for your domain High Resource Usage Problem: Ollama consuming excessive CPU/RAM Solutions: Reduce context window size (from 4096 to 2048) Use a smaller model variant (llama3.1:8b instead of default) Limit concurrent workflow executions in n8n Add delay/throttling between email processing Consider using a remote Ollama instance with better hardware Monitor email volume and processing time IMAP Connection Failures Problem: Workflow can't connect to email server Solutions: Verify IMAP credentials are correct Check if IMAP is enabled on email account Ensure SSL/TLS settings match server requirements For Gmail: enable "Less secure app access" or use App Passwords Check firewall allows outbound connections on IMAP port (993) Test IMAP connection using email client (Thunderbird, Outlook) Workflow Not Triggering Problem: Workflow doesn't execute automatically Solutions: Verify workflow is in "Active" state Check trigger node configuration and schedule Review n8n system logs for scheduler issues Ensure n8n instance has sufficient resources Test manual execution to isolate trigger issues Check if n8n workflow execution queue is backed up Workflow Architecture Node Descriptions Check Incoming Emails - IMAP: Polls email server at regular intervals to retrieve new messages from the configured mailbox. Send Notification from Incoming Email: Immediately sends formatted notification to Telegram for every new email detected, regardless of spam status. Dedicate Filtering As No-Response: Evaluates emails against spam filter criteria to determine if AI processing should occur. No Operation: Placeholder node for filtered emails that should not receive an auto-reply (spam, newsletters, automated messages). Ollama Model: Provides the AI language model (llama3.1) used for natural language processing and response generation. Basic LLM Chain: Executes the AI prompt against the email content to generate contextual auto-reply text. Send Auto-Response in SMTP: Sends the AI-generated acknowledgment email back to the original sender via SMTP server. Send Notification from Response: Sends confirmation to Telegram showing the auto-reply was successfully sent, including the AI-generated content. AI Processing Pipeline Email Content Extraction: Email body text is extracted from IMAP data Context Loading: Email content is passed to LLM with prompt instructions Topic Analysis: AI identifies main subject or purpose in 2-4 words Template Population: AI fills response template with identified topic Output Formatting: Response is formatted and cleaned for email delivery Quality Assurance: n8n validates response before sending