import { useState, useRef, useEffect } from "react"; import { Alert, AlertDescription, AlertTitle } from "@/components/ds/ui/alert"; import { Button } from "@/components/ds/ui/button"; import { Input } from "@/components/ds/ui/input"; import { Label } from "@/components/ds/ui/label"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ds/ui/card"; import { AlertCircle, Database, ExternalLink, Loader2, Terminal, ChevronDown, ChevronRight, } from "lucide-react"; import { toast } from "sonner"; import { Collapsible, CollapsibleContent, CollapsibleTrigger, } from "@/components/ds/ui/collapsible"; interface DatabaseSetupGuideProps { missingTables: string[]; supabaseUrl: string; } export function DatabaseSetupGuide({ missingTables, supabaseUrl, }: DatabaseSetupGuideProps) { const projectRef = supabaseUrl.match(/https:\/\/([^.]+)\.supabase\.co/)?.[1]; // Auto-Migration State const [isMigrating, setIsMigrating] = useState(false); const [migrationLogs, setMigrationLogs] = useState([]); const [dbPassword, setDbPassword] = useState(""); const [accessToken, setAccessToken] = useState(""); const logsEndRef = useRef(null); const [manualOpen, setManualOpen] = useState(false); // Scroll logs useEffect(() => { if (logsEndRef.current) { logsEndRef.current.scrollIntoView({ behavior: "smooth" }); } }, [migrationLogs]); const handleAutoMigrate = async () => { if (!projectRef) { toast.error("Could not determine Project ID from Supabase URL."); return; } setIsMigrating(true); setMigrationLogs(["🚀 Initializing migration process..."]); try { const response = await fetch("/api/migrate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ projectRef, dbPassword, accessToken, }), }); if (!response.ok) { throw new Error( `Server returned ${response.status}: ${response.statusText}`, ); } const reader = response.body?.getReader(); if (!reader) throw new Error("No response stream received."); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = decoder.decode(value); const lines = text.split("\n").filter(Boolean); setMigrationLogs((prev) => [...prev, ...lines]); } // Auto-reload on success (simple check for "success" in logs or just finish) toast.success("Migration process completed. Reloading..."); setTimeout(() => window.location.reload(), 2000); } catch (err) { console.error(err); setMigrationLogs((prev) => [ ...prev, `❌ Error: ${err instanceof Error ? err.message : String(err)}`, ]); toast.error("Migration failed. See logs for details."); } finally { setIsMigrating(false); } }; return (
Database Schema Not Configured Your Supabase database is connected, but the CRM schema hasn't been set up yet. {/* Auto-Migration Card */}
Automatic Setup (Recommended)
We can automatically set up the database tables and policies for you.
Generate Token
setAccessToken(e.target.value)} disabled={isMigrating} />
setDbPassword(e.target.value)} disabled={isMigrating} />
{/* Logs Terminal */}
{migrationLogs.length === 0 ? (
Logs will appear here...
) : ( migrationLogs.map((log, i) => (
{log}
)) )}
{/* Manual Setup (Collapsed by default) */}
Manual Setup Instructions
{manualOpen ? ( ) : ( )}
Advanced: Run commands manually if automatic setup fails
{/* Missing Tables */}

Missing Tables:

{missingTables.map((table) => ( {table} ))}
{/* Option 1: Supabase CLI */}
1

Using Supabase CLI

Install Supabase CLI:

                      npm install -g supabase
                    
{/* ... rest of CLI steps ... */}

Link to your Supabase project:

                      supabase link --project-ref{" "}
                      {projectRef || "YOUR_PROJECT_REF"}
                    

Push the migrations:

                      supabase db push
                    
{/* Option 2: SQL Editor */}
2

Using Supabase SQL Editor

Manually run the SQL migrations in your Supabase SQL Editor:

  1. Download migrations from{" "} GitHub
  2. Open your{" "} Supabase SQL Editor
  3. Run each migration file in order (by date in filename)
{/* Additional Resources */} Need Help? View Full Setup Guide Report an Issue
); }