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.

feat(prompts): retarget a selection of prompts in one go (#786)

Gökhan Geyik46a2015266e0
diff --git a/supabase/migrations/00074_apply_prompt_locations.sql b/supabase/migrations/00074_apply_prompt_locations.sql
new file mode 100644
index 000000000..9cacdd4bf
--- /dev/null
+++ b/supabase/migrations/00074_apply_prompt_locations.sql
@@ -0,0 +1,57 @@
+-- Apply a bulk retargeting of prompt locations in one statement (#691).
+--
+-- Retargeting a selection is the one prompt edit that meters against the plan:
+-- adding a location to forty prompts costs forty locations. Looping the
+-- single-prompt action over the selection would read, check and write once per
+-- prompt, and the failure mode is the bad one — the twenty-first write hits the
+-- cap and the operation stops half-applied, with no way back and a bill for
+-- what did land. One statement makes the batch all-or-nothing.
+--
+-- The caller passes the finished per-prompt result rather than the operation to
+-- perform. Add/remove semantics, the "never leave a prompt with zero locations"
+-- rule and the quota arithmetic all live in `planBulkLocationChange`
+-- (web/src/lib/prompt-locations.ts), which the dialog also runs to price the
+-- change before the click. Re-implementing that here would give the preview and
+-- the write two definitions that can drift; this function only stores what it
+-- is given.
+--
+-- SECURITY INVOKER, like org_prompt_location_usage (00070): `prompts` carries
+-- an admin/manager update policy through its prompt set's brand, so RLS decides
+-- which ids a caller may touch. Ids outside the caller's organization simply
+-- match no row, and the returned count reflects that.
+--
+-- The plan cap itself stays in the app tier, because the limit lives in the
+-- plan config rather than the database (`maxPrompts`, with enterprise
+-- overrides). A concurrent write between the check and this call could still
+-- carry an org a few locations past its cap — the same window the single-prompt
+-- path has always had, and bounded by what one batch can add.
+create or replace function public.apply_prompt_locations(p_updates jsonb)
+returns bigint
+language sql
+volatile
+security invoker
+set search_path to 'public'
+as $$
+ with wanted as (
+ select (e ->> 'id')::uuid as id,
+ array(select jsonb_array_elements_text(e -> 'regions')) as regions
+ from jsonb_array_elements(p_updates) e
+ ),
+ applied as (
+ update public.prompts p
+ set regions = w.regions
+ from wanted w
+ -- The empty guard is defence in depth: a prompt with no location is not
+ -- tracked at all, and the planner already refuses to produce one.
+ where p.id = w.id
+ and coalesce(array_length(w.regions, 1), 0) > 0
+ returning 1
+ )
+ select count(*)::bigint from applied;
+$$;
+
+revoke all on function public.apply_prompt_locations(jsonb) from public;
+grant execute on function public.apply_prompt_locations(jsonb) to authenticated, service_role;
+
+comment on function public.apply_prompt_locations(jsonb) is
+ 'Bulk-writes prompt tracking locations from [{id, regions}] (#691), one statement so a batch cannot land half-applied. Security invoker: RLS decides which prompts the caller may retarget.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 6b959fa83..7118ef804 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -8595,3 +8595,64 @@ update brands
set logo_url = null
where logo_url like '%s2/favicons%';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00074_apply_prompt_locations.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Apply a bulk retargeting of prompt locations in one statement (#691).
+--
+-- Retargeting a selection is the one prompt edit that meters against the plan:
+-- adding a location to forty prompts costs forty locations. Looping the
+-- single-prompt action over the selection would read, check and write once per
+-- prompt, and the failure mode is the bad one — the twenty-first write hits the
+-- cap and the operation stops half-applied, with no way back and a bill for
+-- what did land. One statement makes the batch all-or-nothing.
+--
+-- The caller passes the finished per-prompt result rather than the operation to
+-- perform. Add/remove semantics, the "never leave a prompt with zero locations"
+-- rule and the quota arithmetic all live in `planBulkLocationChange`
+-- (web/src/lib/prompt-locations.ts), which the dialog also runs to price the
+-- change before the click. Re-implementing that here would give the preview and
+-- the write two definitions that can drift; this function only stores what it
+-- is given.
+--
+-- SECURITY INVOKER, like org_prompt_location_usage (00070): `prompts` carries
+-- an admin/manager update policy through its prompt set's brand, so RLS decides
+-- which ids a caller may touch. Ids outside the caller's organization simply
+-- match no row, and the returned count reflects that.
+--
+-- The plan cap itself stays in the app tier, because the limit lives in the
+-- plan config rather than the database (`maxPrompts`, with enterprise
+-- overrides). A concurrent write between the check and this call could still
+-- carry an org a few locations past its cap — the same window the single-prompt
+-- path has always had, and bounded by what one batch can add.
+create or replace function public.apply_prompt_locations(p_updates jsonb)
+returns bigint
+language sql
+volatile
+security invoker
+set search_path to 'public'
+as $$
+ with wanted as (
+ select (e ->> 'id')::uuid as id,
+ array(select jsonb_array_elements_text(e -> 'regions')) as regions
+ from jsonb_array_elements(p_updates) e
+ ),
+ applied as (
+ update public.prompts p
+ set regions = w.regions
+ from wanted w
+ -- The empty guard is defence in depth: a prompt with no location is not
+ -- tracked at all, and the planner already refuses to produce one.
+ where p.id = w.id
+ and coalesce(array_length(w.regions, 1), 0) > 0
+ returning 1
+ )
+ select count(*)::bigint from applied;
+$$;
+
+revoke all on function public.apply_prompt_locations(jsonb) from public;
+grant execute on function public.apply_prompt_locations(jsonb) to authenticated, service_role;
+
+comment on function public.apply_prompt_locations(jsonb) is
+ 'Bulk-writes prompt tracking locations from [{id, regions}] (#691), one statement so a batch cannot land half-applied. Security invoker: RLS decides which prompts the caller may retarget.';
+
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 b92e443b4..7f8b598fd 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
@@ -9,12 +9,16 @@ import {
addPromptToSet,
updatePrompt,
updatePromptLocations,
+ bulkUpdatePromptLocations,
getLocationQuota,
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 { LocationPicker } from '@/components/dashboard/location-picker';
+import { planBulkLocationChange } from '@/lib/prompt-locations';
+import { formatRegionDisplay } from '@/lib/region';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
@@ -28,7 +32,8 @@ import {
} from '@/components/ui/select';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
-import { Loader2, Plus, Sparkles, Save, X, Play, Search, Lock } from 'lucide-react';
+import { Loader2, Plus, Sparkles, Save, X, Play, Search, Lock, Globe } from 'lucide-react';
+import { cn } from '@/lib/utils';
import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';
import { usePlanContext } from '@/components/providers/plan-provider';
import { useUserRole } from '@/hooks/use-user-role';
@@ -112,6 +117,14 @@ export default function PromptsPage() {
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [analyzeDialogOpen, setAnalyzeDialogOpen] = useState(false);
const [selectedAnalyzeIds, setSelectedAnalyzeIds] = useState<Set<string>>(new Set());
+
+ // Bulk retargeting (#691). Adding a location to a selection multiplies
+ // scraper spend, so the dialog prices the change before it is applied.
+ const [bulkOpen, setBulkOpen] = useState(false);
+ const [bulkAction, setBulkAction] = useState<'add' | 'remove'>('add');
+ const [bulkLocations, setBulkLocations] = useState<string[]>([]);
+ const [bulkPromptIds, setBulkPromptIds] = useState<Set<string>>(new Set());
+ const [isBulkSaving, setIsBulkSaving] = useState(false);
const [isLoadingUnanalyzed, setIsLoadingUnanalyzed] = useState(false);
// Flatten all prompts from all sets, sorted newest first
@@ -426,6 +439,64 @@ export default function PromptsPage() {
[brandId, updatePromptLocal, loadData],
);
+ // The dialog prices the change with the same function the server action
+ // enforces with, so the preview and the guard cannot disagree.
+ const bulkPlan = useMemo(
+ () =>
+ planBulkLocationChange(
+ allPrompts.filter((p) => bulkPromptIds.has(p.id)),
+ bulkAction,
+ bulkLocations,
+ ),
+ [allPrompts, bulkPromptIds, bulkAction, bulkLocations],
+ );
+
+ // Every engine the selection spans: the state-targeting caveat applies if
+ // any selected prompt runs a country-only engine.
+ const bulkSelectedPlatforms = useMemo(
+ () => [
+ ...new Set(allPrompts.filter((p) => bulkPromptIds.has(p.id)).flatMap((p) => p.platforms)),
+ ],
+ [allPrompts, bulkPromptIds],
+ );
+
+ const openBulkDialog = useCallback(() => {
+ setBulkAction('add');
+ setBulkLocations([]);
+ setBulkPromptIds(new Set(allPrompts.map((p) => p.id)));
+ setBulkOpen(true);
+ }, [allPrompts]);
+
+ const handleBulkApply = useCallback(async () => {
+ if (bulkPromptIds.size === 0 || bulkLocations.length === 0) return;
+ setIsBulkSaving(true);
+ try {
+ const result = await bulkUpdatePromptLocations(
+ Array.from(bulkPromptIds),
+ bulkAction,
+ bulkLocations,
+ );
+ if ('error' in result) {
+ toast.error(result.error);
+ return;
+ }
+ // Report what did NOT happen too: a silent "12 updated" hides the
+ // single-location prompts a removal deliberately left alone.
+ const parts = [
+ `${result.updated} prompt${result.updated === 1 ? '' : 's'} updated`,
+ result.unchanged > 0 ? `${result.unchanged} already matched` : null,
+ result.blocked > 0 ? `${result.blocked} kept their only location` : null,
+ ].filter(Boolean);
+ toast.success(parts.join(' · '));
+ setBulkOpen(false);
+ await loadData();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to update locations');
+ } finally {
+ setIsBulkSaving(false);
+ }
+ }, [bulkPromptIds, bulkLocations, bulkAction, loadData]);
+
const handlePlatformsChange = useCallback(
async (promptId: string, platforms: string[]) => {
updatePromptLocal(promptId, { platforms: platforms as Prompt['platforms'] });
@@ -882,19 +953,25 @@ export default function PromptsPage() {
<div className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold">All Prompts ({allPrompts.length})</h2>
- <Button
- size="sm"
- variant={unanalyzedPrompts.length > 0 ? 'default' : 'outline'}
- onClick={openAnalyzeDialog}
- >
- <Search className="mr-2 h-3.5 w-3.5" />
- Analyze Prompts
- {unanalyzedPrompts.length > 0 && (
- <Badge variant="secondary" className="ml-2 text-[10px]">
- {unanalyzedPrompts.length} new
- </Badge>
- )}
- </Button>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" onClick={openBulkDialog}>
+ <Globe className="mr-2 h-3.5 w-3.5" />
+ Locations
+ </Button>
+ <Button
+ size="sm"
+ variant={unanalyzedPrompts.length > 0 ? 'default' : 'outline'}
+ onClick={openAnalyzeDialog}
+ >
+ <Search className="mr-2 h-3.5 w-3.5" />
+ Analyze Prompts
+ {unanalyzedPrompts.length > 0 && (
+ <Badge variant="secondary" className="ml-2 text-[10px]">
+ {unanalyzedPrompts.length} new
+ </Badge>
+ )}
+ </Button>
+ </div>
</div>
<div className="space-y-2">
{allPrompts.map((prompt) => (
@@ -1040,6 +1117,153 @@ export default function PromptsPage() {
</DialogFooter>
</DialogContent>
</Dialog>
+
+ {/* Bulk locations dialog (#691) */}
+ <Dialog open={bulkOpen} onOpenChange={setBulkOpen}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Tracking locations</DialogTitle>
+ <DialogDescription>
+ Add a location to several prompts at once, or stop tracking one. Each prompt keeps the
+ locations you don&apos;t touch.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ <div className="inline-flex rounded-lg border p-1" role="tablist">
+ {(['add', 'remove'] as const).map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ role="tab"
+ aria-selected={bulkAction === mode}
+ onClick={() => setBulkAction(mode)}
+ className={cn(
+ 'rounded-md px-3 py-1 text-xs font-medium transition-colors',
+ bulkAction === mode
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ >
+ {mode === 'add' ? 'Add' : 'Remove'}
+ </button>
+ ))}
+ </div>
+
+ <LocationPicker
+ value={bulkLocations}
+ onChange={setBulkLocations}
+ maxSelectable={null}
+ allowEmpty
+ label={bulkAction === 'add' ? 'Locations to add' : 'Locations to remove'}
+ countNoun="selected"
+ platforms={bulkSelectedPlatforms}
+ />
+
+ <div>
+ <div className="mb-1.5 flex items-center justify-between">
+ <span className="text-xs font-medium text-muted-foreground">
+ {bulkPromptIds.size} of {allPrompts.length} prompts selected
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ setBulkPromptIds(
+ bulkPromptIds.size === allPrompts.length
+ ? new Set()
+ : new Set(allPrompts.map((p) => p.id)),
+ )
+ }
+ >
+ {bulkPromptIds.size === allPrompts.length ? 'Deselect All' : 'Select All'}
+ </Button>
+ </div>
+ <div className="max-h-56 space-y-1.5 overflow-y-auto rounded-md border p-2">
+ {allPrompts.map((prompt) => {
+ const checked = bulkPromptIds.has(prompt.id);
+ return (
+ <label
+ key={prompt.id}
+ className="flex cursor-pointer items-start gap-2.5 rounded-md p-2 transition-colors hover:bg-muted/50"
+ >
+ <Checkbox
+ checked={checked}
+ onCheckedChange={() =>
+ setBulkPromptIds((prev) => {
+ const next = new Set(prev);
+ if (checked) next.delete(prompt.id);
+ else next.add(prompt.id);
+ return next;
+ })
+ }
+ className="mt-0.5"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm leading-snug">{prompt.text}</p>
+ <div className="mt-0.5 flex flex-wrap gap-1">
+ {prompt.regions.map((r) => (
+ <span key={r} className="text-[10px] text-muted-foreground">
+ {formatRegionDisplay(r)}
+ </span>
+ ))}
+ </div>
+ </div>
+ </label>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Priced before the click: every added location is another set of
+ scraper and model calls, and another unit against the plan. */}
+ {bulkLocations.length > 0 && (
+ <div className="rounded-md border bg-muted/30 px-3 py-2 text-xs">
+ {bulkPlan.changes.length === 0 ? (
+ <span className="text-muted-foreground">
+ Nothing to change — the selected prompts already match.
+ </span>
+ ) : (
+ <>
+ <span className="font-medium">
+ {bulkPlan.changes.length} prompt
+ {bulkPlan.changes.length === 1 ? '' : 's'} will change
+ </span>
+ <span className="text-muted-foreground">
+ {' · '}
+ {bulkPlan.delta >= 0 ? '+' : ''}
+ {bulkPlan.delta} location{Math.abs(bulkPlan.delta) === 1 ? '' : 's'}
+ {locationQuota && locationQuota.maxPrompts !== -1
+ ? ` (${locationQuota.used + bulkPlan.delta} of ${locationQuota.maxPrompts} used)`
+ : ''}
+ </span>
+ {bulkPlan.blocked > 0 && (
+ <p className="mt-1 text-muted-foreground">
+ {bulkPlan.blocked} prompt{bulkPlan.blocked === 1 ? '' : 's'} would be left
+ with no location, so {bulkPlan.blocked === 1 ? 'it stays' : 'they stay'} as
+ {bulkPlan.blocked === 1 ? ' it is' : ' they are'}.
+ </p>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setBulkOpen(false)} disabled={isBulkSaving}>
+ Cancel
+ </Button>
+ <Button
+ onClick={handleBulkApply}
+ disabled={isBulkSaving || bulkPlan.changes.length === 0}
+ >
+ {isBulkSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ {bulkAction === 'add' ? 'Add' : 'Remove'} ({bulkPlan.changes.length})
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</div>
);
}
diff --git a/web/src/components/dashboard/location-picker.tsx b/web/src/components/dashboard/location-picker.tsx
index 138310a7c..61eaee6c6 100644
--- a/web/src/components/dashboard/location-picker.tsx
+++ b/web/src/components/dashboard/location-picker.tsx
@@ -36,6 +36,16 @@ export interface LocationPickerProps {
maxSelectable: number | null;
/** Engines the prompt runs, to warn where state targeting doesn't apply. */
platforms?: string[];
+ /** Field label. Defaults to the per-prompt wording. */
+ label?: string;
+ /** What the count describes, when the plan is unlimited. */
+ countNoun?: string;
+ /**
+ * Allow clearing every chip. A prompt must keep at least one location — it
+ * cannot be tracked otherwise — but a picker used to CHOOSE locations (the
+ * bulk dialog) has no such floor.
+ */
+ allowEmpty?: boolean;
}
/** Engines with no sub-country mechanism — mirrors the worker's collapse. */
@@ -55,7 +65,15 @@ const COUNTRY_ONLY_PLATFORMS = new Set(['google-aio', 'google-aimode']);
* and Google's engines have no state targeting, so a state pick runs them
* country-wide instead of twice.
*/
-export function LocationPicker({ value, onChange, maxSelectable, platforms }: LocationPickerProps) {
+export function LocationPicker({
+ value,
+ onChange,
+ maxSelectable,
+ platforms,
+ label = 'Locations',
+ countNoun = 'tracked',
+ allowEmpty = false,
+}: LocationPickerProps) {
const options = useMemo<LocationOption[]>(
() => [
...REGIONS.map((region) => ({
@@ -77,7 +95,7 @@ export function LocationPicker({ value, onChange, maxSelectable, platforms }: Lo
// A prompt with no location cannot be tracked, so the last chip keeps its
// remove control hidden rather than failing server-side.
- const canRemove = value.length > 1;
+ const canRemove = allowEmpty || value.length > 1;
const hasStatePick = value.some((code) => parseLocation(code)?.state);
const countryOnlyEngines = (platforms ?? []).filter((id) => COUNTRY_ONLY_PLATFORMS.has(id));
@@ -96,10 +114,10 @@ export function LocationPicker({ value, onChange, maxSelectable, platforms }: Lo
return (
<div>
<label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Locations
+ {label}
<span className="ml-1 font-normal">
{maxSelectable === null
- ? `· ${value.length} tracked`
+ ? `· ${value.length} ${countNoun}`
: `· ${value.length} of ${maxSelectable} available`}
</span>
</label>
@@ -125,7 +143,7 @@ export function LocationPicker({ value, onChange, maxSelectable, platforms }: Lo
<div>{formatRegionDisplay(option.value)}</div>
<div className="text-[10px] text-muted-foreground">
{selected.has(option.value)
- ? 'Already tracked'
+ ? `Already ${countNoun}`
: atCap
? 'Plan limit reached — remove a location or upgrade'
: option.sublabel}
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index ca26b63d0..581779fd3 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -7,6 +7,7 @@ import { getOrgPlan } from '@/lib/guards/plan-guard';
import {
getOrgLocationUsage,
locationLimitMessage,
+ planBulkLocationChange,
promptLocationCount,
} from '@/lib/prompt-locations';
import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/prompt-options';
@@ -432,6 +433,118 @@ export async function updatePromptLocations(
return { prompt: mapPromptRow(data as Record<string, unknown>) };
}
+/**
+ * PostgREST takes an `.in()` list in the query string, so a selection of a few
+ * hundred prompts would overrun the request line long before the row cap
+ * mattered — 100 UUIDs is already ~3.7KB (#427's lesson, same constant as the
+ * fan-out roster read). The write itself goes out as a POST body and needs no
+ * chunking.
+ */
+const BULK_LOCATION_READ_CHUNK = 100;
+
+export interface BulkLocationSummary {
+ /** Prompts whose locations moved. */
+ updated: number;
+ /** Already had every added location, or none of the removed ones. */
+ unchanged: number;
+ /** Skipped: the removal would have left them with no location at all. */
+ blocked: number;
+ /** Locations the batch added (negative when it freed some). */
+ delta: number;
+}
+
+export type BulkUpdatePromptLocationsResult =
+ | BulkLocationSummary
+ | { error: string; code?: 'plan_limit' };
+
+/**
+ * Add or remove one or more tracking locations across a selection of prompts
+ * (#691).
+ *
+ * Add/remove rather than "set every selected prompt to this list": a selection
+ * can hold prompts targeting different places, and assigning one list to all of
+ * them would erase that targeting without saying so.
+ *
+ * The plan cap is measured once, for the whole batch, and the write goes out as
+ * a single statement (`apply_prompt_locations`, 00074). Looping the
+ * single-prompt action instead would check the cap once per prompt and could
+ * stop half-way through, leaving a partly-retargeted selection and a bill for
+ * whatever landed before the limit bit.
+ *
+ * Current locations are re-read here rather than taken from the caller: the
+ * quota arithmetic must not rest on numbers the client supplied.
+ */
+export async function bulkUpdatePromptLocations(
+ promptIds: string[],
+ action: 'add' | 'remove',
+ locationsInput: string[],
+): Promise<BulkUpdatePromptLocationsResult> {
+ const supabase = await createClient();
+
+ const ids = [...new Set(promptIds)].filter(Boolean);
+ if (ids.length === 0) return { error: 'Select at least one prompt.' };
+
+ const locations = [...new Set(locationsInput.map((r) => r.trim().toUpperCase()))].filter(Boolean);
+ if (locations.length === 0) return { error: 'Select at least one location.' };
+ const unknown = locations.filter((r) => !isValidLocation(r));
+ if (unknown.length > 0) {
+ return {
+ error: `Unknown location code${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`,
+ };
+ }
+
+ const rows: { id: string; regions: string[]; organizationId: string }[] = [];
+ for (let i = 0; i < ids.length; i += BULK_LOCATION_READ_CHUNK) {
+ const { data, error } = await supabase
+ .from('prompts')
+ .select('id, regions, prompt_sets!inner(brands!inner(organization_id))')
+ .in('id', ids.slice(i, i + BULK_LOCATION_READ_CHUNK));
+ if (error) return { error: error.message };
+ for (const row of data ?? []) {
+ const orgId = (row.prompt_sets as unknown as { brands: { organization_id: string } } | null)
+ ?.brands?.organization_id;
+ if (!orgId) continue;
+ rows.push({
+ id: row.id as string,
+ regions: (row.regions as string[] | null) ?? [],
+ organizationId: orgId,
+ });
+ }
+ }
+
+ // RLS decides what came back; a selection that resolves to nothing is a
+ // stale page, not a request to write.
+ if (rows.length === 0) return { error: 'None of the selected prompts are available.' };
+
+ const plan = planBulkLocationChange(rows, action, locations);
+ if (plan.changes.length === 0) {
+ return { updated: 0, unchanged: plan.unchanged, blocked: plan.blocked, delta: 0 };
+ }
+
+ if (plan.delta > 0) {
+ const orgId = rows[0].organizationId;
+ const [orgPlan, usage] = await Promise.all([
+ getOrgPlan(orgId),
+ getOrgLocationUsage(supabase, orgId),
+ ]);
+ const limitError = locationLimitMessage(orgPlan, usage.total, plan.delta);
+ if (limitError) return { error: limitError, code: 'plan_limit' };
+ }
+
+ const { data: written, error } = await supabase.rpc('apply_prompt_locations', {
+ p_updates: plan.changes.map((c) => ({ id: c.promptId, regions: c.regions })),
+ });
+ if (error) return { error: error.message };
+
+ revalidatePath('/dashboard/brands');
+ return {
+ updated: Number(written ?? 0),
+ unchanged: plan.unchanged,
+ blocked: plan.blocked,
+ delta: plan.delta,
+ };
+}
+
/**
* Org-wide tracked-location usage against the plan cap, for the prompts page
* to bound its location pickers before a save can fail.
diff --git a/web/src/lib/prompt-locations.test.ts b/web/src/lib/prompt-locations.test.ts
index c805ed9ec..da17b553b 100644
--- a/web/src/lib/prompt-locations.test.ts
+++ b/web/src/lib/prompt-locations.test.ts
@@ -3,6 +3,7 @@ import {
promptLocationCount,
summarizeLocationRows,
locationLimitMessage,
+ planBulkLocationChange,
} from './prompt-locations';
import { PLANS } from '@/config/plans';
@@ -83,3 +84,76 @@ describe('locationLimitMessage', () => {
expect(locationLimitMessage(starter, 50, 1)).toContain('Remove 1 location ');
});
});
+
+describe('planBulkLocationChange', () => {
+ const prompts = [
+ { id: 'a', regions: ['US'] },
+ { id: 'b', regions: ['US', 'DE'] },
+ { id: 'c', regions: ['TR'] },
+ ];
+
+ it('adds a location only where it is missing', () => {
+ const plan = planBulkLocationChange(prompts, 'add', ['DE']);
+ expect(plan.changes.map((c) => c.promptId)).toEqual(['a', 'c']);
+ expect(plan.changes[0].regions).toEqual(['US', 'DE']);
+ // 'b' already had DE — no cost, no write.
+ expect(plan.unchanged).toBe(1);
+ expect(plan.delta).toBe(2);
+ });
+
+ it('appends rather than reorders, so existing targeting is untouched', () => {
+ const plan = planBulkLocationChange([{ id: 'a', regions: ['DE', 'US'] }], 'add', ['TR']);
+ expect(plan.changes[0].regions).toEqual(['DE', 'US', 'TR']);
+ });
+
+ it('removes a location and frees capacity', () => {
+ const plan = planBulkLocationChange(prompts, 'remove', ['DE']);
+ expect(plan.changes.map((c) => c.promptId)).toEqual(['b']);
+ expect(plan.changes[0].regions).toEqual(['US']);
+ expect(plan.delta).toBe(-1);
+ expect(plan.unchanged).toBe(2);
+ });
+
+ it('never empties a prompt — single-location prompts are skipped, not emptied', () => {
+ // 'a' and 'c' each target one location; removing it would make them
+ // untrackable, so they stay and are reported.
+ const plan = planBulkLocationChange(prompts, 'remove', ['US', 'TR']);
+ expect(plan.blocked).toBe(2);
+ expect(plan.changes.map((c) => c.promptId)).toEqual(['b']);
+ expect(plan.changes[0].regions).toEqual(['DE']);
+ });
+
+ it('counts a batch add as one location per prompt', () => {
+ const many = Array.from({ length: 40 }, (_, i) => ({ id: `p${i}`, regions: ['US'] }));
+ expect(planBulkLocationChange(many, 'add', ['DE']).delta).toBe(40);
+ });
+
+ it('prices multiple locations per prompt', () => {
+ const plan = planBulkLocationChange([{ id: 'a', regions: ['US'] }], 'add', ['DE', 'TR']);
+ expect(plan.delta).toBe(2);
+ expect(plan.changes[0].regions).toEqual(['US', 'DE', 'TR']);
+ });
+
+ it('normalizes case and ignores duplicates in the requested list', () => {
+ const plan = planBulkLocationChange([{ id: 'a', regions: ['US'] }], 'add', [
+ 'de',
+ 'DE',
+ ' de ',
+ ]);
+ expect(plan.delta).toBe(1);
+ expect(plan.changes[0].regions).toEqual(['US', 'DE']);
+ });
+
+ it('does nothing when no location is chosen', () => {
+ const plan = planBulkLocationChange(prompts, 'add', []);
+ expect(plan).toEqual({ changes: [], unchanged: 0, blocked: 0, delta: 0 });
+ });
+
+ it('charges nothing for the first location of a prompt that had none', () => {
+ // An empty region list already costs one — the worker runs it untargeted
+ // once — so naming that location is free.
+ const plan = planBulkLocationChange([{ id: 'a', regions: [] }], 'add', ['DE']);
+ expect(plan.changes[0].regions).toEqual(['DE']);
+ expect(plan.delta).toBe(0);
+ });
+});
diff --git a/web/src/lib/prompt-locations.ts b/web/src/lib/prompt-locations.ts
index 92a13befe..33d0f4c75 100644
--- a/web/src/lib/prompt-locations.ts
+++ b/web/src/lib/prompt-locations.ts
@@ -100,3 +100,81 @@ export function locationLimitMessage(plan: Plan, used: number, adding: number):
`to continue, or upgrade your plan.`
);
}
+
+// ─── Bulk retargeting ────────────────────────────────────────────────────────
+
+export interface PromptLocations {
+ id: string;
+ regions: string[];
+}
+
+export interface BulkLocationChange {
+ promptId: string;
+ /** The prompt's locations after the change. Never empty. */
+ regions: string[];
+ /** Locations this prompt gains (negative when it loses some). */
+ delta: number;
+}
+
+export interface BulkLocationPlan {
+ /** Only the prompts whose locations actually move. */
+ changes: BulkLocationChange[];
+ /** Already had every added location, or had none of the removed ones. */
+ unchanged: number;
+ /** Would have been left with no location at all, so they were left alone. */
+ blocked: number;
+ /** Locations the whole batch adds — what the plan cap is measured against. */
+ delta: number;
+}
+
+/**
+ * Work out what a bulk add/remove does, before anything is written (#691).
+ *
+ * Add and remove rather than "set the list to X": prompts in a selection can
+ * target different places, and assigning one list to all of them would wipe
+ * that targeting silently. Adding a location a prompt already has, or
+ * removing one it doesn't, costs nothing and changes nothing.
+ *
+ * A prompt is never left with zero locations — one with no location cannot
+ * be tracked at all — so a remove that would empty a prompt skips it and is
+ * reported instead. The batch still applies to everything else: refusing the
+ * whole operation because one prompt of forty is single-location would be
+ * worse than telling the user which ones stayed put.
+ *
+ * The same function runs in the dialog (to price the change before the click)
+ * and in the server action (to enforce it), so the preview and the guard can
+ * never disagree.
+ */
+export function planBulkLocationChange(
+ prompts: readonly PromptLocations[],
+ action: 'add' | 'remove',
+ locations: readonly string[],
+): BulkLocationPlan {
+ const wanted = [...new Set(locations.map((code) => code.trim().toUpperCase()))].filter(Boolean);
+ const plan: BulkLocationPlan = { changes: [], unchanged: 0, blocked: 0, delta: 0 };
+ if (wanted.length === 0) return plan;
+
+ for (const prompt of prompts) {
+ const current = prompt.regions ?? [];
+ const next =
+ action === 'add'
+ ? [...current, ...wanted.filter((code) => !current.includes(code))]
+ : current.filter((code) => !wanted.includes(code));
+
+ if (next.length === current.length) {
+ plan.unchanged++;
+ continue;
+ }
+ // Removing every location would make the prompt untrackable.
+ if (next.length === 0) {
+ plan.blocked++;
+ continue;
+ }
+
+ const delta = promptLocationCount(next) - promptLocationCount(current);
+ plan.changes.push({ promptId: prompt.id, regions: next, delta });
+ plan.delta += delta;
+ }
+
+ return plan;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 1187486fc..42e810930 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -2406,6 +2406,10 @@ export type Database = {
}
Returns: Json
}
+ apply_prompt_locations: {
+ Args: { p_updates: Json }
+ Returns: number
+ }
citation_competitor_sources: {
Args: {
p_brand_domains: string[]