Take-Home Assignment

AI & Automation Architecture

End-to-end automation design for CybeReact's cybersecurity incident response pipeline

Prepared by: Avi Kaner
Position: AI & Automation Specialist
Date: March 2026

New Client Intake Automation

From contact form submission to assigned rep with AI-enriched context — in seconds, not minutes.

Design principle: Scam victims are distressed. Every automation decision prioritizes trust and human oversight. AI accelerates the process — a human delivers the empathy.

Automation Flow

1
Victim Submits Contact Form
WordPress form captures name, email, phone, and free-text description of the incident. Client sees a confirmation message: "We received your inquiry and will respond within 24 hours."
WordPress
2
Webhook Fires to Zoho Flow
Form submission triggers a real-time webhook. Zero manual intervention — the pipeline starts the moment the form is submitted.
Webhook → Zoho Flow
3
AI Classification & Extraction
Zoho Flow sends the raw text to Claude API via a Deluge HTTP call. The AI extracts and returns structured data:
Scam Type Amount Lost Urgency Level Contact Details Structured Summary
Claude API via Deluge
4
CRM Record Created
A lead record is created in Zoho CRM with all structured fields populated: scam type, amount, urgency, AI summary, and source tracking. No data lost — raw form text preserved alongside AI interpretation.
Zoho CRM
5
AI Drafts Response Email
Claude generates a professional, empathetic first-response email tailored to the scam type and specifics of the victim's situation. The draft is stored in the CRM record — not auto-sent. A human reviews and sends it.
Claude API → Zoho CRM Draft
6
Slack Alert + Rep Assignment
Team receives a Slack notification: "New lead — [scam type] — [urgency]" with a claim button. Assignment logic:
  • Primary: Match rep specialization tags in Zoho (e.g., "crypto fraud," "romance scam")
  • Secondary: Round-robin based on current workload
  • Fallback: First to click the claim button
Slack API
7
Rep Reviews & Sends Email
The assigned rep opens the CRM record, reviews the AI-drafted email, personalizes if needed, and sends manually. This human-in-the-loop step ensures every first contact is appropriate for a distressed individual.
Human in the Loop
8
Follow-Up Scheduled
A Zoho task and Google Calendar event are automatically created for the assigned rep — typically a follow-up call within 48 hours. Nothing falls through the cracks.
Zoho Tasks + Google Calendar API

Implementation: The Claude API Prompt

This is the actual system prompt that powers step 3. It's where domain knowledge meets automation — the AI doesn't guess, it follows a defined taxonomy.

System Prompt Claude API — Intake Classification
// System prompt sent with every intake form submission

You are an intake classifier for a cybersecurity incident response firm
that helps scam victims. Analyze the following form submission and
extract structured data.

CLASSIFICATION TAXONOMY (use exactly these categories):
- rug_pull: Token/project disappeared with funds (DeFi, NFT)
- phishing: Signed malicious transaction, gave seed phrase, wallet drain
- romance_scam: Social engineering via dating/social media
- pig_butchering: Fake trading platform, locked withdrawals
- impersonation: Fake support agent, exchange rep, government official
- investment_fraud: Ponzi, fake yield, unlicensed broker
- recovery_scam: Scammer posing as recovery service (re-victimization)
- other: Doesn't match — flag for manual review

URGENCY RULES:
- Amount > $50K → high
- Incident within 72 hours → high (funds may be recoverable)
- Active threat indicators → critical
- Emotional distress markers (suicidal ideation, desperation) → critical + flag
- Recovery scam indicators → critical
- Everything else → assess from context

RETURN FORMAT (strict JSON):
{
  "scam_type": "category_from_taxonomy",
  "amount_lost": "extracted amount or 'not specified'",
  "currency": "USD/BTC/ETH/etc",
  "urgency": "low | medium | high | critical",
  "urgency_reason": "one-line explanation",
  "contact": {
    "name": "",
    "email": "",
    "phone": ""
  },
  "summary": "2-3 sentence summary of the incident",
  "key_entities": ["wallet addresses, domains, names mentioned"],
  "needs_manual_review": false,
  "draft_email": "professional, empathetic first response (3-4 paragraphs)"
}

