Public Access
1
0

chore: reorganize frontend into app and admin roots

This commit is contained in:
pguerrerox
2026-05-30 00:45:06 +00:00
parent d71f2f1f8a
commit a926d06b54
39 changed files with 76 additions and 49 deletions
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Leads4less</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+937
View File
@@ -0,0 +1,937 @@
import { type ReactElement, type SVGProps, useEffect, useState } from 'react';
import { APIProvider } from '@vis.gl/react-google-maps';
import {
AlertCircle,
ArrowRight,
Briefcase,
Building2,
Check,
LogIn,
Map,
MapPinned,
Search,
ShieldAlert,
Sparkles,
User,
UserPlus,
} from 'lucide-react';
import { Layout, type AppTab } from './components/Layout';
import { AccountPage } from './components/AccountPage';
import { Dashboard } from './components/Dashboard';
import { MapView } from './components/MapView';
import { PricingCards } from './components/PricingCards';
import { PricingComparisonTable } from './components/PricingComparisonTable';
import { ResearchWorkspace } from './components/ResearchWorkspace';
import { ResultsWorkspace } from './components/ResultsWorkspace';
import { Alert, Badge, Button, Card, FieldLabel, Input, Surface } from './components/ui';
import type { BillingInterval, PlanCode } from '@/shared/billing/plans';
import type { AdminBootstrapStatusResponse, SessionUser } from '@/shared/types';
import {
claimAdminBootstrap,
getAdminBootstrapStatus,
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 [publicPage, setPublicPage] = useState<'landing' | 'auth'>(() => getPublicPageFromLocation());
const [user, setUser] = useState<SessionUser | null>(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<AppTab>('setup');
const [selectedJobIds, setSelectedJobIds] = useState<string[]>([]);
const [authError, setAuthError] = useState<string | null>(null);
const [authNotice, setAuthNotice] = useState<string | null>(null);
const [isAuthenticating, setIsAuthenticating] = useState(false);
const [authMode, setAuthMode] = useState<'sign_in' | 'sign_up'>('sign_in');
const [billingIntentPlanCode, setBillingIntentPlanCode] = useState<PlanCode | null>(null);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [displayName, setDisplayName] = useState('');
const [bootstrapToken, setBootstrapToken] = useState('');
const [bootstrapStatus, setBootstrapStatus] = useState<AdminBootstrapStatusResponse | null>(null);
const [bootstrapLoading, setBootstrapLoading] = useState(false);
useEffect(() => {
const handlePopState = () => {
setPublicPage(getPublicPageFromLocation());
};
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('popstate', handlePopState);
};
}, []);
useEffect(() => {
if (user || publicPage !== 'auth') {
return;
}
let isMounted = true;
const loadBootstrapStatus = async () => {
setBootstrapLoading(true);
try {
const status = await getAdminBootstrapStatus();
if (!isMounted) {
return;
}
setBootstrapStatus(status);
} catch (error) {
if (!isMounted) {
return;
}
setAuthError(error instanceof Error ? error.message : 'Failed to load bootstrap status.');
} finally {
if (isMounted) {
setBootstrapLoading(false);
}
}
};
void loadBootstrapStatus();
return () => {
isMounted = false;
};
}, [publicPage, user]);
const isBootstrapRequired = bootstrapStatus?.bootstrapRequired === true;
useEffect(() => {
let isMounted = true;
const loadSession = async () => {
try {
const sessionUser = await getLocalSessionUser();
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);
}
}
};
void loadSession();
return () => {
isMounted = false;
};
}, []);
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 handleShowJobIdsOnMap = (jobIds: string[]) => {
setSelectedJobIds(jobIds);
setActiveTab('map');
};
const handleLogin = async () => {
if (isBootstrapRequired && bootstrapLoading) {
return;
}
setAuthError(null);
setAuthNotice(null);
setIsAuthenticating(true);
try {
if (isBootstrapRequired) {
const nextUser = await claimAdminBootstrap({
email,
password,
displayName: displayName.trim() || undefined,
bootstrapToken,
});
setUser(nextUser);
setAuthNotice('First site admin created and signed in.');
navigatePublicPage('landing', setPublicPage);
return;
}
if (authMode === 'sign_up') {
const nextUser = await signUpWithLocalAuth({
email,
password,
displayName: displayName.trim() || undefined,
});
setUser(nextUser);
setAuthNotice('Account created and signed in.');
if (billingIntentPlanCode) {
setActiveTab('account');
}
return;
}
const nextUser = await signInWithLocalAuth({
email,
password,
});
setUser(nextUser);
if (billingIntentPlanCode) {
setActiveTab('account');
}
navigatePublicPage('landing', setPublicPage);
} catch (error) {
setAuthError(error instanceof Error ? error.message : 'Authentication failed.');
} finally {
setIsAuthenticating(false);
}
};
const handleLogout = async () => {
const sessionId = user?.sessionId;
setAuthError(null);
setAuthNotice(null);
setSelectedJobIds([]);
setUser(null);
setActiveTab('setup');
setBootstrapStatus(null);
setBootstrapToken('');
try {
await signOutWithLocalAuth(sessionId);
} catch (error) {
setAuthError(error instanceof Error ? error.message : 'Failed to sign out.');
}
};
if (loading) {
return (
<div className="flex h-screen items-center justify-center bg-stone-50">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-stone-900 border-t-transparent"></div>
</div>
);
}
if (!hasApiConfig) {
return (
<ConfigScreen
icon={<ShieldAlert className="h-8 w-8" />}
title="Local API Config Required"
description="Add your local API base URL before running the app."
steps={[
'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 now uses a local API, PostgreSQL, and local session auth."
/>
);
}
if (!user) {
const handleSetAuthMode = (mode: 'sign_in' | 'sign_up') => {
setAuthMode(mode);
setAuthError(null);
setAuthNotice(null);
};
if (publicPage === 'auth') {
return (
<AuthPage
authMode={isBootstrapRequired ? 'sign_up' : authMode}
authError={authError}
authNotice={authNotice}
bootstrapLoading={bootstrapLoading}
bootstrapRequired={isBootstrapRequired}
bootstrapToken={bootstrapToken}
displayName={displayName}
email={email}
isAuthenticating={isAuthenticating}
bootstrapEnabled={bootstrapStatus?.bootstrapEnabled ?? false}
password={password}
onBootstrapTokenChange={setBootstrapToken}
onDisplayNameChange={setDisplayName}
onEmailChange={setEmail}
onPasswordChange={setPassword}
onGoHome={() => navigatePublicPage('landing', setPublicPage)}
onSetAuthMode={handleSetAuthMode}
onSubmit={() => void handleLogin()}
/>
);
}
return (
<LandingPage
onGoToAuth={(mode, planCode) => {
handleSetAuthMode(mode);
setBillingIntentPlanCode(planCode ?? null);
navigatePublicPage('auth', setPublicPage);
}}
/>
);
}
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 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 for the local API server.',
'Enable Geocoding API and Places API in Google Cloud.',
]}
footer="You can create a local account without the maps key, but the workspace needs it before loading."
/>
);
}
return (
<APIProvider apiKey={GOOGLE_MAPS_API_KEY} version="weekly">
<Layout
user={user}
activeTab={activeTab}
setActiveTab={setActiveTab}
onLogout={() => void handleLogout()}
>
{activeTab === 'setup' && (
<ResearchWorkspace
user={user}
selectedJobIds={selectedJobIds}
onToggleJobSelection={handleToggleJobSelection}
onSelectCreatedJob={handleSelectCreatedJob}
onShowSelectedOnMap={handleShowSelectedOnMap}
onClearSelection={handleClearSelectedJobs}
onShowBatchOnMap={handleShowJobIdsOnMap}
/>
)}
{activeTab === 'results' && (
<ResultsWorkspace
user={user}
selectedJobIds={selectedJobIds}
onToggleJobSelection={handleToggleJobSelection}
onShowSelectedOnMap={handleShowSelectedOnMap}
onClearSelection={handleClearSelectedJobs}
onShowBatchOnMap={handleShowJobIdsOnMap}
/>
)}
{activeTab === 'dashboard' && <Dashboard user={user} />}
{activeTab === 'map' && <MapView user={user} jobIds={selectedJobIds} />}
{activeTab === 'account' && (
<AccountPage
user={user}
onUserUpdated={(nextUser) => setUser((currentUser) => (currentUser ? { ...nextUser, sessionId: currentUser.sessionId } : currentUser))}
initialCheckoutPlanCode={billingIntentPlanCode}
onConsumeInitialCheckoutPlanCode={() => setBillingIntentPlanCode(null)}
/>
)}
</Layout>
</APIProvider>
);
}
function getPublicPageFromLocation(): 'landing' | 'auth' {
if (typeof window === 'undefined') {
return 'landing';
}
return window.location.pathname === '/auth' ? 'auth' : 'landing';
}
function navigatePublicPage(page: 'landing' | 'auth', setPublicPage: (page: 'landing' | 'auth') => void) {
const nextPath = page === 'auth' ? '/auth' : '/';
if (typeof window !== 'undefined' && window.location.pathname !== nextPath) {
window.history.pushState({}, '', nextPath);
}
setPublicPage(page);
}
function LandingPage(props: {
onGoToAuth: (mode: 'sign_in' | 'sign_up', planCode?: PlanCode) => void;
}) {
const { onGoToAuth } = props;
const [pricingInterval, setPricingInterval] = useState<Extract<BillingInterval, 'monthly' | 'annual'>>('monthly');
const featureCards = [
{
icon: Search,
title: 'Research Runs',
description: 'Research local markets by city, radius, business type, and keywords without juggling spreadsheets or manual lookups.',
},
{
icon: MapPinned,
title: 'Deep Research',
description: 'Drop one pin and expand intelligently into nearby postal areas to uncover surrounding territory opportunities.',
},
{
icon: Map,
title: 'Territory Mapping',
description: 'Review returned businesses on a focused map built for territory analysis and operational decision-making.',
},
{
icon: Briefcase,
title: 'Operational Workspace',
description: 'Keep past runs, saved businesses, and mapped results in one place for repeatable prospecting workflows.',
},
] as const;
const audienceCards = [
{
icon: User,
title: 'Starter Teams',
description: 'For solo operators, freelancers, and small local teams that need a structured market research workflow.',
},
{
icon: Building2,
title: 'Growth Teams',
description: 'For agencies and outbound teams running recurring territory research across multiple service areas.',
},
{
icon: Sparkles,
title: 'Enterprise',
description: 'For larger organizations that need custom market intelligence capacity, rollout support, and tailored operating controls.',
},
] as const;
return (
<div className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.08),_transparent_28%),linear-gradient(180deg,#fafaf9_0%,#f5f5f4_100%)] text-stone-900">
<div className="mx-auto max-w-7xl px-4 pb-16 pt-4 sm:px-6 lg:px-8 lg:pb-24">
<header className="sticky top-4 z-10 rounded-3xl border border-stone-200/80 bg-white/90 px-5 py-4 shadow-sm backdrop-blur md:px-6">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div className="flex items-center gap-3">
<div className="rounded-2xl bg-stone-900 p-2.5 text-white shadow-sm">
<Briefcase className="h-5 w-5" />
</div>
<div>
<p className="text-lg font-bold tracking-tight">LocaleScope</p>
<p className="text-sm text-stone-500">Local market intelligence for modern outbound teams</p>
</div>
</div>
<nav className="flex flex-wrap items-center gap-3 text-sm font-medium text-stone-600">
<a href="#product" className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
Product
</a>
<a href="#workflow" className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
Workflow
</a>
<a href="#pricing" className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
Pricing
</a>
<button
type="button"
onClick={() => onGoToAuth('sign_in')}
className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900"
>
Sign In
</button>
<button type="button" onClick={() => onGoToAuth('sign_up')} className="inline-flex items-center gap-2 rounded-full bg-stone-900 px-4 py-2 text-white shadow-sm transition hover:bg-stone-800">
Sign Up
<ArrowRight className="h-4 w-4" />
</button>
</nav>
</div>
</header>
<section className="py-12 lg:py-16">
<div className="space-y-8">
<Badge variant="primary" className="px-4 py-2 text-sm">
<Sparkles className="h-4 w-4" />
Geographic prospecting intelligence platform
</Badge>
<div className="space-y-5">
<h1 className="max-w-4xl text-5xl font-bold tracking-tight text-stone-950 sm:text-6xl">
Discover underserved markets, map territories, and turn local research into repeatable intelligence.
</h1>
<p className="max-w-3xl text-lg leading-8 text-stone-600 sm:text-xl">
Run targeted local research, expand coverage from a single pin, and review every result in one focused workspace built for modern prospecting operations.
</p>
</div>
<div className="flex flex-col gap-3 sm:flex-row">
<Button type="button" onClick={() => onGoToAuth('sign_up')} size="lg" className="rounded-2xl bg-stone-900 hover:bg-stone-800">
Sign Up
<ArrowRight className="h-4 w-4" />
</Button>
<a
href="#pricing"
className="inline-flex items-center justify-center rounded-2xl border border-stone-200 bg-white px-6 py-4 text-sm font-semibold text-stone-700 shadow-sm transition hover:border-stone-300 hover:bg-stone-50"
>
See pricing
</a>
</div>
</div>
</section>
<section id="product" className="rounded-[2rem] border border-stone-200 bg-white px-6 py-10 shadow-sm sm:px-8 lg:px-10">
<div className="max-w-3xl">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Product</p>
<h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">One workspace for local market intelligence</h2>
<p className="mt-4 text-base leading-8 text-stone-600">
LocaleScope keeps market research, deep area expansion, map review, and saved business history in a single operating flow so teams can move faster without losing context.
</p>
</div>
<div className="mt-8 grid gap-4 lg:grid-cols-3">
<div className="rounded-3xl bg-stone-950 p-6 text-white lg:col-span-2">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-300">Operational Workflow</p>
<p className="mt-4 text-2xl font-bold tracking-tight">Search a market, expand intelligently, and review results visually.</p>
<p className="mt-4 max-w-2xl text-sm leading-7 text-stone-300">
Instead of stitching together Google tabs, spreadsheets, and hand-written notes, run the full territory research loop from one product surface built for repeatable analysis. Launch deeper market coverage from a single map interaction while keeping research, deep research, dashboard, and map review connected in one workspace.
</p>
</div>
<div className="rounded-3xl border border-stone-200 bg-stone-50 p-6">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Best Fit</p>
<p className="mt-4 text-2xl font-bold tracking-tight text-stone-900">Local teams who need speed and structure</p>
<p className="mt-4 text-sm leading-7 text-stone-600">Built for recurring territory research, geographic prospecting, and targeted market expansion.</p>
</div>
</div>
</section>
<section id="workflow" className="py-16">
<div className="max-w-3xl">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Workflow</p>
<h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">A clear research process from first search to mapped review</h2>
</div>
<div className="mt-8 grid gap-4 lg:grid-cols-4">
{[
['01', 'Search', 'Start with location, radius, business type, and optional keywords.'],
['02', 'Expand', 'Use deep research to fan out from a pin into nearby postal areas.'],
['03', 'Review', 'Inspect returned businesses on a clean map and in the dashboard.'],
['04', 'Act', 'Keep high-value results organized for follow-up and repeated market work.'],
].map(([step, title, description]) => (
<div key={step} className="rounded-3xl border border-stone-200 bg-white p-6 shadow-sm">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">{step}</p>
<h3 className="mt-4 text-xl font-bold tracking-tight text-stone-900">{title}</h3>
<p className="mt-3 text-sm leading-7 text-stone-600">{description}</p>
</div>
))}
</div>
</section>
<section className="rounded-[2rem] border border-stone-200 bg-white px-6 py-10 shadow-sm sm:px-8 lg:px-10">
<div className="max-w-3xl">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Who It's For</p>
<h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">Designed for growing prospecting teams and enterprise rollouts</h2>
</div>
<div className="mt-8 grid gap-4 lg:grid-cols-3">
{audienceCards.map((audience) => (
<div key={audience.title} className="rounded-3xl border border-stone-200 bg-stone-50 p-6">
<div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-white text-emerald-600 shadow-sm">
<audience.icon className="h-5 w-5" />
</div>
<h3 className="mt-5 text-xl font-bold tracking-tight text-stone-900">{audience.title}</h3>
<p className="mt-3 text-sm leading-7 text-stone-600">{audience.description}</p>
</div>
))}
</div>
</section>
<section id="pricing" className="py-16">
<div className="max-w-3xl">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Pricing</p>
<h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">Choose the plan that matches your market intelligence workflow</h2>
<p className="mt-4 text-base leading-8 text-stone-600">
Start with focused territory research, then upgrade as your operational scale, collaboration needs, and research capacity expand.
</p>
</div>
<div className="mt-8 flex justify-center">
<div className="inline-flex rounded-full border border-stone-200 bg-white p-1 shadow-sm">
{(['monthly', 'annual'] as const).map((interval) => (
<button
key={interval}
type="button"
onClick={() => setPricingInterval(interval)}
className={`rounded-full px-5 py-2 text-sm font-semibold transition ${
pricingInterval === interval ? 'bg-stone-900 text-white' : 'text-stone-600 hover:bg-stone-100 hover:text-stone-900'
}`}
>
{interval === 'monthly' ? 'Monthly' : 'Annual'}
</button>
))}
</div>
</div>
<div className="mt-8">
<PricingCards billingInterval={pricingInterval} onGoToAuth={onGoToAuth} />
</div>
<div className="mt-8">
<PricingComparisonTable billingInterval={pricingInterval} />
</div>
</section>
<section className="rounded-[2rem] bg-stone-950 px-6 py-12 text-white shadow-sm sm:px-8 lg:px-10">
<div className="flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
<div className="max-w-3xl">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-300">Start Now</p>
<h2 className="mt-3 text-3xl font-bold tracking-tight sm:text-4xl">Turn local market research into a repeatable system.</h2>
<p className="mt-4 text-base leading-8 text-stone-300">
Create an account, run your first research job, and start building a repeatable local intelligence workflow from day one.
</p>
</div>
<div className="flex flex-col gap-3 sm:flex-row">
<button
type="button"
onClick={() => onGoToAuth('sign_up')}
className="inline-flex items-center justify-center gap-2 rounded-2xl bg-emerald-500 px-6 py-4 text-sm font-semibold text-white transition hover:bg-emerald-400"
>
Choose a plan
<ArrowRight className="h-4 w-4" />
</button>
<a
href="#pricing"
className="inline-flex items-center justify-center rounded-2xl border border-white/20 px-6 py-4 text-sm font-semibold text-white transition hover:bg-white/10"
>
Compare plans
</a>
</div>
</div>
</section>
</div>
</div>
);
}
function AuthPage(props: {
authMode: 'sign_in' | 'sign_up';
authError: string | null;
authNotice: string | null;
bootstrapEnabled: boolean;
bootstrapLoading: boolean;
bootstrapRequired: boolean;
bootstrapToken: string;
displayName: string;
email: string;
isAuthenticating: boolean;
password: string;
onBootstrapTokenChange: (value: string) => void;
onDisplayNameChange: (value: string) => void;
onEmailChange: (value: string) => void;
onPasswordChange: (value: string) => void;
onGoHome: () => void;
onSetAuthMode: (mode: 'sign_in' | 'sign_up') => void;
onSubmit: () => void;
}) {
const {
authMode,
authError,
authNotice,
bootstrapEnabled,
bootstrapLoading,
bootstrapRequired,
bootstrapToken,
displayName,
email,
isAuthenticating,
password,
onBootstrapTokenChange,
onDisplayNameChange,
onEmailChange,
onPasswordChange,
onGoHome,
onSetAuthMode,
onSubmit,
} = props;
return (
<div className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.08),_transparent_30%),linear-gradient(180deg,#fafaf9_0%,#f5f5f4_100%)] text-stone-900">
<div className="mx-auto max-w-7xl px-4 py-4 sm:px-6 lg:px-8">
<header className="rounded-3xl border border-stone-200/80 bg-white/90 px-5 py-4 shadow-sm backdrop-blur md:px-6">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<button type="button" onClick={onGoHome} className="flex items-center gap-3 text-left">
<div className="rounded-2xl bg-stone-900 p-2.5 text-white shadow-sm">
<Briefcase className="h-5 w-5" />
</div>
<div>
<p className="text-lg font-bold tracking-tight">LocaleScope</p>
<p className="text-sm text-stone-500">Local market intelligence for modern outbound teams</p>
</div>
</button>
<div className="flex items-center gap-3 text-sm font-medium text-stone-600">
<button type="button" onClick={onGoHome} className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
Back to home
</button>
</div>
</div>
</header>
<section className="grid gap-10 py-12 lg:grid-cols-[minmax(0,1fr)_440px] lg:items-center lg:py-16">
<div className="space-y-8">
<Badge variant="primary" className="px-4 py-2 text-sm">
<Sparkles className="h-4 w-4" />
{bootstrapRequired ? 'First-run initialization mode' : 'Secure access to your intelligence workspace'}
</Badge>
<div className="space-y-5">
<h1 className="max-w-3xl text-5xl font-bold tracking-tight text-stone-950 sm:text-6xl">
{bootstrapRequired
? 'Create first site admin'
: authMode === 'sign_up'
? 'Create your workspace and start researching local markets.'
: 'Sign in and continue your market intelligence workflow.'}
</h1>
<p className="max-w-2xl text-lg leading-8 text-stone-600 sm:text-xl">
Access research runs, deep research coverage, clean map review, and saved business history from one focused operating surface.
</p>
</div>
<div className="grid gap-4 sm:grid-cols-3">
{[
['Targeted search', 'Run location-based business research with clear inputs and repeatable jobs.'],
['Map review', 'Inspect returned businesses on a cleaner map built for operational use.'],
['Persistent history', 'Keep research runs and saved businesses available whenever you come back.'],
].map(([title, description]) => (
<Surface key={title} className="p-5">
<p className="text-base font-bold tracking-tight text-stone-900">{title}</p>
<p className="mt-2 text-sm leading-7 text-stone-600">{description}</p>
</Surface>
))}
</div>
</div>
<Card className="rounded-[2rem] p-6 shadow-xl shadow-stone-200/70 sm:p-8">
<div className="mb-6 flex items-center justify-between">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Account Access</p>
<h2 className="mt-2 text-2xl font-bold tracking-tight text-stone-900">
{authMode === 'sign_up' ? 'Create account' : 'Sign in'}
</h2>
<p className="mt-2 text-sm text-stone-600">
{bootstrapRequired
? 'Bootstrap is required because no active app admin exists.'
: authMode === 'sign_up'
? 'Set up your account to start using LocaleScope.'
: 'Use your account to continue where you left off.'}
</p>
</div>
<div className="rounded-2xl bg-stone-100 p-3 text-stone-900">
{authMode === 'sign_up' ? <UserPlus className="h-6 w-6" /> : <LogIn className="h-6 w-6" />}
</div>
</div>
{!bootstrapRequired && (
<div className="grid grid-cols-2 gap-2 rounded-2xl bg-stone-100 p-1">
<button
type="button"
onClick={() => onSetAuthMode('sign_in')}
className={`rounded-xl px-3 py-2.5 text-sm font-semibold transition-all ${
authMode === 'sign_in' ? 'bg-white text-stone-900 shadow-sm' : 'text-stone-500 hover:text-stone-900'
}`}
>
Sign In
</button>
<button
type="button"
onClick={() => onSetAuthMode('sign_up')}
className={`rounded-xl px-3 py-2.5 text-sm font-semibold transition-all ${
authMode === 'sign_up' ? 'bg-white text-stone-900 shadow-sm' : 'text-stone-500 hover:text-stone-900'
}`}
>
Sign Up
</button>
</div>
)}
{bootstrapRequired && !bootstrapEnabled && (
<Alert variant="error" title="Bootstrap Disabled" className="mt-5">
<p>Bootstrap is required, but ALLOW_ADMIN_BOOTSTRAP is disabled.</p>
</Alert>
)}
{authError && (
<Alert variant="error" title="Authentication Error" className="mt-5">
<p>{authError}</p>
</Alert>
)}
{authNotice && <Alert variant="success" className="mt-5">{authNotice}</Alert>}
<form
className="mt-5 space-y-4"
onSubmit={(event) => {
event.preventDefault();
onSubmit();
}}
>
{authMode === 'sign_up' && (
<div>
<FieldLabel>Name</FieldLabel>
<Input
type="text"
value={displayName}
onChange={(event) => onDisplayNameChange(event.target.value)}
placeholder="Your name"
/>
</div>
)}
{bootstrapRequired && (
<div>
<FieldLabel>Bootstrap token</FieldLabel>
<Input
type="password"
required
value={bootstrapToken}
onChange={(event) => onBootstrapTokenChange(event.target.value)}
placeholder="Enter ADMIN_BOOTSTRAP_TOKEN"
/>
</div>
)}
<div>
<FieldLabel>Email</FieldLabel>
<Input
type="email"
required
value={email}
onChange={(event) => onEmailChange(event.target.value)}
placeholder="you@example.com"
/>
</div>
<div>
<FieldLabel>Password</FieldLabel>
<Input
type="password"
required
minLength={6}
value={password}
onChange={(event) => onPasswordChange(event.target.value)}
placeholder="At least 6 characters"
/>
</div>
<Button
type="submit"
disabled={isAuthenticating || (bootstrapRequired && bootstrapLoading)}
size="lg"
className="w-full rounded-2xl bg-stone-900 hover:bg-stone-800"
>
{isAuthenticating ? (
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
) : authMode === 'sign_up' ? (
<UserPlus className="h-5 w-5" />
) : (
<LogIn className="h-5 w-5" />
)}
{bootstrapRequired
? isAuthenticating
? 'Creating first admin...'
: bootstrapLoading
? 'Checking bootstrap status...'
: 'Create First Admin'
: isAuthenticating
? authMode === 'sign_up'
? 'Creating account...'
: 'Signing in...'
: authMode === 'sign_up'
? 'Create Account'
: 'Sign In'}
</Button>
</form>
</Card>
</section>
</div>
</div>
);
}
function ConfigScreen(props: {
icon: ReactElement;
title: string;
description: string;
steps: string[];
footer: string;
}) {
const { icon, title, description, steps, footer } = props;
return (
<div className="flex h-screen items-center justify-center bg-stone-50 p-6 font-sans">
<Card className="w-full max-w-lg p-8 text-center shadow-xl">
<div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-stone-100 text-stone-900">
{icon}
</div>
<h2 className="mb-4 text-2xl font-semibold text-stone-950">{title}</h2>
<p className="mb-6 text-left text-stone-600">{description}</p>
<div className="mb-6 space-y-4 rounded-xl border border-stone-200 bg-stone-50 p-6 text-left">
<p className="text-sm font-medium text-stone-900">Follow these steps:</p>
<ol className="list-inside list-decimal space-y-2 text-sm text-stone-600">
{steps.map((step) => (
<li key={step}>{step}</li>
))}
</ol>
</div>
<p className="text-xs text-stone-400">{footer}</p>
</Card>
</div>
);
}
function MapIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg
{...props}
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21" />
<line x1="9" y1="3" x2="9" y2="18" />
<line x1="15" y1="6" x2="15" y2="21" />
</svg>
);
}
+623
View File
@@ -0,0 +1,623 @@
import { AlertCircle, ArrowUpRight, Building2, CreditCard, Loader2, Shield, Users } from 'lucide-react';
import { useEffect, useState } from 'react';
import { getEligibleAddonsForPlan } from '@/shared/billing/addons';
import { formatLifecycleDate } from '@/shared/billing/lifecycle';
import { getPlanByCode, getPublicPricingPlans, type PlanCode } from '@/shared/billing/plans';
import type { AccountPageData, AppUser } from '@/shared/types';
import {
createAddonCheckout,
createBillingPortalSession,
createSubscriptionCheckout,
getAccountPageData,
updateAccountProfile,
} from '../lib/account';
import {
formatBillingIntervalLabel,
formatBillingStatusLabel,
formatDateLabel,
formatPlanPeriod,
formatPlanPrice,
formatQuantity,
formatUsageResourceName,
getBillingStatusBadgeVariant,
getSuggestedUpgradePlanCode,
getUsageProgressPercent,
getUsageWarningBarClass,
getUsageWarningMessage,
getUsageWarningState,
} from '../lib/billing-ui';
import { sendAnalyticsEvent } from '../lib/analytics';
import { Alert, Badge, Button, Card, FieldLabel, Input, LoadingState, PageContainer, PageShell, SectionHeader, StatCard } from './ui';
const SALES_EMAIL = 'sales@localescope.app';
interface AccountPageProps {
user: AppUser;
onUserUpdated: (user: AppUser) => void;
initialCheckoutPlanCode?: PlanCode | null;
onConsumeInitialCheckoutPlanCode?: () => void;
}
export function AccountPage({ user, onUserUpdated, initialCheckoutPlanCode = null, onConsumeInitialCheckoutPlanCode }: AccountPageProps) {
const [account, setAccount] = useState<AccountPageData | null>(null);
const [displayName, setDisplayName] = useState(user.displayName);
const [avatarUrl, setAvatarUrl] = useState(user.avatarUrl ?? '');
const [workspaceName, setWorkspaceName] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [billingAction, setBillingAction] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
useEffect(() => {
let isMounted = true;
const loadAccount = async () => {
setLoading(true);
setError(null);
try {
const nextAccount = await getAccountPageData();
if (!isMounted) {
return;
}
setAccount(nextAccount);
setDisplayName(nextAccount.profile.displayName);
setAvatarUrl(nextAccount.profile.avatarUrl ?? '');
setWorkspaceName(nextAccount.workspace.name);
setNotice(getBillingReturnNotice());
} catch (nextError) {
if (!isMounted) {
return;
}
setError(nextError instanceof Error ? nextError.message : 'Failed to load account page.');
} finally {
if (isMounted) {
setLoading(false);
}
}
};
void loadAccount();
return () => {
isMounted = false;
};
}, []);
useEffect(() => {
if (!notice || typeof window === 'undefined') {
return;
}
const url = new URL(window.location.href);
if (url.searchParams.has('billing')) {
url.searchParams.delete('billing');
window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
}
}, [notice]);
useEffect(() => {
if (!account || !initialCheckoutPlanCode || billingAction !== null) {
return;
}
void handlePlanAction(initialCheckoutPlanCode).finally(() => {
onConsumeInitialCheckoutPlanCode?.();
});
}, [account, initialCheckoutPlanCode, billingAction, onConsumeInitialCheckoutPlanCode]);
const handleSave = async () => {
setSaving(true);
setError(null);
setNotice(null);
try {
const nextAccount = await updateAccountProfile({
displayName,
avatarUrl: avatarUrl.trim() || null,
workspaceName,
});
setAccount(nextAccount);
onUserUpdated(nextAccount.profile);
setNotice('Account settings updated.');
} catch (nextError) {
setError(nextError instanceof Error ? nextError.message : 'Failed to update account.');
} finally {
setSaving(false);
}
};
const handleSubscriptionCheckout = async (planCode: string) => {
setBillingAction(`plan:${planCode}`);
setError(null);
setNotice(null);
try {
sendAnalyticsEvent({
eventName: 'checkout_started',
planCode,
});
const response = await createSubscriptionCheckout(planCode);
window.location.assign(response.checkoutUrl);
} catch (nextError) {
setError(nextError instanceof Error ? nextError.message : 'Failed to start checkout.');
} finally {
setBillingAction(null);
}
};
const handleAddonCheckout = async (addonCode: string) => {
setBillingAction(`addon:${addonCode}`);
setError(null);
setNotice(null);
try {
sendAnalyticsEvent({
eventName: 'addon_checkout_started',
addonCode,
});
const response = await createAddonCheckout(addonCode);
window.location.assign(response.checkoutUrl);
} catch (nextError) {
setError(nextError instanceof Error ? nextError.message : 'Failed to start add-on checkout.');
} finally {
setBillingAction(null);
}
};
const handleBillingPortal = async () => {
setBillingAction('portal');
setError(null);
try {
sendAnalyticsEvent({
eventName: 'portal_opened',
});
const response = await createBillingPortalSession();
window.location.assign(response.url);
} catch (nextError) {
setError(nextError instanceof Error ? nextError.message : 'Failed to open billing portal.');
} finally {
setBillingAction(null);
}
};
const handlePlanAction = async (planCode: PlanCode) => {
const targetPlan = getPlanByCode(planCode);
if (!targetPlan) {
setError('Selected plan is unavailable. Please refresh and try again.');
return;
}
if (targetPlan.contactSalesRequired || !targetPlan.isSelfServe) {
setError(null);
setNotice(`This plan is available through sales. Contact ${SALES_EMAIL} to coordinate your rollout.`);
if (typeof window !== 'undefined') {
window.location.assign(`mailto:${SALES_EMAIL}`);
}
return;
}
if (account.billing.planCode === planCode && !account.billing.cancelAtPeriodEnd) {
setError(null);
setNotice('You are already on this plan.');
return;
}
const hasExternalPaidSubscription = Boolean(account.billing.externalCustomerRef && account.billing.externalSubscriptionRef);
if (hasExternalPaidSubscription && account.billing.planCode !== planCode) {
setNotice('Use the billing portal to change plans for your existing subscription.');
await handleBillingPortal();
return;
}
await handleSubscriptionCheckout(planCode);
};
if (loading) {
return (
<PageShell>
<PageContainer>
<LoadingState message="Loading account settings..." />
</PageContainer>
</PageShell>
);
}
if (!account) {
return (
<PageShell>
<PageContainer>
<Alert variant="error">{error || 'Account data is unavailable.'}</Alert>
</PageContainer>
</PageShell>
);
}
const activePlan = account.billing.planCode ? getPlanByCode(account.billing.planCode) : null;
const suggestedUpgradePlanCode = getSuggestedUpgradePlanCode(account.billing.planCode, account.billing.billingInterval);
const suggestedUpgradePlan = suggestedUpgradePlanCode ? getPlanByCode(suggestedUpgradePlanCode) : null;
const eligibleAddons = activePlan ? getEligibleAddonsForPlan(activePlan.code, { includeComingSoon: true }) : [];
const publicPricingPlans = getPublicPricingPlans();
const hasExternalPaidSubscription = Boolean(account.billing.externalCustomerRef && account.billing.externalSubscriptionRef);
return (
<PageShell>
<PageContainer>
<SectionHeader
title="Account"
description="Manage your profile, workspace, and subscription settings."
/>
{error ? <Alert variant="error">{error}</Alert> : null}
{notice ? <Alert variant="success">{notice}</Alert> : null}
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1.25fr)_minmax(320px,0.75fr)]">
<Card className="p-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">My Profile</p>
<h2 className="mt-2 text-2xl font-semibold tracking-tight text-stone-950">Personal details</h2>
<p className="mt-2 text-sm text-stone-600">Update the information shown across your workspace.</p>
</div>
<img
src={avatarUrl.trim() || account.profile.avatarUrl || `https://ui-avatars.com/api/?name=${encodeURIComponent(displayName || account.profile.email)}`}
alt={displayName || account.profile.email}
className="h-14 w-14 rounded-full border border-stone-200 object-cover"
referrerPolicy="no-referrer"
/>
</div>
<div className="mt-6 grid gap-4 md:grid-cols-2">
<div>
<FieldLabel>Display Name</FieldLabel>
<Input value={displayName} onChange={(event) => setDisplayName(event.target.value)} placeholder="Your name" />
</div>
<div>
<FieldLabel>Email</FieldLabel>
<Input value={account.profile.email} disabled className="cursor-not-allowed opacity-80" />
</div>
<div className="md:col-span-2">
<FieldLabel>Avatar URL</FieldLabel>
<Input value={avatarUrl} onChange={(event) => setAvatarUrl(event.target.value)} placeholder="https://example.com/avatar.png" />
</div>
<div>
<FieldLabel>Joined</FieldLabel>
<Input value={new Date(account.profile.createdAt).toLocaleDateString()} disabled className="cursor-not-allowed opacity-80" />
</div>
</div>
<div className="mt-6 border-t border-stone-100 pt-6">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Workspace</p>
<div className="mt-4 grid gap-4 md:grid-cols-2">
<div>
<FieldLabel>Workspace Name</FieldLabel>
<Input value={workspaceName} onChange={(event) => setWorkspaceName(event.target.value)} placeholder="Workspace name" />
</div>
<div>
<FieldLabel>Role</FieldLabel>
<div className="flex h-11 items-center rounded-xl border border-stone-200 bg-stone-50 px-4 text-sm text-stone-700">
<Badge variant="neutral">{account.workspace.role}</Badge>
</div>
</div>
</div>
</div>
<div className="mt-6 flex justify-end">
<Button onClick={() => void handleSave()} disabled={saving} size="lg" className="w-full sm:w-auto">
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
Save changes
</Button>
</div>
</Card>
<div className="space-y-6">
<Card className="p-6">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-stone-100 p-3 text-stone-900">
<Building2 className="h-5 w-5" />
</div>
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Workspace</p>
<h3 className="text-lg font-semibold text-stone-950">{account.workspace.name}</h3>
</div>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<Badge variant="primary">{account.workspace.workspaceType}</Badge>
<Badge>{account.workspace.memberCount === 1 ? '1 member' : `${account.workspace.memberCount} members`}</Badge>
</div>
<p className="mt-4 text-sm text-stone-600">
This workspace is the foundation for future team access, subscriptions, and shared territory research workflows.
</p>
</Card>
<Card className="p-6">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-stone-100 p-3 text-stone-900">
<CreditCard className="h-5 w-5" />
</div>
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Plan & Billing</p>
<h3 className="text-lg font-semibold text-stone-950">{activePlan ? activePlan.name : 'Subscription foundation in progress'}</h3>
</div>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<Badge variant={getBillingStatusBadgeVariant(account.billing.status)}>{formatBillingStatusLabel(account.billing.status)}</Badge>
<Badge>{formatBillingIntervalLabel(account.billing.billingInterval)}</Badge>
{account.billing.cancelAtPeriodEnd ? <Badge variant="warning">Cancels at period end</Badge> : null}
</div>
<div className="mt-4 grid gap-3 rounded-2xl bg-stone-50 p-4 text-sm text-stone-600">
<div className="flex items-center justify-between gap-3">
<span>Current period starts</span>
<span className="font-medium text-stone-900">{formatDateLabel(account.billing.currentPeriodStartsAt)}</span>
</div>
<div className="flex items-center justify-between gap-3">
<span>Current period ends</span>
<span className="font-medium text-stone-900">{formatDateLabel(account.billing.currentPeriodEndsAt)}</span>
</div>
<div className="flex items-center justify-between gap-3">
<span>Grace period ends</span>
<span className="font-medium text-stone-900">{formatDateLabel(account.billing.gracePeriodEndsAt)}</span>
</div>
<div className="flex items-center justify-between gap-3">
<span>Stripe sync</span>
<span className="font-medium text-stone-900">{account.billing.billingSyncStatus}</span>
</div>
</div>
<p className="mt-4 text-sm text-stone-600">{account.billing.message}</p>
{account.billing.pendingPlanCode && account.billing.pendingPlanEffectiveAt ? (
<div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
Scheduled downgrade to <span className="font-semibold">{account.billing.pendingPlanCode}</span> on {formatLifecycleDate(account.billing.pendingPlanEffectiveAt)}. If usage is above the new limits after this date, chargeable actions may pause until usage resets, you add capacity, or you upgrade again.
</div>
) : null}
<div className="mt-4 flex flex-wrap gap-3">
{account.billing.externalCustomerRef ? (
<Button type="button" variant="secondary" onClick={() => void handleBillingPortal()} disabled={billingAction !== null}>
{billingAction === 'portal' ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
Manage billing
</Button>
) : null}
{suggestedUpgradePlan ? (
<Button
type="button"
onClick={() => void handlePlanAction(suggestedUpgradePlan.code)}
disabled={billingAction !== null}
>
{billingAction === `plan:${suggestedUpgradePlan.code}` ? <Loader2 className="h-4 w-4 animate-spin" /> : <ArrowUpRight className="h-4 w-4" />}
Upgrade to {suggestedUpgradePlan.name}
</Button>
) : null}
</div>
{suggestedUpgradePlan ? (
<div className="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
<p className="text-sm font-semibold text-emerald-900">Suggested next plan</p>
<div className="mt-2 flex items-center justify-between gap-3">
<div>
<p className="text-base font-semibold text-emerald-950">{suggestedUpgradePlan.name}</p>
<p className="text-sm text-emerald-800">Step up when you need more usage headroom or premium workflows.</p>
</div>
<Button
type="button"
size="sm"
className="shrink-0"
onClick={() => void handlePlanAction(suggestedUpgradePlan.code)}
disabled={billingAction !== null}
>
{billingAction === `plan:${suggestedUpgradePlan.code}` ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
Upgrade
<ArrowUpRight className="h-4 w-4" />
</Button>
</div>
</div>
) : null}
</Card>
<Card className="p-6">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Plan Options</p>
<h3 className="text-lg font-semibold text-stone-950">Choose the right subscription</h3>
</div>
<div className="mt-4 space-y-3">
{publicPricingPlans.map((plan) => {
const isCurrentPlan = account.billing.planCode === plan.code && !account.billing.cancelAtPeriodEnd;
const buttonLabel = isCurrentPlan
? 'Current plan'
: plan.contactSalesRequired
? 'Contact sales'
: hasExternalPaidSubscription
? 'Change in billing portal'
: `Choose ${plan.name}`;
return (
<div key={plan.code} className="rounded-2xl border border-stone-200 p-4">
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-sm font-semibold text-stone-900">{plan.name}</p>
<p className="mt-1 text-xs text-stone-500">
{formatPlanPrice(plan.priceCents, plan.currencyCode)} {formatPlanPeriod(plan.billingInterval, plan.contactSalesRequired)}
</p>
</div>
<Button
type="button"
size="sm"
variant={isCurrentPlan ? 'secondary' : 'primary'}
onClick={() => void handlePlanAction(plan.code)}
disabled={isCurrentPlan || billingAction !== null}
>
{billingAction === `plan:${plan.code}` || (billingAction === 'portal' && hasExternalPaidSubscription && !plan.contactSalesRequired && !isCurrentPlan)
? <Loader2 className="h-4 w-4 animate-spin" />
: null}
{buttonLabel}
</Button>
</div>
</div>
);
})}
</div>
</Card>
<Card className="p-6">
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Usage This Period</p>
<h3 className="text-lg font-semibold text-stone-950">Quota visibility</h3>
</div>
{account.billing.usage.some((usage) => {
const state = getUsageWarningState(usage);
return state === 'warning' || state === 'critical';
}) ? <Badge variant="warning">Needs attention</Badge> : null}
</div>
<div className="mt-4 space-y-4">
{account.billing.usage.map((usage) => {
const warningMessage = getUsageWarningMessage(usage);
const progressPercent = getUsageProgressPercent(usage);
return (
<div key={usage.resource} className="rounded-2xl border border-stone-200 p-4">
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-sm font-semibold text-stone-900">{formatUsageResourceName(usage.resource)}</p>
<p className="mt-1 text-xs text-stone-500">
Included: {formatQuantity(usage.included)} · Consumed: {formatQuantity(usage.consumed)} · Remaining: {formatQuantity(usage.remaining)}
</p>
</div>
<Badge variant={usage.availability === 'not_available' ? 'neutral' : getUsageWarningState(usage) === 'critical' ? 'danger' : getUsageWarningState(usage) === 'warning' ? 'warning' : 'success'}>
{usage.availability === 'not_available' ? 'Not included' : usage.availability === 'custom' ? 'Custom' : usage.availability === 'unlimited' ? 'Unlimited' : 'Tracked'}
</Badge>
</div>
{progressPercent !== null ? (
<div className="mt-3 h-2 rounded-full bg-stone-100">
<div className={`h-2 rounded-full ${getUsageWarningBarClass(usage)}`} style={{ width: `${progressPercent}%` }} />
</div>
) : null}
{warningMessage ? (
<div className="mt-3 flex items-start gap-2 rounded-xl bg-stone-50 px-3 py-2 text-xs text-stone-600">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
<span>{warningMessage}</span>
</div>
) : null}
</div>
);
})}
</div>
</Card>
<Card className="p-6">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Add-On Balances</p>
<h3 className="text-lg font-semibold text-stone-950">Extra capacity</h3>
</div>
{account.billing.addonBalances.length === 0 ? (
<p className="mt-4 text-sm text-stone-600">No add-on balances are active yet.</p>
) : (
<div className="mt-4 space-y-3">
{account.billing.addonBalances.map((balance) => (
<div key={`${balance.addonCode}-${balance.resource}`} className="rounded-2xl border border-stone-200 p-4 text-sm">
<div className="flex items-center justify-between gap-3">
<div>
<p className="font-semibold text-stone-900">{balance.addonCode}</p>
<p className="text-xs text-stone-500">{formatUsageResourceName(balance.resource)}</p>
</div>
<Badge variant="info">{formatQuantity(balance.remainingQuantity)} remaining</Badge>
</div>
<p className="mt-2 text-xs text-stone-500">Expires: {formatDateLabel(balance.expiresAt)}</p>
</div>
))}
</div>
)}
</Card>
<Card className="p-6">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Available Add-Ons</p>
<h3 className="text-lg font-semibold text-stone-950">Optional capacity and feature packs</h3>
</div>
{eligibleAddons.length === 0 ? (
<p className="mt-4 text-sm text-stone-600">No add-ons are configured for this plan yet.</p>
) : (
<div className="mt-4 space-y-3">
{eligibleAddons.map((addon) => (
<div key={addon.code} className="rounded-2xl border border-stone-200 p-4 text-sm">
<div className="flex items-center justify-between gap-3">
<div>
<p className="font-semibold text-stone-900">{addon.name}</p>
<p className="mt-1 text-xs text-stone-500">{addon.description}</p>
</div>
<Badge variant={addon.availability === 'active' ? 'success' : 'warning'}>
{addon.availability === 'active' ? 'Available' : 'Coming soon'}
</Badge>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<Badge variant="info">{addon.purchaseMode === 'one_time' ? 'One-time' : 'Recurring'}</Badge>
<Badge>{addon.quantity === null ? 'Feature add-on' : `${formatQuantity(addon.quantity)} units`}</Badge>
</div>
{addon.availability === 'active' ? (
<div className="mt-3">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => void handleAddonCheckout(addon.code)}
disabled={billingAction !== null}
>
{billingAction === `addon:${addon.code}` ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
Buy add-on
</Button>
</div>
) : null}
</div>
))}
</div>
)}
</Card>
<Card className="p-6">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-stone-100 p-3 text-stone-900">
<Users className="h-5 w-5" />
</div>
<div>
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Team</p>
<h3 className="text-lg font-semibold text-stone-950">Member management placeholder</h3>
</div>
</div>
<p className="mt-4 text-sm text-stone-600">{account.team.message}</p>
</Card>
</div>
</div>
<div className="grid grid-cols-1 gap-6 md:grid-cols-3">
<StatCard title="Research Runs" value={account.summary.totalSearchJobs} icon={Building2} />
<StatCard title="Deep Research Batches" value={account.summary.totalDeepResearchBatches} icon={Users} />
<StatCard title="Saved Businesses" value={account.summary.totalBusinesses} icon={Shield} />
</div>
</PageContainer>
</PageShell>
);
}
function getBillingReturnNotice() {
if (typeof window === 'undefined') {
return null;
}
const billing = new URL(window.location.href).searchParams.get('billing');
switch (billing) {
case 'success':
return 'Billing checkout completed. Subscription sync should appear here shortly.';
case 'addon-success':
return 'Add-on purchase completed. New balance should appear here shortly.';
case 'cancelled':
return 'Checkout was canceled before completion.';
default:
return null;
}
}
+85
View File
@@ -0,0 +1,85 @@
import React, { useEffect, useMemo } from 'react';
import { Map, Marker, useMap } from '@vis.gl/react-google-maps';
import { cleanMapOptions } from '../lib/map-styles';
interface BasicResearchMapProps {
pin: google.maps.LatLngLiteral | null;
radiusKm: number;
onPinChange: (nextPin: google.maps.LatLngLiteral) => void;
}
export function BasicResearchMap({ pin, radiusKm, onPinChange }: BasicResearchMapProps) {
const defaultCenter = useMemo(() => pin ?? { lat: 39.5, lng: -98.35 }, [pin]);
return (
<div className="relative h-[280px] overflow-hidden rounded-3xl border border-stone-200 bg-stone-100 shadow-sm sm:h-[360px] lg:h-full lg:min-h-[540px]">
<Map
defaultCenter={defaultCenter}
defaultZoom={5}
style={{ width: '100%', height: '100%' }}
gestureHandling="cooperative"
{...cleanMapOptions}
onClick={(event) => {
const latLng = event.detail.latLng;
if (latLng) {
onPinChange(latLng);
}
}}
>
<BasicResearchOverlay pin={pin} radiusKm={radiusKm} />
{pin && (
<Marker
position={pin}
icon={{
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#059669',
fillOpacity: 1,
strokeColor: '#064e3b',
strokeWeight: 2,
scale: 7,
}}
/>
)}
</Map>
{!pin && (
<div className="pointer-events-none absolute inset-x-4 top-4 rounded-2xl border border-white/20 bg-white/90 p-3 text-sm text-stone-600 shadow-lg backdrop-blur-sm sm:inset-x-6 sm:top-6 sm:p-4">
Click anywhere on the map to drop a pin. Use the Area field to adjust the search circle.
</div>
)}
</div>
);
}
function BasicResearchOverlay({ pin, radiusKm }: { pin: google.maps.LatLngLiteral | null; radiusKm: number }) {
const map = useMap();
useEffect(() => {
if (!map || !pin) {
return;
}
const circle = new google.maps.Circle({
map,
center: pin,
radius: Math.max(1, radiusKm) * 1000,
strokeColor: '#059669',
strokeOpacity: 0.9,
strokeWeight: 2,
fillColor: '#10b981',
fillOpacity: 0.12,
clickable: false,
});
const bounds = circle.getBounds();
if (bounds) {
map.fitBounds(bounds, 60);
}
return () => {
circle.setMap(null);
};
}, [map, pin, radiusKm]);
return null;
}
+300
View File
@@ -0,0 +1,300 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
AlertCircle,
CalendarDays,
Check,
CheckCircle2,
CircleOff,
Clock3,
Loader2,
MapPin,
Search as SearchIcon,
SlidersHorizontal,
} from 'lucide-react';
import { listSearchJobs } from '../lib/database';
import type { SearchJob, SearchJobStatus } from '../types';
import type { AppUser } from '@/shared/types';
import { Alert, Badge, Button, Card, EmptyState, LoadingState, MetricPill, SectionHeader, Select, Input } from './ui';
interface BasicResultsViewProps {
user: AppUser;
selectedJobIds: string[];
onToggleJobSelection: (jobId: string) => void;
onShowSelectedOnMap: () => void;
onClearSelection: () => void;
}
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 BasicResultsView({ user, selectedJobIds, onToggleJobSelection, onShowSelectedOnMap, onClearSelection }: BasicResultsViewProps) {
const [searchTerm, setSearchTerm] = useState('');
const [statusFilter, setStatusFilter] = useState<JobStatusFilter>('all');
const [sortOrder, setSortOrder] = useState<SortOption>('newest');
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]);
return (
<div className="space-y-5">
<SectionHeader
eyebrow="Basic Results"
title="Basic research runs"
description="Filter the grid to find specific runs, select the ones you want, then send the full selection to the map."
actions={
<MetricPill>
{filteredJobs.length} shown of {jobs.length}
</MetricPill>
}
/>
<Card className="space-y-4 p-4">
<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"
/>
</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)}
>
{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)}
>
{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}>
Show selected on map ({selectedJobCount})
</Button>
<Button type="button" onClick={onClearSelection} variant="secondary">
Clear selection
</Button>
</div>
</div>
)}
</Card>
{error && <Alert variant="error">{error}</Alert>}
{isLoadingHistory ? (
<LoadingState message="Loading research jobs..." />
) : filteredJobs.length === 0 ? (
<EmptyState title="No research jobs match the current filters." description="Try adjusting the search term, status filter, or sort order." />
) : (
<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">
<Badge variant={statusMeta.variant} icon={statusMeta.icon}>
<span className={statusMeta.icon === Loader2 ? 'inline-flex animate-pulse' : ''}>{statusMeta.label}</span>
</Badge>
<span className={`inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-semibold ${isSelected ? 'bg-stone-900 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 business found' : `${job.totalResults} businesses found`}</span>
<span className={isSelected ? 'text-emerald-700' : 'text-stone-400'}>{isSelected ? 'Included in selection' : 'Available to select'}</span>
</div>
</button>
);
})}
</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,
variant: 'success' as const,
};
case 'running':
return {
label: 'Running',
icon: Loader2,
variant: 'info' as const,
};
case 'failed':
return {
label: 'Failed',
icon: AlertCircle,
variant: 'danger' as const,
};
case 'stopped':
return {
label: 'Stopped',
icon: CircleOff,
variant: 'neutral' as const,
};
case 'pending':
default:
return {
label: 'Pending',
icon: Clock3,
variant: 'warning' as const,
};
}
}
+383
View File
@@ -0,0 +1,383 @@
import React, { useEffect, useMemo, useState } from 'react';
import Papa from 'papaparse';
import {
ArrowUpDown,
Briefcase,
ChevronLeft,
ChevronRight,
Download,
Globe,
Loader2,
Phone,
Star,
} from 'lucide-react';
import { listBusinesses, listJobResultLinks, listSearchJobs, type SearchJobResultLink } from '../lib/database';
import type { Business, SearchJob } from '../types';
import type { AppUser } from '@/shared/types';
import { cn } from '../lib/cn';
import { Alert, Badge, Button, Card, EmptyState, Input, LoadingState, PageContainer, PageShell, SectionHeader, Select, StatCard } from './ui';
interface DashboardProps {
user: AppUser;
}
export function Dashboard({ user }: DashboardProps) {
const [businesses, setBusinesses] = useState<Business[]>([]);
const [jobs, setJobs] = useState<SearchJob[]>([]);
const [jobLinks, setJobLinks] = useState<SearchJobResultLink[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [filterJobId, setFilterJobId] = useState<string>('all');
const [filterHasWebsite, setFilterHasWebsite] = useState(false);
const [filterHasPhone, setFilterHasPhone] = useState(false);
const [sortField, setSortField] = useState<keyof Business>('name');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
useEffect(() => {
const loadDashboard = async () => {
setLoading(true);
setError(null);
try {
const [nextBusinesses, nextJobs, nextLinks] = await Promise.all([
listBusinesses(user.id),
listSearchJobs(user.id, 100),
listJobResultLinks(user.id),
]);
setBusinesses(nextBusinesses);
setJobs(nextJobs);
setJobLinks(nextLinks);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load dashboard data.');
} finally {
setLoading(false);
}
};
void loadDashboard();
}, [user.id]);
useEffect(() => {
setCurrentPage(1);
}, [searchTerm, filterJobId, filterHasWebsite, filterHasPhone, sortField, sortDirection]);
const filteredBusinesses = useMemo(() => {
const allowedIds =
filterJobId === 'all'
? null
: new Set(jobLinks.filter((link) => link.searchJobId === filterJobId).map((link) => link.businessId));
return businesses
.filter((business) => {
const matchesSearch =
business.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
business.city?.toLowerCase().includes(searchTerm.toLowerCase()) ||
business.category?.toLowerCase().includes(searchTerm.toLowerCase());
const matchesWebsite = !filterHasWebsite || Boolean(business.website);
const matchesPhone = !filterHasPhone || Boolean(business.phone);
const matchesJob = !allowedIds || allowedIds.has(business.id);
return matchesSearch && matchesWebsite && matchesPhone && matchesJob;
})
.sort((a, b) => {
const aVal = a[sortField] ?? '';
const bVal = b[sortField] ?? '';
if (aVal < bVal) {
return sortDirection === 'asc' ? -1 : 1;
}
if (aVal > bVal) {
return sortDirection === 'asc' ? 1 : -1;
}
return 0;
});
}, [businesses, filterHasPhone, filterHasWebsite, filterJobId, jobLinks, searchTerm, sortDirection, sortField]);
const paginatedBusinesses = useMemo(() => {
const start = (currentPage - 1) * itemsPerPage;
return filteredBusinesses.slice(start, start + itemsPerPage);
}, [currentPage, filteredBusinesses]);
const totalPages = Math.max(1, Math.ceil(filteredBusinesses.length / itemsPerPage));
const kpis = useMemo(() => {
const total = businesses.length;
const withWebsite = businesses.filter((business) => Boolean(business.website)).length;
const withPhone = businesses.filter((business) => Boolean(business.phone)).length;
const ratedBusinesses = businesses.filter((business) => typeof business.rating === 'number');
const avgRating = ratedBusinesses.length
? ratedBusinesses.reduce((sum, business) => sum + (business.rating ?? 0), 0) / ratedBusinesses.length
: 0;
return [
{ name: 'Saved Businesses', value: total, icon: Briefcase },
{ name: 'With Website', value: withWebsite, icon: Globe },
{ name: 'With Phone', value: withPhone, icon: Phone },
{ name: 'Avg Rating', value: avgRating.toFixed(1), icon: Star },
];
}, [businesses]);
const handleExport = () => {
const csv = Papa.unparse(
filteredBusinesses.map((business) => ({
Name: business.name,
Address: business.address,
City: business.city,
State: business.stateProvince,
PostalCode: business.postalCode,
Country: business.country,
Phone: business.phone,
Website: business.website,
Rating: business.rating,
Reviews: business.reviewCount,
Category: business.category,
Latitude: business.latitude,
Longitude: business.longitude,
Source: business.source,
CreatedAt: business.createdAt,
})),
);
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', `localescope_export_${new Date().toISOString().split('T')[0]}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const toggleSort = (field: keyof Business) => {
if (sortField === field) {
setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
return;
}
setSortField(field);
setSortDirection('asc');
};
if (loading) {
return (
<PageShell>
<PageContainer>
<LoadingState message="Loading dashboard data..." />
</PageContainer>
</PageShell>
);
}
return (
<PageShell>
<PageContainer>
<SectionHeader
title="Research Dashboard"
description="Browse saved search results from your workspace and export targeted business datasets."
actions={
<Button onClick={handleExport} size="lg" className="w-full sm:w-auto">
<Download className="h-5 w-5" />
Export CSV
</Button>
}
/>
{error && <Alert variant="error">{error}</Alert>}
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
{kpis.map((kpi) => (
<StatCard key={kpi.name} title={kpi.name} value={kpi.value} icon={kpi.icon} />
))}
</div>
<Card className="space-y-4 p-6">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-[minmax(0,1fr)_220px_auto_auto]">
<Input
type="text"
placeholder="Search by name, city, or category..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Select
value={filterJobId}
onChange={(e) => setFilterJobId(e.target.value)}
>
<option value="all">All jobs</option>
{jobs.map((job) => (
<option key={job.id} value={job.id}>
{job.name}
</option>
))}
</Select>
<Button
onClick={() => setFilterHasWebsite(!filterHasWebsite)}
variant={filterHasWebsite ? 'primary' : 'secondary'}
className={cn('w-full px-4 sm:w-auto')}
>
Has Website
</Button>
<Button
onClick={() => setFilterHasPhone(!filterHasPhone)}
variant={filterHasPhone ? 'primary' : 'secondary'}
className={cn('w-full px-4 sm:w-auto')}
>
Has Phone
</Button>
</div>
</Card>
{filteredBusinesses.length === 0 ? (
<EmptyState title="No businesses found matching your filters." description="Try adjusting your search term or filters to see more results." />
) : (
<Card className="overflow-hidden p-0">
<div className="md:hidden">
<div className="divide-y divide-stone-100">
{paginatedBusinesses.map((business) => (
<article key={business.id} className="space-y-4 p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate text-base font-semibold text-stone-950">{business.name}</p>
<p className="mt-1 line-clamp-2 text-sm text-stone-500">{business.address || business.city || 'Location unavailable'}</p>
</div>
<Badge>{business.category || 'Uncategorized'}</Badge>
</div>
<div className="grid grid-cols-2 gap-3 rounded-2xl bg-stone-50 p-4 text-sm">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Location</p>
<p className="mt-1 text-sm font-medium text-stone-700">{business.city || 'Unknown'}</p>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Rating</p>
<div className="mt-1 flex items-center gap-1 text-sm font-semibold text-amber-600">
<Star className="h-4 w-4 fill-amber-500 text-amber-500" />
{business.rating || 'N/A'}
<span className="text-xs font-normal text-stone-400">({business.reviewCount || 0})</span>
</div>
</div>
</div>
<div className="flex items-center gap-4 text-sm text-stone-500">
{business.website ? (
<a href={business.website} target="_blank" rel="noopener" className="inline-flex items-center gap-2 transition hover:text-emerald-700">
<Globe className="h-4 w-4" />
Website
</a>
) : null}
{business.phone ? (
<a href={`tel:${business.phone}`} className="inline-flex items-center gap-2 transition hover:text-stone-900">
<Phone className="h-4 w-4" />
Call
</a>
) : null}
</div>
</article>
))}
</div>
</div>
<div className="hidden overflow-x-auto md:block">
<table className="w-full border-collapse text-left">
<thead>
<tr className="border-b border-stone-200 bg-stone-50">
<th className="cursor-pointer px-6 py-4 text-xs font-bold uppercase tracking-wider text-stone-500 hover:text-stone-900" onClick={() => toggleSort('name')}>
<div className="flex items-center gap-2">
Business Name
<ArrowUpDown className="h-3 w-3" />
</div>
</th>
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-stone-500">Location</th>
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-stone-500">Category</th>
<th className="cursor-pointer px-6 py-4 text-xs font-bold uppercase tracking-wider text-stone-500 hover:text-stone-900" onClick={() => toggleSort('rating')}>
<div className="flex items-center gap-2">
Rating
<ArrowUpDown className="h-3 w-3" />
</div>
</th>
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-stone-500">Contact</th>
</tr>
</thead>
<tbody className="divide-y divide-stone-100">
{paginatedBusinesses.map((business) => (
<tr key={business.id} className="group transition-colors hover:bg-stone-50">
<td className="px-6 py-4">
<div className="font-semibold text-stone-950">{business.name}</div>
<div className="mt-0.5 max-w-[260px] truncate text-xs text-stone-400">{business.address}</div>
</td>
<td className="px-6 py-4 text-sm text-stone-600">{business.city || 'Unknown'}</td>
<td className="px-6 py-4">
<Badge>
{business.category || 'Uncategorized'}
</Badge>
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-1 text-sm font-semibold text-amber-600">
<Star className="h-4 w-4 fill-amber-500 text-amber-500" />
{business.rating || 'N/A'}
<span className="text-xs font-normal text-stone-400">({business.reviewCount || 0})</span>
</div>
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-3">
{business.website && (
<a href={business.website} target="_blank" rel="noopener" className="text-stone-500 transition hover:text-emerald-700">
<Globe className="h-5 w-5" />
</a>
)}
{business.phone && (
<a href={`tel:${business.phone}`} className="text-stone-500 transition hover:text-stone-900">
<Phone className="h-5 w-5" />
</a>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{filteredBusinesses.length > itemsPerPage && (
<div className="flex flex-col gap-3 border-t border-stone-200 bg-stone-50 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-6">
<p className="text-sm text-stone-500">
Showing <span className="font-medium">{(currentPage - 1) * itemsPerPage + 1}</span> to{' '}
<span className="font-medium">{Math.min(currentPage * itemsPerPage, filteredBusinesses.length)}</span> of{' '}
<span className="font-medium">{filteredBusinesses.length}</span> businesses
</p>
<div className="flex items-center justify-end gap-2">
<Button
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
disabled={currentPage === 1}
variant="secondary"
size="icon"
>
<ChevronLeft className="h-5 w-5" />
</Button>
<Button
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
disabled={currentPage === totalPages}
variant="secondary"
size="icon"
>
<ChevronRight className="h-5 w-5" />
</Button>
</div>
</div>
)}
</Card>
)}
</PageContainer>
</PageShell>
);
}
@@ -0,0 +1,135 @@
import React, { useEffect, useMemo } from 'react';
import { Map, Marker, useMap } from '@vis.gl/react-google-maps';
import type { DeepResearchPreview } from '@/shared/types';
import { cleanMapOptions } from '../lib/map-styles';
interface DeepResearchPreviewMapProps {
pin: google.maps.LatLngLiteral | null;
preview: DeepResearchPreview | null;
onPinChange: (nextPin: google.maps.LatLngLiteral) => void;
}
const ringPalette = ['#059669', '#10b981', '#34d399', '#6ee7b7', '#a7f3d0', '#d1fae5'];
export function DeepResearchPreviewMap({ pin, preview, onPinChange }: DeepResearchPreviewMapProps) {
const defaultCenter = useMemo(() => {
if (pin) {
return pin;
}
const baseArea = preview?.baseArea;
if (baseArea?.centroidLat != null && baseArea?.centroidLng != null) {
return { lat: baseArea.centroidLat, lng: baseArea.centroidLng };
}
return { lat: 39.5, lng: -98.35 };
}, [pin, preview]);
return (
<div className="relative h-[280px] overflow-hidden rounded-3xl border border-stone-200 bg-stone-100 shadow-sm sm:h-[360px] lg:h-[440px]">
<Map
defaultCenter={defaultCenter}
defaultZoom={5}
style={{ width: '100%', height: '100%' }}
gestureHandling="cooperative"
{...cleanMapOptions}
onClick={(event) => {
const latLng = event.detail.latLng;
if (latLng) {
onPinChange(latLng);
}
}}
>
<PreviewOverlay overlay={preview?.overlay ?? null} pin={pin} preview={preview} />
{pin && (
<Marker
position={pin}
icon={{
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#059669',
fillOpacity: 1,
strokeColor: '#064e3b',
strokeWeight: 2,
scale: 7,
}}
/>
)}
</Map>
{!pin && (
<div className="pointer-events-none absolute inset-x-4 top-4 rounded-2xl border border-white/20 bg-white/90 p-3 text-sm text-stone-600 shadow-lg backdrop-blur-sm sm:inset-x-6 sm:top-6 sm:p-4">
Click anywhere on the map to drop a pin and preview the ZIP/FSA areas included in the deep research run.
</div>
)}
</div>
);
}
function PreviewOverlay({
overlay,
pin,
preview,
}: {
overlay: DeepResearchPreview['overlay'] | null;
pin: google.maps.LatLngLiteral | null;
preview: DeepResearchPreview | null;
}) {
const map = useMap();
useEffect(() => {
if (!map || !overlay) {
return;
}
const addedFeatures = map.data.addGeoJson(overlay as never);
map.data.setStyle((feature) => {
const ring = Number(feature.getProperty('propagationRing') ?? 0);
const color = ringPalette[Math.min(ring, ringPalette.length - 1)];
return {
fillColor: color,
fillOpacity: ring === 0 ? 0.28 : 0.16,
strokeColor: color,
strokeWeight: ring === 0 ? 3 : 2,
clickable: false,
};
});
return () => {
addedFeatures.forEach((feature) => map.data.remove(feature));
};
}, [map, overlay]);
useEffect(() => {
if (!map) {
return;
}
if (pin && (!preview || preview.areas.length === 0)) {
map.panTo(pin);
map.setZoom(15);
return;
}
const bounds = new google.maps.LatLngBounds();
let hasBounds = false;
if (pin) {
bounds.extend(pin);
hasBounds = true;
}
preview?.areas.forEach((area) => {
if (area.centroidLat != null && area.centroidLng != null) {
bounds.extend({ lat: area.centroidLat, lng: area.centroidLng });
hasBounds = true;
}
});
if (hasBounds) {
map.fitBounds(bounds, 40);
}
}, [map, pin, preview]);
return null;
}
@@ -0,0 +1,133 @@
import React, { useCallback, useEffect, useState } from 'react';
import type { DeepResearchBatchSummary } from '@/shared/types';
import { getDeepResearchBatch, listDeepResearchBatches } from '../lib/database';
import { Alert, Badge, Button, EmptyState, LoadingState, MetricPill, SectionHeader, Surface } from './ui';
interface DeepResearchResultsViewProps {
onShowBatchOnMap: (jobIds: string[]) => void;
}
export function DeepResearchResultsView({ onShowBatchOnMap }: DeepResearchResultsViewProps) {
const [batches, setBatches] = useState<DeepResearchBatchSummary[]>([]);
const [error, setError] = useState<string | null>(null);
const [isLoadingBatches, setIsLoadingBatches] = useState(true);
const [activeBatchId, setActiveBatchId] = useState<string | null>(null);
const refreshBatches = useCallback(async () => {
setIsLoadingBatches(true);
try {
const nextBatches = await listDeepResearchBatches();
setBatches(nextBatches);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load deep research history.');
} finally {
setIsLoadingBatches(false);
}
}, []);
useEffect(() => {
void refreshBatches();
}, [refreshBatches]);
const handleOpenBatchOnMap = async (batchId: string) => {
setActiveBatchId(batchId);
setError(null);
try {
const batch = await getDeepResearchBatch(batchId);
if (batch.jobIds.length === 0) {
setError('This deep research batch does not have child jobs yet.');
return;
}
onShowBatchOnMap(batch.jobIds);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load batch details.');
} finally {
setActiveBatchId(null);
}
};
return (
<div className="space-y-5">
<SectionHeader
eyebrow="Deep Research Results"
title="Previous deep research batches"
description="Review completed or failed batch runs and open their bundled map results."
actions={<MetricPill>{batches.length} batches</MetricPill>}
/>
{error && <Alert variant="error">{error}</Alert>}
{isLoadingBatches ? (
<LoadingState message="Loading deep research batches..." />
) : batches.length === 0 ? (
<EmptyState title="No deep research batches yet." description="Preview a pin on the map and run your first deep research batch." />
) : (
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
{batches.map((batch) => (
<Surface key={batch.id} className="p-5">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-lg font-semibold text-stone-950">{batch.businessType}</p>
<p className="mt-1 text-sm text-stone-500">{batch.basePostalCode ? `${batch.basePostalCode} · ${batch.countryCode ?? 'N/A'}` : 'Base postal area unavailable'}</p>
</div>
<Badge variant={statusBadgeVariant(batch.status)}>{batch.status}</Badge>
</div>
<div className="mt-4 grid grid-cols-2 gap-3 rounded-2xl bg-stone-50 p-4 text-sm text-stone-600">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Propagation</p>
<p className="mt-1 text-base font-bold text-stone-900">{batch.propagation}</p>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Postal Areas</p>
<p className="mt-1 text-base font-bold text-stone-900">{batch.totalPostalAreas}</p>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Child Jobs</p>
<p className="mt-1 text-base font-bold text-stone-900">{batch.childJobCount}</p>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-stone-400">Businesses</p>
<p className="mt-1 text-base font-bold text-stone-900">{batch.totalResults}</p>
</div>
</div>
{batch.keywords && <p className="mt-4 text-sm text-stone-500">Keywords: {batch.keywords}</p>}
<div className="mt-4 flex items-center justify-between border-t border-stone-100 pt-4 text-sm text-stone-500">
<span>Created {new Date(batch.createdAt).toLocaleDateString()}</span>
<Button
type="button"
onClick={() => void handleOpenBatchOnMap(batch.id)}
disabled={activeBatchId === batch.id}
size="sm"
>
{activeBatchId === batch.id ? 'Loading...' : 'Show bundle on map'}
</Button>
</div>
</Surface>
))}
</div>
)}
</div>
);
}
function statusBadgeVariant(status: DeepResearchBatchSummary['status']) {
switch (status) {
case 'completed':
return 'success' as const;
case 'failed':
return 'danger' as const;
case 'running':
return 'info' as const;
case 'stopped':
return 'neutral' as const;
case 'pending':
default:
return 'warning' as const;
}
}
+243
View File
@@ -0,0 +1,243 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Crosshair, Loader2, MapPinned, Sparkles } from 'lucide-react';
import type { DeepResearchPreview } from '@/shared/types';
import { createDeepResearchBatch, previewDeepResearch } from '../lib/database';
import { DeepResearchPreviewMap } from './DeepResearchPreviewMap';
import { Alert, Badge, Button, FieldLabel, Input, MetricPill, PageContainer, PageShell, SectionHeader, Surface } from './ui';
interface DeepResearchViewProps {
onShowBatchOnMap: (jobIds: string[]) => void;
topContent?: React.ReactNode;
}
export function DeepResearchView({ onShowBatchOnMap, topContent }: DeepResearchViewProps) {
const [pin, setPin] = useState<google.maps.LatLngLiteral | null>(null);
const [businessType, setBusinessType] = useState('');
const [keywords, setKeywords] = useState('');
const [propagation, setPropagation] = useState(1);
const [preview, setPreview] = useState<DeepResearchPreview | null>(null);
const [previewError, setPreviewError] = useState<string | null>(null);
const [isPreviewing, setIsPreviewing] = useState(false);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
setPreview(null);
setPreviewError(null);
}, [businessType, keywords, pin?.lat, pin?.lng, propagation]);
const canPreview = Boolean(pin && businessType.trim());
const previewSummary = useMemo(() => {
if (!preview) {
return null;
}
return `${preview.totalAreas} postal areas across ${preview.countryCode} with ${preview.estimatedChildJobs} child researches.`;
}, [preview]);
const handlePreview = async () => {
if (!pin || !businessType.trim()) {
setPreviewError('Drop a pin and add a business type before previewing deep research.');
return;
}
setIsPreviewing(true);
setPreviewError(null);
try {
const nextPreview = await previewDeepResearch({
lat: pin.lat,
lng: pin.lng,
propagation,
businessType: businessType.trim(),
keywords: keywords.trim() || undefined,
});
setPreview(nextPreview);
} catch (err) {
setPreviewError(err instanceof Error ? err.message : 'Failed to preview deep research.');
} finally {
setIsPreviewing(false);
}
};
const handleRunDeepResearch = async () => {
if (!pin || !businessType.trim()) {
setPreviewError('Drop a pin and add a business type before running deep research.');
return;
}
setIsRunning(true);
setPreviewError(null);
try {
const batch = await createDeepResearchBatch({
lat: pin.lat,
lng: pin.lng,
propagation,
businessType: businessType.trim(),
keywords: keywords.trim() || undefined,
});
if (batch.jobIds.length > 0) {
onShowBatchOnMap(batch.jobIds);
}
} catch (err) {
setPreviewError(err instanceof Error ? err.message : 'Failed to run deep research.');
} finally {
setIsRunning(false);
}
};
return (
<PageShell>
<PageContainer>
{topContent}
<SectionHeader
title="Deep Research"
description="Drop a pin, choose a propagation depth, preview the ZIP or FSA areas that will be covered, and run one bundled research batch across every adjacent postal area."
/>
<section className="grid grid-cols-1 items-stretch gap-6 xl:grid-cols-[400px_minmax(0,1fr)]">
<Surface className="p-5 sm:p-7">
<div className="space-y-5">
<div className="space-y-2">
<FieldLabel>Business Type</FieldLabel>
<Input
type="text"
value={businessType}
onChange={(event) => setBusinessType(event.target.value)}
placeholder="e.g. dentists, HVAC, bakeries"
/>
</div>
<div className="space-y-2">
<FieldLabel>Keywords</FieldLabel>
<Input
type="text"
value={keywords}
onChange={(event) => setKeywords(event.target.value)}
placeholder="Optional comma-separated keywords"
/>
</div>
<div className="space-y-2.5">
<FieldLabel>Location</FieldLabel>
<div className="rounded-2xl border border-stone-200 bg-stone-50 p-4 text-sm text-stone-600">
Click directly on the map to place the deep research center. The preview uses that active pin to find the base ZIP or FSA and expand outward.
</div>
</div>
{pin && (
<Alert variant="success" title="Active research center">
<p>{pin.lat.toFixed(5)}, {pin.lng.toFixed(5)}</p>
</Alert>
)}
<div className="space-y-2">
<FieldLabel>Propagation</FieldLabel>
<input
type="range"
min="0"
max="5"
value={propagation}
onChange={(event) => setPropagation(Number.parseInt(event.target.value, 10) || 0)}
className="w-full accent-emerald-600"
/>
<div className="mt-2 flex items-center justify-between text-xs text-stone-500">
<span>Base postal area only</span>
<Badge variant="primary">{propagation} hop{propagation === 1 ? '' : 's'}</Badge>
<span>Expand outward</span>
</div>
</div>
<div className="rounded-2xl border border-stone-200 bg-stone-50 p-4 text-sm text-stone-600">
<div className="flex items-center gap-2 font-semibold text-stone-900">
<Crosshair className="h-4 w-4 text-emerald-600" />
Pin placement
</div>
<p className="mt-2">Click the map to drop a pin. The preview will find the containing ZIP or FSA and expand to adjacent postal areas based on the propagation depth.</p>
{pin && <p className="mt-3 font-medium text-stone-800">Pin: {pin.lat.toFixed(5)}, {pin.lng.toFixed(5)}</p>}
</div>
{previewError && (
<Alert variant="error">{previewError}</Alert>
)}
{previewSummary && (
<Alert variant="success" title="Preview ready">
<p>{previewSummary}</p>
<p className="mt-2 text-emerald-800">
Base area: <span className="font-semibold">{preview?.baseArea.displayName}</span>
</p>
</Alert>
)}
<div className="flex flex-col gap-3 sm:flex-row">
<Button
type="button"
onClick={() => void handlePreview()}
disabled={!canPreview || isPreviewing || isRunning}
variant="secondary"
className="flex-1"
>
{isPreviewing ? <Loader2 className="h-4 w-4 animate-spin" /> : <MapPinned className="h-4 w-4" />}
Preview areas
</Button>
<Button
type="button"
onClick={() => void handleRunDeepResearch()}
disabled={!canPreview || isPreviewing || isRunning}
className="flex-1"
>
{isRunning ? <Loader2 className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />}
Run deep research
</Button>
</div>
</div>
</Surface>
<div className="flex h-full flex-col gap-4">
<DeepResearchPreviewMap pin={pin} preview={preview} onPinChange={setPin} />
<Surface className="p-5">
<div className="flex items-center gap-2 text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">
<MapPinned className="h-4 w-4" />
Map Controls
</div>
<h3 className="mt-3 text-lg font-semibold text-stone-950">Preview center and coverage</h3>
<p className="mt-2 text-sm text-stone-600">
Drop a pin directly on the map to define the base postal area. Preview colors and rings show how propagation expands the deep research batch into adjacent areas.
</p>
</Surface>
{preview && (
<Surface className="p-6">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 className="text-lg font-semibold text-stone-950">Preview coverage</h3>
<p className="mt-1 text-sm text-stone-600">These postal areas will become child researches in the batch.</p>
</div>
<MetricPill className="bg-stone-50 text-stone-700 shadow-none">
{preview.totalAreas} areas
</MetricPill>
</div>
<div className="mt-4 flex flex-wrap gap-2">
{preview.areas.map((area) => (
<Badge
key={area.id}
variant={area.propagationRing === 0 ? 'primary' : 'neutral'}
>
{area.displayName} · ring {area.propagationRing}
</Badge>
))}
</div>
</Surface>
)}
</div>
</section>
</PageContainer>
</PageShell>
);
}
+134
View File
@@ -0,0 +1,134 @@
import React from 'react';
import { Search, LayoutDashboard, Map as MapIcon, LogOut, Briefcase, Files, UserRound } from 'lucide-react';
import type { SessionUser } from '@/shared/types';
import { getUserAvatarUrl, getUserDisplayName } from '../lib/auth';
import { cn } from '../lib/cn';
import { Button } from './ui';
export type AppTab = 'setup' | 'results' | 'dashboard' | 'map' | 'account';
interface LayoutProps {
user: SessionUser;
activeTab: AppTab;
setActiveTab: (tab: AppTab) => void;
onLogout: () => void;
children: React.ReactNode;
}
export function Layout({ user, activeTab, setActiveTab, onLogout, children }: LayoutProps) {
const userDisplayName = getUserDisplayName(user);
const userAvatarUrl = getUserAvatarUrl(user);
const navigation = [
{ id: 'setup', name: 'Research', icon: Search },
{ id: 'results', name: 'Results', icon: Files },
{ id: 'dashboard', name: 'Dashboard', icon: LayoutDashboard },
{ id: 'map', name: 'Map View', icon: MapIcon },
{ id: 'account', name: 'Account', icon: UserRound },
] as const;
const activeNavigationItem = navigation.find((item) => item.id === activeTab) ?? navigation[0];
return (
<div className="flex h-[100dvh] flex-col overflow-hidden bg-stone-100 lg:h-screen lg:flex-row">
<header className="flex items-center justify-between border-b border-stone-200 bg-white px-4 py-3 lg:hidden">
<div className="flex min-w-0 items-center gap-3">
<div className="rounded-xl bg-stone-900 p-2 text-white shadow-sm">
<Briefcase className="h-5 w-5" />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-semibold text-stone-950">LocaleScope</p>
<p className="truncate text-xs text-stone-500">{activeNavigationItem.name}</p>
</div>
</div>
<Button onClick={onLogout} variant="secondary" size="sm" className="shrink-0 px-3 text-stone-600 hover:text-stone-900">
<LogOut className="h-4 w-4" />
Sign Out
</Button>
</header>
<aside className="hidden w-72 flex-col border-r border-stone-200 bg-white lg:flex">
<div className="border-b border-stone-100 px-6 py-6">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-stone-900 p-2.5 text-white shadow-sm">
<Briefcase className="h-6 w-6" />
</div>
<div>
<p className="text-lg font-semibold tracking-tight text-stone-950">LocaleScope</p>
<p className="text-sm text-stone-500">Operational local market intelligence workspace</p>
</div>
</div>
</div>
<nav className="flex-1 space-y-1 px-4 py-5">
{navigation.map((item) => (
<button
key={item.id}
onClick={() => setActiveTab(item.id)}
className={cn(
'flex w-full items-center gap-3 rounded-xl px-4 py-3 text-sm font-semibold transition',
activeTab === item.id
? 'bg-stone-900 text-white shadow-sm'
: 'text-stone-600 hover:bg-stone-100 hover:text-stone-900',
)}
>
<item.icon className={cn('h-5 w-5', activeTab === item.id ? 'text-white' : 'text-stone-400')} />
{item.name}
</button>
))}
</nav>
<div className="border-t border-stone-100 p-4">
<div className="mb-3 rounded-2xl border border-stone-200 bg-stone-50 px-4 py-3">
<div className="flex items-center gap-3">
<img
src={userAvatarUrl || `https://ui-avatars.com/api/?name=${encodeURIComponent(userDisplayName)}`}
alt={userDisplayName}
className="h-8 w-8 rounded-full border border-stone-200"
referrerPolicy="no-referrer"
/>
<div className="min-w-0 flex-1">
{user.isAdmin ? (
<span className="mb-1 inline-flex items-center rounded-full border border-stone-300 bg-white px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-stone-700">
Site Admin
</span>
) : null}
<p className="truncate text-sm font-semibold text-stone-900">{userDisplayName}</p>
<p className="truncate text-xs text-stone-500">{user.email}</p>
</div>
</div>
</div>
<Button onClick={onLogout} variant="secondary" className="w-full justify-start gap-3 text-stone-600 hover:text-stone-900">
<LogOut className="h-5 w-5" />
Sign Out
</Button>
</div>
</aside>
<main className="relative flex min-h-0 flex-1 flex-col overflow-hidden pb-16 lg:pb-0">{children}</main>
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-stone-200 bg-white/95 px-2 pb-[calc(env(safe-area-inset-bottom,0px)+0.5rem)] pt-2 backdrop-blur lg:hidden">
<div className="grid grid-cols-5 gap-1">
{navigation.map((item) => {
const isActive = activeTab === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => setActiveTab(item.id)}
className={cn(
'flex min-w-0 flex-col items-center justify-center gap-1 rounded-xl px-2 py-2 text-[11px] font-semibold transition',
isActive ? 'bg-stone-900 text-white shadow-sm' : 'text-stone-500 hover:bg-stone-100 hover:text-stone-900',
)}
>
<item.icon className="h-4 w-4 shrink-0" />
<span className="truncate">{item.name}</span>
</button>
);
})}
</div>
</nav>
</div>
);
}
+232
View File
@@ -0,0 +1,232 @@
import React, { useEffect, useMemo, useState } from 'react';
import { InfoWindow, Map, Marker, useMap } from '@vis.gl/react-google-maps';
import { Globe, Loader2, MapPin, Navigation, Phone, Star } from 'lucide-react';
import { listBusinesses, listBusinessesForJobs } from '../lib/database';
import { cleanMapOptions } from '../lib/map-styles';
import type { Business } from '../types';
import type { AppUser } from '@/shared/types';
import { Alert, Badge, EmptyState } from './ui';
interface MapViewProps {
user: AppUser;
jobIds?: string[] | null;
}
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 () => {
setLoading(true);
setError(null);
try {
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 results.');
} finally {
setLoading(false);
}
};
void loadBusinesses();
}, [jobIds, selectedJobCount, user.id]);
useEffect(() => {
if (!selected) {
return;
}
const stillExists = businesses.some((business) => business.id === selected.id);
if (!stillExists) {
setSelected(null);
}
}, [businesses, selected]);
useEffect(() => {
if (!map || businesses.length === 0) {
return;
}
const bounds = new google.maps.LatLngBounds();
let hasCoords = false;
businesses.forEach((business) => {
if (typeof business.latitude === 'number' && typeof business.longitude === 'number') {
bounds.extend({ lat: business.latitude, lng: business.longitude });
hasCoords = true;
}
});
if (!hasCoords) {
return;
}
map.fitBounds(bounds, 50);
if (businesses.length === 1) {
map.setZoom(15);
}
}, [businesses, map]);
const center = useMemo(() => {
const validCoords = businesses.filter(
(business) => typeof business.latitude === 'number' && typeof business.longitude === 'number',
);
if (validCoords.length === 0) {
return { lat: 37.42, lng: -122.08 };
}
const lat = validCoords.reduce((sum, business) => sum + (business.latitude ?? 0), 0) / validCoords.length;
const lng = validCoords.reduce((sum, business) => sum + (business.longitude ?? 0), 0) / validCoords.length;
return { lat, lng };
}, [businesses]);
if (loading) {
return (
<div className="flex flex-1 items-center justify-center bg-stone-50">
<Loader2 className="h-8 w-8 animate-spin text-emerald-500" />
</div>
);
}
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">
<EmptyState
icon={MapPin}
title="No businesses to show on the map"
description={selectedJobCount > 0
? 'The selected research jobs do not have saved map results yet. Try completed jobs or run the research again.'
: 'No saved businesses are available yet. Run a research job to populate the map.'}
/>
{error ? <Alert variant="error" className="mt-4">{error}</Alert> : null}
</div>
</div>
);
}
return (
<div className="relative flex-1 bg-stone-100">
{error && (
<Alert variant="error" className="absolute left-4 right-4 top-4 z-10 shadow-lg lg:left-8 lg:right-auto lg:top-8 lg:max-w-md">{error}</Alert>
)}
<Map
defaultCenter={center}
defaultZoom={12}
style={{ width: '100%', height: '100%' }}
gestureHandling="greedy"
{...cleanMapOptions}
>
{businesses.map((business) =>
typeof business.latitude === 'number' && typeof business.longitude === 'number' ? (
<Marker
key={business.id}
position={{ lat: business.latitude, lng: business.longitude }}
onClick={() => setSelected(business)}
icon={{
path: google.maps.SymbolPath.CIRCLE,
fillColor: selected?.id === business.id ? '#059669' : '#10b981',
fillOpacity: 1,
strokeColor: selected?.id === business.id ? '#064e3b' : '#065f46',
strokeWeight: 2,
scale: selected?.id === business.id ? 8 : 7,
}}
/>
) : null,
)}
{selected && typeof selected.latitude === 'number' && typeof selected.longitude === 'number' && (
<InfoWindow position={{ lat: selected.latitude, lng: selected.longitude }} onCloseClick={() => setSelected(null)}>
<div className="max-w-[280px] space-y-3 p-2">
<header>
<h3 className="text-base font-semibold leading-tight text-stone-950">{selected.name}</h3>
<div className="mt-1 flex items-center gap-1 text-xs text-stone-500">
<MapPin className="h-3 w-3" />
<span className="truncate">{selected.address}</span>
</div>
</header>
<div className="flex items-center gap-3 border-y border-stone-100 py-2">
<div className="flex items-center gap-1 text-sm font-semibold text-amber-600">
<Star className="h-4 w-4 fill-amber-500 text-amber-500" />
{selected.rating || 'N/A'}
<span className="text-xs font-normal text-stone-400">({selected.reviewCount || 0})</span>
</div>
<Badge>
{selected.category || 'Uncategorized'}
</Badge>
</div>
<div className="flex items-center gap-2">
{selected.website && (
<a
href={selected.website}
target="_blank"
rel="noopener"
className="inline-flex h-9 flex-1 items-center justify-center gap-2 rounded-xl bg-emerald-600 px-3 text-xs font-semibold text-white transition hover:bg-emerald-700"
>
<Globe className="h-3.5 w-3.5" />
Website
</a>
)}
{selected.phone && (
<a
href={`tel:${selected.phone}`}
className="inline-flex h-9 flex-1 items-center justify-center gap-2 rounded-xl border border-stone-200 bg-white px-3 text-xs font-semibold text-stone-700 transition hover:bg-stone-50"
>
<Phone className="h-3.5 w-3.5" />
Call
</a>
)}
</div>
<a
href={`https://www.google.com/maps/dir/?api=1&destination=${selected.latitude},${selected.longitude}`}
target="_blank"
rel="noopener"
className="flex w-full items-center justify-center gap-2 pt-1 text-xs font-medium text-stone-500 hover:text-stone-900"
>
<Navigation className="h-3.5 w-3.5" />
Get Directions
</a>
</div>
</InfoWindow>
)}
</Map>
<div className="absolute inset-x-4 bottom-4 z-10 rounded-2xl border border-white/20 bg-white/90 p-4 shadow-xl backdrop-blur-sm lg:inset-x-auto lg:bottom-8 lg:left-8 lg:max-w-xs">
<h4 className="mb-2 text-sm font-semibold text-stone-950">Map Summary</h4>
<div className="space-y-2">
<div className="flex items-center justify-between text-xs">
<span className="text-stone-500">Businesses on Map</span>
<span className="font-bold text-emerald-600">{businesses.length}</span>
</div>
<div className="flex items-center justify-between text-xs">
<span className="text-stone-500">Selected Business</span>
<span className="max-w-[140px] truncate font-bold text-stone-900 lg:max-w-[120px]">{selected ? selected.name : 'None'}</span>
</div>
{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 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>
</div>
</div>
);
}
+80
View File
@@ -0,0 +1,80 @@
import { Check } from 'lucide-react';
import { getPlanCardBullets, getPlanDisplayMeta, getPublicPricingPlansForInterval, type BillingInterval, type PlanCode } from '@/shared/billing/plans';
import { Button } from './ui';
import { formatPlanPeriod, formatPlanPrice } from '../lib/billing-ui';
import { sendAnalyticsEvent } from '../lib/analytics';
interface PricingCardsProps {
billingInterval: Extract<BillingInterval, 'monthly' | 'annual'>;
onGoToAuth: (mode: 'sign_in' | 'sign_up', planCode?: PlanCode) => void;
}
export function PricingCards({ billingInterval, onGoToAuth }: PricingCardsProps) {
const pricingPlans = getPublicPricingPlansForInterval(billingInterval);
return (
<div className="grid gap-5 xl:grid-cols-4">
{pricingPlans.map((plan) => {
const display = getPlanDisplayMeta(plan.code);
const isFeatured = display.badgeLabel === 'Best Value';
return (
<div
key={plan.code}
className={`rounded-[2rem] border p-7 shadow-sm ${
isFeatured ? 'border-emerald-300 bg-emerald-50/60 shadow-emerald-100' : 'border-stone-200 bg-white'
}`}
>
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xl font-bold tracking-tight text-stone-900">{plan.name}</p>
<p className="mt-2 text-sm text-stone-600">{display.audience}</p>
</div>
{display.badgeLabel ? (
<span className="rounded-full bg-emerald-600 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-white">
{display.badgeLabel}
</span>
) : null}
</div>
<div className="mt-8 flex items-end gap-1">
<span className="text-4xl font-bold tracking-tight text-stone-950">{formatPlanPrice(plan.priceCents, plan.currencyCode)}</span>
<span className="pb-1 text-sm text-stone-500">{formatPlanPeriod(plan.billingInterval, plan.contactSalesRequired)}</span>
</div>
<p className="mt-3 text-sm leading-7 text-stone-600">{display.summary}</p>
<Button
type="button"
onClick={() => {
sendAnalyticsEvent({
eventName: 'pricing_plan_selected',
planCode: plan.code,
metadata: {
billingInterval,
},
});
onGoToAuth(display.ctaMode, plan.code);
}}
className={`mt-8 w-full rounded-2xl ${isFeatured ? 'bg-emerald-600 hover:bg-emerald-700' : ''}`}
variant={isFeatured ? 'primary' : 'secondary'}
>
{display.ctaLabel}
</Button>
<div className="mt-8 space-y-3">
{getPlanCardBullets(plan.code).map((item) => (
<div key={item} className="flex items-start gap-3 text-sm text-stone-700">
<div className="mt-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-emerald-100 text-emerald-700">
<Check className="h-3.5 w-3.5" />
</div>
<span>{item}</span>
</div>
))}
</div>
</div>
);
})}
</div>
);
}
@@ -0,0 +1,132 @@
import { Check, Minus } from 'lucide-react';
import { getFeatureGate } from '@/shared/billing/feature-gates';
import { getPlanByCode, getPublicPricingPlansForInterval, type ActivePlanCode, type BillingInterval, type PlanFeatures } from '@/shared/billing/plans';
import { Card, Badge } from './ui';
import { formatQuantity } from '../lib/billing-ui';
const FEATURE_ROWS: Array<{ feature: keyof PlanFeatures; label: string }> = [
{ feature: 'csvExport', label: 'CSV export' },
{ feature: 'mapSearch', label: 'Map search' },
{ feature: 'radiusSearch', label: 'Radius search' },
{ feature: 'advancedFilters', label: 'Advanced filtering' },
{ feature: 'savedSearches', label: 'Saved searches' },
{ feature: 'territoryMapping', label: 'Territory mapping' },
{ feature: 'deduplication', label: 'Deduplication' },
{ feature: 'exportHistory', label: 'Export history' },
{ feature: 'taggingNotes', label: 'Tagging & notes' },
{ feature: 'sharedLists', label: 'Shared lists' },
{ feature: 'scheduledResearch', label: 'Scheduled research' },
{ feature: 'bulkExports', label: 'Bulk exports' },
{ feature: 'crmIntegrations', label: 'CRM integrations' },
{ feature: 'apiAccess', label: 'API access' },
{ feature: 'webhooks', label: 'Webhooks' },
{ feature: 'collaboration', label: 'Collaboration' },
{ feature: 'enrichments', label: 'Enrichments' },
{ feature: 'prioritySupport', label: 'Priority support' },
{ feature: 'sso', label: 'SSO' },
{ feature: 'sla', label: 'SLA' },
{ feature: 'whiteLabel', label: 'White-labeling' },
];
interface PricingComparisonTableProps {
billingInterval: Extract<BillingInterval, 'monthly' | 'annual'>;
}
export function PricingComparisonTable({ billingInterval }: PricingComparisonTableProps) {
const plans = getPublicPricingPlansForInterval(billingInterval);
return (
<Card className="overflow-hidden">
<div className="border-b border-stone-200 px-6 py-5">
<p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Plan Comparison</p>
<h3 className="mt-2 text-2xl font-semibold tracking-tight text-stone-950">Compare capabilities across plans</h3>
<p className="mt-2 text-sm leading-7 text-stone-600">Included-but-not-ready capabilities are labeled as coming soon so the table stays honest with the current rollout phase.</p>
</div>
<div className="overflow-x-auto">
<table className="min-w-full border-collapse text-left text-sm">
<thead>
<tr className="border-b border-stone-200 bg-stone-50">
<th className="px-6 py-4 font-semibold text-stone-500">Capability</th>
{plans.map((plan) => (
<th key={plan.code} className="px-6 py-4 font-semibold text-stone-900">
<div className="flex flex-col gap-1">
<span>{plan.name}</span>
{plan.code === 'growth_monthly' || plan.code === 'growth_annual' ? <Badge variant="primary">Best Value</Badge> : null}
</div>
</th>
))}
</tr>
</thead>
<tbody>
<ComparisonValueRow
label="Research runs / month"
values={plans.map((plan) => (plan.limits.researchRunsPerMonth === null ? 'Custom' : formatQuantity(plan.limits.researchRunsPerMonth)))}
/>
<ComparisonValueRow
label="Exports / month"
values={plans.map((plan) => (plan.limits.exportsPerMonth === null ? 'Custom' : formatQuantity(plan.limits.exportsPerMonth)))}
/>
<ComparisonValueRow
label="Users included"
values={plans.map((plan) => (plan.limits.usersIncluded === null ? 'Custom' : formatQuantity(plan.limits.usersIncluded)))}
/>
<ComparisonValueRow
label="Workspaces included"
values={plans.map((plan) => (plan.limits.workspacesIncluded === null ? 'Unlimited' : formatQuantity(plan.limits.workspacesIncluded)))}
/>
{FEATURE_ROWS.map(({ feature, label }) => (
<ComparisonFeatureRow key={feature} label={label} planCodes={plans.map((plan) => plan.code)} feature={feature} />
))}
</tbody>
</table>
</div>
</Card>
);
}
function ComparisonValueRow({ label, values }: { label: string; values: string[] }) {
return (
<tr className="border-b border-stone-100 align-top">
<td className="px-6 py-4 font-medium text-stone-700">{label}</td>
{values.map((value, index) => (
<td key={`${label}-${index}`} className="px-6 py-4 text-stone-600">{value}</td>
))}
</tr>
);
}
function ComparisonFeatureRow({ label, planCodes, feature }: { label: string; planCodes: ActivePlanCode[]; feature: keyof PlanFeatures }) {
return (
<tr className="border-b border-stone-100 align-top">
<td className="px-6 py-4 font-medium text-stone-700">{label}</td>
{planCodes.map((planCode) => (
<td key={`${label}-${planCode}`} className="px-6 py-4">
<FeatureGateCell planCode={planCode} feature={feature} />
</td>
))}
</tr>
);
}
function FeatureGateCell({ planCode, feature }: { planCode: ActivePlanCode; feature: keyof PlanFeatures }) {
const plan = getPlanByCode(planCode);
const gate = getFeatureGate(planCode, feature);
if (!plan) {
return null;
}
switch (gate.state) {
case 'available':
return <span className="inline-flex items-center gap-2 text-emerald-700"><Check className="h-4 w-4" />Included</span>;
case 'coming_soon':
return <Badge variant="warning">Coming soon</Badge>;
case 'contact_sales':
return plan.code === 'enterprise_custom' && plan.features[feature] ? <Badge variant="warning">Coming soon</Badge> : <Badge variant="info">Enterprise</Badge>;
case 'upgrade_required':
return <span className="text-stone-500">Higher tier</span>;
case 'hidden':
return <span className="inline-flex items-center gap-2 text-stone-300"><Minus className="h-4 w-4" />Not included</span>;
}
}
+42
View File
@@ -0,0 +1,42 @@
import React, { useState } from 'react';
import { MapPinned, Search } from 'lucide-react';
import type { AppUser } from '@/shared/types';
import { DeepResearchView } from './DeepResearchView';
import { SearchSetup } from './SearchSetup';
import { SegmentedTabs } from './ui';
type ResearchTab = 'research' | 'deepResearch';
interface ResearchWorkspaceProps {
user: AppUser;
selectedJobIds: string[];
onToggleJobSelection: (jobId: string) => void;
onSelectCreatedJob: (jobId: string) => void;
onShowSelectedOnMap: () => void;
onClearSelection: () => void;
onShowBatchOnMap: (jobIds: string[]) => void;
}
export function ResearchWorkspace({
user,
selectedJobIds,
onToggleJobSelection,
onSelectCreatedJob,
onShowSelectedOnMap,
onClearSelection,
onShowBatchOnMap,
}: ResearchWorkspaceProps) {
const [activeTab, setActiveTab] = useState<ResearchTab>('research');
const tabs = <SegmentedTabs tabs={[{ value: 'research', label: 'Basic', icon: Search }, { value: 'deepResearch', label: 'Deep Research', icon: MapPinned }]} value={activeTab} onChange={(value) => setActiveTab(value)} />;
return activeTab === 'research' ? (
<SearchSetup
user={user}
onSelectCreatedJob={onSelectCreatedJob}
topContent={tabs}
/>
) : (
<DeepResearchView onShowBatchOnMap={onShowBatchOnMap} topContent={tabs} />
);
}
+46
View File
@@ -0,0 +1,46 @@
import React, { useState } from 'react';
import { Files, MapPinned } from 'lucide-react';
import type { AppUser } from '@/shared/types';
import { BasicResultsView } from './BasicResultsView';
import { DeepResearchResultsView } from './DeepResearchResultsView';
import { PageContainer, PageShell, SectionHeader, SegmentedTabs } from './ui';
type ResultsTab = 'basic' | 'deepResearch';
interface ResultsWorkspaceProps {
user: AppUser;
selectedJobIds: string[];
onToggleJobSelection: (jobId: string) => void;
onShowSelectedOnMap: () => void;
onClearSelection: () => void;
onShowBatchOnMap: (jobIds: string[]) => void;
}
export function ResultsWorkspace({ user, selectedJobIds, onToggleJobSelection, onShowSelectedOnMap, onClearSelection, onShowBatchOnMap }: ResultsWorkspaceProps) {
const [activeTab, setActiveTab] = useState<ResultsTab>('basic');
return (
<PageShell>
<PageContainer>
<SegmentedTabs tabs={[{ value: 'basic', label: 'Basic', icon: Files }, { value: 'deepResearch', label: 'Deep Research', icon: MapPinned }]} value={activeTab} onChange={(value) => setActiveTab(value)} />
<SectionHeader
title="Results"
description="Browse previous Basic and Deep Research runs, select items, and send them to the map when needed."
/>
{activeTab === 'basic' ? (
<BasicResultsView
user={user}
selectedJobIds={selectedJobIds}
onToggleJobSelection={onToggleJobSelection}
onShowSelectedOnMap={onShowSelectedOnMap}
onClearSelection={onClearSelection}
/>
) : (
<DeepResearchResultsView onShowBatchOnMap={onShowBatchOnMap} />
)}
</PageContainer>
</PageShell>
);
}
+216
View File
@@ -0,0 +1,216 @@
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';
import { Alert, Button, FieldLabel, Input, PageContainer, PageShell, SectionHeader, Surface } from './ui';
interface SearchSetupProps {
user: AppUser;
onSelectCreatedJob: (jobId: string) => void;
topContent?: React.ReactNode;
}
export function SearchSetup({
user: _user,
onSelectCreatedJob,
topContent,
}: SearchSetupProps) {
const [name, setName] = useState('');
const [radius, setRadius] = useState(5);
const [businessType, setBusinessType] = useState('');
const [keywords, setKeywords] = useState('');
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 [error, setError] = useState<string | null>(null);
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);
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: `${pin.lat.toFixed(5)}, ${pin.lng.toFixed(5)}`,
radiusKm: radius,
businessType: businessType.trim(),
keywords: keywords.trim() || undefined,
lat: pin.lat,
lng: pin.lng,
});
onSelectCreatedJob(response.job.id);
} catch (err) {
setError(err instanceof Error ? err.message : 'Research failed.');
} finally {
setIsSearching(false);
}
};
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 (
<PageShell>
<PageContainer>
{topContent}
<SectionHeader
title="Basic Research"
description="Drop a pin on the map, define the search area, and run standard research before reviewing saved jobs below."
/>
<section className="grid grid-cols-1 items-stretch gap-6 xl:grid-cols-[400px_minmax(0,1fr)]">
<Surface className="p-5 sm:p-7">
<form onSubmit={handleRunSearch} className="space-y-5">
<div className="space-y-2">
<FieldLabel>Research Name</FieldLabel>
<Input
type="text"
placeholder="Give this research a memorable name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="space-y-2">
<FieldLabel>Business Type</FieldLabel>
<Input
type="text"
required
placeholder="e.g. coffee shop, plumber"
value={businessType}
onChange={(e) => setBusinessType(e.target.value)}
/>
</div>
<div className="space-y-2">
<FieldLabel>Keywords</FieldLabel>
<Input
type="text"
placeholder="e.g. organic, emergency, family-owned"
value={keywords}
onChange={(e) => setKeywords(e.target.value)}
/>
</div>
<div className="space-y-2.5">
<FieldLabel>Location Source</FieldLabel>
<Button
type="button"
onClick={handleUseMyLocation}
disabled={locationAction !== null}
variant="secondary"
>
<LocateFixed className="h-4 w-4" />
{locationAction === 'geolocate' ? 'Locating...' : 'Use my location'}
</Button>
{locationError && (
<Alert variant="error">{locationError}</Alert>
)}
</div>
<div className="space-y-2">
<FieldLabel>Area (km radius)</FieldLabel>
<Input
type="number"
min="1"
max="50"
value={radius}
onChange={(e) => setRadius(Number.parseInt(e.target.value, 10) || 1)}
/>
</div>
<div className="rounded-2xl border border-stone-200 bg-stone-50 px-4 py-3 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>
{hasLocationPin && (
<Alert variant="success" title="Active search center">
<p>{pin!.lat.toFixed(5)}, {pin!.lng.toFixed(5)}</p>
</Alert>
)}
{error && (
<Alert variant="error">{error}</Alert>
)}
<Button
type="submit"
disabled={isSearching}
size="lg"
className="w-full sm:w-auto"
>
{isSearching ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Running Research...
</>
) : (
<>
<Play className="h-5 w-5" />
Run Research
</>
)}
</Button>
</form>
</Surface>
<div className="flex h-full flex-col gap-4">
<BasicResearchMap pin={pin} radiusKm={radius} onPinChange={(nextPin) => void applyPin(nextPin)} />
<Surface className="p-5">
<div className="flex items-center gap-2 text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">
<MapPin className="h-4 w-4" />
Map Controls
</div>
<h3 className="mt-3 text-lg font-semibold text-stone-950">Search center and radius</h3>
<p className="mt-2 text-sm text-stone-600">
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>
</Surface>
</div>
</section>
</PageContainer>
</PageShell>
);
}
+284
View File
@@ -0,0 +1,284 @@
import type { ButtonHTMLAttributes, HTMLAttributes, InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from 'react';
import { AlertCircle, CheckCircle2, Info, type LucideIcon } from 'lucide-react';
import { cn } from '../lib/cn';
export function PageShell({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('flex-1 overflow-y-auto bg-stone-50 px-4 py-5 sm:p-6 lg:p-8', className)} {...props} />;
}
export function PageContainer({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('mx-auto max-w-7xl space-y-6 lg:space-y-8', className)} {...props} />;
}
export function SectionHeader({
eyebrow,
title,
description,
actions,
className,
}: {
eyebrow?: string;
title: string;
description?: string;
actions?: ReactNode;
className?: string;
}) {
return (
<div className={cn('flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between', className)}>
<div>
{eyebrow ? <p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">{eyebrow}</p> : null}
<h1 className={cn(eyebrow ? 'mt-2' : '', 'text-3xl font-semibold tracking-tight text-stone-950')}>{title}</h1>
{description ? <p className="mt-2 max-w-3xl text-sm leading-7 text-stone-600">{description}</p> : null}
</div>
{actions ? <div className="w-full sm:w-auto sm:shrink-0">{actions}</div> : null}
</div>
);
}
export function Card({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('rounded-2xl border border-stone-200 bg-white shadow-sm', className)} {...props} />;
}
export function Surface({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('rounded-3xl border border-stone-200 bg-white shadow-sm', className)} {...props} />;
}
const buttonVariants = {
primary: 'bg-emerald-600 text-white shadow-sm hover:bg-emerald-700 focus-visible:ring-emerald-500',
secondary: 'border border-stone-200 bg-white text-stone-700 hover:bg-stone-50 focus-visible:ring-emerald-500',
subtle: 'bg-stone-100 text-stone-700 hover:bg-stone-200 focus-visible:ring-emerald-500',
danger: 'bg-red-600 text-white shadow-sm hover:bg-red-700 focus-visible:ring-red-500',
} as const;
const buttonSizes = {
sm: 'h-10 px-4 text-sm',
md: 'h-11 px-4 text-sm',
lg: 'h-12 px-6 text-sm',
icon: 'h-10 w-10',
} as const;
export function Button({
className,
variant = 'primary',
size = 'md',
...props
}: ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: keyof typeof buttonVariants;
size?: keyof typeof buttonSizes;
}) {
return (
<button
className={cn(
'inline-flex items-center justify-center gap-2 rounded-xl font-semibold transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
buttonVariants[variant],
buttonSizes[size],
className,
)}
{...props}
/>
);
}
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
return (
<input
className={cn(
'w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm text-stone-900 outline-none transition placeholder:text-stone-400 focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500',
className,
)}
{...props}
/>
);
}
export function Select({ className, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
return (
<select
className={cn(
'w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm text-stone-900 outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500',
className,
)}
{...props}
/>
);
}
export function FieldLabel({ className, ...props }: HTMLAttributes<HTMLLabelElement>) {
return <label className={cn('mb-2 block text-sm font-semibold text-stone-700', className)} {...props} />;
}
const alertVariants = {
error: {
shell: 'border-red-100 bg-red-50 text-red-700',
icon: AlertCircle,
title: 'Issue',
},
success: {
shell: 'border-emerald-200 bg-emerald-50/80 text-emerald-900',
icon: CheckCircle2,
title: 'Success',
},
info: {
shell: 'border-stone-200 bg-stone-50 text-stone-700',
icon: Info,
title: 'Info',
},
} as const;
export function Alert({
variant = 'info',
title,
children,
className,
}: {
variant?: keyof typeof alertVariants;
title?: string;
children: ReactNode;
className?: string;
}) {
const config = alertVariants[variant];
const Icon = config.icon;
return (
<div className={cn('flex items-start gap-3 rounded-2xl border p-4 text-sm', config.shell, className)}>
<Icon className="mt-0.5 h-5 w-5 shrink-0" />
<div>
{title ? <p className="font-semibold">{title}</p> : null}
<div className={cn(title ? 'mt-1' : '')}>{children}</div>
</div>
</div>
);
}
const badgeVariants = {
neutral: 'border-stone-200 bg-stone-100 text-stone-700',
primary: 'border-emerald-200 bg-emerald-50 text-emerald-700',
success: 'border-emerald-200 bg-emerald-50 text-emerald-700',
warning: 'border-amber-200 bg-amber-50 text-amber-700',
danger: 'border-red-200 bg-red-50 text-red-700',
info: 'border-sky-200 bg-sky-50 text-sky-700',
} as const;
export function Badge({
className,
variant = 'neutral',
icon: Icon,
children,
}: {
className?: string;
variant?: keyof typeof badgeVariants;
icon?: LucideIcon;
children: ReactNode;
}) {
return (
<span className={cn('inline-flex items-center gap-1 rounded-full border px-3 py-1 text-xs font-semibold', badgeVariants[variant], className)}>
{Icon ? <Icon className="h-3.5 w-3.5" /> : null}
{children}
</span>
);
}
export function MetricPill({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('rounded-full border border-stone-200 bg-white px-4 py-2 text-sm font-medium text-stone-600 shadow-sm', className)} {...props} />;
}
export function EmptyState({
icon: Icon,
title,
description,
action,
className,
}: {
icon?: LucideIcon;
title: string;
description: string;
action?: ReactNode;
className?: string;
}) {
return (
<Card className={cn('border-dashed p-6 text-center sm:p-10', className)}>
{Icon ? (
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-stone-100 text-stone-500">
<Icon className="h-5 w-5" />
</div>
) : null}
<p className={cn('text-lg font-semibold text-stone-900', Icon ? 'mt-4' : '')}>{title}</p>
<p className="mt-2 text-sm text-stone-500">{description}</p>
{action ? <div className="mt-5">{action}</div> : null}
</Card>
);
}
export function LoadingState({ message }: { message: string }) {
return (
<Card className="flex items-center gap-3 p-5 text-sm text-stone-500">
<svg className="h-4 w-4 animate-spin text-emerald-600" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<circle cx="12" cy="12" r="10" className="opacity-20" stroke="currentColor" strokeWidth="4" />
<path d="M22 12a10 10 0 0 0-10-10" className="opacity-100" stroke="currentColor" strokeWidth="4" />
</svg>
{message}
</Card>
);
}
export function SegmentedTabs<T extends string>({
tabs,
value,
onChange,
}: {
tabs: Array<{ value: T; label: string; icon?: LucideIcon }>;
value: T;
onChange: (value: T) => void;
}) {
return (
<div className="sticky top-0 z-20 -mx-1 bg-stone-50/95 px-1 pb-2 pt-1 backdrop-blur-sm sm:-mx-2 sm:px-2">
<Surface className="p-2">
<div className={cn('grid gap-2', tabs.length === 2 ? 'grid-cols-1 sm:grid-cols-2' : 'grid-cols-1 sm:grid-cols-3')}>
{tabs.map((tab) => {
const Icon = tab.icon;
const isActive = tab.value === value;
return (
<button
key={tab.value}
type="button"
onClick={() => onChange(tab.value)}
className={cn(
'flex items-center justify-center gap-2 rounded-2xl px-4 py-3 text-sm font-semibold transition',
isActive ? 'bg-stone-900 text-white shadow-sm' : 'text-stone-600 hover:bg-stone-50 hover:text-stone-900',
)}
>
{Icon ? <Icon className="h-4 w-4" /> : null}
{tab.label}
</button>
);
})}
</div>
</Surface>
</div>
);
}
export function StatCard({
title,
value,
icon: Icon,
}: {
title: string;
value: ReactNode;
icon: LucideIcon;
}) {
return (
<Card className="p-6">
<div className="flex items-center gap-4">
<div className="rounded-xl bg-stone-100 p-3 text-emerald-700">
<Icon className="h-5 w-5" />
</div>
<div>
<p className="text-sm font-medium text-stone-500">{title}</p>
<p className="text-2xl font-semibold tracking-tight text-stone-950">{value}</p>
</div>
</div>
</Card>
);
}
+18
View File
@@ -0,0 +1,18 @@
@import "tailwindcss";
@layer base {
html {
color-scheme: light;
}
body {
margin: 0;
background: rgb(250 250 249);
color: rgb(28 25 23);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
}
+46
View File
@@ -0,0 +1,46 @@
import type {
AccountPageData,
BillingCheckoutSessionResponse,
BillingDebugData,
BillingPortalSessionResponse,
UpdateAccountProfileRequest,
} from '@/shared/types';
import { apiRequest } from './api';
export async function getAccountPageData() {
const response = await apiRequest<{ account: AccountPageData }>('/account/me');
return response.account;
}
export async function updateAccountProfile(payload: UpdateAccountProfileRequest) {
const response = await apiRequest<{ account: AccountPageData }>('/account/me', {
method: 'PATCH',
body: JSON.stringify(payload),
});
return response.account;
}
export async function createSubscriptionCheckout(planCode: string) {
return apiRequest<BillingCheckoutSessionResponse>('/billing/checkout/subscription', {
method: 'POST',
body: JSON.stringify({ planCode }),
});
}
export async function createAddonCheckout(addonCode: string) {
return apiRequest<BillingCheckoutSessionResponse>('/billing/checkout/addon', {
method: 'POST',
body: JSON.stringify({ addonCode }),
});
}
export async function createBillingPortalSession() {
return apiRequest<BillingPortalSessionResponse>('/billing/portal', {
method: 'POST',
});
}
export async function getBillingDebugData() {
return apiRequest<BillingDebugData>('/billing/debug');
}
+12
View File
@@ -0,0 +1,12 @@
import type { AnalyticsEventInput } from '@/shared/analytics/events';
import { apiRequest } from './api';
export function sendAnalyticsEvent(event: Omit<AnalyticsEventInput, 'eventSource'> & { eventSource?: AnalyticsEventInput['eventSource'] }) {
void apiRequest<{ ok: boolean }>('/analytics/events', {
method: 'POST',
body: JSON.stringify({
...event,
eventSource: event.eventSource ?? 'web_app',
}),
}).catch(() => undefined);
}
+72
View File
@@ -0,0 +1,72 @@
function isLoopbackHostname(hostname: string) {
return hostname === 'localhost' || hostname === '127.0.0.1';
}
function normalizeBaseUrl(baseUrl: string) {
return baseUrl.replace(/\/+$/, '');
}
function resolveApiBaseUrl() {
const configuredBaseUrl = (import.meta.env.VITE_API_BASE_URL ?? '').trim();
if (typeof window === 'undefined') {
return normalizeBaseUrl(configuredBaseUrl);
}
const fallbackBaseUrl = `${window.location.protocol}//${window.location.hostname}:4000/api`;
if (!configuredBaseUrl) {
return fallbackBaseUrl;
}
try {
const configuredUrl = new URL(configuredBaseUrl);
if (isLoopbackHostname(configuredUrl.hostname) && !isLoopbackHostname(window.location.hostname)) {
configuredUrl.hostname = window.location.hostname;
return normalizeBaseUrl(configuredUrl.toString());
}
return normalizeBaseUrl(configuredUrl.toString());
} catch {
return normalizeBaseUrl(configuredBaseUrl);
}
}
const apiBaseUrl = resolveApiBaseUrl();
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.');
}
let response: Response;
try {
response = await fetch(`${apiBaseUrl}${path}`, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...(init?.headers ?? {}),
},
...init,
});
} catch (error) {
throw new Error(
`Failed to reach the local API at ${apiBaseUrl}. Check that the API server is running and that VITE_API_BASE_URL matches the host you opened in the browser.`,
{ cause: error },
);
}
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;
}
+59
View File
@@ -0,0 +1,59 @@
import type {
AdminBootstrapClaimRequest,
AdminBootstrapClaimResponse,
AdminBootstrapStatusResponse,
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(sessionId?: string) {
await apiRequest<{ success: boolean }>('/auth/logout', {
method: 'POST',
body: JSON.stringify(sessionId ? { sessionId } : {}),
});
}
export async function getAdminBootstrapStatus(): Promise<AdminBootstrapStatusResponse> {
return apiRequest<AdminBootstrapStatusResponse>('/admin/bootstrap/status');
}
export async function claimAdminBootstrap(payload: AdminBootstrapClaimRequest): Promise<SessionUser> {
const response = await apiRequest<AdminBootstrapClaimResponse>('/admin/bootstrap/claim', {
method: 'POST',
body: JSON.stringify(payload),
});
return response.user;
}
+182
View File
@@ -0,0 +1,182 @@
import type { ActivePlanCode, BillingInterval, PlanCode } from '@/shared/billing/plans';
import { getPlanByCode, getPlanVariant } from '@/shared/billing/plans';
import type { AccountBillingStatus, BillingUsageResourceSummary } from '@/shared/types';
export type UsageWarningState = 'healthy' | 'warning' | 'critical' | 'unavailable';
export function formatPlanPrice(priceCents: number | null, currencyCode: string) {
if (priceCents === null) {
return 'Custom';
}
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currencyCode,
maximumFractionDigits: 0,
}).format(priceCents / 100);
}
export function formatPlanPeriod(billingInterval: BillingInterval, contactSalesRequired: boolean) {
if (contactSalesRequired || billingInterval === 'custom') {
return 'pricing';
}
return billingInterval === 'annual' ? '/year' : '/month';
}
export function formatBillingIntervalLabel(billingInterval: BillingInterval | null) {
if (!billingInterval) {
return 'Not scheduled';
}
switch (billingInterval) {
case 'monthly':
return 'Monthly';
case 'annual':
return 'Annual';
case 'custom':
return 'Custom';
}
}
export function formatBillingStatusLabel(status: AccountBillingStatus) {
switch (status) {
case 'active':
return 'Active';
case 'past_due':
return 'Past due';
case 'inactive':
return 'Inactive';
case 'canceled':
return 'Canceled';
case 'not_configured':
return 'Bootstrap';
}
}
export function getBillingStatusBadgeVariant(status: AccountBillingStatus) {
switch (status) {
case 'active':
return 'success' as const;
case 'past_due':
return 'warning' as const;
case 'inactive':
case 'canceled':
return 'danger' as const;
case 'not_configured':
return 'info' as const;
}
}
export function formatUsageResourceName(resource: BillingUsageResourceSummary['resource']) {
switch (resource) {
case 'research_credits':
return 'Research credits';
case 'exports':
return 'Exports';
case 'enrichments':
return 'Enrichments';
case 'api_requests':
return 'API requests';
}
}
export function formatQuantity(value: number | null) {
if (value === null) {
return 'Custom';
}
return new Intl.NumberFormat('en-US').format(value);
}
export function getUsageWarningState(summary: BillingUsageResourceSummary): UsageWarningState {
if (summary.availability === 'not_available') {
return 'unavailable';
}
if (summary.included === null || summary.remaining === null || summary.included <= 0) {
return 'healthy';
}
const remainingRatio = summary.remaining / summary.included;
if (summary.remaining === 0 || remainingRatio <= 0.1) {
return 'critical';
}
if (remainingRatio <= 0.2) {
return 'warning';
}
return 'healthy';
}
export function getUsageWarningMessage(summary: BillingUsageResourceSummary) {
const warningState = getUsageWarningState(summary);
const resourceName = formatUsageResourceName(summary.resource);
switch (warningState) {
case 'unavailable':
return `${resourceName} are not included on this plan.`;
case 'critical':
return `You are close to exhausting your ${resourceName.toLowerCase()}.`;
case 'warning':
return `${resourceName} are running low for this period.`;
case 'healthy':
return null;
}
}
export function getUsageProgressPercent(summary: BillingUsageResourceSummary) {
if (summary.included === null || summary.included <= 0) {
return null;
}
const consumedRatio = summary.consumed / summary.included;
return Math.max(0, Math.min(consumedRatio * 100, 100));
}
export function getUsageWarningBarClass(summary: BillingUsageResourceSummary) {
switch (getUsageWarningState(summary)) {
case 'critical':
return 'bg-red-500';
case 'warning':
return 'bg-amber-500';
case 'unavailable':
return 'bg-stone-300';
case 'healthy':
return 'bg-emerald-500';
}
}
export function getSuggestedUpgradePlanCode(planCode: PlanCode | null, billingInterval: BillingInterval | null) {
if (!planCode) {
return 'starter_monthly' as const;
}
const plan = getPlanByCode(planCode);
if (!plan) {
return null;
}
const targetInterval = billingInterval === 'annual' ? 'annual' : 'monthly';
switch (plan.planFamily) {
case 'starter':
return getPlanVariant('growth', targetInterval)?.code ?? null;
case 'growth':
return getPlanVariant('pro', targetInterval)?.code ?? null;
case 'pro':
return 'enterprise_custom';
case 'enterprise':
return null;
}
}
export function formatDateLabel(value: string | null) {
if (!value) {
return 'Not set';
}
return new Date(value).toLocaleDateString();
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+97
View File
@@ -0,0 +1,97 @@
import { apiRequest } from './api';
import type { Business, SearchJob } from '../types';
import type {
CreateDeepResearchBatchRequest,
DeepResearchBatchDetail,
DeepResearchBatchSummary,
DeepResearchPreview,
DeepResearchPreviewRequest,
} from '@/shared/types';
export type SearchJobResultLink = {
businessId: string;
searchJobId: string;
};
export type RunSearchPayload = {
name?: string;
location: string;
radiusKm: number;
businessType: string;
keywords?: string;
lat?: number;
lng?: number;
};
export type RunSearchResponse = {
job: SearchJob;
totalResults: number;
};
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;
}
export async function listBusinesses(_userId?: string): Promise<Business[]> {
const response = await apiRequest<{ businesses: Business[] }>('/businesses');
return response.businesses;
}
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 [];
}
const response = await apiRequest<{ businesses: Business[] }>(`/businesses?jobIds=${encodeURIComponent(jobIds.join(','))}`);
return response.businesses;
}
export async function runSearch(payload: RunSearchPayload): Promise<RunSearchResponse> {
return apiRequest<RunSearchResponse>('/search-jobs', {
method: 'POST',
body: JSON.stringify(payload),
});
}
export async function previewDeepResearch(payload: DeepResearchPreviewRequest): Promise<DeepResearchPreview> {
const response = await apiRequest<{ preview: DeepResearchPreview }>('/deep-research/preview', {
method: 'POST',
body: JSON.stringify(payload),
});
return response.preview;
}
export async function createDeepResearchBatch(payload: CreateDeepResearchBatchRequest): Promise<DeepResearchBatchDetail> {
const response = await apiRequest<{ batch: DeepResearchBatchDetail }>('/deep-research/batches', {
method: 'POST',
body: JSON.stringify(payload),
});
return response.batch;
}
export async function listDeepResearchBatches(): Promise<DeepResearchBatchSummary[]> {
const response = await apiRequest<{ batches: DeepResearchBatchSummary[] }>('/deep-research/batches');
return response.batches;
}
export async function getDeepResearchBatch(batchId: string): Promise<DeepResearchBatchDetail> {
const response = await apiRequest<{ batch: DeepResearchBatchDetail }>(`/deep-research/batches/${batchId}`);
return response.batch;
}
+48
View File
@@ -0,0 +1,48 @@
type CleanMapOptions = Pick<google.maps.MapOptions, 'clickableIcons' | 'streetViewControl' | 'fullscreenControl' | 'mapTypeControl' | 'styles'>;
export const cleanMapOptions: CleanMapOptions = {
clickableIcons: false,
streetViewControl: false,
fullscreenControl: false,
mapTypeControl: false,
styles: [
{
featureType: 'poi',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'transit',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'landscape',
elementType: 'labels',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'administrative.neighborhood',
elementType: 'labels',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'administrative.land_parcel',
elementType: 'labels',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'road.highway',
elementType: 'labels',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'road.arterial',
elementType: 'labels.icon',
stylers: [{ visibility: 'off' }],
},
{
featureType: 'road.local',
elementType: 'labels.icon',
stylers: [{ visibility: 'off' }],
},
],
};
+10
View File
@@ -0,0 +1,10 @@
import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
+56
View File
@@ -0,0 +1,56 @@
export type SearchJobStatus = 'pending' | 'running' | 'completed' | 'failed' | 'stopped';
export interface SearchJob {
id: string;
name: string;
city?: string;
address?: string;
postalCode?: string;
radiusKm: number;
businessType: string;
keywords?: string;
status: SearchJobStatus;
totalResults: number;
startedAt?: string;
completedAt?: string;
createdAt: string;
updatedAt: string;
userId: string;
}
export interface Business {
id: string;
externalSourceId?: string;
source: string;
name: string;
address?: string;
city?: string;
stateProvince?: string;
postalCode?: string;
country?: string;
phone?: string;
website?: string;
rating?: number;
reviewCount?: number;
category?: string;
hoursJson?: string;
latitude?: number;
longitude?: number;
generalInfo?: string;
metadataJson?: string;
firstSeenAt?: string;
lastSeenAt?: string;
createdAt: string;
updatedAt: string;
userId: string;
}
export interface SearchJobResult {
id: string;
searchJobId: string;
businessId: string;
matchedKeywords?: string[];
rank?: number;
capturedAt: string;
userId: string;
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string;
readonly VITE_GOOGLE_MAPS_PLATFORM_KEY: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+25
View File
@@ -0,0 +1,25 @@
import tailwindcss from '@tailwindcss/vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import {defineConfig} from 'vite';
export default defineConfig({
root: path.resolve(__dirname),
envDir: path.resolve(__dirname, '..'),
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': path.resolve(__dirname, '..'),
},
},
server: {
allowedHosts: ['project-1.duramente.com'],
hmr: process.env.DISABLE_HMR !== 'true',
port: 3000,
strictPort: true,
host: '0.0.0.0',
},
build: {
outDir: '../dist',
},
});