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(content): start from the prompts AI doesn't name or cite the brand for yet (#1323)

Cihan3a4fcde58def
diff --git a/supabase/migrations/00230_content_start_prompts.sql b/supabase/migrations/00230_content_start_prompts.sql
new file mode 100644
index 000000000..b551a78ba
--- /dev/null
+++ b/supabase/migrations/00230_content_start_prompts.sql
@@ -0,0 +1,82 @@
+-- ============================================================================
+-- 00230: New content's prompts, marked where the brand already shows (CE-003)
+-- ============================================================================
+-- New content › Create from scratch › Prompt starts a page for a tracked
+-- prompt. A prompt the brand is already named in or cited for needs no new
+-- page, so Start lists the others; the editor's "Add source" still offers
+-- every prompt.
+--
+-- * content_start_prompts(brand, days): the brand's active prompts, each
+-- marked seen when an answer in the last p_days UTC days (today included)
+-- named the brand or cited one of its pages, from the prompt-grain
+-- Insights rollup (insights_prompt_daily, its (brand_id, day) index).
+-- Those not seen come first, each group by text, up to p_limit; seen
+-- counts every seen prompt, past the limit too, for Start's note.
+-- * As the content reads (00226) are: plpgsql planned for its own values
+-- (plan_cache_mode), security definer with the organization check made
+-- explicit, null to a caller outside the brand's organization.
+
+create or replace function public.content_start_prompts(
+ p_brand_id uuid,
+ p_days integer default 30,
+ p_limit integer default 500
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_days integer := least(greatest(coalesce(p_days, 30), 1), 365);
+ v_limit integer := least(greatest(coalesce(p_limit, 500), 1), 2000);
+ v_result jsonb;
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) then
+ return null;
+ end if;
+
+ with seen as (
+ select distinct d.prompt_id
+ from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and d.day > current_date - v_days
+ and (d.has_mention or d.has_citation)
+ ),
+ active as (
+ select p.id, p.text, (s.prompt_id is not null) as seen
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ left join seen s on s.prompt_id = p.id
+ where ps.brand_id = p_brand_id
+ and p.is_active
+ ),
+ listed as (
+ select a.id, a.text, a.seen
+ from active a
+ order by a.seen, a.text
+ limit v_limit
+ )
+ select jsonb_build_object(
+ 'prompts', coalesce(
+ (select jsonb_agg(jsonb_build_object('id', l.id, 'text', l.text, 'seen', l.seen)
+ order by l.seen, l.text)
+ from listed l),
+ '[]'::jsonb),
+ 'seen', (select count(*) from active a where a.seen))
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke execute on function public.content_start_prompts(uuid, integer, integer) from public, anon;
+grant execute on function public.content_start_prompts(uuid, integer, integer) to authenticated, service_role;
+
+comment on function public.content_start_prompts(uuid, integer, integer) is
+ 'Content Editor New content (CE-003): the brand''s active prompts, each marked seen when an answer in the last p_days UTC days named the brand or cited its pages (insights_prompt_daily); not seen first, by text, up to p_limit, with the count of seen ones. Security definer, planned with its arguments; null when the caller is not a member of the brand''s organization.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index f46a48f91..cc09bd2ec 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -33541,6 +33541,92 @@ create trigger profiles_guard_server_columns
before update on public.profiles
for each row execute function public.guard_profile_server_columns();
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00230_content_start_prompts.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00230: New content's prompts, marked where the brand already shows (CE-003)
+-- ============================================================================
+-- New content › Create from scratch › Prompt starts a page for a tracked
+-- prompt. A prompt the brand is already named in or cited for needs no new
+-- page, so Start lists the others; the editor's "Add source" still offers
+-- every prompt.
+--
+-- * content_start_prompts(brand, days): the brand's active prompts, each
+-- marked seen when an answer in the last p_days UTC days (today included)
+-- named the brand or cited one of its pages, from the prompt-grain
+-- Insights rollup (insights_prompt_daily, its (brand_id, day) index).
+-- Those not seen come first, each group by text, up to p_limit; seen
+-- counts every seen prompt, past the limit too, for Start's note.
+-- * As the content reads (00226) are: plpgsql planned for its own values
+-- (plan_cache_mode), security definer with the organization check made
+-- explicit, null to a caller outside the brand's organization.
+
+create or replace function public.content_start_prompts(
+ p_brand_id uuid,
+ p_days integer default 30,
+ p_limit integer default 500
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_days integer := least(greatest(coalesce(p_days, 30), 1), 365);
+ v_limit integer := least(greatest(coalesce(p_limit, 500), 1), 2000);
+ v_result jsonb;
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) then
+ return null;
+ end if;
+
+ with seen as (
+ select distinct d.prompt_id
+ from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and d.day > current_date - v_days
+ and (d.has_mention or d.has_citation)
+ ),
+ active as (
+ select p.id, p.text, (s.prompt_id is not null) as seen
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ left join seen s on s.prompt_id = p.id
+ where ps.brand_id = p_brand_id
+ and p.is_active
+ ),
+ listed as (
+ select a.id, a.text, a.seen
+ from active a
+ order by a.seen, a.text
+ limit v_limit
+ )
+ select jsonb_build_object(
+ 'prompts', coalesce(
+ (select jsonb_agg(jsonb_build_object('id', l.id, 'text', l.text, 'seen', l.seen)
+ order by l.seen, l.text)
+ from listed l),
+ '[]'::jsonb),
+ 'seen', (select count(*) from active a where a.seen))
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke execute on function public.content_start_prompts(uuid, integer, integer) from public, anon;
+grant execute on function public.content_start_prompts(uuid, integer, integer) to authenticated, service_role;
+
+comment on function public.content_start_prompts(uuid, integer, integer) is
+ 'Content Editor New content (CE-003): the brand''s active prompts, each marked seen when an answer in the last p_days UTC days named the brand or cited its pages (insights_prompt_daily); not seen first, by text, up to p_limit, with the count of seen ones. Security definer, planned with its arguments; null when the caller is not a member of the brand''s organization.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00232_prompt_results_metrics_cover.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index be0ea0e1b..ed24ac17f 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3233,7 +3233,9 @@
"tab": "Prompt",
"placeholder": "Pick a tracked prompt",
"search": "Search prompts",
- "empty": "No tracked prompts."
+ "empty": "No tracked prompts.",
+ "seen": "{count, plural, one {# prompt} other {# prompts}} where AI already names or cites you in the last 30 days {count, plural, one {isn't} other {aren't}} listed: {count, plural, one {it needs} other {they need}} no new page.",
+ "allSeen": "AI already names or cites you for every tracked prompt in the last 30 days."
},
"topic": {
"tab": "Topic",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx
index 01bb88892..3a156c4ee 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx
@@ -78,7 +78,14 @@ export function AddSourceDialog({
let cancelled = false;
getContentStartOptions(brandId)
.then((options) => {
- if (!cancelled) setPrompts(options.prompts.map((p) => ({ value: p.id, label: p.text })));
+ // Every prompt, seen or not (New content lists the unseen first), by text.
+ if (!cancelled) {
+ setPrompts(
+ [...options.prompts]
+ .sort((a, b) => a.text.localeCompare(b.text))
+ .map((p) => ({ value: p.id, label: p.text })),
+ );
+ }
})
.catch((err) => {
console.error('Failed to read the prompts:', err);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
index a1e4fe4e4..ebb212271 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
@@ -111,7 +111,7 @@ beforeEach(() => {
addDraftSource.mockReset().mockResolvedValue(undefined);
getContentStartOptions
.mockReset()
- .mockResolvedValue({ opportunities: [], prompts: [], topics: [] });
+ .mockResolvedValue({ opportunities: [], prompts: [], promptsSeen: 0, topics: [] });
onRebuild.mockReset();
toast.mockReset();
toast.success.mockReset();
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
index 8cdeba2df..9d561f3d3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
@@ -86,6 +86,7 @@ beforeEach(() => {
getContentStartOptions.mockReset().mockResolvedValue({
opportunities: [],
prompts: [],
+ promptsSeen: 0,
topics: [],
});
push.mockReset();
diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsx
index c3aba6224..b43944e55 100644
--- a/web/src/components/content/new-content-dialog.test.tsx
+++ b/web/src/components/content/new-content-dialog.test.tsx
@@ -64,7 +64,8 @@ const OPTIONS = {
pageTitle: 'CRM for real estate teams',
},
],
- prompts: [{ id: 'p1', text: 'best crm for realtors' }],
+ prompts: [{ id: 'p1', text: 'best crm for realtors', seen: false }],
+ promptsSeen: 0,
topics: [{ id: 't1', name: 'Real estate', promptCount: 3 }],
};
@@ -186,6 +187,67 @@ describe('New content', () => {
expect(value?.closest('[data-slot="combobox-trigger"]')).not.toBeNull();
});
+ it('lists the prompts AI doesn’t name or cite the brand for yet, and says how many are left out', async () => {
+ getContentStartOptions.mockResolvedValue({
+ ...OPTIONS,
+ prompts: [
+ { id: 'p1', text: 'best crm for realtors', seen: false },
+ { id: 'p2', text: 'crm pricing', seen: true },
+ { id: 'p3', text: 'crm for teams', seen: true },
+ ],
+ promptsSeen: 2,
+ });
+ await render();
+ await click(tab('Prompt'));
+ expect(document.body.textContent).toContain(
+ "2 prompts where AI already names or cites you in the last 30 days aren't listed: they need no new page.",
+ );
+ await click(button('Pick a tracked prompt'));
+ expect([...document.querySelectorAll('[role="option"]')].map((o) => o.textContent)).toEqual([
+ 'best crm for realtors',
+ ]);
+ });
+
+ it('says so when AI already names or cites the brand for every prompt', async () => {
+ getContentStartOptions.mockResolvedValue({
+ ...OPTIONS,
+ prompts: [{ id: 'p2', text: 'crm pricing', seen: true }],
+ promptsSeen: 1,
+ });
+ await render();
+ await click(tab('Prompt'));
+ await click(button('Pick a tracked prompt'));
+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(0);
+ expect(document.body.textContent).toContain(
+ 'AI already names or cites you for every tracked prompt in the last 30 days.',
+ );
+ });
+
+ it('says no prompt matches on a search miss, not that every prompt is seen', async () => {
+ getContentStartOptions.mockResolvedValue({
+ ...OPTIONS,
+ prompts: [
+ { id: 'p1', text: 'best crm for realtors', seen: false },
+ { id: 'p2', text: 'crm pricing', seen: true },
+ ],
+ promptsSeen: 1,
+ });
+ await render();
+ await click(tab('Prompt'));
+ await click(button('Pick a tracked prompt'));
+ const search = document.querySelector<HTMLInputElement>('input[placeholder="Search prompts"]')!;
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setValue.call(search, 'zzz no such prompt');
+ search.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(0);
+ expect(document.body.textContent).toContain('No tracked prompts.');
+ expect(document.body.textContent).not.toContain(
+ 'AI already names or cites you for every tracked prompt',
+ );
+ });
+
it('names the page by the opportunity’s brief title when it has one', async () => {
await render();
await click(button('Pick a content opportunity'));
diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsx
index 58dbb1eee..b6db9fb2d 100644
--- a/web/src/components/content/new-content-dialog.tsx
+++ b/web/src/components/content/new-content-dialog.tsx
@@ -301,7 +301,8 @@ export function NewContentDialog({
pageTitle: o.pageTitle ?? undefined,
}))
: kind === 'prompt'
- ? options.prompts.map((p) => ({ value: p.id, label: p.text }))
+ ? // A prompt the brand is already named in or cited for needs no new page.
+ options.prompts.filter((p) => !p.seen).map((p) => ({ value: p.id, label: p.text }))
: options.topics.map((topic) => ({
value: topic.id,
label: topic.name,
@@ -750,7 +751,12 @@ export function NewContentDialog({
<ComboboxContent>
<ComboboxInput placeholder={t(`sources.${kind}.search`)} />
<ComboboxList>
- <ComboboxEmpty>{t(`sources.${kind}.empty`)}</ComboboxEmpty>
+ <ComboboxEmpty>
+ {/* "All seen" only when nothing is left to list, not on a search miss. */}
+ {kind === 'prompt' && items.length === 0 && options?.promptsSeen
+ ? t('sources.prompt.allSeen')
+ : t(`sources.${kind}.empty`)}
+ </ComboboxEmpty>
<ComboboxCollection>
{(item: PickerItem) => (
<ComboboxItem key={item.value} value={item} title={item.label}>
@@ -767,6 +773,11 @@ export function NewContentDialog({
</ComboboxContent>
</Combobox>
)}
+ {kind === 'prompt' && options && options.promptsSeen > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {t('sources.prompt.seen', { count: options.promptsSeen })}
+ </p>
+ )}
</div>
) : (
<div className="space-y-2">
diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.ts
index 116540ed7..325400eb9 100644
--- a/web/src/lib/actions/content-drafts-start.test.ts
+++ b/web/src/lib/actions/content-drafts-start.test.ts
@@ -21,7 +21,8 @@ let calls: Call[];
// What a read of each table returns: a row for maybeSingle, rows otherwise.
let reads: Record<string, unknown>;
let rpcCalls: { fn: string; args: unknown }[];
-let rpcRows: unknown[];
+let rpcRows: unknown;
+let rpcError: { code: string; message: string } | null;
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
// The server's writes: a draft linked to an action (CE-022).
@@ -52,7 +53,7 @@ vi.mock('@/lib/supabase/server', () => ({
},
rpc: async (fn: string, args: unknown) => {
rpcCalls.push({ fn, args });
- return { data: rpcRows, error: null };
+ return { data: rpcError ? null : rpcRows, error: rpcError };
},
from: (table: string) => {
const call: Call = { table, op: 'select', filters: [] };
@@ -98,6 +99,7 @@ beforeEach(() => {
reads = {};
rpcCalls = [];
rpcRows = [];
+ rpcError = null;
admin.inserts = [];
admin.result = { data: { id: 'action-draft' }, error: null };
admin.onInsert = null;
@@ -115,16 +117,20 @@ describe('getContentStartOptions', () => {
},
{ id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', brief: null },
],
- prompts: [
- { id: PROMPT, text: 'best crm for realtors' },
- { id: 'p2', text: 'crm pricing' },
- ],
// Counted in the database: a big brand's topics past the listed prompts too.
topics: [
{ id: TOPIC, name: 'Real estate', prompts: [{ count: 640 }] },
{ id: 't2', name: 'Empty topic', prompts: [{ count: 0 }] },
],
};
+ // The prompts, marked where the brand already shows (00230), not seen first.
+ rpcRows = {
+ prompts: [
+ { id: PROMPT, text: 'best crm for realtors', seen: false },
+ { id: 'p2', text: 'crm pricing', seen: true },
+ ],
+ seen: 7,
+ };
await expect(getContentStartOptions(BRAND)).resolves.toEqual({
opportunities: [
{
@@ -136,25 +142,65 @@ describe('getContentStartOptions', () => {
{ id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', pageTitle: null },
],
prompts: [
- { id: PROMPT, text: 'best crm for realtors' },
- { id: 'p2', text: 'crm pricing' },
+ { id: PROMPT, text: 'best crm for realtors', seen: false },
+ { id: 'p2', text: 'crm pricing', seen: true },
],
+ // Every seen prompt, past the listed ones too.
+ promptsSeen: 7,
topics: [{ id: TOPIC, name: 'Real estate', promptCount: 640 }],
});
+ expect(rpcCalls).toEqual([
+ {
+ fn: 'content_start_prompts',
+ args: { p_brand_id: BRAND, p_days: 30, p_limit: 500 },
+ },
+ ]);
expect(calls.find((call) => call.table === 'content_opportunities')!.filters).toEqual([
['eq', 'brand_id', BRAND],
['in', 'status', ['new', 'reviewed', 'sent', 'in_progress']],
]);
- expect(calls.find((call) => call.table === 'prompts')!.filters).toEqual([
- ['eq', 'prompt_sets.brand_id', BRAND],
- ['eq', 'is_active', true],
- ]);
+ expect(calls.find((call) => call.table === 'prompts')).toBeUndefined();
expect(calls.find((call) => call.table === 'topics')!.filters).toEqual([
['eq', 'brand_id', BRAND],
['eq', 'is_active', true],
['eq', 'prompts.is_active', true],
]);
});
+
+ it('lists every active prompt, none seen, before the function exists', async () => {
+ rpcError = { code: 'PGRST202', message: 'Could not find the function' };
+ reads = {
+ prompts: [
+ { id: PROMPT, text: 'best crm for realtors' },
+ { id: 'p2', text: 'crm pricing' },
+ ],
+ };
+ const options = await getContentStartOptions(BRAND);
+ expect(options.prompts).toEqual([
+ { id: PROMPT, text: 'best crm for realtors', seen: false },
+ { id: 'p2', text: 'crm pricing', seen: false },
+ ]);
+ expect(options.promptsSeen).toBe(0);
+ expect(calls.find((call) => call.table === 'prompts')!.filters).toEqual([
+ ['eq', 'prompt_sets.brand_id', BRAND],
+ ['eq', 'is_active', true],
+ ]);
+ });
+
+ it('lists no prompts for a brand that isn’t the member’s, and says so when the read fails', async () => {
+ rpcRows = null;
+ await expect(getContentStartOptions(BRAND)).resolves.toMatchObject({
+ prompts: [],
+ promptsSeen: 0,
+ });
+ rpcError = { code: '57014', message: 'canceling statement due to statement timeout' };
+ await expect(getContentStartOptions(BRAND)).rejects.toThrow('statement timeout');
+ });
+
+ it('throws on a payload the schema doesn’t know, rather than list no prompts', async () => {
+ rpcRows = { prompts: 'not a list', seen: 'x' };
+ await expect(getContentStartOptions(BRAND)).rejects.toThrow();
+ });
});
describe('createContentDraft', () => {
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 340022e27..d1b148ae1 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -243,10 +243,51 @@ const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];
/** How many of each New content lists to pick from. */
const START_LIMIT = 500;
+/** A prompt the brand was named in or cited for over these days is seen. */
+const SEEN_DAYS = 30;
+
+const startPromptsSchema = z.object({
+ prompts: z.array(z.object({ id: z.string(), text: z.string(), seen: z.boolean() })),
+ seen: z.number(),
+});
+
+/**
+ * The brand's active prompts, each marked seen when an answer of the last
+ * 30 days named the brand or cited its pages (content_start_prompts, 00230),
+ * those not seen first. Before that migration, every prompt, none seen.
+ */
+async function readStartPrompts(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+): Promise<{ prompts: DraftStartOptions['prompts']; seen: number }> {
+ const read = await supabase.rpc('content_start_prompts', {
+ p_brand_id: brandId,
+ p_days: SEEN_DAYS,
+ p_limit: START_LIMIT,
+ });
+ if (read.error?.code !== 'PGRST202') {
+ if (read.error) throw new Error(read.error.message);
+ // Null: not the member's brand. Any other shape is drift between the
+ // function and this schema, which throws (New content says it couldn't
+ // load) rather than empty the picker.
+ if (read.data === null) return { prompts: [], seen: 0 };
+ return startPromptsSchema.parse(read.data);
+ }
+ const { data, error } = await supabase
+ .from('prompts')
+ .select('id, text, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId)
+ .eq('is_active', true)
+ .order('text')
+ .limit(START_LIMIT);
+ if (error) throw new Error(error.message);
+ return { prompts: (data ?? []).map((p) => ({ id: p.id, text: p.text, seen: false })), seen: 0 };
+}
/**
* What New content (CE-003) offers to start a new page from: the brand's
- * open Content Opportunities, its active tracked prompts and its topics.
+ * open Content Opportunities, its active tracked prompts (each marked seen
+ * when the brand already shows in its answers) and its topics.
*/
export async function getContentStartOptions(brandId: string): Promise<DraftStartOptions> {
const supabase = await createClient();
@@ -258,13 +299,7 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar
.in('status', OPEN_OPPORTUNITY_STATUSES)
.order('opportunity_score', { ascending: false, nullsFirst: false })
.limit(START_LIMIT),
- supabase
- .from('prompts')
- .select('id, text, prompt_sets!inner(brand_id)')
- .eq('prompt_sets.brand_id', brandId)
- .eq('is_active', true)
- .order('text')
- .limit(START_LIMIT),
+ readStartPrompts(supabase, brandId),
// Each topic's active prompts counted in the database: the prompt list
// above stops at START_LIMIT, and would undercount a big brand's topics.
supabase
@@ -275,7 +310,7 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar
.eq('prompts.is_active', true)
.order('name'),
]);
- const failed = opportunities.error ?? prompts.error ?? topics.error;
+ const failed = opportunities.error ?? topics.error;
if (failed) throw new Error(failed.message);
return {
@@ -288,7 +323,8 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar
pageTitle: typeof suggested === 'string' && suggested.trim() ? suggested.trim() : null,
};
}),
- prompts: (prompts.data ?? []).map((p) => ({ id: p.id, text: p.text })),
+ prompts: prompts.prompts,
+ promptsSeen: prompts.seen,
// A topic with no active prompt has nothing for a page to answer.
topics: (topics.data ?? [])
.map((topic) => ({
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index 82dfe78bd..efe48778c 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -207,7 +207,13 @@ export interface DraftStartOptions {
* the opportunity's own title says what to do, not what to call the page.
*/
opportunities: { id: string; title: string; decision: string | null; pageTitle: string | null }[];
- prompts: { id: string; text: string }[];
+ /**
+ * seen: the brand was named in or cited for it lately, so it needs no new
+ * page (New content leaves it out; Add source keeps it). Not seen first.
+ */
+ prompts: { id: string; text: string; seen: boolean }[];
+ /** How many active prompts are seen, past the listed ones too. */
+ promptsSeen: number;
topics: { id: string; name: string; promptCount: number }[];
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 45b99407a..36b23a92a 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3786,6 +3786,10 @@ export type Database = {
Args: { p_brand_id: string; p_days?: number }
Returns: Json
}
+ content_start_prompts: {
+ Args: { p_brand_id: string; p_days?: number; p_limit?: number }
+ Returns: Json
+ }
content_page_overlap: {
Args: { p_brand_id: string; p_prompt_ids: string[]; p_since?: string }
Returns: {