Implementation: Zoho Flow Deluge Script

This is the Deluge code that runs inside Zoho Flow when the webhook fires. It calls Claude, parses the response, and creates the CRM record.

Deluge Zoho Flow — Webhook Handler
// Triggered when WordPress form webhook fires
// Input: form_data (Map) from webhook payload

// 1. Call Claude API for classification
headers = Map();
headers.put("x-api-key", zoho.encryption.getDecryptedValue("claude_api_key"));
headers.put("anthropic-version", "2023-06-01");
headers.put("content-type", "application/json");

payload = Map();
payload.put("model", "claude-sonnet-4-20250514");
payload.put("max_tokens", 2048);
payload.put("system", system_prompt);  // prompt from above
payload.put("messages", {
  {"role": "user", "content": form_data.get("message")}
});

response = invokeurl[
  url: "https://api.anthropic.com/v1/messages"
  type: POST
  headers: headers
  parameters: payload.toString()
];

// 2. Parse AI response
ai_data = response.get("content").get(0).get("text");
parsed = ai_data.toJSON();

// 3. Create Zoho CRM Lead
lead = Map();
lead.put("Last_Name", parsed.get("contact").get("name"));
lead.put("Email", parsed.get("contact").get("email"));
lead.put("Phone", parsed.get("contact").get("phone"));
lead.put("Scam_Type", parsed.get("scam_type"));
lead.put("Amount_Lost", parsed.get("amount_lost"));
lead.put("Urgency", parsed.get("urgency"));
lead.put("AI_Summary", parsed.get("summary"));
lead.put("Email_Draft", parsed.get("draft_email"));
lead.put("Raw_Submission", form_data.get("message"));
lead.put("Lead_Source", "Website Form");

crm_response = zoho.crm.createRecord("Leads", lead);
lead_id = crm_response.get("id");

// 4. Send Slack notification
slack_msg = "*New Lead — " + parsed.get("scam_type") + " — " + parsed.get("urgency").toUpperCase() + "*\n";
slack_msg = slack_msg + "Amount: " + parsed.get("amount_lost") + "\n";
slack_msg = slack_msg + parsed.get("summary");
// Slack webhook call here...

// 5. Create follow-up task
task = Map();
task.put("Subject", "Follow-up call: " + parsed.get("contact").get("name"));
task.put("Due_Date", zoho.currentdate.addDay(2));
zoho.crm.createRecord("Tasks", task);

What the Team Sees: Slack Alert

When a new lead comes in, the team's #intake channel gets this:

#intake-alerts — Slack
C
CybeReact Bot APP 2:34 PM
New Lead — Pig Butchering — HIGH
Scam Type Pig Butchering (fake trading platform)
Amount $87,000 USD
Urgency HIGH — 6-figure loss, platform may still be live
Summary Victim met someone on Instagram who introduced them to a trading platform. Deposited over 3 months. Platform now blocking withdrawals. Wallet shows funds moved to mixing service.
Claim This Lead View in CRM

What the CRM Record Looks Like

This is what the rep sees when they open the auto-created lead — every field populated by AI in seconds:

Zoho CRM — Lead Record
Sarah Mitchell — New Lead
AI-Enriched
Contact Information
Full Name
Sarah Mitchell
Email
sarah.mitchell@gmail.com
Phone
+1 (415) 555-0183
Lead Source
Website Form (Google Ads — utm_campaign=crypto_recovery)
AI Classification
Scam Type
Pig Butchering
Amount Lost
$87,000 USD
Urgency
HIGH
Urgency Reason
6-figure loss, fake platform may still be live, funds partially traced to mixing service
Key Entities
0x7a3f...b42e (deposit wallet), cryptoprime-fx.com (scam platform)
AI Summary
Victim was contacted via Instagram by an individual claiming to be a crypto trader. Over 3 months, she was guided to deposit funds into "CryptoPrime FX," a fake trading platform showing fabricated returns. Total deposits: $87K across 4 transactions to wallet 0x7a3f...b42e. Platform now blocking withdrawals citing "tax verification." Blockchain analysis shows funds moved through a mixing service within 48h of each deposit.
AI-Drafted Email Response DRAFT — NOT SENT

