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): review and approve brand facts in Brand settings (CE-047, part c) (#1464)

Cihan3b81aec87897
diff --git a/web/messages/en.json b/web/messages/en.json
index 74e2c6b5d..490e0e8cc 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7347,6 +7347,62 @@
"ecommerceDetected": "{brand} looks like an online store, so we turned on Product Visibility: ChatGPT Shopping is tracked for your prompts on plans that include it. You can turn it off in brand settings."
},
"settings": {
+ "facts": {
+ "tab": "Brand facts",
+ "title": "Brand facts",
+ "description": "Your prices and plans, your trial, when you were founded and the claims you make, read from your own pricing, About and product pages. Approve the ones that are right: Quality checks your pages against the approved ones that are still on your site.",
+ "loading": "Reading your brand facts",
+ "loadFailed": "Your brand facts couldn't be read. Try again in a moment.",
+ "off": "Brand facts aren't available yet.",
+ "quoted": "“{quote}”",
+ "pageStatusAfter": ": {status}",
+ "noDomain": "Add your site's domain under Domains to read your brand facts from it.",
+ "checked": "Read from your site {date}",
+ "pageStatus": {
+ "ok": "read",
+ "blocked": "turned our reader away",
+ "not_found": "not found",
+ "failed": "didn't answer, read again next time",
+ "missed": "couldn't be read, tried again a day later"
+ },
+ "sources": {
+ "pricing": "Pricing page",
+ "about": "About page",
+ "product": "Product page"
+ },
+ "readAgain": "Read again",
+ "readAgainSoon": "Your site was read a few minutes ago. You can read it again shortly.",
+ "readFailed": "Your site couldn't be read again. Try again in a moment.",
+ "aiPaused": "This month's AI usage is used up: pages not read yet are read at the first read after it renews.",
+ "empty": "No facts were found on your site yet.",
+ "toApprove": "To approve ({count})",
+ "approved": "Approved",
+ "rejected": "Rejected ({count})",
+ "approve": "Approve",
+ "reject": "Reject",
+ "approveFact": "Approve {fact}",
+ "rejectFact": "Reject {fact}",
+ "reviewFailed": "That fact couldn't be saved. Try again.",
+ "gone": "No longer on your site",
+ "replaces": "Was {value}",
+ "trialDays": "{days, plural, one {# day} other {# days}}",
+ "perSeat": "per seat",
+ "periods": {
+ "month": "/ month",
+ "year": "/ year",
+ "once": "once"
+ },
+ "billed": {
+ "monthly": "billed monthly",
+ "annually": "billed annually"
+ },
+ "kinds": {
+ "price": "Price",
+ "trial": "Trial",
+ "founded": "Founded",
+ "claim": "Claim"
+ }
+ },
"title": "Brand Settings",
"generalTab": "General",
"domainsTab": "Domains",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_brand-facts-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_brand-facts-tab.test.tsx
new file mode 100644
index 000000000..7cbb63e7a
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_brand-facts-tab.test.tsx
@@ -0,0 +1,235 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import type { BrandFact, BrandFactsRead } from '@/lib/content/brand-facts';
+import { BrandFactsTab } from './_brand-facts-tab';
+
+const getBrandFacts = vi.fn();
+const readBrandFactsAgain = vi.fn();
+const setBrandFactStatus = vi.fn();
+vi.mock('@/lib/actions/brand-facts', () => ({
+ getBrandFacts: (...args: unknown[]) => getBrandFacts(...args),
+ readBrandFactsAgain: (...args: unknown[]) => readBrandFactsAgain(...args),
+ setBrandFactStatus: (...args: unknown[]) => setBrandFactStatus(...args),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/**
+ * Brand settings › Brand facts (Quality CE-047): the facts read from the
+ * brand's own site, each approved or rejected by a member, with where it
+ * was read and what it would replace.
+ */
+
+const NOW = Date.parse('2026-10-24T12:00:00Z');
+const fact = (over: Partial<BrandFact>): BrandFact => ({
+ id: 'f1',
+ kind: 'price',
+ value: { plan: 'Pro', amount: 49, currency: 'USD', period: 'month', billed: null, per: null },
+ quote: '$49 per month',
+ sourceUrl: 'https://ledgerly.example/pricing',
+ sourceKind: 'pricing',
+ status: 'pending',
+ reviewedAt: null,
+ firstSeenAt: '2026-10-24T11:00:00Z',
+ gone: false,
+ replaces: null,
+ ...over,
+});
+const READ: BrandFactsRead = {
+ facts: [
+ fact({
+ replaces: {
+ id: 'f0',
+ value: {
+ plan: 'Pro',
+ amount: 59,
+ currency: 'USD',
+ period: 'month',
+ billed: null,
+ per: null,
+ },
+ },
+ }),
+ fact({
+ id: 'f2',
+ kind: 'trial',
+ value: { days: 14 },
+ quote: '14-day free trial',
+ status: 'approved',
+ }),
+ fact({
+ id: 'f3',
+ kind: 'claim',
+ value: {},
+ quote: 'SOC 2 Type II certified',
+ status: 'approved',
+ gone: true,
+ }),
+ fact({
+ id: 'f4',
+ kind: 'founded',
+ value: { year: 2015 },
+ quote: 'Founded in 2015',
+ status: 'rejected',
+ sourceKind: 'about',
+ }),
+ ],
+ pages: [
+ {
+ kind: 'pricing',
+ url: 'https://ledgerly.example/pricing',
+ status: 'ok',
+ checkedAt: '2026-10-24T11:59:00Z',
+ },
+ { kind: 'about', url: null, status: 'blocked', checkedAt: '2026-10-24T11:59:00Z' },
+ ],
+ checkedAt: '2026-10-24T11:59:00Z',
+ recheckAt: '2026-10-24T12:09:00Z',
+ paused: false,
+ noDomain: false,
+};
+
+let container: HTMLDivElement;
+let root: Root;
+const render = async () => {
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <BrandFactsTab brandId="b1" />
+ </NextIntlClientProvider>,
+ ),
+ );
+};
+const button = (label: string, within: ParentNode = container) =>
+ [...within.querySelectorAll('button')].find((b) => b.textContent === label);
+/** A section by its heading (aria-labelledby). */
+const section = (label: string) =>
+ [...container.querySelectorAll('section')].find(
+ (s) => document.getElementById(s.getAttribute('aria-labelledby')!)?.textContent === label,
+ )!;
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(NOW);
+ getBrandFacts.mockReset().mockResolvedValue(READ);
+ readBrandFactsAgain.mockReset();
+ setBrandFactStatus.mockReset();
+ toast.error.mockReset();
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe('BrandFactsTab', () => {
+ it('lists the facts to approve, approved and rejected, with their words, page and what they replace', async () => {
+ await render();
+ expect(getBrandFacts).toHaveBeenCalledWith('b1');
+ const toApprove = section('To approve (1)');
+ expect(toApprove.textContent).toContain('Pro · $49 / month');
+ expect(toApprove.textContent).toContain('“$49 per month”');
+ expect(toApprove.textContent).toContain('Was Pro · $59 / month');
+ expect(toApprove.querySelector('a')?.getAttribute('href')).toBe(
+ 'https://ledgerly.example/pricing',
+ );
+ expect(button('Approve', toApprove)?.getAttribute('aria-label')).toBe(
+ 'Approve Pro · $49 / month',
+ );
+
+ const approved = section('Approved');
+ expect(approved.textContent).toContain('14 days');
+ expect(approved.textContent).toContain('“SOC 2 Type II certified”');
+ expect(approved.textContent).toContain('No longer on your site');
+ // An approved fact can only be rejected; a rejected one approved again.
+ expect(button('Approve', approved)).toBeUndefined();
+ const rejected = container.querySelector('details')!;
+ expect(rejected.querySelector('summary')?.textContent).toBe('Rejected (1)');
+ expect(rejected.textContent).toContain('2015');
+
+ // Each page read, and how.
+ expect(container.textContent).toContain('Pricing page: read');
+ expect(container.textContent).toContain('About page: turned our reader away');
+ });
+
+ it('approves a fact as the member, in the list at once, dropping the gone one it replaces', async () => {
+ const gone = fact({ id: 'f0', status: 'approved', gone: true, quote: '$59 per month' });
+ getBrandFacts.mockResolvedValue({ ...READ, facts: [...READ.facts, gone] });
+ await render();
+ setBrandFactStatus.mockResolvedValue({ id: 'f1', status: 'approved' });
+ await act(async () => button('Approve', section('To approve (1)'))!.click());
+ expect(setBrandFactStatus).toHaveBeenCalledWith('f1', 'approved');
+ // No read of the site, nor of the list: the review is the list's.
+ expect(getBrandFacts).toHaveBeenCalledTimes(1);
+ expect(section('To approve (1)')).toBeUndefined();
+ const approved = section('Approved');
+ expect(approved.textContent).toContain('Pro · $49 / month');
+ expect(approved.textContent).not.toContain('$59 per month');
+ });
+
+ it('reads the list again when a review fails (a read removed the fact meanwhile)', async () => {
+ await render();
+ setBrandFactStatus.mockResolvedValue({ error: 'failed' });
+ getBrandFacts.mockResolvedValueOnce({ ...READ, facts: READ.facts.slice(1) });
+ await act(async () => button('Approve', section('To approve (1)'))!.click());
+ expect(toast.error).toHaveBeenCalledWith("That fact couldn't be saved. Try again.");
+ expect(getBrandFacts).toHaveBeenCalledTimes(2);
+ expect(section('To approve (1)')).toBeUndefined();
+ });
+
+ it('does one thing at a time: no second review, and no read of the site, while one is out', async () => {
+ vi.setSystemTime(Date.parse('2026-10-24T12:10:00Z'));
+ await render();
+ let answer: (value: unknown) => void = () => {};
+ setBrandFactStatus.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ await act(async () => button('Approve', section('To approve (1)'))!.click());
+ expect(button('Approve', section('To approve (1)'))!.disabled).toBe(true);
+ expect(button('Read again')!.disabled).toBe(true);
+ expect(section('To approve (1)').querySelector('li')!.getAttribute('aria-busy')).toBe('true');
+ await act(async () => answer({ id: 'f1', status: 'approved' }));
+ expect(button('Read again')!.disabled).toBe(false);
+ });
+
+ it('reads the site again only once the API allows it', async () => {
+ await render();
+ expect(button('Read again')?.disabled).toBe(true);
+ vi.setSystemTime(Date.parse('2026-10-24T12:10:00Z'));
+ getBrandFacts.mockResolvedValue({ ...READ, recheckAt: '2026-10-24T12:09:00Z' });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ readBrandFactsAgain.mockResolvedValue({ ...READ, paused: true, facts: [] });
+ await act(async () => button('Read again')!.click());
+ expect(readBrandFactsAgain).toHaveBeenCalledWith('b1');
+ expect(container.textContent).toContain("This month's AI usage is used up");
+ expect(container.textContent).toContain('No facts were found on your site yet.');
+ });
+
+ it('says when the API has them off', async () => {
+ getBrandFacts.mockResolvedValueOnce({ error: 'off' });
+ await render();
+ expect(container.textContent).toContain("Brand facts aren't available yet.");
+ });
+
+ it('says when the brand has no domain, and when the facts can’t be read', async () => {
+ getBrandFacts.mockResolvedValueOnce({ ...READ, noDomain: true, facts: [] });
+ await render();
+ expect(container.textContent).toContain("Add your site's domain under Domains");
+ expect(button('Read again')).toBeUndefined();
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ getBrandFacts.mockResolvedValueOnce({ error: 'failed' });
+ await render();
+ expect(container.textContent).toContain("Your brand facts couldn't be read.");
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_brand-facts-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_brand-facts-tab.tsx
new file mode 100644
index 000000000..b288805fa
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_brand-facts-tab.tsx
@@ -0,0 +1,307 @@
+'use client';
+
+import { useEffect, useId, useState } from 'react';
+import { useFormatter, useNow, useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { LoadingDots } from '@/components/ui/loading-dots';
+import { getBrandFacts, readBrandFactsAgain, setBrandFactStatus } from '@/lib/actions/brand-facts';
+import {
+ factValueText,
+ isPrice,
+ type BrandFact,
+ type BrandFactsRead,
+ type FactStatus,
+} from '@/lib/content/brand-facts';
+import { cn } from '@/lib/utils';
+
+/**
+ * Brand settings › Brand facts (Quality spec §10, CE-047): the facts the API
+ * read from the brand's own pricing, About and product pages, each with its
+ * words on the page and where; a member approves or rejects each one (no
+ * "approve all": the spec has each approved). Only approved facts still on
+ * the site are compared with a page. "Read again" reads the site again, not
+ * more than the API allows; nothing else here reads the site.
+ */
+export function BrandFactsTab({ brandId }: { brandId: string }) {
+ const t = useTranslations('brands.settings.facts');
+ const format = useFormatter();
+ // Read again turns on when the API allows it, without a reload.
+ const now = useNow({ updateInterval: 30_000 });
+ const [read, setRead] = useState<BrandFactsRead | null>(null);
+ const [failed, setFailed] = useState<'off' | 'failed' | null>(null);
+ const [reading, setReading] = useState(false);
+ const [busy, setBusy] = useState<string | null>(null);
+ const ids = useId();
+
+ useEffect(() => {
+ let cancelled = false;
+ getBrandFacts(brandId)
+ .then((result) => {
+ if (cancelled) return;
+ if ('error' in result) setFailed(result.error === 'off' ? 'off' : 'failed');
+ else setRead(result);
+ })
+ .catch(() => !cancelled && setFailed('failed'));
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
+
+ const readAgain = async () => {
+ setReading(true);
+ try {
+ const result = await readBrandFactsAgain(brandId);
+ if ('error' in result) toast.error(t('readFailed'));
+ else setRead(result);
+ } catch {
+ toast.error(t('readFailed'));
+ } finally {
+ setReading(false);
+ }
+ };
+
+ /** The facts as kept after a review: its status, and the gone fact an approval replaces dropped. */
+ const reviewed = (fact: BrandFact, status: FactStatus) => (prev: BrandFactsRead | null) =>
+ prev && {
+ ...prev,
+ facts: prev.facts
+ .filter((f) => !(status === 'approved' && f.id === fact.replaces?.id && f.gone))
+ .map((f) => (f.id === fact.id ? { ...f, status, replaces: null } : f)),
+ };
+
+ const review = async (fact: BrandFact, status: 'approved' | 'rejected') => {
+ setBusy(fact.id);
+ try {
+ const result = await setBrandFactStatus(fact.id, status);
+ if (!('error' in result)) {
+ setRead(reviewed(fact, result.status));
+ return;
+ }
+ toast.error(t('reviewFailed'));
+ // A read may have removed it meanwhile: the list as kept now.
+ const again = await getBrandFacts(brandId);
+ if (!('error' in again)) setRead(again);
+ } catch {
+ toast.error(t('reviewFailed'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const valueOf = (fact: Pick<BrandFact, 'kind' | 'value' | 'quote'>) => {
+ const text = factValueText(fact.kind, fact.value, fact.quote);
+ if (fact.kind === 'trial') return t('trialDays', { days: Number(text) });
+ if (!isPrice(fact)) return text;
+ const { plan, period, billed, per } = fact.value;
+ return [
+ plan,
+ `${text}${period ? ` ${t(`periods.${period}`)}` : ''}`,
+ per ? t('perSeat') : null,
+ billed ? t(`billed.${billed}`) : null,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+ };
+
+ if (failed) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('title')}</CardTitle>
+ <CardDescription>{failed === 'off' ? t('off') : t('loadFailed')}</CardDescription>
+ </CardHeader>
+ </Card>
+ );
+ }
+
+ const pending = read?.facts.filter((f) => f.status === 'pending') ?? [];
+ const approved = read?.facts.filter((f) => f.status === 'approved') ?? [];
+ const rejected = read?.facts.filter((f) => f.status === 'rejected') ?? [];
+ // One thing at a time: a read of the site and a review would overwrite each other.
+ const canReadAgain =
+ !!read &&
+ !reading &&
+ busy === null &&
+ (!read.recheckAt || Date.parse(read.recheckAt) <= now.getTime());
+
+ const row = (fact: BrandFact) => (
+ <li
+ key={fact.id}
+ aria-busy={busy === fact.id}
+ className={cn('flex items-start gap-3 px-3 py-2.5 text-sm', busy === fact.id && 'opacity-60')}
+ >
+ <div className="min-w-0 flex-1 space-y-0.5">
+ <p className="font-medium [overflow-wrap:anywhere]">
+ <span className="mr-1.5 text-xs font-normal text-muted-foreground">
+ {t(`kinds.${fact.kind}`)}
+ </span>
+ {fact.kind === 'claim' ? t('quoted', { quote: fact.quote }) : valueOf(fact)}
+ {fact.gone && (
+ <Badge variant="outline" className="ml-2 align-middle text-[11px] font-normal">
+ {t('gone')}
+ </Badge>
+ )}
+ </p>
+ {fact.kind !== 'claim' && (
+ <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">
+ {t('quoted', { quote: fact.quote })}
+ </p>
+ )}
+ <p className="text-xs text-muted-foreground">
+ <a
+ href={fact.sourceUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline-offset-2 hover:underline"
+ >
+ {t(`sources.${fact.sourceKind}`)}
+ </a>
+ {fact.replaces && (
+ <>
+ {' · '}
+ {t('replaces', {
+ value: valueOf({ kind: fact.kind, value: fact.replaces.value, quote: '' }),
+ })}
+ </>
+ )}
+ </p>
+ </div>
+ <div className="flex shrink-0 gap-1.5">
+ {fact.status !== 'approved' && (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={busy !== null || reading}
+ aria-label={t('approveFact', { fact: valueOf(fact) })}
+ onClick={() => void review(fact, 'approved')}
+ >
+ {t('approve')}
+ </Button>
+ )}
+ {fact.status !== 'rejected' && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7"
+ disabled={busy !== null || reading}
+ aria-label={t('rejectFact', { fact: valueOf(fact) })}
+ onClick={() => void review(fact, 'rejected')}
+ >
+ {t('reject')}
+ </Button>
+ )}
+ </div>
+ </li>
+ );
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('title')}</CardTitle>
+ <CardDescription>{t('description')}</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {!read ? (
+ <div className="flex justify-center py-8">
+ <LoadingDots size="md" label={t('loading')} className="text-muted-foreground" />
+ </div>
+ ) : read.noDomain ? (
+ <p className="text-sm text-muted-foreground">{t('noDomain')}</p>
+ ) : (
+ <>
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="space-y-1 text-xs text-muted-foreground">
+ {read.checkedAt && (
+ <p>
+ {t('checked', {
+ date: format.dateTime(new Date(read.checkedAt), {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }),
+ })}
+ </p>
+ )}
+ <ul className="space-y-0.5">
+ {read.pages.map((page) => {
+ const name = t(`sources.${page.kind}`);
+ return (
+ <li key={page.kind}>
+ {page.url && page.status !== 'not_found' ? (
+ <a
+ href={page.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline-offset-2 hover:underline"
+ >
+ {name}
+ </a>
+ ) : (
+ name
+ )}
+ {t('pageStatusAfter', { status: t(`pageStatus.${page.status}`) })}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!canReadAgain}
+ title={canReadAgain ? undefined : t('readAgainSoon')}
+ onClick={() => void readAgain()}
+ >
+ {reading && <LoadingDots />}
+ {t('readAgain')}
+ </Button>
+ </div>
+
+ {read.paused && (
+ <p className="rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs">
+ {t('aiPaused')}
+ </p>
+ )}
+
+ {read.facts.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('empty')}</p>
+ ) : (
+ <>
+ {pending.length > 0 && (
+ <section aria-labelledby={`${ids}-pending`} className="space-y-2">
+ <h4 id={`${ids}-pending`} className="text-xs font-medium text-muted-foreground">
+ {t('toApprove', { count: pending.length })}
+ </h4>
+ <ul className="divide-y rounded-xl border">{pending.map(row)}</ul>
+ </section>
+ )}
+ {approved.length > 0 && (
+ <section aria-labelledby={`${ids}-approved`} className="space-y-2">
+ <h4
+ id={`${ids}-approved`}
+ className="text-xs font-medium text-muted-foreground"
+ >
+ {t('approved')}
+ </h4>
+ <ul className="divide-y rounded-xl border">{approved.map(row)}</ul>
+ </section>
+ )}
+ {rejected.length > 0 && (
+ <details className="space-y-2">
+ <summary className="cursor-pointer text-xs font-medium text-muted-foreground">
+ {t('rejected', { count: rejected.length })}
+ </summary>
+ <ul className="mt-2 divide-y rounded-xl border">{rejected.map(row)}</ul>
+ </details>
+ )}
+ </>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/layout.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/layout.tsx
new file mode 100644
index 000000000..a0eb19030
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/layout.tsx
@@ -0,0 +1,10 @@
+/**
+ * Brand settings › Brand facts' server actions wait while the API reads the
+ * brand's site (CE-047: a few pages, then the model, up to a minute), past a
+ * page's default time on the platform. As the content editor's do.
+ */
+export const maxDuration = 300;
+
+export default function BrandSettingsLayout({ children }: { children: React.ReactNode }) {
+ return children;
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.test.tsx
index 60c823a20..0c7434974 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.test.tsx
@@ -97,6 +97,11 @@ vi.mock('sonner', () => ({
},
}));
+// Brand facts are _brand-facts-tab.test.tsx's; here, when the tab is there.
+vi.mock('./_brand-facts-tab', () => ({
+ BrandFactsTab: ({ brandId }: { brandId: string }) => <p data-testid="brand-facts">{brandId}</p>,
+}));
+
import BrandSettingsPage from './page';
afterEach(() => {
@@ -334,3 +339,49 @@ describe('brand settings role gates', () => {
await act(async () => root.unmount());
});
});
+
+describe('Brand facts tab (Quality CE-047)', () => {
+ const roots: ReturnType<typeof createRoot>[] = [];
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ for (const root of roots.splice(0)) act(() => root.unmount());
+ });
+ const open = async (tab?: string) => {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+ roots.push(root);
+ await act(async () => {
+ root.render(
+ <Suspense>
+ <BrandSettingsPage
+ params={Promise.resolve({ id: brand.id })}
+ searchParams={Promise.resolve({ tab })}
+ />
+ </Suspense>,
+ );
+ });
+ const tabs = [...container.querySelectorAll('[role="tab"]')];
+ return {
+ container,
+ labels: tabs.map((t) => t.textContent),
+ selected: tabs.find((t) => t.getAttribute('aria-selected') === 'true')?.textContent,
+ };
+ };
+
+ it('is there with phase 2, and ?tab=facts opens it', async () => {
+ vi.stubEnv('NEXT_PUBLIC_CONTENT_QUALITY_PHASE', '2');
+ const { container, labels, selected } = await open('facts');
+ expect(labels).toContain('settings.facts.tab');
+ expect(selected).toBe('settings.facts.tab');
+ expect(container.querySelector('[data-testid="brand-facts"]')?.textContent).toBe(brand.id);
+ });
+
+ it('isn’t before phase 2, where ?tab=facts opens General', async () => {
+ vi.stubEnv('NEXT_PUBLIC_CONTENT_QUALITY_PHASE', '1');
+ const { container, labels, selected } = await open('facts');
+ expect(labels).not.toContain('settings.facts.tab');
+ expect(selected).toBe('settings.generalTab');
+ expect(container.querySelector('[data-testid="brand-facts"]')).toBeNull();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
index 191909667..47f54d0d6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
@@ -58,15 +58,27 @@ import {
} from '@/components/ui/dialog';
import { getPublicApiBaseUrl } from '@/config/api';
import { SITE_TYPES, guessSiteType, isSiteType, type SiteType } from '@/lib/content/page-types';
+import { qualityPhase } from '@/lib/content/quality';
+import { BrandFactsTab } from './_brand-facts-tab';
interface PageProps {
params: Promise<{ id: string }>;
+ /** `?tab=facts` opens Brand facts (the editor's to-do links there). */
+ searchParams?: Promise<{ tab?: string }>;
}
+const TABS = ['general', 'domains', 'tracking', 'competitors', 'facts', 'danger'];
+/** No search params: one promise for every render, as use() needs. */
+const NO_SEARCH: Promise<{ tab?: string }> = Promise.resolve({});
+
const INDUSTRY_ITEMS = INDUSTRIES.map((industry) => ({ value: industry, label: industry }));
-export default function BrandSettingsPage({ params }: PageProps) {
+export default function BrandSettingsPage({ params, searchParams }: PageProps) {
const { id } = use(params);
+ const { tab } = use(searchParams ?? NO_SEARCH);
+ // Brand facts with Quality's second phase (CE-047).
+ const factsOn = qualityPhase() >= 2;
+ const opened = tab && TABS.includes(tab) && (tab !== 'facts' || factsOn) ? tab : 'general';
const t = useTranslations('brands');
const router = useRouter();
const { brands, updateBrand: updateBrandStore, removeBrand } = useBrandStore();
@@ -87,12 +99,13 @@ export default function BrandSettingsPage({ params }: PageProps) {
return (
<div className="space-y-6">
- <Tabs defaultValue="general" className="space-y-4">
+ <Tabs defaultValue={opened} className="space-y-4">
<TabsList>
<TabsTrigger value="general">{t('settings.generalTab')}</TabsTrigger>
<TabsTrigger value="domains">{t('settings.domainsTab')}</TabsTrigger>
<TabsTrigger value="tracking">Tracking</TabsTrigger>
<TabsTrigger value="competitors">Competitors</TabsTrigger>
+ {factsOn && <TabsTrigger value="facts">{t('settings.facts.tab')}</TabsTrigger>}
<TabsTrigger
value="danger"
className="text-destructive data-[state=active]:text-destructive"
@@ -125,6 +138,12 @@ export default function BrandSettingsPage({ params }: PageProps) {
<CompetitorsTab brandId={brand.id} />
</TabsContent>
+ {factsOn && (
+ <TabsContent value="facts">
+ <BrandFactsTab brandId={brand.id} />
+ </TabsContent>
+ )}
+
<TabsContent value="danger">
<DangerTab
brand={brand}
diff --git a/web/src/lib/actions/brand-facts.test.ts b/web/src/lib/actions/brand-facts.test.ts
new file mode 100644
index 000000000..97cbd5888
--- /dev/null
+++ b/web/src/lib/actions/brand-facts.test.ts
@@ -0,0 +1,66 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * A brand's facts (Quality CE-047) through the API: read, read again,
+ * approved or rejected; errors returned, not thrown.
+ */
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
+ })),
+}));
+
+const { getBrandFacts, readBrandFactsAgain, setBrandFactStatus } = await import('./brand-facts');
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const FACT = '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29';
+let response: Response;
+const fetchMock = vi.fn<(input: string, init?: RequestInit) => Promise<Response>>(
+ async () => response,
+);
+
+beforeEach(() => {
+ response = new Response(JSON.stringify({ facts: [], pages: [], paused: true }), { status: 200 });
+ fetchMock.mockClear();
+ vi.stubGlobal('fetch', fetchMock);
+});
+afterEach(() => vi.unstubAllGlobals());
+
+describe('brand facts actions', () => {
+ it('reads the facts, filling what the API leaves out', async () => {
+ expect(await getBrandFacts(BRAND)).toEqual({
+ facts: [],
+ pages: [],
+ checkedAt: null,
+ recheckAt: null,
+ paused: true,
+ noDomain: false,
+ });
+ expect(fetchMock.mock.calls[0][0]).toMatch(/\/api\/brand-facts\?brandId=33333333-/);
+ });
+
+ it('reads the site again, and approves or rejects a fact', async () => {
+ await readBrandFactsAgain(BRAND);
+ expect(fetchMock.mock.calls[0]).toEqual([
+ expect.stringMatching(/\/api\/brand-facts\/fetch$/),
+ expect.objectContaining({ method: 'POST', body: JSON.stringify({ brandId: BRAND }) }),
+ ]);
+ response = new Response(JSON.stringify({ id: FACT, status: 'approved' }), { status: 200 });
+ expect(await setBrandFactStatus(FACT, 'approved')).toEqual({ id: FACT, status: 'approved' });
+ expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'PATCH' });
+ });
+
+ it('says off before phase 2, failed otherwise, and asks nothing for a malformed id', async () => {
+ response = new Response(JSON.stringify({ code: 'off' }), { status: 404 });
+ expect(await getBrandFacts(BRAND)).toEqual({ error: 'off' });
+ response = new Response('{}', { status: 500 });
+ expect(await getBrandFacts(BRAND)).toEqual({ error: 'failed' });
+ fetchMock.mockClear();
+ expect(await getBrandFacts('nope')).toEqual({ error: 'invalid' });
+ expect(await setBrandFactStatus(FACT, 'pending' as unknown as 'approved')).toEqual({
+ error: 'invalid',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/actions/brand-facts.ts b/web/src/lib/actions/brand-facts.ts
new file mode 100644
index 000000000..e0d26811d
--- /dev/null
+++ b/web/src/lib/actions/brand-facts.ts
@@ -0,0 +1,82 @@
+'use server';
+
+import { z } from 'zod';
+import { API_BASE_URL } from '@/config/api';
+import { createClient } from '@/lib/supabase/server';
+import type { BrandFactsRead, FactStatus } from '@/lib/content/brand-facts';
+
+/**
+ * A brand's facts (Quality CE-047), as the API reads them from the brand's
+ * own site and keeps them. Returned, not thrown: 'off' before Quality's
+ * phase 2 is live on the API, 'failed' otherwise.
+ */
+
+type FactsError = { error: 'invalid' | 'failed' | 'off' };
+
+const id = z.guid();
+
+async function call(path: string, init: RequestInit = {}): Promise<Response | FactsError> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'failed' };
+ try {
+ const res = await fetch(`${API_BASE_URL}/api/brand-facts${path}`, {
+ ...init,
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ });
+ if (res.status === 404) {
+ const body = (await res.json().catch(() => ({}))) as { code?: string };
+ if (body.code === 'off') return { error: 'off' };
+ }
+ if (!res.ok) return { error: 'failed' };
+ return res;
+ } catch (err) {
+ console.error('Failed to reach the brand facts:', err);
+ return { error: 'failed' };
+ }
+}
+
+const readOf = async (res: Response | FactsError): Promise<BrandFactsRead | FactsError> => {
+ if ('error' in res) return res;
+ const body = (await res.json().catch(() => null)) as Partial<BrandFactsRead> | null;
+ if (!body) return { error: 'failed' };
+ return {
+ facts: body.facts ?? [],
+ pages: body.pages ?? [],
+ checkedAt: body.checkedAt ?? null,
+ recheckAt: body.recheckAt ?? null,
+ paused: body.paused ?? false,
+ noDomain: body.noDomain ?? false,
+ };
+};
+
+/** The brand's facts: read from its site on the first ask, else as kept. */
+export async function getBrandFacts(brandId: string): Promise<BrandFactsRead | FactsError> {
+ if (!id.safeParse(brandId).success) return { error: 'invalid' };
+ return readOf(await call(`?brandId=${encodeURIComponent(brandId)}`));
+}
+
+/** Reads the brand's site again (not more than every few minutes; the API says when). */
+export async function readBrandFactsAgain(brandId: string): Promise<BrandFactsRead | FactsError> {
+ if (!id.safeParse(brandId).success) return { error: 'invalid' };
+ return readOf(await call('/fetch', { method: 'POST', body: JSON.stringify({ brandId }) }));
+}
+
+/** Approves or rejects a fact, as the member who does. */
+export async function setBrandFactStatus(
+ factId: string,
+ status: Exclude<FactStatus, 'pending'>,
+): Promise<{ id: string; status: FactStatus } | FactsError> {
+ if (!id.safeParse(factId).success || (status !== 'approved' && status !== 'rejected')) {
+ return { error: 'invalid' };
+ }
+ const res = await call(`/${factId}`, { method: 'PATCH', body: JSON.stringify({ status }) });
+ if ('error' in res) return res;
+ const body = (await res.json().catch(() => null)) as { id: string; status: FactStatus } | null;
+ return body ? { id: body.id, status: body.status } : { error: 'failed' };
+}
diff --git a/web/src/lib/content/brand-facts.test.ts b/web/src/lib/content/brand-facts.test.ts
new file mode 100644
index 000000000..2ea6c1b6c
--- /dev/null
+++ b/web/src/lib/content/brand-facts.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { brandFactsPath, factValueText } from './brand-facts';
+
+/** A brand fact's value as a person reads it (Quality CE-047). */
+describe('factValueText', () => {
+ it('writes a price in its currency, a trial’s days, a year, and a claim’s words', () => {
+ const price = (amount: number, currency: string) => ({
+ plan: 'Pro',
+ amount,
+ currency,
+ period: 'month' as const,
+ billed: null,
+ per: null,
+ });
+ expect(factValueText('price', price(49, 'USD'))).toBe('$49');
+ expect(factValueText('price', price(49.99, 'EUR'))).toBe('€49.99');
+ expect(factValueText('price', price(499, 'TRY'))).toMatch(/^TRY\s499$/);
+ expect(factValueText('trial', { days: 14 })).toBe('14');
+ expect(factValueText('founded', { year: 2015 })).toBe('2015');
+ expect(factValueText('claim', {}, 'SOC 2 certified')).toBe('SOC 2 certified');
+ expect(brandFactsPath('b1')).toBe('/dashboard/brands/b1/settings?tab=facts');
+ });
+});
diff --git a/web/src/lib/content/brand-facts.ts b/web/src/lib/content/brand-facts.ts
new file mode 100644
index 000000000..3700e398e
--- /dev/null
+++ b/web/src/lib/content/brand-facts.ts
@@ -0,0 +1,89 @@
+/**
+ * A brand's facts (Content Editor Quality spec §10, CE-047): its prices and
+ * plans, its trial, when it was founded and the claims it makes of itself,
+ * read from its own pricing, About and product pages by the API
+ * (brand-facts.js), each with its words on the page. A person approves each
+ * one in Brand settings › Brand facts; Trust compares a page with the
+ * approved ones that are still on the site.
+ */
+
+export const FACT_KINDS = ['price', 'trial', 'founded', 'claim'] as const;
+export type FactKind = (typeof FACT_KINDS)[number];
+export const FACT_SOURCES = ['pricing', 'about', 'product'] as const;
+export type FactSource = (typeof FACT_SOURCES)[number];
+export type FactStatus = 'pending' | 'approved' | 'rejected';
+export type FactPageStatus = 'ok' | 'blocked' | 'not_found' | 'failed' | 'missed';
+
+/** A price as the API reads it from its words. */
+export interface PriceValue {
+ plan: string;
+ amount: number;
+ currency: string;
+ period: 'month' | 'year' | 'once' | null;
+ billed: 'monthly' | 'annually' | null;
+ per: 'seat' | null;
+}
+
+export type FactValue = PriceValue | { days: number } | { year: number } | Record<string, never>;
+
+export interface BrandFact {
+ id: string;
+ kind: FactKind;
+ value: FactValue;
+ /** The page's own words, which hold it. */
+ quote: string;
+ sourceUrl: string;
+ sourceKind: FactSource;
+ status: FactStatus;
+ reviewedAt: string | null;
+ firstSeenAt: string;
+ /** No longer on the site: left out of the check. */
+ gone: boolean;
+ /** The approved fact a pending one would replace ("Was $49"). */
+ replaces: { id: string; value: FactValue } | null;
+}
+
+export interface BrandFactsRead {
+ facts: BrandFact[];
+ pages: { kind: FactSource; url: string | null; status: FactPageStatus; checkedAt: string }[];
+ checkedAt: string | null;
+ /** When the site may be read again. */
+ recheckAt: string | null;
+ /** The workspace's AI budget is spent: pages not read wait. */
+ paused: boolean;
+ /** The brand has no domain to read. */
+ noDomain: boolean;
+}
+
+/** Where a brand's facts are approved: Brand settings › Brand facts. */
+export const brandFactsPath = (brandId: string) =>
+ `/dashboard/brands/${brandId}/settings?tab=facts`;
+
+export const isPrice = (
+ fact: Pick<BrandFact, 'kind' | 'value'>,
+): fact is BrandFact & {
+ value: PriceValue;
+} => fact.kind === 'price';
+
+/**
+ * A fact's value as a person reads it: "$49", "€49.99", "14 days", "2015";
+ * a claim is its words. Amounts in the currency's own format, the app's
+ * English otherwise.
+ */
+export function factValueText(kind: FactKind, value: FactValue, quote = ''): string {
+ if (kind === 'price') {
+ const price = value as PriceValue;
+ try {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: price.currency,
+ maximumFractionDigits: Number.isInteger(price.amount) ? 0 : 2,
+ }).format(price.amount);
+ } catch {
+ return `${price.amount} ${price.currency}`;
+ }
+ }
+ if (kind === 'trial') return String((value as { days: number }).days);
+ if (kind === 'founded') return String((value as { year: number }).year);
+ return quote;
+}