Public Access
1
0

feat: split research workflows and results into dedicated workspaces

This commit is contained in:
pguerrerox
2026-04-19 22:31:33 +00:00
parent dc7686f507
commit d1363d6677
23 changed files with 1646 additions and 713 deletions
+138 -402
View File
@@ -1,139 +1,59 @@
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, SearchJobStatus } from '../types';
import React, { useCallback, useState } from 'react';
import { AlertCircle, LocateFixed, Loader2, MapPin, Play } from 'lucide-react';
import { runSearch } from '../lib/database';
import type { AppUser } from '../../shared/types';
import { BasicResearchMap } from './BasicResearchMap';
interface SearchSetupProps {
user: AppUser;
selectedJobIds: string[];
onToggleJobSelection: (jobId: string) => void;
onSelectCreatedJob: (jobId: string) => void;
onShowSelectedOnMap: () => void;
onClearSelection: () => void;
topContent?: React.ReactNode;
}
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,
user: _user,
onSelectCreatedJob,
onShowSelectedOnMap,
onClearSelection,
topContent,
}: 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 [pin, setPin] = useState<google.maps.LatLngLiteral | null>(null);
const [locationError, setLocationError] = useState<string | null>(null);
const [locationAction, setLocationAction] = useState<'geolocate' | null>(null);
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, 100);
setJobs(nextJobs);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load research jobs.');
} finally {
setIsLoadingHistory(false);
}
}, [user.id]);
useEffect(() => {
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 applyPin = useCallback(async (nextPin: google.maps.LatLngLiteral) => {
setPin(nextPin);
setLocationError(null);
}, []);
const handleRunSearch = async (e: React.FormEvent) => {
e.preventDefault();
setIsSearching(true);
setError(null);
setLocationError(null);
try {
const response = await runSearch({
if (!pin) {
setLocationError('Drop a pin on the map or use your current location before running research.');
setIsSearching(false);
return;
}
try {
const response = await runSearch({
name: name.trim() || undefined,
location: location.trim(),
location: `${pin.lat.toFixed(5)}, ${pin.lng.toFixed(5)}`,
radiusKm: radius,
businessType: businessType.trim(),
keywords: keywords.trim() || undefined,
});
lat: pin.lat,
lng: pin.lng,
});
await refreshJobs();
onSelectCreatedJob(response.job.id);
onSelectCreatedJob(response.job.id);
} catch (err) {
setError(err instanceof Error ? err.message : 'Research failed.');
} finally {
@@ -141,53 +61,56 @@ export function SearchSetup({
}
};
const handleUseMyLocation = () => {
setLocationAction('geolocate');
setLocationError(null);
navigator.geolocation.getCurrentPosition(
async (position) => {
try {
await applyPin({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
} catch (err) {
setLocationError(err instanceof Error ? err.message : 'Failed to use your current location.');
} finally {
setLocationAction(null);
}
},
(geoError) => {
setLocationError(geoError.message || 'Location access was denied.');
setLocationAction(null);
},
{ enableHighAccuracy: true, timeout: 10000 },
);
};
const hasLocationPin = Boolean(pin);
return (
<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">
{topContent}
<header className="space-y-2">
<h1 className="text-3xl font-bold text-stone-900">Research</h1>
<h1 className="text-3xl font-bold text-stone-900">Basic 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.
Drop a pin on the map, define the search area, and run standard research before reviewing saved jobs below.
</p>
</header>
<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>
<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="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>
<section className="grid grid-cols-1 items-stretch gap-6 xl:grid-cols-[400px_minmax(0,1fr)]">
<div className="rounded-3xl border border-stone-200 bg-white p-5 shadow-sm sm:p-7">
<form onSubmit={handleRunSearch} className="space-y-5">
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Radius (km)</label>
<label className="text-sm font-semibold text-stone-700">Research Name</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-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
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-2.5 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
@@ -199,289 +122,102 @@ export function SearchSetup({
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"
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-2.5 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
<div className="space-y-2 xl:col-span-2">
<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-3 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-2.5 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
<div className="space-y-2 xl:col-span-2">
<label className="text-sm font-semibold text-stone-700">Research Name</label>
<div className="space-y-2.5">
<label className="text-sm font-semibold text-stone-700">Location Source</label>
<button
type="button"
onClick={handleUseMyLocation}
disabled={locationAction !== null}
className="inline-flex items-center gap-2 rounded-xl border border-stone-200 bg-white px-4 py-2.5 text-sm font-semibold text-stone-700 transition hover:bg-stone-50 disabled:cursor-not-allowed disabled:opacity-50"
>
<LocateFixed className="h-4 w-4" />
{locationAction === 'geolocate' ? 'Locating...' : 'Use my location'}
</button>
{locationError && (
<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>{locationError}</span>
</div>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-stone-700">Area (km radius)</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"
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.5 outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
/>
</div>
</div>
<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 className="rounded-xl border border-stone-200 bg-stone-50 px-4 py-2.5 text-sm text-stone-600">
Drop a pin directly on the map or use your current location. The map circle always reflects the current area value.
</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 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
</>
{hasLocationPin && (
<div className="rounded-2xl border border-emerald-200 bg-emerald-50/70 p-3.5 text-sm text-emerald-900">
<p className="font-semibold">Active search center</p>
<p className="mt-1">{pin!.lat.toFixed(5)}, {pin!.lng.toFixed(5)}</p>
</div>
)}
</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>
{error && (
<div className="flex items-center gap-3 rounded-xl border border-red-100 bg-red-50 p-3.5 text-sm text-red-700">
<AlertCircle className="h-5 w-5 flex-shrink-0" />
<span>{error}</span>
</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 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>
</div>
<div className="flex h-full flex-col gap-4">
<BasicResearchMap pin={pin} radiusKm={radius} onPinChange={(nextPin) => void applyPin(nextPin)} />
<div className="rounded-3xl border border-stone-200 bg-white p-5 shadow-sm">
<h3 className="text-lg font-bold text-stone-900">Map controls</h3>
<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.
Drop a pin directly on the map or use your current location. The circle updates from the Area field and the search runs from the active pin.
</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
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"
>
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>
{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',
};
}
}