AI Scam Classification Taxonomy

The Claude API prompt includes a domain-specific taxonomy for crypto and financial scams. This ensures consistent categorization across all intake submissions.

Scam Type Description Urgency Signal
Rug Pull Token/project disappears with invested funds. Often DeFi-related. High — funds often irrecoverable after 48h
Phishing / Wallet Drain Victim signed a malicious transaction or gave seed phrase access. Critical — active drain may be in progress
Romance Scam Long-term social engineering via dating apps/social media. Gradual fund extraction. Medium — ongoing, but victim may not realize scope
Pig Butchering Hybrid romance/investment scam. Fake trading platform shows profits, then locks withdrawals. High — often 6-figure losses
Impersonation Fake support agent, exchange rep, or government official requests funds/access. High — may be actively cooperating with scammer
Investment Fraud Ponzi scheme, fake yield platform, unlicensed broker. Variable — depends on whether platform is still operational
Recovery Scam Scammer posing as recovery service to extract more from prior victim. Critical — victim being re-victimized
Other / Unclassified Doesn't match known categories. Flagged for manual review. Review required

AI Urgency Assessment

The AI assigns urgency based on multiple signals extracted from the submission:

  • Amount lost: > $50K automatically escalates to high urgency
  • Recency: Incidents within the last 72 hours are flagged — some funds may be recoverable
  • Emotional language: Markers of acute distress (suicidal ideation, desperation) trigger immediate human review
  • Active threat: If the scam appears to be ongoing, urgency is elevated
  • Re-victimization: Recovery scam indicators push to critical

Error Handling

Every failure mode has a defined fallback. No submission is ever lost.

Zoho CRM API Down
Lead data can't be written to CRM.
Mitigation: Retry queue in Zoho Flow — hold data in memory, retry every 2 minutes, max 5 attempts. Raw submission logged separately as backup.
Claude API Classification Fails
AI can't extract structured data from submission.
Mitigation: CRM record created with raw unprocessed text. Flagged as "Needs Manual Review." Team still gets Slack alert. No lead is lost.
Slack Notification Fails
Team doesn't receive the alert for a new lead.
Mitigation: Fallback email sent to team lead. CRM record exists regardless — Zoho dashboard shows unassigned leads.
Webhook Not Received
Form submitted but webhook didn't fire.
Mitigation: WordPress shows confirmation to client. Daily reconciliation job compares form submission log vs CRM records — any gaps are flagged to ops.
Any Unhandled Failure
Something unexpected breaks in the pipeline.
Mitigation: Catch-all alert to Slack #ops channel with error details and the original form payload. Nothing is silently dropped.

Time Impact

Before
20–30 min
Manual read → classify → CRM entry → draft email → assign
After
~15 sec
Automated pipeline + human review time for email

* The automation runs in seconds. Total time-to-first-response depends on rep availability for email review — but the prep work is done before the rep even opens the ticket.

Investigation Intelligence Tool

Multi-source OSINT aggregation with AI analysis — from a single search target to a structured intelligence report.

Core principle: Raw data and AI analysis are always clearly separated. Until the system is calibrated through real cases, AI interpretation is labeled as advisory — not fact.

Input & Trigger

An investigator enters a search target via an n8n form or a Zoho CRM button. Supported target types:

Domain Name Company Name Wallet Address Individual Name Linked to Client Ticket (optional)

If triggered from a client's CRM record (linked to Task 1 intake), the intake form data automatically enriches the investigation context — scam description, claimed addresses, dates, and amounts are pre-loaded.

Data Sources & APIs

n8n orchestrates parallel calls to multiple intelligence sources. Each source returns structured data with source URL and timestamp.

Source API Returns
Domain Intel WHOIS XML API Registration dates, registrant info, DNS history, name server changes
Blockchain Etherscan API + Alchemy RPC Transaction history, wallet connections, token holdings, fund flow patterns
Corporate Records OpenCorporates API Company registration, directors, filings, jurisdiction, status
Social Profiles SerpAPI / Apify LinkedIn, Twitter, and other social profiles linked to the entity
Infrastructure Shodan API Server info, hosting history, associated domains, open ports
Threat Intel VirusTotal API Domain/URL reputation, malware associations, community reports

Processing Pipeline

1
Target Input
Investigator enters target identifier. If linked to a CRM ticket, intake data is pre-loaded as context.
n8n Form / Zoho CRM Button
2
Parallel API Collection
n8n fires all applicable API calls simultaneously. Target type determines which sources are queried — a wallet address queries Etherscan + VirusTotal; a domain queries WHOIS + Shodan + VirusTotal; a company name queries OpenCorporates + SerpAPI.
n8n Parallel Execution
3
Data Aggregation
All API responses are merged into a structured JSON payload. Every data point includes its source URL and collection timestamp. If any API fails, the report generates with available data + a "source unavailable" flag.
n8n Data Merge
4
AI Analysis
Claude API receives the aggregated raw data and produces: threat assessment, entity connections (wallet → company → person), red flags, anomalies, and recommended next steps. All AI output is clearly labeled as interpretation.
Claude API via n8n HTTP Node
5
Triple Output
Report is delivered in three formats simultaneously:
  • Zoho CRM: Custom "Investigation" module linked to client record
  • HTML Report: Styled, visual, shareable with lawyers/regulators
  • Slack Summary: Team alert with key findings + link to full report
Zoho CRM + HTML + Slack

Raw Data vs. AI Analysis Separation

Why this matters: Investigation reports may be used in legal proceedings or shared with regulators. Raw data (verifiable facts from APIs) must never be confused with AI interpretation (pattern analysis, threat assessment). The report clearly delineates both.
Raw Data Section
  • Every data point has a source URL
  • Collection timestamp on each entry
  • Original API response preserved
  • "Source unavailable" flag if API failed
  • No editorialization or interpretation
AI Analysis Section
  • Labeled "AI-GENERATED ANALYSIS"
  • Threat assessment summary
  • Entity connection mapping
  • Red flags and anomalies
  • Recommended next investigation steps

Integration with Client Intake (Task 1)

When an investigation is triggered from a client's CRM record, the system automatically pulls intake data:

This creates a continuous intelligence thread from first contact through investigation.

Implementation: n8n Workflow Config

This is the core workflow definition — the part that actually runs. Each node is a step in the pipeline.

JSON n8n Workflow — Investigation Pipeline (simplified)
// Key nodes from the n8n workflow
{
  "nodes": [
    {
      "name": "Webhook Trigger",
      "type": "n8n-nodes-base.webhook",
      "parameters": {
        "path": "investigate",
        "method": "POST"
      }
    },
    {
      "name": "Route by Target Type",
      "type": "n8n-nodes-base.switch",
      "parameters": {
        "rules": [
          { "value": "wallet", "output": 0 },
          { "value": "domain", "output": 1 },
          { "value": "company", "output": 2 }
        ]
      }
    },
    {
      "name": "Etherscan Lookup",
      "type": "n8n-nodes-base.httpRequest",
      "parameters": {
        "url": "https://api.etherscan.io/api",
        "qs": {
          "module": "account",
          "action": "txlist",
          "address": "={{ $json.target }}"
        }
      }
    },
    {
      "name": "WHOIS Lookup",
      "type": "n8n-nodes-base.httpRequest",
      "parameters": {
        "url": "https://www.whoisxmlapi.com/whoisserver/WhoisService",
        "qs": {
          "domainName": "={{ $json.target }}",
          "outputFormat": "JSON"
        }
      }
    },
    {
      "name": "Merge All Sources",
      "type": "n8n-nodes-base.merge",
      "parameters": { "mode": "append" }
    },
    {
      "name": "Claude Analysis",
      "type": "n8n-nodes-base.httpRequest",
      "parameters": {
        "url": "https://api.anthropic.com/v1/messages",
        "method": "POST",
        "body": {
          "model": "claude-sonnet-4-20250514",
          "system": "You are an investigation analyst...",
          "messages": [{ "role": "user", "content": "={{ JSON.stringify($json) }}" }]
        }
      }
    },
    {
      "name": "Save to Supabase",
      "type": "n8n-nodes-base.supabase",
      "parameters": {
        "operation": "create",
        "table": "investigations"
      }
    }
  ]
}

What the Report Looks Like

This is the output an investigator gets — raw data with source attribution on top, AI analysis clearly separated below.

Investigation Report — INV-2026-0847
cryptoprime-fx.com
Linked to: Sarah Mitchell — Case #CYB-4521
Generated
2026-03-19 14:22 UTC
Raw Data Domain Intelligence
Registrar NameCheap Inc.
Created 2025-11-02
Expires 2026-11-02 (1-year registration)
Registrant REDACTED (privacy proxy: WhoisGuard)
Name Servers ns1.hostinger.com, ns2.hostinger.com
Hosting IP 185.199.110.153 (Hostinger, Lithuania)
Source: WHOIS XML API — collected 2026-03-19T14:22:03Z
Raw Data Blockchain Analysis
Wallet 0x7a3f...b42e
Total Received 142.8 ETH ($412,000 at receipt dates)
Unique Depositors 23 wallets
Outflows 138.2 ETH → 0xd91c...f8a1 (mixer) within 48h of each deposit
Current Balance 4.6 ETH
Source: Etherscan API — collected 2026-03-19T14:22:07Z
Raw Data Threat Intelligence
VirusTotal 7/87 vendors flagged as malicious
Community 3 user reports — "fake trading platform," "withdrawal scam"
Source: VirusTotal API — collected 2026-03-19T14:22:05Z
AI Analysis Threat Assessment Claude Sonnet 4 — advisory only

High confidence: Organized pig butchering operation.

Pattern indicators: (1) Domain registered 4 months ago on budget hosting with privacy proxy — typical throwaway infrastructure. (2) 23 unique depositors suggests multiple victims, not a one-off. (3) Systematic 48-hour fund cycling to mixer is a known laundering pattern, not manual withdrawals. (4) VirusTotal community reports align with victim testimony.

Entity connections: The deposit wallet 0x7a3f...b42e connects to mixer 0xd91c...f8a1, which has been flagged in 4 prior investigations (source: our internal DB). Hosting IP shared with 2 other recently-flagged domains: crypto-yield-pro.com, btcprime-trading.net.

Recommended next steps: (1) Check if mixer output wallets have touched any exchanges with KYC — potential for law enforcement subpoena. (2) Cross-reference the 23 depositor wallets against known victim databases. (3) Archive domain content before it goes offline.

Future Optimizations

  • Full Ethereum node: Eliminates API rate limits for high-volume wallet investigations. Worth the infrastructure cost when investigation volume justifies it.
  • Custom threat intelligence database: Historical investigations build a proprietary dataset — known scam wallets, recurring infrastructure patterns, associated entities. Each investigation makes the next one smarter.
  • Automated re-investigation triggers: Monitor flagged wallets for new activity. When funds move, automatically re-run the investigation and alert the team.

Architecture & Tool Selection

Three tools, clear roles, zero overlap — and the full system architecture connecting them.

The Three-Tool Backbone

🏢
Zoho CRM
Source of Truth

Client records, case status, rep assignments, email drafts, payment tracking. Every team member looks here.

🗄️
Supabase
Data Backbone

