An intelligent B2B lead qualification system built with n8n that automatically captures, researches, scores, and syncs qualified business leads from Lightspeed to Pipedrive CRM.
This automation system eliminates manual lead qualification by using AI-powered research to evaluate business customers from your Lightspeed e-commerce platform. It intelligently scores leads (0-10), enriches company data through web research, and automatically synchronizes qualified leads to your Pipedrive CRM.
Problem Solved: Manual lead qualification is time-consuming and inconsistent. This system automates the entire process from order receipt to CRM entry, ensuring only high-quality B2B leads reach your sales pipeline.
- Real-Time Webhook Processing - Captures new orders instantly from Lightspeed
- AI-Powered Lead Research - Uses Google Gemini to research and evaluate companies
- Intelligent Lead Scoring - Scores leads 0-10 based on business potential
- Duplicate Prevention - Maintains data integrity with unique customer tracking
- Complete Order History - Analyzes total orders, paid orders, and revenue
- Automated CRM Sync - Daily batch processing to Pipedrive at 9:00 PM (CET)
- Smart Updates - Refreshes existing leads with new order data
- Interactive Dashboard - Web-based interface to monitor leads and configure settings
- Priority Queue - Processes highest-scoring leads first
βββββββββββββββββββ
β Lightspeed β
β E-commerce β
ββββββββββ¬βββββββββ
β Webhook (New Order)
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β n8n Workflow Engine β
β β
β ββββββββββββββββ ββββββββββββββββ β
β β Webhook βββββββββΆβ Duplicate β β
β β Receiver β β Check β β
β ββββββββββββββββ βββββββββ¬βββββββ β
β β β
β βββββββββββββββ΄ββββββββββ β
β βΌ βΌ β
β ββββββββββββββββ ββββββββββββββββ β
β βUpdate Existingβ β New Lead β β
β β Lead β β AI Agent β β
β ββββββββββββββββ βββββββββ¬βββββββ β
β β β
β βββββββββββΌβββββββ β
β β Web Search β β
β β AI Agent β β
β β (Gemini API) β β
β βββββββββββ¬βββββββ β
β β β
β βββββββββββΌβββββββ β
β β Lead Scoring β β
β β (Score > 5) β β
β βββββββββββ¬βββββββ β
β β β
β βββββββββββΌβββββββ β
β β Database β β
β β (Queued) β β
β ββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β Scheduled Trigger (9 PM Daily)
βΌ
ββββββββββββββββββββ
β Pipedrive β
β CRM β
β β
β β’ Organization β
β β’ Person β
β β’ Deal β
β β’ Note β
ββββββββββββββββββββ
Purpose: Handles incoming orders, performs AI qualification, and manages database operations.
Flow:
- Webhook Trigger - Listens for new Lightspeed orders
- Business Filter - Validates if customer is a business (B2B)
- Duplicate Check - Queries database using unique Lightspeed customer ID
- Path Split:
- Existing Customer: Updates database and Pipedrive records
- New Customer: Triggers AI research workflow
Base AI Agent:
- Interprets company information from Lightspeed
- Generates natural language search queries
- Evaluates if sufficient data has been collected
- Makes final qualification decision
Web Search AI Agent:
- Receives queries from Base Agent
- Executes multiple web searches via Google Gemini Grounding API
- Returns summarized text chunks about the company
- Iterates until Base Agent has enough information
Decision Logic:
IF AI Decision = "NO" β Stop processing
IF AI Decision = "YES" AND Lead Score > 5 β Add to queue
ELSE β Stop processing
Purpose: Pushes qualified leads to Pipedrive on a schedule.
Trigger: Daily at 21:00 (9:00 PM) Netherlands time
Process:
- Fetches batch size limit from KVS configuration table
- Retrieves all leads with status = "queued"
- Sorts by lead_score (highest first)
- Limits to configured batch size
- Loops through each lead:
- Creates Organization in Pipedrive
- Creates Person (contact)
- Creates Deal (pipeline stage 1)
- Creates Note (AI summary + order history)
- Updates lead status to "processed"
- Stores Pipedrive IDs in database
Purpose: Analyzes complete order history from Lightspeed.
Data Retrieved:
- Total number of orders
- Count of paid orders
- Total revenue from paid orders (β¬)
Calculation:
paidOrders = orders.filter(order => order.status === 'paid')
totalValue = sum(paidOrders.map(order => order.priceIncl))
totalValue = round(totalValue, 2)Purpose: Provides web interface for monitoring and configuration.
Endpoint: GET /verpakkingenxl
Features:
- Real-time lead monitoring with filters
- Status tracking (queued/processed)
- Location and score filtering
- Sortable data table with pagination
- Lead detail modal popups
- KVS configuration editor
Purpose: Updates system configuration via dashboard.
Endpoint: POST /update-kvs
Updates:
- AI system prompts
- Batch size limits
- Other configuration parameters
Purpose: Global error handler that automatically sends email alerts when any workflow fails.
Trigger: Error Trigger (catches failures from all workflows)
Process:
- Error Trigger - Detects when any workflow execution fails
- Edit Error Message - Formats error details into styled HTML email with:
- Workflow name that failed
- Error message from the failed node
- Name of the node that caused the failure
- Direct link to the execution details
- Notify User - Sends email notification via SMTP
Email Template Features:
- Mobile-responsive HTML design
- Professional styling with clear error highlighting
- System tag: "verpakkingenxl β Lead Processing System"
- Monospace formatting for technical details
- Direct link to view full execution in n8n
Configuration Required:
- SMTP credentials in n8n
- Update
fromEmailandtoEmailin the "Notify User" node
Note: This workflow acts as a safety net for the entire system, ensuring you're immediately notified of any issues in the lead processing pipeline.
Configure these in n8n's credential manager:
-
Lightspeed API (HTTP Basic Auth)
- Username: API Key
- Password: API Secret
- Base URL:
api.webshopapp.com
-
Pipedrive API (Query Auth)
- Parameter:
api_token - Value: Your Pipedrive API token
- Parameter:
-
Google Gemini API
- API Key from Google Cloud Console
-
Google Custom Search
- Search Engine ID (cx)
- API Key
-
SMTP Account (for error notifications)
- Host: Your SMTP server
- Port: Usually 587 or 465
- Username: Your email address
- Password: Your email password or app-specific password
- Secure: False
- Clone this repository:
git clone https://github.com/anas-farooq8/verpakkingenxl.git
cd verpakkingenxl- Import workflows into n8n:
- Open n8n interface
- Go to Workflows β Import from File
- Import each JSON file from
/workflowsfolder
Create two data tables in your n8n instance:
Main lead database with columns:
| Column Name | Type | Description |
|---|---|---|
| lightspeed_customer_id | String | Unique customer identifier (Primary Key) |
| company_name | String | Business name |
| coc_number | String | Chamber of Commerce number |
| vat_number | String | VAT registration number |
| contact_name | String | Contact person name |
| String | Email address | |
| phone | String | Phone number |
| address | String | Full address |
| city | String | City |
| country | String | Country |
| ai_decision | String | YES/NO |
| ai_score | Number | Lead score 0-10 |
| ai_reason | Text | AI evaluation summary |
| total_orders | Number | Total order count |
| paid_orders | Number | Paid order count |
| total_value | Number | Total revenue (β¬) |
| status | String | queued/processed |
| pipedrive_org_id | String | Pipedrive Organization ID |
| pipedrive_person_id | String | Pipedrive Person ID |
| pipedrive_deal_id | String | Pipedrive Deal ID |
| pipedrive_note_id | String | Pipedrive Note ID |
| created_at | DateTime | Record creation timestamp |
| updated_at | DateTime | Last update timestamp |
Configuration key-value store:
| Column Name | Type | Description |
|---|---|---|
| key | String | Configuration key (Primary Key) |
| value | Text | Configuration value |
Required Keys:
system_prompt_base_agent- AI prompt for base agentsystem_prompt_web_search_agent- AI prompt for search agenttotal_limit- Batch processing size (e.g., "100")
-
Open each workflow in n8n
-
Update credential references:
- Lightspeed API nodes β Select your Lightspeed credential
- Pipedrive API nodes β Select your Pipedrive credential
- Google Gemini nodes β Select your Gemini credential
- SMTP nodes (in Error Notification workflow) β Select your SMTP credential
-
Configure Error Notification workflow:
- Open the "Notify-On-Error" workflow
- Update the "Notify User" node:
- Set
fromEmailto your sender email address - Set
toEmailto the admin/recipient email address
- Set
- Activate the workflow
- Go to Pipedrive β Settings β Data fields β Organization
- Create custom fields and note their IDs:
| Field Name | Field Type | Example ID |
|---|---|---|
| Lightspeed ID | Text | 1a654f5d... |
| Total Orders | Numeric | ae01b186... |
| Paid Orders | Numeric | 0a516666... |
| Total Value | Monetary | a785a890... |
| Lead Score | Numeric | e62dba18... |
| Estimated Shipping Volume | Text | 13096dc6... |
| Logistics Type | Text | 5df1b60a... |
| CoC Number | Text | 7e89f763... |
| VAT Number | Text | c1b3f8b6... |
- Update field IDs in workflow nodes:
- Open "Create Organization" node
- Replace field IDs with your actual IDs
- Repeat for "Update Organization" node
-
Get your Pipedrive pipeline ID and first stage ID:
- Go to Pipedrive β Settings β Pipelines
- Note the pipeline ID and first stage ID
-
Update in workflow:
- Open "Create Deal" node
- Set
pipeline_idandstage_id
- Activate the main workflow to generate webhook URL
- Copy the webhook URL from the "Webhook" node
- Option A: Use the "Create Webhook" helper node
- Update URL in the node
- Execute once manually
- Option B: Register manually in Lightspeed backend:
- Go to Lightspeed β API β Webhooks
- Create new webhook for "Order Created" event
- Paste your webhook URL
- Populate the KVS table with initial values:
-- Example prompts (customize for your business)
INSERT INTO verpakkingenxl_kvs (key, value) VALUES
('system_prompt_base_agent', 'You are a B2B lead qualification expert...'),
('system_prompt_web_search_agent', 'You are a web research specialist...'),
('total_limit', '100');- Or use the dashboard to configure via UI
-
Test Webhook:
- Create a test B2B order in Lightspeed
- Check n8n execution log
- Verify database entry
-
Test AI Research:
- Ensure a new company triggers AI workflow
- Check AI decision and score in database
-
Test Batch Processing:
- Manually trigger the scheduled workflow
- Verify leads appear in Pipedrive
- Check all 4 records created (Org, Person, Deal, Note)
-
Test Dashboard:
- Access dashboard URL
- Verify lead data displays correctly
- Test KVS configuration updates
-
Test Error Notifications:
- Manually trigger a workflow failure (e.g., invalid credentials)
- Verify you receive an email notification
- Check email formatting and execution link
Customize the AI behavior by editing the system prompts in the KVS table:
Base Agent Prompt Example:
You are a B2B lead qualification expert for a packaging company.
Analyze the provided company information and determine if they are
a good fit for our business.
Evaluate based on:
- Company size and shipping volume potential
- Industry relevance (e-commerce, manufacturing, retail)
- Geographic location and market presence
- Legitimacy and business maturity
Provide:
1. Decision: YES or NO
2. Score: 0-10 (where 10 is highest priority)
3. Detailed reasoning for your decision
Web Search Agent Prompt Example:
You are a web research specialist. Given a company name and details,
search the internet to find:
- Company size and employee count
- Business model and products/services
- Shipping and logistics needs
- Market presence and reputation
- Industry and sector information
Return concise, factual information that helps evaluate the company
as a potential B2B customer for packaging supplies.
Adjust the number of leads processed daily:
UPDATE verpakkingenxl_kvs
SET value = '50'
WHERE key = 'total_limit';Modify the batch processing time:
- Open the "Schedule Trigger" node
- Change the cron expression or time
- Save workflow
Access the dashboard at: https://your-n8n-instance.com/webhook/verpakkingenxl
Dashboard Features:
-
Filters:
- Status: All, Queued, Processed
- Location: Filter by city/country
- Lead Score: Minimum score threshold
-
Lead Table:
- Sortable columns
- Pagination (20 records per page)
- Click row for detailed view
-
KVS Configuration Tab:
- Edit AI prompts
- Adjust batch size
- Save changes via POST request
Organization:
- Name, address, contact details
- Custom fields: metrics, IDs, scores
- Linked to Person
Person:
- Contact name, email, phone
- Label: "B2B Contact"
- Linked to Organization
Deal:
- Title: "New Business Lead β [Company Name]"
- Pipeline: Stage 1
- Source: Lightspeed
- Linked to Organization and Person
Note:
- AI qualification summary
- Complete order history
- Lead score and reasoning
- Pinned to Deal
Symptoms: No executions when orders are placed
Solutions:
- Verify webhook is registered in Lightspeed
- Check workflow is activated
- Use "Get All Webhooks" node to verify registration
- Test with webhook URL directly using Postman
Symptoms: Leads stuck in processing, no AI decision
Solutions:
- Verify Google Gemini API credentials
- Check API quota limits
- Review system prompts for errors
- Check n8n execution logs for API errors
Symptoms: Status shows "queued" but no CRM records
Solutions:
- Verify Pipedrive API token is valid
- Check custom field IDs match your Pipedrive setup
- Verify pipeline and stage IDs are correct
- Manually trigger batch workflow to check errors
- Review Pipedrive API rate limits
Symptoms: Same company appears multiple times
Solutions:
- Check if
lightspeed_customer_idis being stored correctly - Verify duplicate check logic is working
- Clear and rebuild database if corrupted
- Check for multiple webhook registrations
Symptoms: 404 or blank page
Solutions:
- Verify dashboard workflow is activated
- Check webhook URL is correct
- Review data table connections
- Check browser console for JavaScript errors
Symptoms: Workflows fail but no email received
Solutions:
- Verify Error Notification workflow is activated
- Check SMTP credentials are configured correctly
- Verify
fromEmailandtoEmailare set in "Notify User" node - Check spam/junk folder for notification emails
- Test SMTP connection with a simple email node
- Review email server logs for delivery issues
- Ensure firewall/network allows SMTP connections