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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): add locations to many prompts at once, priced before saving, with more countries (PROMPT-015, part 3) (#1657)
Cihan0bb8512497bc
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdxindex d0b039cda..b476e35a7 100644--- a/docs/guides/prompts.mdx+++ b/docs/guides/prompts.mdx@@ -59,6 +59,20 @@ A prompt tracked in several locations (countries or US states) has figures for eClick a cell to open the prompt's Positions panel for that location. A location the prompt isn't tracked in shows **+ Track** for admins, managers and analysts. The date range and filters work as in the table, and a location's numbers equal the table filtered to it.+### Adding locations++**+ Add location** in the Locations view, or **+ Track** in a cell, opens **Track in more locations**:++1. Pick one or more countries or US states (about 50 countries).+2. Choose which prompts to ask there: the one you clicked, the selected ones, a topic, or every prompt shown.+3. Check **Plan usage**. Every prompt in every location counts once on your plan's prompt locations; for example, 50 prompts in two more places use 100 more. Paused prompts don't count.++If the choice would pass your plan's limit, the dialog says how many it needs and how many are left, and saves nothing. Pick fewer prompts or places, or:++- **Starter**: upgrade, or contact us for a custom plan;+- **Growth**: contact us for a custom plan;+- **Enterprise**: contact us to raise your limit.+## PerformanceThe **Performance** filter groups prompts by where your brand is named in their AI answers over the selected range, across every platform the prompt tracks:diff --git a/web/messages/en.json b/web/messages/en.jsonindex 500bd0153..dfea06b4e 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7484,10 +7484,33 @@"late": "Named late","first": "Named first","legend": "A cell opens the prompt's Positions panel for that location.",- "none": "Your prompts aren't tracked in a location yet. Add one from a prompt's Edit.",+ "none": "Your prompts aren't tracked in a location yet.","failed": "Couldn't read the locations right now. Try again in a moment.","capped": "Showing the {count} locations your prompts track most."},+ "addLocations": {+ "button": "+ Add location",+ "title": "Track in more locations",+ "lead": "The same prompts, asked from each place you add. Each place gets its own column in the Locations view.",+ "locations": "Locations to add",+ "picked": "picked",+ "scope": "Ask these prompts there",+ "selected": "The {count, plural, one {# prompt} other {# prompts}} selected",+ "topic": "Topic",+ "allShown": "All {count, plural, one {# prompt} other {# prompts}} shown",+ "promptsCount": "{count, plural, one {# prompt} other {# prompts}}",+ "usage": "Plan usage",+ "usageLine": "{used} → {after} of {max} tracked locations",+ "unlimited": "{used} → {after} tracked locations · no limit on your plan",+ "usageHint": "Each prompt in each location is one tracked location on your plan, checked every day. Paused prompts don't count.",+ "over": "This needs {adding, plural, one {# more tracked location} other {# more tracked locations}}; {left, plural, =0 {none are} one {# is} other {# are}} left on your {plan} plan.",+ "overHint": "Pick fewer prompts or places. {plan, select, starter {Or upgrade your plan, or contact us for a custom plan.} growth {Or contact us for a custom plan.} other {Or contact us to raise your limit.}}",+ "nothing": "These prompts are already tracked in these locations.",+ "noPrompts": "Choose the prompts to add these locations to.",+ "cancel": "Cancel",+ "submit": "Track in {count, plural, =0 {these locations} one {# location} other {# locations}}",+ "done": "{count, plural, one {# prompt is} other {# prompts are}} now tracked in the new locations."+ },"performance": {"label": "Performance","title": "Where your brand is named in this prompt's AI answers: Best in the first third of the brands listed, Good in the middle, Late in the last third, Missing in fewer than half the answers. Late and Missing list the furthest behind first.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsxnew file mode 100644index 000000000..dd408a2a1--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx@@ -0,0 +1,166 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { Prompt } from '@/types';++const actions = vi.hoisted(() => ({+ getLocationQuota: vi.fn(),+ bulkUpdatePromptLocations: vi.fn(),+}));+vi.mock('@/lib/actions/prompt', () => actions);+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++const { AddLocationsDialog } = await import('./_add-locations-dialog');++/** Track in more locations (PROMPT-015c). */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const BRAND = '11111111-1111-1111-1111-111111111111';+let container: HTMLDivElement;+let root: Root;+const onDone = vi.fn();++const prompt = (id: string, regions: string[], category = 'Delivery'): Prompt =>+ ({ id, text: `prompt ${id}`, regions, category, isActive: true }) as unknown as Prompt;+const prompts = [prompt('p1', ['US']), prompt('p2', ['US']), prompt('p3', ['US'], 'Buying')];++async function render(preset: { promptId?: string; locations?: string[] } | null) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <AddLocationsDialog+ open+ onOpenChange={() => {}}+ brandId={BRAND}+ prompts={prompts}+ selectedIds={new Set()}+ preset={preset}+ onDone={onDone}+ />+ </NextIntlClientProvider>,+ );+ });+ return document.body.textContent ?? '';+}++const submit = () =>+ [...document.body.querySelectorAll('button')].find((b) =>+ b.textContent?.startsWith('Track in'),+ ) as HTMLButtonElement;+const scope = (label: string) =>+ [...document.body.querySelectorAll('label')]+ .find((l) => l.textContent?.includes(label))!+ .querySelector('input') as HTMLInputElement;++beforeEach(() => {+ actions.getLocationQuota.mockReset().mockResolvedValue({+ maxPrompts: 200,+ used: 152,+ planId: 'growth',+ planName: 'Growth',+ });+ actions.bulkUpdatePromptLocations+ .mockReset()+ .mockResolvedValue({ updated: 1, unchanged: 0, blocked: 0, delta: 1 });+ toast.success.mockReset();+ onDone.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('AddLocationsDialog', () => {+ it("opens on a cell's prompt and location, prices it, and tracks it there", async () => {+ const text = await render({ promptId: 'p2', locations: ['TR'] });+ expect(text).toContain('Track in more locations');+ expect(text).toContain('Turkey');+ expect(text).toContain('152 → 153 of 200 tracked locations');+ expect(scope('prompt p2').checked).toBe(true);+ await act(async () => submit().click());+ expect(actions.bulkUpdatePromptLocations).toHaveBeenCalledWith(['p2'], 'add', ['TR']);+ expect(toast.success).toHaveBeenCalledWith('1 prompt is now tracked in the new locations.');+ expect(onDone).toHaveBeenCalled();+ });++ it("adds to no prompt when the cell's prompt is no longer shown, rather than to all", async () => {+ const text = await render({ promptId: 'gone', locations: ['TR'] });+ expect(scope('All 3 prompts shown').checked).toBe(false);+ expect(text).toContain('152 → 152 of 200 tracked locations');+ expect(text).toContain('Choose the prompts to add these locations to.');+ expect(submit().disabled).toBe(true);+ await act(async () => scope('All 3 prompts shown').click());+ expect(document.body.textContent).toContain('152 → 155 of 200 tracked locations');+ expect(submit().disabled).toBe(false);+ });++ it('prices a topic and every prompt shown', async () => {+ await render({ locations: ['TR', 'DE'] });+ expect(scope('All 3 prompts shown').checked).toBe(true);+ expect(document.body.textContent).toContain('152 → 158 of 200 tracked locations');+ // The first topic, Buying, has one prompt; Delivery has two.+ await act(async () => scope('Topic').click());+ expect(document.body.textContent).toContain('152 → 154 of 200 tracked locations');+ const topic = document.body.querySelector('select[aria-label="Topic"]') as HTMLSelectElement;+ await act(async () => {+ topic.value = 'Delivery';+ topic.dispatchEvent(new Event('change', { bubbles: true }));+ });+ expect(document.body.textContent).toContain('152 → 156 of 200 tracked locations');+ });++ it('stops a choice past the limit in place, with the numbers and the plan’s way out', async () => {+ actions.getLocationQuota.mockResolvedValue({+ maxPrompts: 200,+ used: 199,+ planId: 'growth',+ planName: 'Growth',+ });+ const text = await render({ locations: ['TR'] });+ expect(text).toContain('199 → 202 of 200 tracked locations');+ expect(text).toContain('This needs 3 more tracked locations; 1 is left on your Growth plan.');+ expect(text).toContain('Or contact us for a custom plan.');+ expect(submit().disabled).toBe(true);+ expect(document.body.querySelector('a[href*="billing"]')).toBeNull();+ });++ it('offers Starter an upgrade', async () => {+ actions.getLocationQuota.mockResolvedValue({+ maxPrompts: 50,+ used: 50,+ planId: 'starter',+ planName: 'Starter',+ });+ const text = await render({ locations: ['TR'] });+ expect(text).toContain('none are left on your Starter plan');+ expect(text).toContain('Or upgrade your plan, or contact us for a custom plan.');+ expect(document.body.querySelector('a[href="/dashboard/settings?tab=billing"]')).not.toBeNull();+ });++ it("says what the server refused, and changes nothing it didn't save", async () => {+ actions.bulkUpdatePromptLocations.mockResolvedValue({+ error: 'Your Growth plan allows up to 200 active prompt locations',+ code: 'plan_limit',+ });+ await render({ promptId: 'p1', locations: ['TR'] });+ await act(async () => submit().click());+ expect(document.body.textContent).toContain('Your Growth plan allows up to 200');+ expect(onDone).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsxnew file mode 100644index 000000000..ee0bb27ec--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx@@ -0,0 +1,287 @@+'use client';++import { useEffect, useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Loader2 } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { LocationPicker } from '@/components/dashboard/location-picker';+import {+ bulkUpdatePromptLocations,+ getLocationQuota,+ type LocationQuota,+} from '@/lib/actions/prompt';+import { planBulkLocationChange } from '@/lib/prompt-locations';+import { cn } from '@/lib/utils';+import type { Prompt } from '@/types';+import { PromptLimitActions } from './_prompt-limit-actions';++type Scope = 'one' | 'selected' | 'topic' | 'all';++export interface AddLocationsPreset {+ /** One prompt, from a Locations view cell's + Track. */+ promptId?: string;+ locations?: string[];+}++/**+ * Track in more locations (PROMPT-015c): the locations to add, the prompts+ * to add them to (one, the selected, a topic, or all shown), and what it+ * does to the plan's tracked locations before anything is saved. Past the+ * limit it says what the choice needs and what is left, with the plan's+ * way out, and saves nothing. The preview and the save run the same+ * arithmetic (planBulkLocationChange), and the save checks the limit again.+ */+export function AddLocationsDialog({+ open,+ onOpenChange,+ brandId,+ prompts,+ selectedIds,+ preset,+ onDone,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ brandId: string;+ /** The rows the table shows. */+ prompts: Prompt[];+ selectedIds: ReadonlySet<string>;+ preset: AddLocationsPreset | null;+ onDone: () => void;+}) {+ const t = useTranslations('prompts.addLocations');+ const [locations, setLocations] = useState<string[]>([]);+ const [scope, setScope] = useState<Scope>('all');+ const [topic, setTopic] = useState('');+ const [quota, setQuota] = useState<LocationQuota | null>(null);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const topics = useMemo(+ () => [...new Set(prompts.map((p) => p.category?.trim()).filter(Boolean))].sort() as string[],+ [prompts],+ );+ const selected = prompts.filter((p) => selectedIds.has(p.id));+ const one = preset?.promptId ? prompts.find((p) => p.id === preset.promptId) : undefined;++ // Each opening starts from what opened it.+ useEffect(() => {+ if (!open) return;+ setLocations(preset?.locations ?? []);+ setScope(preset?.promptId ? 'one' : selectedIds.size ? 'selected' : 'all');+ setTopic('');+ setError(null);+ let cancelled = false;+ getLocationQuota(brandId)+ .then((q) => {+ if (!cancelled) setQuota(q);+ })+ .catch((err) => console.error('Failed to read the plan usage:', err));+ return () => {+ cancelled = true;+ };+ // Read when it opens; the preset and selection are what opened it.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, brandId]);++ const chosenTopic = topic || topics[0] || '';+ // A cell's prompt the rows no longer show is no prompt, never every prompt.+ const targets =+ scope === 'one'+ ? one+ ? [one]+ : []+ : scope === 'selected'+ ? selected+ : scope === 'topic'+ ? prompts.filter((p) => p.category?.trim() === chosenTopic)+ : prompts;+ const change = planBulkLocationChange(+ targets.map((p) => ({ id: p.id, regions: p.regions, isActive: p.isActive })),+ 'add',+ locations,+ );+ const unlimited = quota === null || quota.maxPrompts === -1;+ const after = (quota?.used ?? 0) + change.delta;+ const over = !unlimited && quota !== null && after > quota.maxPrompts;+ const left = quota ? Math.max(0, quota.maxPrompts - quota.used) : 0;++ const save = async () => {+ setSaving(true);+ setError(null);+ const result = await bulkUpdatePromptLocations(+ targets.map((p) => p.id),+ 'add',+ locations,+ );+ setSaving(false);+ if ('error' in result) {+ setError(result.error);+ return;+ }+ toast.success(t('done', { count: result.updated }));+ onOpenChange(false);+ onDone();+ };++ const scopes: { id: Scope; label: string; count: number }[] = [+ ...(one ? [{ id: 'one' as const, label: one.text, count: 1 }] : []),+ ...(selected.length+ ? [+ {+ id: 'selected' as const,+ label: t('selected', { count: selected.length }),+ count: selected.length,+ },+ ]+ : []),+ ...(topics.length+ ? [+ {+ id: 'topic' as const,+ label: t('topic'),+ count: prompts.filter((p) => p.category?.trim() === chosenTopic).length,+ },+ ]+ : []),+ { id: 'all', label: t('allShown', { count: prompts.length }), count: prompts.length },+ ];++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>{t('lead')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <LocationPicker+ value={locations}+ onChange={setLocations}+ maxSelectable={null}+ label={t('locations')}+ countNoun={t('picked')}+ allowEmpty+ />++ <fieldset className="space-y-2">+ <legend className="mb-2 text-xs font-medium text-muted-foreground">{t('scope')}</legend>+ {scopes.map((s) => (+ <label+ key={s.id}+ className={cn(+ 'flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2 text-sm',+ scope === s.id && 'border-foreground',+ )}+ >+ <input+ type="radio"+ name="add-locations-scope"+ checked={scope === s.id}+ onChange={() => setScope(s.id)}+ />+ <span className="min-w-0 flex-1 truncate">{s.label}</span>+ {s.id === 'topic' && (+ <select+ aria-label={t('topic')}+ value={chosenTopic}+ onChange={(e) => {+ setTopic(e.target.value);+ setScope('topic');+ }}+ className="h-7 max-w-[160px] rounded-md border bg-background px-1.5 text-xs"+ >+ {topics.map((name) => (+ <option key={name} value={name}>+ {name}+ </option>+ ))}+ </select>+ )}+ <span className="text-xs tabular-nums text-muted-foreground">+ {t('promptsCount', { count: s.count })}+ </span>+ </label>+ ))}+ </fieldset>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between gap-3 text-sm">+ <span className="font-medium">{t('usage')}</span>+ <span className="tabular-nums">+ {quota === null+ ? '…'+ : unlimited+ ? t('unlimited', { used: quota.used, after })+ : t('usageLine', { used: quota.used, after, max: quota.maxPrompts })}+ </span>+ </div>+ {!unlimited && quota && (+ <div aria-hidden className="flex h-2 overflow-hidden rounded-full bg-muted">+ <span+ className="bg-foreground"+ style={{ width: `${Math.min(100, (quota.used / quota.maxPrompts) * 100)}%` }}+ />+ <span+ className={over ? 'bg-amber-500' : 'bg-foreground/40'}+ style={{+ width: `${Math.max(0, Math.min(100 - (quota.used / quota.maxPrompts) * 100, (change.delta / quota.maxPrompts) * 100))}%`,+ }}+ />+ </div>+ )}+ <p className="text-xs text-muted-foreground">{t('usageHint')}</p>+ </div>++ {over && quota && (+ <div+ role="alert"+ className="space-y-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200"+ >+ <p className="font-medium">+ {t('over', { adding: change.delta, left, plan: quota.planName })}+ </p>+ <p className="text-xs">{t('overHint', { plan: quota.planId })}</p>+ <div className="flex flex-wrap gap-2">+ <PromptLimitActions planId={quota.planId} />+ </div>+ </div>+ )}+ {targets.length === 0 ? (+ <p className="text-xs text-muted-foreground">{t('noPrompts')}</p>+ ) : (+ locations.length > 0 &&+ change.changes.length === 0 && (+ <p className="text-xs text-muted-foreground">{t('nothing')}</p>+ )+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('cancel')}+ </Button>+ <Button+ onClick={() => void save()}+ disabled={saving || over || targets.length === 0 || change.changes.length === 0}+ >+ {saving && <Loader2 className="animate-spin" />}+ {t('submit', { count: locations.length })}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsxindex 5e4d2deb1..571d88f58 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx@@ -2,6 +2,7 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import {Table,@@ -129,6 +130,7 @@ export function LocationMatrix({window,onOpenCell,onTrack,+ onAddLocations,}: {brandId: string;/** Every row the filters keep, for the averages and the cards. */@@ -140,8 +142,11 @@ export function LocationMatrix({onOpenCell: (promptId: string, region: string) => void;/** Adds the location to the prompt; undefined for members who can't edit. */onTrack?: (prompt: Prompt, region: string) => void;+ /** Opens Track in more locations; undefined for members who can't edit. */+ onAddLocations?: () => void;}) {const t = useTranslations('prompts.locations');+ const tAdd = useTranslations('prompts.addLocations');const [metric, setMetric] = useState<LocationMetric>('visibility');const allRegions = matrixLocations(rows);const regions = allRegions.slice(0, MATRIX_REGIONS);@@ -168,8 +173,18 @@ export function LocationMatrix({// eslint-disable-next-line react-hooks/exhaustive-deps}, [key]);+ const addButton = onAddLocations && (+ <Button size="sm" className="h-8 text-xs" onClick={onAddLocations}>+ {tAdd('button')}+ </Button>+ );if (!regions.length) {- return <p className="px-6 py-10 text-center text-sm text-muted-foreground">{t('none')}</p>;+ return (+ <div className="space-y-3 px-6 py-10 text-center">+ <p className="text-sm text-muted-foreground">{t('none')}</p>+ {addButton}+ </div>+ );}const matrix = read?.key === key ? read.matrix : undefined;if (matrix === undefined) {@@ -227,6 +242,8 @@ export function LocationMatrix({{t('capped', { count: MATRIX_REGIONS })}</span>)}+ <span className="flex-1" />+ {addButton}</div><div className="grid gap-3 px-6 sm:grid-cols-3">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_prompt-limit-actions.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_prompt-limit-actions.tsxnew file mode 100644index 000000000..929c0a86d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_prompt-limit-actions.tsx@@ -0,0 +1,37 @@+'use client';++import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { buttonVariants } from '@/components/ui/button-variants';+import { CONTACT_SALES_URL } from '@/config/plans';+import type { LocationQuota } from '@/lib/actions/prompt';++/**+ * Where to go when the limit is reached. Starter can upgrade to Growth in+ * billing; Growth and Enterprise (custom limits) are raised by Ansvisor.+ */+export function PromptLimitActions({ planId }: { planId: LocationQuota['planId'] }) {+ const contact = (+ <a+ href={CONTACT_SALES_URL}+ target="_blank"+ rel="noopener noreferrer"+ className={buttonVariants({+ variant: planId === 'starter' ? 'outline' : 'default',+ size: 'sm',+ })}+ >+ Contact us+ <ExternalLink />+ </a>+ );+ if (planId !== 'starter') return contact;+ return (+ <>+ <Link href="/dashboard/settings?tab=billing" className={buttonVariants({ size: 'sm' })}>+ Upgrade plan+ </Link>+ {contact}+ </>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex cb216c821..11da985a5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -96,7 +96,6 @@ import {Sparkles,ArrowUp,ArrowDown,- ExternalLink,MoreHorizontal,Pause,Play,@@ -159,7 +158,7 @@ import { DateRangeFilter } from '@/components/filters/date-range-filter';import { getBrandFilterOptions } from '@/lib/actions/tracking';import { formatRegionDisplay, isValidLocation, locationCode, regionLabel } from '@/lib/region';import { SuggestionsTab } from './_suggestions-tab';-import { CONTACT_SALES_URL, PLANS } from '@/config/plans';+import { PLANS } from '@/config/plans';import { getPromptUsage, isPromptLimitReached } from '@/lib/prompt-usage';import { getTopics } from '@/lib/actions/topic';import type { PromptVisibilitySummary } from '@/lib/actions/tracking';@@ -199,7 +198,9 @@ import {} from './prompt-sort';import { BulkActionBar } from './_bulk-action-bar';import { ColumnsPanel } from './_columns-panel';+import { PromptLimitActions } from './_prompt-limit-actions';import { LocationMatrix, clearLocationMatrixCache, loadLocationMatrix } from './_location-matrix';+import { AddLocationsDialog, type AddLocationsPreset } from './_add-locations-dialog';import { getPromptTableViews, type PromptTableViews } from '@/lib/actions/prompt-table-views';import {effectiveView,@@ -633,36 +634,6 @@ function brandLocation(region: string | undefined, state: string | undefined): s// ─── Tracked prompt limit (PROMPT-009) ────────────────────────────────────────-/**- * Where to go when the limit is reached. Starter can upgrade to Growth in- * billing; Growth and Enterprise (custom limits) are raised by Ansvisor.- */-function PromptLimitActions({ planId }: { planId: LocationQuota['planId'] }) {- const contact = (- <a- href={CONTACT_SALES_URL}- target="_blank"- rel="noopener noreferrer"- className={buttonVariants({- variant: planId === 'starter' ? 'outline' : 'default',- size: 'sm',- })}- >- Contact us- <ExternalLink />- </a>- );- if (planId !== 'starter') return contact;- return (- <>- <Link href="/dashboard/settings?tab=billing" className={buttonVariants({ size: 'sm' })}>- Upgrade plan- </Link>- {contact}- </>- );-}-/*** Quick-add dialog for the active brand (#460). Same mechanism as the Add* Prompt card on brands/[id]/prompts: topic select + the grouped@@ -3380,6 +3351,11 @@ function AllPromptsTab({if (!loading && positionsId && !openPositions) setPositionsId(null);// The panel opens on the table's window; changing it there only moves the panel.+ // Track in more locations (PROMPT-015c): from the Locations view, or a cell's + Track.+ const [addLocations, setAddLocations] = useState<{+ open: boolean;+ preset: AddLocationsPreset | null;+ }>({ open: false, preset: null });// A Locations view cell opens the panel on its location (PROMPT-015b).const [panelRegion, setPanelRegion] = useState<string | null>(null);const openPositionsPanel = useCallback(@@ -3962,7 +3938,18 @@ function AllPromptsTab({pageRows={pageRows}window={positionsWindow}onOpenCell={(promptId, region) => openPositionsPanel(promptId, 'platforms', region)}- onTrack={onEditPrompt ? (prompt) => onEditPrompt(prompt) : undefined}+ onTrack={+ onEditPrompt+ ? (prompt, region) =>+ setAddLocations({+ open: true,+ preset: { promptId: prompt.id, locations: [region] },+ })+ : undefined+ }+ onAddLocations={+ onEditPrompt ? () => setAddLocations({ open: true, preset: null }) : undefined+ }/>) : (<Table stickyHeader stickyFirstColumn>@@ -4324,6 +4311,21 @@ function AllPromptsTab({</div>))}</CardContent>+ {onEditPrompt && (+ <AddLocationsDialog+ open={addLocations.open}+ onOpenChange={(open) => setAddLocations((prev) => ({ ...prev, open }))}+ brandId={activeBrandId}+ prompts={filtered}+ selectedIds={selectedIds}+ preset={addLocations.preset}+ onDone={() => {+ // The prompts' locations changed: read the matrix again.+ clearLocationMatrixCache();+ onChanged();+ }}+ />+ )}<PromptPositionsSheetprompt={openPositions}range={positionsRange}diff --git a/web/src/components/dashboard/location-picker.tsx b/web/src/components/dashboard/location-picker.tsxindex a4348cbf1..c4283975b 100644--- a/web/src/components/dashboard/location-picker.tsx+++ b/web/src/components/dashboard/location-picker.tsx@@ -3,7 +3,7 @@import { useMemo } from 'react';import { X } from 'lucide-react';-import { REGIONS, US_STATES } from '@/config/prompt-options';+import { TRACKING_COUNTRIES, US_STATES } from '@/config/prompt-options';import { formatRegionDisplay, locationCode, parseLocation } from '@/lib/region';import { Badge } from '@/components/ui/badge';import {@@ -56,7 +56,7 @@ const COUNTRY_ONLY_PLATFORMS = new Set(['google-aio', 'google-aimode']);** Follows the card's existing "add, then chip" idiom (the Platform & Models* picker): the list adds, the chips below remove. It is a Combobox rather- * than a Select because the list is 18 countries plus 50 states — long+ * than a Select because the list is about 50 countries plus 50 states — long* enough that scrolling to a known name is worse than typing it.** Two things this picker must say out loud, because both cost money or@@ -76,7 +76,7 @@ export function LocationPicker({}: LocationPickerProps) {const options = useMemo<LocationOption[]>(() => [- ...REGIONS.map((region) => ({+ ...TRACKING_COUNTRIES.map((region) => ({value: region.code,label: region.label,sublabel: 'Country',diff --git a/web/src/config/prompt-options.ts b/web/src/config/prompt-options.tsindex a3ca9da53..f2f2ff8a4 100644--- a/web/src/config/prompt-options.ts+++ b/web/src/config/prompt-options.ts@@ -23,6 +23,51 @@ export const REGIONS = [export type RegionCode = (typeof REGIONS)[number]['code'];+/**+ * Countries a prompt can be tracked in (PROMPT-015c): the brand regions+ * above, then more markets every tracking engine answers from (the AI+ * engines' provider covers about 195 countries). A brand's own region stays+ * the shorter list: volumes and audits are read for it.+ */+export const TRACKING_COUNTRIES: readonly { code: string; label: string }[] = [+ ...REGIONS,+ { code: 'AR', label: 'Argentina' },+ { code: 'AT', label: 'Austria' },+ { code: 'BE', label: 'Belgium' },+ { code: 'CH', label: 'Switzerland' },+ { code: 'CL', label: 'Chile' },+ { code: 'CO', label: 'Colombia' },+ { code: 'CZ', label: 'Czechia' },+ { code: 'DK', label: 'Denmark' },+ { code: 'EG', label: 'Egypt' },+ { code: 'FI', label: 'Finland' },+ { code: 'GR', label: 'Greece' },+ { code: 'HU', label: 'Hungary' },+ { code: 'ID', label: 'Indonesia' },+ { code: 'IE', label: 'Ireland' },+ { code: 'IL', label: 'Israel' },+ { code: 'KE', label: 'Kenya' },+ { code: 'KW', label: 'Kuwait' },+ { code: 'MA', label: 'Morocco' },+ { code: 'MY', label: 'Malaysia' },+ { code: 'NG', label: 'Nigeria' },+ { code: 'NO', label: 'Norway' },+ { code: 'NZ', label: 'New Zealand' },+ { code: 'PE', label: 'Peru' },+ { code: 'PH', label: 'Philippines' },+ { code: 'PK', label: 'Pakistan' },+ { code: 'PL', label: 'Poland' },+ { code: 'PT', label: 'Portugal' },+ { code: 'QA', label: 'Qatar' },+ { code: 'RO', label: 'Romania' },+ { code: 'SA', label: 'Saudi Arabia' },+ { code: 'TH', label: 'Thailand' },+ { code: 'TW', label: 'Taiwan' },+ { code: 'UA', label: 'Ukraine' },+ { code: 'VN', label: 'Vietnam' },+ { code: 'ZA', label: 'South Africa' },+];+/** `items` for a Select over REGIONS — without it the trigger shows the raw code. */export const REGION_ITEMS = REGIONS.map((r) => ({ value: r.code, label: r.label }));diff --git a/web/src/lib/region.test.ts b/web/src/lib/region.test.tsindex 460dea340..162a550a2 100644--- a/web/src/lib/region.test.ts+++ b/web/src/lib/region.test.ts@@ -66,6 +66,12 @@ describe('location codes', () => {expect(isValidLocation('ZZ')).toBe(false);});+ it('takes the tracking countries beyond the brand regions (PROMPT-015c)', () => {+ expect(isValidLocation('PL')).toBe(true);+ expect(regionLabel('PL')).toBe('Poland');+ expect(isValidLocation('ZA')).toBe(true);+ });+it('builds codes from a country and optional state', () => {expect(locationCode('US')).toBe('US');expect(locationCode('US', null)).toBe('US');diff --git a/web/src/lib/region.ts b/web/src/lib/region.tsindex 60db8a034..6a8e7e3a0 100644--- a/web/src/lib/region.ts+++ b/web/src/lib/region.ts@@ -1,4 +1,4 @@-import { REGIONS, US_STATES } from '@/config/prompt-options';+import { TRACKING_COUNTRIES, US_STATES } from '@/config/prompt-options';/*** Tracking locations (#691).@@ -13,7 +13,7 @@ import { REGIONS, US_STATES } from '@/config/prompt-options';*/const REGION_LABELS: ReadonlyMap<string, string> = new Map(- REGIONS.map((region) => [region.code, region.label]),+ TRACKING_COUNTRIES.map((region) => [region.code, region.label]),);const STATE_LABELS: ReadonlyMap<string, string> = new Map(