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): bulk import prompts and add several at once (#1013)
Cihan32a4d7b79534
diff --git a/server/src/routes/tracking-analyze-new.test.js b/server/src/routes/tracking-analyze-new.test.jsnew file mode 100644index 000000000..369572fca--- /dev/null+++ b/server/src/routes/tracking-analyze-new.test.js@@ -0,0 +1,116 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * POST /analyze-new with the prompt ids a bulk import sends (up to 1,000).+ * One PostgREST `in` filter over that many ids fails, and the route used to+ * read the failure as "nothing new", so a large import never got its first+ * analysis. These pin that every `in` filter stays at 100 ids and that a+ * failed lookup is an error, not `newCount: 0`.+ */++const createJob = vi.fn();+const runTrackingJob = vi.fn();++let inSizes = [];+let failTable = null;++function builder(table) {+ const filters = {};+ const chain = {+ select: () => chain,+ eq: () => chain,+ in: (column, values) => {+ inSizes.push({ table, column, size: values.length });+ filters[column] = values;+ return chain;+ },+ single: async () => {+ if (table === 'brands') {+ return { data: { id: 'b1', organization_id: 'org-1', is_active: true }, error: null };+ }+ if (table === 'profiles') return { data: { organization_id: 'org-1' }, error: null };+ return { data: null, error: null };+ },+ then: (resolve) => {+ if (table === failTable) return resolve({ data: null, error: new Error('URI too long') });+ if (table === 'prompt_sets') return resolve({ data: [{ id: 'set-1' }], error: null });+ if (table === 'prompts') {+ return resolve({ data: (filters.id ?? []).map((id) => ({ id })), error: null });+ }+ // No prompt has results yet: every imported prompt is new.+ return resolve({ data: [], error: null });+ },+ };+ return chain;+}++vi.mock('../config/supabase.js', () => ({ default: { from: (table) => builder(table) } }));+vi.mock('../lib/job-manager.js', () => ({ createJob, getJob: vi.fn(), cancelJob: vi.fn() }));+vi.mock('../lib/job-runner.js', () => ({ runTrackingJob }));+vi.mock('../lib/tracking-quota.js', () => ({+ enforceOnDemandTrackingQuota: vi.fn(),+ TrackingQuotaError: class TrackingQuotaError extends Error {},+}));+vi.mock('../lib/access.js', () => ({ assertBrandAccess: vi.fn() }));++const { default: router } = await import('./tracking.js');++const handler = router.stack.find((layer) => layer.route?.path === '/analyze-new').route.stack[0]+ .handle;++async function analyzeNew(body) {+ const res = {+ statusCode: 200,+ body: null,+ status(code) {+ this.statusCode = code;+ return this;+ },+ json(payload) {+ this.body = payload;+ return this;+ },+ };+ const req = {+ body,+ user: { id: 'u1' },+ log: { error: vi.fn() },+ app: { get: () => null },+ };+ await handler(req, res);+ return res;+}++const ids = Array.from(+ { length: 1000 },+ (_, i) => `00000000-0000-0000-0000-${String(i).padStart(12, '0')}`,+);++describe('POST /analyze-new', () => {+ beforeEach(() => {+ inSizes = [];+ failTable = null;+ createJob.mockReset().mockResolvedValue({ id: 'job-1' });+ runTrackingJob.mockReset();+ });++ it('submits all 1,000 imported prompts with no `in` filter over 100 ids', async () => {+ const res = await analyzeNew({ brandId: 'b1', promptIds: ids });++ expect(res.body).toMatchObject({ success: true, jobId: 'job-1', newCount: 1000 });+ expect(createJob.mock.calls[0][0].data.promptIds).toHaveLength(1000);+ const idFilters = inSizes.filter((f) => f.column !== 'prompt_set_id');+ expect(idFilters.length).toBeGreaterThanOrEqual(20);+ expect(Math.max(...idFilters.map((f) => f.size))).toBeLessThanOrEqual(100);+ });++ it('fails instead of reporting nothing new when a lookup errors', async () => {+ failTable = 'prompt_results';++ const res = await analyzeNew({ brandId: 'b1', promptIds: ids });++ expect(res.statusCode).toBe(500);+ expect(res.body).toMatchObject({ success: false });+ expect(createJob).not.toHaveBeenCalled();+ });+});diff --git a/server/src/routes/tracking.js b/server/src/routes/tracking.jsindex b59d2a4af..59d1e7d67 100644--- a/server/src/routes/tracking.js+++ b/server/src/routes/tracking.js@@ -4,6 +4,7 @@ import { runTrackingJob } from '../lib/job-runner.js';import supabaseAdmin from '../config/supabase.js';import { enforceOnDemandTrackingQuota, TrackingQuotaError } from '../lib/tracking-quota.js';import { assertBrandAccess } from '../lib/access.js';+import { selectInChunks } from '../lib/chunked-in.js';const router = Router();@@ -137,12 +138,18 @@ router.post('/analyze-new', async (req, res) => {if (Array.isArray(clientPromptIds) && clientPromptIds.length > 0) {// Client sent specific prompt IDs — validate they belong to this brand.- const { data: validPrompts } = await supabaseAdmin- .from('prompts')- .select('id')- .in('prompt_set_id', setIds)- .in('id', clientPromptIds)- .eq('is_active', true);+ // A bulk import sends up to 1,000, more than one `in` filter carries.+ const { data: validPrompts, error: validErr } = await selectInChunks(+ clientPromptIds,+ (chunk) =>+ supabaseAdmin+ .from('prompts')+ .select('id')+ .in('prompt_set_id', setIds)+ .in('id', chunk)+ .eq('is_active', true),+ );+ if (validErr) throw validErr;candidateIds = (validPrompts || []).map((p) => p.id);} else {@@ -168,11 +175,16 @@ router.post('/analyze-new', async (req, res) => {// landing, which previously caused duplicate Cloro/LLM spend.let newPromptIds = candidateIds;if (candidateIds.length > 0) {- const { data: existingResults } = await supabaseAdmin- .from('prompt_results')- .select('prompt_id')- .eq('brand_id', brandId)- .in('prompt_id', candidateIds);+ const { data: existingResults, error: existingErr } = await selectInChunks(+ candidateIds,+ (chunk) =>+ supabaseAdmin+ .from('prompt_results')+ .select('prompt_id')+ .eq('brand_id', brandId)+ .in('prompt_id', chunk),+ );+ if (existingErr) throw existingErr;const analyzedIds = new Set((existingResults || []).map((r) => r.prompt_id));newPromptIds = candidateIds.filter((id) => !analyzedIds.has(id));diff --git a/supabase/migrations/00122_import_prompts.sql b/supabase/migrations/00122_import_prompts.sqlnew file mode 100644index 000000000..ac1eabc7c--- /dev/null+++ b/supabase/migrations/00122_import_prompts.sql@@ -0,0 +1,77 @@+-- Bulk import of prompts from a spreadsheet (PROMPT-005), capped at the plan+-- limit inside the database.+--+-- The single-prompt path checks the cap in the app tier and then inserts,+-- which leaves a window where two writes can both pass the check (00074).+-- One prompt at a time that window costs at most a location or two; a bulk+-- import can add hundreds, and the task requires that two imports running at+-- once still stop at the limit. So this function takes a per-organization+-- advisory lock, counts the org's tracked locations, and inserts the rows in+-- the order given until the next one would not fit. A second import waits for+-- the first to commit and then counts what it added.+--+-- The rows arrive already validated and resolved (topic ids, plan-filtered+-- platforms) by the server action, which runs the same preview the dialog+-- showed (web/src/lib/prompt-import.ts). This function only stores them and+-- enforces the cap. -1 means unlimited.+--+-- SECURITY INVOKER: `prompts` keeps its admin/manager insert policy through+-- the prompt set's brand, so RLS still decides whether the caller may write.++create or replace function public.import_prompts(+ p_prompt_set_id uuid,+ p_organization_id uuid,+ p_max_locations integer,+ p_rows jsonb+)+returns table (idx integer, id uuid)+language plpgsql+volatile+security invoker+set search_path to 'public'+as $$+declare+ v_used bigint;+ v_row jsonb;+ v_regions text[];+ v_cost integer;+ v_id uuid;+begin+ perform pg_advisory_xact_lock(hashtextextended('import_prompts:' || p_organization_id::text, 0));++ select coalesce(sum(u.locations), 0) into v_used+ from public.org_prompt_location_usage(p_organization_id) u;++ for v_row in select value from jsonb_array_elements(p_rows) loop+ v_regions := array(select jsonb_array_elements_text(v_row -> 'regions'));+ -- Same unit as org_prompt_location_usage: one per region, minimum one.+ v_cost := greatest(coalesce(array_length(v_regions, 1), 0), 1);+ exit when p_max_locations <> -1 and v_used + v_cost > p_max_locations;++ insert into public.prompts+ (prompt_set_id, text, category, topic_id, platforms, models, regions, is_active)+ values (+ p_prompt_set_id,+ v_row ->> 'text',+ nullif(v_row ->> 'category', ''),+ nullif(v_row ->> 'topic_id', '')::uuid,+ array(select jsonb_array_elements_text(v_row -> 'platforms')),+ array(select jsonb_array_elements_text(v_row -> 'models')),+ v_regions,+ true+ )+ returning prompts.id into v_id;++ v_used := v_used + v_cost;+ idx := (v_row ->> 'idx')::integer;+ id := v_id;+ return next;+ end loop;+end;+$$;++revoke all on function public.import_prompts(uuid, uuid, integer, jsonb) from public;+grant execute on function public.import_prompts(uuid, uuid, integer, jsonb) to authenticated, service_role;++comment on function public.import_prompts(uuid, uuid, integer, jsonb) is+ 'Bulk-inserts prompts [{idx, text, category, topic_id, platforms, models, regions}] in order under a per-organization advisory lock, stopping before the org would exceed p_max_locations tracked locations (-1 = unlimited). Returns the (idx, id) of each inserted row. PROMPT-005.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 01bf15e8a..145f8d92f 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -14330,6 +14330,87 @@ comment on column public.action_tasks.details isalter table public.prompt_improve_suggestionsadd column if not exists sent_actions jsonb not null default '[]'::jsonb;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00122_import_prompts.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Bulk import of prompts from a spreadsheet (PROMPT-005), capped at the plan+-- limit inside the database.+--+-- The single-prompt path checks the cap in the app tier and then inserts,+-- which leaves a window where two writes can both pass the check (00074).+-- One prompt at a time that window costs at most a location or two; a bulk+-- import can add hundreds, and the task requires that two imports running at+-- once still stop at the limit. So this function takes a per-organization+-- advisory lock, counts the org's tracked locations, and inserts the rows in+-- the order given until the next one would not fit. A second import waits for+-- the first to commit and then counts what it added.+--+-- The rows arrive already validated and resolved (topic ids, plan-filtered+-- platforms) by the server action, which runs the same preview the dialog+-- showed (web/src/lib/prompt-import.ts). This function only stores them and+-- enforces the cap. -1 means unlimited.+--+-- SECURITY INVOKER: `prompts` keeps its admin/manager insert policy through+-- the prompt set's brand, so RLS still decides whether the caller may write.++create or replace function public.import_prompts(+ p_prompt_set_id uuid,+ p_organization_id uuid,+ p_max_locations integer,+ p_rows jsonb+)+returns table (idx integer, id uuid)+language plpgsql+volatile+security invoker+set search_path to 'public'+as $$+declare+ v_used bigint;+ v_row jsonb;+ v_regions text[];+ v_cost integer;+ v_id uuid;+begin+ perform pg_advisory_xact_lock(hashtextextended('import_prompts:' || p_organization_id::text, 0));++ select coalesce(sum(u.locations), 0) into v_used+ from public.org_prompt_location_usage(p_organization_id) u;++ for v_row in select value from jsonb_array_elements(p_rows) loop+ v_regions := array(select jsonb_array_elements_text(v_row -> 'regions'));+ -- Same unit as org_prompt_location_usage: one per region, minimum one.+ v_cost := greatest(coalesce(array_length(v_regions, 1), 0), 1);+ exit when p_max_locations <> -1 and v_used + v_cost > p_max_locations;++ insert into public.prompts+ (prompt_set_id, text, category, topic_id, platforms, models, regions, is_active)+ values (+ p_prompt_set_id,+ v_row ->> 'text',+ nullif(v_row ->> 'category', ''),+ nullif(v_row ->> 'topic_id', '')::uuid,+ array(select jsonb_array_elements_text(v_row -> 'platforms')),+ array(select jsonb_array_elements_text(v_row -> 'models')),+ v_regions,+ true+ )+ returning prompts.id into v_id;++ v_used := v_used + v_cost;+ idx := (v_row ->> 'idx')::integer;+ id := v_id;+ return next;+ end loop;+end;+$$;++revoke all on function public.import_prompts(uuid, uuid, integer, jsonb) from public;+grant execute on function public.import_prompts(uuid, uuid, integer, jsonb) to authenticated, service_role;++comment on function public.import_prompts(uuid, uuid, integer, jsonb) is+ 'Bulk-inserts prompts [{idx, text, category, topic_id, platforms, models, regions}] in order under a per-organization advisory lock, stopping before the org would exceed p_max_locations tracked locations (-1 = unlimited). Returns the (idx, id) of each inserted row. PROMPT-005.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00125_opportunity_usage.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/package.json b/web/package.jsonindex e75a12af4..a238eb8be 100644--- a/web/package.json+++ b/web/package.json@@ -44,6 +44,7 @@"react-dom": "19.2.3","react-is": "^19.2.4","react-markdown": "^10.1.0",+ "read-excel-file": "9.3.12","recharts": "^3.8.0","remark-breaks": "^4.0.0","remark-gfm": "^4.0.1",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex d3e906bba..98b4f555c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -45,6 +45,8 @@ import {} from '@/components/ui/select';import { CompetitionBars } from '@/components/ui/competition-bars';import { WorkStatusBadge } from '@/components/prompts/work-status';+import { BulkImportPrompts } from '@/components/prompts/bulk-import-prompts';+import { promptKey } from '@/lib/prompt-import';import {DropdownMenu,DropdownMenuContent,@@ -89,9 +91,9 @@ import {type VolumeErrorCode,} from '@/lib/actions/volumes';import {- addPromptToBrand,deletePrompt,getPromptsPageData,+ importPrompts,updatePrompt,type LocationQuota,} from '@/lib/actions/prompt';@@ -112,12 +114,12 @@ import {} from '@/config/prompt-options';import { DateRangeFilter } from '@/components/filters/date-range-filter';import { getBrandFilterOptions } from '@/lib/actions/tracking';-import { formatRegionDisplay } from '@/lib/region';+import { formatRegionDisplay, isValidLocation, locationCode } from '@/lib/region';import { SuggestionsTab } from './_suggestions-tab';import { CONTACT_SALES_URL, PLANS } from '@/config/plans';import { getPromptUsage, isPromptLimitReached } from '@/lib/prompt-usage';import { getTopics } from '@/lib/actions/topic';-import { analyzeNewPrompt, type PromptVisibilitySummary } from '@/lib/actions/tracking';+import type { PromptVisibilitySummary } from '@/lib/actions/tracking';import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import type { PromptVolume, Prompt, Topic } from '@/types';import { toast } from 'sonner';@@ -522,6 +524,13 @@ function PromptFormFields({);}+/** The brand's tracking location, as new prompts get it (addPromptToSet). */+function brandLocation(region: string | undefined, state: string | undefined): string {+ const country = region ?? 'US';+ const candidate = locationCode(country, state ?? null);+ return isValidLocation(candidate) ? candidate : country;+}+// ─── Tracked prompt limit (PROMPT-009) ────────────────────────────────────────const PROMPT_USAGE_TOOLTIP =@@ -628,12 +637,18 @@ function AddPromptDialog({brandId,shoppingEnabled,locationQuota,+ existingTexts,+ defaultRegion,open,onClose,onAdded,}: {brandId: string;shoppingEnabled: boolean;+ /** Texts the brand already tracks, for Bulk import's duplicate check. */+ existingTexts: string[];+ /** The brand's location, for Bulk import rows that name none. */+ defaultRegion: string;/** When the plan limit is already reached, the dialog explains it instead of the form. */locationQuota: LocationQuota | null;open: boolean;@@ -653,6 +668,12 @@ function AddPromptDialog({const [topics, setTopics] = useState<Topic[]>([]);const [error, setError] = useState<string | null>(null);const [saving, setSaving] = useState(false);+ const [mode, setMode] = useState<'single' | 'bulk'>('single');+ // Prompts queued with "Add to list", not saved yet: each keeps the topic and+ // engines chosen when it was queued.+ const [staged, setStaged] = useState<+ { key: string; text: string; category: string; platforms: string[]; models: string[] }[]+ >([]);// Reset to a fresh form on every open: all allowed engines pre-selected// (matching the brand page's defaults) and topics fetched lazily — the@@ -661,6 +682,8 @@ function AddPromptDialog({if (!open) return;setText('');setError(null);+ setMode('single');+ setStaged([]);setScrapers(allowedScraperIds);setModels(allowedModelIds);let cancelled = false;@@ -682,35 +705,83 @@ function AddPromptDialog({onClose();};- const handleAdd = async () => {- if (!text.trim() || (scrapers.length === 0 && models.length === 0) || saving) return;+ const enginesChosen = scrapers.length > 0 || models.length > 0;+ const takenKeys = new Set([...existingTexts, ...staged.map((s) => s.text)].map(promptKey));++ /** Queue the typed prompt below the form and clear the field for the next one. */+ const addToList = () => {+ const value = text.trim().replace(/\s+/g, ' ');+ if (!value || !enginesChosen || saving) return;+ if (takenKeys.has(promptKey(value))) {+ setError('This prompt is already tracked or in the list.');+ return;+ }+ setStaged((list) => [+ ...list,+ { key: `${Date.now()}-${list.length}`, text: value, category, platforms: scrapers, models },+ ]);+ setText('');+ setError(null);+ };++ // What a save writes: the list, plus a typed prompt not queued yet.+ const typed = text.trim().replace(/\s+/g, ' ');+ const typedCounts = !!typed && enginesChosen && !takenKeys.has(promptKey(typed));+ const toSave = [+ ...staged,+ ...(typedCounts ? [{ key: 'typed', text: typed, category, platforms: scrapers, models }] : []),+ ];++ /**+ * Save the list in one locked call (the same path as Bulk import, so the+ * plan limit holds the same way), then close or stay open for more.+ */+ const handleSave = async (closeAfter: boolean) => {+ if (toSave.length === 0 || saving) return;+ if (typed && !typedCounts && staged.length === 0) {+ setError('This prompt is already tracked or in the list.');+ return;+ }setSaving(true);setError(null);try {- const result = await addPromptToBrand(brandId, {- text,- category: category || undefined,- platforms: scrapers,- models,- });+ const result = await importPrompts(+ brandId,+ toSave.map((s, idx) => ({+ idx,+ text: s.text,+ topic: s.category || null,+ platforms: s.platforms,+ models: s.models,+ regions: [defaultRegion],+ })),+ );if ('error' in result) {setError(result.error);return;}- // Send the prompt off to be analyzed straight away instead of leaving it- // idle until tomorrow's scheduled run. Only this prompt is submitted, and- // a refusal (daily cap, cooldown, paused brand) is not an error — the- // prompt is saved either way, so the message just says which happened.- const { started } = await analyzeNewPrompt(brandId, result.prompt.id);- onClose();+ const added = result.importedIdx.length;+ const skipped = toSave.length - added;+ if (added === 0) {+ setError(+ 'Nothing was added: your plan limit is reached, or these prompts are already tracked.',+ );+ return;+ }toast.success(- started- ? 'Prompt added — analyzing it now.'- : 'Prompt added — it will be picked up by the next tracking run.',+ `${added} prompt${added === 1 ? '' : 's'} added${skipped ? ` · ${skipped} not added (plan limit or duplicate)` : ''}`,+ {+ description: result.analysisStarted+ ? 'Analyzing them now.'+ : 'They will be picked up by the next tracking run.',+ },);+ setStaged([]);+ setText('');+ if (closeAfter) onClose();onAdded();} catch {- setError('Failed to add prompt. Please try again.');+ setError('Failed to add prompts. Please try again.');} finally {setSaving(false);}@@ -718,7 +789,12 @@ function AddPromptDialog({return (<Dialog open={open} onOpenChange={(v) => !v && handleClose()}>- <DialogContent className="sm:max-w-md max-h-[85vh] overflow-y-auto">+ <DialogContent+ className={cn(+ 'max-h-[85vh] overflow-y-auto',+ mode === 'bulk' && !limitReached ? 'sm:max-w-3xl' : 'sm:max-w-md',+ )}+ ><DialogHeader><DialogTitle className="flex items-center gap-2 text-base"><Plus className="h-4 w-4" />@@ -754,53 +830,126 @@ function AddPromptDialog({</DialogFooter></>) : (- <>- <div className="space-y-3">- <PromptFormFields- autoFocus- text={text}- onTextChange={(value) => {- setText(value);- if (error) setError(null);- }}- onSubmit={handleAdd}- category={category}- onCategoryChange={setCategory}- topics={topics}- scrapers={scrapers}- models={models}- setScrapers={setScrapers}- setModels={setModels}- visibleScrapers={visibleScrapers}- visibleModels={visibleModels}- saving={saving}- />+ <Tabs value={mode} onValueChange={(v) => setMode(v as 'single' | 'bulk')}>+ <TabsList>+ <TabsTrigger value="single">Single</TabsTrigger>+ <TabsTrigger value="bulk">Bulk import</TabsTrigger>+ </TabsList>+ <TabsContent value="single" className="mt-3 space-y-4">+ <div className="space-y-3">+ <PromptFormFields+ autoFocus+ text={text}+ onTextChange={(value) => {+ setText(value);+ if (error) setError(null);+ }}+ onSubmit={addToList}+ category={category}+ onCategoryChange={setCategory}+ topics={topics}+ scrapers={scrapers}+ models={models}+ setScrapers={setScrapers}+ setModels={setModels}+ visibleScrapers={visibleScrapers}+ visibleModels={visibleModels}+ saving={saving}+ />- {error && <p className="text-xs text-red-500">{error}</p>}- </div>- <DialogFooter>- <Button type="button" variant="outline" onClick={handleClose} disabled={saving}>- Cancel- </Button>- <Button- type="button"- onClick={handleAdd}- disabled={saving || !text.trim() || (scrapers.length === 0 && models.length === 0)}- >- {saving ? (- <>- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- Adding…- </>- ) : (- <>- <Plus className="mr-2 h-4 w-4" />- Add Prompt- </>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={addToList}+ disabled={saving || !text.trim() || !enginesChosen}+ >+ <Plus className="mr-1 h-3.5 w-3.5" />+ Add to list+ </Button>++ {error && <p className="text-xs text-red-500">{error}</p>}++ {staged.length > 0 && (+ <div className="space-y-1.5">+ <p className="text-xs font-medium text-muted-foreground">+ Ready to save ({staged.length})+ </p>+ <ul className="max-h-48 divide-y overflow-y-auto rounded-md border">+ {staged.map((s) => (+ <li key={s.key} className="flex items-start gap-2 px-3 py-2 text-sm">+ <div className="min-w-0 flex-1">+ <p className="break-words">{s.text}</p>+ {s.category && (+ <p className="text-xs text-muted-foreground">{s.category}</p>+ )}+ </div>+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label={`Remove "${s.text}" from the list`}+ disabled={saving}+ onClick={() =>+ setStaged((list) => list.filter((item) => item.key !== s.key))+ }+ >+ <X />+ </Button>+ </li>+ ))}+ </ul>+ </div>)}- </Button>- </DialogFooter>- </>+ </div>+ <DialogFooter className="gap-2 sm:gap-2">+ <Button type="button" variant="outline" onClick={handleClose} disabled={saving}>+ Cancel+ </Button>+ <Button+ type="button"+ variant="outline"+ onClick={() => handleSave(false)}+ disabled={saving || toSave.length === 0}+ >+ Save & add more+ </Button>+ <Button+ type="button"+ onClick={() => handleSave(true)}+ disabled={saving || toSave.length === 0}+ >+ {saving ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ Saving…+ </>+ ) : (+ <>+ <Plus className="mr-2 h-4 w-4" />+ {toSave.length > 1 ? `Save ${toSave.length} & close` : 'Save & close'}+ </>+ )}+ </Button>+ </DialogFooter>+ </TabsContent>+ <TabsContent value="bulk" className="mt-3">+ <BulkImportPrompts+ brandId={brandId}+ existingTexts={existingTexts}+ defaults={{ platforms: scrapers, models }}+ defaultRegion={defaultRegion}+ quota={locationQuota}+ limitActions={+ locationQuota ? <PromptLimitActions planId={locationQuota.planId} /> : null+ }+ onImported={() => {+ onClose();+ onAdded();+ }}+ />+ </TabsContent>+ </Tabs>)}</DialogContent></Dialog>@@ -2167,6 +2316,8 @@ export default function PromptsPage() {brandId={activeBrandId}shoppingEnabled={!!activeBrand?.shoppingModeEnabled}locationQuota={locationQuota}+ existingTexts={allPrompts.map((p) => p.text)}+ defaultRegion={brandLocation(activeBrand?.region, activeBrand?.state)}open={addPromptOpen}onClose={() => setAddPromptOpen(false)}onAdded={loadData}diff --git a/web/src/components/prompts/bulk-import-prompts.tsx b/web/src/components/prompts/bulk-import-prompts.tsxnew file mode 100644index 000000000..cfabdb258--- /dev/null+++ b/web/src/components/prompts/bulk-import-prompts.tsx@@ -0,0 +1,355 @@+'use client';++/**+ * Add prompt → Bulk import (PROMPT-005): read a one-column .xlsx or .csv of+ * prompts in the browser, preview every row (valid, duplicate, error, over+ * the plan limit), then import the rows that fit in one locked server call.+ * Topic and location are set afterwards from each prompt's Edit.+ */++import { useCallback, useMemo, useRef, useState } from 'react';+import { AlertCircle, Download, FileSpreadsheet, Info, Loader2, Upload } from 'lucide-react';+import { toast } from 'sonner';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import { toCsv } from '@/lib/csv';+import { importPrompts } from '@/lib/actions/prompt';+import {+ MAX_IMPORT_ROWS,+ TEMPLATE_HEADER,+ TEMPLATE_ROWS,+ buildPreview,+ cellsToText,+ parseCsv,+ rowsForCsv,+ type ImportRow,+} from '@/lib/prompt-import';++interface Props {+ brandId: string;+ /** Prompt texts the brand already tracks, for duplicate detection. */+ existingTexts: string[];+ /** The dialog's platform and model selection, given to every imported prompt. */+ defaults: { platforms: string[]; models: string[] };+ /** The brand's location, given to every imported prompt. */+ defaultRegion: string;+ /** The plan's tracked-location cap and usage; null when unknown. */+ quota: { maxPrompts: number; used: number; planName: string; planId: string } | null;+ /** Upgrade / Contact us, as the Add prompt limit message shows them. */+ limitActions: React.ReactNode;+ onImported: () => void;+}++function downloadCsv(name: string, csv: string) {+ // BOM so Excel opens UTF-8 (Turkish characters) correctly.+ const blob = new Blob([`${csv}`], { type: 'text/csv;charset=utf-8' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = name;+ a.click();+ URL.revokeObjectURL(url);+}++const STATUS_BADGE: Record<ImportRow['status'], { label: string; className: string }> = {+ valid: {+ label: 'Valid',+ className: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',+ },+ duplicate: {+ label: 'Duplicate',+ className: 'border-muted-foreground/30 text-muted-foreground',+ },+ error: {+ label: 'Error',+ className: 'border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-300',+ },+ over_limit: {+ label: 'Over plan limit',+ className: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300',+ },+};++export function BulkImportPrompts({+ brandId,+ existingTexts,+ defaults,+ defaultRegion,+ quota,+ limitActions,+ onImported,+}: Props) {+ const [sheet, setSheet] = useState<string[][] | null>(null);+ const [fileName, setFileName] = useState<string | null>(null);+ const [readError, setReadError] = useState<string | null>(null);+ const [dragging, setDragging] = useState(false);+ const [importing, setImporting] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);++ const freeSlots =+ !quota || quota.maxPrompts === -1 ? -1 : Math.max(0, quota.maxPrompts - quota.used);++ const preview = useMemo(+ () => (sheet ? buildPreview(sheet, { existingTexts, freeSlots }) : null),+ [sheet, existingTexts, freeSlots],+ );++ const readFile = useCallback(async (file: File) => {+ setReadError(null);+ setSheet(null);+ setFileName(file.name);+ const name = file.name.toLowerCase();+ try {+ if (name.endsWith('.csv')) {+ setSheet(parseCsv(await file.text()));+ } else if (name.endsWith('.xlsx')) {+ // Loaded on demand: the reader is only needed when someone imports.+ const { readSheet } = await import('read-excel-file/browser');+ setSheet(cellsToText((await readSheet(file)) as unknown[][]));+ } else {+ setReadError('Choose an .xlsx or .csv file.');+ }+ } catch {+ setReadError('This file could not be read. Check that it is a valid .xlsx or .csv file.');+ }+ }, []);++ const overRows = preview?.rows.filter((r) => r.status === 'over_limit') ?? [];+ const errorRows = preview?.rows.filter((r) => r.status === 'error') ?? [];+ const totalCandidates = (preview?.counts.valid ?? 0) + overRows.length;++ const handleImport = async () => {+ if (!preview || preview.importable.length === 0 || importing) return;+ setImporting(true);+ try {+ const result = await importPrompts(+ brandId,+ preview.importable.map((r, idx) => ({+ idx,+ text: r.text,+ topic: null,+ platforms: defaults.platforms,+ models: defaults.models,+ regions: [defaultRegion],+ })),+ );+ if ('error' in result) {+ toast.error(result.error);+ return;+ }+ const imported = result.importedIdx.length;+ const notImported = totalCandidates - imported;+ toast.success(+ notImported > 0+ ? `${imported} imported · ${notImported} not imported due to plan limit`+ : `${imported} prompt${imported === 1 ? '' : 's'} imported`,+ {+ description: result.analysisStarted+ ? 'Analyzing them now. Set topics and locations with Edit in All Prompts.'+ : 'They will be picked up by the next tracking run.',+ },+ );+ onImported();+ } catch {+ toast.error('Import failed. Please try again.');+ } finally {+ setImporting(false);+ }+ };++ const linkClass =+ 'inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground';++ return (+ <div className="space-y-3">+ <div className="flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <p>+ Put your prompts in <span className="font-medium text-foreground">one column</span>, one+ prompt per row, going down. A first row titled{' '}+ <span className="font-medium text-foreground">Prompt</span> is read as the header+ (optional). Imported prompts use the platforms selected under Single and the brand's+ location; set each one's topic and location afterwards with Edit in All Prompts.+ </p>+ </div>++ <div+ role="button"+ tabIndex={0}+ onClick={() => inputRef.current?.click()}+ onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && inputRef.current?.click()}+ onDragOver={(e) => {+ e.preventDefault();+ setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(e) => {+ e.preventDefault();+ setDragging(false);+ const file = e.dataTransfer.files?.[0];+ if (file) void readFile(file);+ }}+ className={cn(+ 'flex cursor-pointer flex-col items-center gap-2 rounded-lg border border-dashed px-4 py-6 text-center text-sm transition-colors',+ dragging ? 'border-primary bg-primary/5' : 'hover:bg-muted/50',+ )}+ >+ {fileName && !readError ? (+ <FileSpreadsheet className="h-6 w-6 text-muted-foreground" />+ ) : (+ <Upload className="h-6 w-6 text-muted-foreground" />+ )}+ <p className="font-medium">+ {fileName ?? 'Drop an .xlsx or .csv file, or click to browse'}+ </p>+ <p className="text-xs text-muted-foreground">+ One prompt per row · up to {MAX_IMPORT_ROWS.toLocaleString()} rows+ </p>+ <input+ ref={inputRef}+ type="file"+ accept=".xlsx,.csv,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+ className="hidden"+ onChange={(e) => {+ const file = e.target.files?.[0];+ if (file) void readFile(file);+ e.target.value = '';+ }}+ />+ </div>++ <button+ type="button"+ onClick={() => downloadCsv('prompts-template.csv', toCsv(TEMPLATE_ROWS, [TEMPLATE_HEADER]))}+ className={linkClass}+ >+ <Download className="h-3.5 w-3.5" />+ Download template+ </button>++ {readError && <p className="text-xs text-red-600 dark:text-red-400">{readError}</p>}++ {preview && (+ <>+ <p className="text-sm">+ <span className="font-medium">{preview.counts.valid} valid</span> ·{' '}+ {preview.counts.duplicates} duplicate{preview.counts.duplicates === 1 ? '' : 's'} ·{' '}+ {preview.counts.errors} error{preview.counts.errors === 1 ? '' : 's'}+ {quota && quota.maxPrompts !== -1 && (+ <span className="text-muted-foreground">+ {' '}+ · {quota.used} / {quota.maxPrompts} prompt locations in use+ </span>+ )}+ </p>+ {preview.truncated > 0 && (+ <p className="text-xs text-amber-700 dark:text-amber-400">+ Only the first {MAX_IMPORT_ROWS.toLocaleString()} rows were read;{' '}+ {preview.truncated.toLocaleString()} more were left out. Split larger files.+ </p>+ )}+ {preview.extraColumns && (+ <p className="text-xs text-muted-foreground">+ Only the prompt column is read; the file's other columns were ignored.+ </p>+ )}++ {overRows.length > 0 && quota && (+ <div className="flex items-start gap-2.5 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm dark:border-amber-900/50 dark:bg-amber-950/30">+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />+ <div className="space-y-2">+ <p className="text-amber-900 dark:text-amber-200">+ {preview.counts.valid === 0+ ? `No prompts can be imported. Your ${quota.planName} plan tracks up to ${quota.maxPrompts} prompt locations and ${quota.used} are already in use.`+ : `Only ${preview.counts.valid} of ${totalCandidates} prompts will be imported. Your ${quota.planName} plan tracks up to ${quota.maxPrompts} prompt locations and ${quota.used} are already in use. The remaining ${overRows.length} prompt${overRows.length === 1 ? '' : 's'} (from row ${overRows[0].row}) won't be imported.`}{' '}+ To add more prompts,{' '}+ {quota.planId === 'starter' ? 'upgrade your plan' : 'contact us'}.+ </p>+ <div className="flex flex-wrap gap-2">{limitActions}</div>+ </div>+ </div>+ )}++ <div className="max-h-64 overflow-auto rounded-md border">+ <table className="w-full text-xs">+ <thead className="sticky top-0 bg-muted text-left text-muted-foreground">+ <tr>+ <th className="w-12 px-2 py-1.5 font-medium">Row</th>+ <th className="px-2 py-1.5 font-medium">Prompt</th>+ <th className="w-40 px-2 py-1.5 font-medium">Status</th>+ </tr>+ </thead>+ <tbody>+ {preview.rows.map((r) => (+ <tr key={r.row} className="border-t align-top">+ <td className="px-2 py-1.5 tabular-nums text-muted-foreground">{r.row}</td>+ <td className="px-2 py-1.5 break-words">{r.text || '—'}</td>+ <td className="px-2 py-1.5">+ <Badge+ variant="outline"+ className={cn('text-[10px]', STATUS_BADGE[r.status].className)}+ >+ {STATUS_BADGE[r.status].label}+ </Badge>+ {r.reason && r.status !== 'over_limit' && (+ <p className="mt-0.5 text-[11px] text-muted-foreground">{r.reason}</p>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap gap-3">+ {overRows.length > 0 && (+ <button+ type="button"+ onClick={() =>+ downloadCsv(+ 'prompts-not-imported.csv',+ toCsv(rowsForCsv(overRows, false), [TEMPLATE_HEADER]),+ )+ }+ className={linkClass}+ >+ <Download className="h-3.5 w-3.5" />+ Download not-imported prompts (.csv)+ </button>+ )}+ {errorRows.length > 0 && (+ <button+ type="button"+ onClick={() =>+ downloadCsv(+ 'prompts-errors.csv',+ toCsv(rowsForCsv(errorRows, true), [TEMPLATE_HEADER, 'reason']),+ )+ }+ className={linkClass}+ >+ <Download className="h-3.5 w-3.5" />+ Download errors (.csv)+ </button>+ )}+ </div>+ <Button+ type="button"+ onClick={handleImport}+ disabled={importing || preview.counts.valid === 0}+ >+ {importing ? (+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ ) : (+ <Upload className="mr-2 h-4 w-4" />+ )}+ Import {preview.counts.valid} prompt{preview.counts.valid === 1 ? '' : 's'}+ </Button>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 8769b3277..e7220245b 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -14,7 +14,11 @@ import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/primport { isValidLocation, locationCode } from '@/lib/region';import type { Plan, PlanId } from '@/config/plans';import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';-import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';+import {+ analyzeNewPrompts,+ getPromptVisibilitySummaries,+ type PromptVisibilitySummary,+} from '@/lib/actions/tracking';function filterByPlan(plan: Plan, platforms: string[], models: string[]) {const allowedScrapers = plan.limits.allowedScrapers@@ -715,6 +719,131 @@ export async function addPromptToBrand(return { prompt: result.prompt };}+export interface ImportPromptRow {+ /** Index in the preview's importable list, echoed back for the imported ones. */+ idx: number;+ text: string;+ topic: string | null;+ platforms: string[];+ models: string[];+ regions: string[];+}++export type ImportPromptsResult =+ | { importedIdx: number[]; promptIds: string[]; analysisStarted: boolean }+ | { error: string };++/**+ * Bulk import (PROMPT-005). The rows are the preview's importable ones, in+ * file order; they are checked again here (text, locations, duplicates, plan+ * engines) because the client is not trusted, then written by one locked+ * database call that stops at the plan's tracked-location cap+ * (import_prompts, 00122). New topics are created first, without touching the+ * brand's existing ones. The imported prompts are submitted for their first+ * run in one request.+ */+export async function importPrompts(+ brandId: string,+ rows: ImportPromptRow[],+): Promise<ImportPromptsResult> {+ if (rows.length === 0) return { importedIdx: [], promptIds: [], analysisStarted: false };+ if (rows.length > 1000) return { error: 'Import at most 1,000 prompts at a time.' };+ const supabase = await createClient();++ let promptSetId: string;+ {+ const { data: ps, error } = await supabase+ .from('prompt_sets')+ .select('id')+ .eq('brand_id', brandId)+ .order('created_at', { ascending: true })+ .limit(1)+ .maybeSingle();+ if (error) return { error: error.message };+ if (ps?.id) promptSetId = ps.id as string;+ else {+ const { data: created, error: setErr } = await supabase+ .from('prompt_sets')+ .insert({ brand_id: brandId, name: 'Prompts' })+ .select('id')+ .single();+ if (setErr || !created) return { error: setErr?.message ?? 'Failed to create a prompt set.' };+ promptSetId = created.id as string;+ }+ }++ const { organizationId: orgId } = await getBrandContext(supabase, brandId);+ const [plan, { data: brandRow }, { data: existing }, { data: topicRows }] = await Promise.all([+ getOrgPlan(orgId),+ supabase.from('brands').select('shopping_mode_enabled').eq('id', brandId).single(),+ supabase+ .from('prompts')+ .select('text, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId),+ supabase.from('topics').select('id, name').eq('brand_id', brandId),+ ]);+ const shopping = !!brandRow?.shopping_mode_enabled;+ const keyOf = (t: string) => t.trim().toLowerCase().replace(/\s+/g, ' ');+ const seen = new Set((existing ?? []).map((p) => keyOf(p.text as string)));+ const topicIds = new Map((topicRows ?? []).map((t) => [keyOf(t.name as string), t.id as string]));++ const clean = rows.flatMap((r) => {+ const text = r.text.trim().replace(/\s+/g, ' ');+ if (!text || text.length > 500) return [];+ if (seen.has(keyOf(text))) return [];+ seen.add(keyOf(text));+ const regions = [...new Set(r.regions.map((c) => c.trim().toUpperCase()))].filter(+ isValidLocation,+ );+ if (regions.length === 0) return [];+ const filtered = filterByPlan(plan, r.platforms, r.models);+ const platforms = shopping+ ? Array.from(new Set([...filtered.platforms, 'chatgpt-shopping']))+ : stripShoppingWhenDisabled(filtered.platforms, false);+ if (platforms.length === 0 && filtered.models.length === 0) return [];+ return [{ ...r, text, regions, platforms, models: filtered.models }];+ });++ // New topics, once each, alongside the brand's existing ones.+ const newTopics = [+ ...new Map(+ clean+ .filter((r) => r.topic && !topicIds.has(keyOf(r.topic)))+ .map((r) => [keyOf(r.topic!), r.topic!.trim().slice(0, 60)]),+ ).values(),+ ];+ if (newTopics.length) {+ const { data: created, error } = await supabase+ .from('topics')+ .insert(newTopics.map((name) => ({ brand_id: brandId, name, is_active: true })))+ .select('id, name');+ if (error) return { error: error.message };+ for (const t of created ?? []) topicIds.set(keyOf(t.name as string), t.id as string);+ }++ const { data: inserted, error } = await supabase.rpc('import_prompts', {+ p_prompt_set_id: promptSetId,+ p_organization_id: orgId,+ p_max_locations: plan.limits.maxPrompts,+ p_rows: clean.map((r) => ({+ idx: r.idx,+ text: r.text,+ category: r.topic?.trim() ?? '',+ topic_id: r.topic ? (topicIds.get(keyOf(r.topic)) ?? '') : '',+ platforms: r.platforms,+ models: r.models,+ regions: r.regions,+ })),+ });+ if (error) return { error: error.message };++ const imported = (inserted ?? []) as { idx: number; id: string }[];+ const promptIds = imported.map((r) => r.id);+ const { started } = await analyzeNewPrompts(brandId, promptIds);+ revalidatePath('/dashboard/prompts');+ return { importedIdx: imported.map((r) => r.idx), promptIds, analysisStarted: started };+}+export async function deletePrompt(id: string): Promise<void> {const supabase = await createClient();diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex bad4f32fa..9de228d96 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -1608,6 +1608,20 @@ export async function analyzeNewPrompt(brandId: string,promptId: string,): Promise<{ started: boolean }> {+ return analyzeNewPrompts(brandId, [promptId]);+}++/**+ * Submit several just-added prompts for their first run in one request — a+ * bulk import (PROMPT-005) spends one on-demand run, not one per row. A+ * refusal (daily cap, cooldown, paused brand) is not an error: the prompts are+ * saved and the next scheduled run picks them up.+ */+export async function analyzeNewPrompts(+ brandId: string,+ promptIds: string[],+): Promise<{ started: boolean }> {+ if (promptIds.length === 0) return { started: false };const supabase = await dbClient();const {@@ -1622,7 +1636,7 @@ export async function analyzeNewPrompt('Content-Type': 'application/json',Authorization: `Bearer ${session.access_token}`,},- body: JSON.stringify({ brandId, promptIds: [promptId] }),+ body: JSON.stringify({ brandId, promptIds }),});if (!res.ok) {diff --git a/web/src/lib/prompt-import.test.ts b/web/src/lib/prompt-import.test.tsnew file mode 100644index 000000000..fb4bf4b9c--- /dev/null+++ b/web/src/lib/prompt-import.test.ts@@ -0,0 +1,144 @@+/**+ * prompt-import.test.ts (PROMPT-005)+ *+ * Tests reading a one-column prompt file and the bulk-import preview:+ * duplicates, errors and the plan limit taken in file order.+ */++import { describe, expect, test } from 'vitest';+import {+ MAX_IMPORT_ROWS,+ buildPreview,+ cellsToText,+ parseCsv,+ promptColumn,+ promptKey,+ type PreviewContext,+} from './prompt-import';++const ctx = (over: Partial<PreviewContext> = {}): PreviewContext => ({+ existingTexts: [],+ freeSlots: -1,+ ...over,+});++describe('parseCsv', () => {+ test('reads quotes, doubled quotes, CRLF and a BOM', () => {+ expect(parseCsv('Prompt\r\n"Best, cheapest coffee"\r\n"Say ""hi"""\r\n')).toEqual([+ ['Prompt'],+ ['Best, cheapest coffee'],+ ['Say "hi"'],+ ]);+ });++ test('keeps Turkish characters and drops blank lines', () => {+ expect(parseCsv('Prompt\n\nEn iyi kahve aboneliği hangisi?\n\n')).toEqual([+ ['Prompt'],+ ['En iyi kahve aboneliği hangisi?'],+ ]);+ });+});++describe('cellsToText', () => {+ test('stringifies spreadsheet cells and drops empty rows', () => {+ expect(+ cellsToText([+ ['A', 3],+ [null, undefined],+ [' B ', true],+ ]),+ ).toEqual([+ ['A', '3'],+ ['B', 'true'],+ ]);+ });+});++describe('promptColumn', () => {+ test('a "Prompt" header, in any column and case, picks that column', () => {+ expect(+ promptColumn([+ ['id', 'PROMPT'],+ ['1', 'x'],+ ]),+ ).toEqual({ column: 1, hasHeader: true });+ });++ test('without a header the first column is prompts from the first row on', () => {+ expect(promptColumn([['Best coffee'], ['Best tea']])).toEqual({ column: 0, hasHeader: false });+ });+});++describe('buildPreview', () => {+ test('a file without a header imports every row', () => {+ const p = buildPreview([['Best coffee'], ['Best tea']], ctx());+ expect(p.importable.map((r) => r.text)).toEqual(['Best coffee', 'Best tea']);+ });++ test('marks duplicates (case and whitespace insensitive) and errors', () => {+ const p = buildPreview(+ [+ ['Prompt'],+ ['Best Coffee'],+ ['best coffee'],+ ['Already here'],+ [''],+ ['x'.repeat(501)],+ ['Tea'],+ ],+ ctx({ existingTexts: ['already HERE'] }),+ );+ expect(p.rows.map((r) => r.status)).toEqual([+ 'valid',+ 'duplicate',+ 'duplicate',+ 'error',+ 'error',+ 'valid',+ ]);+ expect(p.rows[0].text).toBe('Best Coffee');+ expect(p.counts).toEqual({ valid: 2, duplicates: 2, errors: 2, overLimit: 0 });+ });++ test('Growth 200 with 50 used and a 250-row file: rows 1–150 in, 151–250 out', () => {+ const sheet = [['Prompt'], ...Array.from({ length: 250 }, (_, i) => [`Prompt ${i + 1}`])];+ const p = buildPreview(sheet, ctx({ freeSlots: 200 - 50 }));+ expect(p.counts).toEqual({ valid: 150, duplicates: 0, errors: 0, overLimit: 100 });+ expect(p.importable[149].row).toBe(150);+ expect(p.rows[150]).toMatchObject({ row: 151, status: 'over_limit' });+ });++ test('duplicates and errors after the limit still read as what they are', () => {+ const p = buildPreview([['Prompt'], ['A'], ['B'], ['a'], ['']], ctx({ freeSlots: 1 }));+ expect(p.rows.map((r) => r.status)).toEqual(['valid', 'over_limit', 'duplicate', 'error']);+ });++ test('zero free slots imports nothing', () => {+ const p = buildPreview([['Prompt'], ['A']], ctx({ freeSlots: 0 }));+ expect(p.counts).toMatchObject({ valid: 0, overLimit: 1 });+ });++ test('notes other columns, which are not read', () => {+ expect(+ buildPreview(+ [+ ['Prompt', 'Topic'],+ ['A', 'x'],+ ],+ ctx(),+ ).extraColumns,+ ).toBe(true);+ expect(buildPreview([['Prompt'], ['A']], ctx()).extraColumns).toBe(false);+ });++ test('reads at most MAX_IMPORT_ROWS rows and reports the rest', () => {+ const sheet = [['Prompt'], ...Array.from({ length: MAX_IMPORT_ROWS + 5 }, (_, i) => [`P${i}`])];+ const p = buildPreview(sheet, ctx());+ expect(p.rows).toHaveLength(MAX_IMPORT_ROWS);+ expect(p.truncated).toBe(5);+ });++ test('promptKey ignores case and inner whitespace', () => {+ expect(promptKey(' Best COFFEE ')).toBe(promptKey('best coffee'));+ });+});diff --git a/web/src/lib/prompt-import.ts b/web/src/lib/prompt-import.tsnew file mode 100644index 000000000..f47ab4378--- /dev/null+++ b/web/src/lib/prompt-import.ts@@ -0,0 +1,188 @@+/**+ * Bulk import of prompts from a spreadsheet (PROMPT-005): reading the rows,+ * and the preview that decides, before anything is written, which rows are+ * imported, skipped or left out by the plan limit.+ *+ * The file is one column of prompts, one per row, with an optional "Prompt"+ * header — the shape a list exported from another tool already has. Topic and+ * location are set afterwards from each prompt's Edit; imported prompts get+ * the dialog's platforms and the brand's location, like a single add.+ *+ * Pure on purpose. The dialog runs it to show the preview; the server action+ * re-runs the limit inside one locked database call, so the preview is a+ * promise the write keeps rather than a second definition that can drift.+ *+ * The limit is counted in tracked prompt locations, the unit the plan cap is+ * enforced in (prompt-locations.ts). Every imported row tracks one location.+ */++/** Rows a single file may carry; larger files are split by the user. */+export const MAX_IMPORT_ROWS = 1000;+/** Longest prompt text accepted. */+export const MAX_PROMPT_LENGTH = 500;++export const TEMPLATE_HEADER = 'Prompt';++export type ImportRowStatus = 'valid' | 'duplicate' | 'error' | 'over_limit';++export interface ImportRow {+ /** 1-based row number in the file, header excluded. */+ row: number;+ text: string;+ status: ImportRowStatus;+ /** Why a row is skipped; null for valid rows. */+ reason: string | null;+}++export interface ImportPreview {+ rows: ImportRow[];+ /** Rows that will be imported, in file order. */+ importable: ImportRow[];+ counts: { valid: number; duplicates: number; errors: number; overLimit: number };+ /** Rows beyond MAX_IMPORT_ROWS, not read at all. */+ truncated: number;+ /** The file had more columns than the prompt one; they were not read. */+ extraColumns: boolean;+}++// ─── Reading ──────────────────────────────────────────────────────────────────++/**+ * CSV with the delimiter detected from the first line (comma or semicolon —+ * Excel in many European locales saves with semicolons), quoted fields with+ * doubled quotes, CRLF, and a UTF-8 BOM.+ */+export function parseCsv(input: string): string[][] {+ const text = input.replace(/^/, '');+ const firstLine = text.split(/\r?\n/, 1)[0] ?? '';+ const count = (ch: string) => firstLine.split(ch).length - 1;+ const delimiter = count(';') > count(',') ? ';' : ',';++ const rows: string[][] = [];+ let row: string[] = [];+ let field = '';+ let quoted = false;+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (quoted) {+ if (ch === '"') {+ if (text[i + 1] === '"') {+ field += '"';+ i++;+ } else quoted = false;+ } else field += ch;+ } else if (ch === '"' && field === '') quoted = true;+ else if (ch === delimiter) {+ row.push(field);+ field = '';+ } else if (ch === '\n' || ch === '\r') {+ if (ch === '\r' && text[i + 1] === '\n') i++;+ row.push(field);+ rows.push(row);+ row = [];+ field = '';+ } else field += ch;+ }+ if (field !== '' || row.length) {+ row.push(field);+ rows.push(row);+ }+ return rows.filter((r) => r.some((c) => c.trim() !== ''));+}++/** Spreadsheet cells (numbers, dates, booleans, nulls) as trimmed text. */+export function cellsToText(rows: unknown[][]): string[][] {+ return rows+ .map((r) => r.map((c) => (c === null || c === undefined ? '' : String(c).trim())))+ .filter((r) => r.some((c) => c !== ''));+}++const PROMPT_HEADERS = new Set(['prompt', 'prompts']);++/**+ * Where the prompts are. A first row naming a "Prompt" column is a header and+ * picks that column; without one, the first column holds the prompts from the+ * first row on.+ */+export function promptColumn(sheet: string[][]): { column: number; hasHeader: boolean } {+ const first = sheet[0] ?? [];+ const i = first.findIndex((c) => PROMPT_HEADERS.has(c.trim().toLowerCase()));+ return i >= 0 ? { column: i, hasHeader: true } : { column: 0, hasHeader: false };+}++// ─── Preview ──────────────────────────────────────────────────────────────────++/** Duplicates ignore case and whitespace. */+export function promptKey(text: string): string {+ return text.trim().toLowerCase().replace(/\s+/g, ' ');+}++export interface PreviewContext {+ /** Prompt texts the brand already tracks. */+ existingTexts: string[];+ /** Free tracked-location slots under the plan; -1 = unlimited. */+ freeSlots: number;+}++/**+ * Every row's fate. Duplicates and errors are skipped and use no slot. Valid+ * rows are taken in file order until the limit is reached; from there on+ * every valid row is "over limit".+ */+export function buildPreview(sheet: string[][], ctx: PreviewContext): ImportPreview {+ const { column, hasHeader } = promptColumn(sheet);+ const body = hasHeader ? sheet.slice(1) : sheet;+ const truncated = Math.max(0, body.length - MAX_IMPORT_ROWS);+ const data = body.slice(0, MAX_IMPORT_ROWS);+ const extraColumns = sheet.some((r) => r.some((c, i) => i !== column && c.trim() !== ''));++ const seen = new Set(ctx.existingTexts.map(promptKey));+ let used = 0;+ const rows: ImportRow[] = data.map((r, i) => {+ const text = (r[column] ?? '').trim().replace(/\s+/g, ' ');+ const row = i + 1;+ if (!text) return { row, text, status: 'error', reason: 'Empty prompt' };+ if (text.length > MAX_PROMPT_LENGTH) {+ return { row, text, status: 'error', reason: `Longer than ${MAX_PROMPT_LENGTH} characters` };+ }+ const key = promptKey(text);+ if (seen.has(key)) {+ return { row, text, status: 'duplicate', reason: 'Already tracked or repeated in the file' };+ }+ seen.add(key);+ if (ctx.freeSlots === -1 || used < ctx.freeSlots) {+ used += 1;+ return { row, text, status: 'valid', reason: null };+ }+ return { row, text, status: 'over_limit', reason: 'Over plan limit' };+ });++ const importable = rows.filter((r) => r.status === 'valid');+ return {+ rows,+ importable,+ counts: {+ valid: importable.length,+ duplicates: rows.filter((r) => r.status === 'duplicate').length,+ errors: rows.filter((r) => r.status === 'error').length,+ overLimit: rows.filter((r) => r.status === 'over_limit').length,+ },+ truncated,+ extraColumns,+ };+}++/** Rows as a one-column file, for the "not imported" and error downloads. */+export function rowsForCsv(rows: ImportRow[], withReason: boolean): Record<string, string>[] {+ return rows.map((r) => ({+ [TEMPLATE_HEADER]: r.text,+ ...(withReason ? { reason: r.reason ?? '' } : {}),+ }));+}++/** The downloadable template: the header and a few example prompts. */+export const TEMPLATE_ROWS: Record<string, string>[] = [+ { [TEMPLATE_HEADER]: 'Best project management tools for startups' },+ { [TEMPLATE_HEADER]: 'En iyi proje yönetim araçları hangileri?' },+ { [TEMPLATE_HEADER]: 'Which CRM is best for small businesses?' },+];diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 8e4f1346c..c1cc91fff 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3082,6 +3082,18 @@ export type Database = {}[]}normalize_page_path: { Args: { p_url: string }; Returns: string }+ import_prompts: {+ Args: {+ p_max_locations: number+ p_organization_id: string+ p_prompt_set_id: string+ p_rows: Json+ }+ Returns: {+ id: string+ idx: number+ }[]+ }org_prompt_location_usage: {Args: { p_organization_id: string }Returns: {diff --git a/web/yarn.lock b/web/yarn.lockindex 905e162fb..467e775f6 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -4133,7 +4133,7 @@ fflate@^0.4.8:resolved "https://registry.yarnpkg.com/fflate/-/fflate-0.4.8.tgz#f90b82aefbd8ac174213abb338bd7ef848f0f5ae"integrity sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==-fflate@^0.8.2:+fflate@^0.8.2, fflate@^0.8.3:version "0.8.3"resolved "https://registry.yarnpkg.com/fflate/-/fflate-0.8.3.tgz#bc27d8eb30343d4d512abb03480202ce65d825fc"integrity sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==@@ -4392,7 +4392,7 @@ gopd@^1.0.1, gopd@^1.2.0:resolved "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz"integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==-graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.4:+graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.2, graceful-fs@^4.2.4:version "4.2.11"resolved "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz"integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==@@ -6025,6 +6025,11 @@ node-fetch@^3.3.2:fetch-blob "^3.1.4"formdata-polyfill "^4.0.10"+node-int64@^0.4.0:+ version "0.4.0"+ resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"+ integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==+node-releases@^2.0.27:version "2.0.36"resolved "https://registry.npmjs.org/node-releases/-/node-releases-2.0.36.tgz"@@ -6615,6 +6620,16 @@ [email protected]:resolved "https://registry.npmjs.org/react/-/react-19.2.3.tgz"integrity sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==+ version "9.3.12"+ resolved "https://registry.yarnpkg.com/read-excel-file/-/read-excel-file-9.3.12.tgz#aacedbef34d555b8fb0f9bfe4e93652b56ace203"+ integrity sha512-benNAoQbe5HqoTi3qrQkR8wMeHq0gVWLt2Br73hVvmBPGdzMf9OLGsps/812AfZ+bvzVYsUyhF77Y3o4B51yCA==+ dependencies:+ fflate "^0.8.3"+ saxen "^11.1.0"+ unzipper-esm "^0.13.3"+ worker-f "^0.1.12"+recast@^0.23.11:version "0.23.11"resolved "https://registry.npmjs.org/recast/-/recast-0.23.11.tgz"@@ -6918,6 +6933,11 @@ safe-regex-test@^1.0.3, safe-regex-test@^1.1.0:resolved "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz"integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==+saxen@^11.1.0:+ version "11.2.0"+ resolved "https://registry.yarnpkg.com/saxen/-/saxen-11.2.0.tgz#fec7492a2606c01dda58b3426be696de36a4952c"+ integrity sha512-2bG564AAJcm/3vyZC0Uhs/mACrH+4AHMaKHKAB2M5xMqomUZa27FQ7MYaQGFKVcJk/MVzSEQ34A8QZWW+eiWEw==+saxes@^6.0.0:version "6.0.0"resolved "https://registry.yarnpkg.com/saxes/-/saxes-6.0.0.tgz#fe5b4a4768df4f14a201b1ba6a65c1f3d9988cc5"@@ -7851,6 +7871,14 @@ until-async@^3.0.2:resolved "https://registry.npmjs.org/until-async/-/until-async-3.0.2.tgz"integrity sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw==+unzipper-esm@^0.13.3:+ version "0.13.3"+ resolved "https://registry.yarnpkg.com/unzipper-esm/-/unzipper-esm-0.13.3.tgz#731e1b28f895f174a5351cf84ea24e8adb4f155c"+ integrity sha512-LUO6VZ6fCzkDbdMev0/fOhoIeVGKaOkTIOoYxVLE0SQjfvmAHK+oywl7lfhloSZIsdGJ25mJ18Mtd9CyTASjrA==+ dependencies:+ graceful-fs "^4.2.2"+ node-int64 "^0.4.0"+update-browserslist-db@^1.2.0:version "1.2.3"resolved "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz"@@ -8117,6 +8145,11 @@ word-wrap@^1.2.5:resolved "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz"integrity sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==+worker-f@^0.1.12:+ version "0.1.20"+ resolved "https://registry.yarnpkg.com/worker-f/-/worker-f-0.1.20.tgz#8425fe1c89ad54d2e6732cf03943ffc05b42cc02"+ integrity sha512-7z5K5z4x++FykhpDTfriT/dOu7CmSap9BBv38DVFU3CD38obopq+DoFH75yBV3butpGm+OeqR9BKdSvYJSnUfQ==+wrap-ansi@^6.2.0:version "6.2.0"resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz"