Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

chore(tooling): adopt Prettier + add CI (format check & typecheck) (#80)

Gökhan Geyik4d4af69a6098
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
new file mode 100644
index 000000000..750d97858
--- /dev/null
+++ b/.git-blame-ignore-revs
@@ -0,0 +1,7 @@
+# Revisions to ignore in `git blame` (bulk, mechanical changes).
+# Enable locally with:
+# git config blame.ignoreRevsFile .git-blame-ignore-revs
+# (GitHub honors this file automatically.)
+
+# style: apply Prettier formatting to web/src
+5f16f36a64b5ae14aef0caeb723ab05d577ae567
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 000000000..3c55e9161
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,26 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+jobs:
+ web:
+ name: web — format & typecheck
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: web
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: yarn
+ cache-dependency-path: web/yarn.lock
+ - run: yarn install --frozen-lockfile
+ - name: Prettier format check
+ run: yarn format:check
+ - name: TypeScript typecheck
+ run: yarn typecheck
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3ebcbaf33..e0963a08c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -188,6 +188,7 @@ fix(web): correct chart rendering on mobile
- TypeScript with strict mode enabled
- ESLint with `eslint-config-next` (core-web-vitals + typescript)
- Run `yarn lint` before submitting
+- **Prettier owns formatting.** Run `yarn format` before submitting (or enable format-on-save with the repo's Prettier config). CI runs `yarn format:check`, so unformatted code will fail the check — don't hand-format or reformat unrelated lines.
### Server (`server/`)
diff --git a/web/.prettierignore b/web/.prettierignore
new file mode 100644
index 000000000..24f8e02d9
--- /dev/null
+++ b/web/.prettierignore
@@ -0,0 +1,7 @@
+.next/
+out/
+build/
+node_modules/
+next-env.d.ts
+# Generated by `supabase gen types` — don't reformat
+src/types/supabase.ts
diff --git a/web/.prettierrc.json b/web/.prettierrc.json
new file mode 100644
index 000000000..2c1db6c3f
--- /dev/null
+++ b/web/.prettierrc.json
@@ -0,0 +1,7 @@
+{
+ "singleQuote": true,
+ "printWidth": 100,
+ "trailingComma": "all",
+ "semi": true,
+ "tabWidth": 2
+}
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index 05e726d1b..213ed9028 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -1,10 +1,14 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
+import prettier from "eslint-config-prettier";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
+ // Disable ESLint rules that conflict with Prettier — keep ESLint for code
+ // quality and let Prettier own formatting. Must come last.
+ prettier,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
diff --git a/web/package.json b/web/package.json
index c3c615d86..579d63f2d 100644
--- a/web/package.json
+++ b/web/package.json
@@ -14,7 +14,9 @@
"build": "next build",
"start": "next start",
"lint": "eslint",
- "typecheck": "tsc --noEmit"
+ "typecheck": "tsc --noEmit",
+ "format": "prettier --write \"src/**/*.{ts,tsx}\"",
+ "format:check": "prettier --check \"src/**/*.{ts,tsx}\""
},
"dependencies": {
"@base-ui/react": "^1.2.0",
@@ -57,6 +59,8 @@
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.6",
+ "eslint-config-prettier": "^10.1.8",
+ "prettier": "^3.8.3",
"tailwindcss": "^4",
"typescript": "^5"
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx
index 6e63076be..bca5daa42 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx
@@ -1,17 +1,17 @@
-"use client";
+'use client';
-import { use } from "react";
-import { usePathname, Link } from "@/i18n/navigation";
-import { useBrandStore } from "@/stores/use-brand-store";
-import { Button } from "@/components/ui/button";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import { cn } from "@/lib/utils";
-import { ArrowLeft, MessageSquareText, Settings, Tag } from "lucide-react";
+import { use } from 'react';
+import { usePathname, Link } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { Button } from '@/components/ui/button';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { cn } from '@/lib/utils';
+import { ArrowLeft, MessageSquareText, Settings, Tag } from 'lucide-react';
const SUB_NAV = [
- { href: "topics", label: "Topics", icon: Tag },
- { href: "prompts", label: "Prompts", icon: MessageSquareText },
- { href: "settings", label: "Settings", icon: Settings },
+ { href: 'topics', label: 'Topics', icon: Tag },
+ { href: 'prompts', label: 'Prompts', icon: MessageSquareText },
+ { href: 'settings', label: 'Settings', icon: Settings },
] as const;
export default function BrandDetailLayout({
@@ -29,12 +29,12 @@ export default function BrandDetailLayout({
const initials = brand
? brand.name
- .split(" ")
+ .split(' ')
.map((w) => w[0])
- .join("")
+ .join('')
.toUpperCase()
.slice(0, 2)
- : "?";
+ : '?';
return (
<div className="space-y-6">
@@ -48,11 +48,7 @@ export default function BrandDetailLayout({
{brand && (
<div className="flex items-center gap-3">
<Avatar className="h-9 w-9 rounded-lg bg-zinc-50 dark:bg-zinc-100">
- <AvatarImage
- src={brand.logoUrl}
- alt={brand.name}
- className="object-contain p-1"
- />
+ <AvatarImage src={brand.logoUrl} alt={brand.name} className="object-contain p-1" />
<AvatarFallback className="rounded-lg bg-primary/10 text-primary text-sm font-semibold">
{initials}
</AvatarFallback>
@@ -60,7 +56,7 @@ export default function BrandDetailLayout({
<div>
<h1 className="text-xl font-bold tracking-tight">{brand.name}</h1>
<p className="text-xs text-muted-foreground">
- {brand.domains.find((d) => d.isPrimary)?.domain ?? ""}
+ {brand.domains.find((d) => d.isPrimary)?.domain ?? ''}
</p>
</div>
</div>
@@ -77,10 +73,10 @@ export default function BrandDetailLayout({
<Link key={item.href} href={fullHref}>
<span
className={cn(
- "inline-flex items-center gap-2 border-b-2 px-4 py-2 text-sm font-medium transition-colors",
+ 'inline-flex items-center gap-2 border-b-2 px-4 py-2 text-sm font-medium transition-colors',
isActive
- ? "border-primary text-primary"
- : "border-transparent text-muted-foreground hover:text-foreground"
+ ? 'border-primary text-primary'
+ : 'border-transparent text-muted-foreground hover:text-foreground',
)}
>
<item.icon className="h-4 w-4" />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
index 131e8281c..76888b270 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
@@ -1,25 +1,37 @@
-"use client";
-
-import { useEffect, useState, useCallback, useMemo } from "react";
-import { useParams } from "next/navigation";
-import { createClient } from "@/lib/supabase/client";
-import { getPromptSets, savePromptSet, addPromptToSet, updatePrompt, deletePrompt } from "@/lib/actions/prompt";
-import { getBrandById } from "@/lib/actions/brand";
-import { getTopics } from "@/lib/actions/topic";
-import { PromptSuggestionCard } from "@/components/dashboard/prompt-suggestion-card";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Input } from "@/components/ui/input";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { toast } from "sonner";
-import { Badge } from "@/components/ui/badge";
-import { Loader2, Plus, Sparkles, Save, X, Play, Search } from "lucide-react";
-import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from "@/config/prompt-options";
-import { usePlanContext } from "@/components/providers/plan-provider";
-import { PLANS } from "@/config/plans";
-import { saveTrackingJob } from "@/lib/tracking-job-store";
-import { useRouter } from "@/i18n/navigation";
+'use client';
+
+import { useEffect, useState, useCallback, useMemo } from 'react';
+import { useParams } from 'next/navigation';
+import { createClient } from '@/lib/supabase/client';
+import {
+ getPromptSets,
+ savePromptSet,
+ addPromptToSet,
+ updatePrompt,
+ deletePrompt,
+} from '@/lib/actions/prompt';
+import { getBrandById } from '@/lib/actions/brand';
+import { getTopics } from '@/lib/actions/topic';
+import { PromptSuggestionCard } from '@/components/dashboard/prompt-suggestion-card';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { toast } from 'sonner';
+import { Badge } from '@/components/ui/badge';
+import { Loader2, Plus, Sparkles, Save, X, Play, Search } from 'lucide-react';
+import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';
+import { usePlanContext } from '@/components/providers/plan-provider';
+import { PLANS } from '@/config/plans';
+import { saveTrackingJob } from '@/lib/tracking-job-store';
+import { useRouter } from '@/i18n/navigation';
import {
Dialog,
DialogContent,
@@ -27,9 +39,9 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/components/ui/dialog";
-import { Checkbox } from "@/components/ui/checkbox";
-import type { Brand, Prompt, PromptSet, Topic } from "@/types";
+} from '@/components/ui/dialog';
+import { Checkbox } from '@/components/ui/checkbox';
+import type { Brand, Prompt, PromptSet, Topic } from '@/types';
interface UnanalyzedPrompt {
id: string;
@@ -37,7 +49,7 @@ interface UnanalyzedPrompt {
category: string;
}
-const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:80";
+const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
interface SuggestedPrompt {
text: string;
@@ -57,8 +69,8 @@ export default function PromptsPage() {
const [isLoading, setIsLoading] = useState(true);
const [isGenerating, setIsGenerating] = useState(false);
const [isSaving, setIsSaving] = useState(false);
- const [manualText, setManualText] = useState("");
- const [manualCategory, setManualCategory] = useState("");
+ const [manualText, setManualText] = useState('');
+ const [manualCategory, setManualCategory] = useState('');
const [generateTopics, setGenerateTopics] = useState<string[] | null>(null);
const { planId } = usePlanContext();
const allowedScraperIds = useMemo(() => {
@@ -96,12 +108,14 @@ export default function PromptsPage() {
const fetchUnanalyzed = useCallback(async () => {
try {
const supabase = createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) return;
const resp = await fetch(`${AEO_SERVER_URL}/api/tracking/unanalyzed/${brandId}`, {
headers: {
Authorization: `Bearer ${session.access_token}`,
- "ngrok-skip-browser-warning": "1",
+ 'ngrok-skip-browser-warning': '1',
},
});
if (resp.ok) {
@@ -123,12 +137,10 @@ export default function PromptsPage() {
if (topicsData.length > 0 && !manualCategory) {
setManualCategory(topicsData[0].name);
}
- setGenerateTopics((prev) =>
- prev === null ? topicsData.map((t) => t.name) : prev,
- );
+ setGenerateTopics((prev) => (prev === null ? topicsData.map((t) => t.name) : prev));
setPromptSets(sets);
} catch {
- toast.error("Failed to load data");
+ toast.error('Failed to load data');
} finally {
setIsLoading(false);
}
@@ -142,7 +154,7 @@ export default function PromptsPage() {
const handleGenerate = async () => {
if (!brand) return;
if (!generateTopics || generateTopics.length === 0) {
- toast.error("Select at least one topic to generate prompts");
+ toast.error('Select at least one topic to generate prompts');
return;
}
@@ -151,13 +163,15 @@ export default function PromptsPage() {
try {
const supabase = createClient();
- const { data: { session } } = await supabase.auth.getSession();
- if (!session) throw new Error("Not authenticated");
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) throw new Error('Not authenticated');
const response = await fetch(`${AEO_SERVER_URL}/api/prompts/from-topics`, {
- method: "POST",
+ method: 'POST',
headers: {
- "Content-Type": "application/json",
+ 'Content-Type': 'application/json',
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({
@@ -165,7 +179,7 @@ export default function PromptsPage() {
industry: brand.industry || undefined,
description: brand.description || undefined,
topics: generateTopics,
- language: brand.language || "en",
+ language: brand.language || 'en',
}),
});
@@ -184,7 +198,7 @@ export default function PromptsPage() {
setSuggestions(allPrompts);
toast.success(`${allPrompts.length} prompt suggestions generated!`);
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to generate suggestions");
+ toast.error(err instanceof Error ? err.message : 'Failed to generate suggestions');
} finally {
setIsGenerating(false);
}
@@ -193,7 +207,7 @@ export default function PromptsPage() {
const handleSaveSuggestions = async () => {
const activePrompts = suggestions.filter((s) => s.isActive);
if (activePrompts.length === 0) {
- toast.error("Select at least one prompt to save");
+ toast.error('Select at least one prompt to save');
return;
}
@@ -207,7 +221,7 @@ export default function PromptsPage() {
if (!targetSetId) {
const newSet = await savePromptSet({
brandId,
- name: "Prompts",
+ name: 'Prompts',
prompts: activePrompts.map((p) => ({
text: p.text,
category: p.category,
@@ -225,8 +239,8 @@ export default function PromptsPage() {
category: p.category,
platforms: defaultPlatforms,
models: defaultModels,
- })
- )
+ }),
+ ),
);
}
@@ -234,7 +248,7 @@ export default function PromptsPage() {
toast.success(`Saved ${activePrompts.length} prompts`);
await loadData();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to save prompts");
+ toast.error(err instanceof Error ? err.message : 'Failed to save prompts');
} finally {
setIsSaving(false);
}
@@ -267,13 +281,13 @@ export default function PromptsPage() {
});
}
- setManualText("");
+ setManualText('');
setManualModels(allowedModelIds);
setManualScrapers(allowedScraperIds);
- toast.success("Prompt added");
+ toast.success('Prompt added');
await loadData();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to add prompt");
+ toast.error(err instanceof Error ? err.message : 'Failed to add prompt');
} finally {
setIsAddingManual(false);
}
@@ -283,9 +297,7 @@ export default function PromptsPage() {
setPromptSets((prev) =>
prev.map((set) => ({
...set,
- prompts: set.prompts.map((p) =>
- p.id === promptId ? { ...p, ...patch } : p,
- ),
+ prompts: set.prompts.map((p) => (p.id === promptId ? { ...p, ...patch } : p)),
})),
);
}, []);
@@ -299,77 +311,97 @@ export default function PromptsPage() {
);
}, []);
- const handleTogglePrompt = useCallback(async (prompt: Prompt) => {
- updatePromptLocal(prompt.id, { isActive: !prompt.isActive });
- try {
- await updatePrompt(prompt.id, { isActive: !prompt.isActive });
- } catch {
- updatePromptLocal(prompt.id, { isActive: prompt.isActive });
- toast.error("Failed to update prompt");
- }
- }, [updatePromptLocal]);
+ const handleTogglePrompt = useCallback(
+ async (prompt: Prompt) => {
+ updatePromptLocal(prompt.id, { isActive: !prompt.isActive });
+ try {
+ await updatePrompt(prompt.id, { isActive: !prompt.isActive });
+ } catch {
+ updatePromptLocal(prompt.id, { isActive: prompt.isActive });
+ toast.error('Failed to update prompt');
+ }
+ },
+ [updatePromptLocal],
+ );
- const handleEditPrompt = useCallback(async (promptId: string, text: string) => {
- updatePromptLocal(promptId, { text });
- try {
- await updatePrompt(promptId, { text });
- } catch {
- toast.error("Failed to update prompt");
- await loadData();
- }
- }, [updatePromptLocal, loadData]);
+ const handleEditPrompt = useCallback(
+ async (promptId: string, text: string) => {
+ updatePromptLocal(promptId, { text });
+ try {
+ await updatePrompt(promptId, { text });
+ } catch {
+ toast.error('Failed to update prompt');
+ await loadData();
+ }
+ },
+ [updatePromptLocal, loadData],
+ );
- const handleCategoryChange = useCallback(async (promptId: string, category: string) => {
- updatePromptLocal(promptId, { category });
- try {
- await updatePrompt(promptId, { category });
- } catch {
- toast.error("Failed to update topic");
- await loadData();
- }
- }, [updatePromptLocal, loadData]);
+ const handleCategoryChange = useCallback(
+ async (promptId: string, category: string) => {
+ updatePromptLocal(promptId, { category });
+ try {
+ await updatePrompt(promptId, { category });
+ } catch {
+ toast.error('Failed to update topic');
+ await loadData();
+ }
+ },
+ [updatePromptLocal, loadData],
+ );
- const handleModelsChange = useCallback(async (promptId: string, models: string[]) => {
- updatePromptLocal(promptId, { models });
- try {
- await updatePrompt(promptId, { models });
- } catch {
- toast.error("Failed to update models");
- await loadData();
- }
- }, [updatePromptLocal, loadData]);
+ const handleModelsChange = useCallback(
+ async (promptId: string, models: string[]) => {
+ updatePromptLocal(promptId, { models });
+ try {
+ await updatePrompt(promptId, { models });
+ } catch {
+ toast.error('Failed to update models');
+ await loadData();
+ }
+ },
+ [updatePromptLocal, loadData],
+ );
- const handlePlatformsChange = useCallback(async (promptId: string, platforms: string[]) => {
- updatePromptLocal(promptId, { platforms: platforms as Prompt["platforms"] });
- try {
- await updatePrompt(promptId, { platforms });
- } catch {
- toast.error("Failed to update platforms");
- await loadData();
- }
- }, [updatePromptLocal, loadData]);
+ const handlePlatformsChange = useCallback(
+ async (promptId: string, platforms: string[]) => {
+ updatePromptLocal(promptId, { platforms: platforms as Prompt['platforms'] });
+ try {
+ await updatePrompt(promptId, { platforms });
+ } catch {
+ toast.error('Failed to update platforms');
+ await loadData();
+ }
+ },
+ [updatePromptLocal, loadData],
+ );
- const handleDeletePrompt = useCallback(async (promptId: string) => {
- removePromptLocal(promptId);
- try {
- await deletePrompt(promptId);
- } catch {
- toast.error("Failed to delete prompt");
- await loadData();
- }
- }, [removePromptLocal, loadData]);
+ const handleDeletePrompt = useCallback(
+ async (promptId: string) => {
+ removePromptLocal(promptId);
+ try {
+ await deletePrompt(promptId);
+ } catch {
+ toast.error('Failed to delete prompt');
+ await loadData();
+ }
+ },
+ [removePromptLocal, loadData],
+ );
const openAnalyzeDialog = useCallback(async () => {
setAnalyzeDialogOpen(true);
setIsLoadingUnanalyzed(true);
try {
const supabase = createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) return;
const resp = await fetch(`${AEO_SERVER_URL}/api/tracking/unanalyzed/${brandId}`, {
headers: {
Authorization: `Bearer ${session.access_token}`,
- "ngrok-skip-browser-warning": "1",
+ 'ngrok-skip-browser-warning': '1',
},
});
if (resp.ok) {
@@ -379,7 +411,7 @@ export default function PromptsPage() {
setSelectedAnalyzeIds(new Set(prompts.map((p) => p.id)));
}
} catch {
- toast.error("Failed to load unanalyzed prompts");
+ toast.error('Failed to load unanalyzed prompts');
} finally {
setIsLoadingUnanalyzed(false);
}
@@ -390,15 +422,17 @@ export default function PromptsPage() {
setIsAnalyzing(true);
try {
const supabase = createClient();
- const { data: { session } } = await supabase.auth.getSession();
- if (!session) throw new Error("Not authenticated");
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) throw new Error('Not authenticated');
const resp = await fetch(`${AEO_SERVER_URL}/api/tracking/analyze-new`, {
- method: "POST",
+ method: 'POST',
headers: {
- "Content-Type": "application/json",
+ 'Content-Type': 'application/json',
Authorization: `Bearer ${session.access_token}`,
- "ngrok-skip-browser-warning": "1",
+ 'ngrok-skip-browser-warning': '1',
},
body: JSON.stringify({ brandId, promptIds: Array.from(selectedAnalyzeIds) }),
});
@@ -406,21 +440,21 @@ export default function PromptsPage() {
const data = await resp.json();
if (!resp.ok) {
- toast.error(data.message || "Failed to start analysis");
+ toast.error(data.message || 'Failed to start analysis');
return;
}
if (data.newCount === 0) {
- toast.info(data.message || "All prompts already analyzed");
+ toast.info(data.message || 'All prompts already analyzed');
} else {
toast.success(data.message || `Analyzing ${data.newCount} new prompts`);
setUnanalyzedPrompts([]);
setAnalyzeDialogOpen(false);
saveTrackingJob({ jobId: data.jobId, brandId, startedAt: Date.now() });
- router.push("/dashboard/insights");
+ router.push('/dashboard/insights');
}
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to start analysis");
+ toast.error(err instanceof Error ? err.message : 'Failed to start analysis');
} finally {
setIsAnalyzing(false);
}
@@ -462,14 +496,16 @@ export default function PromptsPage() {
value={manualText}
onChange={(e) => setManualText(e.target.value)}
onKeyDown={(e) => {
- if (e.key === "Enter" && manualText.trim()) handleAddManualPrompt();
+ if (e.key === 'Enter' && manualText.trim()) handleAddManualPrompt();
}}
/>
<div className="space-y-3">
{/* Topic */}
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topic</label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ Topic
+ </label>
{topics.length > 0 ? (
<Select value={manualCategory} onValueChange={(v) => v && setManualCategory(v)}>
<SelectTrigger className="w-full">
@@ -477,7 +513,9 @@ export default function PromptsPage() {
</SelectTrigger>
<SelectContent>
{topics.map((topic) => (
- <SelectItem key={topic.id} value={topic.name}>{topic.name}</SelectItem>
+ <SelectItem key={topic.id} value={topic.name}>
+ {topic.name}
+ </SelectItem>
))}
</SelectContent>
</Select>
@@ -490,14 +528,19 @@ export default function PromptsPage() {
{/* Platform & Models — combined select */}
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Platform & Models</label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ Platform & Models
+ </label>
<Select
value="__placeholder__"
onValueChange={(v) => {
- if (!v || v === "__placeholder__") return;
+ if (!v || v === '__placeholder__') return;
if (visibleModels.some((m) => m.id === v) && !manualModels.includes(v)) {
setManualModels((prev) => [...prev, v]);
- } else if (visibleScrapers.some((s) => s.id === v) && !manualScrapers.includes(v)) {
+ } else if (
+ visibleScrapers.some((s) => s.id === v) &&
+ !manualScrapers.includes(v)
+ ) {
setManualScrapers((prev) => [...prev, v]);
}
}}
@@ -506,7 +549,7 @@ export default function PromptsPage() {
<span className="truncate text-muted-foreground">
{manualModels.length + manualScrapers.length > 0
? `${manualModels.length + manualScrapers.length} selected`
- : "Select platform & models"}
+ : 'Select platform & models'}
</span>
</SelectTrigger>
<SelectContent>
@@ -517,12 +560,20 @@ export default function PromptsPage() {
if (scrapers.length === 0) return null;
return (
<div key={group.provider}>
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">{group.provider} (Scraper)</div>
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
+ {group.provider} (Scraper)
+ </div>
{scrapers.map((s) => (
- <SelectItem key={s.id} value={s.id} disabled={manualScrapers.includes(s.id)}>
+ <SelectItem
+ key={s.id}
+ value={s.id}
+ disabled={manualScrapers.includes(s.id)}
+ >
<div>
<div>{s.label}</div>
- <div className="text-[10px] text-muted-foreground font-mono">{s.id}</div>
+ <div className="text-[10px] text-muted-foreground font-mono">
+ {s.id}
+ </div>
</div>
</SelectItem>
))}
@@ -536,12 +587,20 @@ export default function PromptsPage() {
if (groupModels.length === 0) return null;
return (
<div key={group.provider}>
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">{group.provider} (API)</div>
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
+ {group.provider} (API)
+ </div>
{groupModels.map((m) => (
- <SelectItem key={m.id} value={m.id} disabled={manualModels.includes(m.id)}>
+ <SelectItem
+ key={m.id}
+ value={m.id}
+ disabled={manualModels.includes(m.id)}
+ >
<div>
<div>{m.label}</div>
- <div className="text-[10px] text-muted-foreground font-mono">{m.id}</div>
+ <div className="text-[10px] text-muted-foreground font-mono">
+ {m.id}
+ </div>
</div>
</SelectItem>
))}
@@ -557,7 +616,10 @@ export default function PromptsPage() {
return (
<Badge key={id} variant="outline" className="gap-1 text-xs">
{s?.label ?? id}
- <button type="button" onClick={() => setManualScrapers((p) => p.filter((i) => i !== id))}>
+ <button
+ type="button"
+ onClick={() => setManualScrapers((p) => p.filter((i) => i !== id))}
+ >
<X className="h-3 w-3" />
</button>
</Badge>
@@ -568,7 +630,10 @@ export default function PromptsPage() {
return (
<Badge key={id} variant="secondary" className="gap-1 text-xs">
{m?.label ?? id}
- <button type="button" onClick={() => setManualModels((p) => p.filter((i) => i !== id))}>
+ <button
+ type="button"
+ onClick={() => setManualModels((p) => p.filter((i) => i !== id))}
+ >
<X className="h-3 w-3" />
</button>
</Badge>
@@ -614,20 +679,22 @@ export default function PromptsPage() {
</p>
{topics.length > 0 ? (
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topics</label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ Topics
+ </label>
<div className="flex flex-wrap gap-1.5">
{topics.map((topic) => {
const selected = generateTopics?.includes(topic.name) ?? false;
return (
<Badge
key={topic.id}
- variant={selected ? "default" : "outline"}
+ variant={selected ? 'default' : 'outline'}
className="cursor-pointer select-none"
onClick={() =>
setGenerateTopics((prev) =>
selected
? (prev ?? []).filter((t) => t !== topic.name)
- : [...(prev ?? []), topic.name]
+ : [...(prev ?? []), topic.name],
)
}
>
@@ -638,7 +705,8 @@ export default function PromptsPage() {
</div>
{generateTopics && generateTopics.length > 0 && (
<p className="mt-1.5 text-xs text-muted-foreground">
- {generateTopics.length} topic{generateTopics.length !== 1 ? "s" : ""} selected — {generateTopics.length * 5} prompts will be generated
+ {generateTopics.length} topic{generateTopics.length !== 1 ? 's' : ''} selected
+ — {generateTopics.length * 5} prompts will be generated
</p>
)}
</div>
@@ -688,17 +756,11 @@ export default function PromptsPage() {
isActive={s.isActive}
onToggle={() =>
setSuggestions((prev) =>
- prev.map((p, idx) =>
- idx === i ? { ...p, isActive: !p.isActive } : p
- )
+ prev.map((p, idx) => (idx === i ? { ...p, isActive: !p.isActive } : p)),
)
}
onTextChange={(text) =>
- setSuggestions((prev) =>
- prev.map((p, idx) =>
- idx === i ? { ...p, text } : p
- )
- )
+ setSuggestions((prev) => prev.map((p, idx) => (idx === i ? { ...p, text } : p)))
}
mode="review"
/>
@@ -714,11 +776,7 @@ export default function PromptsPage() {
)}
Save Selected ({suggestions.filter((s) => s.isActive).length})
</Button>
- <Button
- variant="outline"
- onClick={handleGenerate}
- disabled={isGenerating}
- >
+ <Button variant="outline" onClick={handleGenerate} disabled={isGenerating}>
{isGenerating ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
@@ -738,12 +796,10 @@ export default function PromptsPage() {
{allPrompts.length > 0 && (
<div className="space-y-3">
<div className="flex items-center justify-between">
- <h2 className="text-lg font-semibold">
- All Prompts ({allPrompts.length})
- </h2>
+ <h2 className="text-lg font-semibold">All Prompts ({allPrompts.length})</h2>
<Button
size="sm"
- variant={unanalyzedPrompts.length > 0 ? "default" : "outline"}
+ variant={unanalyzedPrompts.length > 0 ? 'default' : 'outline'}
onClick={openAnalyzeDialog}
>
<Search className="mr-2 h-3.5 w-3.5" />
@@ -760,7 +816,7 @@ export default function PromptsPage() {
<PromptSuggestionCard
key={prompt.id}
text={prompt.text}
- category={prompt.category ?? ""}
+ category={prompt.category ?? ''}
isActive={prompt.isActive}
regions={prompt.regions}
models={prompt.models}
@@ -799,8 +855,8 @@ export default function PromptsPage() {
<DialogTitle>Analyze Prompts</DialogTitle>
<DialogDescription>
{unanalyzedPrompts.length > 0
- ? "Select which prompts to analyze with AI platforms."
- : "All prompts have already been analyzed."}
+ ? 'Select which prompts to analyze with AI platforms.'
+ : 'All prompts have already been analyzed.'}
</DialogDescription>
</DialogHeader>
@@ -825,7 +881,9 @@ export default function PromptsPage() {
}
}}
>
- {selectedAnalyzeIds.size === unanalyzedPrompts.length ? "Deselect All" : "Select All"}
+ {selectedAnalyzeIds.size === unanalyzedPrompts.length
+ ? 'Deselect All'
+ : 'Select All'}
</Button>
</div>
<div className="max-h-64 space-y-1.5 overflow-y-auto rounded-md border p-2">
@@ -869,10 +927,7 @@ export default function PromptsPage() {
)}
<DialogFooter>
- <Button
- variant="outline"
- onClick={() => setAnalyzeDialogOpen(false)}
- >
+ <Button variant="outline" onClick={() => setAnalyzeDialogOpen(false)}>
Cancel
</Button>
{unanalyzedPrompts.length > 0 && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
index 8dfcab474..219f543c0 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
@@ -1,57 +1,32 @@
-"use client";
-
-import { use, useState, useEffect, useCallback } from "react";
-import { useTranslations } from "next-intl";
-import { useRouter, Link } from "@/i18n/navigation";
-import { useBrandStore } from "@/stores/use-brand-store";
-import { updateBrand, deleteBrand } from "@/lib/actions/brand";
-import { syncDomains } from "@/lib/actions/brand-domain";
-import {
- getCompetitors,
- addCompetitor,
- deleteCompetitor,
-} from "@/lib/actions/competitor";
-import { getFaviconUrl } from "@/lib/favicon";
-import type { Competitor } from "@/types";
-import {
- INDUSTRIES,
- type Brand,
- type BrandDomain,
-} from "@/types";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
+'use client';
+
+import { use, useState, useEffect, useCallback } from 'react';
+import { useTranslations } from 'next-intl';
+import { useRouter, Link } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { updateBrand, deleteBrand } from '@/lib/actions/brand';
+import { syncDomains } from '@/lib/actions/brand-domain';
+import { getCompetitors, addCompetitor, deleteCompetitor } from '@/lib/actions/competitor';
+import { getFaviconUrl } from '@/lib/favicon';
+import type { Competitor } from '@/types';
+import { INDUSTRIES, type Brand, type BrandDomain } from '@/types';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
-} from "@/components/ui/select";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { toast } from "sonner";
-import {
- Check,
- Code,
- Copy,
- Globe,
- Loader2,
- Pencil,
- Plus,
- Save,
- Trash2,
- X,
-} from "lucide-react";
+} from '@/components/ui/select';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Separator } from '@/components/ui/separator';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { toast } from 'sonner';
+import { Check, Code, Copy, Globe, Loader2, Pencil, Plus, Save, Trash2, X } from 'lucide-react';
import {
Dialog,
DialogContent,
@@ -61,7 +36,7 @@ import {
DialogTitle,
DialogTrigger,
DialogClose,
-} from "@/components/ui/dialog";
+} from '@/components/ui/dialog';
interface PageProps {
params: Promise<{ id: string }>;
@@ -69,7 +44,7 @@ interface PageProps {
export default function BrandSettingsPage({ params }: PageProps) {
const { id } = use(params);
- const t = useTranslations("brands");
+ const t = useTranslations('brands');
const router = useRouter();
const { brands, updateBrand: updateBrandStore, removeBrand } = useBrandStore();
@@ -79,9 +54,7 @@ export default function BrandSettingsPage({ params }: PageProps) {
return (
<div className="flex flex-col items-center justify-center py-20 text-center">
<h2 className="text-lg font-semibold">Brand not found</h2>
- <p className="text-muted-foreground text-sm mt-1">
- This brand may have been deleted.
- </p>
+ <p className="text-muted-foreground text-sm mt-1">This brand may have been deleted.</p>
<Link href="/dashboard/brands" className="mt-4">
<Button variant="outline">Back to Brands</Button>
</Link>
@@ -93,27 +66,24 @@ export default function BrandSettingsPage({ params }: PageProps) {
<div className="space-y-6">
<Tabs defaultValue="general" className="space-y-4">
<TabsList>
- <TabsTrigger value="general">{t("settings.generalTab")}</TabsTrigger>
- <TabsTrigger value="domains">{t("settings.domainsTab")}</TabsTrigger>
+ <TabsTrigger value="general">{t('settings.generalTab')}</TabsTrigger>
+ <TabsTrigger value="domains">{t('settings.domainsTab')}</TabsTrigger>
<TabsTrigger value="tracking">Tracking</TabsTrigger>
<TabsTrigger value="competitors">Competitors</TabsTrigger>
- <TabsTrigger value="danger" className="text-destructive data-[state=active]:text-destructive">
- {t("settings.dangerTab")}
+ <TabsTrigger
+ value="danger"
+ className="text-destructive data-[state=active]:text-destructive"
+ >
+ {t('settings.dangerTab')}
</TabsTrigger>
</TabsList>
<TabsContent value="general">
- <GeneralTab
- brand={brand}
- onUpdate={(updated) => updateBrandStore(brand.id, updated)}
- />
+ <GeneralTab brand={brand} onUpdate={(updated) => updateBrandStore(brand.id, updated)} />
</TabsContent>
<TabsContent value="domains">
- <DomainsTab
- brand={brand}
- onUpdate={(updated) => updateBrandStore(brand.id, updated)}
- />
+ <DomainsTab brand={brand} onUpdate={(updated) => updateBrandStore(brand.id, updated)} />
</TabsContent>
<TabsContent value="tracking">
@@ -129,8 +99,8 @@ export default function BrandSettingsPage({ params }: PageProps) {
brand={brand}
onDelete={async () => {
removeBrand(brand.id);
- toast.success("Brand deleted.");
- router.push("/dashboard/brands");
+ toast.success('Brand deleted.');
+ router.push('/dashboard/brands');
}}
/>
</TabsContent>
@@ -148,10 +118,10 @@ function GeneralTab({
brand: Brand;
onUpdate: (updates: Partial<Brand>) => void;
}) {
- const t = useTranslations("brands");
+ const t = useTranslations('brands');
const [name, setName] = useState(brand.name);
- const [industry, setIndustry] = useState(brand.industry ?? "");
- const [description, setDescription] = useState(brand.description ?? "");
+ const [industry, setIndustry] = useState(brand.industry ?? '');
+ const [description, setDescription] = useState(brand.description ?? '');
const [isSaving, setIsSaving] = useState(false);
const handleSave = async () => {
@@ -170,9 +140,9 @@ function GeneralTab({
description: updated.description,
updatedAt: updated.updatedAt,
});
- toast.success(t("settings.saved"));
+ toast.success(t('settings.saved'));
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to save changes.");
+ toast.error(err instanceof Error ? err.message : 'Failed to save changes.');
} finally {
setIsSaving(false);
}
@@ -181,25 +151,25 @@ function GeneralTab({
return (
<Card>
<CardHeader>
- <CardTitle>{t("settings.generalTab")}</CardTitle>
+ <CardTitle>{t('settings.generalTab')}</CardTitle>
<CardDescription>Update your brand&apos;s basic information.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
- <Label htmlFor="name">{t("brandName")} *</Label>
+ <Label htmlFor="name">{t('brandName')} *</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
- placeholder={t("brandNamePlaceholder")}
+ placeholder={t('brandNamePlaceholder')}
/>
</div>
<div className="space-y-2">
- <Label htmlFor="industry">{t("industry")}</Label>
- <Select value={industry} onValueChange={(v) => setIndustry(v ?? "")}>
+ <Label htmlFor="industry">{t('industry')}</Label>
+ <Select value={industry} onValueChange={(v) => setIndustry(v ?? '')}>
<SelectTrigger id="industry">
- <SelectValue placeholder={t("industryPlaceholder")} />
+ <SelectValue placeholder={t('industryPlaceholder')} />
</SelectTrigger>
<SelectContent>
{INDUSTRIES.map((ind) => (
@@ -212,23 +182,19 @@ function GeneralTab({
</div>
<div className="space-y-2">
- <Label htmlFor="description">{t("description_field")}</Label>
+ <Label htmlFor="description">{t('description_field')}</Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
- placeholder={t("descriptionPlaceholder")}
+ placeholder={t('descriptionPlaceholder')}
rows={3}
/>
</div>
<Button onClick={handleSave} disabled={isSaving || !name.trim()} className="gap-2">
- {isSaving ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Save className="h-4 w-4" />
- )}
- {t("settings.saveChanges")}
+ {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ {t('settings.saveChanges')}
</Button>
</CardContent>
</Card>
@@ -244,11 +210,11 @@ function DomainsTab({
brand: Brand;
onUpdate: (updates: Partial<Brand>) => void;
}) {
- const t = useTranslations("brands");
+ const t = useTranslations('brands');
const [domains, setDomains] = useState<BrandDomain[]>(brand.domains);
const [isSaving, setIsSaving] = useState(false);
- const [newDomain, setNewDomain] = useState("");
- const [newCountry, setNewCountry] = useState("");
+ const [newDomain, setNewDomain] = useState('');
+ const [newCountry, setNewCountry] = useState('');
const addDomain = () => {
if (!newDomain.trim()) return;
@@ -260,8 +226,8 @@ function DomainsTab({
isPrimary: domains.length === 0,
};
setDomains((prev) => [...prev, entry]);
- setNewDomain("");
- setNewCountry("");
+ setNewDomain('');
+ setNewCountry('');
};
const removeDomainLocal = (id: string) => {
@@ -287,7 +253,7 @@ function DomainsTab({
domain: d.domain,
country: d.country,
isPrimary: d.isPrimary,
- }))
+ })),
);
setDomains(savedDomains);
@@ -304,9 +270,9 @@ function DomainsTab({
logoUrl: newLogoUrl ?? undefined,
updatedAt: new Date().toISOString(),
});
- toast.success(t("settings.saved"));
+ toast.success(t('settings.saved'));
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to save domains.");
+ toast.error(err instanceof Error ? err.message : 'Failed to save domains.');
} finally {
setIsSaving(false);
}
@@ -315,7 +281,7 @@ function DomainsTab({
return (
<Card>
<CardHeader>
- <CardTitle>{t("settings.domainsTab")}</CardTitle>
+ <CardTitle>{t('settings.domainsTab')}</CardTitle>
<CardDescription>
Manage the domains tracked for this brand. One domain must be set as primary.
</CardDescription>
@@ -323,20 +289,15 @@ function DomainsTab({
<CardContent className="space-y-4">
<div className="space-y-2">
{domains.map((d) => (
- <div
- key={d.id}
- className="flex items-center gap-3 rounded-lg border px-3 py-2.5"
- >
+ <div key={d.id} className="flex items-center gap-3 rounded-lg border px-3 py-2.5">
<Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
<div className="flex-1 overflow-hidden">
<p className="truncate text-sm font-medium">{d.domain}</p>
- {d.country && (
- <p className="text-xs text-muted-foreground">{d.country}</p>
- )}
+ {d.country && <p className="text-xs text-muted-foreground">{d.country}</p>}
</div>
{d.isPrimary && (
<Badge variant="secondary" className="text-xs shrink-0">
- {t("primaryDomain")}
+ {t('primaryDomain')}
</Badge>
)}
{!d.isPrimary && (
@@ -346,7 +307,7 @@ function DomainsTab({
className="h-7 text-xs shrink-0"
onClick={() => setPrimary(d.id)}
>
- {t("setPrimary")}
+ {t('setPrimary')}
</Button>
)}
{domains.length > 1 && (
@@ -366,17 +327,17 @@ function DomainsTab({
<Separator />
<div className="space-y-2">
- <Label className="text-sm font-medium">{t("addDomain")}</Label>
+ <Label className="text-sm font-medium">{t('addDomain')}</Label>
<div className="flex gap-2">
<Input
- placeholder={t("domainPlaceholder")}
+ placeholder={t('domainPlaceholder')}
value={newDomain}
onChange={(e) => setNewDomain(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && addDomain()}
+ onKeyDown={(e) => e.key === 'Enter' && addDomain()}
className="flex-1"
/>
<Input
- placeholder={t("countryPlaceholder")}
+ placeholder={t('countryPlaceholder')}
value={newCountry}
onChange={(e) => setNewCountry(e.target.value)}
className="w-28"
@@ -393,17 +354,9 @@ function DomainsTab({
</div>
</div>
- <Button
- onClick={handleSave}
- disabled={isSaving || domains.length === 0}
- className="gap-2"
- >
- {isSaving ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Save className="h-4 w-4" />
- )}
- {t("settings.saveChanges")}
+ <Button onClick={handleSave} disabled={isSaving || domains.length === 0} className="gap-2">
+ {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ {t('settings.saveChanges')}
</Button>
</CardContent>
</Card>
@@ -417,8 +370,8 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
const [isLoading, setIsLoading] = useState(true);
const [isAdding, setIsAdding] = useState(false);
const [deletingId, setDeletingId] = useState<string | null>(null);
- const [newName, setNewName] = useState("");
- const [newDomain, setNewDomain] = useState("");
+ const [newName, setNewName] = useState('');
+ const [newDomain, setNewDomain] = useState('');
const load = useCallback(async () => {
setIsLoading(true);
@@ -426,7 +379,7 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
const data = await getCompetitors(brandId);
setCompetitors(data);
} catch {
- toast.error("Failed to load competitors");
+ toast.error('Failed to load competitors');
} finally {
setIsLoading(false);
}
@@ -445,11 +398,11 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
domain: newDomain.trim(),
});
setCompetitors((prev) => [...prev, added]);
- setNewName("");
- setNewDomain("");
+ setNewName('');
+ setNewDomain('');
toast.success(`${added.name} added`);
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to add competitor");
+ toast.error(err instanceof Error ? err.message : 'Failed to add competitor');
} finally {
setIsAdding(false);
}
@@ -460,9 +413,9 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
await deleteCompetitor(id);
setCompetitors((prev) => prev.filter((c) => c.id !== id));
setDeletingId(null);
- toast.success("Competitor removed");
+ toast.success('Competitor removed');
} catch {
- toast.error("Failed to remove competitor");
+ toast.error('Failed to remove competitor');
}
};
@@ -485,10 +438,7 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
{competitors.length > 0 && (
<div className="space-y-2">
{competitors.map((c) => (
- <div
- key={c.id}
- className="flex items-center gap-3 rounded-lg border px-3 py-2.5"
- >
+ <div key={c.id} className="flex items-center gap-3 rounded-lg border px-3 py-2.5">
{c.domain ? (
/* eslint-disable-next-line @next/next/no-img-element */
<img
@@ -503,11 +453,12 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
)}
<div className="flex-1 overflow-hidden">
<p className="truncate text-sm font-medium">{c.name}</p>
- {c.domain && (
- <p className="text-xs text-muted-foreground">{c.domain}</p>
- )}
+ {c.domain && <p className="text-xs text-muted-foreground">{c.domain}</p>}
</div>
- <Dialog open={deletingId === c.id} onOpenChange={(open) => !open && setDeletingId(null)}>
+ <Dialog
+ open={deletingId === c.id}
+ onOpenChange={(open) => !open && setDeletingId(null)}
+ >
<Button
variant="ghost"
size="icon"
@@ -520,7 +471,8 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
<DialogHeader>
<DialogTitle>Remove {c.name}?</DialogTitle>
<DialogDescription>
- This will remove the competitor and its comparison data. This action cannot be undone.
+ This will remove the competitor and its comparison data. This action
+ cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -555,14 +507,14 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
placeholder="Competitor name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && newName.trim() && handleAdd()}
+ onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAdd()}
className="flex-1"
/>
<Input
placeholder="domain.com"
value={newDomain}
onChange={(e) => setNewDomain(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && newName.trim() && handleAdd()}
+ onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAdd()}
className="w-40"
/>
<Button
@@ -590,14 +542,14 @@ function CompetitorsTab({ brandId }: { brandId: string }) {
// ─── Tracking Tab ────────────────────────────────────────────────────────
function TrackingTab({ brand }: { brand: Brand }) {
- const [copied, setCopied] = useState<"code" | "snippet" | null>(null);
- const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === "true";
- const apiUrl = isCloud ? "https://api.ansops.ai" : process.env.NEXT_PUBLIC_API_URL;
+ const [copied, setCopied] = useState<'code' | 'snippet' | null>(null);
+ const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === 'true';
+ const apiUrl = isCloud ? 'https://api.ansops.ai' : process.env.NEXT_PUBLIC_API_URL;
const snippet = apiUrl
- ? `<script src="${apiUrl}/t.js" data-t="${brand.trackingCode || ""}" defer></script>`
- : "";
+ ? `<script src="${apiUrl}/t.js" data-t="${brand.trackingCode || ''}" defer></script>`
+ : '';
- const copyToClipboard = (text: string, key: "code" | "snippet") => {
+ const copyToClipboard = (text: string, key: 'code' | 'snippet') => {
navigator.clipboard.writeText(text);
setCopied(key);
setTimeout(() => setCopied(null), 2000);
@@ -611,7 +563,8 @@ function TrackingTab({ brand }: { brand: Brand }) {
AI Traffic Tracking
</CardTitle>
<CardDescription>
- Track visits to your website that come from AI platforms like ChatGPT, Perplexity, Claude, and more.
+ Track visits to your website that come from AI platforms like ChatGPT, Perplexity, Claude,
+ and more.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
@@ -619,9 +572,20 @@ function TrackingTab({ brand }: { brand: Brand }) {
<>
{!apiUrl && (
<div className="rounded-lg border border-yellow-500/30 bg-yellow-500/5 px-4 py-3 text-sm">
- <p className="font-medium text-yellow-700 dark:text-yellow-400">Server URL not configured</p>
+ <p className="font-medium text-yellow-700 dark:text-yellow-400">
+ Server URL not configured
+ </p>
<p className="text-xs text-muted-foreground mt-0.5">
- Set <code className="text-[11px] bg-muted px-1 py-0.5 rounded">NEXT_PUBLIC_API_URL</code> in your <code className="text-[11px] bg-muted px-1 py-0.5 rounded">.env</code> file to your aeo-server URL (e.g. <code className="text-[11px] bg-muted px-1 py-0.5 rounded">https://api.yourdomain.com</code>).
+ Set{' '}
+ <code className="text-[11px] bg-muted px-1 py-0.5 rounded">
+ NEXT_PUBLIC_API_URL
+ </code>{' '}
+ in your <code className="text-[11px] bg-muted px-1 py-0.5 rounded">.env</code>{' '}
+ file to your aeo-server URL (e.g.{' '}
+ <code className="text-[11px] bg-muted px-1 py-0.5 rounded">
+ https://api.yourdomain.com
+ </code>
+ ).
</p>
</div>
)}
@@ -635,9 +599,9 @@ function TrackingTab({ brand }: { brand: Brand }) {
variant="outline"
size="icon"
className="shrink-0"
- onClick={() => copyToClipboard(brand.trackingCode!, "code")}
+ onClick={() => copyToClipboard(brand.trackingCode!, 'code')}
>
- {copied === "code" ? (
+ {copied === 'code' ? (
<Check className="h-4 w-4 text-green-500" />
) : (
<Copy className="h-4 w-4" />
@@ -651,7 +615,8 @@ function TrackingTab({ brand }: { brand: Brand }) {
<div className="space-y-2">
<Label className="text-sm font-medium">Installation Snippet</Label>
<p className="text-xs text-muted-foreground">
- Add this script tag before the closing <code className="text-[11px]">&lt;/head&gt;</code> tag of your website.
+ Add this script tag before the closing{' '}
+ <code className="text-[11px]">&lt;/head&gt;</code> tag of your website.
</p>
<div className="relative">
<pre className="text-[12px] bg-muted rounded-md px-4 py-3 overflow-x-auto font-mono leading-relaxed">
@@ -661,9 +626,9 @@ function TrackingTab({ brand }: { brand: Brand }) {
variant="ghost"
size="icon"
className="absolute top-2 right-2 h-7 w-7"
- onClick={() => copyToClipboard(snippet, "snippet")}
+ onClick={() => copyToClipboard(snippet, 'snippet')}
>
- {copied === "snippet" ? (
+ {copied === 'snippet' ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
<Copy className="h-3.5 w-3.5" />
@@ -677,7 +642,10 @@ function TrackingTab({ brand }: { brand: Brand }) {
<div className="rounded-lg border p-4 space-y-2">
<p className="text-sm font-medium">How it works</p>
<ul className="text-xs text-muted-foreground space-y-1 list-disc pl-4">
- <li>The script detects visitors coming from AI platforms (ChatGPT, Perplexity, Claude, Gemini, Copilot, etc.)</li>
+ <li>
+ The script detects visitors coming from AI platforms (ChatGPT, Perplexity, Claude,
+ Gemini, Copilot, etc.)
+ </li>
<li>Only AI-referred visits are tracked — regular traffic is ignored</li>
<li>Data appears in your AI Traffic Analytics dashboard</li>
<li>The script is lightweight (~1KB) and does not affect page performance</li>
@@ -702,15 +670,9 @@ function TrackingTab({ brand }: { brand: Brand }) {
// ─── Danger Tab ───────────────────────────────────────────────────────────────
-function DangerTab({
- brand,
- onDelete,
-}: {
- brand: Brand;
- onDelete: () => Promise<void>;
-}) {
- const t = useTranslations("brands");
- const [confirmValue, setConfirmValue] = useState("");
+function DangerTab({ brand, onDelete }: { brand: Brand; onDelete: () => Promise<void> }) {
+ const t = useTranslations('brands');
+ const [confirmValue, setConfirmValue] = useState('');
const [isDeleting, setIsDeleting] = useState(false);
const canDelete = confirmValue === brand.name;
@@ -722,7 +684,7 @@ function DangerTab({
await deleteBrand(brand.id);
await onDelete();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to delete brand.");
+ toast.error(err instanceof Error ? err.message : 'Failed to delete brand.');
setIsDeleting(false);
}
};
@@ -730,17 +692,16 @@ function DangerTab({
return (
<Card className="border-destructive/30">
<CardHeader>
- <CardTitle className="text-destructive">{t("settings.dangerTab")}</CardTitle>
- <CardDescription>{t("settings.deleteWarning")}</CardDescription>
+ <CardTitle className="text-destructive">{t('settings.dangerTab')}</CardTitle>
+ <CardDescription>{t('settings.deleteWarning')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label className="text-sm">
- {t("settings.confirmDelete")}{" "}
- <span className="font-semibold">{brand.name}</span>
+ {t('settings.confirmDelete')} <span className="font-semibold">{brand.name}</span>
</Label>
<Input
- placeholder={t("settings.deleteConfirmPlaceholder")}
+ placeholder={t('settings.deleteConfirmPlaceholder')}
value={confirmValue}
onChange={(e) => setConfirmValue(e.target.value)}
/>
@@ -756,7 +717,7 @@ function DangerTab({
) : (
<Trash2 className="h-4 w-4" />
)}
- {t("settings.deleteButton")}
+ {t('settings.deleteButton')}
</Button>
</CardContent>
</Card>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
index 9b38e20cd..c300197eb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
@@ -1,27 +1,21 @@
-"use client";
+'use client';
-import { use, useCallback, useEffect, useState } from "react";
+import { use, useCallback, useEffect, useState } from 'react';
import {
createTopic,
deleteTopic,
getPromptCountByTopic,
getTopics,
updateTopic,
-} from "@/lib/actions/topic";
-import type { Topic } from "@/types";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Separator } from "@/components/ui/separator";
-import { toast } from "sonner";
-import { Check, Loader2, Pencil, Plus, Tag, Trash2, X } from "lucide-react";
+} from '@/lib/actions/topic';
+import type { Topic } from '@/types';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Separator } from '@/components/ui/separator';
+import { toast } from 'sonner';
+import { Check, Loader2, Pencil, Plus, Tag, Trash2, X } from 'lucide-react';
import {
Dialog,
DialogClose,
@@ -31,7 +25,7 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
-} from "@/components/ui/dialog";
+} from '@/components/ui/dialog';
interface PageProps {
params: Promise<{ id: string }>;
@@ -44,9 +38,9 @@ export default function BrandTopicsPage({ params }: PageProps) {
const [promptCounts, setPromptCounts] = useState<Record<string, number>>({});
const [isLoading, setIsLoading] = useState(true);
const [isAdding, setIsAdding] = useState(false);
- const [newName, setNewName] = useState("");
+ const [newName, setNewName] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
- const [editName, setEditName] = useState("");
+ const [editName, setEditName] = useState('');
const load = useCallback(async () => {
setIsLoading(true);
@@ -61,7 +55,7 @@ export default function BrandTopicsPage({ params }: PageProps) {
);
setPromptCounts(counts);
} catch {
- toast.error("Failed to load topics");
+ toast.error('Failed to load topics');
} finally {
setIsLoading(false);
}
@@ -75,17 +69,17 @@ export default function BrandTopicsPage({ params }: PageProps) {
const name = newName.trim();
if (!name) return;
if (topics.some((t) => t.name.toLowerCase() === name.toLowerCase())) {
- toast.error("This topic already exists");
+ toast.error('This topic already exists');
return;
}
setIsAdding(true);
try {
const added = await createTopic(brandId, name);
setTopics((prev) => [...prev, added]);
- setNewName("");
+ setNewName('');
toast.success(`"${added.name}" topic added`);
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to add topic");
+ toast.error(err instanceof Error ? err.message : 'Failed to add topic');
} finally {
setIsAdding(false);
}
@@ -95,16 +89,16 @@ export default function BrandTopicsPage({ params }: PageProps) {
const name = editName.trim();
if (!name) return;
if (topics.some((t) => t.id !== id && t.name.toLowerCase() === name.toLowerCase())) {
- toast.error("This topic already exists");
+ toast.error('This topic already exists');
return;
}
try {
const updated = await updateTopic(id, name);
setTopics((prev) => prev.map((t) => (t.id === id ? updated : t)));
setEditingId(null);
- toast.success("Topic updated");
+ toast.success('Topic updated');
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to update topic");
+ toast.error(err instanceof Error ? err.message : 'Failed to update topic');
}
};
@@ -112,9 +106,9 @@ export default function BrandTopicsPage({ params }: PageProps) {
try {
await deleteTopic(id);
setTopics((prev) => prev.filter((t) => t.id !== id));
- toast.success("Topic removed");
+ toast.success('Topic removed');
} catch {
- toast.error("Failed to remove topic");
+ toast.error('Failed to remove topic');
}
};
@@ -126,7 +120,8 @@ export default function BrandTopicsPage({ params }: PageProps) {
Topics
</CardTitle>
<CardDescription>
- Manage the topics used to categorize your prompts. Topics are assigned to prompts during creation.
+ Manage the topics used to categorize your prompts. Topics are assigned to prompts during
+ creation.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
@@ -151,8 +146,8 @@ export default function BrandTopicsPage({ params }: PageProps) {
value={editName}
onChange={(e) => setEditName(e.target.value)}
onKeyDown={(e) => {
- if (e.key === "Enter") handleEdit(topic.id);
- if (e.key === "Escape") setEditingId(null);
+ if (e.key === 'Enter') handleEdit(topic.id);
+ if (e.key === 'Escape') setEditingId(null);
}}
className="h-8 text-sm"
autoFocus
@@ -176,9 +171,7 @@ export default function BrandTopicsPage({ params }: PageProps) {
</div>
) : (
<>
- <p className="flex-1 truncate text-sm font-medium">
- {topic.name}
- </p>
+ <p className="flex-1 truncate text-sm font-medium">{topic.name}</p>
<Button
variant="ghost"
size="icon"
@@ -208,8 +201,8 @@ export default function BrandTopicsPage({ params }: PageProps) {
<DialogDescription>
Are you sure you want to delete &quot;{topic.name}&quot;?
{(promptCounts[topic.id] ?? 0) > 0
- ? ` ${promptCounts[topic.id]} prompt${promptCounts[topic.id] === 1 ? "" : "s"} using this topic will become uncategorized.`
- : " No prompts are using this topic."}
+ ? ` ${promptCounts[topic.id]} prompt${promptCounts[topic.id] === 1 ? '' : 's'} using this topic will become uncategorized.`
+ : ' No prompts are using this topic.'}
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -253,7 +246,7 @@ export default function BrandTopicsPage({ params }: PageProps) {
placeholder="e.g. Industry, Comparison, How-to..."
value={newName}
onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && newName.trim() && handleAdd()}
+ onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAdd()}
className="flex-1"
/>
<Button
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx
index b558622c1..af6d2aa83 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx
@@ -1,14 +1,14 @@
-"use client";
+'use client';
-import { useEffect } from "react";
-import { useTranslations } from "next-intl";
-import { Link } from "@/i18n/navigation";
-import { useBrandStore } from "@/stores/use-brand-store";
-import { BrandCard } from "@/components/dashboard/brand-card";
-import { Button } from "@/components/ui/button";
-import type { Brand } from "@/types";
-import type { BrandCardSummary } from "@/lib/actions/brand";
-import { Building2, Plus } from "lucide-react";
+import { useEffect } from 'react';
+import { useTranslations } from 'next-intl';
+import { Link } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { BrandCard } from '@/components/dashboard/brand-card';
+import { Button } from '@/components/ui/button';
+import type { Brand } from '@/types';
+import type { BrandCardSummary } from '@/lib/actions/brand';
+import { Building2, Plus } from 'lucide-react';
interface BrandsClientProps {
brands: Brand[];
@@ -29,31 +29,25 @@ export function BrandsClient({ brands, summaries }: BrandsClientProps) {
return (
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
{brands.map((brand) => (
- <BrandCard
- key={brand.id}
- brand={brand}
- summary={summaries[brand.id]}
- />
+ <BrandCard key={brand.id} brand={brand} summary={summaries[brand.id]} />
))}
</div>
);
}
function EmptyState() {
- const t = useTranslations("brands");
+ const t = useTranslations('brands');
return (
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed py-20 text-center">
<div className="mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-muted">
<Building2 className="h-7 w-7 text-muted-foreground" />
</div>
- <h2 className="text-lg font-semibold">{t("noBrands")}</h2>
- <p className="mt-1 max-w-sm text-sm text-muted-foreground">
- {t("noBrandsDescription")}
- </p>
+ <h2 className="text-lg font-semibold">{t('noBrands')}</h2>
+ <p className="mt-1 max-w-sm text-sm text-muted-foreground">{t('noBrandsDescription')}</p>
<Link href="/dashboard/brands/new" className="mt-6">
<Button className="gap-2">
<Plus className="h-4 w-4" />
- {t("addBrand")}
+ {t('addBrand')}
</Button>
</Link>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx
index a3abcaa6a..da450eaf6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx
@@ -46,8 +46,7 @@ import {
} from 'lucide-react';
import { cn } from '@/lib/utils';
-const AEO_SERVER_URL =
- process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
+const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
// ── Step indicator ─────────────────────────────────────────────────────────────
@@ -78,16 +77,10 @@ function BrandHeader({ name, domain }: { name: string; domain: string }) {
<div className="flex items-center gap-2.5 mb-8">
{domain && (
/* eslint-disable-next-line @next/next/no-img-element */
- <img
- src={getFaviconUrl(domain, 32)}
- alt=""
- className="h-6 w-6 rounded"
- />
+ <img src={getFaviconUrl(domain, 32)} alt="" className="h-6 w-6 rounded" />
)}
<span className="text-sm font-medium">{name}</span>
- {domain && (
- <span className="text-sm text-muted-foreground">{domain}</span>
- )}
+ {domain && <span className="text-sm text-muted-foreground">{domain}</span>}
</div>
);
}
@@ -136,9 +129,7 @@ function TopicAccordion({
<ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<span className="font-medium">{data.topic}</span>
- <span className="text-xs text-muted-foreground">
- {data.prompts.length} prompts
- </span>
+ <span className="text-xs text-muted-foreground">{data.prompts.length} prompts</span>
</button>
<DropdownMenu>
<DropdownMenuTrigger className="p-1 rounded hover:bg-muted text-muted-foreground">
@@ -187,12 +178,7 @@ function TopicAccordion({
>
<Check className="h-4 w-4" />
</Button>
- <Button
- size="sm"
- variant="ghost"
- onClick={() => setNewPrompt('')}
- className="h-9 px-2"
- >
+ <Button size="sm" variant="ghost" onClick={() => setNewPrompt('')} className="h-9 px-2">
<X className="h-4 w-4" />
</Button>
</div>
@@ -262,8 +248,7 @@ export default function NewBrandPage() {
topicMsgIdx.current = 0;
const interval = setInterval(() => {
- topicMsgIdx.current =
- (topicMsgIdx.current + 1) % TOPIC_LOADING_MESSAGES.length;
+ topicMsgIdx.current = (topicMsgIdx.current + 1) % TOPIC_LOADING_MESSAGES.length;
setTopicLoadingMsg(TOPIC_LOADING_MESSAGES[topicMsgIdx.current]);
}, 2500);
@@ -280,9 +265,7 @@ export default function NewBrandPage() {
domain: string;
selected: boolean;
}
- const [suggestedCompetitors, setSuggestedCompetitors] = useState<
- CompetitorItem[]
- >([]);
+ const [suggestedCompetitors, setSuggestedCompetitors] = useState<CompetitorItem[]>([]);
const [loadingCompetitors, setLoadingCompetitors] = useState(false);
const [competitorName, setCompetitorName] = useState('');
const [competitorDomain, setCompetitorDomain] = useState('');
@@ -311,9 +294,7 @@ export default function NewBrandPage() {
const interval = setInterval(() => {
competitorMsgIdx.current =
(competitorMsgIdx.current + 1) % COMPETITOR_LOADING_MESSAGES.length;
- setCompetitorLoadingMsg(
- COMPETITOR_LOADING_MESSAGES[competitorMsgIdx.current],
- );
+ setCompetitorLoadingMsg(COMPETITOR_LOADING_MESSAGES[competitorMsgIdx.current]);
}, 2500);
return () => clearInterval(interval);
@@ -321,12 +302,7 @@ export default function NewBrandPage() {
// Auto-fetch competitor suggestions when arriving at step 5 with none loaded
useEffect(() => {
- if (
- step === 5 &&
- !loadingCompetitors &&
- suggestedCompetitors.length === 0 &&
- createdBrand
- ) {
+ if (step === 5 && !loadingCompetitors && suggestedCompetitors.length === 0 && createdBrand) {
fetchCompetitorSuggestions();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -385,8 +361,7 @@ export default function NewBrandPage() {
.eq('id', user.id)
.single();
- if (!profile?.organization_id)
- throw new Error('No organization found');
+ if (!profile?.organization_id) throw new Error('No organization found');
const logoUrl = domain ? getFaviconUrl(domain) : undefined;
@@ -410,9 +385,7 @@ export default function NewBrandPage() {
fetchTopicSuggestions();
}
} catch (err) {
- toast.error(
- err instanceof Error ? err.message : 'Failed to create brand',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to create brand');
} finally {
setIsLoading(false);
}
@@ -518,12 +491,10 @@ export default function NewBrandPage() {
const data = await res.json();
setTopicPrompts(
- (data.topicPrompts || []).map(
- (tp: { topic: string; prompts: string[] }) => ({
- topic: tp.topic,
- prompts: tp.prompts,
- }),
- ),
+ (data.topicPrompts || []).map((tp: { topic: string; prompts: string[] }) => ({
+ topic: tp.topic,
+ prompts: tp.prompts,
+ })),
);
setStep(4);
} catch (err) {
@@ -565,9 +536,7 @@ export default function NewBrandPage() {
setStep(5);
fetchCompetitorSuggestions();
} catch (err) {
- toast.error(
- err instanceof Error ? err.message : 'Failed to save prompts',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to save prompts');
} finally {
setIsLoading(false);
}
@@ -632,10 +601,7 @@ export default function NewBrandPage() {
.replace(/^https?:\/\//, '')
.replace(/\/+$/, '');
if (!name) return;
- setSuggestedCompetitors((prev) => [
- ...prev,
- { name, domain: d, selected: true },
- ]);
+ setSuggestedCompetitors((prev) => [...prev, { name, domain: d, selected: true }]);
setCompetitorName('');
setCompetitorDomain('');
};
@@ -649,9 +615,7 @@ export default function NewBrandPage() {
const selected = suggestedCompetitors.filter((c) => c.selected);
if (selected.length > 0) {
await Promise.all(
- selected.map((c) =>
- addCompetitor(createdBrand.id, { name: c.name, domain: c.domain }),
- ),
+ selected.map((c) => addCompetitor(createdBrand.id, { name: c.name, domain: c.domain })),
);
}
@@ -672,9 +636,7 @@ export default function NewBrandPage() {
toast.success('Brand setup complete! Tracking is starting.');
router.push('/dashboard/insights');
} catch (err) {
- toast.error(
- err instanceof Error ? err.message : 'Failed to save competitors',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to save competitors');
setSavingCompetitors(false);
}
};
@@ -687,9 +649,7 @@ export default function NewBrandPage() {
const addPromptToTopic = (topicIndex: number, prompt: string) => {
setTopicPrompts((prev) =>
- prev.map((tp, i) =>
- i === topicIndex ? { ...tp, prompts: [...tp.prompts, prompt] } : tp,
- ),
+ prev.map((tp, i) => (i === topicIndex ? { ...tp, prompts: [...tp.prompts, prompt] } : tp)),
);
};
@@ -703,10 +663,7 @@ export default function NewBrandPage() {
);
};
- const totalPrompts = topicPrompts.reduce(
- (sum, tp) => sum + tp.prompts.length,
- 0,
- );
+ const totalPrompts = topicPrompts.reduce((sum, tp) => sum + tp.prompts.length, 0);
// ── Step 1: Brand Info ──
@@ -718,12 +675,9 @@ export default function NewBrandPage() {
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground">
<Globe className="h-6 w-6" />
</div>
- <h1 className="text-2xl font-bold tracking-tight">
- Add a new brand
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Add a new brand</h1>
<p className="text-sm text-muted-foreground">
- See how AI platforms talk about your brand. Fill in the basics to
- get started.
+ See how AI platforms talk about your brand. Fill in the basics to get started.
</p>
</div>
@@ -757,8 +711,7 @@ export default function NewBrandPage() {
<div className="space-y-2">
<Label htmlFor="description">
- Describe your brand{' '}
- <span className="text-muted-foreground">(optional)</span>
+ Describe your brand <span className="text-muted-foreground">(optional)</span>
</Label>
<Textarea
id="description"
@@ -797,12 +750,10 @@ export default function NewBrandPage() {
<BrandHeader name={brandName} domain={domain} />
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Select your target market
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Select your target market</h1>
<p className="text-sm text-muted-foreground mt-1">
- Pick the region and language your audience uses. This helps us
- deliver more accurate AI visibility data.
+ Pick the region and language your audience uses. This helps us deliver more accurate
+ AI visibility data.
</p>
</div>
@@ -825,10 +776,7 @@ export default function NewBrandPage() {
<div className="space-y-2">
<Label>Language</Label>
- <Select
- value={language}
- onValueChange={(v) => v && setLanguage(v)}
- >
+ <Select value={language} onValueChange={(v) => v && setLanguage(v)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
@@ -842,11 +790,7 @@ export default function NewBrandPage() {
</Select>
</div>
- <Button
- className="w-full"
- onClick={handleCreateBrand}
- disabled={isLoading}
- >
+ <Button className="w-full" onClick={handleCreateBrand} disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -885,13 +829,9 @@ export default function NewBrandPage() {
<div className="grid grid-cols-1 gap-10 lg:grid-cols-5">
<div className="lg:col-span-3 space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Choose topics to monitor
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Choose topics to monitor</h1>
<div className="flex items-center gap-2 mt-3">
- <span className="text-sm text-muted-foreground">
- Select up to 10 topics
- </span>
+ <span className="text-sm text-muted-foreground">Select up to 10 topics</span>
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full bg-primary rounded-full transition-all"
@@ -906,10 +846,7 @@ export default function NewBrandPage() {
{loadingTopics ? (
<div className="flex flex-col items-center gap-3 py-12 text-muted-foreground">
<Sparkles className="h-5 w-5 animate-pulse" />
- <span
- key={topicLoadingMsg}
- className="text-sm animate-in fade-in duration-500"
- >
+ <span key={topicLoadingMsg} className="text-sm animate-in fade-in duration-500">
{topicLoadingMsg}
</span>
</div>
@@ -965,9 +902,7 @@ export default function NewBrandPage() {
<Button
className="w-full"
- disabled={
- selectedTopics.size === 0 || loadingPrompts || loadingTopics
- }
+ disabled={selectedTopics.size === 0 || loadingPrompts || loadingTopics}
onClick={handleGeneratePrompts}
>
{loadingPrompts ? (
@@ -983,31 +918,25 @@ export default function NewBrandPage() {
<div className="lg:col-span-2">
<div className="rounded-xl border bg-card p-5 sticky top-10">
- <h3 className="text-sm font-semibold mb-4">
- Topic Selection Tips
- </h3>
+ <h3 className="text-sm font-semibold mb-4">Topic Selection Tips</h3>
<div className="space-y-4">
<div className="flex gap-3">
<Check className="h-4 w-4 text-foreground shrink-0 mt-0.5" />
<div>
- <p className="text-sm font-medium">
- 5 prompts are created per topic
- </p>
+ <p className="text-sm font-medium">5 prompts are created per topic</p>
<p className="text-xs text-muted-foreground mt-0.5">
- You can select up to 10 topics for a total of 50
- prompts. More can be added anytime from the dashboard.
+ You can select up to 10 topics for a total of 50 prompts. More can be added
+ anytime from the dashboard.
</p>
</div>
</div>
<div className="flex gap-3">
<Check className="h-4 w-4 text-foreground shrink-0 mt-0.5" />
<div>
- <p className="text-sm font-medium">
- Think like your customers
- </p>
+ <p className="text-sm font-medium">Think like your customers</p>
<p className="text-xs text-muted-foreground mt-0.5">
- Use terms your audience would search for when looking
- for products or services like yours.
+ Use terms your audience would search for when looking for products or
+ services like yours.
</p>
</div>
</div>
@@ -1016,8 +945,8 @@ export default function NewBrandPage() {
<div>
<p className="text-sm font-medium">Keep it short</p>
<p className="text-xs text-muted-foreground mt-0.5">
- Topics should be concise — we&apos;ll turn them into
- detailed prompts in the next step.
+ Topics should be concise — we&apos;ll turn them into detailed prompts in the
+ next step.
</p>
</div>
</div>
@@ -1052,12 +981,10 @@ export default function NewBrandPage() {
<div className="flex items-start justify-between mb-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Review your prompts
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Review your prompts</h1>
<p className="text-sm text-muted-foreground mt-1">
- These prompts will be sent to AI platforms daily. Feel free to
- edit, add, or remove any before starting.
+ These prompts will be sent to AI platforms daily. Feel free to edit, add, or remove
+ any before starting.
</p>
</div>
<Button
@@ -1077,9 +1004,7 @@ export default function NewBrandPage() {
<div className="mb-4">
<p className="text-sm font-medium">Your Prompt List</p>
- <p className="text-xs text-muted-foreground">
- {totalPrompts} prompts total
- </p>
+ <p className="text-xs text-muted-foreground">{totalPrompts} prompts total</p>
</div>
<div className="rounded-lg border">
@@ -1122,9 +1047,7 @@ export default function NewBrandPage() {
// ── Step 5: Competitors ──
if (step === 5) {
- const selectedCompetitorCount = suggestedCompetitors.filter(
- (c) => c.selected,
- ).length;
+ const selectedCompetitorCount = suggestedCompetitors.filter((c) => c.selected).length;
return (
<div className="flex min-h-svh flex-col p-6 md:p-10">
@@ -1132,22 +1055,16 @@ export default function NewBrandPage() {
<BrandHeader name={brandName} domain={domain} />
<div className="mb-6">
- <h1 className="text-2xl font-bold tracking-tight">
- Add your competitors
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Add your competitors</h1>
<p className="text-sm text-muted-foreground mt-1">
- We&apos;ll track how often competitors appear alongside your brand
- in AI responses.
+ We&apos;ll track how often competitors appear alongside your brand in AI responses.
</p>
</div>
{loadingCompetitors ? (
<div className="flex flex-col items-center gap-3 py-16 text-muted-foreground">
<Sparkles className="h-5 w-5 animate-pulse" />
- <span
- key={competitorLoadingMsg}
- className="text-sm animate-in fade-in duration-500"
- >
+ <span key={competitorLoadingMsg} className="text-sm animate-in fade-in duration-500">
{competitorLoadingMsg}
</span>
</div>
@@ -1186,17 +1103,14 @@ export default function NewBrandPage() {
alt=""
className="h-5 w-5 rounded-sm"
onError={(e) => {
- (e.target as HTMLImageElement).style.display =
- 'none';
+ (e.target as HTMLImageElement).style.display = 'none';
}}
/>
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{c.name}</p>
{c.domain && (
- <p className="text-xs text-muted-foreground truncate">
- {c.domain}
- </p>
+ <p className="text-xs text-muted-foreground truncate">{c.domain}</p>
)}
</div>
<button
@@ -1228,9 +1142,7 @@ export default function NewBrandPage() {
placeholder="domain.com"
value={competitorDomain}
onChange={(e) => setCompetitorDomain(e.target.value)}
- onKeyDown={(e) =>
- e.key === 'Enter' && addManualCompetitor()
- }
+ onKeyDown={(e) => e.key === 'Enter' && addManualCompetitor()}
className="text-sm"
/>
<Button
@@ -1244,11 +1156,7 @@ export default function NewBrandPage() {
</div>
</div>
- <Button
- className="w-full"
- onClick={handleFinish}
- disabled={savingCompetitors}
- >
+ <Button className="w-full" onClick={handleFinish} disabled={savingCompetitors}>
{savingCompetitors ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx
index 0cc350cb9..cf318d7c3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx
@@ -7,7 +7,13 @@ import { BrandsClient } from './_brands-client';
import { Button } from '@/components/ui/button';
import { Crown, Plus } from 'lucide-react';
-function BrandsHeader({ canAddBrand, needsUpgrade }: { canAddBrand: boolean; needsUpgrade: boolean }) {
+function BrandsHeader({
+ canAddBrand,
+ needsUpgrade,
+}: {
+ canAddBrand: boolean;
+ needsUpgrade: boolean;
+}) {
const t = useTranslations('brands');
return (
<div className="flex items-center justify-between">
@@ -37,10 +43,7 @@ function BrandsHeader({ canAddBrand, needsUpgrade }: { canAddBrand: boolean; nee
export default async function BrandsPage() {
const supabase = await createClient();
- const { data: profile } = await supabase
- .from('profiles')
- .select('organization_id')
- .single();
+ const { data: profile } = await supabase.from('profiles').select('organization_id').single();
const orgId = profile?.organization_id;
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
index f5affdfc9..70e11881c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
@@ -1,27 +1,10 @@
'use client';
-import {
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
-import {
- PieChart,
- Pie,
- Cell,
- Tooltip,
-} from 'recharts';
-import {
- Quote,
- Globe,
- ExternalLink,
- Filter as FilterIcon,
- Layers,
-} from 'lucide-react';
+import { PieChart, Pie, Cell, Tooltip } from 'recharts';
+import { Quote, Globe, ExternalLink, Filter as FilterIcon, Layers } from 'lucide-react';
import { useBrandStore } from '@/stores/use-brand-store';
import {
getCitationsOverview,
@@ -45,17 +28,9 @@ import {
ComboboxValue,
} from '@/components/ui/combobox';
import type { Topic } from '@/types';
-import {
- SOURCE_CATEGORY_LABELS,
- type SourceCategory,
-} from '@/lib/citations/classify';
+import { SOURCE_CATEGORY_LABELS, type SourceCategory } from '@/lib/citations/classify';
import { getFaviconUrl } from '@/lib/favicon';
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from '@/components/ui/card';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -66,12 +41,7 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from '@/components/ui/tabs';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Table,
TableBody,
@@ -91,14 +61,7 @@ import {
// ─── Constants ───────────────────────────────────────────────────────────────
-const DATE_PRESETS: CitationsDatePreset[] = [
- '24h',
- '7d',
- '30d',
- '90d',
- 'all',
- 'custom',
-];
+const DATE_PRESETS: CitationsDatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];
const CATEGORY_COLORS: Record<SourceCategory, string> = {
you: '#6366f1',
@@ -113,20 +76,13 @@ const CATEGORY_COLORS: Record<SourceCategory, string> = {
const CATEGORY_BADGE_CLASSES: Record<SourceCategory, string> = {
you: 'border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300',
- competitor:
- 'border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300',
- editorial:
- 'border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300',
- forum:
- 'border-green-500/30 bg-green-500/10 text-green-700 dark:text-green-300',
- social:
- 'border-purple-500/30 bg-purple-500/10 text-purple-700 dark:text-purple-300',
- review:
- 'border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300',
- institutional:
- 'border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300',
- other:
- 'border-slate-400/30 bg-slate-400/10 text-slate-700 dark:text-slate-300',
+ competitor: 'border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300',
+ editorial: 'border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300',
+ forum: 'border-green-500/30 bg-green-500/10 text-green-700 dark:text-green-300',
+ social: 'border-purple-500/30 bg-purple-500/10 text-purple-700 dark:text-purple-300',
+ review: 'border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300',
+ institutional: 'border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300',
+ other: 'border-slate-400/30 bg-slate-400/10 text-slate-700 dark:text-slate-300',
};
// AI platform / model friendly names — kept in sync with the insights page.
@@ -231,9 +187,7 @@ const DEFAULT_FILTERS: UIFilters = {
competitorOnly: false,
};
-function buildPlatformOptions(
- rows: CitationsOverview['rows'],
-): PlatformOption[] {
+function buildPlatformOptions(rows: CitationsOverview['rows']): PlatformOption[] {
const slugToLabel = new Map<string, string>();
for (const row of rows) {
for (const slug of row.models) {
@@ -254,10 +208,7 @@ function buildPlatformOptions(
label,
value: slugs.sort().join(','),
}))
- .sort(
- (a, b) =>
- a.label.localeCompare(b.label) || a.value.localeCompare(b.value),
- );
+ .sort((a, b) => a.label.localeCompare(b.label) || a.value.localeCompare(b.value));
}
// ─── Sub-components ───────────────────────────────────────────────────────────
@@ -305,14 +256,9 @@ function UsageBar({ pct }: { pct: number }) {
return (
<div className="flex items-center gap-2">
<div className="h-1.5 w-20 rounded-full bg-muted overflow-hidden">
- <div
- className="h-full rounded-full bg-primary"
- style={{ width: `${clamped}%` }}
- />
+ <div className="h-full rounded-full bg-primary" style={{ width: `${clamped}%` }} />
</div>
- <span className="text-xs tabular-nums text-foreground">
- {pct.toFixed(1)}%
- </span>
+ <span className="text-xs tabular-nums text-foreground">{pct.toFixed(1)}%</span>
</div>
);
}
@@ -443,9 +389,7 @@ function SourceTypeDonut({
aria-hidden
/>
<span className="truncate text-foreground">{d.label}</span>
- <span className="ml-auto tabular-nums text-muted-foreground">
- {d.pct.toFixed(1)}%
- </span>
+ <span className="ml-auto tabular-nums text-muted-foreground">{d.pct.toFixed(1)}%</span>
</li>
))}
</ul>
@@ -485,9 +429,7 @@ function FilterBar({
return (
<div className="flex flex-wrap items-end gap-3">
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Date Range
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Date Range</label>
<div className="flex rounded-md border overflow-hidden">
{DATE_PRESETS.map((p) => (
<button
@@ -510,9 +452,7 @@ function FilterBar({
{filters.datePreset === 'custom' && (
<>
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- From
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>
<Input
type="date"
value={filters.dateFrom}
@@ -521,9 +461,7 @@ function FilterBar({
/>
</div>
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- To
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>
<Input
type="date"
value={filters.dateTo}
@@ -536,14 +474,10 @@ function FilterBar({
{topics.length > 0 && (
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Topic
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topic</label>
<Select
value={filters.topic || null}
- onValueChange={(v) =>
- onChange({ topic: !v || v === '__all__' ? '' : v })
- }
+ onValueChange={(v) => onChange({ topic: !v || v === '__all__' ? '' : v })}
>
<SelectTrigger className="h-8 w-40 text-xs">
<SelectValue placeholder="All Topics">
@@ -568,16 +502,12 @@ function FilterBar({
{prompts.length > 0 && (
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Prompt
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Prompt</label>
<Combobox
items={promptComboboxItems}
value={
filters.prompt
- ? (promptComboboxItems.find(
- (item) => item.value === filters.prompt,
- ) ?? null)
+ ? (promptComboboxItems.find((item) => item.value === filters.prompt) ?? null)
: null
}
onValueChange={(item: PromptComboboxItem | null) =>
@@ -607,21 +537,17 @@ function FilterBar({
)}
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Platform
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Platform</label>
<Select
value={filters.platform || null}
- onValueChange={(v) =>
- onChange({ platform: !v || v === '__all__' ? '' : v })
- }
+ onValueChange={(v) => onChange({ platform: !v || v === '__all__' ? '' : v })}
>
<SelectTrigger className="h-8 w-40 text-xs">
<SelectValue placeholder="All Platforms">
{(value) =>
value && value !== '__all__'
- ? platforms.find((platform) => platform.value === value)
- ?.label ?? getGroupedPlatformLabel(value)
+ ? (platforms.find((platform) => platform.value === value)?.label ??
+ getGroupedPlatformLabel(value))
: 'All Platforms'
}
</SelectValue>
@@ -638,14 +564,10 @@ function FilterBar({
</div>
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Region
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Region</label>
<Select
value={filters.region || null}
- onValueChange={(v) =>
- onChange({ region: !v || v === '__all__' ? '' : v })
- }
+ onValueChange={(v) => onChange({ region: !v || v === '__all__' ? '' : v })}
>
<SelectTrigger className="h-8 w-32 text-xs">
<SelectValue placeholder="All Regions" />
@@ -667,9 +589,7 @@ function FilterBar({
variant={filters.excludeOwnDomain ? 'default' : 'outline'}
size="sm"
className="h-8 text-xs"
- onClick={() =>
- onChange({ excludeOwnDomain: !filters.excludeOwnDomain })
- }
+ onClick={() => onChange({ excludeOwnDomain: !filters.excludeOwnDomain })}
>
Exclude own domain
</Button>
@@ -681,9 +601,7 @@ function FilterBar({
onClick={() =>
onChange({
competitorOnly: !filters.competitorOnly,
- excludeOwnDomain: !filters.competitorOnly
- ? true
- : filters.excludeOwnDomain,
+ excludeOwnDomain: !filters.competitorOnly ? true : filters.excludeOwnDomain,
})
}
>
@@ -742,16 +660,12 @@ function DomainsTable({ rows }: { rows: CitationDomainRow[] }) {
<TableBody>
{rows.map((row, i) => (
<TableRow key={row.domain}>
- <TableCell className="text-xs text-muted-foreground tabular-nums">
- {i + 1}
- </TableCell>
+ <TableCell className="text-xs text-muted-foreground tabular-nums">{i + 1}</TableCell>
<TableCell>
<div className="flex items-center gap-2 min-w-0">
<DomainFavicon domain={row.domain} />
<div className="flex min-w-0 flex-col">
- <span className="truncate text-sm font-medium">
- {row.domain}
- </span>
+ <span className="truncate text-sm font-medium">{row.domain}</span>
<div className="flex items-center gap-1.5 pt-0.5">
<CategoryBadge category={row.category} />
<a
@@ -800,9 +714,7 @@ function UrlsTable({ rows }: { rows: CitationUrlRow[] }) {
<TableBody>
{rows.map((row, i) => (
<TableRow key={row.url}>
- <TableCell className="text-xs text-muted-foreground tabular-nums">
- {i + 1}
- </TableCell>
+ <TableCell className="text-xs text-muted-foreground tabular-nums">{i + 1}</TableCell>
<TableCell>
<div className="flex items-start gap-2 min-w-0">
<DomainFavicon domain={row.domain} />
@@ -817,9 +729,7 @@ function UrlsTable({ rows }: { rows: CitationUrlRow[] }) {
{row.title || row.url}
</a>
<div className="flex items-center gap-1.5 pt-0.5">
- <span className="truncate text-[11px] text-muted-foreground">
- {row.domain}
- </span>
+ <span className="truncate text-[11px] text-muted-foreground">{row.domain}</span>
<CategoryBadge category={row.category} />
</div>
</div>
@@ -831,9 +741,7 @@ function UrlsTable({ rows }: { rows: CitationUrlRow[] }) {
<TableCell>
<UsageBar pct={row.usagePct} />
</TableCell>
- <TableCell className="text-right text-xs tabular-nums">
- {row.totalCitations}
- </TableCell>
+ <TableCell className="text-right text-xs tabular-nums">{row.totalCitations}</TableCell>
</TableRow>
))}
</TableBody>
@@ -887,16 +795,16 @@ export default function CitationsPage() {
const [isLoading, setIsLoading] = useState(true);
const [topics, setTopics] = useState<Topic[]>([]);
const [prompts, setPrompts] = useState<PromptOption[]>([]);
- const [availablePlatforms, setAvailablePlatforms] = useState<PlatformOption[]>(
- [],
- );
+ const [availablePlatforms, setAvailablePlatforms] = useState<PlatformOption[]>([]);
const [availableRegions, setAvailableRegions] = useState<string[]>([]);
const activeBrandId = brand?.id ?? null;
useEffect(() => {
if (!activeBrandId) return;
- getTopics(activeBrandId).then(setTopics).catch(() => {});
+ getTopics(activeBrandId)
+ .then(setTopics)
+ .catch(() => {});
getBrandPrompts(activeBrandId)
.then((rows) => setPrompts(rows.map((r) => ({ id: r.id, text: r.text }))))
.catch(() => {});
@@ -933,21 +841,13 @@ export default function CitationsPage() {
setAvailablePlatforms((prev) =>
Array.from(
new Map(
- [...prev, ...platformOptions].map((platform) => [
- platform.value,
- platform,
- ]),
+ [...prev, ...platformOptions].map((platform) => [platform.value, platform]),
).values(),
- ).sort(
- (a, b) =>
- a.label.localeCompare(b.label) || a.value.localeCompare(b.value),
- ),
+ ).sort((a, b) => a.label.localeCompare(b.label) || a.value.localeCompare(b.value)),
);
if (regions.size > 0) {
setAvailableRegions((prev) =>
- Array.from(new Set([...prev, ...regions])).sort((a, b) =>
- a.localeCompare(b),
- ),
+ Array.from(new Set([...prev, ...regions])).sort((a, b) => a.localeCompare(b)),
);
}
} catch {
@@ -1006,9 +906,7 @@ export default function CitationsPage() {
<div className="flex flex-col items-center justify-center py-20 text-center">
<Globe className="h-10 w-10 text-muted-foreground/40 mb-3" />
<h2 className="text-lg font-semibold">{t('noBrandTitle')}</h2>
- <p className="mt-1 max-w-md text-sm text-muted-foreground">
- {t('noBrandDescription')}
- </p>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('noBrandDescription')}</p>
</div>
);
}
@@ -1018,9 +916,7 @@ export default function CitationsPage() {
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-2xl font-bold">{t('title')}</h1>
- <p className="mt-1 text-sm text-muted-foreground">
- {t('description')}
- </p>
+ <p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>
</div>
</div>
@@ -1070,9 +966,7 @@ export default function CitationsPage() {
<Card className="lg:col-span-2">
<CardHeader>
- <CardTitle className="text-base">
- {t('sourceTypesTitle')}
- </CardTitle>
+ <CardTitle className="text-base">{t('sourceTypesTitle')}</CardTitle>
</CardHeader>
<CardContent>
<SourceTypeDonut
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
index caf8e8052..bd5866cdf 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
@@ -1,29 +1,25 @@
-"use client";
-
-import { useState, useEffect, useCallback, useRef } from "react";
-import { useRouter } from "@/i18n/navigation";
-import { createPortal } from "react-dom";
-import { useTranslations } from "next-intl";
-import { useBrandStore } from "@/stores/use-brand-store";
-import { useFeatureGate } from "@/hooks/use-feature-gate";
-import {
- getCompetitors,
- addCompetitor,
- deleteCompetitor,
-} from "@/lib/actions/competitor";
+'use client';
+
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { useRouter } from '@/i18n/navigation';
+import { createPortal } from 'react-dom';
+import { useTranslations } from 'next-intl';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { useFeatureGate } from '@/hooks/use-feature-gate';
+import { getCompetitors, addCompetitor, deleteCompetitor } from '@/lib/actions/competitor';
import {
getCompetitorComparison,
getHeadToHeadComparison,
type CompetitorComparisonData,
type HeadToHeadData,
type HeadToHeadPromptRow,
-} from "@/lib/actions/tracking";
-import { getFaviconUrl } from "@/lib/favicon";
-import type { Competitor } from "@/types";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
+} from '@/lib/actions/tracking';
+import { getFaviconUrl } from '@/lib/favicon';
+import type { Competitor } from '@/types';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
@@ -31,7 +27,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/components/ui/dialog";
+} from '@/components/ui/dialog';
import {
Table,
TableBody,
@@ -39,15 +35,12 @@ import {
TableHead,
TableHeader,
TableRow,
-} from "@/components/ui/table";
-import { Badge } from "@/components/ui/badge";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import {
- AIProviderAvatar,
- resolveAIProvider,
-} from "@/components/ai-provider-avatar";
+} from '@/components/ui/table';
+import { Badge } from '@/components/ui/badge';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { toast } from 'sonner';
+import { cn } from '@/lib/utils';
+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';
import {
Plus,
Trash2,
@@ -67,31 +60,31 @@ import {
ChevronDown,
Eye,
HelpCircle,
-} from "lucide-react";
+} from 'lucide-react';
// ─── Shared Visual Components (mirroring Insights) ───────────────────────────
const MODEL_DISPLAY_NAME: Record<string, string> = {
- "gpt-4o": "GPT-4o",
- "gpt-4o-mini": "GPT-4o Mini",
- "gpt-4.1": "GPT-4.1",
- "gpt-4.1-mini": "GPT-4.1 Mini",
- "gpt-4.1-nano": "GPT-4.1 Nano",
- "gpt-5-chat-latest": "ChatGPT",
- "claude-sonnet-4-6": "Claude Sonnet",
- "claude-opus-4-6": "Claude Opus",
- "claude-haiku-4-5": "Claude Haiku",
- "gemini-2.5-pro": "Gemini 2.5 Pro",
- "gemini-2.5-flash": "Gemini 2.5 Flash",
- "grok-3": "Grok",
- "grok-4-auto": "Grok",
- "chatgpt-web": "ChatGPT",
- "perplexity-web": "Perplexity",
- "google-aio": "Google AI Overview",
- "google-aimode": "Google AI Mode",
- "copilot-web": "Microsoft Copilot",
- "grok-web": "Grok",
- "gemini-web": "Gemini",
+ 'gpt-4o': 'GPT-4o',
+ 'gpt-4o-mini': 'GPT-4o Mini',
+ 'gpt-4.1': 'GPT-4.1',
+ 'gpt-4.1-mini': 'GPT-4.1 Mini',
+ 'gpt-4.1-nano': 'GPT-4.1 Nano',
+ 'gpt-5-chat-latest': 'ChatGPT',
+ 'claude-sonnet-4-6': 'Claude Sonnet',
+ 'claude-opus-4-6': 'Claude Opus',
+ 'claude-haiku-4-5': 'Claude Haiku',
+ 'gemini-2.5-pro': 'Gemini 2.5 Pro',
+ 'gemini-2.5-flash': 'Gemini 2.5 Flash',
+ 'grok-3': 'Grok',
+ 'grok-4-auto': 'Grok',
+ 'chatgpt-web': 'ChatGPT',
+ 'perplexity-web': 'Perplexity',
+ 'google-aio': 'Google AI Overview',
+ 'google-aimode': 'Google AI Mode',
+ 'copilot-web': 'Microsoft Copilot',
+ 'grok-web': 'Grok',
+ 'gemini-web': 'Gemini',
};
function getModelDisplayName(model: string, platform?: string): string {
@@ -99,9 +92,7 @@ function getModelDisplayName(model: string, platform?: string): string {
// so use it directly if available
if (platform) {
const modelName = MODEL_DISPLAY_NAME[model];
- return modelName && modelName !== platform
- ? `${platform} · ${modelName}`
- : platform;
+ return modelName && modelName !== platform ? `${platform} · ${modelName}` : platform;
}
return MODEL_DISPLAY_NAME[model] ?? model;
}
@@ -116,22 +107,18 @@ function ModelBadge({ model, platform }: { model: string; platform?: string }) {
);
}
-function SentimentBadge({
- sentiment,
-}: {
- sentiment: "positive" | "neutral" | "negative";
-}) {
+function SentimentBadge({ sentiment }: { sentiment: 'positive' | 'neutral' | 'negative' }) {
return (
<Badge
variant="outline"
className={cn(
- "text-xs capitalize",
- sentiment === "positive" &&
- "border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400",
- sentiment === "neutral" &&
- "border-yellow-500/30 bg-yellow-500/10 text-yellow-600 dark:text-yellow-400",
- sentiment === "negative" &&
- "border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400",
+ 'text-xs capitalize',
+ sentiment === 'positive' &&
+ 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ sentiment === 'neutral' &&
+ 'border-yellow-500/30 bg-yellow-500/10 text-yellow-600 dark:text-yellow-400',
+ sentiment === 'negative' &&
+ 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
)}
>
{sentiment}
@@ -146,12 +133,8 @@ function VisibilityBar({ score, max = 100 }: { score: number; max?: number }) {
<div className="h-1.5 w-24 rounded-full bg-muted overflow-hidden">
<div
className={cn(
- "h-full rounded-full transition-all",
- score >= 60
- ? "bg-green-500"
- : score >= 40
- ? "bg-yellow-500"
- : "bg-red-500",
+ 'h-full rounded-full transition-all',
+ score >= 60 ? 'bg-green-500' : score >= 40 ? 'bg-yellow-500' : 'bg-red-500',
)}
style={{ width: `${pct}%` }}
/>
@@ -183,7 +166,7 @@ function InfoTip({ content }: { content: string }) {
{pos &&
createPortal(
<div
- style={{ left: pos.x, top: pos.y, transform: "translateX(-50%)" }}
+ style={{ left: pos.x, top: pos.y, transform: 'translateX(-50%)' }}
className="pointer-events-none fixed z-[9999] w-56 rounded-md border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md"
>
{content}
@@ -216,25 +199,23 @@ function ColHead({
// ─── Plan Gate ────────────────────────────────────────────────────────────────
function PlanGateOverlay() {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
return (
<div className="space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('description')}</p>
</div>
<Card>
<CardContent className="flex flex-col items-center justify-center py-16 text-center">
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30 mb-4">
<Crown className="h-7 w-7 text-amber-600 dark:text-amber-400" />
</div>
- <h3 className="text-lg font-semibold">{t("upgradeTitle")}</h3>
- <p className="text-sm text-muted-foreground mt-1 max-w-sm">
- {t("upgradeDescription")}
- </p>
+ <h3 className="text-lg font-semibold">{t('upgradeTitle')}</h3>
+ <p className="text-sm text-muted-foreground mt-1 max-w-sm">{t('upgradeDescription')}</p>
<Badge variant="outline" className="mt-4">
<Crown className="mr-1 h-3 w-3" />
- {t("upgradeRequiredPlan")}
+ {t('upgradeRequiredPlan')}
</Badge>
</CardContent>
</Card>
@@ -245,22 +226,20 @@ function PlanGateOverlay() {
// ─── No Brand ─────────────────────────────────────────────────────────────────
function NoBrandSelected() {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
return (
<div className="space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('description')}</p>
</div>
<Card>
<CardContent className="flex flex-col items-center justify-center py-16 text-center">
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-white mb-4">
<AlertCircle className="h-7 w-7 text-muted-foreground" />
</div>
- <h3 className="text-lg font-semibold">{t("noBrandTitle")}</h3>
- <p className="text-sm text-muted-foreground mt-1 max-w-sm">
- {t("noBrandDescription")}
- </p>
+ <h3 className="text-lg font-semibold">{t('noBrandTitle')}</h3>
+ <p className="text-sm text-muted-foreground mt-1 max-w-sm">{t('noBrandDescription')}</p>
</CardContent>
</Card>
</div>
@@ -270,20 +249,18 @@ function NoBrandSelected() {
// ─── Empty State ──────────────────────────────────────────────────────────────
function EmptyState({ onAdd }: { onAdd: () => void }) {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
return (
<Card>
<CardContent className="flex flex-col items-center justify-center py-16 text-center">
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-white mb-4">
<Users className="h-7 w-7 text-muted-foreground" />
</div>
- <h3 className="text-lg font-semibold">{t("emptyTitle")}</h3>
- <p className="text-sm text-muted-foreground mt-1 max-w-sm">
- {t("emptyDescription")}
- </p>
+ <h3 className="text-lg font-semibold">{t('emptyTitle')}</h3>
+ <p className="text-sm text-muted-foreground mt-1 max-w-sm">{t('emptyDescription')}</p>
<Button className="mt-6 gap-2" onClick={onAdd}>
<Plus className="h-4 w-4" />
- {t("addCompetitor")}
+ {t('addCompetitor')}
</Button>
</CardContent>
</Card>
@@ -301,14 +278,14 @@ function AddCompetitorDialog({
onOpenChange: (open: boolean) => void;
onAdd: (name: string, domain: string) => Promise<void>;
}) {
- const t = useTranslations("competitors");
- const [name, setName] = useState("");
- const [domain, setDomain] = useState("");
+ const t = useTranslations('competitors');
+ const [name, setName] = useState('');
+ const [domain, setDomain] = useState('');
const [saving, setSaving] = useState(false);
function reset() {
- setName("");
- setDomain("");
+ setName('');
+ setDomain('');
}
async function handleSubmit(e: React.FormEvent) {
@@ -320,7 +297,7 @@ function AddCompetitorDialog({
reset();
onOpenChange(false);
} catch {
- toast.error(t("addError"));
+ toast.error(t('addError'));
} finally {
setSaving(false);
}
@@ -331,41 +308,37 @@ function AddCompetitorDialog({
<DialogContent className="sm:max-w-md">
<form onSubmit={handleSubmit}>
<DialogHeader>
- <DialogTitle>{t("addCompetitor")}</DialogTitle>
- <DialogDescription>{t("addDescription")}</DialogDescription>
+ <DialogTitle>{t('addCompetitor')}</DialogTitle>
+ <DialogDescription>{t('addDescription')}</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
- <Label htmlFor="comp-name">{t("name")}</Label>
+ <Label htmlFor="comp-name">{t('name')}</Label>
<Input
id="comp-name"
- placeholder={t("namePlaceholder")}
+ placeholder={t('namePlaceholder')}
value={name}
onChange={(e) => setName(e.target.value)}
autoFocus
/>
</div>
<div className="grid gap-2">
- <Label htmlFor="comp-domain">{t("domain")}</Label>
+ <Label htmlFor="comp-domain">{t('domain')}</Label>
<Input
id="comp-domain"
- placeholder={t("domainPlaceholder")}
+ placeholder={t('domainPlaceholder')}
value={domain}
onChange={(e) => setDomain(e.target.value)}
/>
</div>
</div>
<DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- >
- {t("cancel")}
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('cancel')}
</Button>
<Button type="submit" disabled={saving || !name.trim()}>
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
- {t("add")}
+ {t('add')}
</Button>
</DialogFooter>
</form>
@@ -387,7 +360,8 @@ function DiffBadge({ diff }: { diff: number }) {
if (diff < 0) {
return (
<span className="inline-flex items-center gap-0.5 text-xs font-medium text-red-600 dark:text-red-400">
- <ArrowDownRight className="h-3 w-3" />{diff}
+ <ArrowDownRight className="h-3 w-3" />
+ {diff}
</span>
);
}
@@ -415,13 +389,13 @@ function CompetitorCard({
onDelete: () => void;
deleting: boolean;
}) {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
return (
<div
className={cn(
- "group relative flex items-center gap-3 rounded-lg border p-3 transition-colors cursor-pointer hover:bg-accent/50",
- isSelected && "border-primary bg-primary/5 ring-1 ring-primary/20",
+ 'group relative flex items-center gap-3 rounded-lg border p-3 transition-colors cursor-pointer hover:bg-accent/50',
+ isSelected && 'border-primary bg-primary/5 ring-1 ring-primary/20',
)}
onClick={onSelect}
>
@@ -434,7 +408,7 @@ function CompetitorCard({
className="h-5 w-5 rounded-sm"
onError={(e) => {
const el = e.target as HTMLImageElement;
- el.style.display = "none";
+ el.style.display = 'none';
el.parentElement!.innerHTML =
'<svg class="h-5 w-5 text-muted-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9" /></svg>';
}}
@@ -449,12 +423,12 @@ function CompetitorCard({
<span className="text-sm font-medium truncate">{competitor.name}</span>
{isSelected && (
<Badge variant="outline" className="text-[10px] px-1.5 py-0">
- {t("selected")}
+ {t('selected')}
</Badge>
)}
</div>
<span className="text-xs text-muted-foreground truncate block">
- {competitor.domain || "—"}
+ {competitor.domain || '—'}
</span>
</div>
@@ -468,15 +442,15 @@ function CompetitorCard({
</div>
) : (
<div className="text-right">
- <span className="text-xs text-muted-foreground">{t("noData")}</span>
+ <span className="text-xs text-muted-foreground">{t('noData')}</span>
</div>
)}
<Button
variant="ghost"
size="icon"
- aria-label={t("delete")}
- title={t("delete")}
+ aria-label={t('delete')}
+ title={t('delete')}
className="h-7 w-7 opacity-0 group-hover:opacity-70 hover:opacity-100 focus-visible:opacity-100 text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-opacity"
onClick={(e) => {
e.stopPropagation();
@@ -506,14 +480,12 @@ function PlatformBreakdown({
brandName: string;
competitorName: string;
}) {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
return (
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- {t("h2h.platformBreakdown")}
- </CardTitle>
+ <CardTitle className="text-sm font-medium">{t('h2h.platformBreakdown')}</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
@@ -572,28 +544,22 @@ interface PromptComparisonGroup {
promptId: string;
promptText: string;
promptCategory?: string;
- rows: HeadToHeadData["promptRows"];
+ rows: HeadToHeadData['promptRows'];
avgBrandScore: number;
avgCompetitorScore: number;
avgDiff: number;
}
-function groupH2HByPrompt(
- rows: HeadToHeadData["promptRows"],
-): PromptComparisonGroup[] {
- const map = new Map<string, HeadToHeadData["promptRows"]>();
+function groupH2HByPrompt(rows: HeadToHeadData['promptRows']): PromptComparisonGroup[] {
+ const map = new Map<string, HeadToHeadData['promptRows']>();
for (const r of rows) {
const arr = map.get(r.promptId) || [];
arr.push(r);
map.set(r.promptId, arr);
}
return Array.from(map.entries()).map(([promptId, items]) => {
- const avgB = Math.round(
- items.reduce((s, r) => s + r.brandScore, 0) / items.length,
- );
- const avgC = Math.round(
- items.reduce((s, r) => s + r.competitorScore, 0) / items.length,
- );
+ const avgB = Math.round(items.reduce((s, r) => s + r.brandScore, 0) / items.length);
+ const avgC = Math.round(items.reduce((s, r) => s + r.competitorScore, 0) / items.length);
return {
promptId,
promptText: items[0].promptText,
@@ -621,7 +587,7 @@ interface ModelComparisonGroup {
function groupH2HByModel(rows: HeadToHeadPromptRow[]): ModelComparisonGroup[] {
const map = new Map<string, HeadToHeadPromptRow[]>();
for (const r of rows) {
- const key = `${r.platform}|${r.modelUsed ?? ""}|${r.region ?? ""}`;
+ const key = `${r.platform}|${r.modelUsed ?? ''}|${r.region ?? ''}`;
const arr = map.get(key) || [];
arr.push(r);
map.set(key, arr);
@@ -633,12 +599,8 @@ function groupH2HByModel(rows: HeadToHeadPromptRow[]): ModelComparisonGroup[] {
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
);
const latest = sorted[0];
- const avgB = Math.round(
- sorted.reduce((s, r) => s + r.brandScore, 0) / sorted.length,
- );
- const avgC = Math.round(
- sorted.reduce((s, r) => s + r.competitorScore, 0) / sorted.length,
- );
+ const avgB = Math.round(sorted.reduce((s, r) => s + r.brandScore, 0) / sorted.length);
+ const avgC = Math.round(sorted.reduce((s, r) => s + r.competitorScore, 0) / sorted.length);
return {
key,
platform: latest.platform,
@@ -657,8 +619,8 @@ function groupH2HByModel(rows: HeadToHeadPromptRow[]): ModelComparisonGroup[] {
function formatTimestamp(iso: string): string {
const d = new Date(iso);
return d.toLocaleDateString(undefined, {
- month: "short",
- day: "numeric",
+ month: 'short',
+ day: 'numeric',
});
}
@@ -677,7 +639,7 @@ function ModelSubGroup({
brandName: string;
competitorName: string;
}) {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
const hasHistory = group.rows.length > 1;
return (
@@ -687,54 +649,45 @@ function ModelSubGroup({
tabIndex={0}
onClick={onToggle}
onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
+ if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onToggle();
}
}}
className={cn(
- "flex w-full items-center gap-3 px-3 py-2 transition-colors select-none",
- hasHistory
- ? "hover:bg-muted/40 cursor-pointer"
- : "cursor-default",
+ 'flex w-full items-center gap-3 px-3 py-2 transition-colors select-none',
+ hasHistory ? 'hover:bg-muted/40 cursor-pointer' : 'cursor-default',
)}
>
<ChevronDown
className={cn(
- "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
- !expanded && "-rotate-90",
- !hasHistory && "opacity-0",
+ 'h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform',
+ !expanded && '-rotate-90',
+ !hasHistory && 'opacity-0',
)}
/>
<div className="flex-1 min-w-0 flex items-center gap-2">
- <ModelBadge
- model={group.modelUsed || group.platform}
- platform={group.platform}
- />
+ <ModelBadge model={group.modelUsed || group.platform} platform={group.platform} />
{group.region && (
<Badge variant="outline" className="text-[10px]">
{group.region}
</Badge>
)}
<span className="text-[10px] text-muted-foreground tabular-nums ml-1">
- {group.rows.length} run{group.rows.length !== 1 ? "s" : ""}
+ {group.rows.length} run{group.rows.length !== 1 ? 's' : ''}
</span>
</div>
<div className="flex items-center gap-4 shrink-0">
<div className="text-right">
- <p className="text-[10px] text-muted-foreground">{t("h2h.you")}</p>
- <p className="text-xs font-semibold tabular-nums">
- {group.avgBrandScore}%
- </p>
+ <p className="text-[10px] text-muted-foreground">{t('h2h.you')}</p>
+ <p className="text-xs font-semibold tabular-nums">{group.avgBrandScore}%</p>
</div>
<div className="text-right">
- <p className="text-[10px] text-muted-foreground">{t("h2h.them")}</p>
- <p className="text-xs font-semibold tabular-nums">
- {group.avgCompetitorScore}%
- </p>
+ <p className="text-[10px] text-muted-foreground">{t('h2h.them')}</p>
+ <p className="text-xs font-semibold tabular-nums">{group.avgCompetitorScore}%</p>
</div>
<div className="text-right min-w-[48px]">
- <p className="text-[10px] text-muted-foreground">{t("h2h.diff")}</p>
+ <p className="text-[10px] text-muted-foreground">{t('h2h.diff')}</p>
<DiffBadge diff={group.avgDiff} />
</div>
<SentimentBadge sentiment={group.latest.sentiment} />
@@ -762,18 +715,10 @@ function ModelSubGroup({
<TableHeader>
<TableRow>
<TableHead className="text-[10px] h-7">Date</TableHead>
- <TableHead className="text-[10px] h-7 text-center">
- {brandName}
- </TableHead>
- <TableHead className="text-[10px] h-7 text-center">
- {competitorName}
- </TableHead>
- <TableHead className="text-[10px] h-7 text-center">
- {t("h2h.diff")}
- </TableHead>
- <TableHead className="text-[10px] h-7 text-center">
- Sentiment
- </TableHead>
+ <TableHead className="text-[10px] h-7 text-center">{brandName}</TableHead>
+ <TableHead className="text-[10px] h-7 text-center">{competitorName}</TableHead>
+ <TableHead className="text-[10px] h-7 text-center">{t('h2h.diff')}</TableHead>
+ <TableHead className="text-[10px] h-7 text-center">Sentiment</TableHead>
<TableHead className="text-[10px] h-7 w-[60px]" />
</TableRow>
</TableHeader>
@@ -790,9 +735,7 @@ function ModelSubGroup({
{Math.round(row.competitorScore)}%
</TableCell>
<TableCell className="text-center py-1.5">
- <DiffBadge
- diff={Math.round(row.brandScore - row.competitorScore)}
- />
+ <DiffBadge diff={Math.round(row.brandScore - row.competitorScore)} />
</TableCell>
<TableCell className="text-center py-1.5">
<SentimentBadge sentiment={row.sentiment} />
@@ -827,12 +770,12 @@ function PromptComparisonGrouped({
competitorName,
onViewRow,
}: {
- rows: HeadToHeadData["promptRows"];
+ rows: HeadToHeadData['promptRows'];
brandName: string;
competitorName: string;
onViewRow: (row: HeadToHeadPromptRow) => void;
}) {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
const groups = groupH2HByPrompt(rows);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [expandedModels, setExpandedModels] = useState<Set<string>>(new Set());
@@ -840,21 +783,23 @@ function PromptComparisonGrouped({
const toggle = (id: string) =>
setExpanded((prev) => {
const next = new Set(prev);
- if (next.has(id)) next.delete(id); else next.add(id);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
return next;
});
const toggleModel = (id: string) =>
setExpandedModels((prev) => {
const next = new Set(prev);
- if (next.has(id)) next.delete(id); else next.add(id);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
return next;
});
if (groups.length === 0) {
return (
<div className="flex items-center justify-center py-12 text-sm text-muted-foreground">
- {t("h2h.noPromptData")}
+ {t('h2h.noPromptData')}
</div>
);
}
@@ -865,17 +810,14 @@ function PromptComparisonGrouped({
const isOpen = expanded.has(group.promptId);
const modelGroups = groupH2HByModel(group.rows);
return (
- <div
- key={group.promptId}
- className="rounded-lg border overflow-hidden"
- >
+ <div key={group.promptId} className="rounded-lg border overflow-hidden">
{/* Group Header */}
<div
role="button"
tabIndex={0}
onClick={() => toggle(group.promptId)}
onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
+ if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggle(group.promptId);
}
@@ -884,14 +826,12 @@ function PromptComparisonGrouped({
>
<ChevronDown
className={cn(
- "h-4 w-4 shrink-0 text-muted-foreground transition-transform",
- !isOpen && "-rotate-90",
+ 'h-4 w-4 shrink-0 text-muted-foreground transition-transform',
+ !isOpen && '-rotate-90',
)}
/>
<div className="flex-1 min-w-0">
- <p className="text-sm font-medium line-clamp-1">
- {group.promptText}
- </p>
+ <p className="text-sm font-medium line-clamp-1">{group.promptText}</p>
<div className="flex items-center gap-2 mt-0.5">
{group.promptCategory && (
<Badge variant="outline" className="text-[10px]">
@@ -900,26 +840,22 @@ function PromptComparisonGrouped({
)}
<span className="text-[11px] text-muted-foreground">
{modelGroups.length} platform
- {modelGroups.length !== 1 ? "s" : ""} · {group.rows.length}{" "}
- result{group.rows.length !== 1 ? "s" : ""}
+ {modelGroups.length !== 1 ? 's' : ''} · {group.rows.length} result
+ {group.rows.length !== 1 ? 's' : ''}
</span>
</div>
</div>
<div className="flex items-center gap-4 shrink-0">
<div className="text-right">
- <p className="text-[10px] text-muted-foreground">{t("h2h.you")}</p>
- <p className="text-sm font-semibold tabular-nums">
- {group.avgBrandScore}%
- </p>
+ <p className="text-[10px] text-muted-foreground">{t('h2h.you')}</p>
+ <p className="text-sm font-semibold tabular-nums">{group.avgBrandScore}%</p>
</div>
<div className="text-right">
- <p className="text-[10px] text-muted-foreground">{t("h2h.them")}</p>
- <p className="text-sm font-semibold tabular-nums">
- {group.avgCompetitorScore}%
- </p>
+ <p className="text-[10px] text-muted-foreground">{t('h2h.them')}</p>
+ <p className="text-sm font-semibold tabular-nums">{group.avgCompetitorScore}%</p>
</div>
<div className="text-right min-w-[48px]">
- <p className="text-[10px] text-muted-foreground">{t("h2h.diff")}</p>
+ <p className="text-[10px] text-muted-foreground">{t('h2h.diff')}</p>
<DiffBadge diff={group.avgDiff} />
</div>
</div>
@@ -956,16 +892,14 @@ function PromptComparisonGrouped({
interface GapStrengthGroup {
promptId: string;
promptText: string;
- items: HeadToHeadData["gaps"];
+ items: HeadToHeadData['gaps'];
avgBrandScore: number;
avgCompetitorScore: number;
avgDiff: number;
}
-function groupGapStrengthByPrompt(
- items: HeadToHeadData["gaps"],
-): GapStrengthGroup[] {
- const map = new Map<string, HeadToHeadData["gaps"]>();
+function groupGapStrengthByPrompt(items: HeadToHeadData['gaps']): GapStrengthGroup[] {
+ const map = new Map<string, HeadToHeadData['gaps']>();
for (const item of items) {
const arr = map.get(item.promptId) || [];
arr.push(item);
@@ -973,9 +907,7 @@ function groupGapStrengthByPrompt(
}
return Array.from(map.entries())
.map(([promptId, groupItems]) => {
- const avgB = Math.round(
- groupItems.reduce((s, r) => s + r.brandScore, 0) / groupItems.length,
- );
+ const avgB = Math.round(groupItems.reduce((s, r) => s + r.brandScore, 0) / groupItems.length);
const avgC = Math.round(
groupItems.reduce((s, r) => s + r.competitorScore, 0) / groupItems.length,
);
@@ -988,32 +920,33 @@ function groupGapStrengthByPrompt(
avgDiff: avgB - avgC,
};
})
- .sort((a, b) => (a.avgDiff - b.avgDiff));
+ .sort((a, b) => a.avgDiff - b.avgDiff);
}
function GapStrengthList({
items,
type,
}: {
- items: HeadToHeadData["gaps"];
- type: "gap" | "strength";
+ items: HeadToHeadData['gaps'];
+ type: 'gap' | 'strength';
}) {
- const t = useTranslations("competitors");
- const isGap = type === "gap";
+ const t = useTranslations('competitors');
+ const isGap = type === 'gap';
const groups = groupGapStrengthByPrompt(items);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const toggle = (id: string) =>
setExpanded((prev) => {
const next = new Set(prev);
- if (next.has(id)) next.delete(id); else next.add(id);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
return next;
});
if (groups.length === 0) {
return (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
- {isGap ? t("h2h.noGaps") : t("h2h.noStrengths")}
+ {isGap ? t('h2h.noGaps') : t('h2h.noStrengths')}
</div>
);
}
@@ -1031,34 +964,35 @@ function GapStrengthList({
<div
key={group.promptId}
className={cn(
- "rounded-lg border overflow-hidden",
+ 'rounded-lg border overflow-hidden',
isGap
- ? "border-red-200/50 bg-red-50/50 dark:border-red-900/30 dark:bg-red-950/20"
- : "border-green-200/50 bg-green-50/50 dark:border-green-900/30 dark:bg-green-950/20",
+ ? 'border-red-200/50 bg-red-50/50 dark:border-red-900/30 dark:bg-red-950/20'
+ : 'border-green-200/50 bg-green-50/50 dark:border-green-900/30 dark:bg-green-950/20',
)}
>
{/* Group Header */}
<div
- role={hasMultiple ? "button" : undefined}
+ role={hasMultiple ? 'button' : undefined}
tabIndex={hasMultiple ? 0 : undefined}
onClick={() => hasMultiple && toggle(group.promptId)}
onKeyDown={(e) => {
- if (hasMultiple && (e.key === "Enter" || e.key === " ")) {
+ if (hasMultiple && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
toggle(group.promptId);
}
}}
className={cn(
- "flex items-start gap-3 p-3",
- hasMultiple && "cursor-pointer hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors select-none",
+ 'flex items-start gap-3 p-3',
+ hasMultiple &&
+ 'cursor-pointer hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors select-none',
)}
>
<div
className={cn(
- "flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-bold mt-0.5",
+ 'flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-bold mt-0.5',
isGap
- ? "bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-400"
- : "bg-green-100 text-green-600 dark:bg-green-900/40 dark:text-green-400",
+ ? 'bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-400'
+ : 'bg-green-100 text-green-600 dark:bg-green-900/40 dark:text-green-400',
)}
>
{i + 1}
@@ -1068,26 +1002,37 @@ function GapStrengthList({
{hasMultiple && (
<ChevronDown
className={cn(
- "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
- !isOpen && "-rotate-90",
+ 'h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform',
+ !isOpen && '-rotate-90',
)}
/>
)}
<p className="text-sm line-clamp-2">{group.promptText}</p>
</div>
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
- <span>{t("h2h.you")}: {group.avgBrandScore}%</span>
- <span>{t("h2h.them")}: {group.avgCompetitorScore}%</span>
+ <span>
+ {t('h2h.you')}: {group.avgBrandScore}%
+ </span>
+ <span>
+ {t('h2h.them')}: {group.avgCompetitorScore}%
+ </span>
{hasMultiple ? (
<span>{group.items.length} models</span>
- ) : (group.items[0].modelUsed || group.items[0].platform) ? (
- <ModelBadge model={group.items[0].modelUsed || group.items[0].platform} platform={group.items[0].platform} />
+ ) : group.items[0].modelUsed || group.items[0].platform ? (
+ <ModelBadge
+ model={group.items[0].modelUsed || group.items[0].platform}
+ platform={group.items[0].platform}
+ />
) : (
<span className="text-xs text-muted-foreground">—</span>
)}
{!hasMultiple && group.items[0].createdAt && (
<span className="text-muted-foreground">
- {new Date(group.items[0].createdAt).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}
+ {new Date(group.items[0].createdAt).toLocaleDateString(undefined, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ })}
</span>
)}
</div>
@@ -1104,15 +1049,18 @@ function GapStrengthList({
<div
key={`${item.promptId}-${item.modelUsed}-${j}`}
className={cn(
- "flex items-center gap-3 rounded-md px-3 py-2 text-xs",
+ 'flex items-center gap-3 rounded-md px-3 py-2 text-xs',
isGap
- ? "bg-red-100/50 dark:bg-red-900/20"
- : "bg-green-100/50 dark:bg-green-900/20",
+ ? 'bg-red-100/50 dark:bg-red-900/20'
+ : 'bg-green-100/50 dark:bg-green-900/20',
)}
>
<div className="flex-1 min-w-0">
- {(item.modelUsed || item.platform) ? (
- <ModelBadge model={item.modelUsed || item.platform} platform={item.platform} />
+ {item.modelUsed || item.platform ? (
+ <ModelBadge
+ model={item.modelUsed || item.platform}
+ platform={item.platform}
+ />
) : (
<span className="text-xs text-muted-foreground">—</span>
)}
@@ -1123,14 +1071,17 @@ function GapStrengthList({
</Badge>
)}
<span className="tabular-nums text-muted-foreground">
- {t("h2h.you")}: {Math.round(item.brandScore)}%
+ {t('h2h.you')}: {Math.round(item.brandScore)}%
</span>
<span className="tabular-nums text-muted-foreground">
- {t("h2h.them")}: {Math.round(item.competitorScore)}%
+ {t('h2h.them')}: {Math.round(item.competitorScore)}%
</span>
{item.createdAt && (
<span className="text-muted-foreground whitespace-nowrap">
- {new Date(item.createdAt).toLocaleDateString(undefined, { day: "numeric", month: "short" })}
+ {new Date(item.createdAt).toLocaleDateString(undefined, {
+ day: 'numeric',
+ month: 'short',
+ })}
</span>
)}
<DiffBadge diff={Math.round(item.diff)} />
@@ -1156,7 +1107,7 @@ function HeadToHeadSection({
brandName: string;
competitorName: string;
}) {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
const router = useRouter();
const overallDiff = data.brandAvg - data.competitorAvg;
@@ -1168,7 +1119,7 @@ function HeadToHeadSection({
<CardContent className="pt-5 pb-4">
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-1">
<Target className="h-3.5 w-3.5" />
- {t("h2h.yourAvg")}
+ {t('h2h.yourAvg')}
</div>
<div className="text-2xl font-bold tabular-nums">{data.brandAvg}%</div>
</CardContent>
@@ -1177,7 +1128,7 @@ function HeadToHeadSection({
<CardContent className="pt-5 pb-4">
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-1">
<Swords className="h-3.5 w-3.5" />
- {t("h2h.theirAvg")}
+ {t('h2h.theirAvg')}
</div>
<div className="text-2xl font-bold tabular-nums">{data.competitorAvg}%</div>
</CardContent>
@@ -1190,16 +1141,17 @@ function HeadToHeadSection({
) : (
<TrendingDown className="h-3.5 w-3.5" />
)}
- {t("h2h.overallDiff")}
+ {t('h2h.overallDiff')}
</div>
<div
className={cn(
- "text-2xl font-bold tabular-nums",
- overallDiff > 0 && "text-green-600 dark:text-green-400",
- overallDiff < 0 && "text-red-600 dark:text-red-400",
+ 'text-2xl font-bold tabular-nums',
+ overallDiff > 0 && 'text-green-600 dark:text-green-400',
+ overallDiff < 0 && 'text-red-600 dark:text-red-400',
)}
>
- {overallDiff > 0 ? "+" : ""}{overallDiff}%
+ {overallDiff > 0 ? '+' : ''}
+ {overallDiff}%
</div>
</CardContent>
</Card>
@@ -1207,11 +1159,7 @@ function HeadToHeadSection({
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
{/* Platform Breakdown */}
- <PlatformBreakdown
- data={data}
- brandName={brandName}
- competitorName={competitorName}
- />
+ <PlatformBreakdown data={data} brandName={brandName} competitorName={competitorName} />
{/* Gaps & Strengths */}
<Card className="lg:col-span-2">
@@ -1220,11 +1168,11 @@ function HeadToHeadSection({
<TabsList className="mb-3">
<TabsTrigger value="gaps" className="gap-1.5 text-xs">
<ShieldAlert className="h-3.5 w-3.5" />
- {t("h2h.gaps")} ({data.gaps.length})
+ {t('h2h.gaps')} ({data.gaps.length})
</TabsTrigger>
<TabsTrigger value="strengths" className="gap-1.5 text-xs">
<TrendingUp className="h-3.5 w-3.5" />
- {t("h2h.strengths")} ({data.strengths.length})
+ {t('h2h.strengths')} ({data.strengths.length})
</TabsTrigger>
</TabsList>
<TabsContent value="gaps">
@@ -1241,10 +1189,8 @@ function HeadToHeadSection({
{/* Grouped Prompt-by-Prompt Comparison */}
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- {t("h2h.promptByPrompt")}
- </CardTitle>
- <p className="text-xs text-muted-foreground">{t("h2h.promptByPromptDesc")}</p>
+ <CardTitle className="text-sm font-medium">{t('h2h.promptByPrompt')}</CardTitle>
+ <p className="text-xs text-muted-foreground">{t('h2h.promptByPromptDesc')}</p>
</CardHeader>
<CardContent className="pt-0">
<PromptComparisonGrouped
@@ -1262,13 +1208,12 @@ function HeadToHeadSection({
// ─── Main Page ────────────────────────────────────────────────────────────────
export default function CompetitorsPage() {
- const t = useTranslations("competitors");
+ const t = useTranslations('competitors');
const { canUse, isCloud } = useFeatureGate();
const brand = useBrandStore((s) => s.getActiveBrand());
const [competitors, setCompetitors] = useState<Competitor[]>([]);
- const [comparisonData, setComparisonData] =
- useState<CompetitorComparisonData | null>(null);
+ const [comparisonData, setComparisonData] = useState<CompetitorComparisonData | null>(null);
const [loading, setLoading] = useState(true);
const [dialogOpen, setDialogOpen] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null);
@@ -1290,7 +1235,7 @@ export default function CompetitorsPage() {
setCompetitors(comps);
setComparisonData(comparison.brands.length > 1 ? comparison : null);
} catch {
- toast.error(t("loadError"));
+ toast.error(t('loadError'));
} finally {
setLoading(false);
}
@@ -1310,7 +1255,7 @@ export default function CompetitorsPage() {
const data = await getHeadToHeadComparison(brand.id, competitorId);
setH2hData(data);
} catch {
- toast.error(t("h2h.loadError"));
+ toast.error(t('h2h.loadError'));
} finally {
setH2hLoading(false);
}
@@ -1326,7 +1271,7 @@ export default function CompetitorsPage() {
}
}, [selectedCompetitorId, loadH2H]);
- if (isCloud && !canUse("competitor_tracking")) {
+ if (isCloud && !canUse('competitor_tracking')) {
return <PlanGateOverlay />;
}
@@ -1349,7 +1294,7 @@ export default function CompetitorsPage() {
async function handleAdd(name: string, domain: string) {
if (!brand) return;
await addCompetitor(brand.id, { name, domain });
- toast.success(t("addSuccess"));
+ toast.success(t('addSuccess'));
loadData();
}
@@ -1357,13 +1302,13 @@ export default function CompetitorsPage() {
setDeleting(id);
try {
await deleteCompetitor(id);
- toast.success(t("deleteSuccess"));
+ toast.success(t('deleteSuccess'));
if (selectedCompetitorId === id) {
setSelectedCompetitorId(null);
}
loadData();
} catch {
- toast.error(t("deleteError"));
+ toast.error(t('deleteError'));
} finally {
setDeleting(null);
}
@@ -1375,8 +1320,8 @@ export default function CompetitorsPage() {
return (
<div className="space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('description')}</p>
</div>
<div className="flex items-center justify-center py-20">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
@@ -1390,12 +1335,12 @@ export default function CompetitorsPage() {
{/* Header */}
<div className="flex items-center justify-between">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('description')}</p>
</div>
<Button className="gap-2" onClick={() => setDialogOpen(true)}>
<Plus className="h-4 w-4" />
- {t("addCompetitor")}
+ {t('addCompetitor')}
</Button>
</div>
@@ -1408,12 +1353,12 @@ export default function CompetitorsPage() {
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<Users className="h-4 w-4" />
- {t("trackedCompetitors")}
+ {t('trackedCompetitors')}
<Badge variant="secondary" className="text-xs">
{competitors.length}
</Badge>
</CardTitle>
- <p className="text-xs text-muted-foreground">{t("selectToCompare")}</p>
+ <p className="text-xs text-muted-foreground">{t('selectToCompare')}</p>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
@@ -1424,9 +1369,7 @@ export default function CompetitorsPage() {
stats={scoreMap.get(comp.name) ?? null}
isSelected={selectedCompetitorId === comp.id}
onSelect={() =>
- setSelectedCompetitorId(
- selectedCompetitorId === comp.id ? null : comp.id,
- )
+ setSelectedCompetitorId(selectedCompetitorId === comp.id ? null : comp.id)
}
onDelete={() => setConfirmDelete(comp)}
deleting={deleting === comp.id}
@@ -1442,9 +1385,9 @@ export default function CompetitorsPage() {
<div className="flex items-center gap-2 pt-2">
<Swords className="h-5 w-5 text-primary" />
<h2 className="text-lg font-semibold">
- {t("h2h.title", {
+ {t('h2h.title', {
brand: brand.name,
- competitor: selectedCompetitor?.name ?? "",
+ competitor: selectedCompetitor?.name ?? '',
})}
</h2>
</div>
@@ -1457,15 +1400,15 @@ export default function CompetitorsPage() {
<HeadToHeadSection
data={h2hData}
brandName={brand.name}
- competitorName={selectedCompetitor?.name ?? ""}
+ competitorName={selectedCompetitor?.name ?? ''}
/>
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<Swords className="h-8 w-8 text-muted-foreground mb-3" />
- <h3 className="text-sm font-semibold">{t("h2h.noDataTitle")}</h3>
+ <h3 className="text-sm font-semibold">{t('h2h.noDataTitle')}</h3>
<p className="text-xs text-muted-foreground mt-1 max-w-sm">
- {t("h2h.noDataDescription")}
+ {t('h2h.noDataDescription')}
</p>
</CardContent>
</Card>
@@ -1475,11 +1418,7 @@ export default function CompetitorsPage() {
</>
)}
- <AddCompetitorDialog
- open={dialogOpen}
- onOpenChange={setDialogOpen}
- onAdd={handleAdd}
- />
+ <AddCompetitorDialog open={dialogOpen} onOpenChange={setDialogOpen} onAdd={handleAdd} />
<ConfirmDeleteCompetitorDialog
competitor={confirmDelete}
@@ -1492,9 +1431,7 @@ export default function CompetitorsPage() {
setConfirmDelete(null);
await handleDelete(id);
}}
- deleting={
- confirmDelete !== null && deleting === confirmDelete.id
- }
+ deleting={confirmDelete !== null && deleting === confirmDelete.id}
/>
</div>
);
@@ -1511,8 +1448,8 @@ function ConfirmDeleteCompetitorDialog({
onConfirm: () => void;
deleting: boolean;
}) {
- const t = useTranslations("competitors");
- const name = competitor?.name ?? "";
+ const t = useTranslations('competitors');
+ const name = competitor?.name ?? '';
return (
<Dialog open={competitor !== null} onOpenChange={onOpenChange}>
@@ -1520,11 +1457,9 @@ function ConfirmDeleteCompetitorDialog({
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-destructive" />
- {t("confirmDeleteTitle", { name })}
+ {t('confirmDeleteTitle', { name })}
</DialogTitle>
- <DialogDescription>
- {t("confirmDeleteDescription", { name })}
- </DialogDescription>
+ <DialogDescription>{t('confirmDeleteDescription', { name })}</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-2">
<Button
@@ -1533,7 +1468,7 @@ function ConfirmDeleteCompetitorDialog({
onClick={() => onOpenChange(false)}
disabled={deleting}
>
- {t("cancel")}
+ {t('cancel')}
</Button>
<Button
type="button"
@@ -1543,7 +1478,7 @@ function ConfirmDeleteCompetitorDialog({
>
{deleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Trash2 className="mr-1.5 h-4 w-4" />
- {t("confirmDeleteAction")}
+ {t('confirmDeleteAction')}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
index cd2900414..3d4554390 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
@@ -1,11 +1,11 @@
-"use client";
+'use client';
-import { useState, useEffect } from "react";
-import { useTranslations } from "next-intl";
-import { useParams } from "next/navigation";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
+import { useState, useEffect } from 'react';
+import { useTranslations } from 'next-intl';
+import { useParams } from 'next/navigation';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
import {
ArrowLeft,
Send,
@@ -21,41 +21,41 @@ import {
FileText,
Target,
ListOrdered,
-} from "lucide-react";
-import { cn } from "@/lib/utils";
-import { Link } from "@/i18n/navigation";
+} from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { Link } from '@/i18n/navigation';
import {
getOpportunity,
updateOpportunityStatus,
sendToWebhook,
generateBrief,
-} from "@/lib/actions/content";
-import type { ContentBrief, ContentOpportunity } from "@/types";
-import { toast } from "sonner";
+} from '@/lib/actions/content';
+import type { ContentBrief, ContentOpportunity } from '@/types';
+import { toast } from 'sonner';
const IMPACT_COLORS: Record<string, string> = {
- high: "border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400",
- medium: "border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",
- low: "border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-400",
+ high: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
+ medium: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ low: 'border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-400',
};
const STATUS_COLORS: Record<string, string> = {
- new: "border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400",
- sent: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
- in_progress: "border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400",
- done: "border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400",
- dismissed: "border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400",
+ new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
+ sent: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+ in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',
+ done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ dismissed: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400',
};
const INTENT_LABELS: Record<string, string> = {
- comparison: "Comparison",
- "how-to": "How-to",
- "what-is": "What is",
- "best-top": "Best / Top",
- "vs-review": "vs. / Review",
- recommendation: "Recommendation",
- "problem-solving": "Problem Solving",
- other: "Other",
+ comparison: 'Comparison',
+ 'how-to': 'How-to',
+ 'what-is': 'What is',
+ 'best-top': 'Best / Top',
+ 'vs-review': 'vs. / Review',
+ recommendation: 'Recommendation',
+ 'problem-solving': 'Problem Solving',
+ other: 'Other',
};
function StatCard({
@@ -70,7 +70,7 @@ function StatCard({
className?: string;
}) {
return (
- <div className={cn("flex items-center gap-3 rounded-lg border p-3", className)}>
+ <div className={cn('flex items-center gap-3 rounded-lg border p-3', className)}>
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
<div>
<p className="text-xs text-muted-foreground">{label}</p>
@@ -81,7 +81,7 @@ function StatCard({
}
export default function ContentDetailPage() {
- const t = useTranslations("content");
+ const t = useTranslations('content');
const params = useParams();
const id = params.id as string;
@@ -99,8 +99,8 @@ export default function ContentDetailPage() {
if (opp.brief) setBrief(opp.brief);
})
.catch((err) => {
- console.error("Failed to load opportunity:", err);
- toast.error("Failed to load opportunity");
+ console.error('Failed to load opportunity:', err);
+ toast.error('Failed to load opportunity');
})
.finally(() => setLoading(false));
}, [id]);
@@ -109,12 +109,12 @@ export default function ContentDetailPage() {
setSending(true);
try {
await sendToWebhook(id);
- toast.success("Sent to workflow!");
+ toast.success('Sent to workflow!');
const updated = await getOpportunity(id);
setOpportunity(updated);
} catch (err) {
- console.error("Send failed:", err);
- toast.error(err instanceof Error ? err.message : "Failed to send");
+ console.error('Send failed:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to send');
} finally {
setSending(false);
}
@@ -122,12 +122,12 @@ export default function ContentDetailPage() {
const handleDismiss = async () => {
try {
- await updateOpportunityStatus(id, "dismissed");
- toast.success("Opportunity dismissed");
+ await updateOpportunityStatus(id, 'dismissed');
+ toast.success('Opportunity dismissed');
const updated = await getOpportunity(id);
setOpportunity(updated);
} catch {
- toast.error("Failed to dismiss");
+ toast.error('Failed to dismiss');
}
};
@@ -136,10 +136,10 @@ export default function ContentDetailPage() {
try {
const result = await generateBrief(id);
setBrief(result);
- toast.success("Content brief generated!");
+ toast.success('Content brief generated!');
} catch (err) {
- console.error("Brief generation failed:", err);
- toast.error(err instanceof Error ? err.message : "Failed to generate brief");
+ console.error('Brief generation failed:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to generate brief');
} finally {
setGeneratingBrief(false);
}
@@ -174,13 +174,11 @@ export default function ContentDetailPage() {
<div className="flex-1">
<h1 className="text-xl font-bold tracking-tight">{opportunity.title}</h1>
{opportunity.description && (
- <p className="text-sm text-muted-foreground mt-1">
- {opportunity.description}
- </p>
+ <p className="text-sm text-muted-foreground mt-1">{opportunity.description}</p>
)}
</div>
<div className="flex items-center gap-2">
- {opportunity.status === "new" && (
+ {opportunity.status === 'new' && (
<>
<Button
variant="outline"
@@ -189,20 +187,15 @@ export default function ContentDetailPage() {
className="gap-2 text-muted-foreground"
>
<X className="h-4 w-4" />
- {t("dismiss")}
+ {t('dismiss')}
</Button>
- <Button
- size="sm"
- onClick={handleSend}
- disabled={sending}
- className="gap-2"
- >
+ <Button size="sm" onClick={handleSend} disabled={sending} className="gap-2">
{sending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
- {sending ? t("sending") : t("sendToWorkflow")}
+ {sending ? t('sending') : t('sendToWorkflow')}
</Button>
</>
)}
@@ -211,18 +204,12 @@ export default function ContentDetailPage() {
<div className="flex items-center gap-2">
<Badge variant="outline" className="text-xs">
- {t(`type.${opportunity.type}` as "type.owned" | "type.earned")}
+ {t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}
</Badge>
- <Badge
- variant="outline"
- className={cn("text-xs", IMPACT_COLORS[opportunity.impact])}
- >
- {t(`impact.${opportunity.impact}` as "impact.high" | "impact.medium" | "impact.low")}
+ <Badge variant="outline" className={cn('text-xs', IMPACT_COLORS[opportunity.impact])}>
+ {t(`impact.${opportunity.impact}` as 'impact.high' | 'impact.medium' | 'impact.low')}
</Badge>
- <Badge
- variant="outline"
- className={cn("text-xs", STATUS_COLORS[opportunity.status])}
- >
+ <Badge variant="outline" className={cn('text-xs', STATUS_COLORS[opportunity.status])}>
{t(`status.${opportunity.status}` as `status.${typeof opportunity.status}`)}
</Badge>
<Badge variant="outline" className="text-xs tabular-nums">
@@ -231,9 +218,9 @@ export default function ContentDetailPage() {
<span className="text-xs text-muted-foreground ml-auto flex items-center gap-1.5">
<Clock className="h-3.5 w-3.5" />
{new Date(opportunity.createdAt).toLocaleDateString(undefined, {
- day: "numeric",
- month: "short",
- year: "numeric",
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
})}
</span>
</div>
@@ -241,45 +228,39 @@ export default function ContentDetailPage() {
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- {t("detail.sourceData")}
- </CardTitle>
+ <CardTitle className="text-sm font-medium">{t('detail.sourceData')}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{sd.promptText && (
- <StatCard
- icon={Search}
- label={t("detail.relatedPrompt")}
- value={sd.promptText}
- />
+ <StatCard icon={Search} label={t('detail.relatedPrompt')} value={sd.promptText} />
)}
<div className="grid grid-cols-2 gap-3">
{sd.estAiVolume !== undefined && (
<StatCard
icon={TrendingUp}
- label={t("detail.estAiVolume")}
+ label={t('detail.estAiVolume')}
value={`~${sd.estAiVolume.toLocaleString()}/mo`}
/>
)}
{sd.visibilityScore !== undefined && (
<StatCard
icon={Eye}
- label={t("detail.visibility")}
+ label={t('detail.visibility')}
value={`${Math.round(sd.visibilityScore)}%`}
/>
)}
{sd.competitorGap !== undefined && (
<StatCard
icon={Users}
- label={t("detail.competitorGap")}
- value={`${sd.competitorGap > 0 ? "+" : ""}${Math.round(sd.competitorGap)}%`}
+ label={t('detail.competitorGap')}
+ value={`${sd.competitorGap > 0 ? '+' : ''}${Math.round(sd.competitorGap)}%`}
/>
)}
{sd.intent && (
<StatCard
icon={Tag}
- label={t("detail.intent")}
+ label={t('detail.intent')}
value={INTENT_LABELS[sd.intent] || sd.intent}
/>
)}
@@ -287,9 +268,7 @@ export default function ContentDetailPage() {
{sd.keywords && sd.keywords.length > 0 && (
<div>
- <p className="text-xs text-muted-foreground mb-1.5">
- {t("detail.keywords")}
- </p>
+ <p className="text-xs text-muted-foreground mb-1.5">{t('detail.keywords')}</p>
<div className="flex flex-wrap gap-1">
{sd.keywords.map((kw) => (
<Badge key={kw} variant="outline" className="text-xs">
@@ -303,7 +282,7 @@ export default function ContentDetailPage() {
{sd.competitorsCited && sd.competitorsCited.length > 0 && (
<div>
<p className="text-xs text-muted-foreground mb-1.5">
- {t("detail.competitorsCited")}
+ {t('detail.competitorsCited')}
</p>
<div className="flex flex-wrap gap-1">
{sd.competitorsCited.map((comp) => (
@@ -326,19 +305,15 @@ export default function ContentDetailPage() {
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 text-primary" />
- <CardTitle className="text-sm font-medium">
- Content Brief
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Content Brief</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div>
- <h3 className="text-base font-semibold">
- {brief.suggestedTitle}
- </h3>
+ <h3 className="text-base font-semibold">{brief.suggestedTitle}</h3>
<div className="flex items-center gap-2 mt-1.5">
<Badge variant="outline" className="text-xs">
- {brief.contentType.replace(/-/g, " ")}
+ {brief.contentType.replace(/-/g, ' ')}
</Badge>
<Badge variant="outline" className="text-xs tabular-nums">
~{brief.targetWordCount.toLocaleString()} words
@@ -374,24 +349,18 @@ export default function ContentDetailPage() {
<Card>
<CardContent className="flex flex-col items-center justify-center py-10 text-center">
<Sparkles className="h-10 w-10 text-muted-foreground/40 mb-3" />
- <h3 className="text-sm font-medium mb-1">
- No Content Brief Yet
- </h3>
+ <h3 className="text-sm font-medium mb-1">No Content Brief Yet</h3>
<p className="text-xs text-muted-foreground mb-4 max-w-sm">
- Generate an AI-powered content brief with a suggested title,
- outline, target keywords, and competitor insights.
+ Generate an AI-powered content brief with a suggested title, outline, target
+ keywords, and competitor insights.
</p>
- <Button
- onClick={handleGenerateBrief}
- disabled={generatingBrief}
- className="gap-2"
- >
+ <Button onClick={handleGenerateBrief} disabled={generatingBrief} className="gap-2">
{generatingBrief ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Sparkles className="h-4 w-4" />
)}
- {generatingBrief ? "Generating..." : "Generate Content Brief"}
+ {generatingBrief ? 'Generating...' : 'Generate Content Brief'}
</Button>
</CardContent>
</Card>
@@ -404,27 +373,19 @@ export default function ContentDetailPage() {
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
<ListOrdered className="h-4 w-4 text-primary" />
- <CardTitle className="text-sm font-medium">
- Brief Outline
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Brief Outline</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-3">
{brief.outline.map((section, idx) => (
- <div
- key={idx}
- className="rounded-lg border bg-muted/30 p-3"
- >
+ <div key={idx} className="rounded-lg border bg-muted/30 p-3">
<p className="text-sm font-medium mb-1.5">
{idx + 1}. {section.heading}
</p>
<ul className="space-y-1 ml-4">
{section.keyPoints.map((point, pIdx) => (
- <li
- key={pIdx}
- className="text-xs text-muted-foreground list-disc"
- >
+ <li key={pIdx} className="text-xs text-muted-foreground list-disc">
{point}
</li>
))}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
index 895ac90cb..74a71c0fd 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
@@ -1,24 +1,20 @@
-"use client";
+'use client';
-import { useState, useEffect } from "react";
-import { useTranslations } from "next-intl";
+import { useState, useEffect } from 'react';
+import { useTranslations } from 'next-intl';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Loader2, CheckCircle2, XCircle } from "lucide-react";
-import {
- getWebhookConfig,
- saveWebhookConfig,
- testWebhook,
-} from "@/lib/actions/content";
-import { toast } from "sonner";
+} from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Loader2, CheckCircle2, XCircle } from 'lucide-react';
+import { getWebhookConfig, saveWebhookConfig, testWebhook } from '@/lib/actions/content';
+import { toast } from 'sonner';
interface WebhookSettingsDialogProps {
open: boolean;
@@ -26,15 +22,11 @@ interface WebhookSettingsDialogProps {
brandId: string;
}
-export function WebhookSettingsDialog({
- open,
- onOpenChange,
- brandId,
-}: WebhookSettingsDialogProps) {
- const t = useTranslations("content.webhook");
+export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSettingsDialogProps) {
+ const t = useTranslations('content.webhook');
- const [url, setUrl] = useState("");
- const [secret, setSecret] = useState("");
+ const [url, setUrl] = useState('');
+ const [secret, setSecret] = useState('');
const [isActive, setIsActive] = useState(true);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
@@ -52,7 +44,7 @@ export function WebhookSettingsDialog({
.then((config) => {
if (config) {
setUrl(config.webhookUrl);
- setSecret(config.webhookSecret || "");
+ setSecret(config.webhookSecret || '');
setIsActive(config.isActive);
}
})
@@ -63,7 +55,7 @@ export function WebhookSettingsDialog({
const handleSave = async () => {
if (!url.trim()) {
- toast.error("Webhook URL is required");
+ toast.error('Webhook URL is required');
return;
}
setSaving(true);
@@ -73,11 +65,11 @@ export function WebhookSettingsDialog({
webhookSecret: secret.trim() || undefined,
isActive,
});
- toast.success(t("saved"));
+ toast.success(t('saved'));
onOpenChange(false);
} catch (err) {
- console.error("Save webhook failed:", err);
- toast.error("Failed to save webhook config");
+ console.error('Save webhook failed:', err);
+ toast.error('Failed to save webhook config');
} finally {
setSaving(false);
}
@@ -85,7 +77,7 @@ export function WebhookSettingsDialog({
const handleTest = async () => {
if (!url.trim()) {
- toast.error("Enter a webhook URL first");
+ toast.error('Enter a webhook URL first');
return;
}
setTesting(true);
@@ -94,14 +86,12 @@ export function WebhookSettingsDialog({
const result = await testWebhook(url.trim(), secret.trim() || undefined);
setTestResult({
success: result.success,
- message: result.success
- ? t("testSuccess")
- : result.error || `HTTP ${result.status}`,
+ message: result.success ? t('testSuccess') : result.error || `HTTP ${result.status}`,
});
} catch (err) {
setTestResult({
success: false,
- message: err instanceof Error ? err.message : "Test failed",
+ message: err instanceof Error ? err.message : 'Test failed',
});
} finally {
setTesting(false);
@@ -112,8 +102,8 @@ export function WebhookSettingsDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>{t("title")}</DialogTitle>
- <DialogDescription>{t("description")}</DialogDescription>
+ <DialogTitle>{t('title')}</DialogTitle>
+ <DialogDescription>{t('description')}</DialogDescription>
</DialogHeader>
{loading ? (
@@ -123,22 +113,22 @@ export function WebhookSettingsDialog({
) : (
<div className="space-y-4">
<div className="space-y-2">
- <Label htmlFor="webhook-url">{t("url")}</Label>
+ <Label htmlFor="webhook-url">{t('url')}</Label>
<Input
id="webhook-url"
type="url"
- placeholder={t("urlPlaceholder")}
+ placeholder={t('urlPlaceholder')}
value={url}
onChange={(e) => setUrl(e.target.value)}
/>
</div>
<div className="space-y-2">
- <Label htmlFor="webhook-secret">{t("secret")}</Label>
+ <Label htmlFor="webhook-secret">{t('secret')}</Label>
<Input
id="webhook-secret"
type="password"
- placeholder={t("secretPlaceholder")}
+ placeholder={t('secretPlaceholder')}
value={secret}
onChange={(e) => setSecret(e.target.value)}
/>
@@ -151,26 +141,24 @@ export function WebhookSettingsDialog({
aria-checked={isActive}
onClick={() => setIsActive(!isActive)}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors ${
- isActive ? "bg-primary" : "bg-muted"
+ isActive ? 'bg-primary' : 'bg-muted'
}`}
>
<span
className={`pointer-events-none block h-3.5 w-3.5 rounded-full bg-background shadow-lg transition-transform ${
- isActive ? "translate-x-4" : "translate-x-0.5"
+ isActive ? 'translate-x-4' : 'translate-x-0.5'
}`}
/>
</button>
- <span className="text-sm">
- {isActive ? t("active") : t("inactive")}
- </span>
+ <span className="text-sm">{isActive ? t('active') : t('inactive')}</span>
</div>
{testResult && (
<div
className={`flex items-center gap-2 rounded-md border p-3 text-sm ${
testResult.success
- ? "border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400"
- : "border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400"
+ ? 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400'
+ : 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400'
}`}
>
{testResult.success ? (
@@ -191,7 +179,7 @@ export function WebhookSettingsDialog({
className="gap-2"
>
{testing && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {testing ? t("testing") : t("test")}
+ {testing ? t('testing') : t('test')}
</Button>
<Button
size="sm"
@@ -200,7 +188,7 @@ export function WebhookSettingsDialog({
className="gap-2"
>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {saving ? t("saving") : t("save")}
+ {saving ? t('saving') : t('save')}
</Button>
</div>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index 7becd73f0..4148d0736 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -1,19 +1,19 @@
-"use client";
-
-import { useState, useEffect, useCallback, useRef } from "react";
-import { useTranslations } from "next-intl";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Checkbox } from "@/components/ui/checkbox";
+'use client';
+
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { useTranslations } from 'next-intl';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Checkbox } from '@/components/ui/checkbox';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
-} from "@/components/ui/select";
+} from '@/components/ui/select';
import {
Table,
TableBody,
@@ -21,7 +21,7 @@ import {
TableHead,
TableHeader,
TableRow,
-} from "@/components/ui/table";
+} from '@/components/ui/table';
import {
Lightbulb,
Zap,
@@ -33,10 +33,10 @@ import {
ExternalLink,
X,
Settings2,
-} from "lucide-react";
-import { cn } from "@/lib/utils";
-import { useBrandStore } from "@/stores/use-brand-store";
-import { usePlanContext } from "@/components/providers/plan-provider";
+} from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { usePlanContext } from '@/components/providers/plan-provider';
import {
generateOpportunities,
getGenerationJobStatus,
@@ -45,16 +45,13 @@ import {
sendToWebhook,
bulkSendToWebhook,
bulkUpdateStatus,
-} from "@/lib/actions/content";
-import type {
- ContentOpportunity,
- ContentOpportunityStatus,
-} from "@/types";
-import { toast } from "sonner";
-import { Link } from "@/i18n/navigation";
-import { WebhookSettingsDialog } from "./_webhook-settings";
-
-const GENERATION_STORAGE_KEY = "aeo:content-generation";
+} from '@/lib/actions/content';
+import type { ContentOpportunity, ContentOpportunityStatus } from '@/types';
+import { toast } from 'sonner';
+import { Link } from '@/i18n/navigation';
+import { WebhookSettingsDialog } from './_webhook-settings';
+
+const GENERATION_STORAGE_KEY = 'aeo:content-generation';
const GENERATION_TIMEOUT_MS = 3 * 60 * 1000;
interface GenerationJob {
@@ -64,7 +61,9 @@ interface GenerationJob {
}
function saveGenerationJob(job: GenerationJob) {
- try { localStorage.setItem(GENERATION_STORAGE_KEY, JSON.stringify(job)); } catch {}
+ try {
+ localStorage.setItem(GENERATION_STORAGE_KEY, JSON.stringify(job));
+ } catch {}
}
function loadGenerationJob(): GenerationJob | null {
@@ -77,25 +76,29 @@ function loadGenerationJob(): GenerationJob | null {
return null;
}
return job;
- } catch { return null; }
+ } catch {
+ return null;
+ }
}
function clearGenerationJob() {
- try { localStorage.removeItem(GENERATION_STORAGE_KEY); } catch {}
+ try {
+ localStorage.removeItem(GENERATION_STORAGE_KEY);
+ } catch {}
}
const IMPACT_COLORS: Record<string, string> = {
- high: "border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400",
- medium: "border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",
- low: "border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-400",
+ high: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
+ medium: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ low: 'border-slate-500/30 bg-slate-500/10 text-slate-600 dark:text-slate-400',
};
const STATUS_COLORS: Record<string, string> = {
- new: "border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400",
- sent: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
- in_progress: "border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400",
- done: "border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400",
- dismissed: "border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400",
+ new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
+ sent: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+ in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',
+ done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ dismissed: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400',
};
function KpiCard({
@@ -126,7 +129,7 @@ function KpiCard({
}
export default function ContentPage() {
- const t = useTranslations("content");
+ const t = useTranslations('content');
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const { isCloud } = usePlanContext();
@@ -136,10 +139,10 @@ export default function ContentPage() {
const [generating, setGenerating] = useState(false);
const [sendingId, setSendingId] = useState<string | null>(null);
- const [search, setSearch] = useState("");
- const [statusFilter, setStatusFilter] = useState<string>("all");
- const [impactFilter, setImpactFilter] = useState<string>("all");
- const [typeFilter, setTypeFilter] = useState<string>("all");
+ const [search, setSearch] = useState('');
+ const [statusFilter, setStatusFilter] = useState<string>('all');
+ const [impactFilter, setImpactFilter] = useState<string>('all');
+ const [typeFilter, setTypeFilter] = useState<string>('all');
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [bulkSending, setBulkSending] = useState(false);
@@ -159,21 +162,21 @@ export default function ContentPage() {
setSelectedIds(new Set());
try {
const filters: Record<string, string> = {};
- if (statusFilter !== "all") filters.status = statusFilter;
- if (impactFilter !== "all") filters.impact = impactFilter;
- if (typeFilter !== "all") filters.type = typeFilter;
+ if (statusFilter !== 'all') filters.status = statusFilter;
+ if (impactFilter !== 'all') filters.impact = impactFilter;
+ if (typeFilter !== 'all') filters.type = typeFilter;
const data = await getOpportunities(activeBrandId, {
...filters,
limit: 100,
- sort: "score",
+ sort: 'score',
});
setOpportunities(data.opportunities);
setTotal(data.total);
return data.total;
} catch (err) {
- console.error("Failed to load opportunities:", err);
- toast.error("Failed to load content opportunities");
+ console.error('Failed to load opportunities:', err);
+ toast.error('Failed to load content opportunities');
return 0;
} finally {
setLoading(false);
@@ -184,49 +187,52 @@ export default function ContentPage() {
loadData();
}, [loadData]);
- const pollJob = useCallback((jobId: string, startedAt: number) => {
- pollRef.current = true;
- setGenerating(true);
-
- const poll = async () => {
- while (pollRef.current) {
- await new Promise((r) => setTimeout(r, 3000));
- if (!pollRef.current) break;
- try {
- const status = await getGenerationJobStatus(jobId);
-
- if (status.status === "completed") {
- pollRef.current = false;
- clearGenerationJob();
- setGenerating(false);
- toast.success(`Generated ${status.result?.generated ?? 0} opportunities`);
- loadData();
- break;
+ const pollJob = useCallback(
+ (jobId: string, startedAt: number) => {
+ pollRef.current = true;
+ setGenerating(true);
+
+ const poll = async () => {
+ while (pollRef.current) {
+ await new Promise((r) => setTimeout(r, 3000));
+ if (!pollRef.current) break;
+ try {
+ const status = await getGenerationJobStatus(jobId);
+
+ if (status.status === 'completed') {
+ pollRef.current = false;
+ clearGenerationJob();
+ setGenerating(false);
+ toast.success(`Generated ${status.result?.generated ?? 0} opportunities`);
+ loadData();
+ break;
+ }
+
+ if (status.status === 'failed') {
+ pollRef.current = false;
+ clearGenerationJob();
+ setGenerating(false);
+ toast.error(status.failedReason || 'Generation failed — please try again');
+ break;
+ }
+
+ if (Date.now() - startedAt > GENERATION_TIMEOUT_MS) {
+ pollRef.current = false;
+ clearGenerationJob();
+ setGenerating(false);
+ toast.error('Generation timed out — please try again');
+ break;
+ }
+ } catch {
+ // keep polling
}
-
- if (status.status === "failed") {
- pollRef.current = false;
- clearGenerationJob();
- setGenerating(false);
- toast.error(status.failedReason || "Generation failed — please try again");
- break;
- }
-
- if (Date.now() - startedAt > GENERATION_TIMEOUT_MS) {
- pollRef.current = false;
- clearGenerationJob();
- setGenerating(false);
- toast.error("Generation timed out — please try again");
- break;
- }
- } catch {
- // keep polling
}
- }
- };
+ };
- poll();
- }, [loadData]);
+ poll();
+ },
+ [loadData],
+ );
// Restore generation state from localStorage on mount
useEffect(() => {
@@ -235,7 +241,9 @@ export default function ContentPage() {
if (!saved || saved.brandId !== activeBrandId) return;
pollJob(saved.jobId, saved.startedAt);
- return () => { pollRef.current = false; };
+ return () => {
+ pollRef.current = false;
+ };
}, [activeBrandId, pollJob]);
const handleGenerate = async () => {
@@ -246,8 +254,8 @@ export default function ContentPage() {
saveGenerationJob({ brandId: activeBrandId, jobId, startedAt });
pollJob(jobId, startedAt);
} catch (err) {
- console.error("Generate failed:", err);
- toast.error(err instanceof Error ? err.message : "Failed to generate opportunities");
+ console.error('Generate failed:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to generate opportunities');
setGenerating(false);
}
};
@@ -256,11 +264,11 @@ export default function ContentPage() {
setSendingId(id);
try {
await sendToWebhook(id);
- toast.success("Sent to workflow!");
+ toast.success('Sent to workflow!');
await loadData();
} catch (err) {
- console.error("Webhook send failed:", err);
- toast.error(err instanceof Error ? err.message : "Failed to send");
+ console.error('Webhook send failed:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to send');
} finally {
setSendingId(null);
}
@@ -268,12 +276,12 @@ export default function ContentPage() {
const handleDismiss = async (id: string) => {
try {
- await updateOpportunityStatus(id, "dismissed");
- toast.success("Opportunity dismissed");
+ await updateOpportunityStatus(id, 'dismissed');
+ toast.success('Opportunity dismissed');
await loadData();
} catch (err) {
- console.error("Dismiss failed:", err);
- toast.error("Failed to dismiss");
+ console.error('Dismiss failed:', err);
+ toast.error('Failed to dismiss');
}
};
@@ -286,7 +294,7 @@ export default function ContentPage() {
setSelectedIds(new Set());
await loadData();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Bulk send failed");
+ toast.error(err instanceof Error ? err.message : 'Bulk send failed');
} finally {
setBulkSending(false);
}
@@ -296,29 +304,30 @@ export default function ContentPage() {
setBulkSending(true);
try {
const ids = Array.from(selectedIds);
- const result = await bulkUpdateStatus(ids, "dismissed");
+ const result = await bulkUpdateStatus(ids, 'dismissed');
toast.success(`Dismissed ${result.updated} opportunities`);
setSelectedIds(new Set());
await loadData();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Bulk dismiss failed");
+ toast.error(err instanceof Error ? err.message : 'Bulk dismiss failed');
} finally {
setBulkSending(false);
}
};
- const filtered = opportunities.filter((o) =>
- o.title.toLowerCase().includes(search.toLowerCase()) ||
- (o.description || "").toLowerCase().includes(search.toLowerCase()),
+ const filtered = opportunities.filter(
+ (o) =>
+ o.title.toLowerCase().includes(search.toLowerCase()) ||
+ (o.description || '').toLowerCase().includes(search.toLowerCase()),
);
- const highImpact = opportunities.filter((o) => o.impact === "high").length;
- const sentCount = opportunities.filter((o) => o.status === "sent" || o.status === "in_progress" || o.status === "done").length;
+ const highImpact = opportunities.filter((o) => o.impact === 'high').length;
+ const sentCount = opportunities.filter(
+ (o) => o.status === 'sent' || o.status === 'in_progress' || o.status === 'done',
+ ).length;
const avgScore =
opportunities.length > 0
- ? Math.round(
- opportunities.reduce((s, o) => s + o.opportunityScore, 0) / opportunities.length,
- )
+ ? Math.round(opportunities.reduce((s, o) => s + o.opportunityScore, 0) / opportunities.length)
: 0;
if (!activeBrandId) {
@@ -333,8 +342,8 @@ export default function ContentPage() {
<div className="space-y-6">
<div className="flex items-center justify-between gap-4 flex-wrap">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground text-sm">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground text-sm">{t('description')}</p>
</div>
<div className="flex items-center gap-2">
<Button
@@ -344,7 +353,7 @@ export default function ContentPage() {
className="gap-2"
>
<Settings2 className="h-4 w-4" />
- {t("webhook.title")}
+ {t('webhook.title')}
</Button>
{!isCloud && (
<Button
@@ -361,10 +370,10 @@ export default function ContentPage() {
<Lightbulb className="h-4 w-4" />
)}
{generating
- ? t("generating")
+ ? t('generating')
: opportunities.length > 0
- ? t("regenerate")
- : t("generate")}
+ ? t('regenerate')
+ : t('generate')}
</Button>
)}
</div>
@@ -379,10 +388,8 @@ export default function ContentPage() {
<CardContent className="flex flex-col items-center justify-center py-16 gap-4">
<Lightbulb className="h-12 w-12 text-muted-foreground/40" />
<div className="text-center space-y-1">
- <p className="text-sm font-medium">{t("noOpportunities")}</p>
- <p className="text-xs text-muted-foreground">
- {t("noOpportunitiesHint")}
- </p>
+ <p className="text-sm font-medium">{t('noOpportunities')}</p>
+ <p className="text-xs text-muted-foreground">{t('noOpportunitiesHint')}</p>
</div>
<Button onClick={handleGenerate} disabled={generating} size="sm" className="gap-2">
{generating ? (
@@ -390,7 +397,7 @@ export default function ContentPage() {
) : (
<Lightbulb className="h-4 w-4" />
)}
- {generating ? t("generating") : t("generate")}
+ {generating ? t('generating') : t('generate')}
</Button>
</CardContent>
</Card>
@@ -398,39 +405,35 @@ export default function ContentPage() {
<>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
<KpiCard
- title={t("kpi.total")}
+ title={t('kpi.total')}
icon={Lightbulb}
value={total}
sub={`${filtered.length} shown`}
/>
<KpiCard
- title={t("kpi.highImpact")}
+ title={t('kpi.highImpact')}
icon={Zap}
value={highImpact}
sub="opportunities"
/>
<KpiCard
- title={t("kpi.sentToWorkflow")}
+ title={t('kpi.sentToWorkflow')}
icon={Send}
value={sentCount}
sub="sent or in progress"
/>
- <KpiCard
- title={t("kpi.avgScore")}
- icon={BarChart3}
- value={avgScore}
- sub="out of 100"
- />
+ <KpiCard title={t('kpi.avgScore')} icon={BarChart3} value={avgScore} sub="out of 100" />
</div>
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between gap-4 flex-wrap">
<div className="flex items-center gap-2">
- <CardTitle className="text-sm font-medium">
- {t("opportunities")}
- </CardTitle>
- <Badge variant="outline" className="text-xs border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
+ <CardTitle className="text-sm font-medium">{t('opportunities')}</CardTitle>
+ <Badge
+ variant="outline"
+ className="text-xs border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
+ >
{total} Available
</Badge>
</div>
@@ -449,12 +452,12 @@ export default function ContentPage() {
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="all">{t("filters.allStatuses")}</SelectItem>
- <SelectItem value="new">{t("status.new")}</SelectItem>
- <SelectItem value="sent">{t("status.sent")}</SelectItem>
- <SelectItem value="in_progress">{t("status.in_progress")}</SelectItem>
- <SelectItem value="done">{t("status.done")}</SelectItem>
- <SelectItem value="dismissed">{t("status.dismissed")}</SelectItem>
+ <SelectItem value="all">{t('filters.allStatuses')}</SelectItem>
+ <SelectItem value="new">{t('status.new')}</SelectItem>
+ <SelectItem value="sent">{t('status.sent')}</SelectItem>
+ <SelectItem value="in_progress">{t('status.in_progress')}</SelectItem>
+ <SelectItem value="done">{t('status.done')}</SelectItem>
+ <SelectItem value="dismissed">{t('status.dismissed')}</SelectItem>
</SelectContent>
</Select>
<Select value={impactFilter} onValueChange={(v) => v && setImpactFilter(v)}>
@@ -462,10 +465,10 @@ export default function ContentPage() {
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="all">{t("filters.allImpacts")}</SelectItem>
- <SelectItem value="high">{t("impact.high")}</SelectItem>
- <SelectItem value="medium">{t("impact.medium")}</SelectItem>
- <SelectItem value="low">{t("impact.low")}</SelectItem>
+ <SelectItem value="all">{t('filters.allImpacts')}</SelectItem>
+ <SelectItem value="high">{t('impact.high')}</SelectItem>
+ <SelectItem value="medium">{t('impact.medium')}</SelectItem>
+ <SelectItem value="low">{t('impact.low')}</SelectItem>
</SelectContent>
</Select>
<Select value={typeFilter} onValueChange={(v) => v && setTypeFilter(v)}>
@@ -473,9 +476,9 @@ export default function ContentPage() {
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="all">{t("filters.allTypes")}</SelectItem>
- <SelectItem value="owned">{t("type.owned")}</SelectItem>
- <SelectItem value="earned">{t("type.earned")}</SelectItem>
+ <SelectItem value="all">{t('filters.allTypes')}</SelectItem>
+ <SelectItem value="owned">{t('type.owned')}</SelectItem>
+ <SelectItem value="earned">{t('type.earned')}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -484,7 +487,7 @@ export default function ContentPage() {
{selectedIds.size > 0 && (
<div className="flex items-center gap-2 border-b bg-muted/50 px-4 py-2">
<span className="text-xs text-muted-foreground">
- {t("bulk.selected", { count: selectedIds.size })}
+ {t('bulk.selected', { count: selectedIds.size })}
</span>
<div className="flex items-center gap-1 ml-auto">
<Button
@@ -499,7 +502,7 @@ export default function ContentPage() {
) : (
<Send className="h-3 w-3" />
)}
- {t("bulk.sendAll")}
+ {t('bulk.sendAll')}
</Button>
<Button
variant="outline"
@@ -509,7 +512,7 @@ export default function ContentPage() {
disabled={bulkSending}
>
<X className="h-3 w-3" />
- {t("bulk.dismissAll")}
+ {t('bulk.dismissAll')}
</Button>
</div>
</div>
@@ -520,27 +523,22 @@ export default function ContentPage() {
<TableRow>
<TableHead className="w-10 pl-4">
<Checkbox
- checked={
- filtered.length > 0 &&
- selectedIds.size === filtered.length
- }
+ checked={filtered.length > 0 && selectedIds.size === filtered.length}
onCheckedChange={(checked) => {
if (checked) {
- setSelectedIds(
- new Set(filtered.map((o) => o.id))
- );
+ setSelectedIds(new Set(filtered.map((o) => o.id)));
} else {
setSelectedIds(new Set());
}
}}
/>
</TableHead>
- <TableHead className="pl-6 w-[40%]">{t("table.action")}</TableHead>
- <TableHead className="text-center">{t("table.type")}</TableHead>
- <TableHead className="text-center">{t("table.impact")}</TableHead>
- <TableHead className="text-center">{t("table.score")}</TableHead>
- <TableHead className="text-center">{t("table.status")}</TableHead>
- <TableHead className="text-right pr-6">{t("table.actions")}</TableHead>
+ <TableHead className="pl-6 w-[40%]">{t('table.action')}</TableHead>
+ <TableHead className="text-center">{t('table.type')}</TableHead>
+ <TableHead className="text-center">{t('table.impact')}</TableHead>
+ <TableHead className="text-center">{t('table.score')}</TableHead>
+ <TableHead className="text-center">{t('table.status')}</TableHead>
+ <TableHead className="text-right pr-6">{t('table.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -562,9 +560,7 @@ export default function ContentPage() {
href={`/dashboard/content/${opp.id}`}
className="block hover:underline"
>
- <p className="text-sm font-medium line-clamp-1">
- {opp.title}
- </p>
+ <p className="text-sm font-medium line-clamp-1">{opp.title}</p>
{opp.description && (
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
{opp.description}
@@ -574,15 +570,20 @@ export default function ContentPage() {
</TableCell>
<TableCell className="text-center">
<Badge variant="outline" className="text-xs">
- {t(`type.${opp.type}` as "type.owned" | "type.earned")}
+ {t(`type.${opp.type}` as 'type.owned' | 'type.earned')}
</Badge>
</TableCell>
<TableCell className="text-center">
<Badge
variant="outline"
- className={cn("text-xs", IMPACT_COLORS[opp.impact])}
+ className={cn('text-xs', IMPACT_COLORS[opp.impact])}
>
- {t(`impact.${opp.impact}` as "impact.high" | "impact.medium" | "impact.low")}
+ {t(
+ `impact.${opp.impact}` as
+ | 'impact.high'
+ | 'impact.medium'
+ | 'impact.low',
+ )}
</Badge>
</TableCell>
<TableCell className="text-center">
@@ -593,14 +594,14 @@ export default function ContentPage() {
<TableCell className="text-center">
<Badge
variant="outline"
- className={cn("text-xs whitespace-nowrap", STATUS_COLORS[opp.status])}
+ className={cn('text-xs whitespace-nowrap', STATUS_COLORS[opp.status])}
>
{t(`status.${opp.status}` as `status.${ContentOpportunityStatus}`)}
</Badge>
</TableCell>
<TableCell className="text-right pr-6">
<div className="flex items-center justify-end gap-1">
- {opp.status === "new" && (
+ {opp.status === 'new' && (
<>
<Button
variant="ghost"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/[id]/page.tsx
index ef230d1e6..2c69e96b4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/[id]/page.tsx
@@ -3,23 +3,13 @@
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { useRouter } from '@/i18n/navigation';
-import {
- getPromptResultById,
- type PromptResultWithText,
-} from '@/lib/actions/tracking';
+import { getPromptResultById, type PromptResultWithText } from '@/lib/actions/tracking';
import { Markdown } from '@/components/ui/markdown';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
-import {
- ArrowLeft,
- ExternalLink,
- MessageSquareText,
- Quote,
- Eye,
- Clock,
-} from 'lucide-react';
+import { ArrowLeft, ExternalLink, MessageSquareText, Quote, Eye, Clock } from 'lucide-react';
import { cn } from '@/lib/utils';
const PLATFORM_LABELS: Record<string, string> = {
@@ -41,11 +31,7 @@ const PLATFORM_LABELS: Record<string, string> = {
'gemini-web': 'Gemini',
};
-function SentimentBadge({
- sentiment,
-}: {
- sentiment: 'positive' | 'neutral' | 'negative';
-}) {
+function SentimentBadge({ sentiment }: { sentiment: 'positive' | 'neutral' | 'negative' }) {
return (
<Badge
variant="outline"
@@ -110,11 +96,7 @@ export default function ResultDetailPage() {
<p className="text-muted-foreground text-sm mt-1">
This result may have been deleted or does not exist.
</p>
- <Button
- variant="outline"
- className="mt-6 gap-2"
- onClick={() => router.back()}
- >
+ <Button variant="outline" className="mt-6 gap-2" onClick={() => router.back()}>
<ArrowLeft className="h-4 w-4" />
Go back
</Button>
@@ -137,9 +119,7 @@ export default function ResultDetailPage() {
{/* Header */}
<div className="space-y-3">
- <h1 className="text-xl font-semibold leading-snug">
- {result.promptText}
- </h1>
+ <h1 className="text-xl font-semibold leading-snug">{result.promptText}</h1>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary" className="text-xs">
@@ -164,9 +144,7 @@ export default function ResultDetailPage() {
<CardContent className="flex items-center gap-3 p-4">
<MessageSquareText className="h-5 w-5 text-muted-foreground" />
<div>
- <p className="text-2xl font-bold tabular-nums">
- {result.mentionCount}
- </p>
+ <p className="text-2xl font-bold tabular-nums">{result.mentionCount}</p>
<p className="text-xs text-muted-foreground">Mentions</p>
</div>
</CardContent>
@@ -175,9 +153,7 @@ export default function ResultDetailPage() {
<CardContent className="flex items-center gap-3 p-4">
<Quote className="h-5 w-5 text-muted-foreground" />
<div>
- <p className="text-2xl font-bold tabular-nums">
- {result.citationCount}
- </p>
+ <p className="text-2xl font-bold tabular-nums">{result.citationCount}</p>
<p className="text-xs text-muted-foreground">Brand Citations</p>
</div>
</CardContent>
@@ -186,9 +162,7 @@ export default function ResultDetailPage() {
<CardContent className="flex items-center gap-3 p-4">
<ExternalLink className="h-5 w-5 text-muted-foreground" />
<div>
- <p className="text-2xl font-bold tabular-nums">
- {result.citations.length}
- </p>
+ <p className="text-2xl font-bold tabular-nums">{result.citations.length}</p>
<p className="text-xs text-muted-foreground">Total Citations</p>
</div>
</CardContent>
@@ -209,9 +183,7 @@ export default function ResultDetailPage() {
{result.citations.length > 0 && (
<Card>
<CardContent className="p-6">
- <h2 className="text-sm font-medium mb-4">
- Citations ({result.citations.length})
- </h2>
+ <h2 className="text-sm font-medium mb-4">Citations ({result.citations.length})</h2>
<div className="space-y-2">
{result.citations.map((cite, i) => (
<a
@@ -223,12 +195,8 @@ export default function ResultDetailPage() {
>
<ExternalLink className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" />
<div className="min-w-0">
- <p className="font-medium truncate">
- {cite.title || cite.url}
- </p>
- <p className="text-muted-foreground text-xs truncate">
- {cite.url}
- </p>
+ <p className="font-medium truncate">{cite.title || cite.url}</p>
+ <p className="text-muted-foreground text-xs truncate">{cite.url}</p>
</div>
</a>
))}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
index 10665b5d3..c6e3e29ce 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
@@ -143,9 +143,7 @@ function AreaTooltip({
className="inline-block h-2 w-2 rounded-full shrink-0"
style={{ backgroundColor: entry.color }}
/>
- <span className="text-muted-foreground capitalize">
- {entry.name}:
- </span>
+ <span className="text-muted-foreground capitalize">{entry.name}:</span>
<span className="font-medium text-foreground">{entry.value}</span>
</div>
))}
@@ -183,19 +181,13 @@ function PieTooltip({
// ─── Bar List ─────────────────────────────────────────────────────────────────
-function BarList({
- data,
-}: {
- data: { name: string; value: number; color: string }[];
-}) {
+function BarList({ data }: { data: { name: string; value: number; color: string }[] }) {
const max = 100;
return (
<div className="w-full space-y-2">
{data.map((item) => (
<div key={item.name} className="flex items-center gap-2 text-xs">
- <span className="w-20 shrink-0 text-muted-foreground truncate">
- {item.name}
- </span>
+ <span className="w-20 shrink-0 text-muted-foreground truncate">{item.name}</span>
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full transition-all"
@@ -246,11 +238,7 @@ export function TrendChart({ data }: { data: VisibilityTrendPoint[] }) {
<stop offset="95%" stopColor="#94a3b8" stopOpacity={0} />
</linearGradient>
</defs>
- <CartesianGrid
- strokeDasharray="3 3"
- className="stroke-border"
- vertical={false}
- />
+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />
<XAxis
dataKey="date"
tick={{ fontSize: 11 }}
@@ -266,11 +254,7 @@ export function TrendChart({ data }: { data: VisibilityTrendPoint[] }) {
domain={[0, 100]}
/>
<Tooltip content={<AreaTooltip />} />
- <Legend
- iconType="circle"
- iconSize={8}
- wrapperStyle={{ fontSize: 11, paddingTop: 8 }}
- />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
<Area
type="monotone"
dataKey="score"
@@ -345,8 +329,7 @@ export function PlatformChart({
paddingAngle={2}
dataKey="value"
onMouseEnter={(_, index) => {
- if (!chartData[index].isRemainder)
- setHovered(chartData[index].name);
+ if (!chartData[index].isRemainder) setHovered(chartData[index].name);
}}
onMouseLeave={() => setHovered(null)}
>
@@ -355,11 +338,7 @@ export function PlatformChart({
key={entry.name}
fill={entry.isRemainder ? 'hsl(var(--muted))' : entry.color}
opacity={
- entry.isRemainder
- ? 0.4
- : hovered === null || hovered === entry.name
- ? 1
- : 0.4
+ entry.isRemainder ? 0.4 : hovered === null || hovered === entry.name ? 1 : 0.4
}
stroke="none"
/>
@@ -432,9 +411,7 @@ export function CompetitorChart({
// pick a sensible upper bound. See niceVisibilityYMax for the rules.
const yMax = niceVisibilityYMax(
providerRows.flatMap((row) =>
- brandNames
- .map((name) => row[name])
- .filter((v): v is number => typeof v === 'number'),
+ brandNames.map((name) => row[name]).filter((v): v is number => typeof v === 'number'),
),
);
@@ -449,11 +426,7 @@ export function CompetitorChart({
barGap={2}
barCategoryGap="20%"
>
- <CartesianGrid
- strokeDasharray="3 3"
- className="stroke-border"
- vertical={false}
- />
+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />
<XAxis
dataKey="provider"
tick={{ fontSize: 11 }}
@@ -469,15 +442,8 @@ export function CompetitorChart({
domain={[0, yMax]}
tickFormatter={(v: number) => `${v}%`}
/>
- <Tooltip
- content={<CompetitorTooltip />}
- cursor={{ fill: 'hsl(var(--muted) / 0.3)' }}
- />
- <Legend
- iconType="circle"
- iconSize={8}
- wrapperStyle={{ fontSize: 11, paddingTop: 8 }}
- />
+ <Tooltip content={<CompetitorTooltip />} cursor={{ fill: 'hsl(var(--muted) / 0.3)' }} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
{brandNames.map((name, i) => (
<Bar
key={`${name}-${i}`}
@@ -494,13 +460,7 @@ export function CompetitorChart({
const MAX_VISIBLE = 5;
-function LeaderboardEntry({
- entry,
- rank,
-}: {
- entry: CompetitorComparisonEntry;
- rank: number;
-}) {
+function LeaderboardEntry({ entry, rank }: { entry: CompetitorComparisonEntry; rank: number }) {
return (
<div
className={`flex items-center gap-3 rounded-lg border px-3 py-2.5 ${
@@ -513,9 +473,7 @@ function LeaderboardEntry({
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium truncate">{entry.name}</span>
- {entry.isOwnBrand && (
- <span className="text-[10px] font-medium text-primary">YOU</span>
- )}
+ {entry.isOwnBrand && <span className="text-[10px] font-medium text-primary">YOU</span>}
</div>
<div className="flex items-center gap-3 text-xs text-muted-foreground mt-0.5">
<span>{entry.totalMentions} mentions</span>
@@ -523,9 +481,7 @@ function LeaderboardEntry({
</div>
</div>
<div className="flex flex-col items-end gap-0.5 shrink-0">
- <span className="text-sm font-semibold tabular-nums">
- {entry.avgVisibilityScore}%
- </span>
+ <span className="text-sm font-semibold tabular-nums">{entry.avgVisibilityScore}%</span>
{entry.change !== null && entry.change !== 0 && (
<span
className={`text-[10px] font-medium tabular-nums ${
@@ -536,46 +492,35 @@ function LeaderboardEntry({
</span>
)}
{entry.change === 0 && (
- <span className="text-[10px] font-medium tabular-nums text-muted-foreground">
- — 0%
- </span>
+ <span className="text-[10px] font-medium tabular-nums text-muted-foreground">— 0%</span>
)}
</div>
</div>
);
}
-export function CompetitorLeaderboard({
- data,
-}: {
- data: CompetitorComparisonEntry[];
-}) {
+export function CompetitorLeaderboard({ data }: { data: CompetitorComparisonEntry[] }) {
const [expanded, setExpanded] = useState(false);
const needsTruncation = data.length > MAX_VISIBLE;
- const visibleEntries: { entry: CompetitorComparisonEntry; rank: number }[] =
- (() => {
- if (!needsTruncation || expanded) {
- return data.map((entry, i) => ({ entry, rank: i + 1 }));
- }
-
- const ownBrandIdx = data.findIndex((e) => e.isOwnBrand);
- const ownBrandInTop = ownBrandIdx >= 0 && ownBrandIdx < MAX_VISIBLE - 1;
-
- if (ownBrandInTop || ownBrandIdx < 0) {
- return data
- .slice(0, MAX_VISIBLE)
- .map((entry, i) => ({ entry, rank: i + 1 }));
- }
-
- // Show top 4 + own brand at its actual rank
- const top = data
- .slice(0, MAX_VISIBLE - 1)
- .map((entry, i) => ({ entry, rank: i + 1 }));
- top.push({ entry: data[ownBrandIdx], rank: ownBrandIdx + 1 });
- return top;
- })();
+ const visibleEntries: { entry: CompetitorComparisonEntry; rank: number }[] = (() => {
+ if (!needsTruncation || expanded) {
+ return data.map((entry, i) => ({ entry, rank: i + 1 }));
+ }
+
+ const ownBrandIdx = data.findIndex((e) => e.isOwnBrand);
+ const ownBrandInTop = ownBrandIdx >= 0 && ownBrandIdx < MAX_VISIBLE - 1;
+
+ if (ownBrandInTop || ownBrandIdx < 0) {
+ return data.slice(0, MAX_VISIBLE).map((entry, i) => ({ entry, rank: i + 1 }));
+ }
+
+ // Show top 4 + own brand at its actual rank
+ const top = data.slice(0, MAX_VISIBLE - 1).map((entry, i) => ({ entry, rank: i + 1 }));
+ top.push({ entry: data[ownBrandIdx], rank: ownBrandIdx + 1 });
+ return top;
+ })();
return (
<div className="space-y-2">
@@ -639,18 +584,13 @@ export function ShareOfVoicePlatformChart({
fill: palette[index % palette.length],
voiceMentions: d.brandMentions + d.competitorMentions,
}));
- const totalVoiceMentions = chartData.reduce(
- (sum, d) => sum + d.voiceMentions,
- 0,
- );
+ const totalVoiceMentions = chartData.reduce((sum, d) => sum + d.voiceMentions, 0);
return (
<div className="flex flex-col gap-4">
<div className="text-center">
<div className="text-4xl font-bold tabular-nums">{overallSov}%</div>
- <div className="text-xs text-muted-foreground mt-0.5">
- Overall Share of Voice
- </div>
+ <div className="text-xs text-muted-foreground mt-0.5">Overall Share of Voice</div>
</div>
<ChartContainer height={200}>
@@ -681,15 +621,12 @@ export function ShareOfVoicePlatformChart({
voiceMentions: number;
};
const platformShare =
- totalVoiceMentions > 0
- ? (p.voiceMentions / totalVoiceMentions) * 100
- : 0;
+ totalVoiceMentions > 0 ? (p.voiceMentions / totalVoiceMentions) * 100 : 0;
return (
<div className="rounded-md border bg-popover px-2.5 py-1.5 text-xs shadow-sm">
<div className="font-medium">{p.provider}</div>
<div className="text-muted-foreground">
- {p.sov.toFixed(1)}% SoV · {platformShare.toFixed(1)}% of
- voice
+ {p.sov.toFixed(1)}% SoV · {platformShare.toFixed(1)}% of voice
</div>
</div>
);
@@ -709,9 +646,7 @@ export function ShareOfVoicePlatformChart({
aria-hidden
/>
<span className="truncate text-foreground">{d.provider}</span>
- <span className="ml-auto tabular-nums text-muted-foreground">
- {d.sov.toFixed(1)}%
- </span>
+ <span className="ml-auto tabular-nums text-muted-foreground">{d.sov.toFixed(1)}%</span>
</li>
))}
</ul>
@@ -776,11 +711,7 @@ export function ShareOfVoiceTrendChart({ data }: { data: SoVTrendPoint[] }) {
<stop offset="95%" stopColor="#94a3b8" stopOpacity={0} />
</linearGradient>
</defs>
- <CartesianGrid
- strokeDasharray="3 3"
- className="stroke-border"
- vertical={false}
- />
+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />
<XAxis
dataKey="date"
tick={{ fontSize: 11 }}
@@ -797,11 +728,7 @@ export function ShareOfVoiceTrendChart({ data }: { data: SoVTrendPoint[] }) {
tickFormatter={(v: number) => `${v}%`}
/>
<Tooltip content={<SoVTrendTooltip />} />
- <Legend
- iconType="circle"
- iconSize={8}
- wrapperStyle={{ fontSize: 11, paddingTop: 8 }}
- />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
<Area
type="monotone"
dataKey="brandSov"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
index a5b697130..d40fc2fad 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
@@ -44,12 +44,7 @@ interface Props {
};
}
-export function MetricBreakdownSheet({
- brandId,
- metric,
- onOpenChange,
- filters,
-}: Props) {
+export function MetricBreakdownSheet({ brandId, metric, onOpenChange, filters }: Props) {
const open = Boolean(brandId && metric);
const [data, setData] = useState<InsightsBreakdown | null>(null);
const [loading, setLoading] = useState(false);
@@ -57,10 +52,7 @@ export function MetricBreakdownSheet({
// Filters is passed as a fresh object each render from the parent — derive a
// stable cache key so the fetch effect doesn't re-run needlessly.
- const filtersKey = useMemo(
- () => JSON.stringify(filters ?? {}),
- [filters],
- );
+ const filtersKey = useMemo(() => JSON.stringify(filters ?? {}), [filters]);
useEffect(() => {
if (!open || !brandId || !metric) {
@@ -99,9 +91,7 @@ export function MetricBreakdownSheet({
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="w-full flex flex-col gap-0 p-0 sm:max-w-xl">
<SheetHeader className="border-b px-5 py-4">
- <SheetTitle className="text-base">
- {title} Breakdown
- </SheetTitle>
+ <SheetTitle className="text-base">{title} Breakdown</SheetTitle>
<SheetDescription className="text-xs">
{data
? `Last ${data.windowDays} days vs previous ${data.windowDays} days`
@@ -119,9 +109,7 @@ export function MetricBreakdownSheet({
</div>
)}
- {!loading && !error && data && metric && (
- <BreakdownBody data={data} metric={metric} />
- )}
+ {!loading && !error && data && metric && <BreakdownBody data={data} metric={metric} />}
</div>
</SheetContent>
</Sheet>
@@ -141,19 +129,11 @@ function BreakdownSkeleton() {
);
}
-function BreakdownBody({
- data,
- metric,
-}: {
- data: InsightsBreakdown;
- metric: BreakdownMetric;
-}) {
+function BreakdownBody({ data, metric }: { data: InsightsBreakdown; metric: BreakdownMetric }) {
const [tab, setTab] = useState<'prompts' | 'platforms' | 'topics'>('prompts');
const pickRows = () =>
- tab === 'prompts' ? data.byPrompt
- : tab === 'platforms' ? data.byPlatform
- : data.byTopic;
+ tab === 'prompts' ? data.byPrompt : tab === 'platforms' ? data.byPlatform : data.byTopic;
return (
<div className="space-y-4">
@@ -178,12 +158,7 @@ function BreakdownBody({
</span>
</div>
</div>
- <DeltaPill
- delta={data.delta}
- deltaPct={data.deltaPct}
- metric={metric}
- big
- />
+ <DeltaPill delta={data.delta} deltaPct={data.deltaPct} metric={metric} big />
</div>
<RootCauseSummary data={data} metric={metric} />
</div>
@@ -219,31 +194,18 @@ function BreakdownBody({
);
}
-function RootCauseSummary({
- data,
- metric,
-}: {
- data: InsightsBreakdown;
- metric: BreakdownMetric;
-}) {
+function RootCauseSummary({ data, metric }: { data: InsightsBreakdown; metric: BreakdownMetric }) {
const isDrop = data.delta < 0;
const isFlat = data.delta === 0;
- const topPrompt = isDrop
- ? data.byPrompt[0]
- : data.byPrompt[data.byPrompt.length - 1];
- const topPlatform = isDrop
- ? data.byPlatform[0]
- : data.byPlatform[data.byPlatform.length - 1];
- const promptContributes =
- !!topPrompt && (isDrop ? topPrompt.delta < 0 : topPrompt.delta > 0);
+ const topPrompt = isDrop ? data.byPrompt[0] : data.byPrompt[data.byPrompt.length - 1];
+ const topPlatform = isDrop ? data.byPlatform[0] : data.byPlatform[data.byPlatform.length - 1];
+ const promptContributes = !!topPrompt && (isDrop ? topPrompt.delta < 0 : topPrompt.delta > 0);
const platformContributes =
!!topPlatform && (isDrop ? topPlatform.delta < 0 : topPlatform.delta > 0);
if (isFlat || !promptContributes || !topPrompt) {
return (
- <div className="mt-2 text-xs text-muted-foreground leading-relaxed">
- {data.rootCause}
- </div>
+ <div className="mt-2 text-xs text-muted-foreground leading-relaxed">{data.rootCause}</div>
);
}
@@ -259,7 +221,8 @@ function RootCauseSummary({
{formatContribution(topPrompt, metric)}.
{platformContributes && topPlatform && (
<>
- {' '}Top platform {isDrop ? 'drop' : 'gain'}: {topPlatform.label}{' '}
+ {' '}
+ Top platform {isDrop ? 'drop' : 'gain'}: {topPlatform.label}{' '}
{formatContribution(topPlatform, metric)}.
</>
)}
@@ -310,23 +273,15 @@ function BreakdownTable({
<div className="line-clamp-2 text-sm">{r.label}</div>
)}
{r.sublabel && (
- <div className="mt-0.5 text-[11px] text-muted-foreground">
- {r.sublabel}
- </div>
+ <div className="mt-0.5 text-[11px] text-muted-foreground">{r.sublabel}</div>
)}
</td>
<td className="px-2 py-2 text-right tabular-nums text-muted-foreground">
{formatValue(r.prev, metric)}
</td>
- <td className="px-2 py-2 text-right tabular-nums">
- {formatValue(r.cur, metric)}
- </td>
+ <td className="px-2 py-2 text-right tabular-nums">{formatValue(r.cur, metric)}</td>
<td className="px-2 py-2 text-right">
- <DeltaPill
- delta={r.delta}
- deltaPct={r.deltaPct}
- metric={metric}
- />
+ <DeltaPill delta={r.delta} deltaPct={r.deltaPct} metric={metric} />
</td>
</tr>
))}
@@ -362,9 +317,7 @@ function DeltaPill({
const positive = delta > 0;
const Icon = positive ? TrendingUp : TrendingDown;
- const color = positive
- ? 'text-green-600 dark:text-green-400'
- : 'text-red-500';
+ const color = positive ? 'text-green-600 dark:text-green-400' : 'text-red-500';
// Prefer percentage display for count metrics when available; fall back to
// absolute delta for visibility (pts) or when previous was zero.
@@ -388,12 +341,7 @@ function DeltaPill({
<Icon className={big ? 'h-3.5 w-3.5' : 'h-3 w-3'} />
<span>{primary}</span>
{secondary && (
- <span
- className={cn(
- 'font-normal text-muted-foreground',
- big ? 'text-xs' : 'text-[10px]',
- )}
- >
+ <span className={cn('font-normal text-muted-foreground', big ? 'text-xs' : 'text-[10px]')}>
({secondary})
</span>
)}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 9f700b54b..856bed0e3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -4,7 +4,12 @@ import { useState, useRef, useEffect, useCallback } from 'react';
import { useRouter } from '@/i18n/navigation';
import { useSearchParams } from 'next/navigation';
import { createPortal } from 'react-dom';
-import { CompetitorChart, CompetitorLeaderboard, ShareOfVoicePlatformChart, ShareOfVoiceTrendChart } from './_charts';
+import {
+ CompetitorChart,
+ CompetitorLeaderboard,
+ ShareOfVoicePlatformChart,
+ ShareOfVoiceTrendChart,
+} from './_charts';
import { MetricBreakdownSheet } from './_metric-breakdown-sheet';
import { useBrandStore } from '@/stores/use-brand-store';
import {
@@ -28,18 +33,8 @@ import type { Topic } from '@/types';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog';
-import {
- Table,
- TableBody,
- TableCell,
- TableRow,
-} from '@/components/ui/table';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import {
BarChart3,
@@ -122,10 +117,7 @@ const INSIGHT_EXPORT_HEADERS = [
* "previous runs" history inside each platform group has meaningful depth. */
const PROMPT_RESULTS_ROW_LIMIT = 1500;
-function getDateRange(
- preset: DatePreset,
- custom: { from: string; to: string },
-) {
+function getDateRange(preset: DatePreset, custom: { from: string; to: string }) {
if (preset === 'all') return { dateFrom: undefined, dateTo: undefined };
if (preset === 'custom') {
return {
@@ -181,11 +173,7 @@ function InfoTip({ content }: { content: string }) {
// ─── Sub-components ───────────────────────────────────────────────────────────
-function SentimentBadge({
- sentiment,
-}: {
- sentiment: 'positive' | 'neutral' | 'negative';
-}) {
+function SentimentBadge({ sentiment }: { sentiment: 'positive' | 'neutral' | 'negative' }) {
return (
<Badge
variant="outline"
@@ -212,11 +200,7 @@ function VisibilityBar({ score, max = 100 }: { score: number; max?: number }) {
<div
className={cn(
'h-full rounded-full transition-all',
- score >= 60
- ? 'bg-green-500'
- : score >= 40
- ? 'bg-yellow-500'
- : 'bg-red-500',
+ score >= 60 ? 'bg-green-500' : score >= 40 ? 'bg-yellow-500' : 'bg-red-500',
)}
style={{ width: `${pct}%` }}
/>
@@ -337,9 +321,7 @@ function groupResultsByPlatform(items: PromptResultWithText[]): PlatformGroup[]
latest,
latestScore: latest.visibilityScore,
avgScore:
- Math.round(
- (sorted.reduce((s, r) => s + r.visibilityScore, 0) / sorted.length) * 10,
- ) / 10,
+ Math.round((sorted.reduce((s, r) => s + r.visibilityScore, 0) / sorted.length) * 10) / 10,
totalMentions: sorted.reduce((s, r) => s + r.mentionCount, 0),
totalCitations: sorted.reduce((s, r) => s + r.citationCount, 0),
} satisfies PlatformGroup;
@@ -357,9 +339,7 @@ function computePromptGroup(promptId: string, items: PromptResultWithText[]): Pr
promptCategory: sorted[0].promptCategory,
results: sorted,
platformGroups: groupResultsByPlatform(sorted),
- avgScore: Math.round(
- sorted.reduce((s, r) => s + r.visibilityScore, 0) / sorted.length,
- ),
+ avgScore: Math.round(sorted.reduce((s, r) => s + r.visibilityScore, 0) / sorted.length),
totalMentions: sorted.reduce((s, r) => s + r.mentionCount, 0),
totalCitations: sorted.reduce((s, r) => s + r.citationCount, 0),
};
@@ -372,9 +352,7 @@ function groupResultsByPrompt(results: PromptResultWithText[]): PromptGroup[] {
arr.push(r);
map.set(r.promptId, arr);
}
- return Array.from(map.entries()).map(([promptId, items]) =>
- computePromptGroup(promptId, items),
- );
+ return Array.from(map.entries()).map(([promptId, items]) => computePromptGroup(promptId, items));
}
interface TopicGroup {
@@ -411,9 +389,7 @@ function groupResultsByTopic(results: PromptResultWithText[]): TopicGroup[] {
topicId: items[0].topicId ?? `__cat_${topicName}`,
topicName: topicName === '__uncategorized__' ? 'Uncategorized' : topicName,
prompts,
- avgScore: Math.round(
- items.reduce((s, r) => s + r.visibilityScore, 0) / items.length,
- ),
+ avgScore: Math.round(items.reduce((s, r) => s + r.visibilityScore, 0) / items.length),
totalMentions: items.reduce((s, r) => s + r.mentionCount, 0),
totalCitations: items.reduce((s, r) => s + r.citationCount, 0),
totalResults: items.length,
@@ -424,16 +400,9 @@ function groupResultsByTopic(results: PromptResultWithText[]): TopicGroup[] {
// ─── Delta Badge ──────────────────────────────────────────────────────────────
-function DeltaBadge({
- delta,
- suffix = '%',
-}: {
- delta: number | null;
- suffix?: string;
-}) {
+function DeltaBadge({ delta, suffix = '%' }: { delta: number | null; suffix?: string }) {
if (delta === null) return null;
- if (delta === 0)
- return <span className="text-xs text-muted-foreground">— 0{suffix}</span>;
+ if (delta === 0) return <span className="text-xs text-muted-foreground">— 0{suffix}</span>;
const pos = delta > 0;
return (
<span
@@ -442,11 +411,7 @@ function DeltaBadge({
pos ? 'text-green-600 dark:text-green-400' : 'text-red-500',
)}
>
- {pos ? (
- <TrendingUp className="h-3 w-3" />
- ) : (
- <TrendingDown className="h-3 w-3" />
- )}
+ {pos ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
{pos ? '+' : ''}
{delta}
{suffix}
@@ -540,7 +505,6 @@ function KpiCard({
);
}
-
// ─── Run Single Prompt Dialog ─────────────────────────────────────────────────
function RunSinglePromptDialog({
@@ -591,8 +555,7 @@ function RunSinglePromptDialog({
Run Single Prompt
</DialogTitle>
<p className="text-sm text-muted-foreground">
- Pick a prompt to test. Only that prompt will run across your enabled
- platforms.
+ Pick a prompt to test. Only that prompt will run across your enabled platforms.
</p>
</DialogHeader>
@@ -662,34 +625,29 @@ function FilterBar({
availableModels: string[];
availableTopics: Topic[];
}) {
- const set = (patch: Partial<InsightsFilters>) =>
- onChange({ ...filters, ...patch });
+ const set = (patch: Partial<InsightsFilters>) => onChange({ ...filters, ...patch });
return (
<div className="flex flex-wrap items-end gap-3">
{/* Date presets */}
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Date Range
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Date Range</label>
<div className="flex rounded-md border overflow-hidden">
- {(['24h', '7d', '30d', '90d', 'all', 'custom'] as DatePreset[]).map(
- (p) => (
- <button
- key={p}
- type="button"
- onClick={() => set({ datePreset: p })}
- className={cn(
- 'px-3 py-1.5 text-xs font-medium transition-colors',
- filters.datePreset === p
- ? 'bg-primary text-primary-foreground'
- : 'bg-card hover:bg-muted text-foreground',
- )}
- >
- {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}
- </button>
- ),
- )}
+ {(['24h', '7d', '30d', '90d', 'all', 'custom'] as DatePreset[]).map((p) => (
+ <button
+ key={p}
+ type="button"
+ onClick={() => set({ datePreset: p })}
+ className={cn(
+ 'px-3 py-1.5 text-xs font-medium transition-colors',
+ filters.datePreset === p
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-card hover:bg-muted text-foreground',
+ )}
+ >
+ {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}
+ </button>
+ ))}
</div>
</div>
@@ -697,9 +655,7 @@ function FilterBar({
{filters.datePreset === 'custom' && (
<>
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- From
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>
<Input
type="date"
value={filters.dateFrom}
@@ -708,9 +664,7 @@ function FilterBar({
/>
</div>
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- To
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>
<Input
type="date"
value={filters.dateTo}
@@ -724,9 +678,7 @@ function FilterBar({
{/* Topic filter */}
{availableTopics.length > 0 && (
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Topic
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topic</label>
<Select
value={filters.topic || null}
onValueChange={(v) => set({ topic: !v || v === '__all__' ? '' : v })}
@@ -735,7 +687,7 @@ function FilterBar({
<SelectValue placeholder="All Topics">
{(value) =>
value && value !== '__all__'
- ? availableTopics.find((t) => t.id === value)?.name ?? 'All Topics'
+ ? (availableTopics.find((t) => t.id === value)?.name ?? 'All Topics')
: 'All Topics'
}
</SelectValue>
@@ -754,9 +706,7 @@ function FilterBar({
{/* Region filter */}
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Region
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Region</label>
<Select
value={filters.region || null}
onValueChange={(v) => set({ region: !v || v === '__all__' ? '' : v })}
@@ -777,9 +727,7 @@ function FilterBar({
{/* Model filter */}
<div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- AI Model
- </label>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">AI Model</label>
<Select
value={filters.model || null}
onValueChange={(v) => set({ model: !v || v === '__all__' ? '' : v })}
@@ -836,16 +784,16 @@ function InsightsSkeleton() {
<Skeleton className="h-4 w-24" />
<Skeleton className="h-8 w-16" />
<Skeleton className="h-3 w-32" />
- </CardContent>
- </Card>
+ </CardContent>
+ </Card>
))}
</div>
- <Card>
+ <Card>
<CardContent className="pt-6">
<Skeleton className="h-48 w-full" />
- </CardContent>
- </Card>
- </div>
+ </CardContent>
+ </Card>
+ </div>
);
}
@@ -865,20 +813,12 @@ function EmptyState({
<BarChart3 className="h-12 w-12 text-muted-foreground/40 mb-4" />
<h2 className="text-lg font-semibold">No tracking data yet</h2>
<p className="text-muted-foreground text-sm mt-1 max-w-md">
- Run your prompts through AI platforms to see how your brand appears in
- AI-generated responses.
+ Run your prompts through AI platforms to see how your brand appears in AI-generated
+ responses.
</p>
{!isCloud && (
- <Button
- onClick={onRunPrompts}
- disabled={isRunning}
- className="mt-6 gap-2"
- >
- {isRunning ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Play className="h-4 w-4" />
- )}
+ <Button onClick={onRunPrompts} disabled={isRunning} className="mt-6 gap-2">
+ {isRunning ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
Run Prompts Now
</Button>
)}
@@ -886,13 +826,7 @@ function EmptyState({
);
}
-function NoDataForPeriod({
- datePreset,
- onReset,
-}: {
- datePreset: DatePreset;
- onReset: () => void;
-}) {
+function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onReset: () => void }) {
const labels: Record<DatePreset, string> = {
'24h': 'last 24 hours',
'7d': 'last 7 days',
@@ -904,12 +838,10 @@ function NoDataForPeriod({
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<CalendarX2 className="h-10 w-10 text-muted-foreground/40 mb-3" />
- <h3 className="text-base font-semibold">
- No results for the {labels[datePreset]}
- </h3>
+ <h3 className="text-base font-semibold">No results for the {labels[datePreset]}</h3>
<p className="text-muted-foreground text-sm mt-1 max-w-sm">
- There is tracking data available in other time periods. Try a wider
- range or switch to &quot;All time&quot;.
+ There is tracking data available in other time periods. Try a wider range or switch to
+ &quot;All time&quot;.
</p>
<Button variant="outline" size="sm" className="mt-4" onClick={onReset}>
Show all data
@@ -932,14 +864,11 @@ function TrackingProgressBanner({
}) {
if (!jobStatus) return null;
- const isActive =
- jobStatus.status === 'active' || jobStatus.status === 'waiting';
+ const isActive = jobStatus.status === 'active' || jobStatus.status === 'waiting';
if (!isActive) return null;
const progress = jobStatus.progress;
- const pct = progress
- ? Math.round((progress.current / progress.total) * 100)
- : 0;
+ const pct = progress ? Math.round((progress.current / progress.total) * 100) : 0;
return (
<div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 space-y-2">
@@ -1023,9 +952,7 @@ function PlatformSubGroup({
const hasMoreHistory = group.results.length > 1 + HISTORY_LIMIT;
const latest = group.latest;
const responsePreview =
- (latest.response ?? '').trim().length > 0
- ? latest.response
- : 'No response text available.';
+ (latest.response ?? '').trim().length > 0 ? latest.response : 'No response text available.';
return (
<div className="rounded-md border bg-background/50">
@@ -1034,18 +961,25 @@ function PlatformSubGroup({
tabIndex={0}
onClick={onToggle}
onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggle(); }
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onToggle();
+ }
}}
className="flex w-full items-center gap-3 px-3 py-2 hover:bg-muted/40 transition-colors cursor-pointer select-none"
>
- <ChevronDown className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform', !expanded && '-rotate-90')} />
+ <ChevronDown
+ className={cn(
+ 'h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform',
+ !expanded && '-rotate-90',
+ )}
+ />
<div className="flex-1 min-w-0 flex items-center gap-2">
- <ModelBadge
- model={latest.modelUsed ?? latest.platform}
- platform={latest.platform}
- />
+ <ModelBadge model={latest.modelUsed ?? latest.platform} platform={latest.platform} />
{latest.region && (
- <Badge variant="outline" className="text-[10px]">{latest.region}</Badge>
+ <Badge variant="outline" className="text-[10px]">
+ {latest.region}
+ </Badge>
)}
<span className="text-[10px] text-muted-foreground tabular-nums ml-1">
{group.results.length} run{group.results.length !== 1 ? 's' : ''}
@@ -1078,7 +1012,10 @@ function PlatformSubGroup({
variant="ghost"
size="sm"
className="h-6 gap-1.5 text-[11px]"
- onClick={(e) => { e.stopPropagation(); onViewResult(latest); }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onViewResult(latest);
+ }}
>
<Eye className="h-3 w-3" />
Full detail
@@ -1105,13 +1042,15 @@ function PlatformSubGroup({
<TableCell className="text-center py-1.5 text-xs tabular-nums w-[110px]">
<span className="font-semibold">{r.mentionCount}</span>
<span className="text-muted-foreground">
- {' '}mention{r.mentionCount !== 1 ? 's' : ''}
+ {' '}
+ mention{r.mentionCount !== 1 ? 's' : ''}
</span>
</TableCell>
<TableCell className="text-center py-1.5 text-xs tabular-nums w-[110px]">
<span className="font-semibold">{r.citationCount}</span>
<span className="text-muted-foreground">
- {' '}citation{r.citationCount !== 1 ? 's' : ''}
+ {' '}
+ citation{r.citationCount !== 1 ? 's' : ''}
</span>
</TableCell>
<TableCell className="text-center py-1.5 w-[100px]">
@@ -1126,7 +1065,10 @@ function PlatformSubGroup({
size="icon"
className="h-6 w-6"
title="View detail"
- onClick={(e) => { e.stopPropagation(); onViewResult(r); }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onViewResult(r);
+ }}
>
<Eye className="h-3 w-3" />
</Button>
@@ -1175,11 +1117,19 @@ function PromptSubGroup({
tabIndex={0}
onClick={onToggle}
onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggle(); }
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onToggle();
+ }
}}
className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-muted/50 transition-colors cursor-pointer select-none"
>
- <ChevronDown className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform', !expanded && '-rotate-90')} />
+ <ChevronDown
+ className={cn(
+ 'h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform',
+ !expanded && '-rotate-90',
+ )}
+ />
<div className="flex-1 min-w-0">
<p className="text-sm line-clamp-1">{group.promptText}</p>
<span className="text-[11px] text-muted-foreground">
@@ -1207,7 +1157,10 @@ function PromptSubGroup({
className="h-6 w-6"
title="Refresh results"
disabled={refreshingId !== null}
- onClick={(e) => { e.stopPropagation(); onRefresh(group.promptId); }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onRefresh(group.promptId);
+ }}
>
{refreshingId === group.promptId ? (
<Loader2 className="h-3 w-3 animate-spin" />
@@ -1260,27 +1213,34 @@ function PromptResultsGrouped({
const toggleTopic = (id: string) =>
setExpandedTopics((prev) => {
const next = new Set(prev);
- if (next.has(id)) next.delete(id); else next.add(id);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
return next;
});
const togglePrompt = (id: string) =>
setExpandedPrompts((prev) => {
const next = new Set(prev);
- if (next.has(id)) next.delete(id); else next.add(id);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
return next;
});
const togglePlatform = (id: string) =>
setExpandedPlatforms((prev) => {
const next = new Set(prev);
- if (next.has(id)) next.delete(id); else next.add(id);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
return next;
});
const handleRefresh = async (promptId: string) => {
setRefreshingId(promptId);
- try { await onRefreshPrompt(promptId); } finally { setRefreshingId(null); }
+ try {
+ await onRefreshPrompt(promptId);
+ } finally {
+ setRefreshingId(null);
+ }
};
const truncated = totalRowCount > loadedRowCount && loadedRowCount > 0;
@@ -1292,8 +1252,8 @@ function PromptResultsGrouped({
<CardTitle className="text-sm font-medium">Prompt Results by Topic</CardTitle>
{truncated && (
<p className="text-xs text-muted-foreground font-normal">
- Showing {loadedRowCount} of {totalRowCount} rows (newest first).
- Narrow the date range or filters to focus the list.
+ Showing {loadedRowCount} of {totalRowCount} rows (newest first). Narrow the date range
+ or filters to focus the list.
</p>
)}
</div>
@@ -1309,22 +1269,34 @@ function PromptResultsGrouped({
{topicGroups.map((topic) => {
const isTopicOpen = expandedTopics.has(topic.topicId);
return (
- <div key={topic.topicId + topic.topicName} className="rounded-lg border overflow-hidden">
+ <div
+ key={topic.topicId + topic.topicName}
+ className="rounded-lg border overflow-hidden"
+ >
<div
role="button"
tabIndex={0}
onClick={() => toggleTopic(topic.topicId)}
onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleTopic(topic.topicId); }
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleTopic(topic.topicId);
+ }
}}
className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-muted/50 transition-colors cursor-pointer select-none"
>
- <ChevronDown className={cn('h-4 w-4 shrink-0 text-muted-foreground transition-transform', !isTopicOpen && '-rotate-90')} />
+ <ChevronDown
+ className={cn(
+ 'h-4 w-4 shrink-0 text-muted-foreground transition-transform',
+ !isTopicOpen && '-rotate-90',
+ )}
+ />
<Tag className="h-4 w-4 shrink-0 text-muted-foreground" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">{topic.topicName}</p>
<span className="text-[11px] text-muted-foreground">
- {topic.prompts.length} prompt{topic.prompts.length !== 1 ? 's' : ''} · {topic.totalResults} result{topic.totalResults !== 1 ? 's' : ''}
+ {topic.prompts.length} prompt{topic.prompts.length !== 1 ? 's' : ''} ·{' '}
+ {topic.totalResults} result{topic.totalResults !== 1 ? 's' : ''}
</span>
</div>
<div className="flex items-center gap-4 shrink-0">
@@ -1388,8 +1360,7 @@ export default function InsightsPage() {
const [availableRegions, setAvailableRegions] = useState<string[]>([]);
const [availableModels, setAvailableModels] = useState<string[]>([]);
const [availableTopics, setAvailableTopics] = useState<Topic[]>([]);
- const [competitorData, setCompetitorData] =
- useState<CompetitorComparisonData | null>(null);
+ const [competitorData, setCompetitorData] = useState<CompetitorComparisonData | null>(null);
const [sovData, setSovData] = useState<ShareOfVoiceData | null>(null);
const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);
const filtersRef = useRef(filters);
@@ -1434,7 +1405,8 @@ export default function InsightsPage() {
: Promise.resolve(null),
];
- const [summaryData, resultsData, compData, sovResult, unfilteredCheck] = await Promise.all(promises);
+ const [summaryData, resultsData, compData, sovResult, unfilteredCheck] =
+ await Promise.all(promises);
setSummary(summaryData);
setResults(resultsData.results);
setTotalResults(resultsData.total);
@@ -1448,11 +1420,7 @@ export default function InsightsPage() {
}
const regions = [
- ...new Set(
- resultsData.results
- .map((r) => r.region)
- .filter(Boolean) as string[],
- ),
+ ...new Set(resultsData.results.map((r) => r.region).filter(Boolean) as string[]),
].sort();
// Group raw model slugs by their resolved display name so different
// ChatGPT versions ("gpt-5-3-mini" + "gpt-5-5") collapse into one
@@ -1478,14 +1446,10 @@ export default function InsightsPage() {
.map((slugs) => slugs.sort().join(','))
.sort();
setAvailableRegions((prev) =>
- [...new Set([...prev, ...regions])].sort((a, b) =>
- a.localeCompare(b),
- ),
+ [...new Set([...prev, ...regions])].sort((a, b) => a.localeCompare(b)),
);
setAvailableModels((prev) =>
- [...new Set([...prev, ...models])].sort((a, b) =>
- a.localeCompare(b)
- ),
+ [...new Set([...prev, ...models])].sort((a, b) => a.localeCompare(b)),
);
} catch (err) {
const message = err instanceof Error ? err.message : '';
@@ -1520,7 +1484,9 @@ export default function InsightsPage() {
const next = { ...filtersRef.current, region: '', model: '', topic: '' };
filtersRef.current = next;
setFilters(next);
- getTopics(brand.id).then(setAvailableTopics).catch(() => {});
+ getTopics(brand.id)
+ .then(setAvailableTopics)
+ .catch(() => {});
}, [brand?.id]);
useEffect(() => {
@@ -1573,9 +1539,7 @@ export default function InsightsPage() {
setActiveJobId(null);
setIsRunning(false);
setJobStatus(null);
- toast.success(
- `Analysis complete — ${status.result?.resultCount ?? 0} results saved.`,
- );
+ toast.success(`Analysis complete — ${status.result?.resultCount ?? 0} results saved.`);
loadData(undefined, { silent: true });
break;
}
@@ -1586,9 +1550,7 @@ export default function InsightsPage() {
setIsRunning(false);
setJobStatus(null);
if (status.status === 'failed') {
- toast.error(
- `Job failed: ${status.failedReason ?? 'Unknown error'}`,
- );
+ toast.error(`Job failed: ${status.failedReason ?? 'Unknown error'}`);
}
break;
}
@@ -1625,9 +1587,7 @@ export default function InsightsPage() {
});
} catch (err) {
setIsRunning(false);
- toast.error(
- err instanceof Error ? err.message : 'Failed to trigger tracking',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to trigger tracking');
}
};
@@ -1695,9 +1655,7 @@ export default function InsightsPage() {
sentiment: r.sentiment,
citation_urls: r.citations.map((c) => c.url).join(', '),
competitor_mentions:
- r.competitorMentions
- ?.map((c) => `${c.name}:${c.mention_count}`)
- .join(', ') ?? '',
+ r.competitorMentions?.map((c) => `${c.name}:${c.mention_count}`).join(', ') ?? '',
}));
const csv = toCsv(rows, INSIGHT_EXPORT_HEADERS);
@@ -1723,23 +1681,14 @@ export default function InsightsPage() {
return (
<div className="space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Answer Engine Insights
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Answer Engine Insights</h1>
<p className="text-muted-foreground text-sm">{brand.name}</p>
</div>
- <TrackingProgressBanner
- jobStatus={jobStatus}
- onStop={handleStopTracking}
- />
+ <TrackingProgressBanner jobStatus={jobStatus} onStop={handleStopTracking} />
<EmptyState onRunPrompts={handleRunPrompts} isRunning={isRunning} isCloud={isCloud} />
{!isCloud && (
<div className="flex justify-center">
- <Button
- variant="outline"
- onClick={() => setShowSinglePrompt(true)}
- className="gap-2"
- >
+ <Button variant="outline" onClick={() => setShowSinglePrompt(true)} className="gap-2">
<FlaskConical className="h-4 w-4" />
Or test a single prompt
</Button>
@@ -1770,9 +1719,7 @@ export default function InsightsPage() {
{/* Header */}
<div className="flex items-start justify-between gap-4">
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Answer Engine Insights
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Answer Engine Insights</h1>
<p className="text-muted-foreground text-sm">
{brand.name} · Last run: {lastCheckedLabel} · {totalResults} results
@@ -1789,20 +1736,12 @@ export default function InsightsPage() {
{/* Self-host only */}
{!isCloud && (
<>
- <Button
- variant="outline"
- onClick={() => setShowSinglePrompt(true)}
- className="gap-2"
- >
+ <Button variant="outline" onClick={() => setShowSinglePrompt(true)} className="gap-2">
<FlaskConical className="h-4 w-4" />
Test Single Prompt
</Button>
- <Button
- onClick={handleRunPrompts}
- disabled={isRunning}
- className="gap-2"
- >
+ <Button onClick={handleRunPrompts} disabled={isRunning} className="gap-2">
{isRunning ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
@@ -1825,16 +1764,10 @@ export default function InsightsPage() {
/>
{/* Tracking Progress */}
- <TrackingProgressBanner
- jobStatus={jobStatus}
- onStop={handleStopTracking}
- />
+ <TrackingProgressBanner jobStatus={jobStatus} onStop={handleStopTracking} />
{noResults ? (
- <NoDataForPeriod
- datePreset={filters.datePreset}
- onReset={handleResetFilters}
- />
+ <NoDataForPeriod datePreset={filters.datePreset} onReset={handleResetFilters} />
) : (
<>
{/* KPI Cards */}
@@ -1931,8 +1864,8 @@ export default function InsightsPage() {
Share of Voice by Platform
</CardTitle>
{sovData.overallSovChange !== null && sovData.overallSovChange !== 0 && (
- <DeltaBadge delta={sovData.overallSovChange} suffix=" pts" />
- )}
+ <DeltaBadge delta={sovData.overallSovChange} suffix=" pts" />
+ )}
</CardHeader>
<CardContent>
<ShareOfVoicePlatformChart
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/page.tsx
index 5ba9d6797..528d87cad 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/page.tsx
@@ -1,5 +1,5 @@
-import { redirect } from "next/navigation";
+import { redirect } from 'next/navigation';
export default function DashboardPage() {
- redirect("/dashboard/insights");
+ redirect('/dashboard/insights');
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx
index 6a5f3d169..435544640 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx
@@ -12,19 +12,9 @@ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
-import {
- ArrowLeft,
- ChevronDown,
- Clock,
- Eye,
- MessageSquareText,
- Quote,
-} from 'lucide-react';
+import { ArrowLeft, ChevronDown, Clock, Eye, MessageSquareText, Quote } from 'lucide-react';
import { cn } from '@/lib/utils';
-import {
- AIProviderAvatar,
- resolveAIProvider,
-} from '@/components/ai-provider-avatar';
+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';
const PLATFORM_LABELS: Record<string, string> = {
chatgpt: 'ChatGPT',
@@ -85,11 +75,7 @@ function formatTimestamp(iso: string): string {
});
}
-function SentimentBadge({
- sentiment,
-}: {
- sentiment: 'positive' | 'neutral' | 'negative';
-}) {
+function SentimentBadge({ sentiment }: { sentiment: 'positive' | 'neutral' | 'negative' }) {
return (
<Badge
variant="outline"
@@ -108,13 +94,7 @@ function SentimentBadge({
);
}
-function ModelBadge({
- model,
- platform,
-}: {
- model?: string;
- platform?: string;
-}) {
+function ModelBadge({ model, platform }: { model?: string; platform?: string }) {
const provider = resolveAIProvider(model ?? platform ?? '', platform);
return (
<span className="inline-flex items-center gap-1.5 rounded-full border bg-background px-2 py-1">
@@ -132,18 +112,12 @@ function VisibilityBar({ score }: { score: number }) {
<div
className={cn(
'h-full rounded-full',
- rounded >= 70
- ? 'bg-emerald-500'
- : rounded >= 40
- ? 'bg-amber-500'
- : 'bg-red-500',
+ rounded >= 70 ? 'bg-emerald-500' : rounded >= 40 ? 'bg-amber-500' : 'bg-red-500',
)}
style={{ width: `${Math.min(100, Math.max(0, rounded))}%` }}
/>
</div>
- <span className="w-8 text-right text-xs font-semibold tabular-nums">
- {rounded}
- </span>
+ <span className="w-8 text-right text-xs font-semibold tabular-nums">{rounded}</span>
</div>
);
}
@@ -379,10 +353,7 @@ export default function PromptDetailPage() {
};
}, [promptId]);
- const platformGroups = useMemo(
- () => groupByPlatform(data?.results ?? []),
- [data?.results],
- );
+ const platformGroups = useMemo(() => groupByPlatform(data?.results ?? []), [data?.results]);
const togglePlatform = (key: string) =>
setExpanded((prev) => {
@@ -415,11 +386,7 @@ export default function PromptDetailPage() {
<p className="mt-1 text-sm text-muted-foreground">
This prompt may have been deleted or does not exist.
</p>
- <Button
- variant="outline"
- className="mt-6 gap-2"
- onClick={() => router.back()}
- >
+ <Button variant="outline" className="mt-6 gap-2" onClick={() => router.back()}>
<ArrowLeft className="h-4 w-4" />
Go back
</Button>
@@ -440,9 +407,7 @@ export default function PromptDetailPage() {
</Button>
<div className="space-y-3">
- <h1 className="text-xl font-semibold leading-snug">
- {data.prompt.text}
- </h1>
+ <h1 className="text-xl font-semibold leading-snug">{data.prompt.text}</h1>
<div className="flex flex-wrap items-center gap-2">
{data.prompt.topicName && (
<Badge variant="secondary" className="text-xs">
@@ -491,7 +456,8 @@ export default function PromptDetailPage() {
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Platform Results</CardTitle>
<p className="text-xs text-muted-foreground">
- {data.summary.totalResults} result{data.summary.totalResults !== 1 ? 's' : ''} grouped by platform and model.
+ {data.summary.totalResults} result{data.summary.totalResults !== 1 ? 's' : ''} grouped
+ by platform and model.
</p>
</CardHeader>
<CardContent className="space-y-3">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx
index 203189721..b762c6cb9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx
@@ -1,15 +1,7 @@
'use client';
import { useRef, useState, useEffect } from 'react';
-import {
- BarChart,
- Bar,
- XAxis,
- YAxis,
- CartesianGrid,
- Tooltip,
- Cell,
-} from 'recharts';
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Cell } from 'recharts';
// ─── Auto-sizing wrapper ─────────────────────────────────────────────────────
@@ -108,20 +100,14 @@ export function PlatformVolumeChart({ totalVolume }: { totalVolume: number }) {
layout="vertical"
margin={{ top: 0, right: 12, left: 4, bottom: 0 }}
>
- <CartesianGrid
- strokeDasharray="3 3"
- className="stroke-border"
- horizontal={false}
- />
+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" horizontal={false} />
<XAxis
type="number"
tick={{ fontSize: 10 }}
tickLine={false}
axisLine={false}
className="fill-muted-foreground"
- tickFormatter={(v) =>
- v >= 1000 ? `${(v / 1000).toFixed(0)}k` : `${v}`
- }
+ tickFormatter={(v) => (v >= 1000 ? `${(v / 1000).toFixed(0)}k` : `${v}`)}
/>
<YAxis
type="category"
@@ -139,9 +125,7 @@ export function PlatformVolumeChart({ totalVolume }: { totalVolume: number }) {
const row = payload[0].payload as PlatformVolumeItem;
return (
<div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">
- <p className="font-medium text-foreground mb-0.5">
- {row.name}
- </p>
+ <p className="font-medium text-foreground mb-0.5">{row.name}</p>
<p className="text-muted-foreground">
Est. queries:{' '}
<span className="font-medium text-foreground">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
index d77431243..b6979c8b5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
@@ -1,24 +1,10 @@
'use client';
import { useEffect, useState, useCallback, useTransition } from 'react';
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from '@/components/ui/card';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
-import {
- Sparkles,
- Plus,
- X,
- RefreshCw,
- Loader2,
- TrendingUp,
- Tag,
- Info,
-} from 'lucide-react';
+import { Sparkles, Plus, X, RefreshCw, Loader2, TrendingUp, Tag, Info } from 'lucide-react';
import { toast } from 'sonner';
import {
getPromptSuggestions,
@@ -111,16 +97,14 @@ export function SuggestionsCard({ brandId }: Props) {
<div className="flex items-center justify-between gap-4 flex-wrap">
<div className="flex items-center gap-2">
<Sparkles className="h-4 w-4 text-primary" />
- <CardTitle className="text-sm font-medium">
- Prompt Suggestions
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Prompt Suggestions</CardTitle>
<Info
className="h-3.5 w-3.5 text-muted-foreground cursor-help"
aria-label="AI-generated prompt ideas based on your brand, existing tracked prompts, and competitors cited in AI answers."
>
<title>
- AI-generated prompt ideas based on your brand, existing tracked
- prompts, and competitors cited in AI answers.
+ AI-generated prompt ideas based on your brand, existing tracked prompts, and
+ competitors cited in AI answers.
</title>
</Info>
</div>
@@ -150,15 +134,10 @@ export function SuggestionsCard({ brandId }: Props) {
<Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" />
<p className="text-sm font-medium mb-1">No suggestions right now</p>
<p className="text-xs text-muted-foreground mb-3 max-w-sm">
- Click refresh to generate new prompt ideas tailored to your brand
- and competitor activity.
+ Click refresh to generate new prompt ideas tailored to your brand and competitor
+ activity.
</p>
- <Button
- onClick={handleRefresh}
- disabled={refreshing}
- size="sm"
- className="gap-2"
- >
+ <Button onClick={handleRefresh} disabled={refreshing} size="sm" className="gap-2">
{refreshing ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
@@ -177,9 +156,7 @@ export function SuggestionsCard({ brandId }: Props) {
className="group flex items-start gap-3 rounded-lg border bg-muted/20 p-3 transition-colors hover:bg-muted/40"
>
<div className="flex-1 min-w-0 space-y-1.5">
- <p className="text-sm font-medium leading-snug">
- {s.suggestedText}
- </p>
+ <p className="text-sm font-medium leading-snug">{s.suggestedText}</p>
<div className="flex flex-wrap items-center gap-1.5">
{s.topicName && (
<Badge variant="outline" className="gap-1 text-xs">
@@ -188,19 +165,13 @@ export function SuggestionsCard({ brandId }: Props) {
</Badge>
)}
{s.estVolume != null && s.estVolume > 0 && (
- <Badge
- variant="outline"
- className="gap-1 text-xs tabular-nums"
- >
- <TrendingUp className="h-3 w-3" />
- ~{s.estVolume.toLocaleString()}/mo
+ <Badge variant="outline" className="gap-1 text-xs tabular-nums">
+ <TrendingUp className="h-3 w-3" />~{s.estVolume.toLocaleString()}/mo
</Badge>
)}
</div>
{s.reason && (
- <p className="text-xs text-muted-foreground leading-relaxed">
- {s.reason}
- </p>
+ <p className="text-xs text-muted-foreground leading-relaxed">{s.reason}</p>
)}
</div>
<div className="flex items-center gap-1 shrink-0">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 7f06c7fa8..d24cb774f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -42,10 +42,7 @@ import {
type VolumeQuota,
} from '@/lib/actions/volumes';
import { getPromptSets } from '@/lib/actions/prompt';
-import {
- getPromptVisibilitySummaries,
- type PromptVisibilitySummary,
-} from '@/lib/actions/tracking';
+import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';
import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
import type { PromptVolume, Prompt } from '@/types';
import { toast } from 'sonner';
@@ -118,20 +115,13 @@ const INTENT_LABELS: Record<string, string> = {
};
const INTENT_COLORS: Record<string, string> = {
- comparison:
- 'border-indigo-500/30 bg-indigo-500/10 text-indigo-600 dark:text-indigo-400',
- 'how-to':
- 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',
- 'what-is':
- 'border-purple-400/30 bg-purple-400/10 text-purple-600 dark:text-purple-400',
- 'best-top':
- 'border-blue-400/30 bg-blue-400/10 text-blue-600 dark:text-blue-400',
- 'vs-review':
- 'border-cyan-500/30 bg-cyan-500/10 text-cyan-600 dark:text-cyan-400',
- recommendation:
- 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
- 'problem-solving':
- 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ comparison: 'border-indigo-500/30 bg-indigo-500/10 text-indigo-600 dark:text-indigo-400',
+ 'how-to': 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',
+ 'what-is': 'border-purple-400/30 bg-purple-400/10 text-purple-600 dark:text-purple-400',
+ 'best-top': 'border-blue-400/30 bg-blue-400/10 text-blue-600 dark:text-blue-400',
+ 'vs-review': 'border-cyan-500/30 bg-cyan-500/10 text-cyan-600 dark:text-cyan-400',
+ recommendation: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+ 'problem-solving': 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
};
const PROMPT_EXPORT_HEADERS = [
@@ -212,9 +202,7 @@ function KpiCard({
<p
className={cn(
'text-xs mt-1 flex items-center gap-0.5',
- subPositive
- ? 'text-green-600 dark:text-green-400'
- : 'text-muted-foreground',
+ subPositive ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground',
)}
>
{sub}
@@ -235,9 +223,7 @@ export default function PromptsPage() {
const [search, setSearch] = useState('');
const [volumes, setVolumes] = useState<PromptVolume[]>([]);
const [allPrompts, setAllPrompts] = useState<Prompt[]>([]);
- const [visibility, setVisibility] = useState<
- Record<string, PromptVisibilitySummary>
- >({});
+ const [visibility, setVisibility] = useState<Record<string, PromptVisibilitySummary>>({});
const [loading, setLoading] = useState(true);
const [analyzing, setAnalyzing] = useState(false);
const [refreshing, setRefreshing] = useState(false);
@@ -252,9 +238,7 @@ export default function PromptsPage() {
const initialTab: TabId = (() => {
const raw = searchParams.get('tab');
- return (VALID_TABS as readonly string[]).includes(raw ?? '')
- ? (raw as TabId)
- : 'all';
+ return (VALID_TABS as readonly string[]).includes(raw ?? '') ? (raw as TabId) : 'all';
})();
const [tab, setTab] = useState<TabId>(initialTab);
@@ -311,14 +295,10 @@ export default function PromptsPage() {
);
const promptsToAnalyze =
- promptsWithoutVolume.length > 0
- ? promptsWithoutVolume
- : allPrompts.filter((p) => p.isActive);
+ promptsWithoutVolume.length > 0 ? promptsWithoutVolume : allPrompts.filter((p) => p.isActive);
if (promptsToAnalyze.length === 0) {
- toast.error(
- 'No active prompts to analyze. Add prompts to a brand first.',
- );
+ toast.error('No active prompts to analyze. Add prompts to a brand first.');
return;
}
@@ -337,12 +317,9 @@ export default function PromptsPage() {
toast.success(`Analyzed ${promptsToAnalyze.length} prompts`);
await loadData();
} catch (err: unknown) {
- const message =
- err instanceof Error ? err.message : 'Volume analysis failed';
+ const message = err instanceof Error ? err.message : 'Volume analysis failed';
if (message.includes('limit reached')) {
- toast.error(
- 'Monthly volume analysis limit reached. Upgrade your plan for more.',
- );
+ toast.error('Monthly volume analysis limit reached. Upgrade your plan for more.');
} else {
console.error('Volume analysis failed:', err);
toast.error('Volume analysis failed');
@@ -368,12 +345,9 @@ export default function PromptsPage() {
toast.success(`Refreshed volumes for ${result.refreshed} prompts`);
await loadData();
} catch (err: unknown) {
- const message =
- err instanceof Error ? err.message : 'Volume refresh failed';
+ const message = err instanceof Error ? err.message : 'Volume refresh failed';
if (message.includes('limit reached')) {
- toast.error(
- 'Monthly volume analysis limit reached. Upgrade your plan for more.',
- );
+ toast.error('Monthly volume analysis limit reached. Upgrade your plan for more.');
} else {
console.error('Volume refresh failed:', err);
toast.error('Volume refresh failed');
@@ -407,16 +381,12 @@ export default function PromptsPage() {
used: quota.limit === -1 ? 0 : quota.limit - result.remaining,
});
}
- toast.success(
- `Re-analyzed ${activePrompts.length} prompts with new keywords`,
- );
+ toast.success(`Re-analyzed ${activePrompts.length} prompts with new keywords`);
await loadData();
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Re-analysis failed';
if (message.includes('limit reached')) {
- toast.error(
- 'Monthly volume analysis limit reached. Upgrade your plan for more.',
- );
+ toast.error('Monthly volume analysis limit reached. Upgrade your plan for more.');
} else {
console.error('Re-analysis failed:', err);
toast.error('Re-analysis failed');
@@ -436,8 +406,7 @@ export default function PromptsPage() {
v.intent.toLowerCase().includes(search.toLowerCase()),
);
- const quotaExhausted =
- quota !== null && quota.limit !== -1 && quota.remaining <= 0;
+ const quotaExhausted = quota !== null && quota.limit !== -1 && quota.remaining <= 0;
// Join prompts with their volume + visibility summaries once, reused by the
// All Prompts table.
@@ -570,9 +539,7 @@ export default function PromptsPage() {
<>
<Button
onClick={handleRefreshVolumes}
- disabled={
- refreshing || analyzing || loading || quotaExhausted
- }
+ disabled={refreshing || analyzing || loading || quotaExhausted}
size="sm"
variant="outline"
className="gap-2"
@@ -586,9 +553,7 @@ export default function PromptsPage() {
</Button>
<Button
onClick={handleReanalyzeAll}
- disabled={
- analyzing || refreshing || loading || quotaExhausted
- }
+ disabled={analyzing || refreshing || loading || quotaExhausted}
size="sm"
variant="outline"
className="gap-2"
@@ -603,14 +568,11 @@ export default function PromptsPage() {
</>
)}
{volumes.length > 0 &&
- allPrompts.filter(
- (p) => p.isActive && !volumes.find((v) => v.promptId === p.id),
- ).length > 0 && (
+ allPrompts.filter((p) => p.isActive && !volumes.find((v) => v.promptId === p.id))
+ .length > 0 && (
<Button
onClick={handleAnalyzeNew}
- disabled={
- analyzing || refreshing || loading || quotaExhausted
- }
+ disabled={analyzing || refreshing || loading || quotaExhausted}
size="sm"
className="gap-2"
>
@@ -662,8 +624,7 @@ export default function PromptsPage() {
)}
{quota && quota.limit !== -1 && !quotaExhausted && (
<p className="text-xs text-muted-foreground">
- {quota.remaining}/{quota.limit} analyses remaining this
- month
+ {quota.remaining}/{quota.limit} analyses remaining this month
</p>
)}
</>
@@ -704,14 +665,11 @@ export default function PromptsPage() {
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
<Card className="lg:col-span-2">
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- Prompt Volumes
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Prompt Volumes</CardTitle>
<p className="text-xs text-muted-foreground">
- Total estimated AI-answered queries across all topic
- clusters, split by answer-engine share. Weights include
- Google AI Overview (~35% of Google searches), Google AI
- Mode, and standalone chatbots.
+ Total estimated AI-answered queries across all topic clusters, split by
+ answer-engine share. Weights include Google AI Overview (~35% of Google
+ searches), Google AI Mode, and standalone chatbots.
</p>
</CardHeader>
<CardContent>
@@ -723,9 +681,7 @@ export default function PromptsPage() {
<CardHeader className="pb-2">
<div className="flex items-start justify-between gap-3">
<div>
- <CardTitle className="text-sm font-medium">
- Similar Topics
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Similar Topics</CardTitle>
<p className="text-xs text-muted-foreground">
Most-searched keyword clusters across all prompts
</p>
@@ -751,9 +707,7 @@ export default function PromptsPage() {
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between gap-4 flex-wrap">
- <CardTitle className="text-sm font-medium">
- Prompt Volumes
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Prompt Volumes</CardTitle>
<div className="relative w-60">
<Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
<Input
@@ -806,9 +760,7 @@ export default function PromptsPage() {
{filtered.map((row) => (
<TableRow key={row.id} className="hover:bg-muted/50">
<TableCell className="pl-6 font-medium text-sm max-w-[280px]">
- <span className="line-clamp-1">
- {row.promptText}
- </span>
+ <span className="line-clamp-1">{row.promptText}</span>
</TableCell>
<TableCell className="text-center text-xs text-muted-foreground tabular-nums">
{row.keywords.length}
@@ -844,9 +796,8 @@ export default function PromptsPage() {
)}
<div className="px-6 py-2 border-t">
<p className="text-xs text-muted-foreground">
- * Est. AI Volume = Total Google search volume of extracted
- keywords × AI adoption rate. Figures are approximations
- for planning purposes.
+ * Est. AI Volume = Total Google search volume of extracted keywords × AI
+ adoption rate. Figures are approximations for planning purposes.
</p>
</div>
</CardContent>
@@ -877,10 +828,7 @@ export default function PromptsPage() {
>
Est. AI Volume
</ColHead>
- <ColHead
- className="text-center"
- tooltip="The detected search intent."
- >
+ <ColHead className="text-center" tooltip="The detected search intent.">
Intent
</ColHead>
<ColHead
@@ -896,10 +844,7 @@ export default function PromptsPage() {
.filter((v) => v.estAiVolume >= 5000)
.sort((a, b) => b.estAiVolume - a.estAiVolume)
.map((row) => (
- <TableRow
- key={row.id}
- className="hover:bg-muted/50"
- >
+ <TableRow key={row.id} className="hover:bg-muted/50">
<TableCell className="pl-6 font-medium text-sm">
{row.promptText}
</TableCell>
@@ -909,10 +854,7 @@ export default function PromptsPage() {
<TableCell className="text-center">
<Badge
variant="outline"
- className={cn(
- 'text-xs',
- INTENT_COLORS[row.intent] || '',
- )}
+ className={cn('text-xs', INTENT_COLORS[row.intent] || '')}
>
{INTENT_LABELS[row.intent] || row.intent}
</Badge>
@@ -965,14 +907,11 @@ function AllPromptsTab({
const filtered = useMemo(() => {
const q = search.trim().toLowerCase();
const sorted = [...prompts].sort(
- (a, b) =>
- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
);
if (!q) return sorted;
return sorted.filter(
- (p) =>
- p.text.toLowerCase().includes(q) ||
- (p.category ?? '').toLowerCase().includes(q),
+ (p) => p.text.toLowerCase().includes(q) || (p.category ?? '').toLowerCase().includes(q),
);
}, [prompts, search]);
@@ -1011,9 +950,7 @@ function AllPromptsTab({
<CardHeader className="pb-3">
<div className="flex items-center justify-between gap-4 flex-wrap">
<div>
- <CardTitle className="text-sm font-medium">
- All Prompts ({prompts.length})
- </CardTitle>
+ <CardTitle className="text-sm font-medium">All Prompts ({prompts.length})</CardTitle>
<p className="text-xs text-muted-foreground mt-0.5">
Read-only overview · edit prompts from each brand&apos;s page
</p>
@@ -1054,10 +991,7 @@ function AllPromptsTab({
>
Volume
</ColHead>
- <ColHead
- className="text-right"
- tooltip="Most recent tracking run for this prompt."
- >
+ <ColHead className="text-right" tooltip="Most recent tracking run for this prompt.">
Last run
</ColHead>
<TableHead className="text-right pr-6 w-[60px]">Edit</TableHead>
@@ -1198,17 +1132,13 @@ function SimilarTopicsList({ volumes }: { volumes: PromptVolume[] }) {
/>
</div>
<span className="w-12 text-right font-medium tabular-nums text-foreground">
- {item.volume >= 1000
- ? `${(item.volume / 1000).toFixed(1)}k`
- : item.volume}
+ {item.volume >= 1000 ? `${(item.volume / 1000).toFixed(1)}k` : item.volume}
</span>
</div>
);
})}
{sorted.length === 0 && (
- <p className="text-xs text-muted-foreground text-center py-4">
- No keyword data yet
- </p>
+ <p className="text-xs text-muted-foreground text-center py-4">No keyword data yet</p>
)}
</div>
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx
index 2c8bbe6f0..fe1e25249 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx
@@ -65,9 +65,7 @@ export default function SimilarTopicsPage() {
return all.filter((cluster) => {
if (cluster.keyword.toLowerCase().includes(normalizedSearch)) return true;
- return cluster.prompts.some((prompt) =>
- prompt.text.toLowerCase().includes(normalizedSearch),
- );
+ return cluster.prompts.some((prompt) => prompt.text.toLowerCase().includes(normalizedSearch));
});
}, [search, volumes]);
@@ -95,9 +93,7 @@ export default function SimilarTopicsPage() {
Back to Prompt Insights
</Link>
<div>
- <h1 className="text-2xl font-semibold tracking-tight">
- Similar Topics
- </h1>
+ <h1 className="text-2xl font-semibold tracking-tight">Similar Topics</h1>
<p className="mt-1 text-sm text-muted-foreground">
Keyword clusters aggregated across analyzed prompts.
</p>
@@ -144,9 +140,7 @@ export default function SimilarTopicsPage() {
<CardHeader className="pb-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
- <CardTitle className="text-sm font-medium">
- All Similar Topics
- </CardTitle>
+ <CardTitle className="text-sm font-medium">All Similar Topics</CardTitle>
<Badge variant="secondary">{clusters.length}</Badge>
</div>
<div className="relative w-full sm:w-60">
@@ -181,9 +175,7 @@ export default function SimilarTopicsPage() {
)}
{!loading &&
clusters.map((cluster) => {
- const topPrompt = [...cluster.prompts].sort(
- (a, b) => b.volume - a.volume,
- )[0];
+ const topPrompt = [...cluster.prompts].sort((a, b) => b.volume - a.volume)[0];
return (
<TableRow key={cluster.keyword.toLowerCase()}>
@@ -200,9 +192,7 @@ export default function SimilarTopicsPage() {
{formatVolume(cluster.estimatedAiVolume)}
</TableCell>
<TableCell className="text-center">
- <Badge variant="outline">
- {cluster.occurrences}
- </Badge>
+ <Badge variant="outline">{cluster.occurrences}</Badge>
</TableCell>
<TableCell className="max-w-[360px]">
{topPrompt ? (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx
index 024317c47..7fe6ad744 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx
@@ -1,26 +1,26 @@
-import { useTranslations } from "next-intl";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { FileDown, Plus } from "lucide-react";
+import { useTranslations } from 'next-intl';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { FileDown, Plus } from 'lucide-react';
export default function ReportsPage() {
- const t = useTranslations("reports");
+ const t = useTranslations('reports');
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('description')}</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" className="gap-2">
<FileDown className="h-4 w-4" />
- {t("downloadPDF")}
+ {t('downloadPDF')}
</Button>
<Button className="gap-2">
<Plus className="h-4 w-4" />
- {t("generateReport")}
+ {t('generateReport')}
</Button>
</div>
</div>
@@ -31,8 +31,8 @@ export default function ReportsPage() {
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
- No reports generated yet. Run at least one prompt analysis to
- generate your first report.
+ No reports generated yet. Run at least one prompt analysis to generate your first
+ report.
</p>
</CardContent>
</Card>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
index e4b3d3511..9602fd68d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
@@ -1,66 +1,66 @@
-"use client";
+'use client';
-import { useEffect, useState } from "react";
-import { useTranslations } from "next-intl";
-import { useRouter } from "@/i18n/navigation";
-import { useSearchParams } from "next/navigation";
-import { createClient } from "@/lib/supabase/client";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Button } from "@/components/ui/button";
-import { Separator } from "@/components/ui/separator";
-import { ThemeSwitch } from "@/components/settings/theme-switch";
-import { cn } from "@/lib/utils";
-import { usePlanContext } from "@/components/providers/plan-provider";
-import { BillingSection } from "@/components/settings/billing-section";
-import { TeamSection } from "@/components/settings/team-section";
-import { ApiKeysSection } from "@/components/settings/api-keys-section";
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { useRouter } from '@/i18n/navigation';
+import { useSearchParams } from 'next/navigation';
+import { createClient } from '@/lib/supabase/client';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Button } from '@/components/ui/button';
+import { Separator } from '@/components/ui/separator';
+import { ThemeSwitch } from '@/components/settings/theme-switch';
+import { cn } from '@/lib/utils';
+import { usePlanContext } from '@/components/providers/plan-provider';
+import { BillingSection } from '@/components/settings/billing-section';
+import { TeamSection } from '@/components/settings/team-section';
+import { ApiKeysSection } from '@/components/settings/api-keys-section';
-type Section = "account" | "theme" | "project" | "team" | "api-keys" | "billing";
+type Section = 'account' | 'theme' | 'project' | 'team' | 'api-keys' | 'billing';
export default function SettingsPage() {
- const t = useTranslations("settings");
- const tAuth = useTranslations("auth");
+ const t = useTranslations('settings');
+ const tAuth = useTranslations('auth');
const router = useRouter();
const { isCloud } = usePlanContext();
const searchParams = useSearchParams();
- const tabParam = searchParams.get("tab");
+ const tabParam = searchParams.get('tab');
const [active, setActive] = useState<Section>(
- tabParam === "billing" && isCloud ? "billing" : "account"
+ tabParam === 'billing' && isCloud ? 'billing' : 'account',
);
- const [displayName, setDisplayName] = useState("");
- const [email, setEmail] = useState("");
+ const [displayName, setDisplayName] = useState('');
+ const [email, setEmail] = useState('');
useEffect(() => {
const supabase = createClient();
supabase.auth.getUser().then(({ data: { user: u } }) => {
- setDisplayName(u?.user_metadata?.full_name ?? "");
- setEmail(u?.email ?? "");
+ setDisplayName(u?.user_metadata?.full_name ?? '');
+ setEmail(u?.email ?? '');
});
}, []);
async function handleSignOut() {
const supabase = createClient();
await supabase.auth.signOut();
- router.push("/sign-in");
+ router.push('/sign-in');
router.refresh();
}
const navItems: { id: Section; label: string }[] = [
- { id: "account", label: t("account") },
- { id: "theme", label: t("theme") },
- { id: "project", label: t("project") },
- { id: "team", label: t("team") },
- { id: "api-keys", label: "API Keys" },
- ...(isCloud ? [{ id: "billing" as Section, label: t("billing") }] : []),
+ { id: 'account', label: t('account') },
+ { id: 'theme', label: t('theme') },
+ { id: 'project', label: t('project') },
+ { id: 'team', label: t('team') },
+ { id: 'api-keys', label: 'API Keys' },
+ ...(isCloud ? [{ id: 'billing' as Section, label: t('billing') }] : []),
];
return (
<div className="space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
- <p className="text-muted-foreground">{t("description")}</p>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('description')}</p>
</div>
<Separator />
@@ -73,10 +73,10 @@ export default function SettingsPage() {
key={item.id}
onClick={() => setActive(item.id)}
className={cn(
- "w-full text-left rounded-md px-3 py-2 text-sm font-medium transition-colors",
+ 'w-full text-left rounded-md px-3 py-2 text-sm font-medium transition-colors',
active === item.id
- ? "bg-accent text-accent-foreground"
- : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
+ ? 'bg-accent text-accent-foreground'
+ : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
)}
>
{item.label}
@@ -87,15 +87,15 @@ export default function SettingsPage() {
{/* Main content — only active section shown */}
<div className="lg:col-span-2">
{/* Account */}
- {active === "account" && (
+ {active === 'account' && (
<Card>
<CardHeader>
- <CardTitle>{t("account")}</CardTitle>
- <CardDescription>{t("accountDescription")}</CardDescription>
+ <CardTitle>{t('account')}</CardTitle>
+ <CardDescription>{t('accountDescription')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
- <Label htmlFor="name">{t("displayName")}</Label>
+ <Label htmlFor="name">{t('displayName')}</Label>
<Input
id="name"
placeholder="Your name"
@@ -104,7 +104,7 @@ export default function SettingsPage() {
/>
</div>
<div className="space-y-2">
- <Label htmlFor="email">{t("email")}</Label>
+ <Label htmlFor="email">{t('email')}</Label>
<Input
id="email"
type="email"
@@ -114,26 +114,26 @@ export default function SettingsPage() {
disabled
/>
</div>
- <Button>{t("save")}</Button>
+ <Button>{t('save')}</Button>
<Separator className="my-2" />
<Button
variant="outline"
onClick={handleSignOut}
className="text-destructive hover:text-destructive"
>
- {tAuth("signOut")}
+ {tAuth('signOut')}
</Button>
</CardContent>
</Card>
)}
{/* Theme */}
- {active === "theme" && (
+ {active === 'theme' && (
<div className="space-y-6">
<Card>
<CardHeader>
- <CardTitle>{t("theme")}</CardTitle>
- <CardDescription>{t("themeDescription")}</CardDescription>
+ <CardTitle>{t('theme')}</CardTitle>
+ <CardDescription>{t('themeDescription')}</CardDescription>
</CardHeader>
<CardContent>
<ThemeSwitch />
@@ -143,34 +143,34 @@ export default function SettingsPage() {
)}
{/* Project */}
- {active === "project" && (
+ {active === 'project' && (
<Card>
<CardHeader>
- <CardTitle>{t("project")}</CardTitle>
+ <CardTitle>{t('project')}</CardTitle>
<CardDescription>Configure your project settings.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
- <Label htmlFor="projectName">{t("projectName")}</Label>
+ <Label htmlFor="projectName">{t('projectName')}</Label>
<Input id="projectName" placeholder="My Brand" />
</div>
<div className="space-y-2">
- <Label htmlFor="domain">{t("domain")}</Label>
+ <Label htmlFor="domain">{t('domain')}</Label>
<Input id="domain" placeholder="example.com" />
</div>
- <Button>{t("save")}</Button>
+ <Button>{t('save')}</Button>
</CardContent>
</Card>
)}
{/* Team */}
- {active === "team" && <TeamSection />}
+ {active === 'team' && <TeamSection />}
{/* API Keys */}
- {active === "api-keys" && <ApiKeysSection />}
+ {active === 'api-keys' && <ApiKeysSection />}
{/* Billing */}
- {active === "billing" && isCloud && <BillingSection />}
+ {active === 'billing' && isCloud && <BillingSection />}
</div>
</div>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
index 00a380807..b08339134 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
@@ -17,12 +17,7 @@ import {
} from '@/lib/actions/tracking';
import { getTopics } from '@/lib/actions/topic';
import type { Topic } from '@/types';
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from '@/components/ui/card';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
@@ -38,14 +33,7 @@ import {
} from 'lucide-react';
import { ShareOfVoicePlatformChart } from '../../insights/_charts';
import { cn } from '@/lib/utils';
-import {
- AreaChart,
- Area,
- CartesianGrid,
- Tooltip,
- XAxis,
- YAxis,
-} from 'recharts';
+import { AreaChart, Area, CartesianGrid, Tooltip, XAxis, YAxis } from 'recharts';
function ChartContainer({
height,
@@ -100,9 +88,7 @@ function KpiCard({
<div className="text-2xl font-semibold tabular-nums">
{value}
{suffix && (
- <span className="text-sm font-normal text-muted-foreground ml-0.5">
- {suffix}
- </span>
+ <span className="text-sm font-normal text-muted-foreground ml-0.5">{suffix}</span>
)}
</div>
{change !== null && change !== undefined && (
@@ -214,11 +200,7 @@ function VisibilityTrendChart({ data }: { data: VisibilityTrendPoint[] }) {
// ─── Page ────────────────────────────────────────────────────────────────
-export default function TopicDetailPage({
- params,
-}: {
- params: Promise<{ id: string }>;
-}) {
+export default function TopicDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id: topicId } = use(params);
const router = useRouter();
const activeBrandId = useBrandStore((s) => s.activeBrandId);
@@ -276,17 +258,13 @@ export default function TopicDetailPage({
}
// Top/weak prompts — aggregate by prompt_id
- const promptRollup = new Map<
- string,
- { promptText: string; totalScore: number; count: number }
- >();
+ const promptRollup = new Map<string, { promptText: string; totalScore: number; count: number }>();
for (const r of results) {
- const ex =
- promptRollup.get(r.promptId) ?? {
- promptText: r.promptText,
- totalScore: 0,
- count: 0,
- };
+ const ex = promptRollup.get(r.promptId) ?? {
+ promptText: r.promptText,
+ totalScore: 0,
+ count: 0,
+ };
ex.totalScore += r.visibilityScore;
ex.count += 1;
promptRollup.set(r.promptId, ex);
@@ -366,38 +344,25 @@ export default function TopicDetailPage({
<div className="grid gap-4 lg:grid-cols-3">
<Card className="lg:col-span-2">
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- Visibility trend
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Visibility trend</CardTitle>
<p className="text-xs text-muted-foreground">
Daily average visibility for this topic vs. competitor average
</p>
</CardHeader>
<CardContent>
- {loading ? (
- <Skeleton className="h-[260px]" />
- ) : (
- <VisibilityTrendChart data={trend} />
- )}
+ {loading ? <Skeleton className="h-[260px]" /> : <VisibilityTrendChart data={trend} />}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- Share of voice by platform
- </CardTitle>
- <p className="text-xs text-muted-foreground">
- Brand vs. competitors on answer engines
- </p>
+ <CardTitle className="text-sm font-medium">Share of voice by platform</CardTitle>
+ <p className="text-xs text-muted-foreground">Brand vs. competitors on answer engines</p>
</CardHeader>
<CardContent>
{loading ? (
<Skeleton className="h-[260px]" />
) : sov && sov.byPlatform.length > 0 ? (
- <ShareOfVoicePlatformChart
- data={sov.byPlatform}
- overallSov={sov.overallSov}
- />
+ <ShareOfVoicePlatformChart data={sov.byPlatform} overallSov={sov.overallSov} />
) : (
<div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
No platform data yet.
@@ -439,9 +404,7 @@ export default function TopicDetailPage({
<span className="flex-1 text-sm font-medium truncate">
{c.name}
{c.isOwnBrand && (
- <span className="ml-1.5 text-[10px] font-medium text-primary">
- YOU
- </span>
+ <span className="ml-1.5 text-[10px] font-medium text-primary">YOU</span>
)}
</span>
<span className="text-sm tabular-nums w-10 text-right">
@@ -476,9 +439,7 @@ export default function TopicDetailPage({
{/* Top / Weak prompts */}
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- Prompt performance
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Prompt performance</CardTitle>
<p className="text-xs text-muted-foreground">
Best & worst performing prompts in this topic (last 50 runs)
</p>
@@ -502,17 +463,12 @@ export default function TopicDetailPage({
</div>
<ul className="space-y-1.5">
{topPrompts.map((p) => (
- <li
- key={p.id}
- className="flex items-center gap-2 text-sm"
- >
+ <li key={p.id} className="flex items-center gap-2 text-sm">
<Badge variant="outline" className="text-[10px] shrink-0">
{p.avg}%
</Badge>
<span className="flex-1 truncate">{p.text}</span>
- <span className="text-xs text-muted-foreground">
- {p.runs} runs
- </span>
+ <span className="text-xs text-muted-foreground">{p.runs} runs</span>
</li>
))}
</ul>
@@ -524,17 +480,12 @@ export default function TopicDetailPage({
</div>
<ul className="space-y-1.5">
{weakPrompts.map((p) => (
- <li
- key={p.id}
- className="flex items-center gap-2 text-sm"
- >
+ <li key={p.id} className="flex items-center gap-2 text-sm">
<Badge variant="outline" className="text-[10px] shrink-0">
{p.avg}%
</Badge>
<span className="flex-1 truncate">{p.text}</span>
- <span className="text-xs text-muted-foreground">
- {p.runs} runs
- </span>
+ <span className="text-xs text-muted-foreground">{p.runs} runs</span>
</li>
))}
</ul>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
index 23f2f1e51..a75df0deb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
@@ -3,16 +3,8 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link } from '@/i18n/navigation';
import { useBrandStore } from '@/stores/use-brand-store';
-import {
- getTopicsOverview,
- type TopicOverviewRow,
-} from '@/lib/actions/topic';
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from '@/components/ui/card';
+import { getTopicsOverview, type TopicOverviewRow } from '@/lib/actions/topic';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Table,
TableBody,
@@ -112,11 +104,7 @@ function Sparkline({ points }: { points: number[] }) {
d={path}
fill="none"
strokeWidth={1.5}
- className={
- trendUp
- ? 'stroke-emerald-500'
- : 'stroke-rose-500'
- }
+ className={trendUp ? 'stroke-emerald-500' : 'stroke-rose-500'}
/>
</svg>
);
@@ -150,12 +138,8 @@ function KpiCard({
<Icon className="h-3.5 w-3.5" />
{label}
</div>
- <div className={cn('text-2xl font-semibold tabular-nums', toneClasses[tone])}>
- {value}
- </div>
- {sub && (
- <p className="text-xs text-muted-foreground mt-1 truncate">{sub}</p>
- )}
+ <div className={cn('text-2xl font-semibold tabular-nums', toneClasses[tone])}>{value}</div>
+ {sub && <p className="text-xs text-muted-foreground mt-1 truncate">{sub}</p>}
</CardContent>
</Card>
);
@@ -195,8 +179,7 @@ export default function TopicsPage() {
}, [loadData]);
const sortedByVisibility = useMemo(
- () =>
- [...topics].sort((a, b) => b.avgVisibilityScore - a.avgVisibilityScore),
+ () => [...topics].sort((a, b) => b.avgVisibilityScore - a.avgVisibilityScore),
[topics],
);
@@ -211,17 +194,11 @@ export default function TopicsPage() {
gainer: null as TopicOverviewRow | null,
};
}
- const best = [...withData].sort(
- (a, b) => b.avgVisibilityScore - a.avgVisibilityScore,
- )[0];
- const weakest = [...withData].sort(
- (a, b) => a.avgVisibilityScore - b.avgVisibilityScore,
- )[0];
+ const best = [...withData].sort((a, b) => b.avgVisibilityScore - a.avgVisibilityScore)[0];
+ const weakest = [...withData].sort((a, b) => a.avgVisibilityScore - b.avgVisibilityScore)[0];
const withChange = topics.filter((t) => t.visibilityChange !== null);
const gainer = withChange.length
- ? [...withChange].sort(
- (a, b) => (b.visibilityChange ?? 0) - (a.visibilityChange ?? 0),
- )[0]
+ ? [...withChange].sort((a, b) => (b.visibilityChange ?? 0) - (a.visibilityChange ?? 0))[0]
: null;
return {
@@ -368,9 +345,7 @@ export default function TopicsPage() {
{/* Leaderboard */}
<Card>
<CardHeader className="pb-3">
- <CardTitle className="text-sm font-medium">
- Topic leaderboard
- </CardTitle>
+ <CardTitle className="text-sm font-medium">Topic leaderboard</CardTitle>
<p className="text-xs text-muted-foreground">
Click a topic to drill into detailed analytics
</p>
@@ -410,10 +385,7 @@ export default function TopicsPage() {
{sortedByVisibility.map((t) => (
<TableRow key={t.id} className="group hover:bg-muted/50">
<TableCell className="pl-6 font-medium text-sm">
- <Link
- href={`/dashboard/topics/${t.id}`}
- className="hover:underline"
- >
+ <Link href={`/dashboard/topics/${t.id}`} className="hover:underline">
{t.name}
</Link>
</TableCell>
@@ -457,28 +429,26 @@ export default function TopicsPage() {
{t.totalCitations.toLocaleString()}
</TableCell>
<TableCell>
- {t.trendSparkline.length > 0 &&
- t.trendSparkline.some((v) => v > 0) ? (
+ {t.trendSparkline.length > 0 && t.trendSparkline.some((v) => v > 0) ? (
<div className="flex items-center gap-2">
<Sparkline points={t.trendSparkline} />
- {t.visibilityChange !== null &&
- t.visibilityChange !== 0 && (
- <span
- className={cn(
- 'text-xs font-medium tabular-nums',
- t.visibilityChange > 0
- ? 'text-emerald-600 dark:text-emerald-400'
- : 'text-rose-600 dark:text-rose-400',
- )}
- >
- {t.visibilityChange > 0 ? (
- <TrendingUp className="h-3 w-3 inline mr-0.5" />
- ) : (
- <TrendingDown className="h-3 w-3 inline mr-0.5" />
- )}
- {Math.abs(t.visibilityChange).toFixed(1)}%
- </span>
- )}
+ {t.visibilityChange !== null && t.visibilityChange !== 0 && (
+ <span
+ className={cn(
+ 'text-xs font-medium tabular-nums',
+ t.visibilityChange > 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-rose-600 dark:text-rose-400',
+ )}
+ >
+ {t.visibilityChange > 0 ? (
+ <TrendingUp className="h-3 w-3 inline mr-0.5" />
+ ) : (
+ <TrendingDown className="h-3 w-3 inline mr-0.5" />
+ )}
+ {Math.abs(t.visibilityChange).toFixed(1)}%
+ </span>
+ )}
{t.visibilityChange === 0 && (
<Minus className="h-3 w-3 text-muted-foreground" />
)}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
index d236e0c3f..8d80c5dd1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
@@ -1,6 +1,6 @@
-"use client";
+'use client';
-import { useRef, useState, useEffect } from "react";
+import { useRef, useState, useEffect } from 'react';
import {
AreaChart,
Area,
@@ -12,8 +12,8 @@ import {
PieChart,
Pie,
Cell,
-} from "recharts";
-import type { TrafficTrendPoint } from "@/lib/actions/traffic";
+} from 'recharts';
+import type { TrafficTrendPoint } from '@/lib/actions/traffic';
// ─── Auto-sizing wrapper ─────────────────────────────────────────────────────
@@ -40,7 +40,7 @@ function ChartContainer({
}, []);
return (
- <div ref={ref} style={{ width: "100%", height }}>
+ <div ref={ref} style={{ width: '100%', height }}>
{width > 0 && children(width)}
</div>
);
@@ -49,37 +49,37 @@ function ChartContainer({
// ─── Platform colors ─────────────────────────────────────────────────────────
const PLATFORM_COLORS: Record<string, string> = {
- "chatgpt.com": "#6366f1",
- "chat.openai.com": "#6366f1",
- "search.chatgpt.com": "#6366f1",
- "perplexity.ai": "#8b5cf6",
- "claude.ai": "#c4b5fd",
- "gemini.google.com": "#a78bfa",
- "copilot.microsoft.com": "#ddd6fe",
- "you.com": "#818cf8",
- "phind.com": "#a5b4fc",
- "meta.ai": "#7c3aed",
- "poe.com": "#e9d5ff",
- unknown: "#94a3b8",
+ 'chatgpt.com': '#6366f1',
+ 'chat.openai.com': '#6366f1',
+ 'search.chatgpt.com': '#6366f1',
+ 'perplexity.ai': '#8b5cf6',
+ 'claude.ai': '#c4b5fd',
+ 'gemini.google.com': '#a78bfa',
+ 'copilot.microsoft.com': '#ddd6fe',
+ 'you.com': '#818cf8',
+ 'phind.com': '#a5b4fc',
+ 'meta.ai': '#7c3aed',
+ 'poe.com': '#e9d5ff',
+ unknown: '#94a3b8',
};
const PLATFORM_NAMES: Record<string, string> = {
- "chatgpt.com": "ChatGPT",
- "chat.openai.com": "ChatGPT",
- "search.chatgpt.com": "ChatGPT",
- "perplexity.ai": "Perplexity",
- "claude.ai": "Claude",
- "gemini.google.com": "Gemini",
- "copilot.microsoft.com": "Copilot",
- "you.com": "You.com",
- "phind.com": "Phind",
- "meta.ai": "Meta AI",
- "poe.com": "Poe",
- unknown: "Unknown",
+ 'chatgpt.com': 'ChatGPT',
+ 'chat.openai.com': 'ChatGPT',
+ 'search.chatgpt.com': 'ChatGPT',
+ 'perplexity.ai': 'Perplexity',
+ 'claude.ai': 'Claude',
+ 'gemini.google.com': 'Gemini',
+ 'copilot.microsoft.com': 'Copilot',
+ 'you.com': 'You.com',
+ 'phind.com': 'Phind',
+ 'meta.ai': 'Meta AI',
+ 'poe.com': 'Poe',
+ unknown: 'Unknown',
};
function getColor(platform: string): string {
- return PLATFORM_COLORS[platform] ?? "#94a3b8";
+ return PLATFORM_COLORS[platform] ?? '#94a3b8';
}
export function getPlatformName(platform: string): string {
@@ -171,7 +171,7 @@ export function ReferralTrendChart({ data }: { data: TrafficTrendPoint[] }) {
if (!data.length) return null;
// Extract platform keys (everything except 'date')
- const platformKeys = Object.keys(data[0]).filter((k) => k !== "date");
+ const platformKeys = Object.keys(data[0]).filter((k) => k !== 'date');
return (
<ChartContainer height={220}>
@@ -199,7 +199,7 @@ export function ReferralTrendChart({ data }: { data: TrafficTrendPoint[] }) {
className="fill-muted-foreground"
tickFormatter={(v: string) => {
const d = new Date(v);
- return d.toLocaleDateString("en", { month: "short", day: "numeric" });
+ return d.toLocaleDateString('en', { month: 'short', day: 'numeric' });
}}
/>
<YAxis
@@ -235,11 +235,7 @@ export function ReferralTrendChart({ data }: { data: TrafficTrendPoint[] }) {
);
}
-export function PlatformBreakdownChart({
- data,
-}: {
- data: { platform: string; visits: number }[];
-}) {
+export function PlatformBreakdownChart({ data }: { data: { platform: string; visits: number }[] }) {
const [hovered, setHovered] = useState<string | null>(null);
const total = data.reduce((s, d) => s + d.visits, 0) || 1;
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index 50b79d842..9e778ade9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -1,8 +1,8 @@
-"use client";
+'use client';
-import { useState, useEffect, useCallback } from "react";
-import { ReferralTrendChart, PlatformBreakdownChart, getPlatformName } from "./_charts";
-import { useBrandStore } from "@/stores/use-brand-store";
+import { useState, useEffect, useCallback } from 'react';
+import { ReferralTrendChart, PlatformBreakdownChart, getPlatformName } from './_charts';
+import { useBrandStore } from '@/stores/use-brand-store';
import {
getTrafficSummary,
getTrafficTrend,
@@ -10,9 +10,9 @@ import {
type TrafficSummary,
type TrafficTrendPoint,
type TrafficLog,
-} from "@/lib/actions/traffic";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
+} from '@/lib/actions/traffic';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
import {
Table,
TableBody,
@@ -20,8 +20,8 @@ import {
TableHead,
TableHeader,
TableRow,
-} from "@/components/ui/table";
-import { Skeleton } from "@/components/ui/skeleton";
+} from '@/components/ui/table';
+import { Skeleton } from '@/components/ui/skeleton';
import {
Globe,
TrendingUp,
@@ -31,9 +31,9 @@ import {
Code,
Copy,
Check,
-} from "lucide-react";
-import { cn } from "@/lib/utils";
-import { Button } from "@/components/ui/button";
+} from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { Button } from '@/components/ui/button';
// ─── Sub-components ───────────────────────────────────────────────────────────
@@ -62,12 +62,12 @@ function KpiCard({
<div className="text-3xl font-bold">{value}</div>
<p
className={cn(
- "text-xs mt-1 flex items-center gap-0.5",
+ 'text-xs mt-1 flex items-center gap-0.5',
subPositive === true
- ? "text-green-600 dark:text-green-400"
+ ? 'text-green-600 dark:text-green-400'
: subPositive === false
- ? "text-red-500"
- : "text-muted-foreground"
+ ? 'text-red-500'
+ : 'text-muted-foreground',
)}
>
{sub}
@@ -78,33 +78,37 @@ function KpiCard({
}
function DeltaBadge({ current, previous }: { current: number; previous: number }) {
- if (previous === 0 && current === 0) return <span className="text-xs text-muted-foreground">—</span>;
- if (previous === 0) return (
- <span className="flex items-center gap-0.5 text-xs font-medium text-green-600 dark:text-green-400">
- <TrendingUp className="h-3 w-3" />new
- </span>
- );
+ if (previous === 0 && current === 0)
+ return <span className="text-xs text-muted-foreground">—</span>;
+ if (previous === 0)
+ return (
+ <span className="flex items-center gap-0.5 text-xs font-medium text-green-600 dark:text-green-400">
+ <TrendingUp className="h-3 w-3" />
+ new
+ </span>
+ );
const delta = Math.round(((current - previous) / previous) * 100);
if (delta === 0) return <span className="text-xs text-muted-foreground">—</span>;
const pos = delta > 0;
return (
<span
className={cn(
- "flex items-center gap-0.5 text-xs font-medium",
- pos ? "text-green-600 dark:text-green-400" : "text-red-500"
+ 'flex items-center gap-0.5 text-xs font-medium',
+ pos ? 'text-green-600 dark:text-green-400' : 'text-red-500',
)}
>
{pos ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
- {pos ? "+" : ""}{delta}%
+ {pos ? '+' : ''}
+ {delta}%
</span>
);
}
function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
const [copied, setCopied] = useState(false);
- const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === "true";
- const apiUrl = isCloud ? "https://api.ansops.ai" : process.env.NEXT_PUBLIC_API_URL;
- const snippet = `<script src="${apiUrl}/t.js" data-t="${trackingCode || "YOUR_TRACKING_CODE"}" defer></script>`;
+ const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === 'true';
+ const apiUrl = isCloud ? 'https://api.ansops.ai' : process.env.NEXT_PUBLIC_API_URL;
+ const snippet = `<script src="${apiUrl}/t.js" data-t="${trackingCode || 'YOUR_TRACKING_CODE'}" defer></script>`;
if (!trackingCode || !apiUrl) return null;
@@ -121,7 +125,8 @@ function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">Add this snippet to your website</p>
<p className="text-xs text-muted-foreground mt-0.5">
- Paste this before the closing <code className="text-[11px]">&lt;/head&gt;</code> tag to track AI-referred visits.
+ Paste this before the closing <code className="text-[11px]">&lt;/head&gt;</code> tag to
+ track AI-referred visits.
</p>
<div className="mt-2 relative">
<pre className="text-[11px] bg-muted/50 rounded-md px-3 py-2 overflow-x-auto font-mono">
@@ -130,7 +135,11 @@ function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
</div>
</div>
<Button variant="ghost" size="icon" className="shrink-0 h-8 w-8" onClick={handleCopy}>
- {copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}
+ {copied ? (
+ <Check className="h-3.5 w-3.5 text-green-500" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
</Button>
</CardContent>
</Card>
@@ -140,7 +149,7 @@ function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
function timeAgo(dateStr: string): string {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
- if (mins < 1) return "just now";
+ if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
@@ -174,7 +183,7 @@ export default function TrafficPage() {
setLogs(l.logs);
setLogsTotal(l.total);
} catch (err) {
- console.error("Failed to load traffic data:", err);
+ console.error('Failed to load traffic data:', err);
} finally {
setIsLoading(false);
}
@@ -219,9 +228,8 @@ export default function TrafficPage() {
const totalVisits = summary?.totalVisits ?? 0;
const totalVisitsPrev = summary?.totalVisitsPrev ?? 0;
- const visitsDelta = totalVisitsPrev > 0
- ? Math.round(((totalVisits - totalVisitsPrev) / totalVisitsPrev) * 100)
- : 0;
+ const visitsDelta =
+ totalVisitsPrev > 0 ? Math.round(((totalVisits - totalVisitsPrev) / totalVisitsPrev) * 100) : 0;
const topPlatform = summary?.platformBreakdown[0];
const isEmpty = totalVisits === 0 && logs.length === 0;
@@ -232,7 +240,7 @@ export default function TrafficPage() {
<div>
<h1 className="text-2xl font-bold tracking-tight">AI Traffic Analytics</h1>
<p className="text-muted-foreground text-sm">
- {primaryDomain ? `${primaryDomain} · ` : ""}AI-referred visits to your website
+ {primaryDomain ? `${primaryDomain} · ` : ''}AI-referred visits to your website
</p>
</div>
@@ -246,8 +254,8 @@ export default function TrafficPage() {
<h3 className="text-lg font-semibold mt-4">No traffic data yet</h3>
<p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">
{brand.trackingCode
- ? "Once visitors arrive from AI platforms, their visits will appear here."
- : "Add the tracking snippet to your website to start collecting AI-referred traffic data."}
+ ? 'Once visitors arrive from AI platforms, their visits will appear here.'
+ : 'Add the tracking snippet to your website to start collecting AI-referred traffic data.'}
</p>
</CardContent>
</Card>
@@ -262,11 +270,16 @@ export default function TrafficPage() {
sub={
totalVisitsPrev > 0 ? (
<>
- {visitsDelta >= 0 ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
- {visitsDelta >= 0 ? "+" : ""}{visitsDelta}% vs previous period
+ {visitsDelta >= 0 ? (
+ <TrendingUp className="h-3 w-3" />
+ ) : (
+ <TrendingDown className="h-3 w-3" />
+ )}
+ {visitsDelta >= 0 ? '+' : ''}
+ {visitsDelta}% vs previous period
</>
) : (
- "last 7 days"
+ 'last 7 days'
)
}
subPositive={visitsDelta > 0 ? true : visitsDelta < 0 ? false : undefined}
@@ -274,8 +287,8 @@ export default function TrafficPage() {
<KpiCard
title="Top Platform"
icon={Globe}
- value={topPlatform ? getPlatformName(topPlatform.platform) : "—"}
- sub={topPlatform ? `${topPlatform.visits} visits` : "no data"}
+ value={topPlatform ? getPlatformName(topPlatform.platform) : '—'}
+ sub={topPlatform ? `${topPlatform.visits} visits` : 'no data'}
/>
<KpiCard
title="Platforms"
@@ -289,7 +302,9 @@ export default function TrafficPage() {
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
<Card className="lg:col-span-2">
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">AI Referral Trend — Last 7 Days</CardTitle>
+ <CardTitle className="text-sm font-medium">
+ AI Referral Trend — Last 7 Days
+ </CardTitle>
</CardHeader>
<CardContent>
<ReferralTrendChart data={trend} />
@@ -326,7 +341,9 @@ export default function TrafficPage() {
{(summary?.platformBreakdown ?? []).map((row) => (
<TableRow key={row.platform} className="hover:bg-muted/50">
<TableCell className="pl-6">
- <span className="font-medium text-sm">{getPlatformName(row.platform)}</span>
+ <span className="font-medium text-sm">
+ {getPlatformName(row.platform)}
+ </span>
</TableCell>
<TableCell className="text-right font-semibold tabular-nums">
{row.visits.toLocaleString()}
@@ -390,7 +407,9 @@ export default function TrafficPage() {
<CardTitle className="text-sm font-medium">Recent AI Referral Visits</CardTitle>
</div>
{logsTotal > 10 && (
- <Badge variant="secondary" className="text-xs">{logsTotal} total</Badge>
+ <Badge variant="secondary" className="text-xs">
+ {logsTotal} total
+ </Badge>
)}
</div>
</CardHeader>
@@ -411,17 +430,23 @@ export default function TrafficPage() {
{timeAgo(row.createdAt)}
</TableCell>
<TableCell>
- <span className="text-sm">{getPlatformName(row.sourcePlatform ?? "unknown")}</span>
+ <span className="text-sm">
+ {getPlatformName(row.sourcePlatform ?? 'unknown')}
+ </span>
</TableCell>
<TableCell>
<span className="font-mono text-xs text-muted-foreground line-clamp-1">
{(() => {
- try { return new URL(row.url).pathname; } catch { return row.url; }
+ try {
+ return new URL(row.url).pathname;
+ } catch {
+ return row.url;
+ }
})()}
</span>
</TableCell>
<TableCell className="text-right pr-6">
- <span className="text-xs text-muted-foreground">{row.country ?? "—"}</span>
+ <span className="text-xs text-muted-foreground">{row.country ?? '—'}</span>
</TableCell>
</TableRow>
))}
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index 34c2eb5ab..cda0dbcf9 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -10,11 +10,7 @@ import { BrandGuard } from '@/components/providers/brand-guard';
import { getBrands } from '@/lib/actions/brand';
import { isCloud, type PlanId } from '@/config/plans';
-export default async function DashboardLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const supabase = await createClient();
const {
data: { user },
diff --git a/web/src/app/[locale]/(marketing)/auth/callback/route.ts b/web/src/app/[locale]/(marketing)/auth/callback/route.ts
index 6fa33085b..65acabc50 100644
--- a/web/src/app/[locale]/(marketing)/auth/callback/route.ts
+++ b/web/src/app/[locale]/(marketing)/auth/callback/route.ts
@@ -1,18 +1,18 @@
-import { NextResponse } from "next/server";
-import { createClient } from "@/lib/supabase/server";
+import { NextResponse } from 'next/server';
+import { createClient } from '@/lib/supabase/server';
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
- const code = searchParams.get("code");
- const next = searchParams.get("next") ?? "/dashboard";
+ const code = searchParams.get('code');
+ const next = searchParams.get('next') ?? '/dashboard';
if (code) {
const supabase = await createClient();
const { error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) {
- const forwardedHost = request.headers.get("x-forwarded-host");
- const isLocalEnv = process.env.NODE_ENV === "development";
+ const forwardedHost = request.headers.get('x-forwarded-host');
+ const isLocalEnv = process.env.NODE_ENV === 'development';
if (isLocalEnv) {
return NextResponse.redirect(`${origin}${next}`);
diff --git a/web/src/app/[locale]/(marketing)/layout.tsx b/web/src/app/[locale]/(marketing)/layout.tsx
index 34204ee5c..5a1a44975 100644
--- a/web/src/app/[locale]/(marketing)/layout.tsx
+++ b/web/src/app/[locale]/(marketing)/layout.tsx
@@ -1,11 +1,7 @@
-import { MarketingHeader } from "@/components/marketing/marketing-header";
-import { MarketingFooter } from "@/components/marketing/marketing-footer";
+import { MarketingHeader } from '@/components/marketing/marketing-header';
+import { MarketingFooter } from '@/components/marketing/marketing-footer';
-export default function MarketingLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default function MarketingLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex min-h-screen flex-col">
<MarketingHeader />
diff --git a/web/src/app/[locale]/(marketing)/pricing/page.tsx b/web/src/app/[locale]/(marketing)/pricing/page.tsx
index 78a540e84..708e68c90 100644
--- a/web/src/app/[locale]/(marketing)/pricing/page.tsx
+++ b/web/src/app/[locale]/(marketing)/pricing/page.tsx
@@ -1,45 +1,37 @@
-"use client";
+'use client';
+import { useTranslations } from 'next-intl';
+import { Link } from '@/i18n/navigation';
+import { PLANS, PLAN_ORDER, type PlanId } from '@/config/plans';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import { Separator } from '@/components/ui/separator';
+import { cn } from '@/lib/utils';
+import { Check, Minus, Github } from 'lucide-react';
-import { useTranslations } from "next-intl";
-import { Link } from "@/i18n/navigation";
-import { PLANS, PLAN_ORDER, type PlanId } from "@/config/plans";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { cn } from "@/lib/utils";
-import { Check, Minus, Github } from "lucide-react";
-
-
-function PlanCard({
- planId,
-}: {
- planId: PlanId;
-}) {
+function PlanCard({ planId }: { planId: PlanId }) {
const plan = PLANS[planId];
const price = plan.pricing;
const isHighlighted = plan.highlighted;
const displayPrice = price === null ? null : price.monthly;
const ctaMap: Record<PlanId, { label: string; href: string }> = {
- self_hosted: { label: "Self-Host", href: "/docs/self-host" },
- starter: { label: "Get Started", href: "/sign-up" },
- growth: { label: "Start Free Trial", href: "/sign-up" },
- enterprise: { label: "Contact Sales", href: "mailto:[email protected]" },
+ self_hosted: { label: 'Self-Host', href: '/docs/self-host' },
+ starter: { label: 'Get Started', href: '/sign-up' },
+ growth: { label: 'Start Free Trial', href: '/sign-up' },
+ enterprise: { label: 'Contact Sales', href: 'mailto:[email protected]' },
};
const cta = ctaMap[planId];
return (
<div
className={cn(
- "relative flex flex-col rounded-2xl border bg-card p-6 shadow-sm transition-shadow hover:shadow-md",
- isHighlighted && "border-primary shadow-md ring-1 ring-primary/20",
+ 'relative flex flex-col rounded-2xl border bg-card p-6 shadow-sm transition-shadow hover:shadow-md',
+ isHighlighted && 'border-primary shadow-md ring-1 ring-primary/20',
)}
>
{isHighlighted && (
- <Badge className="absolute -top-3 left-1/2 -translate-x-1/2">
- Most Popular
- </Badge>
+ <Badge className="absolute -top-3 left-1/2 -translate-x-1/2">Most Popular</Badge>
)}
<div className="mb-6">
@@ -49,27 +41,19 @@ function PlanCard({
<div className="mt-4 flex items-end gap-1">
{displayPrice !== null ? (
<>
- <span className="text-4xl font-bold tracking-tight">
- ${displayPrice}
- </span>
+ <span className="text-4xl font-bold tracking-tight">${displayPrice}</span>
{displayPrice !== 0 && (
- <span className="mb-1 text-sm text-muted-foreground">
- /month
- </span>
+ <span className="mb-1 text-sm text-muted-foreground">/month</span>
)}
</>
) : (
<span className="text-3xl font-bold tracking-tight">Custom</span>
)}
</div>
-
</div>
<Link href={cta.href}>
- <Button
- variant={isHighlighted ? "default" : "outline"}
- className="w-full"
- >
+ <Button variant={isHighlighted ? 'default' : 'outline'} className="w-full">
{cta.label}
</Button>
</Link>
@@ -78,63 +62,51 @@ function PlanCard({
<div className="flex-1 space-y-3 text-sm">
<PlanFeature>
- <strong>
- {plan.limits.maxBrands === -1
- ? "Unlimited"
- : plan.limits.maxBrands}
- </strong>{" "}
- {plan.limits.maxBrands === 1 ? "brand" : "brands"}
+ <strong>{plan.limits.maxBrands === -1 ? 'Unlimited' : plan.limits.maxBrands}</strong>{' '}
+ {plan.limits.maxBrands === 1 ? 'brand' : 'brands'}
</PlanFeature>
<PlanFeature>
- <strong>
- {plan.limits.maxPrompts === -1
- ? "Unlimited"
- : plan.limits.maxPrompts}
- </strong>{" "}
+ <strong>{plan.limits.maxPrompts === -1 ? 'Unlimited' : plan.limits.maxPrompts}</strong>{' '}
prompts tracked
</PlanFeature>
<PlanFeature>
{plan.limits.maxPlatforms === 1 ? (
- <><strong>1</strong> platform (ChatGPT)</>
+ <>
+ <strong>1</strong> platform (ChatGPT)
+ </>
) : (
- <><strong>{plan.limits.maxPlatforms}</strong> AI platforms</>
+ <>
+ <strong>{plan.limits.maxPlatforms}</strong> AI platforms
+ </>
)}
</PlanFeature>
<PlanFeature>
<strong>
- {plan.limits.maxTeamMembers === -1
- ? "Unlimited"
- : plan.limits.maxTeamMembers}
- </strong>{" "}
- team {plan.limits.maxTeamMembers === 1 ? "member" : "members"}
+ {plan.limits.maxTeamMembers === -1 ? 'Unlimited' : plan.limits.maxTeamMembers}
+ </strong>{' '}
+ team {plan.limits.maxTeamMembers === 1 ? 'member' : 'members'}
</PlanFeature>
<PlanFeature>
- {plan.limits.features.includes("daily_monitoring")
- ? "Daily monitoring"
- : "Weekly monitoring"}
+ {plan.limits.features.includes('daily_monitoring')
+ ? 'Daily monitoring'
+ : 'Weekly monitoring'}
</PlanFeature>
- {plan.limits.features.includes("competitor_tracking") && (
+ {plan.limits.features.includes('competitor_tracking') && (
<PlanFeature>Competitor tracking</PlanFeature>
)}
- {plan.limits.features.includes("content_optimization") && (
+ {plan.limits.features.includes('content_optimization') && (
<PlanFeature>Content optimization</PlanFeature>
)}
- {plan.limits.features.includes("advanced_analytics") && (
+ {plan.limits.features.includes('advanced_analytics') && (
<PlanFeature>Advanced analytics</PlanFeature>
)}
- {plan.limits.features.includes("custom_reports") && (
+ {plan.limits.features.includes('custom_reports') && (
<PlanFeature>Custom reports</PlanFeature>
)}
- {plan.limits.features.includes("api_access") && (
- <PlanFeature>API access</PlanFeature>
- )}
- {plan.limits.features.includes("white_label") && (
- <PlanFeature>White-label</PlanFeature>
- )}
- {plan.limits.features.includes("sso_saml") && (
- <PlanFeature>SSO / SAML</PlanFeature>
- )}
+ {plan.limits.features.includes('api_access') && <PlanFeature>API access</PlanFeature>}
+ {plan.limits.features.includes('white_label') && <PlanFeature>White-label</PlanFeature>}
+ {plan.limits.features.includes('sso_saml') && <PlanFeature>SSO / SAML</PlanFeature>}
</div>
</div>
);
@@ -161,101 +133,101 @@ const COMPARISON_SECTIONS: {
rows: ComparisonRow[];
}[] = [
{
- title: "Answer Engine Insights",
+ title: 'Answer Engine Insights',
rows: [
{
- label: "AI platforms",
- values: { self_hosted: "All 8", starter: "4", growth: "All 8", enterprise: "All 8" },
+ label: 'AI platforms',
+ values: { self_hosted: 'All 8', starter: '4', growth: 'All 8', enterprise: 'All 8' },
},
{
- label: "Prompts tracked",
- values: { self_hosted: "Unlimited", starter: "10", growth: "200", enterprise: "Unlimited" },
+ label: 'Prompts tracked',
+ values: { self_hosted: 'Unlimited', starter: '10', growth: '200', enterprise: 'Unlimited' },
},
{
- label: "Daily monitoring",
+ label: 'Daily monitoring',
values: { self_hosted: true, starter: true, growth: true, enterprise: true },
},
{
- label: "Competitor tracking",
+ label: 'Competitor tracking',
values: { self_hosted: true, starter: true, growth: true, enterprise: true },
},
{
- label: "Sentiment analysis",
+ label: 'Sentiment analysis',
values: { self_hosted: true, starter: true, growth: true, enterprise: true },
},
{
- label: "Prompt suggestions (AI)",
+ label: 'Prompt suggestions (AI)',
values: { self_hosted: true, starter: true, growth: true, enterprise: true },
},
],
},
{
- title: "Content & Optimization",
+ title: 'Content & Optimization',
rows: [
{
- label: "Content optimization",
+ label: 'Content optimization',
values: { self_hosted: true, starter: false, growth: true, enterprise: true },
},
{
- label: "Advanced analytics",
+ label: 'Advanced analytics',
values: { self_hosted: true, starter: false, growth: true, enterprise: true },
},
{
- label: "Custom reports",
+ label: 'Custom reports',
values: { self_hosted: true, starter: false, growth: true, enterprise: true },
},
],
},
{
- title: "Organization",
+ title: 'Organization',
rows: [
{
- label: "Brands",
- values: { self_hosted: "Unlimited", starter: "1", growth: "10", enterprise: "Unlimited" },
+ label: 'Brands',
+ values: { self_hosted: 'Unlimited', starter: '1', growth: '10', enterprise: 'Unlimited' },
},
{
- label: "Team members",
- values: { self_hosted: "Unlimited", starter: "3", growth: "10", enterprise: "Unlimited" },
+ label: 'Team members',
+ values: { self_hosted: 'Unlimited', starter: '3', growth: '10', enterprise: 'Unlimited' },
},
{
- label: "Domains per brand",
- values: { self_hosted: "Unlimited", starter: "3", growth: "10", enterprise: "Unlimited" },
+ label: 'Domains per brand',
+ values: { self_hosted: 'Unlimited', starter: '3', growth: '10', enterprise: 'Unlimited' },
},
{
- label: "API access",
+ label: 'API access',
values: { self_hosted: true, starter: false, growth: true, enterprise: true },
},
{
- label: "White-label",
+ label: 'White-label',
values: { self_hosted: true, starter: false, growth: false, enterprise: true },
},
{
- label: "SSO / SAML",
+ label: 'SSO / SAML',
values: { self_hosted: false, starter: false, growth: false, enterprise: true },
},
],
},
{
- title: "Support",
+ title: 'Support',
rows: [
{
- label: "Community support",
+ label: 'Community support',
values: { self_hosted: true, starter: true, growth: true, enterprise: true },
},
{
- label: "Email support",
+ label: 'Email support',
values: { self_hosted: false, starter: true, growth: true, enterprise: true },
},
{
- label: "Priority support",
+ label: 'Priority support',
values: { self_hosted: false, starter: false, growth: true, enterprise: true },
},
{
- label: "Dedicated success manager",
+ label: 'Dedicated success manager',
values: { self_hosted: false, starter: false, growth: false, enterprise: true },
},
{
- label: "SLA",
+ label: 'SLA',
values: { self_hosted: false, starter: false, growth: false, enterprise: true },
},
],
@@ -263,7 +235,7 @@ const COMPARISON_SECTIONS: {
];
function ComparisonCell({ value }: { value: string | boolean }) {
- if (typeof value === "boolean") {
+ if (typeof value === 'boolean') {
return value ? (
<Check className="mx-auto h-4 w-4 text-primary" />
) : (
@@ -321,19 +293,15 @@ function ComparisonTable() {
// ─── Main Page ───────────────────────────────────────────────────────────────
export default function PricingPage() {
- const t = useTranslations("marketing.pricing");
+ const t = useTranslations('marketing.pricing');
return (
<div className="py-20">
<div className="container max-w-6xl">
{/* Header */}
<div className="mb-4 text-center">
- <h1 className="text-4xl font-bold tracking-tight sm:text-5xl">
- {t("title")}
- </h1>
- <p className="mt-3 text-lg text-muted-foreground">
- {t("subtitle")}
- </p>
+ <h1 className="text-4xl font-bold tracking-tight sm:text-5xl">{t('title')}</h1>
+ <p className="mt-3 text-lg text-muted-foreground">{t('subtitle')}</p>
</div>
{/* Self-hosted banner */}
@@ -341,11 +309,11 @@ export default function PricingPage() {
<div className="inline-flex items-center gap-2 rounded-full border bg-card px-4 py-2 text-sm">
<Github className="h-4 w-4" />
<span>
- Self-host for free with{" "}
+ Self-host for free with{' '}
<strong className="text-foreground">all features unlocked</strong>
- </span>
- </div>
- </div>
+ </span>
+ </div>
+ </div>
{/* Plan cards */}
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
@@ -357,7 +325,7 @@ export default function PricingPage() {
{/* Comparison table */}
<div className="mt-20">
<h2 className="mb-8 text-center text-2xl font-bold tracking-tight">
- {t("compareTitle")}
+ {t('compareTitle')}
</h2>
<div className="rounded-xl border bg-card p-6 shadow-sm">
<ComparisonTable />
@@ -367,9 +335,9 @@ export default function PricingPage() {
{/* Open source callout */}
<div className="mt-16 rounded-2xl border bg-card p-8 text-center shadow-sm">
<Github className="mx-auto h-10 w-10 text-muted-foreground" />
- <h3 className="mt-4 text-xl font-bold">{t("ossTitle")}</h3>
+ <h3 className="mt-4 text-xl font-bold">{t('ossTitle')}</h3>
<p className="mx-auto mt-2 max-w-md text-sm text-muted-foreground">
- {t("ossDescription")}
+ {t('ossDescription')}
</p>
<div className="mt-6 flex justify-center gap-3">
<Link href="https://github.com/your-org/ansvisor">
diff --git a/web/src/app/[locale]/(marketing)/sign-in/page.tsx b/web/src/app/[locale]/(marketing)/sign-in/page.tsx
index f05f7c20b..66b8c9c16 100644
--- a/web/src/app/[locale]/(marketing)/sign-in/page.tsx
+++ b/web/src/app/[locale]/(marketing)/sign-in/page.tsx
@@ -1,7 +1,7 @@
-import { useTranslations } from "next-intl";
-import { Link } from "@/i18n/navigation";
-import { SignInForm } from "@/components/auth/sign-in-form";
-import { MailCheck } from "lucide-react";
+import { useTranslations } from 'next-intl';
+import { Link } from '@/i18n/navigation';
+import { SignInForm } from '@/components/auth/sign-in-form';
+import { MailCheck } from 'lucide-react';
export default async function SignInPage({
searchParams,
@@ -9,7 +9,7 @@ export default async function SignInPage({
searchParams: Promise<{ verified?: string }>;
}) {
const params = await searchParams;
- const showVerificationBanner = params.verified === "pending";
+ const showVerificationBanner = params.verified === 'pending';
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
@@ -22,32 +22,30 @@ export default async function SignInPage({
}
function VerificationBanner() {
- const t = useTranslations("auth");
+ const t = useTranslations('auth');
return (
<div className="flex items-start gap-3 rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-900 dark:bg-blue-950/50">
<MailCheck className="mt-0.5 h-5 w-5 shrink-0 text-blue-600 dark:text-blue-400" />
- <p className="text-sm text-blue-800 dark:text-blue-300">
- {t("verificationPending")}
- </p>
+ <p className="text-sm text-blue-800 dark:text-blue-300">{t('verificationPending')}</p>
</div>
);
}
function SignInCard() {
- const t = useTranslations("auth");
+ const t = useTranslations('auth');
return (
<div className="rounded-xl border bg-card p-6 shadow-sm">
<div className="mb-6 text-center">
- <h1 className="text-2xl font-semibold tracking-tight">{t("signIn")}</h1>
+ <h1 className="text-2xl font-semibold tracking-tight">{t('signIn')}</h1>
<p className="mt-1 text-sm text-muted-foreground">
- {t("noAccount")}{" "}
+ {t('noAccount')}{' '}
<Link
href="/sign-up"
className="font-medium text-primary underline-offset-4 hover:underline"
>
- {t("createAccount")}
+ {t('createAccount')}
</Link>
</p>
</div>
diff --git a/web/src/app/[locale]/(marketing)/sign-up/page.tsx b/web/src/app/[locale]/(marketing)/sign-up/page.tsx
index 3bbad092e..8299f8dee 100644
--- a/web/src/app/[locale]/(marketing)/sign-up/page.tsx
+++ b/web/src/app/[locale]/(marketing)/sign-up/page.tsx
@@ -1,6 +1,6 @@
-import { useTranslations } from "next-intl";
-import { Link } from "@/i18n/navigation";
-import { SignUpForm } from "@/components/auth/sign-up-form";
+import { useTranslations } from 'next-intl';
+import { Link } from '@/i18n/navigation';
+import { SignUpForm } from '@/components/auth/sign-up-form';
export default function SignUpPage() {
return (
@@ -13,19 +13,19 @@ export default function SignUpPage() {
}
function SignUpCard() {
- const t = useTranslations("auth");
+ const t = useTranslations('auth');
return (
<div className="rounded-xl border bg-card p-6 shadow-sm">
<div className="mb-6 text-center">
- <h1 className="text-2xl font-semibold tracking-tight">{t("signUp")}</h1>
+ <h1 className="text-2xl font-semibold tracking-tight">{t('signUp')}</h1>
<p className="mt-1 text-sm text-muted-foreground">
- {t("hasAccount")}{" "}
+ {t('hasAccount')}{' '}
<Link
href="/sign-in"
className="font-medium text-primary underline-offset-4 hover:underline"
>
- {t("signIn")}
+ {t('signIn')}
</Link>
</p>
</div>
diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
index 07feddc90..642dc2747 100644
--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
@@ -58,8 +58,7 @@ import {
} from 'lucide-react';
import { cn } from '@/lib/utils';
-const AEO_SERVER_URL =
- process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
+const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
// ── Step indicator ─────────────────────────────────────────────────────────────
@@ -90,16 +89,10 @@ function BrandHeader({ name, domain }: { name: string; domain: string }) {
<div className="flex items-center gap-2.5 mb-8">
{domain && (
/* eslint-disable-next-line @next/next/no-img-element */
- <img
- src={getFaviconUrl(domain, 32)}
- alt=""
- className="h-6 w-6 rounded"
- />
+ <img src={getFaviconUrl(domain, 32)} alt="" className="h-6 w-6 rounded" />
)}
<span className="text-sm font-medium">{name}</span>
- {domain && (
- <span className="text-sm text-muted-foreground">{domain}</span>
- )}
+ {domain && <span className="text-sm text-muted-foreground">{domain}</span>}
</div>
);
}
@@ -148,9 +141,7 @@ function TopicAccordion({
<ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<span className="font-medium">{data.topic}</span>
- <span className="text-xs text-muted-foreground">
- {data.prompts.length} prompts
- </span>
+ <span className="text-xs text-muted-foreground">{data.prompts.length} prompts</span>
</button>
<DropdownMenu>
<DropdownMenuTrigger className="p-1 rounded hover:bg-muted text-muted-foreground">
@@ -199,12 +190,7 @@ function TopicAccordion({
>
<Check className="h-4 w-4" />
</Button>
- <Button
- size="sm"
- variant="ghost"
- onClick={() => setNewPrompt('')}
- className="h-9 px-2"
- >
+ <Button size="sm" variant="ghost" onClick={() => setNewPrompt('')} className="h-9 px-2">
<X className="h-4 w-4" />
</Button>
</div>
@@ -272,8 +258,7 @@ export default function OnboardingPage() {
topicMsgIdx.current = 0;
const interval = setInterval(() => {
- topicMsgIdx.current =
- (topicMsgIdx.current + 1) % TOPIC_LOADING_MESSAGES.length;
+ topicMsgIdx.current = (topicMsgIdx.current + 1) % TOPIC_LOADING_MESSAGES.length;
setTopicLoadingMsg(TOPIC_LOADING_MESSAGES[topicMsgIdx.current]);
}, 2500);
@@ -290,9 +275,7 @@ export default function OnboardingPage() {
domain: string;
selected: boolean;
}
- const [suggestedCompetitors, setSuggestedCompetitors] = useState<
- CompetitorItem[]
- >([]);
+ const [suggestedCompetitors, setSuggestedCompetitors] = useState<CompetitorItem[]>([]);
const [loadingCompetitors, setLoadingCompetitors] = useState(false);
const [competitorName, setCompetitorName] = useState('');
const [competitorDomain, setCompetitorDomain] = useState('');
@@ -329,9 +312,7 @@ export default function OnboardingPage() {
const interval = setInterval(() => {
competitorMsgIdx.current =
(competitorMsgIdx.current + 1) % COMPETITOR_LOADING_MESSAGES.length;
- setCompetitorLoadingMsg(
- COMPETITOR_LOADING_MESSAGES[competitorMsgIdx.current],
- );
+ setCompetitorLoadingMsg(COMPETITOR_LOADING_MESSAGES[competitorMsgIdx.current]);
}, 2500);
return () => clearInterval(interval);
@@ -409,15 +390,13 @@ export default function OnboardingPage() {
description: b.description ?? undefined,
region: b.region ?? undefined,
language: b.language ?? undefined,
- domains: (b.brand_domains || []).map(
- (d: Record<string, unknown>) => ({
- id: d.id as string,
- brandId: d.brand_id as string,
- domain: d.domain as string,
- country: (d.country as string) ?? undefined,
- isPrimary: d.is_primary as boolean,
- }),
- ),
+ domains: (b.brand_domains || []).map((d: Record<string, unknown>) => ({
+ id: d.id as string,
+ brandId: d.brand_id as string,
+ domain: d.domain as string,
+ country: (d.country as string) ?? undefined,
+ isPrimary: d.is_primary as boolean,
+ })),
createdAt: b.created_at,
updatedAt: b.updated_at,
};
@@ -528,8 +507,7 @@ export default function OnboardingPage() {
.select()
.single();
- if (orgError || !org)
- throw new Error(orgError?.message ?? 'Failed to create organization');
+ if (orgError || !org) throw new Error(orgError?.message ?? 'Failed to create organization');
const { error: profileError } = await supabase
.from('profiles')
@@ -579,9 +557,7 @@ export default function OnboardingPage() {
fetchTopicSuggestions();
}
} catch (err) {
- toast.error(
- err instanceof Error ? err.message : 'Failed to create brand',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to create brand');
} finally {
setIsLoading(false);
}
@@ -688,12 +664,10 @@ export default function OnboardingPage() {
const data = await res.json();
setTopicPrompts(
- (data.topicPrompts || []).map(
- (tp: { topic: string; prompts: string[] }) => ({
- topic: tp.topic,
- prompts: tp.prompts,
- }),
- ),
+ (data.topicPrompts || []).map((tp: { topic: string; prompts: string[] }) => ({
+ topic: tp.topic,
+ prompts: tp.prompts,
+ })),
);
track('onboarding_step_completed', {
step: 3,
@@ -747,9 +721,7 @@ export default function OnboardingPage() {
setStep(5);
fetchCompetitorSuggestions();
} catch (err) {
- toast.error(
- err instanceof Error ? err.message : 'Failed to save prompts',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to save prompts');
} finally {
setIsLoading(false);
}
@@ -814,10 +786,7 @@ export default function OnboardingPage() {
.replace(/^https?:\/\//, '')
.replace(/\/+$/, '');
if (!name) return;
- setSuggestedCompetitors((prev) => [
- ...prev,
- { name, domain, selected: true },
- ]);
+ setSuggestedCompetitors((prev) => [...prev, { name, domain, selected: true }]);
setCompetitorName('');
setCompetitorDomain('');
};
@@ -832,9 +801,7 @@ export default function OnboardingPage() {
const selected = suggestedCompetitors.filter((c) => c.selected);
if (selected.length > 0) {
await Promise.all(
- selected.map((c) =>
- addCompetitor(createdBrand.id, { name: c.name, domain: c.domain }),
- ),
+ selected.map((c) => addCompetitor(createdBrand.id, { name: c.name, domain: c.domain })),
);
}
@@ -844,10 +811,7 @@ export default function OnboardingPage() {
data: { user },
} = await supabase.auth.getUser();
if (user) {
- await supabase
- .from('profiles')
- .update({ onboarding_completed: true })
- .eq('id', user.id);
+ await supabase.from('profiles').update({ onboarding_completed: true }).eq('id', user.id);
}
const competitorCount = selected.length;
@@ -891,9 +855,7 @@ export default function OnboardingPage() {
// the server-side layout reads the fresh onboarding_completed flag.
window.location.href = '/dashboard/insights';
} catch (err) {
- toast.error(
- err instanceof Error ? err.message : 'Failed to save competitors',
- );
+ toast.error(err instanceof Error ? err.message : 'Failed to save competitors');
setSavingCompetitors(false);
}
};
@@ -937,9 +899,7 @@ export default function OnboardingPage() {
const addPromptToTopic = (topicIndex: number, prompt: string) => {
setTopicPrompts((prev) =>
- prev.map((tp, i) =>
- i === topicIndex ? { ...tp, prompts: [...tp.prompts, prompt] } : tp,
- ),
+ prev.map((tp, i) => (i === topicIndex ? { ...tp, prompts: [...tp.prompts, prompt] } : tp)),
);
};
@@ -953,10 +913,7 @@ export default function OnboardingPage() {
);
};
- const totalPrompts = topicPrompts.reduce(
- (sum, tp) => sum + tp.prompts.length,
- 0,
- );
+ const totalPrompts = topicPrompts.reduce((sum, tp) => sum + tp.prompts.length, 0);
// ── Loading state ──
@@ -978,12 +935,9 @@ export default function OnboardingPage() {
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground">
<Globe className="h-6 w-6" />
</div>
- <h1 className="text-2xl font-bold tracking-tight">
- Set up your brand
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Set up your brand</h1>
<p className="text-sm text-muted-foreground">
- See how AI platforms talk about you. Add your first brand to get
- started.
+ See how AI platforms talk about you. Add your first brand to get started.
</p>
</div>
@@ -1017,8 +971,7 @@ export default function OnboardingPage() {
<div className="space-y-2">
<Label htmlFor="description">
- Describe your brand{' '}
- <span className="text-muted-foreground">(optional)</span>
+ Describe your brand <span className="text-muted-foreground">(optional)</span>
</Label>
<Textarea
id="description"
@@ -1069,12 +1022,10 @@ export default function OnboardingPage() {
<BrandHeader name={brandName} domain={domain} />
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Select your target market
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Select your target market</h1>
<p className="text-sm text-muted-foreground mt-1">
- Pick the region and language your audience uses. This helps us
- deliver more accurate AI visibility data.
+ Pick the region and language your audience uses. This helps us deliver more accurate
+ AI visibility data.
</p>
</div>
@@ -1097,10 +1048,7 @@ export default function OnboardingPage() {
<div className="space-y-2">
<Label>Language</Label>
- <Select
- value={language}
- onValueChange={(v) => v && setLanguage(v)}
- >
+ <Select value={language} onValueChange={(v) => v && setLanguage(v)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
@@ -1114,11 +1062,7 @@ export default function OnboardingPage() {
</Select>
</div>
- <Button
- className="w-full"
- onClick={handleCreateOrgAndBrand}
- disabled={isLoading}
- >
+ <Button className="w-full" onClick={handleCreateOrgAndBrand} disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -1157,13 +1101,9 @@ export default function OnboardingPage() {
<div className="grid grid-cols-1 gap-10 lg:grid-cols-5">
<div className="lg:col-span-3 space-y-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Choose topics to monitor
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Choose topics to monitor</h1>
<div className="flex items-center gap-2 mt-3">
- <span className="text-sm text-muted-foreground">
- Select up to 10 topics
- </span>
+ <span className="text-sm text-muted-foreground">Select up to 10 topics</span>
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full bg-primary rounded-full transition-all"
@@ -1178,10 +1118,7 @@ export default function OnboardingPage() {
{loadingTopics ? (
<div className="flex flex-col items-center gap-3 py-12 text-muted-foreground">
<Sparkles className="h-5 w-5 animate-pulse" />
- <span
- key={topicLoadingMsg}
- className="text-sm animate-in fade-in duration-500"
- >
+ <span key={topicLoadingMsg} className="text-sm animate-in fade-in duration-500">
{topicLoadingMsg}
</span>
</div>
@@ -1237,9 +1174,7 @@ export default function OnboardingPage() {
<Button
className="w-full"
- disabled={
- selectedTopics.size === 0 || loadingPrompts || loadingTopics
- }
+ disabled={selectedTopics.size === 0 || loadingPrompts || loadingTopics}
onClick={handleGeneratePrompts}
>
{loadingPrompts ? (
@@ -1255,31 +1190,25 @@ export default function OnboardingPage() {
<div className="lg:col-span-2">
<div className="rounded-xl border bg-card p-5 sticky top-10">
- <h3 className="text-sm font-semibold mb-4">
- Topic Selection Tips
- </h3>
+ <h3 className="text-sm font-semibold mb-4">Topic Selection Tips</h3>
<div className="space-y-4">
<div className="flex gap-3">
<Check className="h-4 w-4 text-foreground shrink-0 mt-0.5" />
<div>
- <p className="text-sm font-medium">
- 5 prompts are created per topic
- </p>
+ <p className="text-sm font-medium">5 prompts are created per topic</p>
<p className="text-xs text-muted-foreground mt-0.5">
- You can select up to 10 topics for a total of 50
- prompts. More can be added anytime from the dashboard.
+ You can select up to 10 topics for a total of 50 prompts. More can be added
+ anytime from the dashboard.
</p>
</div>
</div>
<div className="flex gap-3">
<Check className="h-4 w-4 text-foreground shrink-0 mt-0.5" />
<div>
- <p className="text-sm font-medium">
- Think like your customers
- </p>
+ <p className="text-sm font-medium">Think like your customers</p>
<p className="text-xs text-muted-foreground mt-0.5">
- Use terms your audience would search for when looking
- for products or services like yours.
+ Use terms your audience would search for when looking for products or
+ services like yours.
</p>
</div>
</div>
@@ -1288,8 +1217,8 @@ export default function OnboardingPage() {
<div>
<p className="text-sm font-medium">Keep it short</p>
<p className="text-xs text-muted-foreground mt-0.5">
- Topics should be concise — we&apos;ll turn them into
- detailed prompts in the next step.
+ Topics should be concise — we&apos;ll turn them into detailed prompts in the
+ next step.
</p>
</div>
</div>
@@ -1324,12 +1253,10 @@ export default function OnboardingPage() {
<div className="flex items-start justify-between mb-6">
<div>
- <h1 className="text-2xl font-bold tracking-tight">
- Review your prompts
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Review your prompts</h1>
<p className="text-sm text-muted-foreground mt-1">
- These prompts will be sent to AI platforms daily. Feel free to
- edit, add, or remove any before starting.
+ These prompts will be sent to AI platforms daily. Feel free to edit, add, or remove
+ any before starting.
</p>
</div>
<Button
@@ -1349,9 +1276,7 @@ export default function OnboardingPage() {
<div className="mb-4">
<p className="text-sm font-medium">Your Prompt List</p>
- <p className="text-xs text-muted-foreground">
- {totalPrompts} prompts total
- </p>
+ <p className="text-xs text-muted-foreground">{totalPrompts} prompts total</p>
</div>
<div className="rounded-lg border">
@@ -1394,158 +1319,144 @@ export default function OnboardingPage() {
// ── Step 5: Competitors ──
if (step === 5) {
- const selectedCompetitorCount = suggestedCompetitors.filter(
- (c) => c.selected,
- ).length;
-
- return (
- <div className="flex min-h-svh flex-col p-6 md:p-10">
- <div className="mx-auto w-full max-w-lg flex-1">
- <BrandHeader name={brandName} domain={domain} />
+ const selectedCompetitorCount = suggestedCompetitors.filter((c) => c.selected).length;
- <div className="mb-6">
- <h1 className="text-2xl font-bold tracking-tight">
- Add your competitors
- </h1>
- <p className="text-sm text-muted-foreground mt-1">
- We&apos;ll track how often competitors appear alongside your brand
- in AI responses.
- </p>
- </div>
+ return (
+ <div className="flex min-h-svh flex-col p-6 md:p-10">
+ <div className="mx-auto w-full max-w-lg flex-1">
+ <BrandHeader name={brandName} domain={domain} />
- {loadingCompetitors ? (
- <div className="flex flex-col items-center gap-3 py-16 text-muted-foreground">
- <Sparkles className="h-5 w-5 animate-pulse" />
- <span
- key={competitorLoadingMsg}
- className="text-sm animate-in fade-in duration-500"
- >
- {competitorLoadingMsg}
- </span>
+ <div className="mb-6">
+ <h1 className="text-2xl font-bold tracking-tight">Add your competitors</h1>
+ <p className="text-sm text-muted-foreground mt-1">
+ We&apos;ll track how often competitors appear alongside your brand in AI responses.
+ </p>
</div>
- ) : (
- <div className="space-y-4">
- {suggestedCompetitors.length > 0 && (
- <div className="space-y-2">
- <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
- Suggested competitors
- </p>
- {suggestedCompetitors.map((c, idx) => (
- <div
- key={`${c.domain}-${idx}`}
- className={cn(
- 'flex items-center gap-3 rounded-lg border px-4 py-3 cursor-pointer transition-colors',
- c.selected
- ? 'border-primary/50 bg-primary/5'
- : 'border-border hover:bg-muted/50',
- )}
- onClick={() => toggleCompetitor(idx)}
- >
+
+ {loadingCompetitors ? (
+ <div className="flex flex-col items-center gap-3 py-16 text-muted-foreground">
+ <Sparkles className="h-5 w-5 animate-pulse" />
+ <span key={competitorLoadingMsg} className="text-sm animate-in fade-in duration-500">
+ {competitorLoadingMsg}
+ </span>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {suggestedCompetitors.length > 0 && (
+ <div className="space-y-2">
+ <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
+ Suggested competitors
+ </p>
+ {suggestedCompetitors.map((c, idx) => (
<div
+ key={`${c.domain}-${idx}`}
className={cn(
- 'flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors',
+ 'flex items-center gap-3 rounded-lg border px-4 py-3 cursor-pointer transition-colors',
c.selected
- ? 'bg-primary border-primary text-primary-foreground'
- : 'border-muted-foreground/30',
+ ? 'border-primary/50 bg-primary/5'
+ : 'border-border hover:bg-muted/50',
)}
+ onClick={() => toggleCompetitor(idx)}
>
- {c.selected && <Check className="h-3 w-3" />}
- </div>
- {c.domain && (
- /* eslint-disable-next-line @next/next/no-img-element */
- <img
- src={getFaviconUrl(c.domain)}
- alt=""
- className="h-5 w-5 rounded-sm"
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = 'none';
- }}
- />
- )}
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">{c.name}</p>
+ <div
+ className={cn(
+ 'flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors',
+ c.selected
+ ? 'bg-primary border-primary text-primary-foreground'
+ : 'border-muted-foreground/30',
+ )}
+ >
+ {c.selected && <Check className="h-3 w-3" />}
+ </div>
{c.domain && (
- <p className="text-xs text-muted-foreground truncate">
- {c.domain}
- </p>
+ /* eslint-disable-next-line @next/next/no-img-element */
+ <img
+ src={getFaviconUrl(c.domain)}
+ alt=""
+ className="h-5 w-5 rounded-sm"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = 'none';
+ }}
+ />
)}
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">{c.name}</p>
+ {c.domain && (
+ <p className="text-xs text-muted-foreground truncate">{c.domain}</p>
+ )}
+ </div>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ removeCompetitor(idx);
+ }}
+ className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-destructive"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
</div>
- <button
- onClick={(e) => {
- e.stopPropagation();
- removeCompetitor(idx);
- }}
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-destructive"
- >
- <X className="h-3.5 w-3.5" />
- </button>
- </div>
- ))}
- </div>
- )}
+ ))}
+ </div>
+ )}
- <div className="space-y-2">
- <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
- Add manually
- </p>
- <div className="flex items-center gap-2">
- <Input
- placeholder="Company name"
- value={competitorName}
- onChange={(e) => setCompetitorName(e.target.value)}
- className="text-sm"
- />
- <Input
- placeholder="domain.com"
- value={competitorDomain}
- onChange={(e) => setCompetitorDomain(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && addManualCompetitor()}
- className="text-sm"
- />
- <Button
- size="sm"
- variant="outline"
- onClick={addManualCompetitor}
- disabled={!competitorName.trim()}
- >
- <Plus className="h-4 w-4" />
- </Button>
+ <div className="space-y-2">
+ <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
+ Add manually
+ </p>
+ <div className="flex items-center gap-2">
+ <Input
+ placeholder="Company name"
+ value={competitorName}
+ onChange={(e) => setCompetitorName(e.target.value)}
+ className="text-sm"
+ />
+ <Input
+ placeholder="domain.com"
+ value={competitorDomain}
+ onChange={(e) => setCompetitorDomain(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && addManualCompetitor()}
+ className="text-sm"
+ />
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={addManualCompetitor}
+ disabled={!competitorName.trim()}
+ >
+ <Plus className="h-4 w-4" />
+ </Button>
+ </div>
</div>
- </div>
- <Button
- className="w-full"
- onClick={handleFinish}
- disabled={savingCompetitors}
- >
- {savingCompetitors ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Finishing setup...
- </>
- ) : selectedCompetitorCount > 0 ? (
- `Start tracking with ${selectedCompetitorCount} competitor${selectedCompetitorCount !== 1 ? 's' : ''}`
- ) : (
- 'Skip & start tracking'
- )}
- </Button>
- </div>
- )}
- </div>
+ <Button className="w-full" onClick={handleFinish} disabled={savingCompetitors}>
+ {savingCompetitors ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Finishing setup...
+ </>
+ ) : selectedCompetitorCount > 0 ? (
+ `Start tracking with ${selectedCompetitorCount} competitor${selectedCompetitorCount !== 1 ? 's' : ''}`
+ ) : (
+ 'Skip & start tracking'
+ )}
+ </Button>
+ </div>
+ )}
+ </div>
- <div className="flex mx-auto w-full max-w-lg items-center justify-between mt-8">
- <button
- onClick={() => setStep(4)}
- className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
- >
- <ArrowLeft className="h-3.5 w-3.5" />
- Back
- </button>
- <StepDots current={5} total={totalSteps} />
- <div className="w-12" />
+ <div className="flex mx-auto w-full max-w-lg items-center justify-between mt-8">
+ <button
+ onClick={() => setStep(4)}
+ className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back
+ </button>
+ <StepDots current={5} total={totalSteps} />
+ <div className="w-12" />
+ </div>
</div>
- </div>
- );
+ );
}
// ── Step 6: Choose Plan (cloud only) ──
@@ -1556,9 +1467,7 @@ export default function OnboardingPage() {
<div className="flex min-h-svh flex-col p-6 md:p-10">
<div className="mx-auto w-full max-w-2xl flex-1">
<div className="mb-8 text-center">
- <h1 className="text-2xl font-bold tracking-tight">
- Choose your plan
- </h1>
+ <h1 className="text-2xl font-bold tracking-tight">Choose your plan</h1>
<p className="text-sm text-muted-foreground mt-1">
Start with a 7-day free trial. Cancel anytime.
</p>
@@ -1578,30 +1487,21 @@ export default function OnboardingPage() {
key={planId}
className={cn(
'relative flex flex-col rounded-2xl border bg-card p-6 shadow-sm transition-shadow hover:shadow-md',
- plan.highlighted &&
- 'border-primary shadow-md ring-1 ring-primary/20',
+ plan.highlighted && 'border-primary shadow-md ring-1 ring-primary/20',
)}
>
{plan.highlighted && (
- <Badge className="absolute -top-3 left-1/2 -translate-x-1/2">
- Most Popular
- </Badge>
+ <Badge className="absolute -top-3 left-1/2 -translate-x-1/2">Most Popular</Badge>
)}
<div className="mb-4">
<h3 className="text-lg font-semibold">{plan.name}</h3>
- <p className="mt-1 text-sm text-muted-foreground">
- {plan.tagline}
- </p>
+ <p className="mt-1 text-sm text-muted-foreground">{plan.tagline}</p>
</div>
<div className="flex items-end gap-1 mb-4">
- <span className="text-4xl font-bold tracking-tight">
- ${price.monthly}
- </span>
- <span className="mb-1 text-sm text-muted-foreground">
- /month
- </span>
+ <span className="text-4xl font-bold tracking-tight">${price.monthly}</span>
+ <span className="mb-1 text-sm text-muted-foreground">/month</span>
</div>
<Button
@@ -1625,17 +1525,13 @@ export default function OnboardingPage() {
<div className="flex-1 space-y-2.5 text-sm">
<PlanFeatureItem>
<strong>
- {plan.limits.maxBrands === -1
- ? 'Unlimited'
- : plan.limits.maxBrands}
+ {plan.limits.maxBrands === -1 ? 'Unlimited' : plan.limits.maxBrands}
</strong>{' '}
{plan.limits.maxBrands === 1 ? 'brand' : 'brands'}
</PlanFeatureItem>
<PlanFeatureItem>
<strong>
- {plan.limits.maxPrompts === -1
- ? 'Unlimited'
- : plan.limits.maxPrompts}
+ {plan.limits.maxPrompts === -1 ? 'Unlimited' : plan.limits.maxPrompts}
</strong>{' '}
prompts tracked
</PlanFeatureItem>
@@ -1643,10 +1539,15 @@ export default function OnboardingPage() {
<strong>{plan.limits.maxPlatforms}</strong> answer engines
{plan.limits.allowedScrapers && plan.limits.allowedScrapers.length > 0 && (
<span className="text-muted-foreground font-normal">
- {' '}({plan.limits.allowedScrapers.map((id) => {
- const s = ALL_SCRAPERS.find((s) => s.id === id);
- return s ? s.label.replace(/\s*\(Web\)/i, '') : id;
- }).join(' & ')})
+ {' '}
+ (
+ {plan.limits.allowedScrapers
+ .map((id) => {
+ const s = ALL_SCRAPERS.find((s) => s.id === id);
+ return s ? s.label.replace(/\s*\(Web\)/i, '') : id;
+ })
+ .join(' & ')}
+ )
</span>
)}
</PlanFeatureItem>
@@ -1678,10 +1579,7 @@ export default function OnboardingPage() {
<p className="mt-6 text-center text-xs text-muted-foreground">
Need more?{' '}
- <a
- href="mailto:[email protected]"
- className="underline hover:text-foreground"
- >
+ <a href="mailto:[email protected]" className="underline hover:text-foreground">
Contact sales
</a>{' '}
for Enterprise pricing.
diff --git a/web/src/app/[locale]/(onboarding)/layout.tsx b/web/src/app/[locale]/(onboarding)/layout.tsx
index fe6f88543..60ca38d62 100644
--- a/web/src/app/[locale]/(onboarding)/layout.tsx
+++ b/web/src/app/[locale]/(onboarding)/layout.tsx
@@ -1,20 +1,16 @@
-import { redirect } from "next/navigation";
-import { createClient } from "@/lib/supabase/server";
-import { AuthProvider } from "@/components/providers/auth-provider";
-import { OnboardingSignOutButton } from "@/components/auth/onboarding-sign-out-button";
+import { redirect } from 'next/navigation';
+import { createClient } from '@/lib/supabase/server';
+import { AuthProvider } from '@/components/providers/auth-provider';
+import { OnboardingSignOutButton } from '@/components/auth/onboarding-sign-out-button';
-export default async function OnboardingLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default async function OnboardingLayout({ children }: { children: React.ReactNode }) {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
- redirect("/sign-in");
+ redirect('/sign-in');
}
return (
diff --git a/web/src/app/[locale]/invite/[token]/page.tsx b/web/src/app/[locale]/invite/[token]/page.tsx
index 651f0b3e6..4255d7317 100644
--- a/web/src/app/[locale]/invite/[token]/page.tsx
+++ b/web/src/app/[locale]/invite/[token]/page.tsx
@@ -1,8 +1,8 @@
-import { redirect } from "@/i18n/navigation";
-import { getInvitationByToken } from "@/lib/actions/team";
-import { createClient } from "@/lib/supabase/server";
-import { AcceptInvitationCard } from "@/components/team/accept-invitation-card";
-import { AlertTriangle } from "lucide-react";
+import { redirect } from '@/i18n/navigation';
+import { getInvitationByToken } from '@/lib/actions/team';
+import { createClient } from '@/lib/supabase/server';
+import { AcceptInvitationCard } from '@/components/team/accept-invitation-card';
+import { AlertTriangle } from 'lucide-react';
export default async function InviteAcceptPage({
params,
@@ -17,7 +17,7 @@ export default async function InviteAcceptPage({
return <InvalidInvitation reason="not_found" />;
}
- if (invitation.status !== "pending") {
+ if (invitation.status !== 'pending') {
return <InvalidInvitation reason={invitation.status} />;
}
@@ -38,18 +38,17 @@ export default async function InviteAcceptPage({
});
}
- const emailMatches =
- user!.email?.toLowerCase() === invitation.email.toLowerCase();
+ const emailMatches = user!.email?.toLowerCase() === invitation.email.toLowerCase();
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
<div className="flex w-full max-w-md flex-col gap-6">
<AcceptInvitationCard
token={token}
- organizationName={invitation.organizationName ?? "this team"}
+ organizationName={invitation.organizationName ?? 'this team'}
email={invitation.email}
role={invitation.role}
- currentUserEmail={user!.email ?? ""}
+ currentUserEmail={user!.email ?? ''}
emailMatches={emailMatches}
/>
</div>
@@ -60,28 +59,28 @@ export default async function InviteAcceptPage({
function InvalidInvitation({
reason,
}: {
- reason: "not_found" | "expired" | "accepted" | "revoked" | "pending";
+ reason: 'not_found' | 'expired' | 'accepted' | 'revoked' | 'pending';
}) {
const messages: Record<string, { title: string; description: string }> = {
not_found: {
- title: "Invitation not found",
- description: "The link you followed is invalid.",
+ title: 'Invitation not found',
+ description: 'The link you followed is invalid.',
},
expired: {
- title: "Invitation expired",
- description: "Ask your team admin to send a new invitation.",
+ title: 'Invitation expired',
+ description: 'Ask your team admin to send a new invitation.',
},
accepted: {
- title: "Invitation already used",
- description: "This invitation has already been accepted.",
+ title: 'Invitation already used',
+ description: 'This invitation has already been accepted.',
},
revoked: {
- title: "Invitation revoked",
- description: "This invitation was revoked by the team admin.",
+ title: 'Invitation revoked',
+ description: 'This invitation was revoked by the team admin.',
},
pending: {
- title: "Invitation unavailable",
- description: "Please try again or contact your team admin.",
+ title: 'Invitation unavailable',
+ description: 'Please try again or contact your team admin.',
},
};
const msg = messages[reason] ?? messages.pending;
diff --git a/web/src/app/[locale]/layout.tsx b/web/src/app/[locale]/layout.tsx
index afd9800c4..32d9f1330 100644
--- a/web/src/app/[locale]/layout.tsx
+++ b/web/src/app/[locale]/layout.tsx
@@ -1,9 +1,9 @@
-import { NextIntlClientProvider, hasLocale } from "next-intl";
-import { getMessages } from "next-intl/server";
-import { notFound } from "next/navigation";
-import { ThemeProvider } from "next-themes";
-import { routing } from "@/i18n/routing";
-import { Toaster } from "@/components/ui/sonner";
+import { NextIntlClientProvider, hasLocale } from 'next-intl';
+import { getMessages } from 'next-intl/server';
+import { notFound } from 'next/navigation';
+import { ThemeProvider } from 'next-themes';
+import { routing } from '@/i18n/routing';
+import { Toaster } from '@/components/ui/sonner';
export default async function LocaleLayout({
children,
@@ -21,12 +21,7 @@ export default async function LocaleLayout({
const messages = await getMessages();
return (
- <ThemeProvider
- attribute="class"
- defaultTheme="dark"
- enableSystem
- disableTransitionOnChange
- >
+ <ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange>
<NextIntlClientProvider messages={messages} locale={locale}>
{children}
<Toaster richColors position="top-right" />
diff --git a/web/src/app/api/cron/daily-tracking/route.ts b/web/src/app/api/cron/daily-tracking/route.ts
index 084bb540e..4dfb8d7a8 100644
--- a/web/src/app/api/cron/daily-tracking/route.ts
+++ b/web/src/app/api/cron/daily-tracking/route.ts
@@ -1,7 +1,6 @@
import { NextResponse } from 'next/server';
-const AEO_SERVER_URL =
- process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
+const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';
export async function GET(request: Request) {
const cronSecret = process.env.CRON_SECRET;
@@ -12,10 +11,7 @@ export async function GET(request: Request) {
const token = vercelHeader ?? authHeader?.replace('Bearer ', '');
if (!cronSecret || token !== cronSecret) {
- return NextResponse.json(
- { success: false, message: 'Unauthorized' },
- { status: 401 },
- );
+ return NextResponse.json({ success: false, message: 'Unauthorized' }, { status: 401 });
}
try {
@@ -31,9 +27,6 @@ export async function GET(request: Request) {
return NextResponse.json(data);
} catch (err) {
console.error('[cron] daily-tracking failed:', err);
- return NextResponse.json(
- { success: false, message: 'Internal error' },
- { status: 500 },
- );
+ return NextResponse.json({ success: false, message: 'Internal error' }, { status: 500 });
}
}
diff --git a/web/src/app/api/keys/[id]/route.ts b/web/src/app/api/keys/[id]/route.ts
index a5ea93301..cf0f53c0e 100644
--- a/web/src/app/api/keys/[id]/route.ts
+++ b/web/src/app/api/keys/[id]/route.ts
@@ -1,10 +1,7 @@
import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
-export async function DELETE(
- _req: Request,
- { params }: { params: Promise<{ id: string }> },
-) {
+export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const supabase = await createClient();
const {
diff --git a/web/src/app/api/keys/route.ts b/web/src/app/api/keys/route.ts
index e320567c5..ceab193cd 100644
--- a/web/src/app/api/keys/route.ts
+++ b/web/src/app/api/keys/route.ts
@@ -53,10 +53,7 @@ export async function POST(req: Request) {
.single();
if (error || !data) {
- return NextResponse.json(
- { error: error?.message ?? 'Could not create key' },
- { status: 500 },
- );
+ return NextResponse.json({ error: error?.message ?? 'Could not create key' }, { status: 500 });
}
return NextResponse.json({
diff --git a/web/src/app/api/mcp/content-opportunities/[id]/route.ts b/web/src/app/api/mcp/content-opportunities/[id]/route.ts
index db0fcb679..c4f5080bc 100644
--- a/web/src/app/api/mcp/content-opportunities/[id]/route.ts
+++ b/web/src/app/api/mcp/content-opportunities/[id]/route.ts
@@ -2,10 +2,7 @@ import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
import { getContentOpportunityFor } from '@/lib/mcp/data';
-export async function GET(
- req: Request,
- { params }: { params: Promise<{ id: string }> },
-) {
+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await authenticateMcpRequest(req);
if (auth instanceof NextResponse) return auth;
@@ -18,10 +15,7 @@ export async function GET(
try {
const opportunity = await getContentOpportunityFor(auth, opportunityId);
if (!opportunity) {
- return NextResponse.json(
- { error: 'Content opportunity not found' },
- { status: 404 },
- );
+ return NextResponse.json({ error: 'Content opportunity not found' }, { status: 404 });
}
return NextResponse.json({ opportunity });
} catch (err) {
diff --git a/web/src/app/api/mcp/content-opportunities/route.ts b/web/src/app/api/mcp/content-opportunities/route.ts
index 813f9bc71..61b31a452 100644
--- a/web/src/app/api/mcp/content-opportunities/route.ts
+++ b/web/src/app/api/mcp/content-opportunities/route.ts
@@ -27,14 +27,9 @@ export async function GET(req: Request) {
: undefined;
const impact =
- impactRaw === 'high' || impactRaw === 'medium' || impactRaw === 'low'
- ? impactRaw
- : undefined;
+ impactRaw === 'high' || impactRaw === 'medium' || impactRaw === 'low' ? impactRaw : undefined;
- const type =
- typeRaw === 'owned' || typeRaw === 'earned'
- ? typeRaw
- : undefined;
+ const type = typeRaw === 'owned' || typeRaw === 'earned' ? typeRaw : undefined;
const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;
diff --git a/web/src/app/api/mcp/prompts/route.ts b/web/src/app/api/mcp/prompts/route.ts
index 18f419f64..239ebeefc 100644
--- a/web/src/app/api/mcp/prompts/route.ts
+++ b/web/src/app/api/mcp/prompts/route.ts
@@ -16,12 +16,7 @@ export async function GET(req: Request) {
const isActiveRaw = url.searchParams.get('is_active');
const limitRaw = url.searchParams.get('limit');
- const isActive =
- isActiveRaw === 'true'
- ? true
- : isActiveRaw === 'false'
- ? false
- : undefined;
+ const isActive = isActiveRaw === 'true' ? true : isActiveRaw === 'false' ? false : undefined;
const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;
try {
diff --git a/web/src/app/api/stripe/checkout/route.ts b/web/src/app/api/stripe/checkout/route.ts
index 1d27e0675..b52d1729d 100644
--- a/web/src/app/api/stripe/checkout/route.ts
+++ b/web/src/app/api/stripe/checkout/route.ts
@@ -20,10 +20,7 @@ export async function POST(req: NextRequest) {
};
if (!planId || !organizationId) {
- return NextResponse.json(
- { error: 'Missing required fields' },
- { status: 400 },
- );
+ return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
}
const priceId = PRICE_IDS[planId]?.monthly;
@@ -34,10 +31,7 @@ export async function POST(req: NextRequest) {
'PRICE_IDS:',
PRICE_IDS,
);
- return NextResponse.json(
- { error: 'Price not configured for this plan' },
- { status: 400 },
- );
+ return NextResponse.json({ error: 'Price not configured for this plan' }, { status: 400 });
}
// Fetch org to check for existing Stripe customer
diff --git a/web/src/app/api/stripe/subscription/route.ts b/web/src/app/api/stripe/subscription/route.ts
index 4eb69df3c..f0a96cfd4 100644
--- a/web/src/app/api/stripe/subscription/route.ts
+++ b/web/src/app/api/stripe/subscription/route.ts
@@ -33,11 +33,7 @@ function getCurrentPeriodEndIso(sub: SubscriptionRaw): string | null {
const itemEnd = sub.items?.data?.[0]?.current_period_end;
const subEnd = sub.current_period_end;
const epochSeconds =
- typeof itemEnd === 'number'
- ? itemEnd
- : typeof subEnd === 'number'
- ? subEnd
- : null;
+ typeof itemEnd === 'number' ? itemEnd : typeof subEnd === 'number' ? subEnd : null;
if (epochSeconds == null) return null;
return new Date(epochSeconds * 1000).toISOString();
}
@@ -60,7 +56,9 @@ async function getOrgStripeIds() {
const { data: org } = await supabase
.from('organizations')
- .select('id, plan, subscription_status, stripe_customer_id, stripe_subscription_id, subscription_ends_at')
+ .select(
+ 'id, plan, subscription_status, stripe_customer_id, stripe_subscription_id, subscription_ends_at',
+ )
.eq('id', profile.organization_id)
.single();
@@ -86,9 +84,9 @@ export async function GET() {
});
}
- const sub = await stripe.subscriptions.retrieve(
+ const sub = (await stripe.subscriptions.retrieve(
org.stripe_subscription_id as string,
- ) as unknown as SubscriptionRaw;
+ )) as unknown as SubscriptionRaw;
const item = sub.items.data[0];
const price = item?.price;
@@ -132,9 +130,9 @@ export async function PATCH(req: NextRequest) {
// Reactivate a canceled-at-period-end subscription
if (reactivate) {
- const updated = await stripe.subscriptions.update(subscriptionId, {
+ const updated = (await stripe.subscriptions.update(subscriptionId, {
cancel_at_period_end: false,
- }) as unknown as SubscriptionRaw;
+ })) as unknown as SubscriptionRaw;
return NextResponse.json({
status: updated.status,
cancelAtPeriodEnd: false,
@@ -156,25 +154,24 @@ export async function PATCH(req: NextRequest) {
return NextResponse.json({ error: 'Price not configured' }, { status: 400 });
}
- const currentSub = await stripe.subscriptions.retrieve(subscriptionId) as unknown as SubscriptionRaw;
+ const currentSub = (await stripe.subscriptions.retrieve(
+ subscriptionId,
+ )) as unknown as SubscriptionRaw;
const itemId = currentSub.items.data[0]?.id;
if (!itemId) {
return NextResponse.json({ error: 'Subscription item not found' }, { status: 400 });
}
- const updated = await stripe.subscriptions.update(subscriptionId, {
+ const updated = (await stripe.subscriptions.update(subscriptionId, {
items: [{ id: itemId, price: priceId }],
metadata: { plan_id: newPlanId, organization_id: org.id },
proration_behavior: 'create_prorations',
- }) as unknown as SubscriptionRaw;
+ })) as unknown as SubscriptionRaw;
// Optimistic DB update
const supabase = await createClient();
- await supabase
- .from('organizations')
- .update({ plan: newPlanId })
- .eq('id', org.id);
+ await supabase.from('organizations').update({ plan: newPlanId }).eq('id', org.id);
const newPrice = updated.items.data[0]?.price;
@@ -207,10 +204,9 @@ export async function DELETE() {
return NextResponse.json({ error: 'No active subscription' }, { status: 400 });
}
- const updated = await stripe.subscriptions.update(
- org.stripe_subscription_id as string,
- { cancel_at_period_end: true },
- ) as unknown as SubscriptionRaw;
+ const updated = (await stripe.subscriptions.update(org.stripe_subscription_id as string, {
+ cancel_at_period_end: true,
+ })) as unknown as SubscriptionRaw;
return NextResponse.json({
cancelAtPeriodEnd: true,
diff --git a/web/src/app/api/stripe/success/route.ts b/web/src/app/api/stripe/success/route.ts
index 89d5a033b..51e57c4d7 100644
--- a/web/src/app/api/stripe/success/route.ts
+++ b/web/src/app/api/stripe/success/route.ts
@@ -21,9 +21,7 @@ export async function GET(req: NextRequest) {
if (session.payment_status === 'paid' || session.status === 'complete') {
const customerId =
- typeof session.customer === 'string'
- ? session.customer
- : session.customer?.id;
+ typeof session.customer === 'string' ? session.customer : session.customer?.id;
const subscription =
typeof session.subscription === 'string'
@@ -31,10 +29,9 @@ export async function GET(req: NextRequest) {
: session.subscription;
const subscriptionId = subscription?.id;
- const orgId =
- (subscription as { metadata?: { organization_id?: string } })?.metadata?.organization_id;
- const planId =
- (subscription as { metadata?: { plan_id?: string } })?.metadata?.plan_id;
+ const orgId = (subscription as { metadata?: { organization_id?: string } })?.metadata
+ ?.organization_id;
+ const planId = (subscription as { metadata?: { plan_id?: string } })?.metadata?.plan_id;
if (orgId && customerId && subscriptionId) {
// Update org subscription (resolves webhook race condition)
@@ -80,7 +77,12 @@ export async function GET(req: NextRequest) {
if (trackingRes.ok) {
const result = await trackingRes.json();
trackingJobId = result.jobId;
- console.log('[stripe/success] Tracking triggered for brand:', brand.id, 'jobId:', trackingJobId);
+ console.log(
+ '[stripe/success] Tracking triggered for brand:',
+ brand.id,
+ 'jobId:',
+ trackingJobId,
+ );
} else {
console.error('[stripe/success] Tracking trigger failed:', trackingRes.status);
}
diff --git a/web/src/app/api/stripe/webhook/route.ts b/web/src/app/api/stripe/webhook/route.ts
index 5cda6d0de..1399a65ee 100644
--- a/web/src/app/api/stripe/webhook/route.ts
+++ b/web/src/app/api/stripe/webhook/route.ts
@@ -13,11 +13,7 @@ export async function POST(req: NextRequest) {
let event: Stripe.Event;
try {
- event = stripe.webhooks.constructEvent(
- body,
- signature,
- process.env.STRIPE_WEBHOOK_SECRET!,
- );
+ event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
} catch (err) {
console.error('[stripe/webhook] Signature verification failed:', err);
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
@@ -28,9 +24,7 @@ export async function POST(req: NextRequest) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session;
const customerId =
- typeof session.customer === 'string'
- ? session.customer
- : session.customer?.id;
+ typeof session.customer === 'string' ? session.customer : session.customer?.id;
const subscriptionId =
typeof session.subscription === 'string'
? session.subscription
@@ -38,11 +32,19 @@ export async function POST(req: NextRequest) {
if (customerId && subscriptionId) {
// Fetch the subscription to get metadata
- const subscription =
- await stripe.subscriptions.retrieve(subscriptionId);
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
const orgId = subscription.metadata.organization_id;
const planId = subscription.metadata.plan_id;
- console.log('[webhook] checkout.session.completed — orgId:', orgId, 'planId:', planId, 'customerId:', customerId, 'subscriptionId:', subscriptionId);
+ console.log(
+ '[webhook] checkout.session.completed — orgId:',
+ orgId,
+ 'planId:',
+ planId,
+ 'customerId:',
+ customerId,
+ 'subscriptionId:',
+ subscriptionId,
+ );
if (orgId) {
const { error } = await supabaseAdmin
@@ -58,7 +60,10 @@ export async function POST(req: NextRequest) {
else console.log('[webhook] DB updated successfully for org:', orgId);
}
} else {
- console.log('[webhook] checkout.session.completed — missing customerId or subscriptionId:', { customerId, subscriptionId });
+ console.log(
+ '[webhook] checkout.session.completed — missing customerId or subscriptionId:',
+ { customerId, subscriptionId },
+ );
}
break;
}
@@ -74,23 +79,18 @@ export async function POST(req: NextRequest) {
// Stripe API 2025-03-31 moved current_period_end to the item level.
// Read item-level first, fall back to subscription-level for older
// API versions, and skip the field entirely if neither is present.
- const subItems = (
- subscription as unknown as {
- items?: { data?: Array<{ current_period_end?: number }> };
- current_period_end?: number;
- }
- );
+ const subItems = subscription as unknown as {
+ items?: { data?: Array<{ current_period_end?: number }> };
+ current_period_end?: number;
+ };
const epochSeconds =
- subItems.items?.data?.[0]?.current_period_end ??
- subItems.current_period_end;
+ subItems.items?.data?.[0]?.current_period_end ?? subItems.current_period_end;
const updates: Record<string, unknown> = {
subscription_status: subscription.status,
};
if (typeof epochSeconds === 'number') {
- updates.subscription_ends_at = new Date(
- epochSeconds * 1000,
- ).toISOString();
+ updates.subscription_ends_at = new Date(epochSeconds * 1000).toISOString();
}
// Update plan if metadata has plan_id
@@ -128,9 +128,7 @@ export async function POST(req: NextRequest) {
case 'invoice.payment_succeeded': {
const invoice = event.data.object as Stripe.Invoice;
const customerId =
- typeof invoice.customer === 'string'
- ? invoice.customer
- : invoice.customer?.id;
+ typeof invoice.customer === 'string' ? invoice.customer : invoice.customer?.id;
if (customerId) {
await supabaseAdmin
@@ -144,9 +142,7 @@ export async function POST(req: NextRequest) {
case 'invoice.payment_failed': {
const invoice = event.data.object as Stripe.Invoice;
const customerId =
- typeof invoice.customer === 'string'
- ? invoice.customer
- : invoice.customer?.id;
+ typeof invoice.customer === 'string' ? invoice.customer : invoice.customer?.id;
if (customerId) {
await supabaseAdmin
diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx
index 0d4afdea0..58201879c 100644
--- a/web/src/app/layout.tsx
+++ b/web/src/app/layout.tsx
@@ -1,52 +1,50 @@
-import type { Metadata } from "next";
-import { Geist, Geist_Mono, Inter, Plus_Jakarta_Sans } from "next/font/google";
-import { Analytics } from "@vercel/analytics/next";
-import { PostHogProvider } from "@/components/providers/posthog-provider";
-import "./globals.css";
+import type { Metadata } from 'next';
+import { Geist, Geist_Mono, Inter, Plus_Jakarta_Sans } from 'next/font/google';
+import { Analytics } from '@vercel/analytics/next';
+import { PostHogProvider } from '@/components/providers/posthog-provider';
+import './globals.css';
const geistSans = Geist({
- variable: "--font-geist-sans",
- subsets: ["latin"],
+ variable: '--font-geist-sans',
+ subsets: ['latin'],
});
const geistMono = Geist_Mono({
- variable: "--font-geist-mono",
- subsets: ["latin"],
+ variable: '--font-geist-mono',
+ subsets: ['latin'],
});
const inter = Inter({
- variable: "--font-inter",
- subsets: ["latin"],
+ variable: '--font-inter',
+ subsets: ['latin'],
});
const jakarta = Plus_Jakarta_Sans({
- variable: "--font-jakarta",
- subsets: ["latin"],
+ variable: '--font-jakarta',
+ subsets: ['latin'],
});
export const metadata: Metadata = {
- metadataBase: new URL(
- process.env.NEXT_PUBLIC_APP_URL || "https://app.ansvisor.com",
- ),
+ metadataBase: new URL(process.env.NEXT_PUBLIC_APP_URL || 'https://app.ansvisor.com'),
title: {
- default: "Ansvisor",
- template: "%s | Ansvisor",
+ default: 'Ansvisor',
+ template: '%s | Ansvisor',
},
description:
"Monitor, analyze, and optimize your brand's visibility in AI-powered search engines.",
openGraph: {
- title: "Ansvisor",
+ title: 'Ansvisor',
description:
- "Track how AI search engines mention your brand — ChatGPT, Gemini, Perplexity, Claude, Copilot.",
- url: "/",
- siteName: "Ansvisor",
- type: "website",
+ 'Track how AI search engines mention your brand — ChatGPT, Gemini, Perplexity, Claude, Copilot.',
+ url: '/',
+ siteName: 'Ansvisor',
+ type: 'website',
},
twitter: {
- card: "summary_large_image",
- title: "Ansvisor",
+ card: 'summary_large_image',
+ title: 'Ansvisor',
description:
- "Track how AI search engines mention your brand — ChatGPT, Gemini, Perplexity, Claude, Copilot.",
+ 'Track how AI search engines mention your brand — ChatGPT, Gemini, Perplexity, Claude, Copilot.',
},
// The product app at app.ansvisor.com should not appear in search results;
// ansvisor.com (the Webflow marketing site) is the indexable surface.
@@ -60,17 +58,13 @@ export const metadata: Metadata = {
},
};
-export default function RootLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
- <html suppressHydrationWarning className={`${geistSans.variable} ${geistMono.variable} ${inter.variable} ${jakarta.variable}`}>
- <body
- suppressHydrationWarning
- className="font-sans antialiased"
- >
+ <html
+ suppressHydrationWarning
+ className={`${geistSans.variable} ${geistMono.variable} ${inter.variable} ${jakarta.variable}`}
+ >
+ <body suppressHydrationWarning className="font-sans antialiased">
<PostHogProvider />
{children}
<Analytics />
diff --git a/web/src/app/opengraph-image.tsx b/web/src/app/opengraph-image.tsx
index 2b6311378..3f135df3f 100644
--- a/web/src/app/opengraph-image.tsx
+++ b/web/src/app/opengraph-image.tsx
@@ -17,44 +17,36 @@ export default async function OpengraphImage() {
const logoSrc = await loadLogoDataUrl();
return new ImageResponse(
- (
+ <div
+ style={{
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background:
+ 'radial-gradient(ellipse at top right, #312e81 0%, #1e1b4b 35%, #0b0a2b 70%, #050516 100%)',
+ position: 'relative',
+ }}
+ >
+ {/* Soft glow accent */}
<div
style={{
- width: '100%',
- height: '100%',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
+ position: 'absolute',
+ top: -200,
+ right: -200,
+ width: 700,
+ height: 700,
+ borderRadius: '50%',
background:
- 'radial-gradient(ellipse at top right, #312e81 0%, #1e1b4b 35%, #0b0a2b 70%, #050516 100%)',
- position: 'relative',
+ 'radial-gradient(circle, rgba(139, 92, 246, 0.4) 0%, rgba(139, 92, 246, 0) 70%)',
+ display: 'flex',
}}
- >
- {/* Soft glow accent */}
- <div
- style={{
- position: 'absolute',
- top: -200,
- right: -200,
- width: 700,
- height: 700,
- borderRadius: '50%',
- background:
- 'radial-gradient(circle, rgba(139, 92, 246, 0.4) 0%, rgba(139, 92, 246, 0) 70%)',
- display: 'flex',
- }}
- />
+ />
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={logoSrc}
- alt=""
- width={360}
- height={360}
- style={{ width: 360, height: 360 }}
- />
- </div>
- ),
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={logoSrc} alt="" width={360} height={360} style={{ width: 360, height: 360 }} />
+ </div>,
{ ...size },
);
}
diff --git a/web/src/components/ai-provider-avatar.tsx b/web/src/components/ai-provider-avatar.tsx
index 6bcb527d5..e418e93a7 100644
--- a/web/src/components/ai-provider-avatar.tsx
+++ b/web/src/components/ai-provider-avatar.tsx
@@ -74,12 +74,7 @@ const AI_PROVIDER_META: Record<
export function resolveAIProvider(model: string, platform?: string): AIProviderKey {
const key = platform || model;
- if (
- key === 'ChatGPT' ||
- key === 'chatgpt' ||
- key === 'chatgpt-web' ||
- key.startsWith('gpt-')
- ) {
+ if (key === 'ChatGPT' || key === 'chatgpt' || key === 'chatgpt-web' || key.startsWith('gpt-')) {
return 'openai';
}
if (key === 'Claude' || key === 'claude' || key.startsWith('claude-')) {
@@ -104,11 +99,7 @@ export function resolveAIProvider(model: string, platform?: string): AIProviderK
if (key === 'Grok' || key === 'grok' || key === 'grok-web' || key.startsWith('grok-')) {
return 'xai';
}
- if (
- key === 'Google AI Overview' ||
- key === 'google-aio' ||
- key === 'google-ai-overviews'
- ) {
+ if (key === 'Google AI Overview' || key === 'google-aio' || key === 'google-ai-overviews') {
return 'googleAio';
}
if (
@@ -173,12 +164,7 @@ export function AIProviderAvatar({
className,
)}
>
- <img
- src={meta.icon}
- alt=""
- className="h-full w-full object-cover"
- aria-hidden="true"
- />
+ <img src={meta.icon} alt="" className="h-full w-full object-cover" aria-hidden="true" />
</span>
);
}
diff --git a/web/src/components/auth/oauth-buttons.tsx b/web/src/components/auth/oauth-buttons.tsx
index 935f8c0b6..139dec24d 100644
--- a/web/src/components/auth/oauth-buttons.tsx
+++ b/web/src/components/auth/oauth-buttons.tsx
@@ -1,9 +1,9 @@
-"use client";
+'use client';
-import { useState } from "react";
-import { createClient } from "@/lib/supabase/client";
-import { Button } from "@/components/ui/button";
-import { Loader2 } from "lucide-react";
+import { useState } from 'react';
+import { createClient } from '@/lib/supabase/client';
+import { Button } from '@/components/ui/button';
+import { Loader2 } from 'lucide-react';
function GitHubIcon({ className }: { className?: string }) {
return (
@@ -16,15 +16,27 @@ function GitHubIcon({ className }: { className?: string }) {
function GoogleIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 24 24" className={className}>
- <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4" />
- <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
- <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
- <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
+ <path
+ d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z"
+ fill="#4285F4"
+ />
+ <path
+ d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
+ fill="#34A853"
+ />
+ <path
+ d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
+ fill="#FBBC05"
+ />
+ <path
+ d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
+ fill="#EA4335"
+ />
</svg>
);
}
-type Provider = "github" | "google";
+type Provider = 'github' | 'google';
export function OAuthButtons() {
const [loadingProvider, setLoadingProvider] = useState<Provider | null>(null);
@@ -51,9 +63,9 @@ export function OAuthButtons() {
variant="outline"
type="button"
disabled={loadingProvider !== null}
- onClick={() => handleOAuth("github")}
+ onClick={() => handleOAuth('github')}
>
- {loadingProvider === "github" ? (
+ {loadingProvider === 'github' ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<GitHubIcon className="mr-2 h-4 w-4" />
@@ -64,9 +76,9 @@ export function OAuthButtons() {
variant="outline"
type="button"
disabled={loadingProvider !== null}
- onClick={() => handleOAuth("google")}
+ onClick={() => handleOAuth('google')}
>
- {loadingProvider === "google" ? (
+ {loadingProvider === 'google' ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<GoogleIcon className="mr-2 h-4 w-4" />
diff --git a/web/src/components/auth/sign-in-form.tsx b/web/src/components/auth/sign-in-form.tsx
index 260fb7374..e63f8f6c1 100644
--- a/web/src/components/auth/sign-in-form.tsx
+++ b/web/src/components/auth/sign-in-form.tsx
@@ -1,26 +1,26 @@
-"use client";
+'use client';
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { useSearchParams } from "next/navigation";
-import { useRouter } from "@/i18n/navigation";
-import { createClient } from "@/lib/supabase/client";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { toast } from "sonner";
-import { Loader2 } from "lucide-react";
-import { OAuthButtons } from "@/components/auth/oauth-buttons";
-import { Separator } from "@/components/ui/separator";
-import { track } from "@/lib/analytics";
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { useSearchParams } from 'next/navigation';
+import { useRouter } from '@/i18n/navigation';
+import { createClient } from '@/lib/supabase/client';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { toast } from 'sonner';
+import { Loader2 } from 'lucide-react';
+import { OAuthButtons } from '@/components/auth/oauth-buttons';
+import { Separator } from '@/components/ui/separator';
+import { track } from '@/lib/analytics';
export function SignInForm() {
- const t = useTranslations("auth");
+ const t = useTranslations('auth');
const router = useRouter();
const searchParams = useSearchParams();
- const nextPath = searchParams.get("next");
- const [email, setEmail] = useState("");
- const [password, setPassword] = useState("");
+ const nextPath = searchParams.get('next');
+ const [email, setEmail] = useState('');
+ const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
@@ -36,12 +36,12 @@ export function SignInForm() {
if (error) {
const msg = error.message.toLowerCase();
- if (msg.includes("email not confirmed")) {
- toast.error(t("errors.emailNotConfirmed"));
- } else if (msg.includes("invalid login credentials")) {
- toast.error(t("errors.invalidCredentials"));
+ if (msg.includes('email not confirmed')) {
+ toast.error(t('errors.emailNotConfirmed'));
+ } else if (msg.includes('invalid login credentials')) {
+ toast.error(t('errors.invalidCredentials'));
} else {
- toast.error(t("errors.generic"));
+ toast.error(t('errors.generic'));
}
setIsLoading(false);
return;
@@ -49,9 +49,9 @@ export function SignInForm() {
// identify() runs centrally in AuthProvider on the SIGNED_IN auth event,
// so the form just needs to capture the funnel event.
- track("signin_completed", { source: "email" });
+ track('signin_completed', { source: 'email' });
- router.push(nextPath && nextPath.startsWith("/") ? nextPath : "/dashboard");
+ router.push(nextPath && nextPath.startsWith('/') ? nextPath : '/dashboard');
router.refresh();
}
@@ -64,60 +64,58 @@ export function SignInForm() {
<Separator className="w-full" />
</div>
<div className="relative flex justify-center text-xs uppercase">
- <span className="bg-card px-2 text-muted-foreground">
- {t("orContinueWith")}
- </span>
+ <span className="bg-card px-2 text-muted-foreground">{t('orContinueWith')}</span>
</div>
</div>
- <form onSubmit={handleSubmit} className="space-y-4">
- <div className="space-y-2">
- <Label htmlFor="email">{t("email")}</Label>
- <Input
- id="email"
- type="email"
- placeholder={t("emailPlaceholder")}
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- required
- autoComplete="email"
- disabled={isLoading}
- />
- </div>
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="email">{t('email')}</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder={t('emailPlaceholder')}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ required
+ autoComplete="email"
+ disabled={isLoading}
+ />
+ </div>
- <div className="space-y-2">
- <div className="flex items-center justify-between">
- <Label htmlFor="password">{t("password")}</Label>
- <a
- href="#"
- className="text-sm text-muted-foreground hover:text-primary underline-offset-4 hover:underline"
- >
- {t("forgotPassword")}
- </a>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="password">{t('password')}</Label>
+ <a
+ href="#"
+ className="text-sm text-muted-foreground hover:text-primary underline-offset-4 hover:underline"
+ >
+ {t('forgotPassword')}
+ </a>
+ </div>
+ <Input
+ id="password"
+ type="password"
+ placeholder={t('passwordPlaceholder')}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ required
+ autoComplete="current-password"
+ disabled={isLoading}
+ />
</div>
- <Input
- id="password"
- type="password"
- placeholder={t("passwordPlaceholder")}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- required
- autoComplete="current-password"
- disabled={isLoading}
- />
- </div>
- <Button type="submit" className="w-full" disabled={isLoading}>
- {isLoading ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- {t("signingIn")}
- </>
- ) : (
- t("signIn")
- )}
- </Button>
- </form>
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ {t('signingIn')}
+ </>
+ ) : (
+ t('signIn')
+ )}
+ </Button>
+ </form>
</div>
);
}
diff --git a/web/src/components/auth/sign-up-form.tsx b/web/src/components/auth/sign-up-form.tsx
index ece6a74a3..5a022c1fb 100644
--- a/web/src/components/auth/sign-up-form.tsx
+++ b/web/src/components/auth/sign-up-form.tsx
@@ -1,36 +1,36 @@
-"use client";
-
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { useSearchParams } from "next/navigation";
-import { useRouter, Link } from "@/i18n/navigation";
-import { createClient } from "@/lib/supabase/client";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { toast } from "sonner";
-import { Loader2 } from "lucide-react";
-import { OAuthButtons } from "@/components/auth/oauth-buttons";
-import { Separator } from "@/components/ui/separator";
-import { siteConfig } from "@/config/site";
-import { track } from "@/lib/analytics";
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { useSearchParams } from 'next/navigation';
+import { useRouter, Link } from '@/i18n/navigation';
+import { createClient } from '@/lib/supabase/client';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { toast } from 'sonner';
+import { Loader2 } from 'lucide-react';
+import { OAuthButtons } from '@/components/auth/oauth-buttons';
+import { Separator } from '@/components/ui/separator';
+import { siteConfig } from '@/config/site';
+import { track } from '@/lib/analytics';
export function SignUpForm() {
- const t = useTranslations("auth");
+ const t = useTranslations('auth');
const router = useRouter();
const searchParams = useSearchParams();
- const invitedEmail = searchParams.get("email") ?? "";
- const nextPath = searchParams.get("next");
- const [fullName, setFullName] = useState("");
+ const invitedEmail = searchParams.get('email') ?? '';
+ const nextPath = searchParams.get('next');
+ const [fullName, setFullName] = useState('');
const [email, setEmail] = useState(invitedEmail);
- const [password, setPassword] = useState("");
+ const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
if (password.length < 8) {
- toast.error(t("errors.passwordTooShort"));
+ toast.error(t('errors.passwordTooShort'));
return;
}
@@ -48,15 +48,15 @@ export function SignUpForm() {
});
if (error) {
- toast.error(t("errors.generic"));
+ toast.error(t('errors.generic'));
setIsLoading(false);
return;
}
- track("signup_completed", { source: "email" });
+ track('signup_completed', { source: 'email' });
- toast.success(t("verificationEmailSent"));
- const nextQuery = nextPath ? `&next=${encodeURIComponent(nextPath)}` : "";
+ toast.success(t('verificationEmailSent'));
+ const nextQuery = nextPath ? `&next=${encodeURIComponent(nextPath)}` : '';
router.push(`/sign-in?verified=pending${nextQuery}`);
}
@@ -69,88 +69,86 @@ export function SignUpForm() {
<Separator className="w-full" />
</div>
<div className="relative flex justify-center text-xs uppercase">
- <span className="bg-card px-2 text-muted-foreground">
- {t("orContinueWith")}
- </span>
+ <span className="bg-card px-2 text-muted-foreground">{t('orContinueWith')}</span>
</div>
</div>
- <form onSubmit={handleSubmit} className="space-y-4">
- <div className="space-y-2">
- <Label htmlFor="fullName">{t("fullName")}</Label>
- <Input
- id="fullName"
- type="text"
- placeholder={t("fullNamePlaceholder")}
- value={fullName}
- onChange={(e) => setFullName(e.target.value)}
- required
- autoComplete="name"
- disabled={isLoading}
- />
- </div>
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="fullName">{t('fullName')}</Label>
+ <Input
+ id="fullName"
+ type="text"
+ placeholder={t('fullNamePlaceholder')}
+ value={fullName}
+ onChange={(e) => setFullName(e.target.value)}
+ required
+ autoComplete="name"
+ disabled={isLoading}
+ />
+ </div>
- <div className="space-y-2">
- <Label htmlFor="email">{t("email")}</Label>
- <Input
- id="email"
- type="email"
- placeholder={t("emailPlaceholder")}
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- required
- autoComplete="email"
- disabled={isLoading || Boolean(invitedEmail)}
- />
- </div>
+ <div className="space-y-2">
+ <Label htmlFor="email">{t('email')}</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder={t('emailPlaceholder')}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ required
+ autoComplete="email"
+ disabled={isLoading || Boolean(invitedEmail)}
+ />
+ </div>
- <div className="space-y-2">
- <Label htmlFor="password">{t("password")}</Label>
- <Input
- id="password"
- type="password"
- placeholder={t("passwordPlaceholder")}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- required
- autoComplete="new-password"
- disabled={isLoading}
- />
- </div>
+ <div className="space-y-2">
+ <Label htmlFor="password">{t('password')}</Label>
+ <Input
+ id="password"
+ type="password"
+ placeholder={t('passwordPlaceholder')}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ required
+ autoComplete="new-password"
+ disabled={isLoading}
+ />
+ </div>
- <Button type="submit" className="w-full" disabled={isLoading}>
- {isLoading ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- {t("signingUp")}
- </>
- ) : (
- t("createAccount")
- )}
- </Button>
-
- <p className="text-center text-xs text-muted-foreground">
- {t("termsAgreement")}{" "}
- <a
- href={siteConfig.legal.terms}
- target="_blank"
- rel="noopener noreferrer"
- className="underline underline-offset-4 hover:text-primary"
- >
- {t("termsOfService")}
- </a>{" "}
- {t("and")}{" "}
- <a
- href={siteConfig.legal.privacy}
- target="_blank"
- rel="noopener noreferrer"
- className="underline underline-offset-4 hover:text-primary"
- >
- {t("privacyPolicy")}
- </a>
- .
- </p>
- </form>
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ {t('signingUp')}
+ </>
+ ) : (
+ t('createAccount')
+ )}
+ </Button>
+
+ <p className="text-center text-xs text-muted-foreground">
+ {t('termsAgreement')}{' '}
+ <a
+ href={siteConfig.legal.terms}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-4 hover:text-primary"
+ >
+ {t('termsOfService')}
+ </a>{' '}
+ {t('and')}{' '}
+ <a
+ href={siteConfig.legal.privacy}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-4 hover:text-primary"
+ >
+ {t('privacyPolicy')}
+ </a>
+ .
+ </p>
+ </form>
</div>
);
}
diff --git a/web/src/components/dashboard/brand-card.tsx b/web/src/components/dashboard/brand-card.tsx
index f32fd6c15..64bf9b1a0 100644
--- a/web/src/components/dashboard/brand-card.tsx
+++ b/web/src/components/dashboard/brand-card.tsx
@@ -1,20 +1,20 @@
-"use client";
+'use client';
-import { useTranslations } from "next-intl";
-import { Link, useRouter } from "@/i18n/navigation";
-import { useBrandStore } from "@/stores/use-brand-store";
-import type { Brand } from "@/types";
-import type { BrandCardSummary } from "@/lib/actions/brand";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
+import { useTranslations } from 'next-intl';
+import { Link, useRouter } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import type { Brand } from '@/types';
+import type { BrandCardSummary } from '@/lib/actions/brand';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+} from '@/components/ui/dropdown-menu';
import {
ArrowUpRight,
BarChart3,
@@ -27,8 +27,8 @@ import {
Tag,
TrendingDown,
TrendingUp,
-} from "lucide-react";
-import { cn } from "@/lib/utils";
+} from 'lucide-react';
+import { cn } from '@/lib/utils';
interface BrandCardProps {
brand: Brand;
@@ -36,14 +36,14 @@ interface BrandCardProps {
}
const GRADIENTS = [
- "from-indigo-500/30 via-purple-500/20 to-fuchsia-500/10",
- "from-sky-500/30 via-cyan-500/20 to-emerald-500/10",
- "from-rose-500/30 via-pink-500/20 to-amber-500/10",
- "from-violet-500/30 via-indigo-500/20 to-blue-500/10",
- "from-emerald-500/30 via-teal-500/20 to-cyan-500/10",
- "from-amber-500/30 via-orange-500/20 to-rose-500/10",
- "from-fuchsia-500/30 via-purple-500/20 to-indigo-500/10",
- "from-blue-500/30 via-sky-500/20 to-teal-500/10",
+ 'from-indigo-500/30 via-purple-500/20 to-fuchsia-500/10',
+ 'from-sky-500/30 via-cyan-500/20 to-emerald-500/10',
+ 'from-rose-500/30 via-pink-500/20 to-amber-500/10',
+ 'from-violet-500/30 via-indigo-500/20 to-blue-500/10',
+ 'from-emerald-500/30 via-teal-500/20 to-cyan-500/10',
+ 'from-amber-500/30 via-orange-500/20 to-rose-500/10',
+ 'from-fuchsia-500/30 via-purple-500/20 to-indigo-500/10',
+ 'from-blue-500/30 via-sky-500/20 to-teal-500/10',
];
function pickGradient(seed: string): string {
@@ -79,8 +79,8 @@ function Sparkline({ data, positive }: { data: number[]; positive: boolean }) {
const y = 26 - ((v - min) / range) * 22;
return `${x.toFixed(2)},${y.toFixed(2)}`;
})
- .join(" ");
- const stroke = positive ? "#10b981" : "#ef4444";
+ .join(' ');
+ const stroke = positive ? '#10b981' : '#ef4444';
return (
<svg viewBox="0 0 100 28" className="h-7 w-full" preserveAspectRatio="none">
<polyline
@@ -95,36 +95,32 @@ function Sparkline({ data, positive }: { data: number[]; positive: boolean }) {
);
}
-function StatusPill({ status }: { status: BrandCardSummary["status"] }) {
+function StatusPill({ status }: { status: BrandCardSummary['status'] }) {
const config = {
healthy: {
- label: "Tracking",
- color:
- "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
+ label: 'Tracking',
+ color: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
icon: CheckCircle2,
},
declining: {
- label: "Needs attention",
- color:
- "border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",
+ label: 'Needs attention',
+ color: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
icon: TrendingDown,
},
- "no-prompts": {
- label: "No prompts yet",
- color:
- "border-zinc-500/30 bg-zinc-500/10 text-zinc-600 dark:text-zinc-400",
+ 'no-prompts': {
+ label: 'No prompts yet',
+ color: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-600 dark:text-zinc-400',
icon: MessageSquareText,
},
- "no-data": {
- label: "Awaiting data",
- color:
- "border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400",
+ 'no-data': {
+ label: 'Awaiting data',
+ color: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
icon: Sparkles,
},
} as const;
const c = config[status];
return (
- <Badge variant="outline" className={cn("gap-1 text-[10px]", c.color)}>
+ <Badge variant="outline" className={cn('gap-1 text-[10px]', c.color)}>
<c.icon className="h-2.5 w-2.5" />
{c.label}
</Badge>
@@ -132,15 +128,15 @@ function StatusPill({ status }: { status: BrandCardSummary["status"] }) {
}
export function BrandCard({ brand, summary }: BrandCardProps) {
- const t = useTranslations("brands");
+ const t = useTranslations('brands');
const router = useRouter();
const { activeBrandId, setActiveBrand } = useBrandStore();
const isActive = brand.id === activeBrandId;
const initials = brand.name
- .split(" ")
+ .split(' ')
.map((w) => w[0])
- .join("")
+ .join('')
.toUpperCase()
.slice(0, 2);
@@ -153,7 +149,7 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
const prompts = summary?.promptCount ?? 0;
const trafficVisits = summary?.trafficVisits7d ?? 0;
const trend = summary?.trend ?? [];
- const status = summary?.status ?? "no-prompts";
+ const status = summary?.status ?? 'no-prompts';
const trendPositive = delta >= 0;
const handleSelectAndGo = (path: string) => {
@@ -164,26 +160,17 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
return (
<div
className={cn(
- "group relative overflow-hidden rounded-xl border bg-card transition-all",
- "hover:border-primary/40 hover:shadow-lg hover:-translate-y-0.5",
- isActive && "ring-2 ring-primary border-primary/60",
+ 'group relative overflow-hidden rounded-xl border bg-card transition-all',
+ 'hover:border-primary/40 hover:shadow-lg hover:-translate-y-0.5',
+ isActive && 'ring-2 ring-primary border-primary/60',
)}
>
{/* Hero gradient backdrop */}
- <div
- className={cn(
- "relative h-28 bg-gradient-to-br px-5 pt-5",
- gradient,
- )}
- >
+ <div className={cn('relative h-28 bg-gradient-to-br px-5 pt-5', gradient)}>
<div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,_rgba(255,255,255,0.15),_transparent_60%)]" />
<div className="relative flex items-start justify-between gap-3">
<Avatar className="h-14 w-14 rounded-xl ring-4 ring-background shadow-md bg-zinc-50 dark:bg-zinc-100">
- <AvatarImage
- src={brand.logoUrl}
- alt={brand.name}
- className="object-contain p-1.5"
- />
+ <AvatarImage src={brand.logoUrl} alt={brand.name} className="object-contain p-1.5" />
<AvatarFallback className="rounded-xl bg-background text-foreground text-base font-bold">
{initials}
</AvatarFallback>
@@ -211,22 +198,16 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
}
/>
<DropdownMenuContent align="end" className="w-44">
- <DropdownMenuItem
- render={<Link href={`/dashboard/brands/${brand.id}/prompts`} />}
- >
+ <DropdownMenuItem render={<Link href={`/dashboard/brands/${brand.id}/prompts`} />}>
<MessageSquareText className="h-3.5 w-3.5 mr-2" />
Prompts
</DropdownMenuItem>
- <DropdownMenuItem
- render={<Link href={`/dashboard/brands/${brand.id}/topics`} />}
- >
+ <DropdownMenuItem render={<Link href={`/dashboard/brands/${brand.id}/topics`} />}>
<Tag className="h-3.5 w-3.5 mr-2" />
Topics
</DropdownMenuItem>
<DropdownMenuSeparator />
- <DropdownMenuItem
- render={<Link href={`/dashboard/brands/${brand.id}/settings`} />}
- >
+ <DropdownMenuItem render={<Link href={`/dashboard/brands/${brand.id}/settings`} />}>
<Settings className="h-3.5 w-3.5 mr-2" />
Settings
</DropdownMenuItem>
@@ -240,9 +221,7 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
<div className="px-5 pt-3 pb-4 space-y-4">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
- <h3 className="font-semibold text-base leading-tight truncate">
- {brand.name}
- </h3>
+ <h3 className="font-semibold text-base leading-tight truncate">{brand.name}</h3>
{primaryDomain && (
<p className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground truncate">
<Globe className="h-3 w-3 shrink-0" />
@@ -263,17 +242,13 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
<div className="flex items-baseline gap-2 mt-0.5">
<span className="text-2xl font-bold tabular-nums">
{visibility}
- <span className="text-base font-medium text-muted-foreground">
- %
- </span>
+ <span className="text-base font-medium text-muted-foreground">%</span>
</span>
{summary && summary.visibilityDelta !== 0 && (
<span
className={cn(
- "flex items-center gap-0.5 text-xs font-medium tabular-nums",
- trendPositive
- ? "text-emerald-600 dark:text-emerald-400"
- : "text-red-500",
+ 'flex items-center gap-0.5 text-xs font-medium tabular-nums',
+ trendPositive ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-500',
)}
>
{trendPositive ? (
@@ -281,7 +256,7 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
) : (
<TrendingDown className="h-3 w-3" />
)}
- {trendPositive ? "+" : ""}
+ {trendPositive ? '+' : ''}
{delta}%
</span>
)}
@@ -296,30 +271,22 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
{/* Compact stat strip */}
<div className="grid grid-cols-3 gap-2 text-center">
<div className="rounded-md border bg-card px-2 py-1.5">
- <p className="text-base font-semibold tabular-nums leading-none">
- {prompts}
- </p>
+ <p className="text-base font-semibold tabular-nums leading-none">{prompts}</p>
<p className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">
Prompts
</p>
</div>
<div className="rounded-md border bg-card px-2 py-1.5">
- <p className="text-base font-semibold tabular-nums leading-none">
- {mentions}
- </p>
+ <p className="text-base font-semibold tabular-nums leading-none">{mentions}</p>
<p className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">
Mentions
</p>
</div>
<div className="rounded-md border bg-card px-2 py-1.5">
<p className="text-base font-semibold tabular-nums leading-none">
- {trafficVisits >= 1000
- ? `${(trafficVisits / 1000).toFixed(1)}k`
- : trafficVisits}
- </p>
- <p className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">
- Visits
+ {trafficVisits >= 1000 ? `${(trafficVisits / 1000).toFixed(1)}k` : trafficVisits}
</p>
+ <p className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">Visits</p>
</div>
</div>
@@ -327,10 +294,10 @@ export function BrandCard({ brand, summary }: BrandCardProps) {
<Button
size="sm"
className="w-full gap-1.5"
- onClick={() => handleSelectAndGo("/dashboard/insights")}
+ onClick={() => handleSelectAndGo('/dashboard/insights')}
>
<BarChart3 className="h-3.5 w-3.5" />
- {t("card.viewInsights")}
+ {t('card.viewInsights')}
<ArrowUpRight className="h-3.5 w-3.5 ml-auto" />
</Button>
</div>
diff --git a/web/src/components/dashboard/prompt-suggestion-card.tsx b/web/src/components/dashboard/prompt-suggestion-card.tsx
index bebc6981a..44ad65882 100644
--- a/web/src/components/dashboard/prompt-suggestion-card.tsx
+++ b/web/src/components/dashboard/prompt-suggestion-card.tsx
@@ -23,12 +23,7 @@ import {
} from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
import { Check, Pencil, Trash2, X } from 'lucide-react';
-import {
- MODEL_GROUPS,
- ALL_MODELS,
- SCRAPER_GROUPS,
- ALL_SCRAPERS,
-} from '@/config/prompt-options';
+import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';
interface TopicOption {
id: string;
@@ -128,9 +123,7 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({
<div
className={cn(
'group flex items-start gap-3 rounded-lg border p-3 transition-colors',
- isActive
- ? 'border-border bg-card'
- : 'border-border/50 bg-muted/30 opacity-60',
+ isActive ? 'border-border bg-card' : 'border-border/50 bg-muted/30 opacity-60',
)}
>
{/* Toggle checkbox */}
@@ -214,10 +207,7 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({
value="__placeholder__"
onValueChange={(v) => {
if (!v || v === '__placeholder__') return;
- if (
- visibleModels.some((m) => m.id === v) &&
- !editModels.includes(v)
- ) {
+ if (visibleModels.some((m) => m.id === v) && !editModels.includes(v)) {
setEditModels((prev) => [...prev, v]);
} else if (
visibleScrapers.some((s) => s.id === v) &&
@@ -296,19 +286,11 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({
{editPlatforms.map((id) => {
const s = ALL_SCRAPERS.find((as_) => as_.id === id);
return (
- <Badge
- key={id}
- variant="outline"
- className="gap-1 text-xs"
- >
+ <Badge key={id} variant="outline" className="gap-1 text-xs">
{s?.label ?? id}
<button
type="button"
- onClick={() =>
- setEditPlatforms((p) =>
- p.filter((i) => i !== id),
- )
- }
+ onClick={() => setEditPlatforms((p) => p.filter((i) => i !== id))}
>
<X className="h-3 w-3" />
</button>
@@ -318,19 +300,11 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({
{editModels.map((id) => {
const m = ALL_MODELS.find((am) => am.id === id);
return (
- <Badge
- key={id}
- variant="secondary"
- className="gap-1 text-xs"
- >
+ <Badge key={id} variant="secondary" className="gap-1 text-xs">
{m?.label ?? id}
<button
type="button"
- onClick={() =>
- setEditModels((p) =>
- p.filter((i) => i !== id),
- )
- }
+ onClick={() => setEditModels((p) => p.filter((i) => i !== id))}
>
<X className="h-3 w-3" />
</button>
@@ -341,7 +315,6 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({
)}
</div>
)}
-
</div>
)}
</div>
@@ -374,22 +347,15 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({
<DialogHeader>
<DialogTitle>Delete Prompt</DialogTitle>
<DialogDescription>
- Are you sure you want to delete this prompt? This action
- cannot be undone.
+ Are you sure you want to delete this prompt? This action cannot be undone.
</DialogDescription>
</DialogHeader>
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground line-clamp-2">
{text}
</p>
<DialogFooter>
- <DialogClose render={<Button variant="outline" />}>
- Cancel
- </DialogClose>
- <DialogClose
- render={
- <Button variant="destructive" onClick={onDelete} />
- }
- >
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
+ <DialogClose render={<Button variant="destructive" onClick={onDelete} />}>
Delete
</DialogClose>
</DialogFooter>
diff --git a/web/src/components/layout/brand-switcher.tsx b/web/src/components/layout/brand-switcher.tsx
index 3b45e704f..52c117f51 100644
--- a/web/src/components/layout/brand-switcher.tsx
+++ b/web/src/components/layout/brand-switcher.tsx
@@ -1,8 +1,8 @@
-"use client";
+'use client';
-import { useTranslations } from "next-intl";
-import { useRouter } from "@/i18n/navigation";
-import { useBrandStore } from "@/stores/use-brand-store";
+import { useTranslations } from 'next-intl';
+import { useRouter } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
import {
DropdownMenu,
DropdownMenuContent,
@@ -11,17 +11,17 @@ import {
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import { cn } from "@/lib/utils";
-import { Check, ChevronsUpDown, Plus } from "lucide-react";
+} from '@/components/ui/dropdown-menu';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { cn } from '@/lib/utils';
+import { Check, ChevronsUpDown, Plus } from 'lucide-react';
interface BrandSwitcherProps {
collapsed?: boolean;
}
export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {
- const t = useTranslations("brands");
+ const t = useTranslations('brands');
const router = useRouter();
const { brands, activeBrandId, setActiveBrand } = useBrandStore();
@@ -29,26 +29,24 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {
const initials = (name: string) =>
name
- .split(" ")
+ .split(' ')
.map((w) => w[0])
- .join("")
+ .join('')
.toUpperCase()
.slice(0, 2);
if (brands.length === 0) {
return (
<button
- onClick={() => router.push("/dashboard/brands/new")}
+ onClick={() => router.push('/dashboard/brands/new')}
className={cn(
- "flex w-full items-center gap-2 rounded-md border border-dashed px-2 py-2 text-sm text-muted-foreground transition-colors hover:border-primary hover:text-primary",
- collapsed && "justify-center px-0"
+ 'flex w-full items-center gap-2 rounded-md border border-dashed px-2 py-2 text-sm text-muted-foreground transition-colors hover:border-primary hover:text-primary',
+ collapsed && 'justify-center px-0',
)}
- title={collapsed ? t("addBrand") : undefined}
+ title={collapsed ? t('addBrand') : undefined}
>
<Plus className="h-4 w-4 shrink-0" />
- {!collapsed && (
- <span className="truncate text-xs">{t("addBrand")}</span>
- )}
+ {!collapsed && <span className="truncate text-xs">{t('addBrand')}</span>}
</button>
);
}
@@ -57,10 +55,10 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {
<DropdownMenu>
<DropdownMenuTrigger
className={cn(
- "flex w-full items-center gap-2 rounded-md px-2 py-2 text-sm transition-colors hover:bg-accent focus-visible:outline-none",
- collapsed && "justify-center px-0"
+ 'flex w-full items-center gap-2 rounded-md px-2 py-2 text-sm transition-colors hover:bg-accent focus-visible:outline-none',
+ collapsed && 'justify-center px-0',
)}
- aria-label={t("switchBrand")}
+ aria-label={t('switchBrand')}
>
<Avatar className="h-6 w-6 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100">
<AvatarImage
@@ -69,29 +67,24 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {
className="object-contain p-0.5"
/>
<AvatarFallback className="rounded-md bg-primary text-primary-foreground text-xs font-semibold">
- {activeBrand ? initials(activeBrand.name) : "?"}
+ {activeBrand ? initials(activeBrand.name) : '?'}
</AvatarFallback>
</Avatar>
{!collapsed && (
<>
<span className="flex-1 truncate text-left text-sm font-medium">
- {activeBrand?.name ?? t("selectBrand")}
+ {activeBrand?.name ?? t('selectBrand')}
</span>
<ChevronsUpDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</>
)}
</DropdownMenuTrigger>
- <DropdownMenuContent
- className="w-56"
- align="start"
- side="bottom"
- sideOffset={4}
- >
+ <DropdownMenuContent className="w-56" align="start" side="bottom" sideOffset={4}>
<DropdownMenuGroup>
<DropdownMenuLabel className="text-xs text-muted-foreground">
- {t("switchBrand")}
+ {t('switchBrand')}
</DropdownMenuLabel>
</DropdownMenuGroup>
<DropdownMenuSeparator />
@@ -119,9 +112,7 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {
<div className="flex-1 overflow-hidden">
<p className="truncate text-sm font-medium">{brand.name}</p>
{primaryDomain && (
- <p className="truncate text-xs text-muted-foreground">
- {primaryDomain.domain}
- </p>
+ <p className="truncate text-xs text-muted-foreground">{primaryDomain.domain}</p>
)}
</div>
{isActive && <Check className="h-3.5 w-3.5 shrink-0 text-primary" />}
@@ -132,13 +123,13 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {
<DropdownMenuSeparator />
<DropdownMenuItem
- onClick={() => router.push("/dashboard/brands")}
+ onClick={() => router.push('/dashboard/brands')}
className="flex items-center gap-2 text-muted-foreground"
>
<div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border">
<Plus className="h-3 w-3" />
</div>
- <span className="text-sm">{t("addBrand")}</span>
+ <span className="text-sm">{t('addBrand')}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsx
index 5ef6bf414..9feef7b89 100644
--- a/web/src/components/layout/mobile-nav.tsx
+++ b/web/src/components/layout/mobile-nav.tsx
@@ -27,8 +27,7 @@ export function MobileNav() {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
- const logoSrc =
- mounted && resolvedTheme === 'dark' ? '/logo_dark.svg' : '/logo_light.svg';
+ const logoSrc = mounted && resolvedTheme === 'dark' ? '/logo_dark.svg' : '/logo_light.svg';
const getLabel = (title: string): string => {
const map: Record<string, string> = {
@@ -48,9 +47,7 @@ export function MobileNav() {
return (
<Sheet open={open} onOpenChange={setOpen}>
- <SheetTrigger
- render={<Button variant="ghost" size="icon" className="md:hidden" />}
- >
+ <SheetTrigger render={<Button variant="ghost" size="icon" className="md:hidden" />}>
<Menu className="h-5 w-5" />
<span className="sr-only">Toggle menu</span>
</SheetTrigger>
@@ -95,9 +92,7 @@ export function MobileNav() {
const label = getLabel(item.title);
const isLocked =
- isCloud &&
- item.requiredFeature != null &&
- !canUse(item.requiredFeature);
+ isCloud && item.requiredFeature != null && !canUse(item.requiredFeature);
if (isLocked) {
return (
@@ -119,11 +114,7 @@ export function MobileNav() {
}
return (
- <Link
- key={item.href}
- href={item.href}
- onClick={() => setOpen(false)}
- >
+ <Link key={item.href} href={item.href} onClick={() => setOpen(false)}>
<span
className={cn(
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
diff --git a/web/src/components/layout/sidebar-error-boundary.tsx b/web/src/components/layout/sidebar-error-boundary.tsx
index 734ac4c58..afdfe5cf9 100644
--- a/web/src/components/layout/sidebar-error-boundary.tsx
+++ b/web/src/components/layout/sidebar-error-boundary.tsx
@@ -1,6 +1,6 @@
-"use client";
+'use client';
-import React from "react";
+import React from 'react';
interface Props {
children: React.ReactNode;
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index d3153218e..433fb4fba 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -28,8 +28,7 @@ export function Sidebar() {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
- const logoSrc =
- mounted && resolvedTheme === 'dark' ? '/logo_dark.svg' : '/logo_light.svg';
+ const logoSrc = mounted && resolvedTheme === 'dark' ? '/logo_dark.svg' : '/logo_light.svg';
const navKeyMap: Record<string, () => string> = {
Overview: () => t('overview'),
@@ -53,17 +52,11 @@ export function Sidebar() {
)}
>
<div
- className={cn(
- 'flex h-16 items-center border-b px-3',
- isCollapsed && 'justify-center px-0',
- )}
+ className={cn('flex h-16 items-center border-b px-3', isCollapsed && 'justify-center px-0')}
>
<Link
href="/dashboard"
- className={cn(
- 'flex items-center gap-2 overflow-hidden',
- !isCollapsed && 'w-full',
- )}
+ className={cn('flex items-center gap-2 overflow-hidden', !isCollapsed && 'w-full')}
>
<Image
src={logoSrc}
@@ -73,9 +66,7 @@ export function Sidebar() {
className="h-6 w-6 shrink-0"
priority
/>
- {!isCollapsed && (
- <span className="truncate font-semibold">{siteConfig.name}</span>
- )}
+ {!isCollapsed && <span className="truncate font-semibold">{siteConfig.name}</span>}
</Link>
</div>
@@ -91,9 +82,7 @@ export function Sidebar() {
{group.title}
</p>
)}
- {group.title && isCollapsed && i > 0 && (
- <Separator className="my-2" />
- )}
+ {group.title && isCollapsed && i > 0 && <Separator className="my-2" />}
<nav className="space-y-0.5">
{group.items.map((item) => {
const isActive =
@@ -104,9 +93,7 @@ export function Sidebar() {
const label = labelFn ? labelFn() : item.title;
const isLocked =
- isCloud &&
- item.requiredFeature != null &&
- !canUse(item.requiredFeature);
+ isCloud && item.requiredFeature != null && !canUse(item.requiredFeature);
if (isLocked) {
return (
@@ -155,9 +142,7 @@ export function Sidebar() {
title={isCollapsed ? label : undefined}
>
<item.icon className="h-4 w-4 shrink-0" />
- {!isCollapsed && (
- <span className="truncate">{label}</span>
- )}
+ {!isCollapsed && <span className="truncate">{label}</span>}
</span>
</Link>
);
@@ -172,12 +157,7 @@ export function Sidebar() {
</div>
<div className="border-t p-2">
- <Button
- variant="ghost"
- size="icon"
- className="mt-1 w-full"
- onClick={toggleCollapse}
- >
+ <Button variant="ghost" size="icon" className="mt-1 w-full" onClick={toggleCollapse}>
{isCollapsed ? (
<PanelLeftOpen className="h-4 w-4" />
) : (
diff --git a/web/src/components/layout/user-profile-nav-item.tsx b/web/src/components/layout/user-profile-nav-item.tsx
index 235926e17..d34ffb361 100644
--- a/web/src/components/layout/user-profile-nav-item.tsx
+++ b/web/src/components/layout/user-profile-nav-item.tsx
@@ -47,9 +47,7 @@ export function UserProfileNavItem({
{initials}
</AvatarFallback>
</Avatar>
- {!collapsed && (
- <span className="truncate text-sm font-medium capitalize">{label}</span>
- )}
+ {!collapsed && <span className="truncate text-sm font-medium capitalize">{label}</span>}
</Link>
);
}
diff --git a/web/src/components/marketing/marketing-footer.tsx b/web/src/components/marketing/marketing-footer.tsx
index ee6af8e43..91012ebee 100644
--- a/web/src/components/marketing/marketing-footer.tsx
+++ b/web/src/components/marketing/marketing-footer.tsx
@@ -1,11 +1,11 @@
-import { siteConfig } from "@/config/site";
+import { siteConfig } from '@/config/site';
export function MarketingFooter() {
return (
<footer className="border-t py-8">
<div className="container flex flex-col items-center justify-between gap-4 md:flex-row">
<p className="text-sm text-muted-foreground">
- &copy; {new Date().getFullYear()} {siteConfig.name}. Open source under{" "}
+ &copy; {new Date().getFullYear()} {siteConfig.name}. Open source under{' '}
<a
href="https://github.com/aeohub/ansvisor/blob/main/LICENSE"
target="_blank"
diff --git a/web/src/components/marketing/marketing-header.tsx b/web/src/components/marketing/marketing-header.tsx
index 51f26f96d..9c1ee6f12 100644
--- a/web/src/components/marketing/marketing-header.tsx
+++ b/web/src/components/marketing/marketing-header.tsx
@@ -1,11 +1,11 @@
-import Image from "next/image";
-import { useTranslations } from "next-intl";
-import { Link } from "@/i18n/navigation";
-import { Button } from "@/components/ui/button";
-import { siteConfig } from "@/config/site";
+import Image from 'next/image';
+import { useTranslations } from 'next-intl';
+import { Link } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import { siteConfig } from '@/config/site';
export function MarketingHeader() {
- const t = useTranslations("auth");
+ const t = useTranslations('auth');
return (
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
@@ -27,19 +27,17 @@ export function MarketingHeader() {
className="hidden h-7 w-7 shrink-0 dark:block"
priority
/>
- <span className="text-xl font-bold tracking-tight">
- {siteConfig.name}
- </span>
+ <span className="text-xl font-bold tracking-tight">{siteConfig.name}</span>
</a>
<div className="flex items-center gap-3">
<Link href="/sign-in">
<Button variant="ghost" size="sm">
- {t("signIn")}
+ {t('signIn')}
</Button>
</Link>
<Link href="/sign-up">
- <Button size="sm">{t("createAccount")}</Button>
+ <Button size="sm">{t('createAccount')}</Button>
</Link>
</div>
</div>
diff --git a/web/src/components/providers/auth-provider.tsx b/web/src/components/providers/auth-provider.tsx
index 0a6bf1bcd..cf7d9d661 100644
--- a/web/src/components/providers/auth-provider.tsx
+++ b/web/src/components/providers/auth-provider.tsx
@@ -1,10 +1,10 @@
-"use client";
+'use client';
-import { useEffect } from "react";
-import type { User } from "@supabase/supabase-js";
-import { useAuthStore } from "@/stores/use-auth-store";
-import { createClient } from "@/lib/supabase/client";
-import { identify, reset as resetAnalytics } from "@/lib/analytics";
+import { useEffect } from 'react';
+import type { User } from '@supabase/supabase-js';
+import { useAuthStore } from '@/stores/use-auth-store';
+import { createClient } from '@/lib/supabase/client';
+import { identify, reset as resetAnalytics } from '@/lib/analytics';
interface AuthProviderProps {
user: User | null;
@@ -29,14 +29,11 @@ export function AuthProvider({ user }: AuthProviderProps) {
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((event, session) => {
- if (
- (event === "INITIAL_SESSION" || event === "SIGNED_IN") &&
- session?.user
- ) {
+ if ((event === 'INITIAL_SESSION' || event === 'SIGNED_IN') && session?.user) {
identify(session.user.id, {
email: session.user.email,
});
- } else if (event === "SIGNED_OUT") {
+ } else if (event === 'SIGNED_OUT') {
resetAnalytics();
}
});
diff --git a/web/src/components/providers/brand-guard.tsx b/web/src/components/providers/brand-guard.tsx
index a4874b0c4..5963a3793 100644
--- a/web/src/components/providers/brand-guard.tsx
+++ b/web/src/components/providers/brand-guard.tsx
@@ -1,25 +1,19 @@
-"use client";
-
-import { useSyncExternalStore, useCallback } from "react";
-import { useBrandStore } from "@/stores/use-brand-store";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent } from "@/components/ui/card";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Link } from "@/i18n/navigation";
-import { Building2, Plus, ChevronRight } from "lucide-react";
-import { usePathname } from "@/i18n/navigation";
-
-const BRAND_EXEMPT_PATHS = [
- "/dashboard/brands",
- "/dashboard/settings",
- "/dashboard/onboarding",
-];
+'use client';
+
+import { useSyncExternalStore, useCallback } from 'react';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Link } from '@/i18n/navigation';
+import { Building2, Plus, ChevronRight } from 'lucide-react';
+import { usePathname } from '@/i18n/navigation';
+
+const BRAND_EXEMPT_PATHS = ['/dashboard/brands', '/dashboard/settings', '/dashboard/onboarding'];
function isExempt(pathname: string) {
- return BRAND_EXEMPT_PATHS.some(
- (p) => pathname === p || pathname.startsWith(p + "/"),
- );
+ return BRAND_EXEMPT_PATHS.some((p) => pathname === p || pathname.startsWith(p + '/'));
}
const emptySubscribe = () => () => {};
@@ -50,12 +44,7 @@ export function BrandGuard({ children }: { children: React.ReactNode }) {
const activeBrand = brands.find((b) => b.id === activeBrandId);
if (!activeBrand) {
- return (
- <BrandSelector
- brands={brands}
- onSelect={(id) => setActiveBrand(id)}
- />
- );
+ return <BrandSelector brands={brands} onSelect={(id) => setActiveBrand(id)} />;
}
return <>{children}</>;
@@ -111,9 +100,9 @@ function BrandSelector({
}) {
const initials = (name: string) =>
name
- .split(" ")
+ .split(' ')
.map((w) => w[0])
- .join("")
+ .join('')
.toUpperCase()
.slice(0, 2);
@@ -136,18 +125,12 @@ function BrandSelector({
>
<CardContent className="flex items-center gap-3 p-4">
<Avatar className="h-9 w-9 rounded-md bg-zinc-50 dark:bg-zinc-100">
- <AvatarImage
- src={brand.logoUrl}
- alt={brand.name}
- className="object-contain p-1"
- />
+ <AvatarImage src={brand.logoUrl} alt={brand.name} className="object-contain p-1" />
<AvatarFallback className="rounded-md bg-primary text-primary-foreground text-sm font-semibold">
{initials(brand.name)}
</AvatarFallback>
</Avatar>
- <span className="flex-1 text-left text-sm font-medium">
- {brand.name}
- </span>
+ <span className="flex-1 text-left text-sm font-medium">{brand.name}</span>
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</CardContent>
</Card>
diff --git a/web/src/components/providers/brand-loader.tsx b/web/src/components/providers/brand-loader.tsx
index 7468f72cb..0f865f659 100644
--- a/web/src/components/providers/brand-loader.tsx
+++ b/web/src/components/providers/brand-loader.tsx
@@ -1,8 +1,8 @@
-"use client";
+'use client';
-import { useEffect } from "react";
-import { useBrandStore } from "@/stores/use-brand-store";
-import type { Brand } from "@/types";
+import { useEffect } from 'react';
+import { useBrandStore } from '@/stores/use-brand-store';
+import type { Brand } from '@/types';
interface BrandLoaderProps {
brands: Brand[];
diff --git a/web/src/components/providers/plan-provider.tsx b/web/src/components/providers/plan-provider.tsx
index e8296749b..5cea25843 100644
--- a/web/src/components/providers/plan-provider.tsx
+++ b/web/src/components/providers/plan-provider.tsx
@@ -1,7 +1,7 @@
-"use client";
+'use client';
-import { createContext, useContext } from "react";
-import type { PlanId } from "@/config/plans";
+import { createContext, useContext } from 'react';
+import type { PlanId } from '@/config/plans';
interface PlanContextValue {
planId: PlanId;
@@ -9,19 +9,13 @@ interface PlanContextValue {
}
const PlanContext = createContext<PlanContextValue>({
- planId: "self_hosted",
+ planId: 'self_hosted',
isCloud: false,
});
-export function PlanProvider({
- planId,
- children,
-}: {
- planId: PlanId;
- children: React.ReactNode;
-}) {
- const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === "true";
- const effectivePlan: PlanId = isCloud ? planId : "self_hosted";
+export function PlanProvider({ planId, children }: { planId: PlanId; children: React.ReactNode }) {
+ const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === 'true';
+ const effectivePlan: PlanId = isCloud ? planId : 'self_hosted';
return (
<PlanContext.Provider value={{ planId: effectivePlan, isCloud }}>
diff --git a/web/src/components/providers/posthog-provider.tsx b/web/src/components/providers/posthog-provider.tsx
index c989b7299..c3334c8da 100644
--- a/web/src/components/providers/posthog-provider.tsx
+++ b/web/src/components/providers/posthog-provider.tsx
@@ -23,8 +23,7 @@ export function PostHogProvider() {
if (!key) return;
posthog.init(key, {
- api_host:
- process.env.NEXT_PUBLIC_POSTHOG_HOST ?? 'https://us.i.posthog.com',
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST ?? 'https://us.i.posthog.com',
capture_pageview: 'history_change',
capture_pageleave: true,
autocapture: false,
diff --git a/web/src/components/settings/api-keys-section.tsx b/web/src/components/settings/api-keys-section.tsx
index e67b26b16..0b65b5c71 100644
--- a/web/src/components/settings/api-keys-section.tsx
+++ b/web/src/components/settings/api-keys-section.tsx
@@ -1,17 +1,11 @@
-"use client";
+'use client';
-import { useCallback, useEffect, useState } from "react";
-import { toast } from "sonner";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
+import { useCallback, useEffect, useState } from 'react';
+import { toast } from 'sonner';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
import {
Dialog,
DialogClose,
@@ -20,10 +14,10 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/components/ui/dialog";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Badge } from "@/components/ui/badge";
-import { Copy, KeyRound, Loader2, Plus, Trash2 } from "lucide-react";
+} from '@/components/ui/dialog';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Badge } from '@/components/ui/badge';
+import { Copy, KeyRound, Loader2, Plus, Trash2 } from 'lucide-react';
interface ApiKey {
id: string;
@@ -34,21 +28,19 @@ interface ApiKey {
created_at: string;
}
-const configuredAppUrl = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, "") ?? "";
+const configuredAppUrl = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, '') ?? '';
function getMcpEndpoint(): string {
- const appUrl =
- configuredAppUrl ||
- (typeof window !== "undefined" ? window.location.origin : "");
+ const appUrl = configuredAppUrl || (typeof window !== 'undefined' ? window.location.origin : '');
return `${appUrl}/api/mcp`;
}
function formatDate(iso: string | null): string {
- if (!iso) return "—";
+ if (!iso) return '—';
return new Date(iso).toLocaleDateString(undefined, {
- year: "numeric",
- month: "short",
- day: "numeric",
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
});
}
@@ -56,7 +48,7 @@ export function ApiKeysSection() {
const [keys, setKeys] = useState<ApiKey[]>([]);
const [loading, setLoading] = useState(true);
const [createOpen, setCreateOpen] = useState(false);
- const [newName, setNewName] = useState("");
+ const [newName, setNewName] = useState('');
const [creating, setCreating] = useState(false);
const [revealedToken, setRevealedToken] = useState<string | null>(null);
const mcpEndpoint = getMcpEndpoint();
@@ -64,12 +56,12 @@ export function ApiKeysSection() {
const load = useCallback(async () => {
setLoading(true);
try {
- const res = await fetch("/api/keys");
+ const res = await fetch('/api/keys');
const body = (await res.json()) as { keys?: ApiKey[]; error?: string };
- if (!res.ok) throw new Error(body.error || "Failed to load");
+ if (!res.ok) throw new Error(body.error || 'Failed to load');
setKeys(body.keys ?? []);
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to load");
+ toast.error(err instanceof Error ? err.message : 'Failed to load');
} finally {
setLoading(false);
}
@@ -83,47 +75,47 @@ export function ApiKeysSection() {
if (!newName.trim()) return;
setCreating(true);
try {
- const res = await fetch("/api/keys", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ const res = await fetch('/api/keys', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName.trim() }),
});
const body = (await res.json()) as {
key?: ApiKey & { token: string };
error?: string;
};
- if (!res.ok || !body.key) throw new Error(body.error || "Failed to create");
+ if (!res.ok || !body.key) throw new Error(body.error || 'Failed to create');
setRevealedToken(body.key.token);
- setNewName("");
+ setNewName('');
setCreateOpen(false);
await load();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to create");
+ toast.error(err instanceof Error ? err.message : 'Failed to create');
} finally {
setCreating(false);
}
};
const handleRevoke = async (id: string) => {
- if (!confirm("Revoke this API key? Clients using it will lose access immediately.")) {
+ if (!confirm('Revoke this API key? Clients using it will lose access immediately.')) {
return;
}
try {
- const res = await fetch(`/api/keys/${id}`, { method: "DELETE" });
+ const res = await fetch(`/api/keys/${id}`, { method: 'DELETE' });
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
- throw new Error(body.error || "Failed to revoke");
+ throw new Error(body.error || 'Failed to revoke');
}
- toast.success("Key revoked");
+ toast.success('Key revoked');
await load();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to revoke");
+ toast.error(err instanceof Error ? err.message : 'Failed to revoke');
}
};
const copy = async (text: string) => {
await navigator.clipboard.writeText(text);
- toast.success("Copied to clipboard");
+ toast.success('Copied to clipboard');
};
return (
@@ -136,8 +128,8 @@ export function ApiKeysSection() {
API Keys
</CardTitle>
<CardDescription>
- Long-lived tokens for the Ansvisor MCP server and other external
- clients. Keys are shown once at creation — store them somewhere safe.
+ Long-lived tokens for the Ansvisor MCP server and other external clients. Keys are
+ shown once at creation — store them somewhere safe.
</CardDescription>
</div>
<Button size="sm" onClick={() => setCreateOpen(true)} className="gap-1.5 shrink-0">
@@ -150,9 +142,7 @@ export function ApiKeysSection() {
<div className="rounded-md border bg-muted/40 p-3 text-xs space-y-1.5">
<p className="font-medium text-foreground">MCP endpoint</p>
<div className="flex items-center gap-2">
- <code className="flex-1 truncate font-mono">
- {mcpEndpoint}
- </code>
+ <code className="flex-1 truncate font-mono">{mcpEndpoint}</code>
<Button
size="sm"
variant="ghost"
@@ -163,8 +153,7 @@ export function ApiKeysSection() {
</Button>
</div>
<p className="text-muted-foreground">
- Paste this URL + a key below into Claude Desktop / Claude Code /
- Cursor. See the{" "}
+ Paste this URL + a key below into Claude Desktop / Claude Code / Cursor. See the{' '}
<a
href="https://github.com/aeohub/ansvisor#whats-next"
target="_blank"
@@ -191,10 +180,7 @@ export function ApiKeysSection() {
{keys.map((k) => {
const revoked = !!k.revoked_at;
return (
- <div
- key={k.id}
- className="flex items-center justify-between gap-4 p-3"
- >
+ <div key={k.id} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm font-medium truncate">{k.name}</p>
@@ -204,12 +190,9 @@ export function ApiKeysSection() {
</Badge>
)}
</div>
- <p className="text-xs text-muted-foreground font-mono">
- {k.prefix}…
- </p>
+ <p className="text-xs text-muted-foreground font-mono">{k.prefix}…</p>
<p className="text-[11px] text-muted-foreground">
- Created {formatDate(k.created_at)} · Last used{" "}
- {formatDate(k.last_used_at)}
+ Created {formatDate(k.created_at)} · Last used {formatDate(k.last_used_at)}
</p>
</div>
{!revoked && (
@@ -252,10 +235,7 @@ export function ApiKeysSection() {
<DialogClose render={<Button variant="outline" disabled={creating} />}>
Cancel
</DialogClose>
- <Button
- onClick={handleCreate}
- disabled={creating || !newName.trim()}
- >
+ <Button onClick={handleCreate} disabled={creating || !newName.trim()}>
{creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create
</Button>
@@ -263,10 +243,7 @@ export function ApiKeysSection() {
</DialogContent>
</Dialog>
- <Dialog
- open={!!revealedToken}
- onOpenChange={(v) => !v && setRevealedToken(null)}
- >
+ <Dialog open={!!revealedToken} onOpenChange={(v) => !v && setRevealedToken(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Copy your API key</DialogTitle>
diff --git a/web/src/components/settings/billing-section.tsx b/web/src/components/settings/billing-section.tsx
index ceb54afee..de2cc7f14 100644
--- a/web/src/components/settings/billing-section.tsx
+++ b/web/src/components/settings/billing-section.tsx
@@ -1,16 +1,16 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import { useTranslations } from "next-intl";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { Skeleton } from "@/components/ui/skeleton";
-import { PlanSwitcher } from "@/components/settings/plan-switcher";
-import { InvoiceList } from "@/components/settings/invoice-list";
-import { usePlanContext } from "@/components/providers/plan-provider";
-import { createClient } from "@/lib/supabase/client";
-import { PLANS, type PlanId } from "@/config/plans";
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Separator } from '@/components/ui/separator';
+import { Skeleton } from '@/components/ui/skeleton';
+import { PlanSwitcher } from '@/components/settings/plan-switcher';
+import { InvoiceList } from '@/components/settings/invoice-list';
+import { usePlanContext } from '@/components/providers/plan-provider';
+import { createClient } from '@/lib/supabase/client';
+import { PLANS, type PlanId } from '@/config/plans';
interface SubscriptionData {
planId: string;
@@ -23,36 +23,36 @@ interface SubscriptionData {
function statusVariant(status: string) {
switch (status) {
- case "active":
- return "default" as const;
- case "trialing":
- return "secondary" as const;
- case "past_due":
- return "destructive" as const;
- case "canceled":
- return "destructive" as const;
+ case 'active':
+ return 'default' as const;
+ case 'trialing':
+ return 'secondary' as const;
+ case 'past_due':
+ return 'destructive' as const;
+ case 'canceled':
+ return 'destructive' as const;
default:
- return "outline" as const;
+ return 'outline' as const;
}
}
function statusLabel(status: string) {
switch (status) {
- case "active":
- return "Active";
- case "trialing":
- return "Trial";
- case "past_due":
- return "Past Due";
- case "canceled":
- return "Canceled";
+ case 'active':
+ return 'Active';
+ case 'trialing':
+ return 'Trial';
+ case 'past_due':
+ return 'Past Due';
+ case 'canceled':
+ return 'Canceled';
default:
return status;
}
}
export function BillingSection() {
- const t = useTranslations("settings");
+ const t = useTranslations('settings');
const { planId: contextPlanId } = usePlanContext();
const [subscription, setSubscription] = useState<SubscriptionData | null>(null);
const [loading, setLoading] = useState(true);
@@ -62,38 +62,40 @@ export function BillingSection() {
try {
// First: load org data directly from Supabase (reliable, no API route auth issues)
const supabase = createClient();
- const { data: { user } } = await supabase.auth.getUser();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
if (!user) return;
const { data: profile } = await supabase
- .from("profiles")
- .select("organization_id")
- .eq("id", user.id)
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', user.id)
.single();
if (!profile?.organization_id) return;
const { data: org } = await supabase
- .from("organizations")
- .select("plan, subscription_status, subscription_ends_at")
- .eq("id", profile.organization_id)
+ .from('organizations')
+ .select('plan, subscription_status, subscription_ends_at')
+ .eq('id', profile.organization_id)
.single();
if (!org) return;
- const plan = PLANS[(org.plan as PlanId) ?? "starter"] ?? PLANS.starter;
+ const plan = PLANS[(org.plan as PlanId) ?? 'starter'] ?? PLANS.starter;
setSubscription({
- planId: org.plan ?? "starter",
- status: (org.subscription_status as string) ?? "active",
+ planId: org.plan ?? 'starter',
+ status: (org.subscription_status as string) ?? 'active',
currentPeriodEnd: (org.subscription_ends_at as string) ?? null,
cancelAtPeriodEnd: false,
priceAmount: plan.pricing?.monthly ?? null,
- interval: "month",
+ interval: 'month',
});
// Then: try to enrich with live Stripe data (cancel status etc.)
- const res = await fetch("/api/stripe/subscription");
+ const res = await fetch('/api/stripe/subscription');
if (res.ok) {
const stripeData = await res.json();
if (stripeData && !stripeData.error) {
@@ -105,11 +107,11 @@ export function BillingSection() {
const plan = PLANS[contextPlanId] ?? PLANS.starter;
setSubscription({
planId: contextPlanId,
- status: "active",
+ status: 'active',
currentPeriodEnd: null,
cancelAtPeriodEnd: false,
priceAmount: plan.pricing?.monthly ?? null,
- interval: "month",
+ interval: 'month',
});
} finally {
setLoading(false);
@@ -140,11 +142,11 @@ export function BillingSection() {
return (
<Card>
<CardHeader>
- <CardTitle>{t("billing")}</CardTitle>
- <CardDescription>{t("billingDescription")}</CardDescription>
+ <CardTitle>{t('billing')}</CardTitle>
+ <CardDescription>{t('billingDescription')}</CardDescription>
</CardHeader>
<CardContent>
- <p className="text-sm text-muted-foreground">{t("noSubscription")}</p>
+ <p className="text-sm text-muted-foreground">{t('noSubscription')}</p>
</CardContent>
</Card>
);
@@ -157,8 +159,8 @@ export function BillingSection() {
{/* Current Plan */}
<Card>
<CardHeader>
- <CardTitle>{t("currentPlan")}</CardTitle>
- <CardDescription>{t("billingDescription")}</CardDescription>
+ <CardTitle>{t('currentPlan')}</CardTitle>
+ <CardDescription>{t('billingDescription')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-3">
@@ -170,17 +172,18 @@ export function BillingSection() {
{subscription.priceAmount != null && (
<p className="text-sm text-muted-foreground">
- ${subscription.priceAmount}/{subscription.interval === "year" ? t("year") : t("month")}
+ ${subscription.priceAmount}/
+ {subscription.interval === 'year' ? t('year') : t('month')}
</p>
)}
{subscription.currentPeriodEnd && !subscription.cancelAtPeriodEnd && (
<p className="text-sm text-muted-foreground">
- {t("renewsOn", {
- date: new Date(subscription.currentPeriodEnd).toLocaleDateString("en-US", {
- year: "numeric",
- month: "long",
- day: "numeric",
+ {t('renewsOn', {
+ date: new Date(subscription.currentPeriodEnd).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
}),
})}
</p>
@@ -191,7 +194,7 @@ export function BillingSection() {
{/* Plan Switcher */}
<Card>
<CardHeader>
- <CardTitle>{t("changePlan")}</CardTitle>
+ <CardTitle>{t('changePlan')}</CardTitle>
</CardHeader>
<CardContent>
<PlanSwitcher
@@ -206,7 +209,7 @@ export function BillingSection() {
{/* Invoices */}
<Card>
<CardHeader>
- <CardTitle>{t("invoices")}</CardTitle>
+ <CardTitle>{t('invoices')}</CardTitle>
</CardHeader>
<CardContent>
<InvoiceList />
diff --git a/web/src/components/settings/invoice-list.tsx b/web/src/components/settings/invoice-list.tsx
index 1d5e20eae..983b432a2 100644
--- a/web/src/components/settings/invoice-list.tsx
+++ b/web/src/components/settings/invoice-list.tsx
@@ -1,8 +1,8 @@
-"use client";
+'use client';
-import { useEffect, useState } from "react";
-import { useTranslations } from "next-intl";
-import { Download } from "lucide-react";
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Download } from 'lucide-react';
import {
Table,
TableBody,
@@ -10,9 +10,9 @@ import {
TableHead,
TableHeader,
TableRow,
-} from "@/components/ui/table";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
+} from '@/components/ui/table';
+import { Badge } from '@/components/ui/badge';
+import { Skeleton } from '@/components/ui/skeleton';
interface Invoice {
id: string;
@@ -25,12 +25,12 @@ interface Invoice {
}
export function InvoiceList() {
- const t = useTranslations("settings");
+ const t = useTranslations('settings');
const [invoices, setInvoices] = useState<Invoice[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
- fetch("/api/stripe/invoices")
+ fetch('/api/stripe/invoices')
.then((r) => r.json())
.then((data) => {
if (Array.isArray(data)) setInvoices(data);
@@ -49,29 +49,27 @@ export function InvoiceList() {
}
if (invoices.length === 0) {
- return (
- <p className="text-sm text-muted-foreground">{t("noInvoices")}</p>
- );
+ return <p className="text-sm text-muted-foreground">{t('noInvoices')}</p>;
}
function formatCurrency(amount: number, currency: string) {
- return new Intl.NumberFormat("en-US", {
- style: "currency",
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
currency: currency.toUpperCase(),
}).format(amount);
}
function statusVariant(status: string | null) {
switch (status) {
- case "paid":
- return "default" as const;
- case "open":
- return "secondary" as const;
- case "uncollectible":
- case "void":
- return "destructive" as const;
+ case 'paid':
+ return 'default' as const;
+ case 'open':
+ return 'secondary' as const;
+ case 'uncollectible':
+ case 'void':
+ return 'destructive' as const;
default:
- return "outline" as const;
+ return 'outline' as const;
}
}
@@ -79,33 +77,29 @@ export function InvoiceList() {
<Table>
<TableHeader>
<TableRow>
- <TableHead>{t("invoiceNumber")}</TableHead>
- <TableHead>{t("invoiceDate")}</TableHead>
- <TableHead>{t("invoiceAmount")}</TableHead>
- <TableHead>{t("invoiceStatus")}</TableHead>
- <TableHead className="text-right">{t("invoiceDownload")}</TableHead>
+ <TableHead>{t('invoiceNumber')}</TableHead>
+ <TableHead>{t('invoiceDate')}</TableHead>
+ <TableHead>{t('invoiceAmount')}</TableHead>
+ <TableHead>{t('invoiceStatus')}</TableHead>
+ <TableHead className="text-right">{t('invoiceDownload')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{invoices.map((inv) => (
<TableRow key={inv.id}>
- <TableCell className="font-medium">
- {inv.number ?? "—"}
- </TableCell>
+ <TableCell className="font-medium">{inv.number ?? '—'}</TableCell>
<TableCell>
{inv.date
- ? new Date(inv.date).toLocaleDateString("en-US", {
- year: "numeric",
- month: "short",
- day: "numeric",
+ ? new Date(inv.date).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
})
- : "—"}
+ : '—'}
</TableCell>
<TableCell>{formatCurrency(inv.amount, inv.currency)}</TableCell>
<TableCell>
- <Badge variant={statusVariant(inv.status)}>
- {inv.status ?? "unknown"}
- </Badge>
+ <Badge variant={statusVariant(inv.status)}>{inv.status ?? 'unknown'}</Badge>
</TableCell>
<TableCell className="text-right">
{inv.pdfUrl ? (
@@ -118,7 +112,7 @@ export function InvoiceList() {
<Download className="h-4 w-4" />
</a>
) : (
- "—"
+ '—'
)}
</TableCell>
</TableRow>
diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsx
index abbb04b1c..c07ba948e 100644
--- a/web/src/components/settings/plan-switcher.tsx
+++ b/web/src/components/settings/plan-switcher.tsx
@@ -1,12 +1,12 @@
-"use client";
+'use client';
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { toast } from "sonner";
-import { Check, ArrowUp, ArrowDown, Mail } from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Check, ArrowUp, ArrowDown, Mail } from 'lucide-react';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
import {
Dialog,
DialogContent,
@@ -15,9 +15,9 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
-} from "@/components/ui/dialog";
-import { PLANS, SUBSCRIBABLE_PLANS, type PlanId } from "@/config/plans";
-import { ALL_SCRAPERS } from "@/config/prompt-options";
+} from '@/components/ui/dialog';
+import { PLANS, SUBSCRIBABLE_PLANS, type PlanId } from '@/config/plans';
+import { ALL_SCRAPERS } from '@/config/prompt-options';
interface SubscriptionData {
planId: string;
@@ -34,7 +34,7 @@ interface PlanSwitcherProps {
}
export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
- const t = useTranslations("settings");
+ const t = useTranslations('settings');
const [loading, setLoading] = useState(false);
const [cancelLoading, setCancelLoading] = useState(false);
const [changePlanOpen, setChangePlanOpen] = useState(false);
@@ -47,21 +47,21 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
if (!selectedPlan) return;
setLoading(true);
try {
- const res = await fetch("/api/stripe/subscription", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
+ const res = await fetch('/api/stripe/subscription', {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ newPlanId: selectedPlan }),
});
if (!res.ok) {
const err = await res.json();
- throw new Error(err.error || "Failed to change plan");
+ throw new Error(err.error || 'Failed to change plan');
}
const data = await res.json();
onUpdate(data);
- toast.success(t("planChanged"));
+ toast.success(t('planChanged'));
setChangePlanOpen(false);
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to change plan");
+ toast.error(err instanceof Error ? err.message : 'Failed to change plan');
} finally {
setLoading(false);
}
@@ -70,10 +70,10 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
async function handleCancel() {
setCancelLoading(true);
try {
- const res = await fetch("/api/stripe/subscription", { method: "DELETE" });
+ const res = await fetch('/api/stripe/subscription', { method: 'DELETE' });
if (!res.ok) {
const err = await res.json();
- throw new Error(err.error || "Failed to cancel");
+ throw new Error(err.error || 'Failed to cancel');
}
const data = await res.json();
onUpdate({
@@ -81,10 +81,10 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
cancelAtPeriodEnd: data.cancelAtPeriodEnd,
currentPeriodEnd: data.currentPeriodEnd,
});
- toast.success(t("subscriptionCanceled"));
+ toast.success(t('subscriptionCanceled'));
setCancelOpen(false);
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to cancel");
+ toast.error(err instanceof Error ? err.message : 'Failed to cancel');
} finally {
setCancelLoading(false);
}
@@ -93,14 +93,14 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
async function handleReactivate() {
setLoading(true);
try {
- const res = await fetch("/api/stripe/subscription", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
+ const res = await fetch('/api/stripe/subscription', {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reactivate: true }),
});
if (!res.ok) {
const err = await res.json();
- throw new Error(err.error || "Failed to reactivate");
+ throw new Error(err.error || 'Failed to reactivate');
}
const data = await res.json();
onUpdate({
@@ -109,9 +109,9 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
status: data.status,
currentPeriodEnd: data.currentPeriodEnd,
});
- toast.success(t("subscriptionReactivated"));
+ toast.success(t('subscriptionReactivated'));
} catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to reactivate");
+ toast.error(err instanceof Error ? err.message : 'Failed to reactivate');
} finally {
setLoading(false);
}
@@ -132,17 +132,14 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
const upgrade = isUpgrade(planId);
return (
- <Card
- key={planId}
- className={isCurrent ? "border-primary" : undefined}
- >
+ <Card key={planId} className={isCurrent ? 'border-primary' : undefined}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">{plan.name}</CardTitle>
{isCurrent && (
<Badge variant="default">
<Check className="mr-1 h-3 w-3" />
- {t("currentPlan")}
+ {t('currentPlan')}
</Badge>
)}
</div>
@@ -150,74 +147,83 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
</CardHeader>
<CardContent>
<div className="mb-4">
- <span className="text-2xl font-bold">
- ${plan.pricing?.monthly}
- </span>
- <span className="text-sm text-muted-foreground">
- /{t("month")}
- </span>
+ <span className="text-2xl font-bold">${plan.pricing?.monthly}</span>
+ <span className="text-sm text-muted-foreground">/{t('month')}</span>
</div>
<ul className="mb-4 space-y-1 text-sm text-muted-foreground">
- <li>{plan.limits.maxBrands === -1 ? t("unlimited") : plan.limits.maxBrands} {t("brands")}</li>
- <li>{plan.limits.maxPrompts === -1 ? t("unlimited") : plan.limits.maxPrompts} {t("prompts")}</li>
<li>
- {plan.limits.maxPlatforms} {t("platforms")}
+ {plan.limits.maxBrands === -1 ? t('unlimited') : plan.limits.maxBrands}{' '}
+ {t('brands')}
+ </li>
+ <li>
+ {plan.limits.maxPrompts === -1 ? t('unlimited') : plan.limits.maxPrompts}{' '}
+ {t('prompts')}
+ </li>
+ <li>
+ {plan.limits.maxPlatforms} {t('platforms')}
{plan.limits.allowedScrapers && plan.limits.allowedScrapers.length > 0 && (
<span className="text-xs text-muted-foreground/70">
- {" "}({plan.limits.allowedScrapers.map((id) => {
- const s = ALL_SCRAPERS.find((s) => s.id === id);
- return s ? s.label.replace(/\s*\(Web\)/i, "") : id;
- }).join(" & ")})
+ {' '}
+ (
+ {plan.limits.allowedScrapers
+ .map((id) => {
+ const s = ALL_SCRAPERS.find((s) => s.id === id);
+ return s ? s.label.replace(/\s*\(Web\)/i, '') : id;
+ })
+ .join(' & ')}
+ )
</span>
)}
</li>
- <li>{plan.limits.maxTeamMembers === -1 ? t("unlimited") : plan.limits.maxTeamMembers} {t("teamMembers")}</li>
+ <li>
+ {plan.limits.maxTeamMembers === -1
+ ? t('unlimited')
+ : plan.limits.maxTeamMembers}{' '}
+ {t('teamMembers')}
+ </li>
</ul>
{!isCurrent && (
- <Dialog open={changePlanOpen && selectedPlan === planId} onOpenChange={(open) => {
- setChangePlanOpen(open);
- if (open) setSelectedPlan(planId);
- }}>
+ <Dialog
+ open={changePlanOpen && selectedPlan === planId}
+ onOpenChange={(open) => {
+ setChangePlanOpen(open);
+ if (open) setSelectedPlan(planId);
+ }}
+ >
<DialogTrigger
render={
- <Button
- className="w-full"
- variant={upgrade ? "default" : "outline"}
- />
+ <Button className="w-full" variant={upgrade ? 'default' : 'outline'} />
}
>
{upgrade ? (
<>
<ArrowUp className="mr-1 h-4 w-4" />
- {t("upgradeTo", { plan: plan.name })}
+ {t('upgradeTo', { plan: plan.name })}
</>
) : (
<>
<ArrowDown className="mr-1 h-4 w-4" />
- {t("downgradeTo", { plan: plan.name })}
+ {t('downgradeTo', { plan: plan.name })}
</>
)}
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
- {t("changePlanConfirmTitle", { plan: plan.name })}
+ {t('changePlanConfirmTitle', { plan: plan.name })}
</DialogTitle>
<DialogDescription>
- {t("changePlanConfirmDescription", {
+ {t('changePlanConfirmDescription', {
plan: plan.name,
price: String(plan.pricing?.monthly),
})}
</DialogDescription>
</DialogHeader>
<DialogFooter>
- <Button
- onClick={handleChangePlan}
- disabled={loading}
- >
- {loading ? t("processing") : t("changePlanConfirm")}
+ <Button onClick={handleChangePlan} disabled={loading}>
+ {loading ? t('processing') : t('changePlanConfirm')}
</Button>
</DialogFooter>
</DialogContent>
@@ -232,17 +238,15 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
{/* Enterprise / Custom Plan CTA */}
<div className="flex items-center justify-between gap-4 rounded-lg border bg-muted/30 p-5">
<div>
- <p className="text-sm font-medium">{t("needCustomPlan")}</p>
- <p className="text-xs text-muted-foreground">
- {t("customPlanDescription")}
- </p>
+ <p className="text-sm font-medium">{t('needCustomPlan')}</p>
+ <p className="text-xs text-muted-foreground">{t('customPlanDescription')}</p>
</div>
<a
href="mailto:[email protected]"
className="inline-flex shrink-0 items-center justify-center rounded-md border bg-background px-5 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground"
>
<Mail className="mr-2 h-4 w-4" />
- {t("contactUs")}
+ {t('contactUs')}
</a>
</div>
@@ -250,48 +254,37 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
{subscription.cancelAtPeriodEnd ? (
<div className="flex items-center justify-between rounded-lg border border-destructive/20 bg-destructive/5 p-4">
<div>
- <p className="text-sm font-medium">{t("cancelsOn", {
- date: subscription.currentPeriodEnd
- ? new Date(subscription.currentPeriodEnd).toLocaleDateString("en-US", {
- year: "numeric",
- month: "long",
- day: "numeric",
- })
- : "",
- })}</p>
+ <p className="text-sm font-medium">
+ {t('cancelsOn', {
+ date: subscription.currentPeriodEnd
+ ? new Date(subscription.currentPeriodEnd).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ })
+ : '',
+ })}
+ </p>
</div>
- <Button
- variant="outline"
- size="sm"
- onClick={handleReactivate}
- disabled={loading}
- >
- {t("reactivate")}
+ <Button variant="outline" size="sm" onClick={handleReactivate} disabled={loading}>
+ {t('reactivate')}
</Button>
</div>
) : (
<Dialog open={cancelOpen} onOpenChange={setCancelOpen}>
<DialogTrigger
- render={
- <Button variant="ghost" className="text-destructive hover:text-destructive" />
- }
+ render={<Button variant="ghost" className="text-destructive hover:text-destructive" />}
>
- {t("cancelSubscription")}
+ {t('cancelSubscription')}
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
- <DialogTitle>{t("cancelConfirmTitle")}</DialogTitle>
- <DialogDescription>
- {t("cancelConfirmDescription")}
- </DialogDescription>
+ <DialogTitle>{t('cancelConfirmTitle')}</DialogTitle>
+ <DialogDescription>{t('cancelConfirmDescription')}</DialogDescription>
</DialogHeader>
<DialogFooter>
- <Button
- variant="destructive"
- onClick={handleCancel}
- disabled={cancelLoading}
- >
- {cancelLoading ? t("processing") : t("cancelConfirm")}
+ <Button variant="destructive" onClick={handleCancel} disabled={cancelLoading}>
+ {cancelLoading ? t('processing') : t('cancelConfirm')}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/web/src/components/settings/team-section.tsx b/web/src/components/settings/team-section.tsx
index 2af70b1cb..895e49a48 100644
--- a/web/src/components/settings/team-section.tsx
+++ b/web/src/components/settings/team-section.tsx
@@ -1,25 +1,19 @@
-"use client";
+'use client';
-import { useCallback, useEffect, useState } from "react";
-import { useTranslations } from "next-intl";
-import { toast } from "sonner";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
-} from "@/components/ui/select";
+} from '@/components/ui/select';
import {
Dialog,
DialogClose,
@@ -29,10 +23,10 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
-} from "@/components/ui/dialog";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
+} from '@/components/ui/dialog';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { Badge } from '@/components/ui/badge';
+import { Skeleton } from '@/components/ui/skeleton';
import {
listMembers,
listInvitations,
@@ -46,7 +40,7 @@ import {
type TeamInvitation,
type TeamInfo,
type TeamRole,
-} from "@/lib/actions/team";
+} from '@/lib/actions/team';
import {
ArrowUpRight,
Copy,
@@ -57,20 +51,20 @@ import {
RefreshCw,
Trash2,
UserPlus,
-} from "lucide-react";
-import { useRouter } from "@/i18n/navigation";
+} from 'lucide-react';
+import { useRouter } from '@/i18n/navigation';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+} from '@/components/ui/dropdown-menu';
const ROLE_OPTIONS: { value: TeamRole; label: string }[] = [
- { value: "admin", label: "Admin" },
- { value: "manager", label: "Manager" },
- { value: "analyst", label: "Analyst" },
- { value: "agency_partner", label: "Agency Partner" },
+ { value: 'admin', label: 'Admin' },
+ { value: 'manager', label: 'Manager' },
+ { value: 'analyst', label: 'Analyst' },
+ { value: 'agency_partner', label: 'Agency Partner' },
];
function roleLabel(role: TeamRole): string {
@@ -81,14 +75,14 @@ function initials(name: string | null, email: string): string {
const source = name?.trim() || email;
return source
.split(/\s+/)
- .map((p) => p[0] ?? "")
+ .map((p) => p[0] ?? '')
.slice(0, 2)
- .join("")
+ .join('')
.toUpperCase();
}
export function TeamSection() {
- const t = useTranslations("settings");
+ const t = useTranslations('settings');
const router = useRouter();
const [members, setMembers] = useState<TeamMember[]>([]);
const [invitations, setInvitations] = useState<TeamInvitation[]>([]);
@@ -98,20 +92,14 @@ export function TeamSection() {
const loadData = useCallback(async () => {
try {
- const [m, i, inf] = await Promise.all([
- listMembers(),
- listInvitations(),
- getTeamInfo(),
- ]);
+ const [m, i, inf] = await Promise.all([listMembers(), listInvitations(), getTeamInfo()]);
setMembers(m);
setInvitations(i);
setInfo(inf);
const me = m.find((mem) => mem.isCurrentUser);
setCurrentRole(me?.role ?? null);
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to load team",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to load team');
} finally {
setIsLoading(false);
}
@@ -121,10 +109,10 @@ export function TeamSection() {
loadData();
}, [loadData]);
- const isAdmin = currentRole === "admin";
+ const isAdmin = currentRole === 'admin';
const seatsLabel = info
? info.maxTeamMembers === -1
- ? `${info.seatsUsed} seat${info.seatsUsed === 1 ? "" : "s"} used`
+ ? `${info.seatsUsed} seat${info.seatsUsed === 1 ? '' : 's'} used`
: `${info.seatsUsed} of ${info.maxTeamMembers} seats used`
: null;
@@ -133,12 +121,10 @@ export function TeamSection() {
<Card>
<CardHeader className="flex flex-row items-start justify-between space-y-0">
<div>
- <CardTitle>{t("team")}</CardTitle>
+ <CardTitle>{t('team')}</CardTitle>
<CardDescription>
Manage team members and their access.
- {seatsLabel && (
- <span className="ml-1 text-foreground">· {seatsLabel}</span>
- )}
+ {seatsLabel && <span className="ml-1 text-foreground">· {seatsLabel}</span>}
</CardDescription>
</div>
{isAdmin && info && (
@@ -176,15 +162,14 @@ export function TeamSection() {
Seat limit reached
</p>
<p className="text-amber-800/80 dark:text-amber-300/80">
- Your {info.planName} plan includes {info.maxTeamMembers}{" "}
- seat{info.maxTeamMembers === 1 ? "" : "s"}. Upgrade to
- invite more teammates.
+ Your {info.planName} plan includes {info.maxTeamMembers} seat
+ {info.maxTeamMembers === 1 ? '' : 's'}. Upgrade to invite more teammates.
</p>
</div>
<Button
size="sm"
variant="outline"
- onClick={() => router.push("/dashboard/settings?tab=billing")}
+ onClick={() => router.push('/dashboard/settings?tab=billing')}
>
Upgrade
<ArrowUpRight className="ml-1 h-3.5 w-3.5" />
@@ -200,9 +185,7 @@ export function TeamSection() {
<Card>
<CardHeader>
<CardTitle>Pending invitations</CardTitle>
- <CardDescription>
- Invitations that haven&apos;t been accepted yet.
- </CardDescription>
+ <CardDescription>Invitations that haven&apos;t been accepted yet.</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-1">
@@ -242,12 +225,10 @@ function MemberRow({
setPendingRole(role);
try {
await updateMemberRole(member.userId, role);
- toast.success("Role updated");
+ toast.success('Role updated');
onChanged();
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to update role",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to update role');
} finally {
setPendingRole(null);
}
@@ -257,13 +238,11 @@ function MemberRow({
setRemoving(true);
try {
await removeMember(member.userId);
- toast.success("Member removed");
+ toast.success('Member removed');
setRemoveDialogOpen(false);
onChanged();
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to remove member",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to remove member');
} finally {
setRemoving(false);
}
@@ -277,9 +256,7 @@ function MemberRow({
</Avatar>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- <span className="truncate text-sm font-medium">
- {member.fullName || member.email}
- </span>
+ <span className="truncate text-sm font-medium">{member.fullName || member.email}</span>
{member.isCurrentUser && (
<Badge variant="secondary" className="text-xs">
You
@@ -287,9 +264,7 @@ function MemberRow({
)}
</div>
{member.fullName && (
- <p className="truncate text-xs text-muted-foreground">
- {member.email}
- </p>
+ <p className="truncate text-xs text-muted-foreground">{member.email}</p>
)}
</div>
@@ -300,11 +275,7 @@ function MemberRow({
disabled={pendingRole !== null}
>
<SelectTrigger size="sm" className="w-36">
- {pendingRole ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <SelectValue />
- )}
+ {pendingRole ? <Loader2 className="h-3 w-3 animate-spin" /> : <SelectValue />}
</SelectTrigger>
<SelectContent>
{ROLE_OPTIONS.map((opt) => (
@@ -331,26 +302,20 @@ function MemberRow({
<DialogHeader>
<DialogTitle>Remove team member?</DialogTitle>
<DialogDescription>
- {member.fullName || member.email} will lose access to this
- organization. This cannot be undone.
+ {member.fullName || member.email} will lose access to this organization. This cannot
+ be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
- <DialogClose render={<Button variant="outline" />}>
- Cancel
- </DialogClose>
- <Button
- variant="destructive"
- onClick={handleRemove}
- disabled={removing}
- >
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
+ <Button variant="destructive" onClick={handleRemove} disabled={removing}>
{removing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Removing...
</>
) : (
- "Remove member"
+ 'Remove member'
)}
</Button>
</DialogFooter>
@@ -370,34 +335,30 @@ function InvitationRow({
isAdmin: boolean;
onChanged: () => void;
}) {
- const [busy, setBusy] = useState<"revoke" | "resend" | null>(null);
+ const [busy, setBusy] = useState<'revoke' | 'resend' | null>(null);
async function handleRevoke() {
- setBusy("revoke");
+ setBusy('revoke');
try {
await revokeInvitation(invitation.id);
- toast.success("Invitation revoked");
+ toast.success('Invitation revoked');
onChanged();
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to revoke invitation",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to revoke invitation');
} finally {
setBusy(null);
}
}
async function handleResend() {
- setBusy("resend");
+ setBusy('resend');
try {
const { inviteLink } = await resendInvitation(invitation.id);
await navigator.clipboard.writeText(inviteLink).catch(() => {});
- toast.success("Invitation resent (link copied)");
+ toast.success('Invitation resent (link copied)');
onChanged();
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to resend invitation",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to resend invitation');
} finally {
setBusy(null);
}
@@ -413,9 +374,7 @@ function InvitationRow({
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{invitation.email}</p>
<p className="text-xs text-muted-foreground">
- {expired
- ? "Expired"
- : `Expires ${new Date(invitation.expiresAt).toLocaleDateString()}`}
+ {expired ? 'Expired' : `Expires ${new Date(invitation.expiresAt).toLocaleDateString()}`}
</p>
</div>
<Badge variant="outline">{roleLabel(invitation.role)}</Badge>
@@ -451,40 +410,32 @@ function InvitationRow({
);
}
-function InviteDialog({
- canInvite,
- onInvited,
-}: {
- canInvite: boolean;
- onInvited: () => void;
-}) {
+function InviteDialog({ canInvite, onInvited }: { canInvite: boolean; onInvited: () => void }) {
const [open, setOpen] = useState(false);
- const [email, setEmail] = useState("");
- const [role, setRole] = useState<TeamRole>("analyst");
+ const [email, setEmail] = useState('');
+ const [role, setRole] = useState<TeamRole>('analyst');
const [submitting, setSubmitting] = useState(false);
const [inviteLink, setInviteLink] = useState<string | null>(null);
function reset() {
- setEmail("");
- setRole("analyst");
+ setEmail('');
+ setRole('analyst');
setInviteLink(null);
}
async function handleSubmit() {
if (!email.trim()) {
- toast.error("Email is required");
+ toast.error('Email is required');
return;
}
setSubmitting(true);
try {
const { inviteLink: link } = await inviteMember(email.trim(), role);
setInviteLink(link);
- toast.success("Invitation sent");
+ toast.success('Invitation sent');
onInvited();
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to send invitation",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to send invitation');
} finally {
setSubmitting(false);
}
@@ -493,7 +444,7 @@ function InviteDialog({
async function copyLink() {
if (!inviteLink) return;
await navigator.clipboard.writeText(inviteLink).catch(() => {});
- toast.success("Link copied");
+ toast.success('Link copied');
}
return (
@@ -572,9 +523,7 @@ function InviteDialog({
<DialogClose render={<Button />}>Done</DialogClose>
) : (
<>
- <DialogClose render={<Button variant="outline" />}>
- Cancel
- </DialogClose>
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
<Button onClick={handleSubmit} disabled={submitting}>
{submitting ? (
<>
@@ -582,7 +531,7 @@ function InviteDialog({
Sending...
</>
) : (
- "Send invitation"
+ 'Send invitation'
)}
</Button>
</>
diff --git a/web/src/components/settings/theme-switch.tsx b/web/src/components/settings/theme-switch.tsx
index 5f06ab9b4..c580c0ef8 100644
--- a/web/src/components/settings/theme-switch.tsx
+++ b/web/src/components/settings/theme-switch.tsx
@@ -1,10 +1,10 @@
-"use client";
+'use client';
-import { useSyncExternalStore, useCallback } from "react";
-import { useTheme } from "next-themes";
-import { Button } from "@/components/ui/button";
-import { Moon, Sun } from "lucide-react";
-import { cn } from "@/lib/utils";
+import { useSyncExternalStore, useCallback } from 'react';
+import { useTheme } from 'next-themes';
+import { Button } from '@/components/ui/button';
+import { Moon, Sun } from 'lucide-react';
+import { cn } from '@/lib/utils';
const emptySubscribe = () => () => {};
@@ -22,9 +22,7 @@ export function ThemeSwitch() {
<div className="flex-1 rounded-md bg-muted/50 py-2 text-center text-sm text-muted-foreground">
Light
</div>
- <div className="flex-1 rounded-md py-2 text-center text-sm text-muted-foreground">
- Dark
- </div>
+ <div className="flex-1 rounded-md py-2 text-center text-sm text-muted-foreground">Dark</div>
</div>
);
}
@@ -35,10 +33,11 @@ export function ThemeSwitch() {
variant="ghost"
size="sm"
className={cn(
- "flex-1 gap-2 transition-colors",
- theme === "light" && "bg-background text-foreground shadow-sm dark:border-input dark:bg-input/30"
+ 'flex-1 gap-2 transition-colors',
+ theme === 'light' &&
+ 'bg-background text-foreground shadow-sm dark:border-input dark:bg-input/30',
)}
- onClick={() => setTheme("light")}
+ onClick={() => setTheme('light')}
>
<Sun className="h-4 w-4" />
Light
@@ -47,10 +46,11 @@ export function ThemeSwitch() {
variant="ghost"
size="sm"
className={cn(
- "flex-1 gap-2 transition-colors",
- theme === "dark" && "bg-background text-foreground shadow-sm dark:border-input dark:bg-input/30"
+ 'flex-1 gap-2 transition-colors',
+ theme === 'dark' &&
+ 'bg-background text-foreground shadow-sm dark:border-input dark:bg-input/30',
)}
- onClick={() => setTheme("dark")}
+ onClick={() => setTheme('dark')}
>
<Moon className="h-4 w-4" />
Dark
diff --git a/web/src/components/team/accept-invitation-card.tsx b/web/src/components/team/accept-invitation-card.tsx
index 80154f052..36a85012b 100644
--- a/web/src/components/team/accept-invitation-card.tsx
+++ b/web/src/components/team/accept-invitation-card.tsx
@@ -1,12 +1,12 @@
-"use client";
+'use client';
-import { useState } from "react";
-import { useRouter } from "@/i18n/navigation";
-import { createClient } from "@/lib/supabase/client";
-import { acceptInvitation, type TeamRole } from "@/lib/actions/team";
-import { Button } from "@/components/ui/button";
-import { toast } from "sonner";
-import { Loader2, Users } from "lucide-react";
+import { useState } from 'react';
+import { useRouter } from '@/i18n/navigation';
+import { createClient } from '@/lib/supabase/client';
+import { acceptInvitation, type TeamRole } from '@/lib/actions/team';
+import { Button } from '@/components/ui/button';
+import { toast } from 'sonner';
+import { Loader2, Users } from 'lucide-react';
interface Props {
token: string;
@@ -19,14 +19,14 @@ interface Props {
function roleLabel(role: TeamRole): string {
switch (role) {
- case "admin":
- return "Admin";
- case "manager":
- return "Manager";
- case "analyst":
- return "Analyst";
- case "agency_partner":
- return "Agency Partner";
+ case 'admin':
+ return 'Admin';
+ case 'manager':
+ return 'Manager';
+ case 'analyst':
+ return 'Analyst';
+ case 'agency_partner':
+ return 'Agency Partner';
}
}
@@ -47,12 +47,10 @@ export function AcceptInvitationCard({
try {
await acceptInvitation(token);
toast.success(`Welcome to ${organizationName}!`);
- router.push("/dashboard");
+ router.push('/dashboard');
router.refresh();
} catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to accept invitation",
- );
+ toast.error(error instanceof Error ? error.message : 'Failed to accept invitation');
setIsAccepting(false);
}
}
@@ -75,11 +73,9 @@ export function AcceptInvitationCard({
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
<Users className="h-6 w-6 text-primary" />
</div>
- <h1 className="text-xl font-semibold tracking-tight">
- Join {organizationName}
- </h1>
+ <h1 className="text-xl font-semibold tracking-tight">Join {organizationName}</h1>
<p className="mt-2 text-sm text-muted-foreground">
- You&apos;ve been invited to join as{" "}
+ You&apos;ve been invited to join as{' '}
<span className="font-medium text-foreground">{roleLabel(role)}</span>
</p>
</div>
@@ -98,31 +94,22 @@ export function AcceptInvitationCard({
{!emailMatches ? (
<div className="mt-6 space-y-3">
<p className="text-sm text-destructive">
- This invitation was sent to{" "}
- <span className="font-medium">{email}</span>, but you&apos;re signed
- in as {currentUserEmail}. Please switch accounts to continue.
+ This invitation was sent to <span className="font-medium">{email}</span>, but
+ you&apos;re signed in as {currentUserEmail}. Please switch accounts to continue.
</p>
- <Button
- onClick={handleSwitchAccount}
- disabled={isSwitching}
- className="w-full"
- >
+ <Button onClick={handleSwitchAccount} disabled={isSwitching} className="w-full">
{isSwitching ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Switching...
</>
) : (
- "Sign out and use correct account"
+ 'Sign out and use correct account'
)}
</Button>
</div>
) : (
- <Button
- onClick={handleAccept}
- disabled={isAccepting}
- className="mt-6 w-full"
- >
+ <Button onClick={handleAccept} disabled={isAccepting} className="mt-6 w-full">
{isAccepting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
diff --git a/web/src/components/ui/avatar.tsx b/web/src/components/ui/avatar.tsx
index e4fed865c..860fa7cde 100644
--- a/web/src/components/ui/avatar.tsx
+++ b/web/src/components/ui/avatar.tsx
@@ -1,109 +1,93 @@
-"use client"
+'use client';
-import * as React from "react"
-import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
+import * as React from 'react';
+import { Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
function Avatar({
className,
- size = "default",
+ size = 'default',
...props
}: AvatarPrimitive.Root.Props & {
- size?: "default" | "sm" | "lg"
+ size?: 'default' | 'sm' | 'lg';
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
- "group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
- className
+ 'group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten',
+ className,
)}
{...props}
/>
- )
+ );
}
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
- className={cn(
- "aspect-square size-full rounded-full object-cover",
- className
- )}
+ className={cn('aspect-square size-full rounded-full object-cover', className)}
{...props}
/>
- )
+ );
}
-function AvatarFallback({
- className,
- ...props
-}: AvatarPrimitive.Fallback.Props) {
+function AvatarFallback({ className, ...props }: AvatarPrimitive.Fallback.Props) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
- "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
- className
+ 'flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs',
+ className,
)}
{...props}
/>
- )
+ );
}
-function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
+function AvatarBadge({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="avatar-badge"
className={cn(
- "absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
- "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
- "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
- "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
- className
+ 'absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none',
+ 'group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden',
+ 'group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2',
+ 'group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2',
+ className,
)}
{...props}
/>
- )
+ );
}
-function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
+function AvatarGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="avatar-group"
className={cn(
- "group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
- className
+ 'group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background',
+ className,
)}
{...props}
/>
- )
+ );
}
-function AvatarGroupCount({
- className,
- ...props
-}: React.ComponentProps<"div">) {
+function AvatarGroupCount({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="avatar-group-count"
className={cn(
- "relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
- className
+ 'relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3',
+ className,
)}
{...props}
/>
- )
+ );
}
-export {
- Avatar,
- AvatarImage,
- AvatarFallback,
- AvatarGroup,
- AvatarGroupCount,
- AvatarBadge,
-}
+export { Avatar, AvatarImage, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarBadge };
diff --git a/web/src/components/ui/badge.tsx b/web/src/components/ui/badge.tsx
index b20959dd7..e0bef5296 100644
--- a/web/src/components/ui/badge.tsx
+++ b/web/src/components/ui/badge.tsx
@@ -1,52 +1,49 @@
-import { mergeProps } from "@base-ui/react/merge-props"
-import { useRender } from "@base-ui/react/use-render"
-import { cva, type VariantProps } from "class-variance-authority"
+import { mergeProps } from '@base-ui/react/merge-props';
+import { useRender } from '@base-ui/react/use-render';
+import { cva, type VariantProps } from 'class-variance-authority';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
const badgeVariants = cva(
- "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
+ 'group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!',
{
variants: {
variant: {
- default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
- secondary:
- "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
+ default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80',
+ secondary: 'bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80',
destructive:
- "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
- outline:
- "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
- ghost:
- "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
- link: "text-primary underline-offset-4 hover:underline",
+ 'bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20',
+ outline: 'border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground',
+ ghost: 'hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50',
+ link: 'text-primary underline-offset-4 hover:underline',
},
},
defaultVariants: {
- variant: "default",
+ variant: 'default',
},
- }
-)
+ },
+);
function Badge({
className,
- variant = "default",
+ variant = 'default',
render,
...props
-}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
+}: useRender.ComponentProps<'span'> & VariantProps<typeof badgeVariants>) {
return useRender({
- defaultTagName: "span",
- props: mergeProps<"span">(
+ defaultTagName: 'span',
+ props: mergeProps<'span'>(
{
className: cn(badgeVariants({ variant }), className),
},
- props
+ props,
),
render,
state: {
- slot: "badge",
+ slot: 'badge',
variant,
},
- })
+ });
}
-export { Badge, badgeVariants }
+export { Badge, badgeVariants };
diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsx
index 712033606..3bd32dd6e 100644
--- a/web/src/components/ui/button.tsx
+++ b/web/src/components/ui/button.tsx
@@ -1,51 +1,51 @@
-"use client"
+'use client';
-import { Button as ButtonPrimitive } from "@base-ui/react/button"
-import { cva, type VariantProps } from "class-variance-authority"
+import { Button as ButtonPrimitive } from '@base-ui/react/button';
+import { cva, type VariantProps } from 'class-variance-authority';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
const buttonVariants = cva(
"group/button inline-flex shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
- default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
+ default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80',
outline:
- "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
+ 'border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50',
secondary:
- "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
+ 'bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground',
ghost:
- "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
+ 'hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50',
destructive:
- "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
- link: "text-primary underline-offset-4 hover:underline",
+ 'bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40',
+ link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default:
- "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ 'h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",
- icon: "size-8",
- "icon-xs":
+ lg: 'h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3',
+ icon: 'size-8',
+ 'icon-xs':
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
- "icon-sm":
- "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
- "icon-lg": "size-9",
+ 'icon-sm':
+ 'size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg',
+ 'icon-lg': 'size-9',
},
},
defaultVariants: {
- variant: "default",
- size: "default",
+ variant: 'default',
+ size: 'default',
},
- }
-)
+ },
+);
function Button({
className,
- variant = "default",
- size = "default",
+ variant = 'default',
+ size = 'default',
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
return (
@@ -54,7 +54,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
- )
+ );
}
-export { Button, buttonVariants }
+export { Button, buttonVariants };
diff --git a/web/src/components/ui/card.tsx b/web/src/components/ui/card.tsx
index 9bd5a2544..499504ab0 100644
--- a/web/src/components/ui/card.tsx
+++ b/web/src/components/ui/card.tsx
@@ -1,103 +1,92 @@
-import * as React from "react"
+import * as React from 'react';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
function Card({
className,
- size = "default",
+ size = 'default',
...props
-}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
+}: React.ComponentProps<'div'> & { size?: 'default' | 'sm' }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
- "group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
- className
+ 'group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl',
+ className,
)}
{...props}
/>
- )
+ );
}
-function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
+function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-header"
className={cn(
- "group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
- className
+ 'group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3',
+ className,
)}
{...props}
/>
- )
+ );
}
-function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
+function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
className={cn(
- "text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
- className
+ 'text-base leading-snug font-medium group-data-[size=sm]/card:text-sm',
+ className,
)}
{...props}
/>
- )
+ );
}
-function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
+function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-description"
- className={cn("text-sm text-muted-foreground", className)}
+ className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
- )
+ );
}
-function CardAction({ className, ...props }: React.ComponentProps<"div">) {
+function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-action"
- className={cn(
- "col-start-2 row-span-2 row-start-1 self-start justify-self-end",
- className
- )}
+ className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
{...props}
/>
- )
+ );
}
-function CardContent({ className, ...props }: React.ComponentProps<"div">) {
+function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-content"
- className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
+ className={cn('px-4 group-data-[size=sm]/card:px-3', className)}
{...props}
/>
- )
+ );
}
-function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
+function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-footer"
className={cn(
- "flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
- className
+ 'flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3',
+ className,
)}
{...props}
/>
- )
+ );
}
-export {
- Card,
- CardHeader,
- CardFooter,
- CardTitle,
- CardAction,
- CardDescription,
- CardContent,
-}
+export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
diff --git a/web/src/components/ui/checkbox.tsx b/web/src/components/ui/checkbox.tsx
index 0f5cfae90..bc301b60a 100644
--- a/web/src/components/ui/checkbox.tsx
+++ b/web/src/components/ui/checkbox.tsx
@@ -1,20 +1,17 @@
-"use client"
+'use client';
-import * as React from "react"
-import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
-import { CheckIcon } from "lucide-react"
-import { cn } from "@/lib/utils"
+import * as React from 'react';
+import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
+import { CheckIcon } from 'lucide-react';
+import { cn } from '@/lib/utils';
-function Checkbox({
- className,
- ...props
-}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
+function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
- "peer h-4 w-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=checked]:text-primary-foreground",
- className
+ 'peer h-4 w-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=checked]:text-primary-foreground',
+ className,
)}
{...props}
>
@@ -22,7 +19,7 @@ function Checkbox({
<CheckIcon className="h-3.5 w-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
- )
+ );
}
-export { Checkbox }
+export { Checkbox };
diff --git a/web/src/components/ui/code-block.tsx b/web/src/components/ui/code-block.tsx
index 4907f8db2..1a5da60a1 100644
--- a/web/src/components/ui/code-block.tsx
+++ b/web/src/components/ui/code-block.tsx
@@ -1,93 +1,79 @@
-"use client"
+'use client';
-import { cn } from "@/lib/utils"
-import React, { useEffect, useState } from "react"
-import { codeToHtml } from "shiki"
+import { cn } from '@/lib/utils';
+import React, { useEffect, useState } from 'react';
+import { codeToHtml } from 'shiki';
export type CodeBlockProps = {
- children?: React.ReactNode
- className?: string
-} & React.HTMLProps<HTMLDivElement>
+ children?: React.ReactNode;
+ className?: string;
+} & React.HTMLProps<HTMLDivElement>;
function CodeBlock({ children, className, ...props }: CodeBlockProps) {
return (
<div
className={cn(
- "not-prose flex w-full flex-col overflow-clip border",
- "border-border bg-card text-card-foreground rounded-xl",
- className
+ 'not-prose flex w-full flex-col overflow-clip border',
+ 'border-border bg-card text-card-foreground rounded-xl',
+ className,
)}
{...props}
>
{children}
</div>
- )
+ );
}
export type CodeBlockCodeProps = {
- code: string
- language?: string
- theme?: string
- className?: string
-} & React.HTMLProps<HTMLDivElement>
+ code: string;
+ language?: string;
+ theme?: string;
+ className?: string;
+} & React.HTMLProps<HTMLDivElement>;
function CodeBlockCode({
code,
- language = "tsx",
- theme = "github-light",
+ language = 'tsx',
+ theme = 'github-light',
className,
...props
}: CodeBlockCodeProps) {
- const [highlightedHtml, setHighlightedHtml] = useState<string | null>(null)
+ const [highlightedHtml, setHighlightedHtml] = useState<string | null>(null);
useEffect(() => {
async function highlight() {
if (!code) {
- setHighlightedHtml("<pre><code></code></pre>")
- return
+ setHighlightedHtml('<pre><code></code></pre>');
+ return;
}
- const html = await codeToHtml(code, { lang: language, theme })
- setHighlightedHtml(html)
+ const html = await codeToHtml(code, { lang: language, theme });
+ setHighlightedHtml(html);
}
- highlight()
- }, [code, language, theme])
+ highlight();
+ }, [code, language, theme]);
- const classNames = cn(
- "w-full overflow-x-auto text-[13px] [&>pre]:px-4 [&>pre]:py-4",
- className
- )
+ const classNames = cn('w-full overflow-x-auto text-[13px] [&>pre]:px-4 [&>pre]:py-4', className);
return highlightedHtml ? (
- <div
- className={classNames}
- dangerouslySetInnerHTML={{ __html: highlightedHtml }}
- {...props}
- />
+ <div className={classNames} dangerouslySetInnerHTML={{ __html: highlightedHtml }} {...props} />
) : (
<div className={classNames} {...props}>
<pre>
<code>{code}</code>
</pre>
</div>
- )
+ );
}
-export type CodeBlockGroupProps = React.HTMLAttributes<HTMLDivElement>
+export type CodeBlockGroupProps = React.HTMLAttributes<HTMLDivElement>;
-function CodeBlockGroup({
- children,
- className,
- ...props
-}: CodeBlockGroupProps) {
+function CodeBlockGroup({ children, className, ...props }: CodeBlockGroupProps) {
return (
- <div
- className={cn("flex items-center justify-between", className)}
- {...props}
- >
+ <div className={cn('flex items-center justify-between', className)} {...props}>
{children}
</div>
- )
+ );
}
-export { CodeBlockGroup, CodeBlockCode, CodeBlock }
+export { CodeBlockGroup, CodeBlockCode, CodeBlock };
diff --git a/web/src/components/ui/combobox.tsx b/web/src/components/ui/combobox.tsx
index 4bfd24b89..7d3f9c12c 100644
--- a/web/src/components/ui/combobox.tsx
+++ b/web/src/components/ui/combobox.tsx
@@ -1,10 +1,10 @@
-"use client";
+'use client';
-import * as React from "react";
-import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";
+import * as React from 'react';
+import { Combobox as ComboboxPrimitive } from '@base-ui/react/combobox';
-import { cn } from "@/lib/utils";
-import { ChevronDownIcon, CheckIcon } from "lucide-react";
+import { cn } from '@/lib/utils';
+import { ChevronDownIcon, CheckIcon } from 'lucide-react';
// Thin styled wrapper around `@base-ui/react/combobox`, matching the look /
// data-slot conventions of `select.tsx` so callers can swap between Select
@@ -23,41 +23,36 @@ function ComboboxValue(props: ComboboxPrimitive.Value.Props) {
function ComboboxTrigger({
className,
- size = "default",
+ size = 'default',
children,
...props
}: ComboboxPrimitive.Trigger.Props & {
- size?: "sm" | "default";
+ size?: 'sm' | 'default';
}) {
return (
<ComboboxPrimitive.Trigger
data-slot="combobox-trigger"
data-size={size}
className={cn(
- "flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] dark:bg-input/30 dark:hover:bg-input/50",
+ 'flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] dark:bg-input/30 dark:hover:bg-input/50',
className,
)}
{...props}
>
{children}
<ComboboxPrimitive.Icon
- render={
- <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
- }
+ render={<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />}
/>
</ComboboxPrimitive.Trigger>
);
}
-function ComboboxInput({
- className,
- ...props
-}: ComboboxPrimitive.Input.Props) {
+function ComboboxInput({ className, ...props }: ComboboxPrimitive.Input.Props) {
return (
<ComboboxPrimitive.Input
data-slot="combobox-input"
className={cn(
- "h-9 w-full border-b border-border bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground focus-visible:outline-none",
+ 'h-9 w-full border-b border-border bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground focus-visible:outline-none',
className,
)}
{...props}
@@ -68,15 +63,12 @@ function ComboboxInput({
function ComboboxContent({
className,
children,
- side = "bottom",
+ side = 'bottom',
sideOffset = 4,
- align = "start",
+ align = 'start',
...props
}: ComboboxPrimitive.Popup.Props &
- Pick<
- ComboboxPrimitive.Positioner.Props,
- "align" | "side" | "sideOffset"
- >) {
+ Pick<ComboboxPrimitive.Positioner.Props, 'align' | 'side' | 'sideOffset'>) {
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Positioner
@@ -88,7 +80,7 @@ function ComboboxContent({
<ComboboxPrimitive.Popup
data-slot="combobox-content"
className={cn(
- "relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-56 origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ 'relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-56 origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
{...props}
@@ -100,36 +92,27 @@ function ComboboxContent({
);
}
-function ComboboxList({
- className,
- ...props
-}: ComboboxPrimitive.List.Props) {
+function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
return (
<ComboboxPrimitive.List
data-slot="combobox-list"
- className={cn("max-h-64 overflow-y-auto p-1", className)}
+ className={cn('max-h-64 overflow-y-auto p-1', className)}
{...props}
/>
);
}
-function ComboboxItem({
- className,
- children,
- ...props
-}: ComboboxPrimitive.Item.Props) {
+function ComboboxItem({ className, children, ...props }: ComboboxPrimitive.Item.Props) {
return (
<ComboboxPrimitive.Item
data-slot="combobox-item"
className={cn(
- "relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1.5 pr-8 pl-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
+ 'relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1.5 pr-8 pl-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50',
className,
)}
{...props}
>
- <span className="flex flex-1 shrink-0 gap-2 whitespace-nowrap truncate">
- {children}
- </span>
+ <span className="flex flex-1 shrink-0 gap-2 whitespace-nowrap truncate">{children}</span>
<ComboboxPrimitive.ItemIndicator
render={
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
@@ -141,10 +124,7 @@ function ComboboxItem({
);
}
-function ComboboxEmpty({
- className,
- ...props
-}: ComboboxPrimitive.Empty.Props) {
+function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
return (
<ComboboxPrimitive.Empty
data-slot="combobox-empty"
@@ -154,7 +134,7 @@ function ComboboxEmpty({
// state changes). `empty:hidden` collapses it to zero height when
// there are matches — otherwise the padding leaks vertical space
// above the list.
- "px-3 py-6 text-center text-sm text-muted-foreground empty:hidden",
+ 'px-3 py-6 text-center text-sm text-muted-foreground empty:hidden',
className,
)}
{...props}
diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx
index 5ca40eee4..6ed0db87e 100644
--- a/web/src/components/ui/dialog.tsx
+++ b/web/src/components/ui/dialog.tsx
@@ -1,42 +1,39 @@
-"use client"
+'use client';
-import * as React from "react"
-import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
+import * as React from 'react';
+import { Dialog as DialogPrimitive } from '@base-ui/react/dialog';
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import { XIcon } from "lucide-react"
+import { cn } from '@/lib/utils';
+import { Button } from '@/components/ui/button';
+import { XIcon } from 'lucide-react';
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
- return <DialogPrimitive.Root data-slot="dialog" {...props} />
+ return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
- return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
- return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
- return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
-function DialogOverlay({
- className,
- ...props
-}: DialogPrimitive.Backdrop.Props) {
+function DialogOverlay({ className, ...props }: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
- "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
- className
+ 'fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
+ className,
)}
{...props}
/>
- )
+ );
}
function DialogContent({
@@ -45,7 +42,7 @@ function DialogContent({
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
- showCloseButton?: boolean
+ showCloseButton?: boolean;
}) {
return (
<DialogPortal>
@@ -53,8 +50,8 @@ function DialogContent({
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
- "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] sm:max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-background p-4 text-sm ring-1 ring-foreground/10 duration-100 outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
- className
+ 'fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] sm:max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-background p-4 text-sm ring-1 ring-foreground/10 duration-100 outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ className,
)}
{...props}
>
@@ -62,32 +59,21 @@ function DialogContent({
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
- render={
- <Button
- variant="ghost"
- className="absolute top-2 right-2"
- size="icon-sm"
- />
- }
+ render={<Button variant="ghost" className="absolute top-2 right-2" size="icon-sm" />}
>
- <XIcon
- />
+ <XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
- )
+ );
}
-function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
- <div
- data-slot="dialog-header"
- className={cn("flex flex-col gap-2", className)}
- {...props}
- />
- )
+ <div data-slot="dialog-header" className={cn('flex flex-col gap-2', className)} {...props} />
+ );
}
function DialogFooter({
@@ -95,52 +81,47 @@ function DialogFooter({
showCloseButton = false,
children,
...props
-}: React.ComponentProps<"div"> & {
- showCloseButton?: boolean
+}: React.ComponentProps<'div'> & {
+ showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
- "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
- className
+ '-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
+ className,
)}
{...props}
>
{children}
{showCloseButton && (
- <DialogPrimitive.Close render={<Button variant="outline" />}>
- Close
- </DialogPrimitive.Close>
+ <DialogPrimitive.Close render={<Button variant="outline" />}>Close</DialogPrimitive.Close>
)}
</div>
- )
+ );
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
- className={cn("text-base leading-none font-medium", className)}
+ className={cn('text-base leading-none font-medium', className)}
{...props}
/>
- )
+ );
}
-function DialogDescription({
- className,
- ...props
-}: DialogPrimitive.Description.Props) {
+function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
- "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
- className
+ 'text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground',
+ className,
)}
{...props}
/>
- )
+ );
}
export {
@@ -154,4 +135,4 @@ export {
DialogPortal,
DialogTitle,
DialogTrigger,
-}
+};
diff --git a/web/src/components/ui/dropdown-menu.tsx b/web/src/components/ui/dropdown-menu.tsx
index a126ca7d6..1788ea192 100644
--- a/web/src/components/ui/dropdown-menu.tsx
+++ b/web/src/components/ui/dropdown-menu.tsx
@@ -1,35 +1,32 @@
-"use client"
+'use client';
-import * as React from "react"
-import { Menu as MenuPrimitive } from "@base-ui/react/menu"
+import * as React from 'react';
+import { Menu as MenuPrimitive } from '@base-ui/react/menu';
-import { cn } from "@/lib/utils"
-import { ChevronRightIcon, CheckIcon } from "lucide-react"
+import { cn } from '@/lib/utils';
+import { ChevronRightIcon, CheckIcon } from 'lucide-react';
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
- return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
+ return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
- return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
+ return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
- return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
+ return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}
function DropdownMenuContent({
- align = "start",
+ align = 'start',
alignOffset = 0,
- side = "bottom",
+ side = 'bottom',
sideOffset = 4,
className,
...props
}: MenuPrimitive.Popup.Props &
- Pick<
- MenuPrimitive.Positioner.Props,
- "align" | "alignOffset" | "side" | "sideOffset"
- >) {
+ Pick<MenuPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset'>) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
@@ -41,16 +38,19 @@ function DropdownMenuContent({
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
- className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
+ className={cn(
+ 'z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95',
+ className,
+ )}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
- )
+ );
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
- return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
+ return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}
function DropdownMenuLabel({
@@ -58,29 +58,29 @@ function DropdownMenuLabel({
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
- inset?: boolean
+ inset?: boolean;
}) {
return (
<MenuPrimitive.GroupLabel
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
- "px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
- className
+ 'px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
+ className,
)}
{...props}
/>
- )
+ );
}
function DropdownMenuItem({
className,
inset,
- variant = "default",
+ variant = 'default',
...props
}: MenuPrimitive.Item.Props & {
- inset?: boolean
- variant?: "default" | "destructive"
+ inset?: boolean;
+ variant?: 'default' | 'destructive';
}) {
return (
<MenuPrimitive.Item
@@ -89,15 +89,15 @@ function DropdownMenuItem({
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
- className
+ className,
)}
{...props}
/>
- )
+ );
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
- return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
+ return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
@@ -106,7 +106,7 @@ function DropdownMenuSubTrigger({
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
- inset?: boolean
+ inset?: boolean;
}) {
return (
<MenuPrimitive.SubmenuTrigger
@@ -114,20 +114,20 @@ function DropdownMenuSubTrigger({
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- className
+ className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
- )
+ );
}
function DropdownMenuSubContent({
- align = "start",
+ align = 'start',
alignOffset = -3,
- side = "right",
+ side = 'right',
sideOffset = 0,
className,
...props
@@ -136,8 +136,8 @@ function DropdownMenuSubContent({
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn(
- "w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
- className
+ 'w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ className,
)}
align={align}
alignOffset={alignOffset}
@@ -145,7 +145,7 @@ function DropdownMenuSubContent({
sideOffset={sideOffset}
{...props}
/>
- )
+ );
}
function DropdownMenuCheckboxItem({
@@ -155,7 +155,7 @@ function DropdownMenuCheckboxItem({
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
- inset?: boolean
+ inset?: boolean;
}) {
return (
<MenuPrimitive.CheckboxItem
@@ -163,7 +163,7 @@ function DropdownMenuCheckboxItem({
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- className
+ className,
)}
checked={checked}
{...props}
@@ -173,22 +173,16 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
- <CheckIcon
- />
+ <CheckIcon />
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
- )
+ );
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
- return (
- <MenuPrimitive.RadioGroup
- data-slot="dropdown-menu-radio-group"
- {...props}
- />
- )
+ return <MenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
}
function DropdownMenuRadioItem({
@@ -197,7 +191,7 @@ function DropdownMenuRadioItem({
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
- inset?: boolean
+ inset?: boolean;
}) {
return (
<MenuPrimitive.RadioItem
@@ -205,7 +199,7 @@ function DropdownMenuRadioItem({
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- className
+ className,
)}
{...props}
>
@@ -214,42 +208,35 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
- <CheckIcon
- />
+ <CheckIcon />
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
- )
+ );
}
-function DropdownMenuSeparator({
- className,
- ...props
-}: MenuPrimitive.Separator.Props) {
+function DropdownMenuSeparator({ className, ...props }: MenuPrimitive.Separator.Props) {
return (
<MenuPrimitive.Separator
data-slot="dropdown-menu-separator"
- className={cn("-mx-1 my-1 h-px bg-border", className)}
+ className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
- )
+ );
}
-function DropdownMenuShortcut({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
- "ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
- className
+ 'ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground',
+ className,
)}
{...props}
/>
- )
+ );
}
export {
@@ -268,4 +255,4 @@ export {
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
-}
+};
diff --git a/web/src/components/ui/input.tsx b/web/src/components/ui/input.tsx
index 7d21babba..70c195a90 100644
--- a/web/src/components/ui/input.tsx
+++ b/web/src/components/ui/input.tsx
@@ -1,20 +1,20 @@
-import * as React from "react"
-import { Input as InputPrimitive } from "@base-ui/react/input"
+import * as React from 'react';
+import { Input as InputPrimitive } from '@base-ui/react/input';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Input({ className, type, ...props }: React.ComponentProps<"input">) {
+function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
return (
<InputPrimitive
type={type}
data-slot="input"
className={cn(
- "h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
- className
+ 'h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',
+ className,
)}
{...props}
/>
- )
+ );
}
-export { Input }
+export { Input };
diff --git a/web/src/components/ui/label.tsx b/web/src/components/ui/label.tsx
index 74da65c33..6d13a34c4 100644
--- a/web/src/components/ui/label.tsx
+++ b/web/src/components/ui/label.tsx
@@ -1,20 +1,20 @@
-"use client"
+'use client';
-import * as React from "react"
+import * as React from 'react';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Label({ className, ...props }: React.ComponentProps<"label">) {
+function Label({ className, ...props }: React.ComponentProps<'label'>) {
return (
<label
data-slot="label"
className={cn(
- "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
- className
+ 'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
+ className,
)}
{...props}
/>
- )
+ );
}
-export { Label }
+export { Label };
diff --git a/web/src/components/ui/markdown.tsx b/web/src/components/ui/markdown.tsx
index 6fda0f39f..596888919 100644
--- a/web/src/components/ui/markdown.tsx
+++ b/web/src/components/ui/markdown.tsx
@@ -1,85 +1,79 @@
-import { cn } from "@/lib/utils"
-import { marked } from "marked"
-import { memo, useId, useMemo } from "react"
-import ReactMarkdown, { Components } from "react-markdown"
-import remarkBreaks from "remark-breaks"
-import remarkGfm from "remark-gfm"
-import { CodeBlock, CodeBlockCode } from "./code-block"
+import { cn } from '@/lib/utils';
+import { marked } from 'marked';
+import { memo, useId, useMemo } from 'react';
+import ReactMarkdown, { Components } from 'react-markdown';
+import remarkBreaks from 'remark-breaks';
+import remarkGfm from 'remark-gfm';
+import { CodeBlock, CodeBlockCode } from './code-block';
export type MarkdownProps = {
- children: string
- id?: string
- className?: string
- components?: Partial<Components>
-}
+ children: string;
+ id?: string;
+ className?: string;
+ components?: Partial<Components>;
+};
function parseMarkdownIntoBlocks(markdown: string): string[] {
- const tokens = marked.lexer(markdown)
- return tokens.map((token) => token.raw)
+ const tokens = marked.lexer(markdown);
+ return tokens.map((token) => token.raw);
}
function extractLanguage(className?: string): string {
- if (!className) return "plaintext"
- const match = className.match(/language-(\w+)/)
- return match ? match[1] : "plaintext"
+ if (!className) return 'plaintext';
+ const match = className.match(/language-(\w+)/);
+ return match ? match[1] : 'plaintext';
}
const INITIAL_COMPONENTS: Partial<Components> = {
code: function CodeComponent({ className, children, ...props }) {
const isInline =
!props.node?.position?.start.line ||
- props.node?.position?.start.line === props.node?.position?.end.line
+ props.node?.position?.start.line === props.node?.position?.end.line;
if (isInline) {
return (
<span
- className={cn(
- "bg-primary-foreground rounded-sm px-1 font-mono text-sm",
- className
- )}
+ className={cn('bg-primary-foreground rounded-sm px-1 font-mono text-sm', className)}
{...props}
>
{children}
</span>
- )
+ );
}
- const language = extractLanguage(className)
+ const language = extractLanguage(className);
return (
<CodeBlock className={className}>
<CodeBlockCode code={children as string} language={language} />
</CodeBlock>
- )
+ );
},
pre: function PreComponent({ children }) {
- return <>{children}</>
+ return <>{children}</>;
},
-}
+};
const MemoizedMarkdownBlock = memo(
function MarkdownBlock({
content,
components = INITIAL_COMPONENTS,
}: {
- content: string
- components?: Partial<Components>
+ content: string;
+ components?: Partial<Components>;
}) {
return (
- <ReactMarkdown
- remarkPlugins={[remarkGfm, remarkBreaks]}
- components={components}
- >
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={components}>
{content}
</ReactMarkdown>
- )
+ );
},
function propsAreEqual(prevProps, nextProps) {
- return prevProps.content === nextProps.content
- }
-)
+ return prevProps.content === nextProps.content;
+ },
+);
-MemoizedMarkdownBlock.displayName = "MemoizedMarkdownBlock"
+MemoizedMarkdownBlock.displayName = 'MemoizedMarkdownBlock';
function MarkdownComponent({
children,
@@ -87,9 +81,9 @@ function MarkdownComponent({
className,
components = INITIAL_COMPONENTS,
}: MarkdownProps) {
- const generatedId = useId()
- const blockId = id ?? generatedId
- const blocks = useMemo(() => parseMarkdownIntoBlocks(children), [children])
+ const generatedId = useId();
+ const blockId = id ?? generatedId;
+ const blocks = useMemo(() => parseMarkdownIntoBlocks(children), [children]);
return (
<div className={className}>
@@ -101,10 +95,10 @@ function MarkdownComponent({
/>
))}
</div>
- )
+ );
}
-const Markdown = memo(MarkdownComponent)
-Markdown.displayName = "Markdown"
+const Markdown = memo(MarkdownComponent);
+Markdown.displayName = 'Markdown';
-export { Markdown }
+export { Markdown };
diff --git a/web/src/components/ui/scroll-area.tsx b/web/src/components/ui/scroll-area.tsx
index 84c1e9fbb..bce3dc319 100644
--- a/web/src/components/ui/scroll-area.tsx
+++ b/web/src/components/ui/scroll-area.tsx
@@ -1,19 +1,15 @@
-"use client"
+'use client';
-import * as React from "react"
-import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
+import * as React from 'react';
+import { ScrollArea as ScrollAreaPrimitive } from '@base-ui/react/scroll-area';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function ScrollArea({
- className,
- children,
- ...props
-}: ScrollAreaPrimitive.Root.Props) {
+function ScrollArea({ className, children, ...props }: ScrollAreaPrimitive.Root.Props) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
- className={cn("relative", className)}
+ className={cn('relative', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
@@ -25,12 +21,12 @@ function ScrollArea({
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
- )
+ );
}
function ScrollBar({
className,
- orientation = "vertical",
+ orientation = 'vertical',
...props
}: ScrollAreaPrimitive.Scrollbar.Props) {
return (
@@ -39,8 +35,8 @@ function ScrollBar({
data-orientation={orientation}
orientation={orientation}
className={cn(
- "flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
- className
+ 'flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent',
+ className,
)}
{...props}
>
@@ -49,7 +45,7 @@ function ScrollBar({
className="relative flex-1 rounded-full bg-border"
/>
</ScrollAreaPrimitive.Scrollbar>
- )
+ );
}
-export { ScrollArea, ScrollBar }
+export { ScrollArea, ScrollBar };
diff --git a/web/src/components/ui/select.tsx b/web/src/components/ui/select.tsx
index e8021f5f2..decf8d1d8 100644
--- a/web/src/components/ui/select.tsx
+++ b/web/src/components/ui/select.tsx
@@ -1,40 +1,40 @@
-"use client"
+'use client';
-import * as React from "react"
-import { Select as SelectPrimitive } from "@base-ui/react/select"
+import * as React from 'react';
+import { Select as SelectPrimitive } from '@base-ui/react/select';
-import { cn } from "@/lib/utils"
-import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
+import { cn } from '@/lib/utils';
+import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from 'lucide-react';
-const Select = SelectPrimitive.Root
+const Select = SelectPrimitive.Root;
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
<SelectPrimitive.Group
data-slot="select-group"
- className={cn("scroll-my-1 p-1", className)}
+ className={cn('scroll-my-1 p-1', className)}
{...props}
/>
- )
+ );
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
data-slot="select-value"
- className={cn("flex flex-1 text-left", className)}
+ className={cn('flex flex-1 text-left', className)}
{...props}
/>
- )
+ );
}
function SelectTrigger({
className,
- size = "default",
+ size = 'default',
children,
...props
}: SelectPrimitive.Trigger.Props & {
- size?: "sm" | "default"
+ size?: 'sm' | 'default';
}) {
return (
<SelectPrimitive.Trigger
@@ -42,33 +42,31 @@ function SelectTrigger({
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- className
+ className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon
- render={
- <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
- }
+ render={<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />}
/>
</SelectPrimitive.Trigger>
- )
+ );
}
function SelectContent({
className,
children,
- side = "bottom",
+ side = 'bottom',
sideOffset = 4,
- align = "center",
+ align = 'center',
alignOffset = 0,
alignItemWithTrigger = true,
...props
}: SelectPrimitive.Popup.Props &
Pick<
SelectPrimitive.Positioner.Props,
- "align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
+ 'align' | 'alignOffset' | 'side' | 'sideOffset' | 'alignItemWithTrigger'
>) {
return (
<SelectPrimitive.Portal>
@@ -83,7 +81,10 @@ function SelectContent({
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
- className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
+ className={cn(
+ 'relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ className,
+ )}
{...props}
>
<SelectScrollUpButton />
@@ -92,33 +93,26 @@ function SelectContent({
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
- )
+ );
}
-function SelectLabel({
- className,
- ...props
-}: SelectPrimitive.GroupLabel.Props) {
+function SelectLabel({ className, ...props }: SelectPrimitive.GroupLabel.Props) {
return (
<SelectPrimitive.GroupLabel
data-slot="select-label"
- className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
+ className={cn('px-1.5 py-1 text-xs text-muted-foreground', className)}
{...props}
/>
- )
+ );
}
-function SelectItem({
- className,
- children,
- ...props
-}: SelectPrimitive.Item.Props) {
+function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Props) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
- className
+ className,
)}
{...props}
>
@@ -133,20 +127,17 @@ function SelectItem({
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
- )
+ );
}
-function SelectSeparator({
- className,
- ...props
-}: SelectPrimitive.Separator.Props) {
+function SelectSeparator({ className, ...props }: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
- className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
+ className={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}
{...props}
/>
- )
+ );
}
function SelectScrollUpButton({
@@ -158,14 +149,13 @@ function SelectScrollUpButton({
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
- className
+ className,
)}
{...props}
>
- <ChevronUpIcon
- />
+ <ChevronUpIcon />
</SelectPrimitive.ScrollUpArrow>
- )
+ );
}
function SelectScrollDownButton({
@@ -177,14 +167,13 @@ function SelectScrollDownButton({
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
- className
+ className,
)}
{...props}
>
- <ChevronDownIcon
- />
+ <ChevronDownIcon />
</SelectPrimitive.ScrollDownArrow>
- )
+ );
}
export {
@@ -198,4 +187,4 @@ export {
SelectSeparator,
SelectTrigger,
SelectValue,
-}
+};
diff --git a/web/src/components/ui/separator.tsx b/web/src/components/ui/separator.tsx
index 6e1369e43..34c7ba051 100644
--- a/web/src/components/ui/separator.tsx
+++ b/web/src/components/ui/separator.tsx
@@ -1,25 +1,21 @@
-"use client"
+'use client';
-import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
+import { Separator as SeparatorPrimitive } from '@base-ui/react/separator';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Separator({
- className,
- orientation = "horizontal",
- ...props
-}: SeparatorPrimitive.Props) {
+function Separator({ className, orientation = 'horizontal', ...props }: SeparatorPrimitive.Props) {
return (
<SeparatorPrimitive
data-slot="separator"
orientation={orientation}
className={cn(
- "shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
- className
+ 'shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch',
+ className,
)}
{...props}
/>
- )
+ );
}
-export { Separator }
+export { Separator };
diff --git a/web/src/components/ui/sheet.tsx b/web/src/components/ui/sheet.tsx
index 727cc4db3..9a543a1da 100644
--- a/web/src/components/ui/sheet.tsx
+++ b/web/src/components/ui/sheet.tsx
@@ -1,26 +1,26 @@
-"use client"
+'use client';
-import * as React from "react"
-import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
+import * as React from 'react';
+import { Dialog as SheetPrimitive } from '@base-ui/react/dialog';
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import { XIcon } from "lucide-react"
+import { cn } from '@/lib/utils';
+import { Button } from '@/components/ui/button';
+import { XIcon } from 'lucide-react';
function Sheet({ ...props }: SheetPrimitive.Root.Props) {
- return <SheetPrimitive.Root data-slot="sheet" {...props} />
+ return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
- return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
+ return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
- return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
+ return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
- return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
+ return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
@@ -28,23 +28,23 @@ function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
<SheetPrimitive.Backdrop
data-slot="sheet-overlay"
className={cn(
- "fixed inset-0 z-50 bg-black/10 duration-100 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
- className
+ 'fixed inset-0 z-50 bg-black/10 duration-100 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
+ className,
)}
{...props}
/>
- )
+ );
}
function SheetContent({
className,
children,
- side = "right",
+ side = 'right',
showCloseButton = true,
...props
}: SheetPrimitive.Popup.Props & {
- side?: "top" | "right" | "bottom" | "left"
- showCloseButton?: boolean
+ side?: 'top' | 'right' | 'bottom' | 'left';
+ showCloseButton?: boolean;
}) {
return (
<SheetPortal>
@@ -53,8 +53,8 @@ function SheetContent({
data-slot="sheet-content"
data-side={side}
className={cn(
- "fixed z-50 flex flex-col gap-4 bg-background bg-clip-padding text-sm shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",
- className
+ 'fixed z-50 flex flex-col gap-4 bg-background bg-clip-padding text-sm shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10',
+ className,
)}
{...props}
>
@@ -62,65 +62,55 @@ function SheetContent({
{showCloseButton && (
<SheetPrimitive.Close
data-slot="sheet-close"
- render={
- <Button
- variant="ghost"
- className="absolute top-3 right-3"
- size="icon-sm"
- />
- }
+ render={<Button variant="ghost" className="absolute top-3 right-3" size="icon-sm" />}
>
- <XIcon
- />
+ <XIcon />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Popup>
</SheetPortal>
- )
+ );
}
-function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-header"
- className={cn("flex flex-col gap-0.5 p-4", className)}
+ className={cn('flex flex-col gap-0.5 p-4', className)}
{...props}
/>
- )
+ );
}
-function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-footer"
- className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
- )
+ );
}
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
- className={cn("text-base font-medium text-foreground", className)}
+ className={cn('text-base font-medium text-foreground', className)}
{...props}
/>
- )
+ );
}
-function SheetDescription({
- className,
- ...props
-}: SheetPrimitive.Description.Props) {
+function SheetDescription({ className, ...props }: SheetPrimitive.Description.Props) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
- className={cn("text-sm text-muted-foreground", className)}
+ className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
- )
+ );
}
export {
@@ -132,4 +122,4 @@ export {
SheetFooter,
SheetTitle,
SheetDescription,
-}
+};
diff --git a/web/src/components/ui/skeleton.tsx b/web/src/components/ui/skeleton.tsx
index 0118624f6..69c99b8d7 100644
--- a/web/src/components/ui/skeleton.tsx
+++ b/web/src/components/ui/skeleton.tsx
@@ -1,13 +1,13 @@
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
+function Skeleton({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="skeleton"
- className={cn("animate-pulse rounded-md bg-muted", className)}
+ className={cn('animate-pulse rounded-md bg-muted', className)}
{...props}
/>
- )
+ );
}
-export { Skeleton }
+export { Skeleton };
diff --git a/web/src/components/ui/sonner.tsx b/web/src/components/ui/sonner.tsx
index 9280ee52f..12ca2d095 100644
--- a/web/src/components/ui/sonner.tsx
+++ b/web/src/components/ui/sonner.tsx
@@ -1,49 +1,45 @@
-"use client"
+'use client';
-import { useTheme } from "next-themes"
-import { Toaster as Sonner, type ToasterProps } from "sonner"
-import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
+import { useTheme } from 'next-themes';
+import { Toaster as Sonner, type ToasterProps } from 'sonner';
+import {
+ CircleCheckIcon,
+ InfoIcon,
+ TriangleAlertIcon,
+ OctagonXIcon,
+ Loader2Icon,
+} from 'lucide-react';
const Toaster = ({ ...props }: ToasterProps) => {
- const { theme = "system" } = useTheme()
+ const { theme = 'system' } = useTheme();
return (
<Sonner
- theme={theme as ToasterProps["theme"]}
+ theme={theme as ToasterProps['theme']}
className="toaster group"
icons={{
- success: (
- <CircleCheckIcon className="size-4" />
- ),
- info: (
- <InfoIcon className="size-4" />
- ),
- warning: (
- <TriangleAlertIcon className="size-4" />
- ),
- error: (
- <OctagonXIcon className="size-4" />
- ),
- loading: (
- <Loader2Icon className="size-4 animate-spin" />
- ),
+ success: <CircleCheckIcon className="size-4" />,
+ info: <InfoIcon className="size-4" />,
+ warning: <TriangleAlertIcon className="size-4" />,
+ error: <OctagonXIcon className="size-4" />,
+ loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
- "--normal-bg": "var(--popover)",
- "--normal-text": "var(--popover-foreground)",
- "--normal-border": "var(--border)",
- "--border-radius": "var(--radius)",
+ '--normal-bg': 'var(--popover)',
+ '--normal-text': 'var(--popover-foreground)',
+ '--normal-border': 'var(--border)',
+ '--border-radius': 'var(--radius)',
} as React.CSSProperties
}
toastOptions={{
classNames: {
- toast: "cn-toast",
+ toast: 'cn-toast',
},
}}
{...props}
/>
- )
-}
+ );
+};
-export { Toaster }
+export { Toaster };
diff --git a/web/src/components/ui/table.tsx b/web/src/components/ui/table.tsx
index 8dc13aee3..722f7e4ae 100644
--- a/web/src/components/ui/table.tsx
+++ b/web/src/components/ui/table.tsx
@@ -1,116 +1,89 @@
-"use client"
+'use client';
-import * as React from "react"
+import * as React from 'react';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Table({ className, ...props }: React.ComponentProps<"table">) {
+function Table({ className, ...props }: React.ComponentProps<'table'>) {
return (
- <div
- data-slot="table-container"
- className="relative w-full overflow-x-auto"
- >
+ <div data-slot="table-container" className="relative w-full overflow-x-auto">
<table
data-slot="table"
- className={cn("w-full caption-bottom text-sm", className)}
+ className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
- )
+ );
}
-function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
- return (
- <thead
- data-slot="table-header"
- className={cn("[&_tr]:border-b", className)}
- {...props}
- />
- )
+function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
+ return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />;
}
-function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
+function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
return (
<tbody
data-slot="table-body"
- className={cn("[&_tr:last-child]:border-0", className)}
+ className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
- )
+ );
}
-function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
+function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return (
<tfoot
data-slot="table-footer"
- className={cn(
- "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
- className
- )}
+ className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
{...props}
/>
- )
+ );
}
-function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
+function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return (
<tr
data-slot="table-row"
className={cn(
- "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
- className
+ 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
+ className,
)}
{...props}
/>
- )
+ );
}
-function TableHead({ className, ...props }: React.ComponentProps<"th">) {
+function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return (
<th
data-slot="table-head"
className={cn(
- "h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
- className
+ 'h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0',
+ className,
)}
{...props}
/>
- )
+ );
}
-function TableCell({ className, ...props }: React.ComponentProps<"td">) {
+function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return (
<td
data-slot="table-cell"
- className={cn(
- "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
- className
- )}
+ className={cn('p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0', className)}
{...props}
/>
- )
+ );
}
-function TableCaption({
- className,
- ...props
-}: React.ComponentProps<"caption">) {
+function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
return (
<caption
data-slot="table-caption"
- className={cn("mt-4 text-sm text-muted-foreground", className)}
+ className={cn('mt-4 text-sm text-muted-foreground', className)}
{...props}
/>
- )
+ );
}
-export {
- Table,
- TableHeader,
- TableBody,
- TableFooter,
- TableHead,
- TableRow,
- TableCell,
- TableCaption,
-}
+export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
diff --git a/web/src/components/ui/tabs.tsx b/web/src/components/ui/tabs.tsx
index 56c428888..d0d56afaa 100644
--- a/web/src/components/ui/tabs.tsx
+++ b/web/src/components/ui/tabs.tsx
@@ -1,46 +1,39 @@
-"use client"
+'use client';
-import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
-import { cva, type VariantProps } from "class-variance-authority"
+import { Tabs as TabsPrimitive } from '@base-ui/react/tabs';
+import { cva, type VariantProps } from 'class-variance-authority';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Tabs({
- className,
- orientation = "horizontal",
- ...props
-}: TabsPrimitive.Root.Props) {
+function Tabs({ className, orientation = 'horizontal', ...props }: TabsPrimitive.Root.Props) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
- className={cn(
- "group/tabs flex gap-2 data-horizontal:flex-col",
- className
- )}
+ className={cn('group/tabs flex gap-2 data-horizontal:flex-col', className)}
{...props}
/>
- )
+ );
}
const tabsListVariants = cva(
- "group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
+ 'group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none',
{
variants: {
variant: {
- default: "bg-muted",
- line: "gap-1 bg-transparent",
+ default: 'bg-muted',
+ line: 'gap-1 bg-transparent',
},
},
defaultVariants: {
- variant: "default",
+ variant: 'default',
},
- }
-)
+ },
+);
function TabsList({
className,
- variant = "default",
+ variant = 'default',
...props
}: TabsPrimitive.List.Props & VariantProps<typeof tabsListVariants>) {
return (
@@ -50,7 +43,7 @@ function TabsList({
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
- )
+ );
}
function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
@@ -59,24 +52,24 @@ function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
- "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
- "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
- className
+ 'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',
+ 'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',
+ 'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',
+ className,
)}
{...props}
/>
- )
+ );
}
function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
return (
<TabsPrimitive.Panel
data-slot="tabs-content"
- className={cn("flex-1 text-sm outline-none", className)}
+ className={cn('flex-1 text-sm outline-none', className)}
{...props}
/>
- )
+ );
}
-export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
+export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
diff --git a/web/src/components/ui/textarea.tsx b/web/src/components/ui/textarea.tsx
index 04d27f7d1..46eab5e3f 100644
--- a/web/src/components/ui/textarea.tsx
+++ b/web/src/components/ui/textarea.tsx
@@ -1,18 +1,18 @@
-import * as React from "react"
+import * as React from 'react';
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils';
-function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<textarea
data-slot="textarea"
className={cn(
- "flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
- className
+ 'flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',
+ className,
)}
{...props}
/>
- )
+ );
}
-export { Textarea }
+export { Textarea };
diff --git a/web/src/components/ui/upgrade-badge.tsx b/web/src/components/ui/upgrade-badge.tsx
index 6b77d8e20..b3f2e4a1d 100644
--- a/web/src/components/ui/upgrade-badge.tsx
+++ b/web/src/components/ui/upgrade-badge.tsx
@@ -1,9 +1,9 @@
-"use client";
+'use client';
-import { useFeatureGate } from "@/hooks/use-feature-gate";
-import type { Feature } from "@/config/plans";
-import { Badge } from "@/components/ui/badge";
-import { Crown } from "lucide-react";
+import { useFeatureGate } from '@/hooks/use-feature-gate';
+import type { Feature } from '@/config/plans';
+import { Badge } from '@/components/ui/badge';
+import { Crown } from 'lucide-react';
interface UpgradeBadgeProps {
feature: Feature;
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index 0b0dd9e2d..d904f43c6 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -8,8 +8,8 @@ import {
Settings,
Tag,
Users,
-} from "lucide-react";
-import type { Feature } from "@/config/plans";
+} from 'lucide-react';
+import type { Feature } from '@/config/plans';
export interface NavItem {
title: string;
@@ -29,67 +29,67 @@ export const dashboardNav: NavGroup[] = [
{
items: [
{
- title: "Brands",
- href: "/dashboard/brands",
+ title: 'Brands',
+ href: '/dashboard/brands',
icon: Building2,
},
],
},
{
- title: "Analytics",
+ title: 'Analytics',
items: [
{
- title: "Answer Engine Insights",
- href: "/dashboard/insights",
+ title: 'Answer Engine Insights',
+ href: '/dashboard/insights',
icon: BarChart3,
- requiredFeature: "basic_insights",
+ requiredFeature: 'basic_insights',
},
{
- title: "Topics",
- href: "/dashboard/topics",
+ title: 'Topics',
+ href: '/dashboard/topics',
icon: Tag,
},
{
- title: "Prompts",
- href: "/dashboard/prompts",
+ title: 'Prompts',
+ href: '/dashboard/prompts',
icon: Globe,
},
{
- title: "Citations",
- href: "/dashboard/citations",
+ title: 'Citations',
+ href: '/dashboard/citations',
icon: Quote,
},
{
- title: "AI Traffic Analytics",
- href: "/dashboard/traffic",
+ title: 'AI Traffic Analytics',
+ href: '/dashboard/traffic',
icon: LineChart,
- requiredFeature: "advanced_analytics",
+ requiredFeature: 'advanced_analytics',
},
{
- title: "Competitors",
- href: "/dashboard/competitors",
+ title: 'Competitors',
+ href: '/dashboard/competitors',
icon: Users,
- requiredFeature: "competitor_tracking",
+ requiredFeature: 'competitor_tracking',
},
],
},
{
- title: "Optimization",
+ title: 'Optimization',
items: [
{
- title: "Content Optimization",
- href: "/dashboard/content",
+ title: 'Content Optimization',
+ href: '/dashboard/content',
icon: FileText,
- requiredFeature: "content_optimization",
+ requiredFeature: 'content_optimization',
},
],
},
{
- title: "System",
+ title: 'System',
items: [
{
- title: "Settings",
- href: "/dashboard/settings",
+ title: 'Settings',
+ href: '/dashboard/settings',
icon: Settings,
},
],
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 3d0ec3c69..1d18c0bee 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -1,20 +1,20 @@
export const FEATURES = [
- "basic_insights",
- "advanced_analytics",
- "prompt_suggestions",
- "prompt_volumes",
- "daily_monitoring",
- "competitor_tracking",
- "content_optimization",
- "custom_reports",
- "api_access",
- "white_label",
- "sso_saml",
+ 'basic_insights',
+ 'advanced_analytics',
+ 'prompt_suggestions',
+ 'prompt_volumes',
+ 'daily_monitoring',
+ 'competitor_tracking',
+ 'content_optimization',
+ 'custom_reports',
+ 'api_access',
+ 'white_label',
+ 'sso_saml',
] as const;
export type Feature = (typeof FEATURES)[number];
-export type PlanId = "self_hosted" | "starter" | "growth" | "enterprise";
+export type PlanId = 'self_hosted' | 'starter' | 'growth' | 'enterprise';
export interface PlanLimits {
maxBrands: number;
@@ -47,9 +47,9 @@ export interface Plan {
export const PLANS: Record<PlanId, Plan> = {
self_hosted: {
- id: "self_hosted",
- name: "Self-Hosted",
- tagline: "Full control on your own infrastructure",
+ id: 'self_hosted',
+ name: 'Self-Hosted',
+ tagline: 'Full control on your own infrastructure',
pricing: null,
limits: {
maxBrands: -1,
@@ -61,22 +61,22 @@ export const PLANS: Record<PlanId, Plan> = {
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
- "basic_insights",
- "prompt_suggestions",
- "prompt_volumes",
- "advanced_analytics",
- "daily_monitoring",
- "competitor_tracking",
- "content_optimization",
- "custom_reports",
- "api_access",
+ 'basic_insights',
+ 'prompt_suggestions',
+ 'prompt_volumes',
+ 'advanced_analytics',
+ 'daily_monitoring',
+ 'competitor_tracking',
+ 'content_optimization',
+ 'custom_reports',
+ 'api_access',
],
},
},
starter: {
- id: "starter",
- name: "Starter",
- tagline: "Track your brand across AI platforms",
+ id: 'starter',
+ name: 'Starter',
+ tagline: 'Track your brand across AI platforms',
pricing: { monthly: 49 },
limits: {
maxBrands: 1,
@@ -87,25 +87,25 @@ export const PLANS: Record<PlanId, Plan> = {
maxVolumeAnalyses: 4,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
- allowedScrapers: ["chatgpt-web", "perplexity-web"],
+ allowedScrapers: ['chatgpt-web', 'perplexity-web'],
allowedModels: [],
features: [
- "basic_insights",
- "advanced_analytics",
- "prompt_suggestions",
- "prompt_volumes",
- "daily_monitoring",
- "competitor_tracking",
- "content_optimization",
- "custom_reports",
- "api_access",
+ 'basic_insights',
+ 'advanced_analytics',
+ 'prompt_suggestions',
+ 'prompt_volumes',
+ 'daily_monitoring',
+ 'competitor_tracking',
+ 'content_optimization',
+ 'custom_reports',
+ 'api_access',
],
},
},
growth: {
- id: "growth",
- name: "Growth",
- tagline: "For brands that need deep insights",
+ id: 'growth',
+ name: 'Growth',
+ tagline: 'For brands that need deep insights',
pricing: { monthly: 249 },
highlighted: true,
limits: {
@@ -118,22 +118,22 @@ export const PLANS: Record<PlanId, Plan> = {
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
features: [
- "basic_insights",
- "prompt_suggestions",
- "prompt_volumes",
- "advanced_analytics",
- "daily_monitoring",
- "competitor_tracking",
- "content_optimization",
- "custom_reports",
- "api_access",
+ 'basic_insights',
+ 'prompt_suggestions',
+ 'prompt_volumes',
+ 'advanced_analytics',
+ 'daily_monitoring',
+ 'competitor_tracking',
+ 'content_optimization',
+ 'custom_reports',
+ 'api_access',
],
},
},
enterprise: {
- id: "enterprise",
- name: "Enterprise",
- tagline: "For agencies and large teams at scale",
+ id: 'enterprise',
+ name: 'Enterprise',
+ tagline: 'For agencies and large teams at scale',
pricing: null,
limits: {
maxBrands: -1,
@@ -145,37 +145,37 @@ export const PLANS: Record<PlanId, Plan> = {
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
- "basic_insights",
- "prompt_suggestions",
- "prompt_volumes",
- "advanced_analytics",
- "daily_monitoring",
- "competitor_tracking",
- "content_optimization",
- "custom_reports",
- "api_access",
- "white_label",
- "sso_saml",
+ 'basic_insights',
+ 'prompt_suggestions',
+ 'prompt_volumes',
+ 'advanced_analytics',
+ 'daily_monitoring',
+ 'competitor_tracking',
+ 'content_optimization',
+ 'custom_reports',
+ 'api_access',
+ 'white_label',
+ 'sso_saml',
],
},
},
} as const;
-export const PLAN_ORDER: PlanId[] = ["starter", "growth", "enterprise"];
+export const PLAN_ORDER: PlanId[] = ['starter', 'growth', 'enterprise'];
-export const SUBSCRIBABLE_PLANS: PlanId[] = ["starter", "growth"];
+export const SUBSCRIBABLE_PLANS: PlanId[] = ['starter', 'growth'];
/**
* Self-hosted instances bypass all limits.
* Cloud is determined by NEXT_PUBLIC_IS_CLOUD env var.
*/
export function isCloud(): boolean {
- return process.env.NEXT_PUBLIC_IS_CLOUD === "true";
+ return process.env.NEXT_PUBLIC_IS_CLOUD === 'true';
}
export function getPlan(planId: string | null | undefined): Plan {
if (!isCloud()) return PLANS.self_hosted;
- return PLANS[(planId as PlanId) ?? "starter"] ?? PLANS.starter;
+ return PLANS[(planId as PlanId) ?? 'starter'] ?? PLANS.starter;
}
export function hasFeature(plan: Plan, feature: Feature): boolean {
@@ -184,7 +184,7 @@ export function hasFeature(plan: Plan, feature: Feature): boolean {
export function isWithinLimit(
plan: Plan,
- key: keyof Omit<PlanLimits, "features" | "allowedScrapers" | "allowedModels">,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
currentCount: number,
): boolean {
const limit = plan.limits[key];
@@ -196,5 +196,5 @@ export function getMinimumPlanForFeature(feature: Feature): PlanId {
for (const id of PLAN_ORDER) {
if (PLANS[id].limits.features.includes(feature)) return id;
}
- return "enterprise";
+ return 'enterprise';
}
diff --git a/web/src/config/prompt-options.ts b/web/src/config/prompt-options.ts
index c44e9f815..91a547676 100644
--- a/web/src/config/prompt-options.ts
+++ b/web/src/config/prompt-options.ts
@@ -42,9 +42,7 @@ export type LanguageCode = (typeof LANGUAGES)[number]['code'];
export const MODEL_GROUPS = [
{
provider: 'Claude',
- models: [
- { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },
- ],
+ models: [{ id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' }],
},
] as const;
diff --git a/web/src/config/site.ts b/web/src/config/site.ts
index 822d387b5..0a1491700 100644
--- a/web/src/config/site.ts
+++ b/web/src/config/site.ts
@@ -1,16 +1,16 @@
export const siteConfig = {
- name: "Ansvisor",
+ name: 'Ansvisor',
description:
"Monitor, analyze, and optimize your brand's visibility in AI-powered search engines like ChatGPT, Perplexity, Gemini, and more.",
- url: "https://ansvisor.com",
- ogImage: "https://app.ansvisor.com/opengraph-image",
+ url: 'https://ansvisor.com',
+ ogImage: 'https://app.ansvisor.com/opengraph-image',
links: {
- github: "https://github.com/aeohub/ansvisor",
- docs: "https://docs.ansvisor.com",
+ github: 'https://github.com/aeohub/ansvisor',
+ docs: 'https://docs.ansvisor.com',
},
legal: {
- privacy: "https://www.ansvisor.com/privacy-policy",
- terms: "https://www.ansvisor.com/terms-of-service",
+ privacy: 'https://www.ansvisor.com/privacy-policy',
+ terms: 'https://www.ansvisor.com/terms-of-service',
},
} as const;
diff --git a/web/src/hooks/use-feature-gate.ts b/web/src/hooks/use-feature-gate.ts
index c58b04473..bb4451ab5 100644
--- a/web/src/hooks/use-feature-gate.ts
+++ b/web/src/hooks/use-feature-gate.ts
@@ -1,6 +1,6 @@
-"use client";
+'use client';
-import { usePlanContext } from "@/components/providers/plan-provider";
+import { usePlanContext } from '@/components/providers/plan-provider';
import {
type Feature,
type PlanLimits,
@@ -8,7 +8,7 @@ import {
hasFeature,
isWithinLimit,
getMinimumPlanForFeature,
-} from "@/config/plans";
+} from '@/config/plans';
export function useFeatureGate() {
const { planId, isCloud } = usePlanContext();
@@ -24,13 +24,15 @@ export function useFeatureGate() {
},
withinLimit(
- key: keyof Omit<PlanLimits, "features" | "allowedScrapers" | "allowedModels">,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
currentCount: number,
): boolean {
return isWithinLimit(plan, key, currentCount);
},
- getLimit(key: keyof Omit<PlanLimits, "features" | "allowedScrapers" | "allowedModels">): number {
+ getLimit(
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
+ ): number {
return plan.limits[key];
},
diff --git a/web/src/i18n/navigation.ts b/web/src/i18n/navigation.ts
index 2c786c54d..089b3d6c3 100644
--- a/web/src/i18n/navigation.ts
+++ b/web/src/i18n/navigation.ts
@@ -1,5 +1,4 @@
-import { createNavigation } from "next-intl/navigation";
-import { routing } from "./routing";
+import { createNavigation } from 'next-intl/navigation';
+import { routing } from './routing';
-export const { Link, redirect, usePathname, useRouter, getPathname } =
- createNavigation(routing);
+export const { Link, redirect, usePathname, useRouter, getPathname } = createNavigation(routing);
diff --git a/web/src/i18n/request.ts b/web/src/i18n/request.ts
index 04d1c5af4..d9d1b6ff4 100644
--- a/web/src/i18n/request.ts
+++ b/web/src/i18n/request.ts
@@ -1,10 +1,10 @@
-import { getRequestConfig } from "next-intl/server";
-import { routing } from "./routing";
+import { getRequestConfig } from 'next-intl/server';
+import { routing } from './routing';
export default getRequestConfig(async ({ requestLocale }) => {
let locale = await requestLocale;
- if (!locale || !routing.locales.includes(locale as "en")) {
+ if (!locale || !routing.locales.includes(locale as 'en')) {
locale = routing.defaultLocale;
}
diff --git a/web/src/i18n/routing.ts b/web/src/i18n/routing.ts
index a0c903600..265d1178a 100644
--- a/web/src/i18n/routing.ts
+++ b/web/src/i18n/routing.ts
@@ -1,9 +1,9 @@
-import { defineRouting } from "next-intl/routing";
+import { defineRouting } from 'next-intl/routing';
export const routing = defineRouting({
- locales: ["en"],
- defaultLocale: "en",
- localePrefix: "as-needed",
+ locales: ['en'],
+ defaultLocale: 'en',
+ localePrefix: 'as-needed',
});
export type Locale = (typeof routing.locales)[number];
diff --git a/web/src/lib/actions/brand-domain.ts b/web/src/lib/actions/brand-domain.ts
index 2a08dc7eb..4212a3501 100644
--- a/web/src/lib/actions/brand-domain.ts
+++ b/web/src/lib/actions/brand-domain.ts
@@ -31,8 +31,7 @@ export async function addDomain(
.select()
.single();
- if (error || !domain)
- throw new Error(error?.message ?? 'Failed to add domain');
+ if (error || !domain) throw new Error(error?.message ?? 'Failed to add domain');
revalidatePath('/dashboard/brands');
return mapDomainRow(domain as Record<string, unknown>);
@@ -56,8 +55,7 @@ export async function updateDomain(
.select()
.single();
- if (error || !domain)
- throw new Error(error?.message ?? 'Failed to update domain');
+ if (error || !domain) throw new Error(error?.message ?? 'Failed to update domain');
revalidatePath('/dashboard/brands');
return mapDomainRow(domain as Record<string, unknown>);
diff --git a/web/src/lib/actions/brand-platform.ts b/web/src/lib/actions/brand-platform.ts
index 5b4c17aa9..2eb94501c 100644
--- a/web/src/lib/actions/brand-platform.ts
+++ b/web/src/lib/actions/brand-platform.ts
@@ -19,9 +19,7 @@ function mapRow(row: Record<string, unknown>): BrandPlatform {
};
}
-export async function getBrandPlatforms(
- brandId: string,
-): Promise<BrandPlatform[]> {
+export async function getBrandPlatforms(brandId: string): Promise<BrandPlatform[]> {
const supabase = await createClient();
const { data, error } = await supabase
@@ -100,10 +98,8 @@ export async function updateBrandPlatform(
const payload: Record<string, unknown> = {};
if (updates.isEnabled !== undefined) payload.is_enabled = updates.isEnabled;
- if (updates.checkFrequency !== undefined)
- payload.check_frequency = updates.checkFrequency;
- if (updates.apiModel !== undefined)
- payload.api_model = updates.apiModel || null;
+ if (updates.checkFrequency !== undefined) payload.check_frequency = updates.checkFrequency;
+ if (updates.apiModel !== undefined) payload.api_model = updates.apiModel || null;
const { data, error } = await supabase
.from('brand_platforms')
@@ -112,8 +108,7 @@ export async function updateBrandPlatform(
.select()
.single();
- if (error || !data)
- throw new Error(error?.message ?? 'Failed to update platform');
+ if (error || !data) throw new Error(error?.message ?? 'Failed to update platform');
revalidatePath('/dashboard/brands');
return mapRow(data as Record<string, unknown>);
diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.ts
index 0b11c25d1..1a0c29f10 100644
--- a/web/src/lib/actions/brand.ts
+++ b/web/src/lib/actions/brand.ts
@@ -25,10 +25,7 @@ function mapDomainRow(d: Record<string, unknown>): BrandDomain {
};
}
-function mapBrandRow(
- brand: Record<string, unknown>,
- domains: Record<string, unknown>[],
-): Brand {
+function mapBrandRow(brand: Record<string, unknown>, domains: Record<string, unknown>[]): Brand {
return {
id: brand.id as string,
organizationId: brand.organization_id as string,
@@ -58,10 +55,7 @@ export async function getBrands(organizationId: string): Promise<Brand[]> {
if (error) throw new Error(error.message);
return (data ?? []).map((b) =>
- mapBrandRow(
- b as Record<string, unknown>,
- (b.brand_domains as Record<string, unknown>[]) ?? [],
- ),
+ mapBrandRow(b as Record<string, unknown>, (b.brand_domains as Record<string, unknown>[]) ?? []),
);
}
@@ -120,8 +114,7 @@ export async function createBrand(input: CreateBrandInput): Promise<Brand> {
.select()
.single();
- if (error || !brand)
- throw new Error(error?.message ?? 'Failed to create brand');
+ if (error || !brand) throw new Error(error?.message ?? 'Failed to create brand');
let insertedDomains: Record<string, unknown>[] = [];
@@ -153,10 +146,7 @@ interface UpdateBrandInput {
description?: string | null;
}
-export async function updateBrand(
- id: string,
- updates: UpdateBrandInput,
-): Promise<Brand> {
+export async function updateBrand(id: string, updates: UpdateBrandInput): Promise<Brand> {
const supabase = await createClient();
const payload: Record<string, unknown> = {};
@@ -166,8 +156,7 @@ export async function updateBrand(
}
if ('logoUrl' in updates) payload.logo_url = updates.logoUrl ?? null;
if ('industry' in updates) payload.industry = updates.industry ?? null;
- if ('description' in updates)
- payload.description = updates.description ?? null;
+ if ('description' in updates) payload.description = updates.description ?? null;
const { data, error } = await supabase
.from('brands')
@@ -176,8 +165,7 @@ export async function updateBrand(
.select('*, brand_domains(*)')
.single();
- if (error || !data)
- throw new Error(error?.message ?? 'Failed to update brand');
+ if (error || !data) throw new Error(error?.message ?? 'Failed to update brand');
revalidatePath('/dashboard/brands');
return mapBrandRow(
@@ -315,8 +303,7 @@ export async function getBrandsCardSummary(
const cur = b.current.count > 0 ? b.current.sum / b.current.count : 0;
const prev = b.prev.count > 0 ? b.prev.sum / b.prev.count : 0;
summary[id].visibility7d = Math.round(cur);
- summary[id].visibilityDelta =
- prev > 0 ? Math.round(((cur - prev) / prev) * 100) : 0;
+ summary[id].visibilityDelta = prev > 0 ? Math.round(((cur - prev) / prev) * 100) : 0;
summary[id].mentions7d = b.current.mentions;
summary[id].trend = dayKeys.map((k) => {
const d = dailyByBrand[id][k];
diff --git a/web/src/lib/actions/citations.ts b/web/src/lib/actions/citations.ts
index 52e05810c..840bab09c 100644
--- a/web/src/lib/actions/citations.ts
+++ b/web/src/lib/actions/citations.ts
@@ -13,13 +13,7 @@ import { classifyArticleType } from '@/lib/citations/article-type';
// ─── Types ────────────────────────────────────────────────────────────────────
-export type CitationsDatePreset =
- | '24h'
- | '7d'
- | '30d'
- | '90d'
- | 'all'
- | 'custom';
+export type CitationsDatePreset = '24h' | '7d' | '30d' | '90d' | 'all' | 'custom';
export interface CitationsFilters {
datePreset: CitationsDatePreset;
@@ -82,9 +76,7 @@ export interface CitationsOverview {
// ─── Helpers ──────────────────────────────────────────────────────────────────
-function resolveDateRange(
- filters: CitationsFilters,
-): { from?: string; to?: string } {
+function resolveDateRange(filters: CitationsFilters): { from?: string; to?: string } {
if (filters.datePreset === 'custom') {
return { from: filters.dateFrom, to: filters.dateTo };
}
@@ -170,9 +162,7 @@ export async function getCitationsOverview(
// 3. Build filtered prompt_results query.
let query = supabase
.from('prompt_results')
- .select(
- 'id, prompt_id, platform, model_used, region, created_at, citations, citation_count',
- )
+ .select('id, prompt_id, platform, model_used, region, created_at, citations, citation_count')
.eq('brand_id', brandId);
const { from, to } = resolveDateRange(filters);
@@ -193,14 +183,10 @@ export async function getCitationsOverview(
.from('prompts')
.select('id')
.in('topic_id', filters.topicIds);
- const topicPromptIds = ((topicPrompts ?? []) as { id: string }[]).map(
- (p) => p.id,
- );
+ const topicPromptIds = ((topicPrompts ?? []) as { id: string }[]).map((p) => p.id);
query = query.in(
'prompt_id',
- topicPromptIds.length > 0
- ? topicPromptIds
- : ['00000000-0000-0000-0000-000000000000'],
+ topicPromptIds.length > 0 ? topicPromptIds : ['00000000-0000-0000-0000-000000000000'],
);
}
@@ -320,14 +306,9 @@ export async function getCitationsOverview(
models: Array.from(agg.models).sort(),
totalCitations: agg.totalCitations,
avgCitationsPerResult:
- resultsCiting > 0
- ? Math.round((agg.totalCitations / resultsCiting) * 10) / 10
- : 0,
+ resultsCiting > 0 ? Math.round((agg.totalCitations / resultsCiting) * 10) / 10 : 0,
resultsCiting,
- usagePct:
- totalResults > 0
- ? Math.round((resultsCiting / totalResults) * 1000) / 10
- : 0,
+ usagePct: totalResults > 0 ? Math.round((resultsCiting / totalResults) * 1000) / 10 : 0,
articleTypes,
};
})
@@ -344,10 +325,7 @@ export async function getCitationsOverview(
models: Array.from(agg.models).sort(),
totalCitations: agg.totalCitations,
resultsCiting,
- usagePct:
- totalResults > 0
- ? Math.round((resultsCiting / totalResults) * 1000) / 10
- : 0,
+ usagePct: totalResults > 0 ? Math.round((resultsCiting / totalResults) * 1000) / 10 : 0,
articleType: agg.articleType,
};
})
@@ -356,25 +334,17 @@ export async function getCitationsOverview(
// 6. Source type breakdown (all categories, even with zero).
const categoryCounts = new Map<SourceCategory, number>();
for (const row of rowsOut) {
- categoryCounts.set(
- row.category,
- (categoryCounts.get(row.category) ?? 0) + 1,
- );
+ categoryCounts.set(row.category, (categoryCounts.get(row.category) ?? 0) + 1);
}
const totalDomains = rowsOut.length;
- const sourceTypeBreakdown: CitationsSourceBreakdown[] = SOURCE_CATEGORIES.map(
- (category) => {
- const count = categoryCounts.get(category) ?? 0;
- return {
- category,
- count,
- pct:
- totalDomains > 0
- ? Math.round((count / totalDomains) * 1000) / 10
- : 0,
- };
- },
- ).filter((b) => b.count > 0);
+ const sourceTypeBreakdown: CitationsSourceBreakdown[] = SOURCE_CATEGORIES.map((category) => {
+ const count = categoryCounts.get(category) ?? 0;
+ return {
+ category,
+ count,
+ pct: totalDomains > 0 ? Math.round((count / totalDomains) * 1000) / 10 : 0,
+ };
+ }).filter((b) => b.count > 0);
return {
rows: rowsOut,
@@ -385,9 +355,7 @@ export async function getCitationsOverview(
citations: totalCitations,
results: totalResults,
avgCitationsPerResult:
- totalResults > 0
- ? Math.round((totalCitations / totalResults) * 10) / 10
- : 0,
+ totalResults > 0 ? Math.round((totalCitations / totalResults) * 10) / 10 : 0,
},
sourceTypeBreakdown,
};
diff --git a/web/src/lib/actions/competitor.ts b/web/src/lib/actions/competitor.ts
index 6883eb0b6..3517a945e 100644
--- a/web/src/lib/actions/competitor.ts
+++ b/web/src/lib/actions/competitor.ts
@@ -37,7 +37,10 @@ export async function addCompetitor(
.insert({
brand_id: brandId,
name: input.name.trim(),
- domain: input.domain.trim().replace(/^https?:\/\//, '').replace(/\/+$/, ''),
+ domain: input.domain
+ .trim()
+ .replace(/^https?:\/\//, '')
+ .replace(/\/+$/, ''),
})
.select()
.single();
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index d759cdedb..031db66a0 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -7,14 +7,14 @@ const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost';
async function getSession() {
const supabase = await createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) throw new Error('Not authenticated');
return session;
}
-export async function generateOpportunities(
- brandId: string,
-): Promise<{ jobId: string }> {
+export async function generateOpportunities(brandId: string): Promise<{ jobId: string }> {
const session = await getSession();
const res = await fetch(`${AEO_SERVER_URL}/api/content/generate`, {
@@ -61,9 +61,10 @@ export async function getGenerationJobStatus(jobId: string): Promise<GenerationJ
const data = await res.json();
return {
status: data.status ?? 'not_found',
- progress: data.progress && typeof data.progress === 'object' && data.progress.phase
- ? data.progress
- : null,
+ progress:
+ data.progress && typeof data.progress === 'object' && data.progress.phase
+ ? data.progress
+ : null,
result: data.result ?? null,
failedReason: data.failedReason ?? null,
};
@@ -127,9 +128,7 @@ export async function getOpportunity(id: string): Promise<ContentOpportunity> {
return res.json();
}
-export async function generateBrief(
- opportunityId: string,
-): Promise<ContentBrief> {
+export async function generateBrief(opportunityId: string): Promise<ContentBrief> {
const session = await getSession();
const res = await fetch(`${AEO_SERVER_URL}/api/content/${opportunityId}/brief`, {
@@ -240,9 +239,7 @@ export async function bulkUpdateStatus(
return res.json();
}
-export async function bulkSendToWebhook(
- ids: string[],
-): Promise<{ sent: number; failed: number }> {
+export async function bulkSendToWebhook(ids: string[]): Promise<{ sent: number; failed: number }> {
const session = await getSession();
const res = await fetch(`${AEO_SERVER_URL}/api/content/bulk/send-webhook`, {
diff --git a/web/src/lib/actions/organization.ts b/web/src/lib/actions/organization.ts
index 2db2e7c3e..edeaa1223 100644
--- a/web/src/lib/actions/organization.ts
+++ b/web/src/lib/actions/organization.ts
@@ -40,8 +40,7 @@ export async function createOrganization(name: string) {
.select()
.single();
- if (error || !org)
- throw new Error(error?.message ?? 'Failed to create organization');
+ if (error || !org) throw new Error(error?.message ?? 'Failed to create organization');
const { error: profileError } = await supabase
.from('profiles')
diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.ts
index 837ed1020..88b357d41 100644
--- a/web/src/lib/actions/prompt-suggestions.ts
+++ b/web/src/lib/actions/prompt-suggestions.ts
@@ -63,13 +63,10 @@ export async function getPromptSuggestions(
brandId: string,
): Promise<{ suggestions: PromptSuggestion[]; stale: boolean }> {
const session = await getSession();
- const res = await fetch(
- `${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}`,
- {
- headers: { Authorization: `Bearer ${session.access_token}` },
- cache: 'no-store',
- },
- );
+ const res = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}`, {
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || `Server error: ${res.status}`);
@@ -84,17 +81,12 @@ export async function getPromptSuggestions(
};
}
-export async function refreshPromptSuggestions(
- brandId: string,
-): Promise<PromptSuggestion[]> {
+export async function refreshPromptSuggestions(brandId: string): Promise<PromptSuggestion[]> {
const session = await getSession();
- const res = await fetch(
- `${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}/refresh`,
- {
- method: 'POST',
- headers: { Authorization: `Bearer ${session.access_token}` },
- },
- );
+ const res = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}/refresh`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || `Server error: ${res.status}`);
@@ -103,17 +95,12 @@ export async function refreshPromptSuggestions(
return data.suggestions.map(mapRow);
}
-export async function dismissSuggestion(
- suggestionId: string,
-): Promise<{ success: boolean }> {
+export async function dismissSuggestion(suggestionId: string): Promise<{ success: boolean }> {
const session = await getSession();
- const res = await fetch(
- `${AEO_SERVER_URL}/api/prompts/suggestions/${suggestionId}/dismiss`,
- {
- method: 'POST',
- headers: { Authorization: `Bearer ${session.access_token}` },
- },
- );
+ const res = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${suggestionId}/dismiss`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || `Server error: ${res.status}`);
@@ -164,8 +151,7 @@ export async function acceptSuggestion(
? (defaults!.platforms as string[])
: ['chatgpt-web']);
const models =
- options?.models ??
- (Array.isArray(defaults?.models) ? (defaults!.models as string[]) : []);
+ options?.models ?? (Array.isArray(defaults?.models) ? (defaults!.models as string[]) : []);
const created = await addPromptToSet({
promptSetId: ps.id,
@@ -175,22 +161,16 @@ export async function acceptSuggestion(
models,
});
- const ack = await fetch(
- `${AEO_SERVER_URL}/api/prompts/suggestions/${suggestionId}/accept`,
- {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${session.access_token}`,
- },
- body: JSON.stringify({ promptId: created.id }),
+ const ack = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${suggestionId}/accept`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
},
- );
+ body: JSON.stringify({ promptId: created.id }),
+ });
if (!ack.ok) {
- console.error(
- '[prompt-suggestions] accept ack failed:',
- await ack.text().catch(() => ''),
- );
+ console.error('[prompt-suggestions] accept ack failed:', await ack.text().catch(() => ''));
}
revalidatePath('/dashboard/prompts');
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index 36f68bee6..056aa4761 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -112,10 +112,7 @@ export async function getPromptSets(brandId: string): Promise<PromptSet[]> {
if (error) throw new Error(error.message);
return (data ?? []).map((ps) =>
- mapPromptSetRow(
- ps as Record<string, unknown>,
- (ps.prompts as Record<string, unknown>[]) ?? [],
- ),
+ mapPromptSetRow(ps as Record<string, unknown>, (ps.prompts as Record<string, unknown>[]) ?? []),
);
}
@@ -183,7 +180,9 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<PromptSe
let insertedPrompts: Record<string, unknown>[] = [];
if (input.prompts.length > 0) {
- const categories = [...new Set(input.prompts.map((p) => p.category).filter(Boolean))] as string[];
+ const categories = [
+ ...new Set(input.prompts.map((p) => p.category).filter(Boolean)),
+ ] as string[];
const topicIdMap = new Map<string, string>();
await Promise.all(
categories.map(async (cat) => {
@@ -198,9 +197,7 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<PromptSe
input.prompts.map((p) => {
const filtered = filterByPlan(plan, p.platforms, p.models ?? []);
if (filtered.platforms.length === 0 && filtered.models.length === 0) {
- throw new Error(
- 'At least one platform or model must be selected for each prompt.',
- );
+ throw new Error('At least one platform or model must be selected for each prompt.');
}
return {
prompt_set_id: set.id,
@@ -260,22 +257,14 @@ export async function updatePrompt(
.select('prompt_sets!inner(brands!inner(organization_id))')
.eq('id', id)
.single();
- const orgId = (
- (promptRow?.prompt_sets as { brands: { organization_id: string } })
- ?.brands?.organization_id
- );
+ const orgId = (promptRow?.prompt_sets as { brands: { organization_id: string } })?.brands
+ ?.organization_id;
if (!orgId) throw new Error('Prompt not found');
const plan = await getOrgPlan(orgId);
- const filtered = filterByPlan(
- plan,
- updates.platforms ?? [],
- updates.models ?? [],
- );
+ const filtered = filterByPlan(plan, updates.platforms ?? [], updates.models ?? []);
if (filtered.platforms.length === 0 && filtered.models.length === 0) {
- throw new Error(
- 'At least one platform or model must be selected.',
- );
+ throw new Error('At least one platform or model must be selected.');
}
if (updates.platforms !== undefined) payload.platforms = filtered.platforms;
if (updates.models !== undefined) payload.models = filtered.models;
diff --git a/web/src/lib/actions/team.ts b/web/src/lib/actions/team.ts
index 1c39579a7..3b8067f4e 100644
--- a/web/src/lib/actions/team.ts
+++ b/web/src/lib/actions/team.ts
@@ -71,19 +71,18 @@ async function requireAdmin() {
export async function getTeamInfo(): Promise<TeamInfo> {
const { profile } = await getCurrentUserAndOrg();
- const [{ count: memberCount }, { count: pendingCount }, plan] =
- await Promise.all([
- supabaseAdmin
- .from('profiles')
- .select('*', { count: 'exact', head: true })
- .eq('organization_id', profile.organization_id),
- supabaseAdmin
- .from('invitations')
- .select('*', { count: 'exact', head: true })
- .eq('organization_id', profile.organization_id)
- .eq('status', 'pending'),
- getOrgPlan(profile.organization_id),
- ]);
+ const [{ count: memberCount }, { count: pendingCount }, plan] = await Promise.all([
+ supabaseAdmin
+ .from('profiles')
+ .select('*', { count: 'exact', head: true })
+ .eq('organization_id', profile.organization_id),
+ supabaseAdmin
+ .from('invitations')
+ .select('*', { count: 'exact', head: true })
+ .eq('organization_id', profile.organization_id)
+ .eq('status', 'pending'),
+ getOrgPlan(profile.organization_id),
+ ]);
const mc = memberCount ?? 0;
const pc = pendingCount ?? 0;
@@ -187,11 +186,8 @@ export async function inviteMember(email: string, role: TeamRole) {
.limit(1);
if (existingMember && existingMember.length > 0) {
- const { data: authUsers } =
- await supabaseAdmin.auth.admin.listUsers({ page: 1, perPage: 200 });
- const matched = authUsers?.users?.find(
- (u) => u.email?.toLowerCase() === normalizedEmail,
- );
+ const { data: authUsers } = await supabaseAdmin.auth.admin.listUsers({ page: 1, perPage: 200 });
+ const matched = authUsers?.users?.find((u) => u.email?.toLowerCase() === normalizedEmail);
if (matched) {
const { data: matchedProfile } = await supabaseAdmin
.from('profiles')
@@ -273,9 +269,7 @@ export async function resendInvitation(invitationId: string) {
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
const inviteLink = `${appUrl}/invite/${invitation.token}`;
- const newExpiresAt = new Date(
- Date.now() + 7 * 24 * 60 * 60 * 1000,
- ).toISOString();
+ const newExpiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();
await supabaseAdmin
.from('invitations')
.update({ expires_at: newExpiresAt })
@@ -333,9 +327,7 @@ export interface AcceptInvitationResult {
role: TeamRole;
}
-export async function acceptInvitation(
- token: string,
-): Promise<AcceptInvitationResult> {
+export async function acceptInvitation(token: string): Promise<AcceptInvitationResult> {
const supabase = await createClient();
const {
data: { user },
@@ -357,19 +349,14 @@ export async function acceptInvitation(
const expiresAt = new Date(invitation.expires_at as string);
if (expiresAt.getTime() < Date.now()) {
- await supabaseAdmin
- .from('invitations')
- .update({ status: 'expired' })
- .eq('id', invitation.id);
+ await supabaseAdmin.from('invitations').update({ status: 'expired' }).eq('id', invitation.id);
throw new Error('This invitation has expired');
}
const inviteEmail = (invitation.email as string).toLowerCase();
const userEmail = user.email?.toLowerCase() ?? '';
if (inviteEmail !== userEmail) {
- throw new Error(
- `This invitation was sent to ${inviteEmail}. Please sign in with that email.`,
- );
+ throw new Error(`This invitation was sent to ${inviteEmail}. Please sign in with that email.`);
}
const { error: profileErr } = await supabaseAdmin
@@ -402,9 +389,7 @@ export async function acceptInvitation(
export async function getInvitationByToken(token: string) {
const { data, error } = await supabaseAdmin
.from('invitations')
- .select(
- 'id, email, role, status, expires_at, organization_id, organizations(name)',
- )
+ .select('id, email, role, status, expires_at, organization_id, organizations(name)')
.eq('token', token)
.maybeSingle();
@@ -417,7 +402,6 @@ export async function getInvitationByToken(token: string) {
status: data.status as TeamInvitation['status'],
expiresAt: data.expires_at as string,
organizationId: data.organization_id as string,
- organizationName:
- (data.organizations as unknown as { name: string } | null)?.name ?? null,
+ organizationName: (data.organizations as unknown as { name: string } | null)?.name ?? null,
};
}
diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.ts
index 685379b45..167dde9e9 100644
--- a/web/src/lib/actions/topic.ts
+++ b/web/src/lib/actions/topic.ts
@@ -13,10 +13,7 @@ function mapTopicRow(row: Record<string, unknown>): Topic {
};
}
-export async function createTopics(
- brandId: string,
- names: string[],
-): Promise<Topic[]> {
+export async function createTopics(brandId: string, names: string[]): Promise<Topic[]> {
const supabase = await createClient();
// Remove existing topics for this brand to avoid duplicates
@@ -28,10 +25,7 @@ export async function createTopics(
name: name.trim(),
}));
- const { data, error } = await supabase
- .from('topics')
- .insert(rows)
- .select();
+ const { data, error } = await supabase.from('topics').insert(rows).select();
if (error) throw new Error(error.message);
return (data ?? []).map((r) => mapTopicRow(r as Record<string, unknown>));
@@ -51,10 +45,7 @@ export async function getTopics(brandId: string): Promise<Topic[]> {
return (data ?? []).map((r) => mapTopicRow(r as Record<string, unknown>));
}
-export async function createTopic(
- brandId: string,
- name: string,
-): Promise<Topic> {
+export async function createTopic(brandId: string, name: string): Promise<Topic> {
const supabase = await createClient();
const { data, error } = await supabase
@@ -67,10 +58,7 @@ export async function createTopic(
return mapTopicRow(data as Record<string, unknown>);
}
-export async function updateTopic(
- topicId: string,
- name: string,
-): Promise<Topic> {
+export async function updateTopic(topicId: string, name: string): Promise<Topic> {
const supabase = await createClient();
const { data, error } = await supabase
@@ -84,16 +72,10 @@ export async function updateTopic(
return mapTopicRow(data as Record<string, unknown>);
}
-export async function getPromptCountByTopic(
- brandId: string,
- topicName: string,
-): Promise<number> {
+export async function getPromptCountByTopic(brandId: string, topicName: string): Promise<number> {
const supabase = await createClient();
- const { data: sets } = await supabase
- .from('prompt_sets')
- .select('id')
- .eq('brand_id', brandId);
+ const { data: sets } = await supabase.from('prompt_sets').select('id').eq('brand_id', brandId);
if (!sets || sets.length === 0) return 0;
@@ -136,9 +118,7 @@ export interface TopicOverviewSummary {
* Change is computed as (current 7d avg) - (previous 7d avg) to mirror
* the logic used by Insights KPI cards.
*/
-export async function getTopicsOverview(
- brandId: string,
-): Promise<TopicOverviewSummary> {
+export async function getTopicsOverview(brandId: string): Promise<TopicOverviewSummary> {
const supabase = await createClient();
const now = Date.now();
@@ -153,10 +133,7 @@ export async function getTopicsOverview(
.eq('brand_id', brandId)
.eq('is_active', true)
.order('created_at', { ascending: true }),
- supabase
- .from('prompts')
- .select('id, topic_id, prompt_set_id')
- .eq('is_active', true),
+ supabase.from('prompts').select('id, topic_id, prompt_set_id').eq('is_active', true),
supabase
.from('prompt_results')
.select(
@@ -187,9 +164,7 @@ export async function getTopicsOverview(
.from('prompt_sets')
.select('id')
.eq('brand_id', brandId);
- const brandSetIds = new Set(
- ((brandSets ?? []) as { id: string }[]).map((s) => s.id),
- );
+ const brandSetIds = new Set(((brandSets ?? []) as { id: string }[]).map((s) => s.id));
const prompts = allPrompts.filter((p) => brandSetIds.has(p.prompt_set_id));
const promptTopicMap = new Map<string, string | null>();
@@ -239,10 +214,7 @@ export async function getTopicsOverview(
const promptCountByTopic = new Map<string, number>();
for (const p of prompts) {
if (!p.topic_id) continue;
- promptCountByTopic.set(
- p.topic_id,
- (promptCountByTopic.get(p.topic_id) ?? 0) + 1,
- );
+ promptCountByTopic.set(p.topic_id, (promptCountByTopic.get(p.topic_id) ?? 0) + 1);
}
for (const row of results) {
@@ -305,18 +277,12 @@ export async function getTopicsOverview(
const avg = agg.allCount > 0 ? Math.round(agg.allScoreSum / agg.allCount) : 0;
const change =
agg.curCount > 0 && agg.prevCount > 0
- ? Math.round(
- (agg.curScoreSum / agg.curCount -
- agg.prevScoreSum / agg.prevCount) *
- 10,
- ) / 10
+ ? Math.round((agg.curScoreSum / agg.curCount - agg.prevScoreSum / agg.prevCount) * 10) / 10
: null;
const totalForSov = agg.brandMentions + agg.compMentions;
const shareOfVoice =
- totalForSov > 0
- ? Math.round((agg.brandMentions / totalForSov) * 1000) / 10
- : 0;
+ totalForSov > 0 ? Math.round((agg.brandMentions / totalForSov) * 1000) / 10 : 0;
let topCompetitor: TopicOverviewRow['topCompetitor'] = null;
if (totalForSov > 0 && agg.competitors.size > 0) {
@@ -334,9 +300,7 @@ export async function getTopicsOverview(
const d = new Date(todayMs - i * 24 * 60 * 60 * 1000);
const key = d.toISOString().slice(0, 10);
const bucket = agg.daily.get(key);
- sparklineDays.push(
- bucket && bucket.count > 0 ? Math.round(bucket.sum / bucket.count) : 0,
- );
+ sparklineDays.push(bucket && bucket.count > 0 ? Math.round(bucket.sum / bucket.count) : 0);
}
return {
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index a211772c5..47d726a9a 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -1,13 +1,7 @@
'use server';
import { createClient } from '@/lib/supabase/server';
-import type {
- PromptResult,
- AIPlatform,
- Sentiment,
- Citation,
- CompetitorMention,
-} from '@/types';
+import type { PromptResult, AIPlatform, Sentiment, Citation, CompetitorMention } from '@/types';
/**
* Apply the `model` filter to a Supabase query against `prompt_results.model_used`.
@@ -18,10 +12,7 @@ import type {
* filter dropdown.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function applyModelFilter<T extends { eq: any; in: any }>(
- query: T,
- model: string | undefined,
-): T {
+function applyModelFilter<T extends { eq: any; in: any }>(query: T, model: string | undefined): T {
if (!model) return query;
const list = model
.split(',')
@@ -45,8 +36,7 @@ function mapResultRow(row: Record<string, unknown>): PromptResult {
visibilityScore: row.visibility_score as number,
modelUsed: (row.model_used as string | null) ?? undefined,
region: (row.region as string | null) ?? undefined,
- competitorMentions:
- (row.competitor_mentions as CompetitorMention[] | null) ?? undefined,
+ competitorMentions: (row.competitor_mentions as CompetitorMention[] | null) ?? undefined,
createdAt: row.created_at as string,
};
}
@@ -113,10 +103,7 @@ async function buildResultsQuery(
},
) {
const supabase = await createClient();
- let query = supabase
- .from('prompt_results')
- .select('*')
- .eq('brand_id', brandId);
+ let query = supabase.from('prompt_results').select('*').eq('brand_id', brandId);
if (opts?.platform) query = query.eq('platform', opts.platform);
query = applyModelFilter(query, opts?.model);
@@ -130,15 +117,11 @@ async function buildResultsQuery(
.from('prompts')
.select('id')
.eq('topic_id', opts.topicId);
- const topicPromptIds = ((topicPrompts ?? []) as { id: string }[]).map(
- (p) => p.id,
- );
+ const topicPromptIds = ((topicPrompts ?? []) as { id: string }[]).map((p) => p.id);
// Use a sentinel that matches nothing when the topic has no prompts so results are empty.
query = query.in(
'prompt_id',
- topicPromptIds.length > 0
- ? topicPromptIds
- : ['00000000-0000-0000-0000-000000000000'],
+ topicPromptIds.length > 0 ? topicPromptIds : ['00000000-0000-0000-0000-000000000000'],
);
}
@@ -174,33 +157,20 @@ export async function getPromptResults(
const promptIds = [...new Set(rows.map((r) => r.prompt_id as string))];
const { data: promptRows } =
promptIds.length > 0
- ? await supabase
- .from('prompts')
- .select('id, text, category, topic_id')
- .in('id', promptIds)
+ ? await supabase.from('prompts').select('id, text, category, topic_id').in('id', promptIds)
: { data: [] };
- const promptRowsRaw = (promptRows ?? []) as unknown as Record<
- string,
- unknown
- >[];
+ const promptRowsRaw = (promptRows ?? []) as unknown as Record<string, unknown>[];
const topicIds = [
- ...new Set(
- promptRowsRaw
- .map((p) => p.topic_id as string | null)
- .filter(Boolean) as string[],
- ),
+ ...new Set(promptRowsRaw.map((p) => p.topic_id as string | null).filter(Boolean) as string[]),
];
const { data: topicRows } =
topicIds.length > 0
? await supabase.from('topics').select('id, name').in('id', topicIds)
: { data: [] };
const topicMap = new Map(
- ((topicRows ?? []) as Record<string, unknown>[]).map((t) => [
- t.id as string,
- t.name as string,
- ]),
+ ((topicRows ?? []) as Record<string, unknown>[]).map((t) => [t.id as string, t.name as string]),
);
const promptMap = new Map(
@@ -226,9 +196,7 @@ export async function getPromptResults(
promptCategory: (pm?.category as string | null) ?? undefined,
topicId: (pm?.topicId as string | null) ?? undefined,
topicName: pm?.topicId
- ? (topicMap.get(pm.topicId) ??
- (pm?.category as string | null) ??
- undefined)
+ ? (topicMap.get(pm.topicId) ?? (pm?.category as string | null) ?? undefined)
: ((pm?.category as string | null) ?? undefined),
};
});
@@ -239,9 +207,7 @@ export async function getPromptResults(
/**
* Fetch a single prompt result by its ID, joining prompt text.
*/
-export async function getPromptResultById(
- resultId: string,
-): Promise<PromptResultWithText | null> {
+export async function getPromptResultById(resultId: string): Promise<PromptResultWithText | null> {
const supabase = await createClient();
const { data, error } = await supabase
@@ -294,9 +260,7 @@ export async function getPromptDetail(
const { data: promptData, error: promptError } = await supabase
.from('prompts')
- .select(
- 'id, prompt_set_id, text, category, topic_id, is_active, created_at',
- )
+ .select('id, prompt_set_id, text, category, topic_id, is_active, created_at')
.eq('id', promptId)
.single();
@@ -347,10 +311,7 @@ export async function getPromptDetail(
const totalResults = results.length;
const avgVisibilityScore =
totalResults > 0
- ? Math.round(
- results.reduce((sum, row) => sum + row.visibilityScore, 0) /
- totalResults,
- )
+ ? Math.round(results.reduce((sum, row) => sum + row.visibilityScore, 0) / totalResults)
: 0;
return {
@@ -415,14 +376,8 @@ export async function getInsightsSummary(
const avgVisibilityScore = Math.round(
rows.reduce((s, r) => s + (r.visibility_score as number), 0) / totalResults,
);
- const totalMentions = rows.reduce(
- (s, r) => s + (r.mention_count as number),
- 0,
- );
- const totalCitations = rows.reduce(
- (s, r) => s + (r.citation_count as number),
- 0,
- );
+ const totalMentions = rows.reduce((s, r) => s + (r.mention_count as number), 0);
+ const totalCitations = rows.reduce((s, r) => s + (r.citation_count as number), 0);
const positiveCount = rows.filter((r) => r.sentiment === 'positive').length;
const positiveSentimentPct = Math.round((positiveCount / totalResults) * 100);
@@ -441,13 +396,11 @@ export async function getInsightsSummary(
modelMap.set(m, existing);
}
- const platformBreakdown = Array.from(modelMap.entries()).map(
- ([model, data]) => ({
- platform: model,
- avgScore: Math.round(data.totalScore / data.count),
- resultCount: data.count,
- }),
- );
+ const platformBreakdown = Array.from(modelMap.entries()).map(([model, data]) => ({
+ platform: model,
+ avgScore: Math.round(data.totalScore / data.count),
+ resultCount: data.count,
+ }));
// --- Previous period comparison ---
let visibilityChange: number | null = null;
@@ -475,10 +428,7 @@ export async function getInsightsSummary(
? opts
: { ...opts, dateFrom: currentFrom.toISOString() };
- const { query: curQuery } = await buildResultsQuery(
- brandId,
- currentFilterOpts,
- );
+ const { query: curQuery } = await buildResultsQuery(brandId, currentFilterOpts);
const { data: curResults } = await curQuery;
const curRows = (curResults ?? []) as Record<string, unknown>[];
@@ -494,38 +444,20 @@ export async function getInsightsSummary(
if (curRows.length > 0 && prevRows.length > 0) {
const curTotal = curRows.length;
const curAvgVis = Math.round(
- curRows.reduce((s, r) => s + (r.visibility_score as number), 0) /
- curTotal,
+ curRows.reduce((s, r) => s + (r.visibility_score as number), 0) / curTotal,
);
- const curMentions = curRows.reduce(
- (s, r) => s + (r.mention_count as number),
- 0,
- );
- const curCitations = curRows.reduce(
- (s, r) => s + (r.citation_count as number),
- 0,
- );
- const curPositive = curRows.filter(
- (r) => r.sentiment === 'positive',
- ).length;
+ const curMentions = curRows.reduce((s, r) => s + (r.mention_count as number), 0);
+ const curCitations = curRows.reduce((s, r) => s + (r.citation_count as number), 0);
+ const curPositive = curRows.filter((r) => r.sentiment === 'positive').length;
const curSentimentPct = Math.round((curPositive / curTotal) * 100);
const prevTotal = prevRows.length;
const prevAvgVis = Math.round(
- prevRows.reduce((s, r) => s + (r.visibility_score as number), 0) /
- prevTotal,
- );
- const prevMentions = prevRows.reduce(
- (s, r) => s + (r.mention_count as number),
- 0,
+ prevRows.reduce((s, r) => s + (r.visibility_score as number), 0) / prevTotal,
);
- const prevCitations = prevRows.reduce(
- (s, r) => s + (r.citation_count as number),
- 0,
- );
- const prevPositive = prevRows.filter(
- (r) => r.sentiment === 'positive',
- ).length;
+ const prevMentions = prevRows.reduce((s, r) => s + (r.mention_count as number), 0);
+ const prevCitations = prevRows.reduce((s, r) => s + (r.citation_count as number), 0);
+ const prevPositive = prevRows.filter((r) => r.sentiment === 'positive').length;
const prevSentimentPct = Math.round((prevPositive / prevTotal) * 100);
visibilityChange = curAvgVis - prevAvgVis;
@@ -595,13 +527,7 @@ export async function triggerTrackingCheck(
}
export interface TrackingJobStatus {
- status:
- | 'waiting'
- | 'active'
- | 'completed'
- | 'failed'
- | 'delayed'
- | 'not_found';
+ status: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'not_found';
progress: {
current: number;
total: number;
@@ -648,9 +574,7 @@ export async function getJobStatus(jobId: string): Promise<TrackingJobStatus> {
return {
status: data.status ?? 'not_found',
progress:
- data.progress &&
- typeof data.progress === 'object' &&
- data.progress.total
+ data.progress && typeof data.progress === 'object' && data.progress.total
? data.progress
: null,
result: data.result ?? null,
@@ -761,9 +685,7 @@ export async function getPromptVisibilitySummaries(
*/
export async function getBrandPrompts(
brandId: string,
-): Promise<
- { id: string; text: string; category?: string; platforms: string[] }[]
-> {
+): Promise<{ id: string; text: string; category?: string; platforms: string[] }[]> {
const supabase = await createClient();
const { data: promptSets } = await supabase
@@ -838,10 +760,7 @@ const SCRAPER_PROVIDER: Record<string, string> = {
'gemini-web': 'Gemini',
};
-function resolveProvider(
- modelUsed: string | null | undefined,
- platform?: string | null,
-): string {
+function resolveProvider(modelUsed: string | null | undefined, platform?: string | null): string {
if (platform && SCRAPER_PROVIDER[platform]) return SCRAPER_PROVIDER[platform];
if (!modelUsed) return 'Unknown';
const mapped = MODEL_TO_PROVIDER[modelUsed];
@@ -870,11 +789,7 @@ export async function getCompetitorComparison(
): Promise<CompetitorComparisonData> {
const supabase = await createClient();
- const { data: brand } = await supabase
- .from('brands')
- .select('name')
- .eq('id', brandId)
- .single();
+ const { data: brand } = await supabase.from('brands').select('name').eq('id', brandId).single();
const { query } = await buildResultsQuery(brandId, opts);
const { data: results, error } = await query;
@@ -915,10 +830,7 @@ export async function getCompetitorComparison(
const [curRes, prevRes] = await Promise.all([
(async () => {
- const { query: curQuery } = await buildResultsQuery(
- brandId,
- currentFilterOpts,
- );
+ const { query: curQuery } = await buildResultsQuery(brandId, currentFilterOpts);
return curQuery;
})(),
(async () => {
@@ -935,19 +847,12 @@ export async function getCompetitorComparison(
const prevRows = (prevRes.data ?? []) as Record<string, unknown>[];
if (curRows.length > 0) {
- const curTotal = curRows.reduce(
- (s, r) => s + (r.visibility_score as number),
- 0,
- );
+ const curTotal = curRows.reduce((s, r) => s + (r.visibility_score as number), 0);
curBrandAvg = curTotal / curRows.length;
- const curCompMap = new Map<
- string,
- { totalScore: number; count: number }
- >();
+ const curCompMap = new Map<string, { totalScore: number; count: number }>();
for (const row of curRows) {
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
for (const cm of mentions) {
const ex = curCompMap.get(cm.competitor_id) ?? {
totalScore: 0,
@@ -964,19 +869,12 @@ export async function getCompetitorComparison(
}
if (prevRows.length > 0) {
- const prevTotal = prevRows.reduce(
- (s, r) => s + (r.visibility_score as number),
- 0,
- );
+ const prevTotal = prevRows.reduce((s, r) => s + (r.visibility_score as number), 0);
prevBrandAvg = prevTotal / prevRows.length;
- const prevCompMap = new Map<
- string,
- { totalScore: number; count: number }
- >();
+ const prevCompMap = new Map<string, { totalScore: number; count: number }>();
for (const row of prevRows) {
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
for (const cm of mentions) {
const ex = prevCompMap.get(cm.competitor_id) ?? {
totalScore: 0,
@@ -996,26 +894,14 @@ export async function getCompetitorComparison(
const brandName = (brand?.name as string) ?? 'Your Brand';
// --- Flat brand-level aggregates ---
- const brandTotalScore = rows.reduce(
- (s, r) => s + (r.visibility_score as number),
- 0,
- );
- const brandTotalMentions = rows.reduce(
- (s, r) => s + (r.mention_count as number),
- 0,
- );
- const brandTotalCitations = rows.reduce(
- (s, r) => s + (r.citation_count as number),
- 0,
- );
+ const brandTotalScore = rows.reduce((s, r) => s + (r.visibility_score as number), 0);
+ const brandTotalMentions = rows.reduce((s, r) => s + (r.mention_count as number), 0);
+ const brandTotalCitations = rows.reduce((s, r) => s + (r.citation_count as number), 0);
const brandAvg = Math.round(brandTotalScore / rows.length);
// Percentage change relative to the previous-period value.
// Null when no comparable previous value exists (or growth from 0 → x is undefined).
- const pctChange = (
- cur: number | null,
- prev: number | null,
- ): number | null => {
+ const pctChange = (cur: number | null, prev: number | null): number | null => {
if (cur === null || prev === null) return null;
if (prev === 0) return cur === 0 ? 0 : null;
return Math.round(((cur - prev) / prev) * 1000) / 10;
@@ -1046,8 +932,7 @@ export async function getCompetitorComparison(
>();
for (const row of rows) {
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
for (const cm of mentions) {
const existing = compMap.get(cm.competitor_id) ?? {
id: cm.competitor_id,
@@ -1100,8 +985,7 @@ export async function getCompetitorComparison(
bp.count += 1;
brandByProvider.set(provider, bp);
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
for (const cm of mentions) {
if (!compByProvider.has(cm.name)) compByProvider.set(cm.name, new Map());
const pm = compByProvider.get(cm.name)!;
@@ -1118,21 +1002,19 @@ export async function getCompetitorComparison(
for (const p of pm.keys()) allProviders.add(p);
}
- const providerRows: ProviderComparisonRow[] = [...allProviders]
- .sort()
- .map((provider) => {
- const row: ProviderComparisonRow = { provider };
+ const providerRows: ProviderComparisonRow[] = [...allProviders].sort().map((provider) => {
+ const row: ProviderComparisonRow = { provider };
- const bp = brandByProvider.get(provider);
- row[brandName] = bp ? Math.round(bp.totalScore / bp.count) : 0;
+ const bp = brandByProvider.get(provider);
+ row[brandName] = bp ? Math.round(bp.totalScore / bp.count) : 0;
- for (const [compName, pm] of compByProvider) {
- const cp = pm.get(provider);
- row[compName] = cp ? Math.round(cp.totalScore / cp.count) : 0;
- }
+ for (const [compName, pm] of compByProvider) {
+ const cp = pm.get(provider);
+ row[compName] = cp ? Math.round(cp.totalScore / cp.count) : 0;
+ }
- return row;
- });
+ return row;
+ });
return { brands: entries, providerRows };
}
@@ -1203,8 +1085,7 @@ export async function getShareOfVoiceData(
};
pa.brandMentions += brandM;
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
let rowCompMentions = 0;
for (const cm of mentions) {
rowCompMentions += cm.mention_count;
@@ -1222,8 +1103,7 @@ export async function getShareOfVoiceData(
}
const totalAll = totalBrandMentions + totalCompMentions;
- const overallSov =
- totalAll > 0 ? Math.round((totalBrandMentions / totalAll) * 1000) / 10 : 0;
+ const overallSov = totalAll > 0 ? Math.round((totalBrandMentions / totalAll) * 1000) / 10 : 0;
// --- By platform ---
const byPlatform: SoVByPlatform[] = [...providerMap.entries()]
@@ -1233,8 +1113,7 @@ export async function getShareOfVoiceData(
provider,
brandMentions: agg.brandMentions,
competitorMentions: agg.competitorMentions,
- sov:
- total > 0 ? Math.round((agg.brandMentions / total) * 1000) / 10 : 0,
+ sov: total > 0 ? Math.round((agg.brandMentions / total) * 1000) / 10 : 0,
};
})
.sort((a, b) => b.sov - a.sov);
@@ -1244,10 +1123,8 @@ export async function getShareOfVoiceData(
const trend: SoVTrendPoint[] = sortedDays.map((day) => {
const d = dayMap.get(day)!;
const total = d.brandMentions + d.competitorMentions;
- const brandSov =
- total > 0 ? Math.round((d.brandMentions / total) * 1000) / 10 : 0;
- const competitorSov =
- total > 0 ? Math.round((d.competitorMentions / total) * 1000) / 10 : 0;
+ const brandSov = total > 0 ? Math.round((d.brandMentions / total) * 1000) / 10 : 0;
+ const competitorSov = total > 0 ? Math.round((d.competitorMentions / total) * 1000) / 10 : 0;
const dateObj = new Date(day + 'T00:00:00');
const label = dateObj.toLocaleDateString('en-US', {
month: 'short',
@@ -1289,13 +1166,11 @@ export async function getShareOfVoiceData(
let prevCompM = 0;
for (const row of prevRows) {
prevBrandM += row.mention_count as number;
- const cms =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const cms = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
for (const cm of cms) prevCompM += cm.mention_count;
}
const prevTotal = prevBrandM + prevCompM;
- const prevSov =
- prevTotal > 0 ? Math.round((prevBrandM / prevTotal) * 1000) / 10 : 0;
+ const prevSov = prevTotal > 0 ? Math.round((prevBrandM / prevTotal) * 1000) / 10 : 0;
overallSovChange = Math.round((overallSov - prevSov) * 10) / 10;
}
}
@@ -1342,10 +1217,7 @@ export async function getVisibilityTrend(
.select('id')
.eq('topic_id', opts.topicId);
const ids = ((topicPrompts ?? []) as { id: string }[]).map((p) => p.id);
- query = query.in(
- 'prompt_id',
- ids.length > 0 ? ids : ['00000000-0000-0000-0000-000000000000'],
- );
+ query = query.in('prompt_id', ids.length > 0 ? ids : ['00000000-0000-0000-0000-000000000000']);
}
const { data, error } = await query;
@@ -1376,8 +1248,7 @@ export async function getVisibilityTrend(
entry.totalScore += row.visibility_score as number;
entry.count += 1;
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
for (const cm of mentions) {
entry.compTotalScore += cm.visibility_score;
entry.compCount += 1;
@@ -1400,8 +1271,7 @@ export async function getVisibilityTrend(
points.push({
date: label,
score: Math.round(d.totalScore / d.count),
- competitors:
- d.compCount > 0 ? Math.round(d.compTotalScore / d.compCount) : null,
+ competitors: d.compCount > 0 ? Math.round(d.compTotalScore / d.compCount) : null,
});
}
@@ -1479,10 +1349,7 @@ export async function getHeadToHeadComparison(
const promptIds = [...new Set(rows.map((r) => r.prompt_id as string))];
const { data: promptData } =
promptIds.length > 0
- ? await supabase
- .from('prompts')
- .select('id, text, category')
- .in('id', promptIds)
+ ? await supabase.from('prompts').select('id, text, category').in('id', promptIds)
: { data: [] };
const promptMap = new Map(
(promptData ?? []).map((p) => [
@@ -1515,8 +1382,7 @@ export async function getHeadToHeadComparison(
row.model_used as string | null,
row.platform as string | null,
);
- const mentions =
- (row.competitor_mentions as CompetitorMention[] | null) ?? [];
+ const mentions = (row.competitor_mentions as CompetitorMention[] | null) ?? [];
const comp = mentions.find((cm) => cm.competitor_id === competitorId);
const compScore = comp?.visibility_score ?? 0;
@@ -1575,10 +1441,8 @@ export async function getHeadToHeadComparison(
})
.sort((a, b) => a.platform.localeCompare(b.platform));
- const brandAvg =
- brandCount > 0 ? Math.round(brandTotalScore / brandCount) : 0;
- const competitorAvg =
- compCount > 0 ? Math.round(compTotalScore / compCount) : 0;
+ const brandAvg = brandCount > 0 ? Math.round(brandTotalScore / brandCount) : 0;
+ const competitorAvg = compCount > 0 ? Math.round(compTotalScore / compCount) : 0;
const sorted = [...promptRows].sort((a, b) => a.diff - b.diff);
const gaps = sorted.filter((r) => r.diff < 0).slice(0, 10);
@@ -1771,10 +1635,7 @@ export async function getInsightsBreakdown(
.in('id', [...allPromptIds])
: { data: [] as unknown[] };
- const promptInfo = new Map<
- string,
- { text: string; topicId: string | null }
- >();
+ const promptInfo = new Map<string, { text: string; topicId: string | null }>();
const topicIds = new Set<string>();
for (const p of (promptRowsRaw ?? []) as Array<{
id: string;
@@ -1826,11 +1687,7 @@ export async function getInsightsBreakdown(
const rows: BreakdownRow[] = keys.map((key) => {
const curAgg = aggregateMetric(curMap.get(key) ?? [], metric);
const prevAgg = aggregateMetric(prevMap.get(key) ?? [], metric);
- const { delta, deltaPct } = computeDelta(
- curAgg.value,
- prevAgg.value,
- metric,
- );
+ const { delta, deltaPct } = computeDelta(curAgg.value, prevAgg.value, metric);
const { id, label, sublabel } = resolver(key);
return {
id,
@@ -1853,9 +1710,7 @@ export async function getInsightsBreakdown(
const prevByPrompt = groupBy(prevRows, (r) => r.prompt_id);
const byPrompt = buildRows(curByPrompt, prevByPrompt, (pid) => {
const info = promptInfo.get(pid);
- const topicName = info?.topicId
- ? topicNameById.get(info.topicId)
- : undefined;
+ const topicName = info?.topicId ? topicNameById.get(info.topicId) : undefined;
return {
id: pid,
label: info?.text ?? 'Unknown prompt',
@@ -1881,9 +1736,7 @@ export async function getInsightsBreakdown(
const byTopic = buildRows(curByTopic, prevByTopic, (tid) => ({
id: tid,
label:
- tid === '__uncategorized__'
- ? 'Uncategorized'
- : (topicNameById.get(tid) ?? 'Unknown topic'),
+ tid === '__uncategorized__' ? 'Uncategorized' : (topicNameById.get(tid) ?? 'Unknown topic'),
}));
// ─── Totals + root-cause summary ────────────────────────────────────────────
@@ -1896,11 +1749,7 @@ export async function getInsightsBreakdown(
);
const metricLabel =
- metric === 'visibility'
- ? 'Visibility'
- : metric === 'mentions'
- ? 'Mentions'
- : 'Citations';
+ metric === 'visibility' ? 'Visibility' : metric === 'mentions' ? 'Mentions' : 'Citations';
const isDrop = totalDelta < 0;
const isFlat = totalDelta === 0;
@@ -1909,12 +1758,9 @@ export async function getInsightsBreakdown(
// `buildRows` sorts ascending by delta so byPrompt[0] is the largest drop and
// byPrompt[last] is the largest gain.
const topPrompt = isDrop ? byPrompt[0] : byPrompt[byPrompt.length - 1];
- const topPlatform = isDrop
- ? byPlatform[0]
- : byPlatform[byPlatform.length - 1];
+ const topPlatform = isDrop ? byPlatform[0] : byPlatform[byPlatform.length - 1];
- const promptContributes =
- !!topPrompt && (isDrop ? topPrompt.delta < 0 : topPrompt.delta > 0);
+ const promptContributes = !!topPrompt && (isDrop ? topPrompt.delta < 0 : topPrompt.delta > 0);
const platformContributes =
!!topPlatform && (isDrop ? topPlatform.delta < 0 : topPlatform.delta > 0);
@@ -1958,10 +1804,7 @@ function truncate(s: string, max: number): string {
* - citations: "lost 7 citations (−15%)"
* - visibility: "dropped 2.1 pts" or "rose 2.1 pts"
*/
-function formatContribution(
- row: BreakdownRow,
- metric: BreakdownMetric,
-): string {
+function formatContribution(row: BreakdownRow, metric: BreakdownMetric): string {
const isLoss = row.delta < 0;
const abs = Math.abs(row.delta);
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 4d0e9b913..937f5655e 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -40,7 +40,12 @@ function mapLogRow(row: Record<string, unknown>): TrafficLog {
};
}
-function getDateRange(days: number): { from: string; to: string; prevFrom: string; prevTo: string } {
+function getDateRange(days: number): {
+ from: string;
+ to: string;
+ prevFrom: string;
+ prevTo: string;
+} {
const now = new Date();
const to = now.toISOString();
const from = new Date(now.getTime() - days * 86400000).toISOString();
@@ -49,10 +54,7 @@ function getDateRange(days: number): { from: string; to: string; prevFrom: strin
return { from, to, prevFrom, prevTo };
}
-export async function getTrafficSummary(
- brandId: string,
- days = 7,
-): Promise<TrafficSummary> {
+export async function getTrafficSummary(brandId: string, days = 7): Promise<TrafficSummary> {
const supabase = await createClient();
const { from, prevFrom, prevTo } = getDateRange(days);
@@ -136,10 +138,7 @@ export async function getTrafficSummary(
};
}
-export async function getTrafficTrend(
- brandId: string,
- days = 7,
-): Promise<TrafficTrendPoint[]> {
+export async function getTrafficTrend(brandId: string, days = 7): Promise<TrafficTrendPoint[]> {
const supabase = await createClient();
const from = new Date(Date.now() - days * 86400000).toISOString();
diff --git a/web/src/lib/actions/volumes.ts b/web/src/lib/actions/volumes.ts
index 7e3b6fd7f..605df456b 100644
--- a/web/src/lib/actions/volumes.ts
+++ b/web/src/lib/actions/volumes.ts
@@ -25,7 +25,9 @@ export async function analyzePromptVolume(
force?: boolean,
): Promise<PromptVolume> {
const supabase = await createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) throw new Error('Not authenticated');
const res = await fetch(`${AEO_SERVER_URL}/api/volumes/analyze`, {
@@ -57,7 +59,9 @@ export async function analyzePromptVolumesBatch(
force?: boolean,
): Promise<{ results: (PromptVolume & { error?: string })[]; remaining?: number }> {
const supabase = await createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) throw new Error('Not authenticated');
const res = await fetch(`${AEO_SERVER_URL}/api/volumes/analyze-batch`, {
@@ -87,7 +91,9 @@ export async function refreshVolumes(
languageCode?: string,
): Promise<{ results: PromptVolume[]; refreshed: number; remaining?: number }> {
const supabase = await createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) throw new Error('Not authenticated');
const res = await fetch(`${AEO_SERVER_URL}/api/volumes/refresh`, {
@@ -110,9 +116,13 @@ export async function refreshVolumes(
/**
* Get all prompt volumes for a brand via the aeo-server API.
*/
-export async function getPromptVolumes(brandId: string): Promise<{ volumes: PromptVolume[]; quota: VolumeQuota }> {
+export async function getPromptVolumes(
+ brandId: string,
+): Promise<{ volumes: PromptVolume[]; quota: VolumeQuota }> {
const supabase = await createClient();
- const { data: { session } } = await supabase.auth.getSession();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
if (!session) throw new Error('Not authenticated');
const res = await fetch(`${AEO_SERVER_URL}/api/volumes/brand/${brandId}`, {
diff --git a/web/src/lib/analytics.ts b/web/src/lib/analytics.ts
index 009408018..b6a267411 100644
--- a/web/src/lib/analytics.ts
+++ b/web/src/lib/analytics.ts
@@ -24,17 +24,11 @@ function getClient(): PostHogInterface | null {
return window.__ansvisor_posthog__ ?? null;
}
-export function track(
- event: string,
- properties?: Record<string, unknown>,
-): void {
+export function track(event: string, properties?: Record<string, unknown>): void {
getClient()?.capture(event, properties);
}
-export function identify(
- distinctId: string,
- properties?: Record<string, unknown>,
-): void {
+export function identify(distinctId: string, properties?: Record<string, unknown>): void {
getClient()?.identify(distinctId, properties);
}
@@ -46,8 +40,6 @@ export function reset(): void {
* Set properties on the current person without sending an event.
* Useful for hydrating subscription_status, plan_id, org_id once after login.
*/
-export function setPersonProperties(
- properties: Record<string, unknown>,
-): void {
+export function setPersonProperties(properties: Record<string, unknown>): void {
getClient()?.setPersonProperties(properties);
}
diff --git a/web/src/lib/citations/article-type.ts b/web/src/lib/citations/article-type.ts
index aa8232e52..9670ea0f7 100644
--- a/web/src/lib/citations/article-type.ts
+++ b/web/src/lib/citations/article-type.ts
@@ -7,12 +7,7 @@
* listicles, comparisons, and reviews from mainstream publishers.
*/
-export type ArticleType =
- | 'Topic Guide'
- | 'How-to Guide'
- | 'Review'
- | 'Ranked List'
- | 'Comparison';
+export type ArticleType = 'Topic Guide' | 'How-to Guide' | 'Review' | 'Ranked List' | 'Comparison';
export const ARTICLE_TYPE_LABELS: Record<ArticleType, string> = {
'Topic Guide': 'Topic Guide',
@@ -90,10 +85,7 @@ const RULES: Rule[] = [
* Classify a citation by URL + optional title. Returns null if no rule
* matches.
*/
-export function classifyArticleType(
- url: string,
- title?: string,
-): ArticleType | null {
+export function classifyArticleType(url: string, title?: string): ArticleType | null {
const corpus = `${url ?? ''} ${title ?? ''}`;
for (const rule of RULES) {
if (rule.patterns.some((p) => p.test(corpus))) {
diff --git a/web/src/lib/citations/classify.ts b/web/src/lib/citations/classify.ts
index 6a214be91..6eaeb2ad1 100644
--- a/web/src/lib/citations/classify.ts
+++ b/web/src/lib/citations/classify.ts
@@ -196,19 +196,13 @@ export function normalizeDomain(raw: string | null | undefined): string {
return host.replace(/\/+$/, '');
}
-export function classifyDomain(
- domain: string,
- ctx: ClassifyContext,
-): SourceCategory {
+export function classifyDomain(domain: string, ctx: ClassifyContext): SourceCategory {
const d = domain.toLowerCase();
if (ctx.brandDomains.length > 0 && matchesSuffix(d, ctx.brandDomains)) {
return 'you';
}
- if (
- ctx.competitorDomains.length > 0 &&
- matchesSuffix(d, ctx.competitorDomains)
- ) {
+ if (ctx.competitorDomains.length > 0 && matchesSuffix(d, ctx.competitorDomains)) {
return 'competitor';
}
if (matchesSuffix(d, FORUM_DOMAINS)) return 'forum';
diff --git a/web/src/lib/csv.ts b/web/src/lib/csv.ts
index 899580b2b..4dfaf8a54 100644
--- a/web/src/lib/csv.ts
+++ b/web/src/lib/csv.ts
@@ -8,9 +8,7 @@ function escape(value: unknown): string {
export function toCsv(rows: Record<string, unknown>[], headers: string[]): string {
const headerLine = headers.join(',');
- const dataLines = rows.map((row) =>
- headers.map((header) => escape(row[header])).join(','),
- );
+ const dataLines = rows.map((row) => headers.map((header) => escape(row[header])).join(','));
return [headerLine, ...dataLines].join('\n');
}
diff --git a/web/src/lib/favicon.ts b/web/src/lib/favicon.ts
index c2c7a1ef7..a07e10bca 100644
--- a/web/src/lib/favicon.ts
+++ b/web/src/lib/favicon.ts
@@ -3,7 +3,10 @@
* using Google's public favicon service.
*/
export function getFaviconUrl(domain: string, size: number = 128): string {
- const clean = domain.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim();
- if (!clean) return "";
+ const clean = domain
+ .replace(/^https?:\/\//, '')
+ .replace(/\/.*$/, '')
+ .trim();
+ if (!clean) return '';
return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(clean)}&sz=${size}`;
}
diff --git a/web/src/lib/guards/plan-guard.ts b/web/src/lib/guards/plan-guard.ts
index 8fe3351cc..34cf66a24 100644
--- a/web/src/lib/guards/plan-guard.ts
+++ b/web/src/lib/guards/plan-guard.ts
@@ -1,4 +1,4 @@
-import { createClient } from "@/lib/supabase/server";
+import { createClient } from '@/lib/supabase/server';
import {
type Feature,
type Plan,
@@ -7,26 +7,26 @@ import {
hasFeature,
isCloud,
isWithinLimit,
-} from "@/config/plans";
+} from '@/config/plans';
export async function getOrgPlan(organizationId: string): Promise<Plan> {
- if (!isCloud()) return getPlan("self_hosted");
+ if (!isCloud()) return getPlan('self_hosted');
const supabase = await createClient();
const { data } = await supabase
- .from("organizations")
- .select("plan, subscription_status, plan_overrides")
- .eq("id", organizationId)
+ .from('organizations')
+ .select('plan, subscription_status, plan_overrides')
+ .eq('id', organizationId)
.single();
- if (data?.subscription_status !== "active") {
- return getPlan("starter");
+ if (data?.subscription_status !== 'active') {
+ return getPlan('starter');
}
const plan = getPlan(data?.plan);
// Enterprise orgs can have custom limit overrides
- if (data?.plan === "enterprise" && data.plan_overrides) {
+ if (data?.plan === 'enterprise' && data.plan_overrides) {
const overrides = data.plan_overrides as Record<string, unknown>;
return {
...plan,
@@ -42,27 +42,21 @@ export class PlanLimitError extends Error {
constructor(message: string, requiredPlan: string) {
super(message);
- this.name = "PlanLimitError";
+ this.name = 'PlanLimitError';
this.requiredPlan = requiredPlan;
}
}
-export async function enforceFeature(
- organizationId: string,
- feature: Feature,
-): Promise<void> {
+export async function enforceFeature(organizationId: string, feature: Feature): Promise<void> {
const plan = await getOrgPlan(organizationId);
if (!hasFeature(plan, feature)) {
- throw new PlanLimitError(
- `This feature requires a higher plan.`,
- plan.name,
- );
+ throw new PlanLimitError(`This feature requires a higher plan.`, plan.name);
}
}
export async function enforceLimit(
organizationId: string,
- key: keyof Omit<PlanLimits, "features" | "allowedScrapers" | "allowedModels">,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
currentCount: number,
): Promise<void> {
const plan = await getOrgPlan(organizationId);
diff --git a/web/src/lib/mcp-auth.ts b/web/src/lib/mcp-auth.ts
index bf61d5659..5cd97b4c5 100644
--- a/web/src/lib/mcp-auth.ts
+++ b/web/src/lib/mcp-auth.ts
@@ -30,17 +30,12 @@ export interface McpAuthContext {
* MCP endpoints are intended to be hit by long-lived external clients, so we
* intentionally don't fall back to the dashboard's session cookie.
*/
-export async function authenticateMcpRequest(
- req: Request,
-): Promise<McpAuthContext | NextResponse> {
+export async function authenticateMcpRequest(req: Request): Promise<McpAuthContext | NextResponse> {
const auth = req.headers.get('authorization') ?? '';
const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : '';
if (!token || !token.startsWith(API_KEY_PREFIX)) {
- return NextResponse.json(
- { error: 'Missing or malformed API key' },
- { status: 401 },
- );
+ return NextResponse.json({ error: 'Missing or malformed API key' }, { status: 401 });
}
const hash = hashApiKey(token);
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 6f6c377fc..af7b5656f 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -17,9 +17,7 @@ export interface BrandRow {
created_at: string;
}
-export async function listBrandsFor(
- auth: McpAuthContext,
-): Promise<BrandRow[]> {
+export async function listBrandsFor(auth: McpAuthContext): Promise<BrandRow[]> {
if (!auth.organizationId) return [];
const { data, error } = await supabaseAdmin
@@ -144,8 +142,7 @@ export async function getVisibilitySummaryFor(
.map(([name, agg]) => ({
name,
mentions: agg.mentions,
- avgVisibility:
- Math.round((agg.visSum / Math.max(agg.mentions, 1)) * 10) / 10,
+ avgVisibility: Math.round((agg.visSum / Math.max(agg.mentions, 1)) * 10) / 10,
}))
.sort((a, b) => b.mentions - a.mentions)
.slice(0, 5);
@@ -212,8 +209,7 @@ export async function listTopicsFor(
.eq('prompt_sets.brand_id', brandId)
.not('topic_id', 'is', null);
- const promptRows =
- (prompts as Array<{ topic_id: string | null }> | null) ?? [];
+ const promptRows = (prompts as Array<{ topic_id: string | null }> | null) ?? [];
const countByTopic = new Map<string, number>();
for (const row of promptRows) {
if (!row.topic_id) continue;
@@ -307,7 +303,7 @@ export async function listPromptsFor(
}> | null) ?? [];
return rows.map((r) => {
- const topic = Array.isArray(r.topics) ? r.topics[0] ?? null : r.topics;
+ const topic = Array.isArray(r.topics) ? (r.topics[0] ?? null) : r.topics;
return {
id: r.id,
text: r.text,
@@ -398,7 +394,7 @@ export async function listContentOpportunitiesFor(
}> | null) ?? [];
return rows.map((r) => {
- const prompt = Array.isArray(r.prompts) ? r.prompts[0] ?? null : r.prompts;
+ const prompt = Array.isArray(r.prompts) ? (r.prompts[0] ?? null) : r.prompts;
return {
id: r.id,
title: r.title,
@@ -466,7 +462,7 @@ export async function getContentOpportunityFor(
prompts: Array<{ text: string }> | { text: string } | null;
};
- const prompt = Array.isArray(r.prompts) ? r.prompts[0] ?? null : r.prompts;
+ const prompt = Array.isArray(r.prompts) ? (r.prompts[0] ?? null) : r.prompts;
return {
id: r.id,
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 535d2b4fd..1f8a5c8ab 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -34,9 +34,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
async () => {
const brands = await listBrandsFor(auth);
return {
- content: [
- { type: 'text', text: JSON.stringify(brands, null, 2) },
- ],
+ content: [{ type: 'text', text: JSON.stringify(brands, null, 2) }],
};
},
);
@@ -47,30 +45,19 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
description:
'Get aggregate visibility metrics for a brand over an optional date range and filter. Returns result count, average visibility score (0-100), total mentions, total citations, and the top 5 competitors by mention count. Use this for "how is my brand doing" / "what changed" style questions.',
inputSchema: {
- brand_id: z
- .string()
- .uuid()
- .describe('Brand UUID, from list_brands.'),
+ brand_id: z.string().uuid().describe('Brand UUID, from list_brands.'),
date_from: z
.string()
.optional()
- .describe(
- 'ISO timestamp (inclusive) lower bound, e.g. 2026-05-01T00:00:00Z.',
- ),
- date_to: z
- .string()
- .optional()
- .describe('ISO timestamp (inclusive) upper bound.'),
+ .describe('ISO timestamp (inclusive) lower bound, e.g. 2026-05-01T00:00:00Z.'),
+ date_to: z.string().optional().describe('ISO timestamp (inclusive) upper bound.'),
model: z
.string()
.optional()
.describe(
'Optional model slug filter, or comma-separated list of slugs to filter a provider family.',
),
- region: z
- .string()
- .optional()
- .describe('Optional region code filter (e.g. "US", "TR").'),
+ region: z.string().optional().describe('Optional region code filter (e.g. "US", "TR").'),
},
},
async (args) => {
@@ -88,9 +75,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
};
}
return {
- content: [
- { type: 'text', text: JSON.stringify(summary, null, 2) },
- ],
+ content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }],
};
},
);
@@ -101,10 +86,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
description:
'List topics for a brand, each with the number of prompts attached to it. Use this to audit prompt coverage ("are any topics empty / under-represented?") or before drilling into prompts for a specific theme. Topic-less prompts are not counted here — call list_prompts without a topic filter to see them.',
inputSchema: {
- brand_id: z
- .string()
- .uuid()
- .describe('Brand UUID, from list_brands.'),
+ brand_id: z.string().uuid().describe('Brand UUID, from list_brands.'),
},
},
async (args) => {
@@ -116,9 +98,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
};
}
return {
- content: [
- { type: 'text', text: JSON.stringify(topics, null, 2) },
- ],
+ content: [{ type: 'text', text: JSON.stringify(topics, null, 2) }],
};
},
);
@@ -129,32 +109,23 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
description:
'List the prompts tracked for a brand, optionally filtered by topic or active status. Returns each prompt with its text, topic, platforms, models, regions, and active flag. Use this when the user asks what is being tracked, wants to drill into a specific topic, or wants to spot inactive / mis-targeted prompts.',
inputSchema: {
- brand_id: z
- .string()
- .uuid()
- .describe('Brand UUID, from list_brands.'),
+ brand_id: z.string().uuid().describe('Brand UUID, from list_brands.'),
topic_id: z
.string()
.uuid()
.optional()
- .describe(
- 'Optional topic UUID (from list_topics) to filter to one topic.',
- ),
+ .describe('Optional topic UUID (from list_topics) to filter to one topic.'),
is_active: z
.boolean()
.optional()
- .describe(
- 'Optional filter — true returns only active prompts, false only inactive.',
- ),
+ .describe('Optional filter — true returns only active prompts, false only inactive.'),
limit: z
.number()
.int()
.min(1)
.max(500)
.optional()
- .describe(
- 'Optional row cap (default 100, max 500). Newest prompts come first.',
- ),
+ .describe('Optional row cap (default 100, max 500). Newest prompts come first.'),
},
},
async (args) => {
@@ -171,9 +142,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
};
}
return {
- content: [
- { type: 'text', text: JSON.stringify(prompts, null, 2) },
- ],
+ content: [{ type: 'text', text: JSON.stringify(prompts, null, 2) }],
};
},
);
@@ -184,10 +153,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
description:
'List content opportunities / gaps for a brand, showing which prompts represent the highest-impact areas where the brand is currently losing visibility. Sorts by opportunity score descending by default. Use this to audit open gaps, see what content needs to be written, or list open strategy priorities.',
inputSchema: {
- brand_id: z
- .string()
- .uuid()
- .describe('Brand UUID, from list_brands.'),
+ brand_id: z.string().uuid().describe('Brand UUID, from list_brands.'),
status: z
.enum(['new', 'sent', 'in_progress', 'done', 'dismissed'])
.optional()
@@ -226,9 +192,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
};
}
return {
- content: [
- { type: 'text', text: JSON.stringify(opportunities, null, 2) },
- ],
+ content: [{ type: 'text', text: JSON.stringify(opportunities, null, 2) }],
};
},
);
@@ -254,9 +218,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
};
}
return {
- content: [
- { type: 'text', text: JSON.stringify(opportunity, null, 2) },
- ],
+ content: [{ type: 'text', text: JSON.stringify(opportunity, null, 2) }],
};
},
);
diff --git a/web/src/lib/prompt-volume-clusters.ts b/web/src/lib/prompt-volume-clusters.ts
index 0f7295500..a9d37e2d2 100644
--- a/web/src/lib/prompt-volume-clusters.ts
+++ b/web/src/lib/prompt-volume-clusters.ts
@@ -14,9 +14,7 @@ export interface PromptVolumeCluster {
}[];
}
-export function aggregatePromptVolumeClusters(
- volumes: PromptVolume[],
-): PromptVolumeCluster[] {
+export function aggregatePromptVolumeClusters(volumes: PromptVolume[]): PromptVolumeCluster[] {
const merged = new Map<string, PromptVolumeCluster>();
for (const v of volumes) {
diff --git a/web/src/lib/supabase/client.ts b/web/src/lib/supabase/client.ts
index f91119aec..05bb632d6 100644
--- a/web/src/lib/supabase/client.ts
+++ b/web/src/lib/supabase/client.ts
@@ -1,9 +1,9 @@
-import { createBrowserClient } from "@supabase/ssr";
-import type { Database } from "@/types/supabase";
+import { createBrowserClient } from '@supabase/ssr';
+import type { Database } from '@/types/supabase';
export function createClient() {
return createBrowserClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
+ process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
);
}
diff --git a/web/src/lib/supabase/middleware.ts b/web/src/lib/supabase/middleware.ts
index a81266440..2eca421c0 100644
--- a/web/src/lib/supabase/middleware.ts
+++ b/web/src/lib/supabase/middleware.ts
@@ -1,6 +1,6 @@
-import { createServerClient } from "@supabase/ssr";
-import { type NextRequest, NextResponse } from "next/server";
-import type { Database } from "@/types/supabase";
+import { createServerClient } from '@supabase/ssr';
+import { type NextRequest, NextResponse } from 'next/server';
+import type { Database } from '@/types/supabase';
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({ request });
@@ -14,16 +14,14 @@ export async function updateSession(request: NextRequest) {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value }) =>
- request.cookies.set(name, value)
- );
+ cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
supabaseResponse = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) =>
- supabaseResponse.cookies.set(name, value, options)
+ supabaseResponse.cookies.set(name, value, options),
);
},
},
- }
+ },
);
const {
diff --git a/web/src/lib/supabase/server.ts b/web/src/lib/supabase/server.ts
index bf2d73c60..5684935f8 100644
--- a/web/src/lib/supabase/server.ts
+++ b/web/src/lib/supabase/server.ts
@@ -1,6 +1,6 @@
-import { createServerClient } from "@supabase/ssr";
-import { cookies } from "next/headers";
-import type { Database } from "@/types/supabase";
+import { createServerClient } from '@supabase/ssr';
+import { cookies } from 'next/headers';
+import type { Database } from '@/types/supabase';
export async function createClient() {
const cookieStore = await cookies();
@@ -16,13 +16,13 @@ export async function createClient() {
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options)
+ cookieStore.set(name, value, options),
);
} catch {
// setAll called from a Server Component — safe to ignore
}
},
},
- }
+ },
);
}
diff --git a/web/src/lib/utils.ts b/web/src/lib/utils.ts
index bd0c391dd..2819a830d 100644
--- a/web/src/lib/utils.ts
+++ b/web/src/lib/utils.ts
@@ -1,6 +1,6 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
+import { clsx, type ClassValue } from 'clsx';
+import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
+ return twMerge(clsx(inputs));
}
diff --git a/web/src/proxy.ts b/web/src/proxy.ts
index 4902cf9b2..db339ce62 100644
--- a/web/src/proxy.ts
+++ b/web/src/proxy.ts
@@ -1,29 +1,25 @@
-import createMiddleware from "next-intl/middleware";
-import { type NextRequest, NextResponse } from "next/server";
-import { routing } from "@/i18n/routing";
-import { updateSession } from "@/lib/supabase/middleware";
+import createMiddleware from 'next-intl/middleware';
+import { type NextRequest, NextResponse } from 'next/server';
+import { routing } from '@/i18n/routing';
+import { updateSession } from '@/lib/supabase/middleware';
const intlMiddleware = createMiddleware(routing);
-const protectedPathnames = ["/dashboard"];
-const authPathnames = ["/sign-in", "/sign-up"];
+const protectedPathnames = ['/dashboard'];
+const authPathnames = ['/sign-in', '/sign-up'];
function isProtected(pathname: string): boolean {
- return protectedPathnames.some(
- (p) => pathname === p || pathname.startsWith(`${p}/`)
- );
+ return protectedPathnames.some((p) => pathname === p || pathname.startsWith(`${p}/`));
}
function isAuthRoute(pathname: string): boolean {
- return authPathnames.some(
- (p) => pathname === p || pathname.startsWith(`${p}/`)
- );
+ return authPathnames.some((p) => pathname === p || pathname.startsWith(`${p}/`));
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
- const pathnameWithoutLocale = pathname.replace(/^\/(en)/, "") || "/";
+ const pathnameWithoutLocale = pathname.replace(/^\/(en)/, '') || '/';
let supabaseResponse: NextResponse | undefined;
let user: { id: string } | null = null;
@@ -37,19 +33,19 @@ export async function proxy(request: NextRequest) {
// so next-intl locale routing still works
}
- if (pathnameWithoutLocale === "/") {
- const target = user ? "/dashboard" : "/sign-in";
+ if (pathnameWithoutLocale === '/') {
+ const target = user ? '/dashboard' : '/sign-in';
return NextResponse.redirect(new URL(target, request.url));
}
if (isProtected(pathnameWithoutLocale) && !user) {
- const signInUrl = new URL("/sign-in", request.url);
- signInUrl.searchParams.set("redirectTo", pathname);
+ const signInUrl = new URL('/sign-in', request.url);
+ signInUrl.searchParams.set('redirectTo', pathname);
return NextResponse.redirect(signInUrl);
}
if (isAuthRoute(pathnameWithoutLocale) && user) {
- return NextResponse.redirect(new URL("/dashboard", request.url));
+ return NextResponse.redirect(new URL('/dashboard', request.url));
}
const intlResponse = intlMiddleware(request);
@@ -64,7 +60,5 @@ export async function proxy(request: NextRequest) {
}
export const config = {
- matcher: [
- "/((?!api|_next|_vercel|.*\\..*).*)",
- ],
+ matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'],
};
diff --git a/web/src/stores/use-auth-store.ts b/web/src/stores/use-auth-store.ts
index f0ebd71d3..0629c9b18 100644
--- a/web/src/stores/use-auth-store.ts
+++ b/web/src/stores/use-auth-store.ts
@@ -1,5 +1,5 @@
-import { create } from "zustand";
-import type { User, Session } from "@supabase/supabase-js";
+import { create } from 'zustand';
+import type { User, Session } from '@supabase/supabase-js';
interface AuthStore {
user: User | null;
diff --git a/web/src/stores/use-brand-store.ts b/web/src/stores/use-brand-store.ts
index fefe9292d..020a6a8dc 100644
--- a/web/src/stores/use-brand-store.ts
+++ b/web/src/stores/use-brand-store.ts
@@ -1,6 +1,6 @@
-import { create } from "zustand";
-import { persist } from "zustand/middleware";
-import type { Brand } from "@/types";
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+import type { Brand } from '@/types';
interface BrandStore {
brands: Brand[];
@@ -22,8 +22,7 @@ export const useBrandStore = create<BrandStore>()(
setBrands: (brands) =>
set({
brands,
- activeBrandId:
- brands.length > 0 ? (get().activeBrandId ?? brands[0].id) : null,
+ activeBrandId: brands.length > 0 ? (get().activeBrandId ?? brands[0].id) : null,
}),
addBrand: (brand) =>
@@ -34,9 +33,7 @@ export const useBrandStore = create<BrandStore>()(
updateBrand: (id, updates) =>
set((state) => ({
- brands: state.brands.map((b) =>
- b.id === id ? { ...b, ...updates } : b
- ),
+ brands: state.brands.map((b) => (b.id === id ? { ...b, ...updates } : b)),
})),
removeBrand: (id) =>
@@ -45,9 +42,7 @@ export const useBrandStore = create<BrandStore>()(
return {
brands: remaining,
activeBrandId:
- state.activeBrandId === id
- ? (remaining[0]?.id ?? null)
- : state.activeBrandId,
+ state.activeBrandId === id ? (remaining[0]?.id ?? null) : state.activeBrandId,
};
}),
@@ -59,11 +54,11 @@ export const useBrandStore = create<BrandStore>()(
},
}),
{
- name: "brand-store",
+ name: 'brand-store',
partialize: (state) => ({
activeBrandId: state.activeBrandId,
brands: state.brands,
}),
- }
- )
+ },
+ ),
);
diff --git a/web/src/stores/use-sidebar-store.ts b/web/src/stores/use-sidebar-store.ts
index 3d5cc9667..5bc4dac49 100644
--- a/web/src/stores/use-sidebar-store.ts
+++ b/web/src/stores/use-sidebar-store.ts
@@ -1,5 +1,5 @@
-import { create } from "zustand";
-import { persist } from "zustand/middleware";
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
interface SidebarStore {
isOpen: boolean;
@@ -18,11 +18,10 @@ export const useSidebarStore = create<SidebarStore>()(
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
open: () => set({ isOpen: true }),
close: () => set({ isOpen: false }),
- toggleCollapse: () =>
- set((state) => ({ isCollapsed: !state.isCollapsed })),
+ toggleCollapse: () => set((state) => ({ isCollapsed: !state.isCollapsed })),
}),
{
- name: "sidebar-store",
- }
- )
+ name: 'sidebar-store',
+ },
+ ),
);
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index 06cfc99e3..cc6bb068e 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -77,24 +77,24 @@ export interface Topic {
}
export type AIPlatform =
- | "chatgpt"
- | "gemini"
- | "claude"
- | "perplexity"
- | "grok"
- | "meta-ai"
- | "copilot"
- | "google-ai-overviews"
- | "google-ai-mode"
- | "chatgpt-web"
- | "google-aio"
- | "google-aimode"
- | "copilot-web"
- | "grok-web"
- | "perplexity-web"
- | "gemini-web";
-
-export type CheckFrequency = "daily" | "weekly" | "monthly";
+ | 'chatgpt'
+ | 'gemini'
+ | 'claude'
+ | 'perplexity'
+ | 'grok'
+ | 'meta-ai'
+ | 'copilot'
+ | 'google-ai-overviews'
+ | 'google-ai-mode'
+ | 'chatgpt-web'
+ | 'google-aio'
+ | 'google-aimode'
+ | 'copilot-web'
+ | 'grok-web'
+ | 'perplexity-web'
+ | 'gemini-web';
+
+export type CheckFrequency = 'daily' | 'weekly' | 'monthly';
export interface BrandPlatform {
id: string;
@@ -108,7 +108,7 @@ export interface BrandPlatform {
updatedAt: string;
}
-export type Sentiment = "positive" | "neutral" | "negative";
+export type Sentiment = 'positive' | 'neutral' | 'negative';
export interface Citation {
url: string;
@@ -166,16 +166,11 @@ export interface PromptVolume {
fetchedAt: string;
}
-export type ContentOpportunityStatus =
- | "new"
- | "sent"
- | "in_progress"
- | "done"
- | "dismissed";
+export type ContentOpportunityStatus = 'new' | 'sent' | 'in_progress' | 'done' | 'dismissed';
-export type ContentOpportunityImpact = "high" | "medium" | "low";
+export type ContentOpportunityImpact = 'high' | 'medium' | 'low';
-export type ContentOpportunityType = "owned" | "earned";
+export type ContentOpportunityType = 'owned' | 'earned';
export interface ContentOpportunitySourceData {
promptText?: string;
@@ -227,7 +222,7 @@ export interface WebhookConfig {
updatedAt: string;
}
-export type UserRole = "admin" | "manager" | "analyst" | "agency_partner";
+export type UserRole = 'admin' | 'manager' | 'analyst' | 'agency_partner';
export interface UserProfile {
id: string;
@@ -239,21 +234,21 @@ export interface UserProfile {
}
export const INDUSTRIES = [
- "Technology",
- "E-commerce & Retail",
- "Finance & Banking",
- "Healthcare",
- "Travel & Hospitality",
- "Media & Entertainment",
- "Education",
- "Food & Beverage",
- "Automotive",
- "Fashion & Apparel",
- "Real Estate",
- "Consumer Goods",
- "B2B Software (SaaS)",
- "Telecommunications",
- "Other",
+ 'Technology',
+ 'E-commerce & Retail',
+ 'Finance & Banking',
+ 'Healthcare',
+ 'Travel & Hospitality',
+ 'Media & Entertainment',
+ 'Education',
+ 'Food & Beverage',
+ 'Automotive',
+ 'Fashion & Apparel',
+ 'Real Estate',
+ 'Consumer Goods',
+ 'B2B Software (SaaS)',
+ 'Telecommunications',
+ 'Other',
] as const;
export type Industry = (typeof INDUSTRIES)[number];
diff --git a/web/yarn.lock b/web/yarn.lock
index f96e3c56d..8fec9f013 100644
--- a/web/yarn.lock
+++ b/web/yarn.lock
@@ -2986,6 +2986,11 @@ [email protected]:
globals "16.4.0"
typescript-eslint "^8.46.0"
+eslint-config-prettier@^10.1.8:
+ version "10.1.8"
+ resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz#15734ce4af8c2778cc32f0b01b37b0b5cd1ecb97"
+ integrity sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==
+
eslint-import-resolver-node@^0.3.6, eslint-import-resolver-node@^0.3.9:
version "0.3.9"
resolved "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz"
@@ -5516,6 +5521,11 @@ prelude-ls@^1.2.1:
resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz"
integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==
+prettier@^3.8.3:
+ version "3.8.3"
+ resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.3.tgz#560f2de55bf01b4c0503bc629d5df99b9a1d09b0"
+ integrity sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==
+
pretty-ms@^9.2.0:
version "9.3.0"
resolved "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz"