Monitor customer risk and AI feedback using PostgreSQL, Gmail and Discord
How it works
This workflow monitors customer health by combining payment behavior, complaint signals, and AI-driven feedback analysis. It runs on daily and weekly schedules to evaluate risk levels, escalate high-risk customers, and generate structured product insights. High-risk cases are notified instantly, while detailed feedback and audit logs are stored for long-term analysis.
Step-by-step
-
Step 1: Triggers & mode selection
- Daily Risk Check Trigger – Starts the workflow on a daily schedule.
- Weekly schedule1 – Triggers the workflow for weekly summary runs.
- Edit Fields3 – Sets flags for daily execution.
- Edit Fields2 – Sets flags for weekly execution.
- Switch1 – Routes execution based on daily or weekly mode.
-
Step 2: Risk evaluation & escalation
- Fetch Customer Risk Data – Pulls customer, payment, product, and complaint data from PostgreSQL.
- Is High Risk Customer? – Evaluates payment status and complaint count.
- Prepare Escalation Summary For Low Risk User – Assigns low-risk status and no-action details.
- Prepare Escalation Summary For High Risk User – Assigns high-risk status and escalation actions.
- Merge Risk Result – Combines low-risk and high-risk customer records.
- Send a message4 – Sends the customer risk summary via Gmail.
- Send a message5 – Sends the same risk summary to Discord.
- Code in JavaScript3 – Appends notification status and timestamps.
- Append or update row in sheet3 – Logs risk evaluations and notification status in Google Sheets.
-
Step 3: AI feedback & reporting
- Get row(s) in sheet1 – Fetches customer records for feedback analysis.
- Loop Over Items1 – Processes customers one by one.
- Prompt For Model1 – Builds a structured prompt for product feedback analysis.
- HTTP Request1 – Sends data to the AI model for insight generation.
- Code in JavaScript – Merges AI feedback with original customer data.
- Append or update row in sheet – Stores AI-generated feedback in Google Sheets.
- Wait1 – Controls execution pacing between records.
- Merge1 – Prepares consolidated feedback data.
- Send a message1 – Emails the final AI-powered feedback report.
Why use this?
- Detect customer churn risk early using payment and complaint signals
- Automatically escalate high-risk customers without manual monitoring
- Convert raw customer issues into executive-ready product insights
- Keep a complete audit trail of risk, feedback, and notifications
- Align support, product, and leadership teams with shared visibility
Monitor Customer Risk and AI Feedback using PostgreSQL, Gmail, and Discord
This n8n workflow automates the process of monitoring customer risk by fetching data from a PostgreSQL database, analyzing it, and then sending alerts via Gmail and Discord based on predefined risk criteria. It also incorporates a feedback loop for human review.
What it does
This workflow performs the following key steps:
- Scheduled Trigger: The workflow is initiated on a schedule (e.g., daily, hourly) to regularly check for new customer data.
- Fetch Customer Data from PostgreSQL: It queries a PostgreSQL database to retrieve customer information.
- Process and Transform Data: The fetched data is then processed and transformed using a "Set" node, likely to format it for subsequent analysis or to extract relevant fields.
- Loop Through Customer Records: The workflow iterates through each customer record, allowing individual processing.
- Analyze Customer Risk (HTTP Request): For each customer, an HTTP request is made, likely to an external AI service or an internal API, to assess customer risk based on the provided data.
- Conditional Logic for Risk Assessment:
- High Risk: If the AI feedback indicates a "High Risk" customer, the workflow proceeds to send an alert.
- Low Risk: If the AI feedback indicates "Low Risk", the workflow merges these items and potentially logs them or takes no further action in this specific flow.
- Send High-Risk Alert via Gmail: For high-risk customers, an email alert is sent via Gmail, likely to a risk management team.
- Send High-Risk Alert via Discord: Simultaneously, a notification is posted to a Discord channel, ensuring immediate visibility for the relevant team.
- Human-in-the-Loop (Wait Node): After sending alerts, the workflow includes a "Wait" node, which could be used to pause the workflow, awaiting manual review or acknowledgment of the high-risk customer.
- Record AI Feedback in Google Sheets: The AI feedback for each customer (both high and low risk) is recorded in a Google Sheet, providing a centralized log for review and auditing.
- Code Execution for Further Processing (Optional): A "Code" node is included, which can be used for custom JavaScript logic, such as further data manipulation, logging, or integration with other systems based on the AI feedback.
Prerequisites/Requirements
To use this workflow, you will need:
- n8n Instance: A running n8n instance.
- PostgreSQL Database: Access to a PostgreSQL database containing customer data. You will need the necessary credentials (host, port, database, user, password).
- Gmail Account: A configured Gmail credential in n8n to send email alerts.
- Discord Account/Webhook: A Discord credential or webhook URL configured in n8n to post messages to a Discord channel.
- Google Sheets Account: A Google Sheets credential in n8n to write AI feedback data.
- External AI Service/API: An endpoint for an HTTP Request node that can analyze customer data and return a risk assessment (e.g., "High Risk", "Low Risk").
Setup/Usage
- Import the workflow: Download the provided JSON and import it into your n8n instance.
- Configure Credentials:
- Set up your PostgreSQL credentials in n8n.
- Set up your Gmail credentials in n8n.
- Set up your Discord credentials (or webhook) in n8n.
- Set up your Google Sheets credentials in n8n.
- Update Node Configurations:
- Postgres Node: Configure the "Postgres" node to connect to your database and specify the query to fetch customer data.
- HTTP Request Node: Update the URL and any necessary headers/body for your AI risk assessment service.
- If Node: Adjust the conditions in the "If" node if your AI service returns different risk classifications.
- Gmail Node: Customize the recipient, subject, and body of the email alert for high-risk customers.
- Discord Node: Customize the message content and target channel for Discord alerts.
- Google Sheets Node: Specify the Spreadsheet ID and sheet name where AI feedback should be recorded.
- Schedule Trigger: Adjust the schedule to your desired frequency for monitoring.
- Wait Node: Configure the duration for the "Wait" node if human intervention is required.
- Code Node: Implement any custom JavaScript logic as needed.
- Activate the Workflow: Once all configurations are complete, activate the workflow.
Related Templates
Send WooCommerce discount coupons to customers via WhatsApp using Rapiwa API
Who is this for? This workflow is ideal for WooCommerce store owners who want to automatically send promotional WhatsApp messages to their customers when new coupons are created. It’s designed for marketers and eCommerce managers looking to boost engagement, streamline coupon sharing, and track campaign performance effortlessly through Google Sheets. Overview This workflow listens for WooCommerce coupon creation events (coupon.created) and uses customer billing data to send promotional WhatsApp messages via the Rapiwa API. The flow formats the coupon data, cleans phone numbers, verifies WhatsApp registration with Rapiwa, sends the promotional message when verified, and logs each attempt to Google Sheets (separate sheets for verified/sent and unverified/not sent). What this Workflow Does Listens for new coupon creation events in WooCommerce via the WooCommerce Trigger node Retrieves all customer data from the WooCommerce store Processes customers in batches to control throughput Cleans and formats customer phone numbers for WhatsApp Verifies if phone numbers are valid WhatsApp accounts using Rapiwa API Sends personalized WhatsApp messages with coupon details to verified numbers Logs all activities to Google Sheets for tracking and analysis Handles both verified and unverified numbers appropriately Key Features Automated coupon distribution: Triggers when new coupons are created in WooCommerce Customer data retrieval: Fetches all customer information from WooCommerce Phone number validation: Verifies WhatsApp numbers before sending messages Personalized messaging: Includes customer name and coupon details in messages Dual logging system: Tracks both successful and failed message attempts Rate limiting: Uses batching and wait nodes to prevent API overload Data formatting: Structures coupon information for consistent messaging Google Sheet Column Structure A Google Sheet formatted like this ➤ sample The workflow uses a Google Sheet with the following columns to track coupon distribution: | name | number | email | address1 | couponCode | couponTitle | couponType | couponAmount | createDate | expireDate | validity | status | | ----------- | ------------- | --------------------------------------------------- | --------- | ---------- | -------------- | ---------- | ------------ | ------------------- | ------------------- | ---------- | -------- | | Abdul Mannan | 8801322827799 | contact@spagreen.net | mirpur-DOHS | 62dhryst | eid offer 2025 | percent | 20.00 | 2025-09-11 06:08:02 | 2025-09-15 00:00:00 | unverified | not sent | | Abdul Mannan | 8801322827799 | contact@spagreen.net | mirpur-DOHS | 62dhryst | eid offer 2025 | percent | 20.00 | 2025-09-11 06:08:02 | 2025-09-15 00:00:00 | verified | sent | Requirements n8n instance with the following nodes: WooCommerce Trigger, Code, SplitInBatches, HTTP Request, IF, Google Sheets, Wait WooCommerce store with API access Rapiwa account with API access for WhatsApp verification and messaging Google account with Sheets access Customer phone numbers in WooCommerce (stored in billing.phone field) Important Notes Phone Number Format: The workflow cleans phone numbers by removing all non-digit characters. Ensure your WooCommerce phone numbers are in a compatible format. API Rate Limits: Rapiwa and WooCommerce APIs have rate limits. Adjust batch sizes and wait times accordingly. Data Privacy: Ensure compliance with data protection regulations when sending marketing messages. Error Handling: The workflow logs unverified numbers but doesn't have extensive error handling. Consider adding error notifications for failed API calls. Message Content: The current message template references the first coupon only (coupons[0]). Adjust if you need to handle multiple coupons. Useful Links Dashboard: https://app.rapiwa.com Official Website: https://rapiwa.com Documentation: https://docs.rapiwa.com Support & Help WhatsApp: Chat on WhatsApp Discord: SpaGreen Community Facebook Group: SpaGreen Support Website: https://spagreen.net Developer Portfolio: Codecanyon SpaGreen
Generate Weather-Based Date Itineraries with Google Places, OpenRouter AI, and Slack
🧩 What this template does This workflow builds a 120-minute local date course around your starting point by querying Google Places for nearby spots, selecting the top candidates, fetching real-time weather data, letting an AI generate a matching emoji, and drafting a friendly itinerary summary with an LLM in both English and Japanese. It then posts the full bilingual plan with a walking route link and weather emoji to Slack. 👥 Who it’s for Makers and teams who want a plug-and-play bilingual local itinerary generator with weather awareness — no custom code required. ⚙️ How it works Trigger – Manual (or schedule/webhook). Discovery – Google Places nearby search within a configurable radius. Selection – Rank by rating and pick the top 3. Weather – Fetch current weather (via OpenWeatherMap). Emoji – Use an AI model to match the weather with an emoji 🌤️. Planning – An LLM writes the itinerary in Markdown (JP + EN). Route – Compose a Google Maps walking route URL. Share – Post the bilingual itinerary, route link, and weather emoji to Slack. 🧰 Requirements n8n (Cloud or self-hosted) Google Maps Platform (Places API) OpenWeatherMap API key Slack Bot (chat:write) LLM provider (e.g., OpenRouter or DeepL for translation) 🚀 Setup (quick) Open Set → Fields: Config and fill in coords/radius/time limit. Connect Credentials for Google, OpenWeatherMap, Slack, and your LLM. Test the workflow and confirm the bilingual plan + weather emoji appear in Slack. 🛠 Customize Adjust ranking filters (type, min rating). Modify translation settings (target language or tone). Change output layout (side-by-side vs separated). Tune emoji logic or travel mode. Add error handling, retries, or logging for production use.
Competitor intelligence agent: SERP monitoring + summary with Thordata + OpenAI
Who this is for? This workflow is designed for: Marketing analysts, SEO specialists, and content strategists who want automated intelligence on their online competitors. Growth teams that need quick insights from SERP (Search Engine Results Pages) without manual data scraping. Agencies managing multiple clients’ SEO presence and tracking competitive positioning in real-time. What problem is this workflow solving? Manual competitor research is time-consuming, fragmented, and often lacks actionable insights. This workflow automates the entire process by: Fetching SERP results from multiple search engines (Google, Bing, Yandex, DuckDuckGo) using Thordata’s Scraper API. Using OpenAI GPT-4.1-mini to analyze, summarize, and extract keyword opportunities, topic clusters, and competitor weaknesses. Producing structured, JSON-based insights ready for dashboards or reports. Essentially, it transforms raw SERP data into strategic marketing intelligence — saving hours of research time. What this workflow does Here’s a step-by-step overview of how the workflow operates: Step 1: Manual Trigger Initiates the process on demand when you click “Execute Workflow.” Step 2: Set the Input Query The “Set Input Fields” node defines your search query, such as: > “Top SEO strategies for e-commerce in 2025” Step 3: Multi-Engine SERP Fetching Four HTTP request tools send the query to Thordata Scraper API to retrieve results from: Google Bing Yandex DuckDuckGo Each uses Bearer Authentication configured via “Thordata SERP Bearer Auth Account.” Step 4: AI Agent Processing The LangChain AI Agent orchestrates the data flow, combining inputs and preparing them for structured analysis. Step 5: SEO Analysis The SEO Analyst node (powered by GPT-4.1-mini) parses SERP results into a structured schema, extracting: Competitor domains Page titles & content types Ranking positions Keyword overlaps Traffic share estimations Strengths and weaknesses Step 6: Summarization The Summarize the content node distills complex data into a concise executive summary using GPT-4.1-mini. Step 7: Keyword & Topic Extraction The Keyword and Topic Analysis node extracts: Primary and secondary keywords Topic clusters and content gaps SEO strength scores Competitor insights Step 8: Output Formatting The Structured Output Parser ensures results are clean, validated JSON objects for further integration (e.g., Google Sheets, Notion, or dashboards). Setup Prerequisites n8n Cloud or Self-Hosted instance Thordata Scraper API Key (for SERP data retrieval) OpenAI API Key (for GPT-based reasoning) Setup Steps Add Credentials Go to Credentials → Add New → HTTP Bearer Auth* → Paste your Thordata API token. Add OpenAI API Credentials* for the GPT model. Import the Workflow Copy the provided JSON or upload it into your n8n instance. Set Input In the “Set the Input Fields” node, replace the example query with your desired topic, e.g.: “Google Search for Top SEO strategies for e-commerce in 2025” Execute Click “Execute Workflow” to run the analysis. How to customize this workflow to your needs Modify Search Query Change the search_query variable in the Set Node to any target keyword or topic. Change AI Model In the OpenAI Chat Model nodes, you can switch from gpt-4.1-mini to another model for better quality or lower cost. Extend Analysis Edit the JSON schema in the “Information Extractor” nodes to include: Sentiment analysis of top pages SERP volatility metrics Content freshness indicators Export Results Connect the output to: Google Sheets / Airtable for analytics Notion / Slack for team reporting Webhook / Database for automated storage Summary This workflow creates an AI-powered Competitor Intelligence System inside n8n by blending: Real-time SERP scraping (Thordata) Automated AI reasoning (OpenAI GPT-4.1-mini) Structured data extraction (LangChain Information Extractors)