Investigation data, ad attribution, analytics, AI results, audit logs. Real SQL for real queries — not locked behind a CRM UI.

n8n
Nervous System

Orchestration layer. Connects everything, stores nothing. Replaces Zoho Flow where needed, handles parallel API calls, AI integration.

Why These Three

Data Architecture — Who Holds What

System What It Stores Role
Zoho CRM Client records, case status, rep assignments, email drafts, payment status Client-facing source of truth
Supabase Investigation raw data, ad attribution (UTM + click IDs), analytics, AI analysis results, audit logs Data backbone for queries & analytics
n8n No persistent data — orchestration only Connects everything
WordPress Website content, contact form Entry point only
Google/Meta Ads Ad spend, impressions, clicks Lead source (data piped to Supabase)
Gmail Email communication Endpoint (triggered from CRM)
Google Calendar Scheduled calls/meetings Endpoint (created by automation)
WhatsApp Business Client chat messages Communication channel

Integration Map

Every connection between systems, the protocol used, and why that method was chosen.

Connection Method Why This Method
WordPress → n8n Webhook Real-time trigger, zero latency, WordPress supports webhooks natively
n8n → Zoho CRM Zoho REST API n8n has a native Zoho node. Create/update records programmatically
n8n → Claude API HTTP Request AI classification (Task 1) + investigation analysis (Task 2)
n8n → Supabase Supabase API / direct PostgreSQL Store investigation data, analytics, audit logs
n8n → Slack Native Slack node Team notifications, lead alerts, investigation-ready alerts
n8n → Gmail Gmail API node Send emails after human approval in CRM
n8n → Google Calendar Google Calendar API Auto-create follow-up reminders for reps
Google Ads → Supabase n8n scheduled pull Daily/hourly sync for ad attribution analytics
Meta Ads → Supabase n8n scheduled pull Same — attribution tracking for paid social
WordPress → Supabase Via n8n (same webhook) Log raw form submission as audit record
Zoho CRM → WhatsApp Zoho Flow / n8n Client updates via WhatsApp during case lifecycle
Supabase → Zoho CRM n8n triggered/scheduled Push investigation results back to client record

System Architecture

Entry Points
🌐
WordPress
Contact Form
📱
WhatsApp
Client Chat
📣
Google Ads
Lead Source
📣
Meta Ads
Lead Source
Orchestration
n8n
Workflow Engine — Webhooks, API Calls, AI, Routing
🤖
Claude API
Classification, Analysis, Email Drafting
Data Layer
🏢
Zoho CRM
Client Records, Cases, Assignments, Payments
🗄️
Supabase
Investigations, Analytics, Attribution, Audit Logs
Outputs & Communication
💬
Slack
Team Alerts
📧
Gmail
Client Emails
📅
Calendar
Follow-ups
📄
HTML Reports
Investigations

Single Points of Failure & Mitigations

n8n Goes Down
Critical
All automations stop. No webhooks processed, no API calls, no routing.
Mitigation: Self-hosted on a reliable server with PM2 process manager for auto-restart. Health check cron pings every minute — failure triggers Slack alert to #ops. Manual process documented as fallback (team knows how to do intake without automation).
Zoho CRM API Down
High
Can't create or update client records.
Mitigation: n8n retry queue holds data and retries every 2 minutes (max 5 attempts). Supabase stores raw submission as backup — nothing is lost even if CRM is down for hours.
Claude API Down
Medium
No AI classification, no email drafts, no investigation analysis.
Mitigation: CRM record created with raw unprocessed text, flagged "Needs Manual Review." Investigation reports generate with raw data only — AI analysis section shows "unavailable." System degrades gracefully, never stops.
Supabase Down
Medium
Analytics and investigation data unavailable. No audit logs.
Mitigation: Zoho CRM still has all client records. n8n logs errors for replay. Supabase has automated daily backups + point-in-time recovery. Analytics gap is backfilled when service returns.
Webhook Missed
Low
Form submission not processed by the pipeline.
Mitigation: WordPress shows confirmation to client (and sends receipt email). Daily reconciliation job compares WordPress form log vs CRM records — gaps are flagged automatically.

