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(content): list opportunities newest first with a clearer prompt tag (#1050)
Cihan0ba7966b6631
diff --git a/server/src/routes/content-list.test.js b/server/src/routes/content-list.test.jsnew file mode 100644index 000000000..31c96feca--- /dev/null+++ b/server/src/routes/content-list.test.js@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for the Content Opportunities list's order.+ *+ * One generation writes many opportunities at the same moment, often with+ * the same score, so the chosen order alone leaves ties the database may+ * break differently on each page. What's checked here is that every order+ * ends on the row's id, so paging never repeats or skips a row.+ */++let orders;+let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class PlanLimitError extends Error {},+ requireFeature: () => (req, res, next) => next(),+ enforceBriefQuota: vi.fn(),+ getBriefQuotaStatus: vi.fn(),+ getContentUsage: vi.fn(),+ getOpportunityRequestAllowance: vi.fn(),+ getOrgIdForUser: vi.fn(),+ }));+ vi.doMock('../lib/access.js', () => ({+ assertBrandAccess: vi.fn(),+ assertOpportunitiesAccess: vi.fn(),+ assertOpportunityAccess: vi.fn(),+ assertPromptAccess: vi.fn(),+ }));+ vi.doMock('../lib/job-manager.js', () => ({ createJob: vi.fn(), getJob: vi.fn() }));+ vi.doMock('../lib/job-runner.js', () => ({ runContentJob: vi.fn() }));+ // Every query resolves to an empty page; only the order() calls are kept.+ vi.doMock('../config/supabase.js', () => {+ const chain = new Proxy(+ {},+ {+ get: (_t, op) => {+ if (op === 'then') return (resolve) => resolve({ data: [], error: null, count: 0 });+ if (op === 'order') {+ return (column, options) => {+ orders.push([column, options?.ascending]);+ return chain;+ };+ }+ return () => chain;+ },+ },+ );+ return { default: { from: () => chain, rpc: async () => ({ data: [], error: null }) } };+ });+ vi.doMock('../lib/prompt-clusters.js', () => ({ loadClusters: vi.fn() }));+ vi.doMock('../lib/action-center/from-opportunity.js', () => ({ sendToActionCenter: vi.fn() }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });++ const { default: router } = await import('./content.js');+ const app = express();+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/content', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content`;+}++const list = (query = '') => fetch(`${baseUrl}/brand/b1${query}`);++beforeEach(async () => {+ orders = [];+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('GET /brand/:brandId order', () => {+ it('lists the newest first, ties in id order', async () => {+ const res = await list('?sort=newest');++ expect(res.status).toBe(200);+ expect(orders).toEqual([+ ['created_at', false],+ ['id', true],+ ]);+ });++ it('lists the oldest first, ties in id order', async () => {+ await list('?sort=oldest');++ expect(orders).toEqual([+ ['created_at', true],+ ['id', true],+ ]);+ });++ it('keeps the highest score first when no order is asked for, ties in id order', async () => {+ await list();++ expect(orders).toEqual([+ ['opportunity_score', false],+ ['id', true],+ ]);+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 176209ed6..fbc85d0e6 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -559,6 +559,9 @@ router.get('/brand/:brandId', async (req, res) => {ascending: sort === 'oldest',});}+ // One generation writes many rows at the same moment and score; id keeps+ // their order stable, so paging never repeats or skips a row.+ dataQuery = dataQuery.order('id', { ascending: true });dataQuery = dataQuery.range(Number(offset), Number(offset) + Number(limit) - 1);diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2d77bc387..b83c4821b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1801,6 +1801,7 @@"fromSignals": "from {count, plural, one {# signal} other {# signals}} analyzed"},"filters": {+ "search": "Search opportunities","allStatuses": "All Statuses","allImpacts": "All Impacts","allTypes": "All Types",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 92f2f1ff4..e6f84c38c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -57,6 +57,7 @@ import {Trash2,Download,Plus,+ ChevronDown,} from 'lucide-react';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';@@ -80,10 +81,26 @@ import { toast } from 'sonner';import { Link } from '@/i18n/navigation';import { WebhookSettingsDialog } from './_webhook-settings';import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { OpportunityDetail } from '@/components/content/opportunity-detail';import { ContentUsageCard } from '@/components/content/content-usage-card';import { hasContentQuota, onDemandMax, type ContentUsage } from '@/lib/content-usage';import { suggestedBounds, suggestedDate, type SuggestedRange } from '@/lib/suggested-date';+import {+ DEFAULT_OPPORTUNITY_SORT,+ OPPORTUNITY_SORTS,+ opportunityScope,+ type OpportunitySort,+} from '@/lib/content/opportunity-list';import {NewOpportunitiesDialog,type NewOpportunitiesInput,@@ -109,7 +126,6 @@ const STATUS_VALUES = [const IMPACT_VALUES = ['all', 'high', 'medium', 'low'] as const;const TYPE_VALUES = ['all', 'owned', 'earned'] as const;const SOURCE_VALUES = ['all', 'system', 'manual', 'prompt'] as const;-const SORT_VALUES = ['score', 'newest', 'oldest'] as const;const SUGGESTED_VALUES = ['all', 'month', 'last30', 'custom'] as const;const URL_DEFAULTS = {status: 'all',@@ -119,7 +135,7 @@ const URL_DEFAULTS = {suggested: 'all',from: '',to: '',- sort: 'score',+ sort: DEFAULT_OPPORTUNITY_SORT,};/** When the list was last opened, per brand: rows suggested since get a dot. */@@ -269,24 +285,32 @@ function SuggestedCell({}/**- * What an opportunity was built for: a group of related prompts in a topic- * (cluster opportunities, #857) or a single prompt (the older generator).+ * What an opportunity was built for, as a tag before its description: a+ * group of related prompts in a topic (cluster opportunities, #857) in+ * violet, or a single prompt (the older generator) in grey. Violet keeps it+ * apart from the impact and status colours on the same row.*/function OpportunityScope({ opp }: { opp: ContentOpportunity }) {const t = useTranslations('content.scope');- const count = opp.sourceData?.prompts?.length ?? 0;- const group = !!opp.clusterId;- const label = group- ? opp.sourceData?.topicName- ? t('group', { topic: opp.sourceData.topicName, count })- : t('groupNoTopic', { count })- : t('single');+ const scope = opportunityScope(opp);+ const group = scope.kind === 'group';+ const label =+ scope.kind === 'group'+ ? scope.topic+ ? t('group', { topic: scope.topic, count: scope.count })+ : t('groupNoTopic', { count: scope.count })+ : t('single');return (<span- className="mr-1.5 font-medium text-foreground/70"+ className={cn(+ 'mr-1.5 inline-flex items-center rounded px-1.5 py-px align-middle text-[11px] font-medium leading-4 ring-1 ring-inset',+ group+ ? 'bg-violet-50 text-violet-700 ring-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:ring-violet-900'+ : 'bg-muted text-foreground/80 ring-border',+ )}title={group ? t('groupHint') : t('singleHint')}>- {label} ·+ {label}</span>);}@@ -325,7 +349,7 @@ export default function ContentPage() {const [customTo, setCustomTo] = useState('');// The previous visit, read once per brand before this one is recorded.const [lastVisit, setLastVisit] = useState<number | null>(null);- const [sortOrder, setSortOrder] = useState<string>('score');+ const [sortOrder, setSortOrder] = useState<string>(DEFAULT_OPPORTUNITY_SORT);// The prompt filter (#836) lives in the URL as ?prompt=<id> so a filtered// view can be linked to. It is read after mount — useSearchParams would need// a Suspense boundary around the page — and loading waits for it, so a@@ -470,7 +494,7 @@ export default function ContentPage() {setSuggestedRange(readUrlChoice('suggested', SUGGESTED_VALUES, 'all'));setCustomFrom(params.get('from') ?? '');setCustomTo(params.get('to') ?? '');- setSortOrder(readUrlChoice('sort', SORT_VALUES, 'score'));+ setSortOrder(readUrlChoice('sort', OPPORTUNITY_SORTS, DEFAULT_OPPORTUNITY_SORT));setUrlRead(true);}, []);@@ -1034,27 +1058,31 @@ export default function ContentPage() {<Card><CardHeader className="pb-3">- <div className="flex items-center justify-between gap-4 flex-wrap">- <div className="flex items-center gap-2">- <CardTitle className="text-sm font-medium">{t('opportunities')}</CardTitle>- <Badge- variant="outline"- className="text-xs border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"- >- {t('available', { count: total })}- </Badge>- </div>- <div className="flex items-center gap-2 flex-wrap">- <div className="relative w-48">- <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />+ {/* The search sits on the title's line, right-aligned and larger,+ so the filters below keep a line of their own. */}+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-4">+ <div className="flex shrink-0 items-center gap-2">+ <CardTitle className="text-sm font-medium">{t('opportunities')}</CardTitle>+ <Badge+ variant="outline"+ className="text-xs border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ >+ {t('available', { count: total })}+ </Badge>+ </div>+ <div className="relative w-full max-w-80">+ <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" /><Input- placeholder={tCommon('search')}+ placeholder={t('filters.search')}value={search}onChange={(e) => setSearch(e.target.value)}- aria-label={tCommon('search')}- className="pl-8 h-8 text-xs"+ aria-label={t('filters.search')}+ className="h-9 pl-9 text-sm"/></div>+ </div>+ <div className="flex items-center gap-2 flex-wrap">{(topicOptions.length >= 2 || topicFilter !== '') && (<Selectitems={[@@ -1190,26 +1218,57 @@ export default function ContentPage() {))}</SelectContent></Select>- <Select- value={suggestedRange}- onValueChange={(v) => v && setSuggestedRange(v as SuggestedRange)}- >- <SelectTrigger- className="h-8 w-[130px] text-xs"- aria-label={t('suggestedRange.label')}+ {/* When it was suggested and the order, in one box: the order+ reads by the Suggested dates, newest first unless picked. */}+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={`${t('suggestedRange.label')}: ${t(`suggestedRange.${suggestedRange}`)}, ${t('sort.label')}: ${t(`sort.${sortOrder as OpportunitySort}`)}`}+ className="flex h-8 w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-xs whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 dark:hover:bg-input/50">- <SelectValue>- {(value) => t(`suggestedRange.${value as SuggestedRange}`)}- </SelectValue>- </SelectTrigger>- <SelectContent>- {SUGGESTED_VALUES.map((value) => (- <SelectItem key={value} value={value}>- {t(`suggestedRange.${value}`)}- </SelectItem>- ))}- </SelectContent>- </Select>+ {t(`suggestedRange.${suggestedRange}`)} ·{' '}+ {t(`sort.${sortOrder as OpportunitySort}`)}+ <ChevronDown className="pointer-events-none size-4 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-44">+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t('suggestedRange.label')}</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={suggestedRange}+ onValueChange={(v) => setSuggestedRange(v as SuggestedRange)}+ >+ {SUGGESTED_VALUES.map((value) => (+ <DropdownMenuRadioItem+ key={value}+ value={value}+ closeOnClick+ className="text-xs"+ >+ {t(`suggestedRange.${value}`)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t('sort.label')}</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={sortOrder}+ onValueChange={(v) => setSortOrder(v as string)}+ >+ {OPPORTUNITY_SORTS.map((value) => (+ <DropdownMenuRadioItem+ key={value}+ value={value}+ closeOnClick+ className="text-xs"+ >+ {t(`sort.${value}`)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>{suggestedRange === 'custom' && (<span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Input@@ -1250,20 +1309,6 @@ export default function ContentPage() {<SelectItem value="archived">{t('status.archived')}</SelectItem></SelectContent></Select>- <Select value={sortOrder} onValueChange={(v) => v && setSortOrder(v)}>- <SelectTrigger className="h-8 w-[130px] text-xs" aria-label={t('sort.label')}>- <SelectValue>- {(value) => t(`sort.${value as 'score' | 'newest' | 'oldest'}`)}- </SelectValue>- </SelectTrigger>- <SelectContent>- {SORT_VALUES.map((value) => (- <SelectItem key={value} value={value}>- {t(`sort.${value}`)}- </SelectItem>- ))}- </SelectContent>- </Select></div></div></CardHeader>diff --git a/web/src/lib/content/opportunity-list.test.ts b/web/src/lib/content/opportunity-list.test.tsnew file mode 100644index 000000000..2e8fd3cc6--- /dev/null+++ b/web/src/lib/content/opportunity-list.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';+import type { ContentOpportunity } from '@/types';+import { DEFAULT_OPPORTUNITY_SORT, OPPORTUNITY_SORTS, opportunityScope } from './opportunity-list';++const opp = (over: Partial<ContentOpportunity>) =>+ ({ clusterId: null, sourceData: null, ...over }) as ContentOpportunity;++describe('Content Opportunities list', () => {+ it('opens on the newest suggestions, with score and oldest still offered', () => {+ expect(DEFAULT_OPPORTUNITY_SORT).toBe('newest');+ expect(OPPORTUNITY_SORTS).toEqual(['newest', 'score', 'oldest']);+ });++ it('tags a cluster opportunity with its topic and prompt count', () => {+ expect(+ opportunityScope(+ opp({+ clusterId: 'c1',+ sourceData: { topicName: 'Coffee subscriptions', prompts: [{}, {}, {}] },+ } as Partial<ContentOpportunity>),+ ),+ ).toEqual({ kind: 'group', count: 3, topic: 'Coffee subscriptions' });+ });++ it('tags an opportunity without a cluster as a single prompt', () => {+ expect(opportunityScope(opp({}))).toEqual({ kind: 'single' });+ });++ it('keeps a group without a topic or prompts list readable', () => {+ expect(opportunityScope(opp({ clusterId: 'c1' }))).toEqual({+ kind: 'group',+ count: 0,+ topic: null,+ });+ });+});diff --git a/web/src/lib/content/opportunity-list.ts b/web/src/lib/content/opportunity-list.tsnew file mode 100644index 000000000..02d8ecef6--- /dev/null+++ b/web/src/lib/content/opportunity-list.ts@@ -0,0 +1,29 @@+import type { ContentOpportunity } from '@/types';++/**+ * How the Content Opportunities list orders its rows, first the default:+ * the newest suggestions on top, so the latest work is what the list opens+ * on. Highest score and Oldest stay a pick away.+ */+export const OPPORTUNITY_SORTS = ['newest', 'score', 'oldest'] as const;+export type OpportunitySort = (typeof OPPORTUNITY_SORTS)[number];+export const DEFAULT_OPPORTUNITY_SORT: OpportunitySort = OPPORTUNITY_SORTS[0];++/**+ * What an opportunity was built for: a group of related prompts in a topic+ * (cluster opportunities, #857), or a single prompt (the older generator).+ */+export type OpportunityScope =+ | { kind: 'group'; count: number; topic: string | null }+ | { kind: 'single' };++export function opportunityScope(+ opp: Pick<ContentOpportunity, 'clusterId' | 'sourceData'>,+): OpportunityScope {+ if (!opp.clusterId) return { kind: 'single' };+ return {+ kind: 'group',+ count: opp.sourceData?.prompts?.length ?? 0,+ topic: opp.sourceData?.topicName ?? null,+ };+}