Public Access
1
0

feat: migrate app to local Fastify and Postgres stack

Replace Supabase auth and search runtime with a local Fastify API, PostgreSQL/PostGIS schema, and local session handling. Scaffold the worker and deep-research foundations while keeping the existing research, dashboard, and map flows running on the new backend.
This commit is contained in:
pguerrerox
2026-03-27 13:56:54 +00:00
parent 0e4910805a
commit a1ba5ee093
44 changed files with 3756 additions and 1128 deletions
+92 -90
View File
@@ -1,21 +1,22 @@
import { type ReactElement, type SVGProps, useEffect, useState } from 'react';
import type { User } from '@supabase/supabase-js';
import { APIProvider } from '@vis.gl/react-google-maps';
import { AlertCircle, Briefcase, LogIn, ShieldAlert, UserPlus } from 'lucide-react';
import { Layout } from './components/Layout';
import { SearchSetup } from './components/SearchSetup';
import { Dashboard } from './components/Dashboard';
import { MapView } from './components/MapView';
import { hasSupabaseConfig, supabase } from './lib/supabase';
import type { AppUser } from '../shared/types';
import { getLocalSessionUser, signInWithLocalAuth, signOutWithLocalAuth, signUpWithLocalAuth } from './lib/auth';
import { hasApiConfig } from './lib/api';
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_PLATFORM_KEY ?? '';
const hasValidMapsKey = Boolean(GOOGLE_MAPS_API_KEY) && GOOGLE_MAPS_API_KEY !== 'YOUR_API_KEY';
export default function App() {
const [user, setUser] = useState<User | null>(null);
const [user, setUser] = useState<AppUser | null>(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'setup' | 'dashboard' | 'map'>('setup');
const [selectedJobId, setSelectedJobId] = useState<string | null>(null);
const [selectedJobIds, setSelectedJobIds] = useState<string[]>([]);
const [authError, setAuthError] = useState<string | null>(null);
const [authNotice, setAuthNotice] = useState<string | null>(null);
const [isAuthenticating, setIsAuthenticating] = useState(false);
@@ -28,99 +29,96 @@ export default function App() {
let isMounted = true;
const loadSession = async () => {
const { data, error } = await supabase.auth.getSession();
try {
const sessionUser = await getLocalSessionUser();
if (!isMounted) {
return;
if (!isMounted) {
return;
}
setUser(sessionUser);
} catch (error) {
if (!isMounted) {
return;
}
setAuthError(error instanceof Error ? error.message : 'Failed to load session.');
} finally {
if (isMounted) {
setLoading(false);
}
}
if (error) {
setAuthError(error.message);
}
setUser(data.session?.user ?? null);
setLoading(false);
};
void loadSession();
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
if (!isMounted) {
return;
}
setUser(session?.user ?? null);
setLoading(false);
});
return () => {
isMounted = false;
subscription.unsubscribe();
};
}, []);
const handleSelectJob = (jobId: string) => {
setSelectedJobId(jobId);
const handleToggleJobSelection = (jobId: string) => {
setSelectedJobIds((currentJobIds) =>
currentJobIds.includes(jobId) ? currentJobIds.filter((currentJobId) => currentJobId !== jobId) : [...currentJobIds, jobId],
);
};
const handleSelectCreatedJob = (jobId: string) => {
setSelectedJobIds((currentJobIds) => (currentJobIds.includes(jobId) ? currentJobIds : [...currentJobIds, jobId]));
};
const handleShowSelectedOnMap = () => {
if (selectedJobIds.length === 0) {
return;
}
setActiveTab('map');
};
const handleClearSelectedJobs = () => {
setSelectedJobIds([]);
};
const handleLogin = async () => {
setAuthError(null);
setAuthNotice(null);
setIsAuthenticating(true);
if (authMode === 'sign_up') {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
full_name: displayName.trim() || undefined,
},
},
});
try {
if (authMode === 'sign_up') {
const nextUser = await signUpWithLocalAuth({
email,
password,
displayName: displayName.trim() || undefined,
});
if (error) {
setAuthError(error.message);
setIsAuthenticating(false);
setUser(nextUser);
setAuthNotice('Account created and signed in.');
return;
}
setAuthNotice(
data.session
? 'Account created and signed in.'
: 'Account created. If email confirmation is enabled, check your inbox before signing in.',
);
const nextUser = await signInWithLocalAuth({
email,
password,
});
setUser(nextUser);
} catch (error) {
setAuthError(error instanceof Error ? error.message : 'Authentication failed.');
} finally {
setIsAuthenticating(false);
return;
}
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
setAuthError(error.message);
setIsAuthenticating(false);
return;
}
setIsAuthenticating(false);
};
const handleLogout = async () => {
const { error } = await supabase.auth.signOut();
if (error) {
setAuthError(error.message);
return;
try {
await signOutWithLocalAuth();
setUser(null);
setSelectedJobIds([]);
setAuthNotice(null);
} catch (error) {
setAuthError(error instanceof Error ? error.message : 'Failed to sign out.');
}
setSelectedJobId(null);
setAuthNotice(null);
};
if (loading) {
@@ -131,33 +129,33 @@ export default function App() {
);
}
if (!hasSupabaseConfig) {
if (!hasApiConfig) {
return (
<ConfigScreen
icon={<ShieldAlert className="h-8 w-8" />}
title="Supabase Config Required"
description="Add your Supabase project URL and anon key before running the app."
title="Local API Config Required"
description="Add your local API base URL before running the app."
steps={[
'Create a Supabase project.',
'Add VITE_SUPABASE_URL to your local environment.',
'Add VITE_SUPABASE_ANON_KEY to your local environment.',
'Start the local Fastify API server.',
'Add VITE_API_BASE_URL to your local environment.',
'Ensure the API can reach your local PostgreSQL database.',
'Restart the Vite dev server after updating env vars.',
]}
footer="The app uses Supabase Auth, Postgres, and Edge Functions now."
footer="The app now uses a local API, PostgreSQL, and local session auth."
/>
);
}
if (!hasValidMapsKey) {
return (
<ConfigScreen
icon={<MapIcon className="h-8 w-8" />}
title="Google Maps API Key Required"
description="Add a browser key for map rendering and a server key for the Supabase search function."
<ConfigScreen
icon={<MapIcon className="h-8 w-8" />}
title="Google Maps API Key Required"
description="Add a browser key for map rendering and a server key for the local search API."
steps={[
'Create a Google Maps Platform API key for the browser app.',
'Set VITE_GOOGLE_MAPS_PLATFORM_KEY locally for the frontend.',
'Set GOOGLE_MAPS_SERVER_KEY in Supabase Edge Function secrets.',
'Set GOOGLE_MAPS_SERVER_KEY for the local API server.',
'Enable Geocoding API and Places API in Google Cloud.',
]}
footer="The app will start once the browser key is available."
@@ -173,8 +171,8 @@ export default function App() {
<div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100 text-emerald-600">
<Briefcase className="h-8 w-8" />
</div>
<h1 className="mt-6 text-3xl font-bold tracking-tight text-stone-900">Lead Finder</h1>
<p className="mt-2 text-stone-600">Use Supabase email auth to access your lead workspace.</p>
<h1 className="mt-6 text-3xl font-bold tracking-tight text-stone-900">Leads4less</h1>
<p className="mt-2 text-stone-600">Create a local account to access your lead workspace.</p>
</div>
<div className="grid grid-cols-2 gap-2 rounded-xl bg-stone-100 p-1">
@@ -298,17 +296,21 @@ export default function App() {
<Layout
user={user}
activeTab={activeTab}
setActiveTab={(tab) => {
setActiveTab(tab);
if (tab !== 'map') {
setSelectedJobId(null);
}
}}
setActiveTab={setActiveTab}
onLogout={() => void handleLogout()}
>
{activeTab === 'setup' && <SearchSetup user={user} onSelectJob={handleSelectJob} />}
{activeTab === 'setup' && (
<SearchSetup
user={user}
selectedJobIds={selectedJobIds}
onToggleJobSelection={handleToggleJobSelection}
onSelectCreatedJob={handleSelectCreatedJob}
onShowSelectedOnMap={handleShowSelectedOnMap}
onClearSelection={handleClearSelectedJobs}
/>
)}
{activeTab === 'dashboard' && <Dashboard user={user} />}
{activeTab === 'map' && <MapView user={user} jobId={selectedJobId} />}
{activeTab === 'map' && <MapView user={user} jobIds={selectedJobIds} />}
</Layout>
</APIProvider>
);
+3 -3
View File
@@ -1,5 +1,4 @@
import React, { useEffect, useMemo, useState } from 'react';
import type { User } from '@supabase/supabase-js';
import Papa from 'papaparse';
import {
ArrowUpDown,
@@ -16,13 +15,14 @@ import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { listBusinesses, listJobResultLinks, listSearchJobs, type SearchJobResultLink } from '../lib/database';
import type { Business, SearchJob } from '../types';
import type { AppUser } from '../../shared/types';
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
interface DashboardProps {
user: User;
user: AppUser;
}
export function Dashboard({ user }: DashboardProps) {
@@ -184,7 +184,7 @@ export function Dashboard({ user }: DashboardProps) {
<header className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
<h1 className="text-3xl font-bold tracking-tight text-stone-900">Lead Dashboard</h1>
<p className="mt-1 text-stone-600">Browse Supabase-backed search results and export targeted lead lists.</p>
<p className="mt-1 text-stone-600">Browse saved search results from your local workspace and export targeted lead lists.</p>
</div>
<button
onClick={handleExport}
+5 -5
View File
@@ -1,16 +1,16 @@
import React from 'react';
import type { User } from '@supabase/supabase-js';
import { Search, LayoutDashboard, Map as MapIcon, LogOut, Briefcase } from 'lucide-react';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { getUserAvatarUrl, getUserDisplayName } from '../lib/supabase';
import type { AppUser } from '../../shared/types';
import { getUserAvatarUrl, getUserDisplayName } from '../lib/auth';
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
interface LayoutProps {
user: User;
user: AppUser;
activeTab: 'setup' | 'dashboard' | 'map';
setActiveTab: (tab: 'setup' | 'dashboard' | 'map') => void;
onLogout: () => void;
@@ -22,7 +22,7 @@ export function Layout({ user, activeTab, setActiveTab, onLogout, children }: La
const userAvatarUrl = getUserAvatarUrl(user);
const navigation = [
{ id: 'setup', name: 'Setup', icon: Search },
{ id: 'setup', name: 'Research', icon: Search },
{ id: 'dashboard', name: 'Dashboard', icon: LayoutDashboard },
{ id: 'map', name: 'Map View', icon: MapIcon },
];
@@ -35,7 +35,7 @@ export function Layout({ user, activeTab, setActiveTab, onLogout, children }: La
<div className="bg-emerald-600 p-2 rounded-lg text-white">
<Briefcase className="h-6 w-6" />
</div>
<span className="font-bold text-xl tracking-tight text-stone-900">LeadFinder</span>
<span className="font-bold text-xl tracking-tight text-stone-900">Leads4less</span>
</div>
<nav className="flex-1 px-4 py-4 space-y-1">
+32 -10
View File
@@ -1,21 +1,22 @@
import React, { useEffect, useMemo, useState } from 'react';
import type { User } from '@supabase/supabase-js';
import { Map, AdvancedMarker, InfoWindow, Pin, useMap } from '@vis.gl/react-google-maps';
import { Globe, Loader2, MapPin, Navigation, Phone, Star } from 'lucide-react';
import { listBusinesses, listBusinessesForJob } from '../lib/database';
import { listBusinesses, listBusinessesForJobs } from '../lib/database';
import type { Business } from '../types';
import type { AppUser } from '../../shared/types';
interface MapViewProps {
user: User;
jobId?: string | null;
user: AppUser;
jobIds?: string[] | null;
}
export function MapView({ user, jobId }: MapViewProps) {
export function MapView({ user, jobIds }: MapViewProps) {
const map = useMap();
const [businesses, setBusinesses] = useState<Business[]>([]);
const [selected, setSelected] = useState<Business | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const selectedJobCount = jobIds?.length ?? 0;
useEffect(() => {
const loadBusinesses = async () => {
@@ -23,7 +24,7 @@ export function MapView({ user, jobId }: MapViewProps) {
setError(null);
try {
const nextBusinesses = jobId ? await listBusinessesForJob(user.id, jobId) : await listBusinesses(user.id);
const nextBusinesses = selectedJobCount > 0 ? await listBusinessesForJobs(user.id, jobIds ?? []) : await listBusinesses(user.id);
setBusinesses(nextBusinesses);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load map leads.');
@@ -33,7 +34,7 @@ export function MapView({ user, jobId }: MapViewProps) {
};
void loadBusinesses();
}, [jobId, user.id]);
}, [jobIds, selectedJobCount, user.id]);
useEffect(() => {
if (!selected) {
@@ -96,6 +97,25 @@ export function MapView({ user, jobId }: MapViewProps) {
);
}
if (businesses.length === 0) {
return (
<div className="flex flex-1 items-center justify-center bg-stone-50 p-8">
<div className="w-full max-w-lg rounded-3xl border border-stone-200 bg-white p-8 text-center shadow-sm">
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-stone-100 text-stone-500">
<MapPin className="h-6 w-6" />
</div>
<h2 className="mt-4 text-2xl font-bold text-stone-900">No leads to show on the map</h2>
<p className="mt-3 text-sm text-stone-600">
{selectedJobCount > 0
? 'The selected research jobs do not have saved map results yet. Try completed jobs or run the research again.'
: 'No saved leads are available yet. Run a research job to populate the map.'}
</p>
{error && <p className="mt-4 text-sm font-medium text-red-700">{error}</p>}
</div>
</div>
);
}
return (
<div className="relative flex-1 bg-stone-100">
{error && (
@@ -198,10 +218,12 @@ export function MapView({ user, jobId }: MapViewProps) {
<span className="text-stone-500">Selected Lead</span>
<span className="max-w-[120px] truncate font-bold text-stone-900">{selected ? selected.name : 'None'}</span>
</div>
{jobId && (
{selectedJobCount > 0 && (
<div className="mt-2 border-t border-stone-200 pt-2">
<p className="text-[10px] font-bold uppercase tracking-wider text-stone-400">Filtering by Job</p>
<p className="text-xs font-medium text-emerald-700 truncate">Active filter applied</p>
<p className="text-[10px] font-bold uppercase tracking-wider text-stone-400">Filtering by Selection</p>
<p className="text-xs font-medium text-emerald-700 truncate">
{selectedJobCount === 1 ? '1 selected research job' : `${selectedJobCount} selected research jobs`}
</p>
</div>
)}
</div>
+404 -133
View File
@@ -1,33 +1,78 @@
import React, { useCallback, useEffect, useState } from 'react';
import type { User } from '@supabase/supabase-js';
import { AlertCircle, CheckCircle2, History, Loader2, MapPin, Play } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
AlertCircle,
CalendarDays,
Check,
CheckCircle2,
CircleOff,
Clock3,
Loader2,
MapPin,
Play,
Search as SearchIcon,
SlidersHorizontal,
} from 'lucide-react';
import { listSearchJobs, runSearch } from '../lib/database';
import type { SearchJob } from '../types';
import type { SearchJob, SearchJobStatus } from '../types';
import type { AppUser } from '../../shared/types';
interface SearchSetupProps {
user: User;
onSelectJob: (jobId: string) => void;
user: AppUser;
selectedJobIds: string[];
onToggleJobSelection: (jobId: string) => void;
onSelectCreatedJob: (jobId: string) => void;
onShowSelectedOnMap: () => void;
onClearSelection: () => void;
}
export function SearchSetup({ user, onSelectJob }: SearchSetupProps) {
type JobStatusFilter = 'all' | SearchJobStatus;
type SortOption = 'newest' | 'oldest' | 'results';
const statusOptions: Array<{ value: JobStatusFilter; label: string }> = [
{ value: 'all', label: 'All statuses' },
{ value: 'pending', label: 'Pending' },
{ value: 'running', label: 'Running' },
{ value: 'completed', label: 'Completed' },
{ value: 'failed', label: 'Failed' },
{ value: 'stopped', label: 'Stopped' },
];
const sortOptions: Array<{ value: SortOption; label: string }> = [
{ value: 'newest', label: 'Newest first' },
{ value: 'oldest', label: 'Oldest first' },
{ value: 'results', label: 'Most results' },
];
export function SearchSetup({
user,
selectedJobIds,
onToggleJobSelection,
onSelectCreatedJob,
onShowSelectedOnMap,
onClearSelection,
}: SearchSetupProps) {
const [name, setName] = useState('');
const [location, setLocation] = useState('');
const [radius, setRadius] = useState(5);
const [businessType, setBusinessType] = useState('');
const [keywords, setKeywords] = useState('');
const [searchTerm, setSearchTerm] = useState('');
const [statusFilter, setStatusFilter] = useState<JobStatusFilter>('all');
const [sortOrder, setSortOrder] = useState<SortOption>('newest');
const [isSearching, setIsSearching] = useState(false);
const [isLoadingHistory, setIsLoadingHistory] = useState(true);
const [jobs, setJobs] = useState<SearchJob[]>([]);
const [error, setError] = useState<string | null>(null);
const selectedJobCount = selectedJobIds.length;
const refreshJobs = useCallback(async () => {
setIsLoadingHistory(true);
try {
const nextJobs = await listSearchJobs(user.id, 10);
const nextJobs = await listSearchJobs(user.id, 100);
setJobs(nextJobs);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load search history.');
setError(err instanceof Error ? err.message : 'Failed to load research jobs.');
} finally {
setIsLoadingHistory(false);
}
@@ -37,6 +82,42 @@ export function SearchSetup({ user, onSelectJob }: SearchSetupProps) {
void refreshJobs();
}, [refreshJobs]);
const filteredJobs = useMemo(() => {
const normalizedSearch = searchTerm.trim().toLowerCase();
const nextJobs = jobs.filter((job) => {
const matchesStatus = statusFilter === 'all' || job.status === statusFilter;
if (!matchesStatus) {
return false;
}
if (!normalizedSearch) {
return true;
}
const haystack = [job.name, job.businessType, job.city, job.address, job.keywords]
.filter(Boolean)
.join(' ')
.toLowerCase();
return haystack.includes(normalizedSearch);
});
nextJobs.sort((left, right) => {
if (sortOrder === 'results') {
return right.totalResults - left.totalResults;
}
const leftTime = new Date(left.createdAt).getTime();
const rightTime = new Date(right.createdAt).getTime();
return sortOrder === 'oldest' ? leftTime - rightTime : rightTime - leftTime;
});
return nextJobs;
}, [jobs, searchTerm, sortOrder, statusFilter]);
const handleRunSearch = async (e: React.FormEvent) => {
e.preventDefault();
setIsSearching(true);
@@ -52,165 +133,355 @@ export function SearchSetup({ user, onSelectJob }: SearchSetupProps) {
});
await refreshJobs();
onSelectJob(response.job.id);
onSelectCreatedJob(response.job.id);
} catch (err) {
setError(err instanceof Error ? err.message : 'Search failed.');
setError(err instanceof Error ? err.message : 'Research failed.');
} finally {
setIsSearching(false);
}
};
return (
<div className="flex-1 overflow-y-auto p-8">
<div className="mx-auto max-w-4xl space-y-8">
<header>
<h1 className="text-3xl font-bold text-stone-900">Search Setup</h1>
<p className="mt-2 text-stone-600">Submit a search job to Supabase and review the results in the dashboard or map view.</p>
<div className="flex-1 overflow-y-auto bg-stone-50 p-6 sm:p-8">
<div className="mx-auto max-w-7xl space-y-8">
<header className="space-y-2">
<h1 className="text-3xl font-bold text-stone-900">Research</h1>
<p className="max-w-3xl text-stone-600">
Run new research from the form below, then browse every job in a single grid with filters and quick access to map results.
</p>
</header>
<div className="grid grid-cols-1 gap-8 md:grid-cols-3">
<div className="md:col-span-2">
<form onSubmit={handleRunSearch} className="space-y-6 rounded-2xl border border-stone-200 bg-white p-8 shadow-sm">
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Location</label>
<div className="relative">
<MapPin className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-stone-400" />
<input
type="text"
required
placeholder="City, address, or zip"
value={location}
onChange={(e) => setLocation(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 py-2 pl-10 pr-4 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
</div>
<section className="rounded-3xl border border-stone-200 bg-white p-6 shadow-sm sm:p-8">
<div className="mb-6 flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Research Form</p>
<h2 className="mt-2 text-2xl font-bold text-stone-900">Start a new research run</h2>
<p className="mt-2 max-w-2xl text-sm text-stone-600">
Each run is processed through the local research API, then saved so you can review it later from the dashboard or map view.
</p>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Radius (km)</label>
<input
type="number"
min="1"
max="50"
value={radius}
onChange={(e) => setRadius(Number.parseInt(e.target.value, 10) || 1)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-2 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Business Type</label>
<form onSubmit={handleRunSearch} className="space-y-6">
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-4">
<div className="space-y-2 xl:col-span-2">
<label className="text-sm font-semibold text-stone-700">Location</label>
<div className="relative">
<MapPin className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-stone-400" />
<input
type="text"
required
placeholder="e.g. coffee shop, plumber"
value={businessType}
onChange={(e) => setBusinessType(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-2 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Keywords</label>
<input
type="text"
placeholder="e.g. organic, emergency, family-owned"
value={keywords}
onChange={(e) => setKeywords(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-2 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
placeholder="City, address, or zip"
value={location}
onChange={(e) => setLocation(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 py-3 pl-10 pr-4 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Job Name</label>
<label className="text-sm font-semibold text-stone-700">Radius (km)</label>
<input
type="text"
placeholder="Give this search a memorable name"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-2 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
type="number"
min="1"
max="50"
value={radius}
onChange={(e) => setRadius(Number.parseInt(e.target.value, 10) || 1)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
<div className="rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm text-stone-600">
Searches now run through a Supabase Edge Function, so the browser no longer writes leads directly into the database.
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Business Type</label>
<input
type="text"
required
placeholder="e.g. coffee shop, plumber"
value={businessType}
onChange={(e) => setBusinessType(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
{error && (
<div className="flex items-center gap-3 rounded-xl border border-red-100 bg-red-50 p-4 text-sm text-red-700">
<AlertCircle className="h-5 w-5 flex-shrink-0" />
<span>{error}</span>
</div>
)}
<div className="space-y-2 xl:col-span-2">
<label className="text-sm font-semibold text-stone-700">Keywords</label>
<input
type="text"
placeholder="e.g. organic, emergency, family-owned"
value={keywords}
onChange={(e) => setKeywords(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
<button
type="submit"
disabled={isSearching}
className="flex w-full items-center justify-center gap-2 rounded-xl bg-emerald-600 py-3 font-semibold text-white shadow-sm transition-all hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{isSearching ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Running Search...
</>
) : (
<>
<Play className="h-5 w-5" />
Run Search
</>
)}
</button>
</form>
</div>
<div className="space-y-4">
<div className="flex items-center gap-2 font-bold text-stone-900">
<History className="h-5 w-5" />
<h2>Recent Searches</h2>
<div className="space-y-2 xl:col-span-2">
<label className="text-sm font-semibold text-stone-700">Research Name</label>
<input
type="text"
placeholder="Give this research a memorable name"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
</div>
{isLoadingHistory ? (
<div className="flex items-center gap-2 rounded-xl border border-stone-200 bg-white p-4 text-sm text-stone-500 shadow-sm">
<Loader2 className="h-4 w-4 animate-spin" />
Loading history...
<div className="rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm text-stone-600">
Research runs now go through the local API, so the browser no longer writes leads directly into the database.
</div>
{error && (
<div className="flex items-center gap-3 rounded-xl border border-red-100 bg-red-50 p-4 text-sm text-red-700">
<AlertCircle className="h-5 w-5 flex-shrink-0" />
<span>{error}</span>
</div>
) : jobs.length === 0 ? (
<p className="text-sm italic text-stone-500">No search history yet.</p>
) : (
<div className="space-y-3">
{jobs.map((job) => (
)}
<button
type="submit"
disabled={isSearching}
className="flex w-full items-center justify-center gap-2 rounded-xl bg-emerald-600 py-3 font-semibold text-white shadow-sm transition-all hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto sm:px-8"
>
{isSearching ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Running Research...
</>
) : (
<>
<Play className="h-5 w-5" />
Run Research
</>
)}
</button>
</form>
</section>
<section className="space-y-5">
<div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Research Jobs</p>
<h2 className="mt-2 text-2xl font-bold text-stone-900">All research runs</h2>
<p className="mt-2 text-sm text-stone-600">
Filter the grid to find specific runs, select the ones you want, then send the full selection to the map.
</p>
</div>
<div className="rounded-full border border-stone-200 bg-white px-4 py-2 text-sm font-medium text-stone-600 shadow-sm">
{filteredJobs.length} shown of {jobs.length}
</div>
</div>
<div className="space-y-4 rounded-2xl border border-stone-200 bg-white p-4 shadow-sm">
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_220px_220px]">
<label className="space-y-2">
<span className="flex items-center gap-2 text-sm font-semibold text-stone-700">
<SearchIcon className="h-4 w-4 text-stone-400" />
Search
</span>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search by name, type, or location"
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</label>
<label className="space-y-2">
<span className="flex items-center gap-2 text-sm font-semibold text-stone-700">
<SlidersHorizontal className="h-4 w-4 text-stone-400" />
Status
</span>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value as JobStatusFilter)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
>
{statusOptions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<label className="space-y-2">
<span className="text-sm font-semibold text-stone-700">Sort</span>
<select
value={sortOrder}
onChange={(e) => setSortOrder(e.target.value as SortOption)}
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
>
{sortOptions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
</div>
{selectedJobCount > 0 && (
<div className="flex flex-col gap-3 border-t border-stone-100 pt-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="text-sm font-semibold text-emerald-900">
{selectedJobCount === 1 ? '1 research job selected' : `${selectedJobCount} research jobs selected`}
</p>
<p className="text-sm text-stone-600">Use the selection action to open all selected jobs together on the map.</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row">
<button
key={job.id}
onClick={() => onSelectJob(job.id)}
className="group w-full space-y-2 rounded-xl border border-stone-200 bg-white p-4 text-left shadow-sm transition-all hover:border-emerald-500 hover:shadow-md"
type="button"
onClick={onShowSelectedOnMap}
className="rounded-xl bg-emerald-600 px-4 py-3 text-sm font-semibold text-white shadow-sm transition-all hover:bg-emerald-700"
>
<div className="flex items-start justify-between gap-2">
<h3 className="truncate text-sm font-bold text-stone-900 group-hover:text-emerald-700">{job.name}</h3>
{job.status === 'completed' ? (
<CheckCircle2 className="h-4 w-4 flex-shrink-0 text-emerald-500" />
) : job.status === 'running' ? (
<Loader2 className="h-4 w-4 flex-shrink-0 animate-spin text-emerald-500" />
) : (
<AlertCircle className="h-4 w-4 flex-shrink-0 text-red-500" />
)}
</div>
<div className="flex items-center gap-2 text-xs text-stone-500">
<MapPin className="h-3 w-3" />
<span className="truncate">{job.city} ({job.radiusKm}km)</span>
</div>
<div className="flex items-center justify-between border-t border-stone-50 pt-2">
<span className="text-xs font-medium text-stone-400">{new Date(job.createdAt).toLocaleDateString()}</span>
<span className="text-xs font-bold text-emerald-600">{job.totalResults} leads</span>
</div>
Show selected on map ({selectedJobCount})
</button>
))}
<button
type="button"
onClick={onClearSelection}
className="rounded-xl border border-stone-200 bg-white px-4 py-3 text-sm font-semibold text-stone-700 transition-all hover:bg-stone-50"
>
Clear selection
</button>
</div>
</div>
)}
</div>
</div>
{isLoadingHistory ? (
<div className="flex items-center gap-3 rounded-2xl border border-stone-200 bg-white p-5 text-sm text-stone-500 shadow-sm">
<Loader2 className="h-4 w-4 animate-spin" />
Loading research jobs...
</div>
) : filteredJobs.length === 0 ? (
<div className="rounded-2xl border border-dashed border-stone-300 bg-white p-10 text-center shadow-sm">
<p className="text-lg font-semibold text-stone-900">No research jobs match the current filters.</p>
<p className="mt-2 text-sm text-stone-500">Try adjusting the search term, status filter, or sort order.</p>
</div>
) : (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
{filteredJobs.map((job) => {
const statusMeta = getStatusMeta(job.status);
const isSelected = selectedJobIds.includes(job.id);
return (
<button
type="button"
key={job.id}
aria-pressed={isSelected}
onClick={() => onToggleJobSelection(job.id)}
className={`group flex h-full flex-col rounded-2xl border p-5 text-left shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md ${
isSelected
? 'border-emerald-400 bg-emerald-50/70 shadow-emerald-100'
: 'border-stone-200 bg-white hover:border-emerald-400'
}`}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate text-lg font-bold text-stone-900 group-hover:text-emerald-700">{job.name}</p>
<p className="mt-1 truncate text-sm text-stone-500">{job.businessType}</p>
</div>
<div className="flex flex-col items-end gap-2">
<span className={statusMeta.badgeClass}>
<statusMeta.icon className={statusMeta.icon === Loader2 ? 'h-3.5 w-3.5 animate-spin' : 'h-3.5 w-3.5'} />
{statusMeta.label}
</span>
<span
className={`inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-semibold ${
isSelected ? 'bg-emerald-600 text-white' : 'bg-stone-100 text-stone-500'
}`}
>
{isSelected ? <Check className="h-3.5 w-3.5" /> : <span className="h-2 w-2 rounded-full bg-current opacity-60"></span>}
{isSelected ? 'Selected' : 'Click to select'}
</span>
</div>
</div>
<div className="mt-5 space-y-3 text-sm text-stone-600">
<div className="flex items-start gap-2">
<MapPin className="mt-0.5 h-4 w-4 flex-shrink-0 text-stone-400" />
<span className="line-clamp-2">{formatLocation(job)}</span>
</div>
<div className="flex items-center gap-2">
<CalendarDays className="h-4 w-4 flex-shrink-0 text-stone-400" />
<span>{new Date(job.createdAt).toLocaleDateString()}</span>
</div>
{job.keywords ? <p className="line-clamp-2 text-stone-500">Keywords: {job.keywords}</p> : null}
</div>
<div className="mt-5 grid grid-cols-2 gap-3 rounded-2xl bg-stone-50 p-4">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Radius</p>
<p className="mt-1 text-base font-bold text-stone-900">{job.radiusKm} km</p>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Results</p>
<p className="mt-1 text-base font-bold text-stone-900">{job.totalResults}</p>
</div>
</div>
<div className="mt-4 flex items-center justify-between border-t border-stone-100 pt-4 text-sm font-medium text-stone-500">
<span>{job.totalResults === 1 ? '1 lead found' : `${job.totalResults} leads found`}</span>
<span className={isSelected ? 'text-emerald-700' : 'text-stone-400'}>
{isSelected ? 'Included in selection' : 'Available to select'}
</span>
</div>
</button>
);
})}
</div>
)}
</section>
</div>
</div>
);
}
function formatLocation(job: SearchJob) {
const primaryLocation = job.address || job.city || 'Location not available';
return `${primaryLocation} (${job.radiusKm} km radius)`;
}
function getStatusMeta(status: SearchJobStatus) {
switch (status) {
case 'completed':
return {
label: 'Completed',
icon: CheckCircle2,
badgeClass:
'inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700',
};
case 'running':
return {
label: 'Running',
icon: Loader2,
badgeClass:
'inline-flex items-center gap-1 rounded-full border border-sky-200 bg-sky-50 px-3 py-1 text-xs font-semibold text-sky-700',
};
case 'failed':
return {
label: 'Failed',
icon: AlertCircle,
badgeClass:
'inline-flex items-center gap-1 rounded-full border border-red-200 bg-red-50 px-3 py-1 text-xs font-semibold text-red-700',
};
case 'stopped':
return {
label: 'Stopped',
icon: CircleOff,
badgeClass:
'inline-flex items-center gap-1 rounded-full border border-stone-200 bg-stone-100 px-3 py-1 text-xs font-semibold text-stone-700',
};
case 'pending':
default:
return {
label: 'Pending',
icon: Clock3,
badgeClass:
'inline-flex items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-xs font-semibold text-amber-700',
};
}
}
+28
View File
@@ -0,0 +1,28 @@
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? '';
export const hasApiConfig = Boolean(apiBaseUrl);
export async function apiRequest<T>(path: string, init?: RequestInit): Promise<T> {
if (!apiBaseUrl) {
throw new Error('VITE_API_BASE_URL is not configured.');
}
const response = await fetch(`${apiBaseUrl}${path}`, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...(init?.headers ?? {}),
},
...init,
});
const contentType = response.headers.get('content-type') || '';
const payload = contentType.includes('application/json') ? ((await response.json()) as unknown) : null;
if (!response.ok) {
const message = payload && typeof payload === 'object' && 'error' in payload ? String(payload.error) : 'Request failed.';
throw new Error(message);
}
return payload as T;
}
+39
View File
@@ -0,0 +1,39 @@
import type { AppUser, SessionUser } from '../../shared/types';
import { apiRequest } from './api';
export function getUserDisplayName(user: AppUser | SessionUser | null): string {
return user?.displayName || user?.email || 'User';
}
export function getUserAvatarUrl(user: AppUser | SessionUser | null): string | null {
return user?.avatarUrl || null;
}
export async function getLocalSessionUser() {
const response = await apiRequest<{ user: SessionUser | null }>('/auth/me');
return response.user;
}
export async function signUpWithLocalAuth(payload: { email: string; password: string; displayName?: string }) {
const response = await apiRequest<{ user: SessionUser }>('/auth/signup', {
method: 'POST',
body: JSON.stringify(payload),
});
return response.user;
}
export async function signInWithLocalAuth(payload: { email: string; password: string }) {
const response = await apiRequest<{ user: SessionUser }>('/auth/login', {
method: 'POST',
body: JSON.stringify(payload),
});
return response.user;
}
export async function signOutWithLocalAuth() {
await apiRequest<{ success: boolean }>('/auth/logout', {
method: 'POST',
});
}
+29 -165
View File
@@ -1,51 +1,6 @@
import { supabase } from './supabase';
import { apiRequest } from './api';
import type { Business, SearchJob } from '../types';
type SearchJobRow = {
id: string;
user_id: string;
name: string;
city: string | null;
address: string | null;
postal_code: string | null;
radius_km: number;
business_type: string;
keywords: string | null;
status: SearchJob['status'];
total_results: number;
started_at: string | null;
completed_at: string | null;
created_at: string;
updated_at: string;
};
type BusinessRow = {
id: string;
user_id: string;
external_source_id: string | null;
source: string;
name: string;
address: string | null;
city: string | null;
state_province: string | null;
postal_code: string | null;
country: string | null;
phone: string | null;
website: string | null;
rating: number | null;
review_count: number | null;
category: string | null;
hours_json: Record<string, unknown> | null;
latitude: number | null;
longitude: number | null;
general_info: string | null;
metadata_json: Record<string, unknown> | null;
first_seen_at: string | null;
last_seen_at: string | null;
created_at: string;
updated_at: string;
};
export type SearchJobResultLink = {
businessId: string;
searchJobId: string;
@@ -64,133 +19,42 @@ export type RunSearchResponse = {
totalResults: number;
};
function mapSearchJob(row: SearchJobRow): SearchJob {
return {
id: row.id,
userId: row.user_id,
name: row.name,
city: row.city ?? undefined,
address: row.address ?? undefined,
postalCode: row.postal_code ?? undefined,
radiusKm: row.radius_km,
businessType: row.business_type,
keywords: row.keywords ?? undefined,
status: row.status,
totalResults: row.total_results,
startedAt: row.started_at ?? undefined,
completedAt: row.completed_at ?? undefined,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
export async function listSearchJobs(userIdOrMax?: string | number, max = 10): Promise<SearchJob[]> {
const limit = typeof userIdOrMax === 'number' ? userIdOrMax : max;
const response = await apiRequest<{ jobs: SearchJob[] }>(`/search-jobs?limit=${limit}`);
return response.jobs;
}
function mapBusiness(row: BusinessRow): Business {
return {
id: row.id,
userId: row.user_id,
externalSourceId: row.external_source_id ?? undefined,
source: row.source,
name: row.name,
address: row.address ?? undefined,
city: row.city ?? undefined,
stateProvince: row.state_province ?? undefined,
postalCode: row.postal_code ?? undefined,
country: row.country ?? undefined,
phone: row.phone ?? undefined,
website: row.website ?? undefined,
rating: row.rating ?? undefined,
reviewCount: row.review_count ?? undefined,
category: row.category ?? undefined,
hoursJson: row.hours_json ? JSON.stringify(row.hours_json) : undefined,
latitude: row.latitude ?? undefined,
longitude: row.longitude ?? undefined,
generalInfo: row.general_info ?? undefined,
metadataJson: row.metadata_json ? JSON.stringify(row.metadata_json) : undefined,
firstSeenAt: row.first_seen_at ?? undefined,
lastSeenAt: row.last_seen_at ?? undefined,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
export async function listBusinesses(_userId?: string): Promise<Business[]> {
const response = await apiRequest<{ businesses: Business[] }>('/businesses');
return response.businesses;
}
function ensureData<T>(data: T | null, error: { message: string } | null, context: string): T {
if (error) {
throw new Error(`${context}: ${error.message}`);
export async function listJobResultLinks(_userId?: string): Promise<SearchJobResultLink[]> {
const response = await apiRequest<{ links: SearchJobResultLink[] }>('/search-job-results/links');
return response.links;
}
export async function listBusinessesForJob(userIdOrJobId: string, maybeJobId?: string): Promise<Business[]> {
const jobId = maybeJobId ?? userIdOrJobId;
const response = await apiRequest<{ businesses: Business[] }>(`/search-jobs/${jobId}/businesses`);
return response.businesses;
}
export async function listBusinessesForJobs(userIdOrJobIds: string | string[], maybeJobIds?: string[]): Promise<Business[]> {
const jobIds = Array.isArray(userIdOrJobIds) ? userIdOrJobIds : maybeJobIds ?? [];
if (jobIds.length === 0) {
return [];
}
if (data === null) {
throw new Error(`${context}: no data returned`);
}
return data;
}
export async function listSearchJobs(userId: string, max = 10): Promise<SearchJob[]> {
const { data, error } = await supabase
.from('search_jobs')
.select('*')
.eq('user_id', userId)
.order('created_at', { ascending: false })
.limit(max);
const rows = ensureData(data as SearchJobRow[] | null, error, 'Failed to load search jobs');
return rows.map(mapSearchJob);
}
export async function listBusinesses(userId: string): Promise<Business[]> {
const { data, error } = await supabase
.from('businesses')
.select('*')
.eq('user_id', userId)
.order('created_at', { ascending: false });
const rows = ensureData(data as BusinessRow[] | null, error, 'Failed to load businesses');
return rows.map(mapBusiness);
}
export async function listJobResultLinks(userId: string): Promise<SearchJobResultLink[]> {
const { data, error } = await supabase
.from('search_job_results')
.select('business_id, search_job_id')
.eq('user_id', userId);
const rows = ensureData(data as Array<{ business_id: string; search_job_id: string }> | null, error, 'Failed to load job links');
return rows.map((row) => ({ businessId: row.business_id, searchJobId: row.search_job_id }));
}
export async function listBusinessesForJob(userId: string, jobId: string): Promise<Business[]> {
const { data, error } = await supabase
.from('search_job_results')
.select('business:businesses(*)')
.eq('user_id', userId)
.eq('search_job_id', jobId);
const rows = ensureData(
data as Array<{ business: BusinessRow[] | null }> | null,
error,
'Failed to load businesses for job',
);
return rows.flatMap((row) => {
const business = row.business?.[0];
if (!business) {
return [];
}
return [mapBusiness(business)];
});
const response = await apiRequest<{ businesses: Business[] }>(`/businesses?jobIds=${encodeURIComponent(jobIds.join(','))}`);
return response.businesses;
}
export async function runSearch(payload: RunSearchPayload): Promise<RunSearchResponse> {
const { data, error } = await supabase.functions.invoke('run-search', {
body: payload,
return apiRequest<RunSearchResponse>('/search-jobs', {
method: 'POST',
body: JSON.stringify(payload),
});
const response = ensureData(data as { job: SearchJobRow; totalResults: number } | null, error, 'Search failed');
return {
job: mapSearchJob(response.job),
totalResults: response.totalResults,
};
}
-34
View File
@@ -1,34 +0,0 @@
import { createClient, type User } from '@supabase/supabase-js';
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL ?? '';
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY ?? '';
export const hasSupabaseConfig = Boolean(supabaseUrl && supabaseAnonKey);
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
persistSession: true,
autoRefreshToken: true,
detectSessionInUrl: true,
},
});
export function getUserDisplayName(user: User | null): string {
if (!user) {
return 'User';
}
const fullName = typeof user.user_metadata?.full_name === 'string' ? user.user_metadata.full_name : null;
const name = typeof user.user_metadata?.name === 'string' ? user.user_metadata.name : null;
const emailName = user.email ? user.email.split('@')[0] : null;
return fullName || name || emailName || user.email || 'User';
}
export function getUserAvatarUrl(user: User | null): string | null {
if (!user) {
return null;
}
return typeof user.user_metadata?.avatar_url === 'string' ? user.user_metadata.avatar_url : null;
}
+1 -2
View File
@@ -1,8 +1,7 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_SUPABASE_URL: string;
readonly VITE_SUPABASE_ANON_KEY: string;
readonly VITE_API_BASE_URL: string;
readonly VITE_GOOGLE_MAPS_PLATFORM_KEY: string;
}