The Client Journey — Ad Click to Case Resolution

📣
Google/Meta Ad — Victim clicks ad (UTM tracked)
🌐
WordPress Landing Page — Contact form submitted
n8n Webhook — Pipeline starts instantly
🤖
Claude AI — Classifies scam type, extracts data, assesses urgency, drafts email
🏢
Zoho CRM — Lead created with all structured fields + Supabase audit log
💬
Slack Alert — Rep claims or gets auto-assigned based on specialization
👤
Rep Reviews & Sends — AI-drafted email personalized and sent manually
🔍
Investigation (Task 2) — OSINT aggregation + AI analysis on scam entities
⚖️
Legal Team — Picks up case with full investigation report
📊
Case Lifecycle — Stages tracked in Zoho CRM through resolution
Resolution — Payment recorded, full journey analytics in Supabase

Implementation: Supabase Schema

This is what the Supabase database actually looks like. These tables power investigation storage, ad attribution, and audit logging — the things CRM can't handle well.

SQL Supabase — Core Tables
-- Investigation data from Task 2 pipeline
CREATE TABLE investigations (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  crm_lead_id   text,          -- links back to Zoho CRM record
  target        text NOT NULL, -- domain, wallet, company name
  target_type   text NOT NULL, -- 'wallet' | 'domain' | 'company' | 'person'
  raw_data      jsonb,         -- full API responses with source URLs
  ai_analysis   jsonb,         -- Claude output, clearly separated
  threat_level  text,          -- 'low' | 'medium' | 'high' | 'critical'
  status        text DEFAULT 'completed',
  created_at    timestamptz DEFAULT now()
);

-- Ad attribution: which campaigns bring real clients
CREATE TABLE ad_attribution (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  crm_lead_id   text,
  utm_source    text,          -- google, meta, organic
  utm_campaign  text,          -- campaign name
  utm_medium    text,
  gclid         text,          -- Google Click ID
  fbclid        text,          -- Meta Click ID
  landing_page  text,
  converted     boolean DEFAULT false,
  conversion_value numeric,    -- actual case value (for ROAS)
  created_at    timestamptz DEFAULT now()
);

-- Audit log: every action in the system
CREATE TABLE audit_log (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  event_type    text NOT NULL, -- 'intake' | 'investigation' | 'email_sent' | 'status_change'
  actor         text,          -- 'system' | rep email | 'ai'
  crm_lead_id   text,
  payload       jsonb,         -- full event data
  created_at    timestamptz DEFAULT now()
);

-- Known scam entities: grows with every investigation
CREATE TABLE known_entities (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  entity        text NOT NULL, -- wallet, domain, or name
  entity_type   text NOT NULL,
  threat_level  text,
  first_seen    timestamptz,
  investigation_ids uuid[],   -- linked investigations
  notes         text,
  created_at    timestamptz DEFAULT now()
);

-- Row-level security: reps see only their cases
ALTER TABLE investigations ENABLE ROW LEVEL SECURITY;
CREATE POLICY "reps_own_cases" ON investigations
  USING (auth.uid() = assigned_rep_id OR auth.jwt() ->> 'role' = 'admin');

* The known_entities table is the secret weapon — every investigation automatically feeds it, so the system gets smarter with every case. After 100 investigations, you have a proprietary threat database that no off-the-shelf tool provides.

Future Optimizations

  • Analytics dashboard: Zoho Analytics or Metabase connected to Supabase — CEO-level visibility into pipeline health, lead conversion, and case outcomes.
  • Automated monthly reports: Cost per lead, conversion rate by ad campaign, average case duration, recovery success rate — generated and distributed automatically.
  • WhatsApp status bot: Clients check case status via WhatsApp message. Reduces inbound calls, improves client satisfaction during stressful wait periods.