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): detect a draft's page type and set the brand's site type (#1262)

Cihan82aac2ee66c8
diff --git a/supabase/migrations/00205_content_page_types.sql b/supabase/migrations/00205_content_page_types.sql
new file mode 100644
index 000000000..0e512d0c3
--- /dev/null
+++ b/supabase/migrations/00205_content_page_types.sql
@@ -0,0 +1,30 @@
+-- ============================================================================
+-- 00205: the brand's site type, and where a draft's page type comes from
+-- (Content Editor, CE-023)
+-- ============================================================================
+-- Page types depend on the kind of site (Content Editor spec v2 §4): a B2B
+-- SaaS site writes feature, comparison and pricing pages, a shop product and
+-- category pages, a B2C site destination and help pages.
+--
+-- * brands.site_type: b2b, ecommerce or b2c, set in the brand's settings.
+-- Null until someone chooses; until then the app guesses it from the
+-- industry and Shopping mode. Updated under the brands policies, as the
+-- industry is (admins and managers).
+-- * content_drafts.page_type_source: 'detected' while the app keeps
+-- page_type in step with the page (its URL, schema and title), 'user'
+-- once a person picks the type. A picked type is never detected over.
+-- New drafts start detected.
+
+alter table public.brands
+ add column if not exists site_type text
+ check (site_type in ('b2b', 'ecommerce', 'b2c'));
+
+comment on column public.brands.site_type is
+ 'Content Editor (CE-023): b2b, ecommerce or b2c; sets the page types the editor offers. Null = guessed from industry and shopping_mode_enabled.';
+
+alter table public.content_drafts
+ add column if not exists page_type_source text not null default 'detected'
+ check (page_type_source in ('detected', 'user'));
+
+comment on column public.content_drafts.page_type_source is
+ 'Content Editor (CE-023): detected = page_type follows the page as it changes; user = a person picked it.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index d59ac0150..8b0024f9f 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -28791,3 +28791,37 @@ create policy "content_drafts: member update"
)
);
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00205_content_page_types.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00205: the brand's site type, and where a draft's page type comes from
+-- (Content Editor, CE-023)
+-- ============================================================================
+-- Page types depend on the kind of site (Content Editor spec v2 §4): a B2B
+-- SaaS site writes feature, comparison and pricing pages, a shop product and
+-- category pages, a B2C site destination and help pages.
+--
+-- * brands.site_type: b2b, ecommerce or b2c, set in the brand's settings.
+-- Null until someone chooses; until then the app guesses it from the
+-- industry and Shopping mode. Updated under the brands policies, as the
+-- industry is (admins and managers).
+-- * content_drafts.page_type_source: 'detected' while the app keeps
+-- page_type in step with the page (its URL, schema and title), 'user'
+-- once a person picks the type. A picked type is never detected over.
+-- New drafts start detected.
+
+alter table public.brands
+ add column if not exists site_type text
+ check (site_type in ('b2b', 'ecommerce', 'b2c'));
+
+comment on column public.brands.site_type is
+ 'Content Editor (CE-023): b2b, ecommerce or b2c; sets the page types the editor offers. Null = guessed from industry and shopping_mode_enabled.';
+
+alter table public.content_drafts
+ add column if not exists page_type_source text not null default 'detected'
+ check (page_type_source in ('detected', 'user'));
+
+comment on column public.content_drafts.page_type_source is
+ 'Content Editor (CE-023): detected = page_type follows the page as it changes; user = a person picked it.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index a819ec04d..a2ffda2ce 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3110,6 +3110,15 @@
"back": "Back to the Library",
"untitled": "Untitled",
"newPage": "New page",
+ "pageType": {
+ "title": "{site} page types",
+ "none": "Set page type",
+ "change": "Page type: {type}. Change it",
+ "detectedHint": "Detected from the page as you write. Pick a type to keep it.",
+ "pickedHint": "You picked this type, so changes to the page don't change it.",
+ "siteSettings": "Change the site type in brand settings",
+ "failed": "Couldn't change the page type. Try again."
+ },
"placeholder": "Start with the page's H1, then write…",
"documentLabel": "Page content",
"jsonLd": "Schema · {type} (JSON-LD)",
@@ -5258,6 +5267,12 @@
"domainPlaceholder": "e.g. example.com",
"countryPlaceholder": "e.g. US, TR (optional)",
"industryPlaceholder": "Select an industry",
+ "siteType": "Site type",
+ "siteTypes": {
+ "b2b": "B2B SaaS",
+ "ecommerce": "E-commerce",
+ "b2c": "B2C"
+ },
"descriptionPlaceholder": "Short description of this brand...",
"domainCount": "{count, plural, one {# domain} other {# domains}}",
"wizard": {
@@ -5287,6 +5302,8 @@
"stateOptional": "State (optional)",
"nationwide": "Nationwide (no state)",
"stateHint": "Localizes AI answers to this state from the next tracking run onward.",
+ "siteTypeHint": "Sets the page types the Content Editor offers: feature and comparison pages for B2B SaaS, product and category pages for e-commerce, destination and help pages for B2C.",
+ "siteTypeGuessed": "Guessed from the industry and Shopping mode until you pick one.",
"deleteWarning": "This action cannot be undone. All data for this brand (insights, content, competitors) will be permanently deleted.",
"confirmDelete": "Type the brand name to confirm:",
"deleteConfirmPlaceholder": "Brand name",
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 5cb62e6f3..6c12db576 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
@@ -67,11 +67,12 @@ vi.mock('@/hooks/use-feature-gate', () => ({
}));
const setBrandShoppingMode = vi.hoisted(() => vi.fn());
+const updateBrand = vi.hoisted(() => vi.fn());
vi.mock('@/lib/actions/brand', () => ({
deleteBrand: vi.fn(),
setBrandActive: vi.fn(),
setBrandShoppingMode,
- updateBrand: vi.fn(),
+ updateBrand,
}));
vi.mock('@/lib/actions/brand-domain', () => ({
@@ -99,6 +100,9 @@ import BrandSettingsPage from './page';
afterEach(() => {
brand.state = 'CA';
+ brand.industry = 'Technology';
+ brand.siteType = undefined;
+ updateBrand.mockReset();
Object.assign(role, { canAdmin: true, canManage: true });
setBrandShoppingMode.mockReset();
document.body.replaceChildren();
@@ -124,6 +128,7 @@ describe('brand settings location selects', () => {
expect(values.map((value) => value.textContent)).toEqual([
'Technology',
+ 'siteTypes.b2b',
'United States',
'California',
]);
@@ -151,12 +156,56 @@ describe('brand settings location selects', () => {
const values = Array.from(container.querySelectorAll('[data-slot="select-value"]'));
- expect(values[2]?.textContent).toBe('Translated Nationwide');
+ expect(values[3]?.textContent).toBe('Translated Nationwide');
await act(async () => root.unmount());
});
});
+describe('brand settings site type', () => {
+ async function render() {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(
+ <Suspense>
+ <BrandSettingsPage params={Promise.resolve({ id: brand.id })} />
+ </Suspense>,
+ );
+ });
+ const siteType = container.querySelector('#site-type [data-slot="select-value"]');
+ return { container, root, siteType };
+ }
+
+ it('shows the guess from the industry until one is picked, and saves no guess', async () => {
+ brand.industry = 'Travel & Hospitality';
+ updateBrand.mockResolvedValue({ ...brand });
+ const { container, root, siteType } = await render();
+ expect(siteType?.textContent).toBe('siteTypes.b2c');
+ expect(container.textContent).toContain('settings.siteTypeGuessed');
+
+ const save = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'settings.saveChanges',
+ )!;
+ await act(async () => save.click());
+ expect(updateBrand).toHaveBeenCalledWith(
+ brand.id,
+ expect.not.objectContaining({ siteType: expect.anything() }),
+ );
+ await act(async () => root.unmount());
+ });
+
+ it('shows the site type the brand chose, with no word of a guess', async () => {
+ brand.siteType = 'ecommerce';
+ const { container, root, siteType } = await render();
+ expect(siteType?.textContent).toBe('siteTypes.ecommerce');
+ expect(container.textContent).toContain('settings.siteTypeHint');
+ expect(container.textContent).not.toContain('settings.siteTypeGuessed');
+ await act(async () => root.unmount());
+ });
+});
+
describe('brand settings Shopping mode', () => {
async function render() {
const container = document.createElement('div');
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 83406ade9..9044a7e5b 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
@@ -57,6 +57,7 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { getPublicApiBaseUrl } from '@/config/api';
+import { SITE_TYPES, guessSiteType, isSiteType, type SiteType } from '@/lib/content/page-types';
interface PageProps {
params: Promise<{ id: string }>;
@@ -159,8 +160,17 @@ function GeneralTab({
const [description, setDescription] = useState(brand.description ?? '');
const [region, setRegion] = useState(brand.region ?? 'US');
const [usState, setUsState] = useState(brand.state ?? '');
+ // Null until someone picks one: the guess follows the industry meanwhile.
+ const [siteType, setSiteType] = useState<SiteType | null>(
+ isSiteType(brand.siteType) ? brand.siteType : null,
+ );
const [isSaving, setIsSaving] = useState(false);
const stateItems = [{ value: 'nationwide', label: t('settings.nationwide') }, ...US_STATE_ITEMS];
+ const siteTypeItems = SITE_TYPES.map((value) => ({ value, label: t(`siteTypes.${value}`) }));
+ const guessedSiteType = guessSiteType({
+ industry,
+ shoppingModeEnabled: brand.shoppingModeEnabled,
+ });
const handleSave = async () => {
if (!name.trim()) return;
@@ -175,6 +185,7 @@ function GeneralTab({
description: description || null,
region,
state: region === 'US' ? usState || null : null,
+ ...(siteType ? { siteType } : {}),
});
onUpdate({
name: updated.name,
@@ -184,6 +195,7 @@ function GeneralTab({
description: updated.description,
region: updated.region,
state: updated.state,
+ siteType: updated.siteType,
updatedAt: updated.updatedAt,
});
toast.success(t('settings.saved'));
@@ -246,6 +258,32 @@ function GeneralTab({
</Select>
</div>
+ <div className="space-y-2">
+ <Label htmlFor="site-type">{t('siteType')}</Label>
+ <Select
+ items={siteTypeItems}
+ value={siteType ?? guessedSiteType}
+ onValueChange={(v) => {
+ if (isSiteType(v)) setSiteType(v);
+ }}
+ >
+ <SelectTrigger id="site-type">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {siteTypeItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {t('settings.siteTypeHint')}
+ {siteType === null && ` ${t('settings.siteTypeGuessed')}`}
+ </p>
+ </div>
+
<div className="space-y-2">
<Label htmlFor="description">{t('description_field')}</Label>
<Textarea
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index 357b53725..9a1ccef2c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
@@ -11,12 +11,11 @@ import Image from '@tiptap/extension-image';
import { CharacterCount, Placeholder } from '@tiptap/extensions';
import { ArrowLeft, Check, Copy, Loader2 } from 'lucide-react';
import { Link } from '@/i18n/navigation';
-import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';
-import { markContentDraftReady } from '@/lib/actions/content-drafts';
-import { CONTENT_LIBRARY_PATH, isPageType, type ContentDraft } from '@/lib/content/drafts';
+import { markContentDraftReady, setContentDraftPageType } from '@/lib/actions/content-drafts';
+import { CONTENT_LIBRARY_PATH, type ContentDraft, type PageType } from '@/lib/content/drafts';
import {
cleanHtml,
formatHtmlSource,
@@ -25,9 +24,11 @@ import {
} from '@/lib/content/clean-html';
import { draftTitleFromDoc, lengthTarget, safeLinkHref } from '@/lib/content/editor';
import { JsonLd } from '@/lib/content/json-ld-node';
+import { detectPageType } from '@/lib/content/page-types';
import { cn } from '@/lib/utils';
import { DropOverlay, useAttachments } from './_attach';
import { HtmlBlock, copyToClipboard } from './_html-block';
+import { PageTypeMenu } from './_page-type-menu';
import { EditorToolbar } from './_toolbar';
import { useDraftAutosave, type SaveState } from './_use-autosave';
@@ -58,15 +59,21 @@ const DOCUMENT_CLASS = cn(
* Shift + V pastes plain text. The HTML view (CE-020) shows the page's
* source, and cleans it the same way when it switches back. HTML blocks
* carry code as written, as many as the page needs, and Copy HTML puts the
- * whole page, or one block, on the clipboard.
+ * whole page, or one block, on the clipboard. The page type follows the page
+ * as it is written until the person picks one (CE-023).
*/
export function DraftEditor({ draft }: { draft: ContentDraft }) {
const t = useTranslations('contentEditor.editor');
- const tTypes = useTranslations('contentEditor.pageTypes');
const autosave = useDraftAutosave(draft.id, draft);
const [title, setTitle] = useState(draft.title);
const [status, setStatus] = useState(draft.status);
const [marking, setMarking] = useState(false);
+ // A picked page type, or the one the page shows as it is written.
+ const [picked, setPicked] = useState(draft.pageTypeSource === 'user' ? draft.pageType : null);
+ const [detectedType, setDetectedType] = useState(() =>
+ detectPageType({ title: draft.title, html: draft.bodyHtml }, draft.siteType),
+ );
+ const pageType = picked ?? detectedType;
// The HTML view's text while it is open; null in the visual editor.
const [htmlSource, setHtmlSource] = useState<string | null>(null);
const [htmlEdited, setHtmlEdited] = useState(false);
@@ -144,8 +151,10 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
},
onUpdate: ({ editor: e }) => {
const next = draftTitleFromDoc(e.getJSON());
+ const bodyHtml = e.getHTML();
setTitle(next);
- autosave.schedule({ title: next, bodyHtml: e.getHTML() });
+ setDetectedType(detectPageType({ title: next, html: bodyHtml }, draft.siteType));
+ autosave.schedule({ title: next, bodyHtml });
},
});
@@ -249,10 +258,18 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
}
};
- const typeLabel = isPageType(draft.pageType) ? tTypes(draft.pageType) : null;
- const pageTag = [typeLabel, draft.method === 'create' ? t('newPage') : null]
- .filter(Boolean)
- .join(' · ');
+ const pickPageType = async (type: PageType) => {
+ if (type === picked) return;
+ const before = picked;
+ setPicked(type);
+ try {
+ await setContentDraftPageType(draft.id, type);
+ } catch (err) {
+ console.error('Failed to set the page type:', err);
+ setPicked(before);
+ toast.error(t('pageType.failed'));
+ }
+ };
return (
<div className="flex min-h-0 flex-1 flex-col">
@@ -271,11 +288,14 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
{title.trim() || t('untitled')}
</h1>
<div className="hidden shrink-0 items-center gap-2 lg:flex">
- {pageTag && (
- <Badge variant="outline" className="font-normal">
- {pageTag}
- </Badge>
- )}
+ <PageTypeMenu
+ brandId={draft.brandId}
+ siteType={draft.siteType}
+ pageType={pageType}
+ detected={picked === null}
+ isNew={draft.method === 'create'}
+ onPick={(type) => void pickPageType(type)}
+ />
<DraftMethodBadge method={draft.method} />
</div>
<span className="shrink-0">
@@ -311,7 +331,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
{editor && (
<EditorToolbar
editor={editor}
- target={lengthTarget(draft.pageType)}
+ target={lengthTarget(pageType)}
htmlView={htmlSource !== null}
onToggleHtml={htmlSource === null ? openHtmlView : applyHtmlView}
onAttach={attachments.open}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsx
new file mode 100644
index 000000000..7c3e90864
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsx
@@ -0,0 +1,97 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ChevronDown, Settings } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { badgeVariants } from '@/components/ui/badge';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { isPageType, type PageType } from '@/lib/content/drafts';
+import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';
+import { cn } from '@/lib/utils';
+
+/**
+ * The draft's page type in the editor's header (CE-023): detected from the
+ * page until the person picks one from the types their kind of site writes.
+ * A type from another kind of site, picked before the site type changed,
+ * stays on the list so the menu still shows it.
+ */
+export function PageTypeMenu({
+ brandId,
+ siteType,
+ pageType,
+ detected,
+ isNew,
+ onPick,
+}: {
+ brandId: string;
+ siteType: SiteType;
+ pageType: string | null;
+ /** Whether the type is detected (not picked). */
+ detected: boolean;
+ /** A new page: the tag says so after the type. */
+ isNew: boolean;
+ onPick: (type: PageType) => void;
+}) {
+ const t = useTranslations('contentEditor.editor');
+ const tTypes = useTranslations('contentEditor.pageTypes');
+ const tSites = useTranslations('brands.siteTypes');
+ const current = isPageType(pageType) ? pageType : null;
+ const offered = SITE_PAGE_TYPES[siteType];
+ const types = current && !offered.includes(current) ? [...offered, current] : offered;
+ const label = current ? tTypes(current) : t('pageType.none');
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={t('pageType.change', { type: label })}
+ title={detected ? t('pageType.detectedHint') : undefined}
+ className={cn(
+ badgeVariants({ variant: 'outline' }),
+ 'cursor-pointer gap-1 font-normal hover:bg-muted',
+ !current && 'border-dashed text-muted-foreground',
+ )}
+ >
+ {[label, isNew ? t('newPage') : null].filter(Boolean).join(' · ')}
+ <ChevronDown className="h-3 w-3 opacity-60" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-60">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t('pageType.title', { site: tSites(siteType) })}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={current ?? ''}
+ onValueChange={(value) => {
+ if (isPageType(value)) onPick(value);
+ }}
+ >
+ {types.map((type) => (
+ <DropdownMenuRadioItem key={type} value={type} closeOnClick>
+ {tTypes(type)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <p className="px-1.5 py-1 text-xs text-muted-foreground">
+ {detected ? t('pageType.detectedHint') : t('pageType.pickedHint')}
+ </p>
+ <DropdownMenuItem
+ render={<Link href={`/dashboard/brands/${brandId}/settings`} />}
+ className="text-xs"
+ >
+ <Settings className="h-3.5 w-3.5" />
+ {t('pageType.siteSettings')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index 895add911..45ed79784 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
@@ -9,10 +9,12 @@ import ContentEditorPage from './page';
const getContentDraft = vi.fn();
const markContentDraftReady = vi.fn();
const saveContentDraft = vi.fn();
+const setContentDraftPageType = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
getContentDraft: (...args: unknown[]) => getContentDraft(...args),
markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),
saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),
+ setContentDraftPageType: (...args: unknown[]) => setContentDraftPageType(...args),
}));
vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));
vi.mock('@/i18n/navigation', () => ({
@@ -83,6 +85,8 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({
brandId: 'b1',
title: 'Pipeline forecasting',
pageType: 'feature_page',
+ pageTypeSource: 'user',
+ siteType: 'b2b',
method: 'optimize',
status: 'in_review',
bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',
@@ -117,6 +121,7 @@ beforeEach(() => {
root = createRoot(container);
getContentDraft.mockReset();
markContentDraftReady.mockReset();
+ setContentDraftPageType.mockReset().mockResolvedValue(undefined);
saveContentDraft.mockReset().mockResolvedValue({ updatedAt: '2026-10-20T10:00:00Z' });
brandState.activeBrandId = 'b1';
brandState.setActiveBrand.mockReset();
@@ -174,6 +179,109 @@ describe('the content editor', () => {
);
});
+ describe('the page type', () => {
+ const typeMenu = () =>
+ container.querySelector<HTMLButtonElement>('header button[aria-label^="Page type:"]')!;
+ /** Opens the page type menu and returns its types. */
+ async function openTypes() {
+ const trigger = typeMenu();
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ return [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];
+ }
+ /** Replaces the page through the HTML view. */
+ async function rewrite(html: string) {
+ await act(async () => button('Edit as HTML')!.click());
+ const source = container.querySelector('textarea')!;
+ const setValue = Object.getOwnPropertyDescriptor(
+ HTMLTextAreaElement.prototype,
+ 'value',
+ )!.set!;
+ await act(async () => {
+ setValue.call(source, html);
+ source.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => button('Back to visual')!.click());
+ }
+
+ it('follows the page while it is detected, and keeps the type the person picks', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ title: 'Northwind vs HubSpot',
+ bodyHtml: '<h1>Northwind vs HubSpot</h1>',
+ pageType: 'comparison',
+ pageTypeSource: 'detected',
+ }),
+ );
+ await renderPage();
+ expect(typeMenu().textContent).toBe('Comparison');
+ expect(typeMenu().title).toBe('Detected from the page as you write. Pick a type to keep it.');
+
+ await rewrite('<h1>How to clean CRM data</h1>');
+ expect(typeMenu().textContent).toBe('Guide');
+
+ const types = await openTypes();
+ expect(types.map((item) => item.textContent)).toEqual([
+ 'Feature page',
+ 'Solution page',
+ 'Comparison',
+ 'Integration',
+ 'Pricing',
+ 'Guide',
+ 'Blog post',
+ 'Docs / FAQ',
+ ]);
+ expect(document.body.textContent).toContain('B2B SaaS page types');
+ await act(async () => types.find((item) => item.textContent === 'Pricing')!.click());
+ expect(setContentDraftPageType).toHaveBeenCalledWith('d1', 'pricing');
+ expect(typeMenu().textContent).toBe('Pricing');
+ expect(typeMenu().title).toBe('');
+
+ // Picked: the page no longer changes it.
+ await rewrite('<h1>Northwind vs HubSpot</h1>');
+ expect(typeMenu().textContent).toBe('Pricing');
+ });
+
+ it('offers a shop its own types, and keeps a type from another kind of site listed', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({ siteType: 'ecommerce', pageType: 'feature_page', method: 'create' }),
+ );
+ await renderPage();
+ expect(typeMenu().textContent).toBe('Feature page · New page');
+ const types = await openTypes();
+ expect(types.map((item) => item.textContent)).toEqual([
+ 'Product page',
+ 'Category page',
+ 'Buying guide',
+ 'Best-of list',
+ 'Policy',
+ 'Blog post',
+ 'Feature page',
+ ]);
+ });
+
+ it('puts the type back when picking it fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ setContentDraftPageType.mockRejectedValue(new Error('not_found'));
+ getContentDraft.mockResolvedValue(draft({ siteType: 'ecommerce', pageType: 'product_page' }));
+ await renderPage();
+ const types = await openTypes();
+ await act(async () => types.find((item) => item.textContent === 'Policy')!.click());
+ expect(toast.error).toHaveBeenCalledWith("Couldn't change the page type. Try again.");
+ expect(typeMenu().textContent).toBe('Product page');
+ });
+
+ it('says when no type is detected yet', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({ pageType: null, pageTypeSource: 'detected', method: 'create' }),
+ );
+ await renderPage();
+ expect(typeMenu().textContent).toBe('Set page type · New page');
+ });
+ });
+
it('marks the draft ready once', async () => {
getContentDraft.mockResolvedValue(draft());
markContentDraftReady.mockResolvedValue('ready');
diff --git a/web/src/lib/actions/brand.test.ts b/web/src/lib/actions/brand.test.ts
index b7649f03d..3faa227d4 100644
--- a/web/src/lib/actions/brand.test.ts
+++ b/web/src/lib/actions/brand.test.ts
@@ -9,6 +9,7 @@ import { PLANS, type Plan } from '@/config/plans';
let brandCount = 0;
let inserted: unknown[] = [];
+let updates: Record<string, unknown>[] = [];
let plan: Plan;
vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
@@ -21,6 +22,20 @@ vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
from: (table: string) => ({
select: () => ({ eq: async () => ({ count: brandCount, error: null }) }),
+ update: (payload: Record<string, unknown>) => {
+ updates.push(payload);
+ const row = {
+ id: 'b1',
+ organization_id: 'org-1',
+ name: 'Acme',
+ slug: 'acme',
+ site_type: payload.site_type ?? null,
+ brand_domains: [],
+ };
+ return {
+ eq: () => ({ select: () => ({ single: async () => ({ data: row, error: null }) }) }),
+ };
+ },
insert: (row: unknown) => {
inserted.push({ table, row });
return {
@@ -36,7 +51,7 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
-const { createBrand } = await import('./brand');
+const { createBrand, updateBrand } = await import('./brand');
const input = { organizationId: 'org-1', name: 'Acme', domains: [] };
const capped = (maxBrands: number): Plan => ({
@@ -72,3 +87,22 @@ describe('createBrand plan limit', () => {
expect(inserted).toHaveLength(1);
});
});
+
+describe('updateBrand site type (Content Editor CE-023)', () => {
+ beforeEach(() => {
+ updates = [];
+ });
+
+ it('saves the site type picked in the settings', async () => {
+ const brand = await updateBrand('b1', { siteType: 'ecommerce' });
+ expect(updates).toEqual([{ site_type: 'ecommerce' }]);
+ expect(brand.siteType).toBe('ecommerce');
+ });
+
+ it('refuses a site type it doesn’t know, before writing', async () => {
+ await expect(
+ updateBrand('b1', { siteType: 'agency' as Parameters<typeof updateBrand>[1]['siteType'] }),
+ ).rejects.toThrow('Unknown site type');
+ expect(updates).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.ts
index 983586546..40791ebce 100644
--- a/web/src/lib/actions/brand.ts
+++ b/web/src/lib/actions/brand.ts
@@ -8,6 +8,7 @@ import { slugify } from '@/lib/slug';
import { API_BASE_URL } from '@/config/api';
import type { Brand, BrandDomain, Industry } from '@/types';
import { MAX_PINNED_COMPETITORS } from '@/lib/insights-trend';
+import { isSiteType, type SiteType } from '@/lib/content/page-types';
function mapDomainRow(d: Record<string, unknown>): BrandDomain {
return {
@@ -33,6 +34,7 @@ function mapBrandRow(brand: Record<string, unknown>, domains: Record<string, unk
language: (brand.language as string | null) ?? undefined,
trackingCode: (brand.tracking_code as string | null) ?? undefined,
shoppingModeEnabled: !!brand.shopping_mode_enabled,
+ siteType: (brand.site_type as string | null) ?? undefined,
isActive: brand.is_active === undefined ? true : !!brand.is_active,
domains: domains.map(mapDomainRow),
createdAt: brand.created_at as string,
@@ -162,6 +164,8 @@ interface UpdateBrandInput {
region?: string;
state?: string | null;
language?: string;
+ /** The kind of site, for the Content Editor's page types (CE-023). */
+ siteType?: SiteType | null;
}
export async function updateBrand(id: string, updates: UpdateBrandInput): Promise<Brand> {
@@ -180,6 +184,12 @@ export async function updateBrand(id: string, updates: UpdateBrandInput): Promis
// A region change away from US invalidates any stored state.
if (updates.region !== undefined && updates.region !== 'US') payload.state = null;
if (updates.language !== undefined) payload.language = updates.language;
+ if ('siteType' in updates) {
+ if (updates.siteType != null && !isSiteType(updates.siteType)) {
+ throw new Error('Unknown site type');
+ }
+ payload.site_type = updates.siteType ?? null;
+ }
const { data, error } = await supabase
.from('brands')
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index 29ff33d87..827c2fe32 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -46,8 +46,13 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
-const { createContentDraft, getContentDraft, markContentDraftReady, saveContentDraft } =
- await import('./content-drafts');
+const {
+ createContentDraft,
+ getContentDraft,
+ markContentDraftReady,
+ saveContentDraft,
+ setContentDraftPageType,
+} = await import('./content-drafts');
const { bodyHash } = await import('@/lib/content/editor');
beforeEach(() => {
@@ -141,6 +146,82 @@ describe('saveContentDraft', () => {
});
});
+describe('the page type on save (CE-023)', () => {
+ const shop = { site_type: null, industry: 'E-commerce & Retail', shopping_mode_enabled: false };
+ const base = { updatedAt: '2026-10-20T14:00:00Z', bodyHash: 'a'.repeat(64) };
+
+ it('detects it again from what was saved, writing it only while it is still detected', async () => {
+ updates = [
+ {
+ updated_at: '2026-10-20T15:00:00Z',
+ page_type: null,
+ page_type_source: 'detected',
+ brands: shop,
+ },
+ { updated_at: '2026-10-20T15:00:01Z' },
+ ];
+ const result = await saveContentDraft(DRAFT, {
+ title: 'The 7 best ultralight tents',
+ bodyHtml: '<h1>The 7 best ultralight tents</h1>',
+ base,
+ });
+ // The type's write makes the version the editor goes on from.
+ expect(result).toMatchObject({ ok: true, updatedAt: '2026-10-20T15:00:01Z' });
+ expect(calls[1]).toMatchObject({
+ op: 'update',
+ value: { page_type: 'best_of' },
+ filters: [
+ ['eq', 'id', DRAFT],
+ ['eq', 'page_type_source', 'detected'],
+ ],
+ });
+ });
+
+ it('writes nothing more when the type is unchanged, or the person picked it', async () => {
+ updated = {
+ updated_at: '2026-10-20T15:00:00Z',
+ page_type: 'best_of',
+ page_type_source: 'detected',
+ brands: shop,
+ };
+ await saveContentDraft(DRAFT, {
+ title: 'The 7 best tents',
+ bodyHtml: '<h1>The 7 best tents</h1>',
+ base,
+ });
+ updated = { ...updated, page_type: 'policy', page_type_source: 'user' };
+ await saveContentDraft(DRAFT, {
+ title: 'The 7 best tents',
+ bodyHtml: '<h1>The 7 best tents</h1>',
+ base,
+ });
+ expect(calls.map((call) => call.op)).toEqual(['update', 'update']);
+ });
+});
+
+describe('setContentDraftPageType', () => {
+ it('keeps the picked type from now on', async () => {
+ updated = { id: DRAFT };
+ await setContentDraftPageType(DRAFT, 'guide');
+ expect(calls[0]).toMatchObject({
+ op: 'update',
+ value: { page_type: 'guide', page_type_source: 'user' },
+ filters: [['eq', 'id', DRAFT]],
+ });
+ });
+
+ it('refuses a type it doesn’t know, and says so when the draft isn’t the member’s', async () => {
+ await expect(
+ setContentDraftPageType(
+ DRAFT,
+ 'landing_page' as Parameters<typeof setContentDraftPageType>[1],
+ ),
+ ).rejects.toThrow('invalid');
+ expect(calls).toEqual([]);
+ await expect(setContentDraftPageType(DRAFT, 'guide')).rejects.toThrow('not_found');
+ });
+});
+
describe('markContentDraftReady', () => {
it('moves a draft or an agent draft in review to ready', async () => {
updated = { status: 'ready' };
@@ -176,6 +257,35 @@ describe('markContentDraftReady', () => {
});
describe('getContentDraft and createContentDraft', () => {
+ it('opens a draft with its brand’s site type, chosen or guessed', async () => {
+ const base = {
+ id: DRAFT,
+ brand_id: 'b1',
+ title: '',
+ page_type: 'guide',
+ page_type_source: 'user',
+ method: 'create',
+ status: 'draft',
+ body_html: '',
+ author: 'user',
+ updated_at: '2026-10-20T15:00:00Z',
+ };
+ row = {
+ ...base,
+ brands: { site_type: 'b2c', industry: 'Technology', shopping_mode_enabled: true },
+ };
+ await expect(getContentDraft(DRAFT)).resolves.toMatchObject({
+ pageType: 'guide',
+ pageTypeSource: 'user',
+ siteType: 'b2c',
+ });
+ row = {
+ ...base,
+ brands: { site_type: null, industry: 'Technology', shopping_mode_enabled: true },
+ };
+ await expect(getContentDraft(DRAFT)).resolves.toMatchObject({ siteType: 'ecommerce' });
+ });
+
it('reads nothing for a malformed id', async () => {
await expect(getContentDraft('../etc')).resolves.toBeNull();
expect(calls).toEqual([]);
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 206efd7b2..855e97572 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -5,10 +5,12 @@ import { createClient } from '@/lib/supabase/server';
import { readAssignees } from '@/lib/action-center/assignees';
import {
DRAFT_STATUSES,
+ PAGE_TYPES,
type ContentDraft,
type ContentDraftListItem,
type DraftMethod,
type DraftStatus,
+ type PageType,
} from '@/lib/content/drafts';
import {
MAX_BODY_HTML_LENGTH,
@@ -16,6 +18,7 @@ import {
bodyHash,
type SaveDraftResult,
} from '@/lib/content/editor';
+import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-types';
import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';
/**
@@ -73,13 +76,32 @@ function draftStatus(value: string): DraftStatus {
const draftId = z.guid();
+/** What a draft row embeds of its brand: enough to know its site type. */
+const BRAND_SITE = 'brands(site_type, industry, shopping_mode_enabled)';
+
+function brandSiteType(
+ brand: {
+ site_type: string | null;
+ industry: string | null;
+ shopping_mode_enabled: boolean;
+ } | null,
+): SiteType {
+ return siteTypeOf({
+ siteType: brand?.site_type,
+ industry: brand?.industry,
+ shoppingModeEnabled: brand?.shopping_mode_enabled,
+ });
+}
+
/** One draft for the editor (CE-004), or null when it isn't the member's to read. */
export async function getContentDraft(id: string): Promise<ContentDraft | null> {
if (!draftId.safeParse(id).success) return null;
const supabase = await createClient();
const { data, error } = await supabase
.from('content_drafts')
- .select('id, brand_id, title, page_type, method, status, body_html, author, updated_at')
+ .select(
+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, updated_at, ${BRAND_SITE}`,
+ )
.eq('id', id)
.maybeSingle();
if (error) throw new Error(error.message);
@@ -89,6 +111,8 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
brandId: data.brand_id,
title: data.title,
pageType: data.page_type,
+ pageTypeSource: data.page_type_source === 'user' ? 'user' : 'detected',
+ siteType: brandSiteType(data.brands),
method: data.method as DraftMethod,
status: draftStatus(data.status),
bodyHtml: data.body_html,
@@ -138,6 +162,11 @@ const SAVE_ATTEMPTS = 3;
* another page means someone else changed it (another tab, a teammate, the
* Content Agent), and nothing is overwritten. A save RLS refused, or of a
* draft that no longer exists, comes back not_found rather than saved.
+ *
+ * Until a person picks the page type, it follows the page (CE-023): detected
+ * again from what was saved, and written only while it is still detected, so
+ * a pick made meanwhile stays. That second write makes the version the
+ * editor goes on from.
*/
export async function saveContentDraft(
id: string,
@@ -158,10 +187,31 @@ export async function saveContentDraft(
.update({ title, body_html: bodyHtml })
.eq('id', id)
.eq('updated_at', expected)
- .select('updated_at')
+ .select(`updated_at, page_type, page_type_source, ${BRAND_SITE}`)
.maybeSingle();
if (error) throw new Error(error.message);
- if (data) return { ok: true, updatedAt: data.updated_at, bodyHash: await bodyHash(bodyHtml) };
+ if (data) {
+ let updatedAt: string = data.updated_at;
+ if (data.page_type_source === 'detected') {
+ const detected = detectPageType({ title, html: bodyHtml }, brandSiteType(data.brands));
+ if (detected !== data.page_type) {
+ const { data: typed, error: typeError } = await supabase
+ .from('content_drafts')
+ .update({ page_type: detected })
+ .eq('id', id)
+ .eq('page_type_source', 'detected')
+ .select('updated_at')
+ .maybeSingle();
+ // The page is saved; its type catches up on the next save.
+ if (typeError) {
+ console.error('Failed to update the detected page type:', typeError.message);
+ } else if (typed) {
+ updatedAt = typed.updated_at;
+ }
+ }
+ }
+ return { ok: true, updatedAt, bodyHash: await bodyHash(bodyHtml) };
+ }
const { data: current, error: readError } = await supabase
.from('content_drafts')
@@ -178,6 +228,27 @@ export async function saveContentDraft(
return { ok: false, reason: 'conflict' };
}
+const pageTypeInput = z.enum(PAGE_TYPES);
+
+/**
+ * A page type the person picked (CE-023): from now on the draft keeps it,
+ * whatever the page says. Throws 'not_found' when no row changed.
+ */
+export async function setContentDraftPageType(id: string, pageType: PageType): Promise<void> {
+ if (!draftId.safeParse(id).success || !pageTypeInput.safeParse(pageType).success) {
+ throw new Error('invalid');
+ }
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .update({ page_type: pageType, page_type_source: 'user' })
+ .eq('id', id)
+ .select('id')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+}
+
/**
* Mark ready: a draft, or an agent's draft in review, is ready to publish.
* Ansvisor never publishes it; the person does (CE-013 records the URL).
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index 6b281cfb4..8d37024e7 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -4,6 +4,8 @@
* content_drafts row (migration 00204).
*/
+import type { SiteType } from './page-types';
+
/** Draft → In review (an agent's draft waiting for a person) → Ready → Published. */
export const DRAFT_STATUSES = ['draft', 'in_review', 'ready', 'published'] as const;
export type DraftStatus = (typeof DRAFT_STATUSES)[number];
@@ -12,9 +14,9 @@ export type DraftStatus = (typeof DRAFT_STATUSES)[number];
export type DraftMethod = 'create' | 'optimize';
/**
- * The page types a draft can be, across brand types (B2B, e-commerce, B2C).
- * Stored as these keys (content_drafts.page_type); named in en.json under
- * content.pageTypes.
+ * The page types a draft can be, across brand types (B2B, e-commerce, B2C;
+ * SITE_PAGE_TYPES says which). Stored as these keys (content_drafts.page_type);
+ * named in en.json under contentEditor.pageTypes.
*/
export const PAGE_TYPES = [
'feature_page',
@@ -76,12 +78,21 @@ export interface ContentDraftListItem {
updatedAt: string;
}
+/**
+ * Where a draft's page type comes from (CE-023): detected from the page, and
+ * kept in step with it as it changes, until a person picks one.
+ */
+export type PageTypeSource = 'detected' | 'user';
+
/** A draft as the editor opens it. */
export interface ContentDraft {
id: string;
brandId: string;
title: string;
pageType: string | null;
+ pageTypeSource: PageTypeSource;
+ /** The brand's site type, which sets the page types on offer. */
+ siteType: SiteType;
method: DraftMethod;
status: DraftStatus;
bodyHtml: string;
diff --git a/web/src/lib/content/page-types.test.ts b/web/src/lib/content/page-types.test.ts
new file mode 100644
index 000000000..56f491151
--- /dev/null
+++ b/web/src/lib/content/page-types.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it } from 'vitest';
+import { PAGE_TYPES } from './drafts';
+import {
+ SITE_PAGE_TYPES,
+ SITE_TYPES,
+ detectPageType,
+ guessSiteType,
+ siteTypeOf,
+} from './page-types';
+
+describe('site types', () => {
+ it('offers each kind of site its own page types, all of them known', () => {
+ expect(SITE_PAGE_TYPES.b2b).toContain('feature_page');
+ expect(SITE_PAGE_TYPES.ecommerce).toContain('product_page');
+ expect(SITE_PAGE_TYPES.b2c).toContain('destination_page');
+ for (const site of SITE_TYPES) {
+ for (const type of SITE_PAGE_TYPES[site]) expect(PAGE_TYPES).toContain(type);
+ }
+ });
+
+ it('guesses a shop from Shopping mode first, then from the industry, else B2B', () => {
+ expect(guessSiteType({ industry: 'B2B Software (SaaS)', shoppingModeEnabled: true })).toBe(
+ 'ecommerce',
+ );
+ expect(guessSiteType({ industry: 'Fashion & Apparel' })).toBe('ecommerce');
+ expect(guessSiteType({ industry: 'Travel & Hospitality' })).toBe('b2c');
+ expect(guessSiteType({ industry: 'Technology' })).toBe('b2b');
+ expect(guessSiteType({ industry: 'Finance & Banking' })).toBe('b2b');
+ expect(guessSiteType({ industry: 'Food & Beverage' })).toBe('ecommerce');
+ expect(guessSiteType({ industry: null })).toBe('b2b');
+ });
+
+ it('keeps the site type the brand chose over the guess', () => {
+ expect(siteTypeOf({ siteType: 'b2c', industry: 'B2B Software (SaaS)' })).toBe('b2c');
+ expect(siteTypeOf({ siteType: null, industry: 'E-commerce & Retail' })).toBe('ecommerce');
+ expect(siteTypeOf({ siteType: 'nonsense', industry: 'Technology' })).toBe('b2b');
+ });
+});
+
+describe('detectPageType from the URL', () => {
+ it.each([
+ ['https://northwind.com/features/pipeline-forecasting', 'feature_page'],
+ ['/solutions/real-estate', 'solution_page'],
+ ['/for-agencies', 'solution_page'],
+ ['/blog/northwind-vs-hubspot', 'comparison'],
+ ['/hubspot-alternatives/', 'comparison'],
+ ['/integrations/slack', 'integration'],
+ ['/en/pricing', 'pricing'],
+ ['/guides/clean-crm-data', 'guide'],
+ ['/how-to-clean-crm-data', 'guide'],
+ ['/blog/crm-data-hygiene', 'blog_post'],
+ ['/blog/best-practices-for-pipeline-reviews', 'blog_post'],
+ ['/docs/api/auth', 'docs_faq'],
+ ['/product/analytics', 'feature_page'],
+ ])('B2B: %s → %s', (url, type) => {
+ expect(detectPageType({ url }, 'b2b')).toBe(type);
+ });
+
+ it.each([
+ ['https://shop.example/products/trail-runner-x?variant=2', 'product_page'],
+ ['/p/daypack-22l.html', 'product_page'],
+ ['/collections/ultralight-tents', 'category_page'],
+ ['/buying-guides/tents', 'buying_guide'],
+ ['/best-hiking-boots', 'best_of'],
+ ['/pages/returns-policy', 'policy'],
+ ['/help/shipping', 'policy'],
+ ['/blog/trail-season', 'blog_post'],
+ ])('e-commerce: %s → %s', (url, type) => {
+ expect(detectPageType({ url }, 'ecommerce')).toBe(type);
+ });
+
+ it.each([
+ ['/destinations/lisbon', 'destination_page'],
+ ['/itineraries/lisbon-with-kids', 'itinerary'],
+ ['/trips/3-days-in-porto', 'itinerary'],
+ ['/best-hotels-in-porto', 'best_of'],
+ ['/help/cancellation', 'help_faq'],
+ ['/guides/azores-in-winter', 'guide'],
+ ['/blog/best-time-to-visit-madeira', 'blog_post'],
+ ])('B2C: %s → %s', (url, type) => {
+ expect(detectPageType({ url }, 'b2c')).toBe(type);
+ });
+
+ it('gives a sign the site’s own type, or skips it when the site writes no such page', () => {
+ expect(detectPageType({ url: '/vs/hubspot' }, 'b2b')).toBe('comparison');
+ expect(detectPageType({ url: '/vs/hubspot' }, 'ecommerce')).toBe('best_of');
+ // A shop has no pricing page type: the URL tells nothing, the title does.
+ expect(
+ detectPageType({ url: '/pricing', title: 'Daypack 22L buying guide' }, 'ecommerce'),
+ ).toBe('buying_guide');
+ });
+
+ it('finds nothing in the home page or a plain path', () => {
+ expect(detectPageType({ url: 'https://northwind.com/' }, 'b2b')).toBeNull();
+ expect(detectPageType({ url: '/about-us' }, 'b2b')).toBeNull();
+ });
+});
+
+describe('detectPageType from the page', () => {
+ const jsonLd = (value: unknown) =>
+ `<p>Text</p><script type="application/ld+json">${JSON.stringify(value)}</script>`;
+
+ it('reads the schema in the JSON-LD, the most telling type first', () => {
+ const product = jsonLd({
+ '@context': 'https://schema.org',
+ '@graph': [{ '@type': 'FAQPage' }, { '@type': 'Product', name: 'Trail Runner X' }],
+ });
+ expect(detectPageType({ html: product }, 'ecommerce')).toBe('product_page');
+ expect(detectPageType({ html: jsonLd({ '@type': ['BlogPosting'] }) }, 'b2b')).toBe('blog_post');
+ expect(detectPageType({ html: jsonLd({ '@type': 'FAQPage' }) }, 'b2c')).toBe('help_faq');
+ expect(
+ detectPageType(
+ { html: jsonLd({ '@type': 'WebPage', mainEntity: { '@type': 'TouristDestination' } }) },
+ 'b2c',
+ ),
+ ).toBe('destination_page');
+ });
+
+ it('ignores JSON-LD that isn’t JSON', () => {
+ expect(
+ detectPageType({ html: '<script type="application/ld+json">{oops</script>' }, 'b2b'),
+ ).toBeNull();
+ });
+
+ it('prefers the URL to the schema, and the schema to the title', () => {
+ const article = jsonLd({ '@type': 'Article' });
+ expect(detectPageType({ url: '/pricing', html: article, title: 'How to' }, 'b2b')).toBe(
+ 'pricing',
+ );
+ expect(detectPageType({ html: article, title: 'Northwind vs HubSpot' }, 'b2b')).toBe(
+ 'blog_post',
+ );
+ });
+
+ it.each([
+ ['Northwind vs HubSpot', 'b2b', 'comparison'],
+ ['Best HubSpot alternatives', 'b2b', 'comparison'],
+ ['CRM for real estate teams', 'b2b', 'solution_page'],
+ ['Slack integration', 'b2b', 'integration'],
+ ['How to clean CRM data', 'b2b', 'guide'],
+ ['Pricing', 'b2b', 'pricing'],
+ ['The 7 best ultralight tents', 'ecommerce', 'best_of'],
+ ['Returns policy', 'ecommerce', 'policy'],
+ ['Tent buying guide', 'ecommerce', 'buying_guide'],
+ ['Lisbon with kids: 3-day plan', 'b2c', 'itinerary'],
+ ['Cancellation policy', 'b2c', 'help_faq'],
+ ] as const)('reads the title "%s" on a %s site as %s', (title, site, type) => {
+ expect(detectPageType({ title }, site)).toBe(type);
+ });
+
+ it('finds nothing when no sign tells', () => {
+ expect(detectPageType({ title: 'Pipeline forecasting' }, 'b2b')).toBeNull();
+ expect(detectPageType({ title: 'Best time to visit Lisbon' }, 'b2c')).toBeNull();
+ expect(detectPageType({}, 'b2b')).toBeNull();
+ });
+});
diff --git a/web/src/lib/content/page-types.ts b/web/src/lib/content/page-types.ts
new file mode 100644
index 000000000..9162011f6
--- /dev/null
+++ b/web/src/lib/content/page-types.ts
@@ -0,0 +1,237 @@
+import type { Industry } from '@/types';
+import type { PageType } from './drafts';
+import { jsonLdScripts } from './html-allowlist';
+
+/**
+ * Page types by kind of site, and a page's type found from the page itself
+ * (Content Editor CE-023, spec §4). A B2B SaaS site writes feature,
+ * comparison and pricing pages; a shop, product and category pages; a B2C
+ * site, destination and help pages. The brand's site type is set in its
+ * settings (brands.site_type, 00205), guessed until someone does.
+ */
+
+export const SITE_TYPES = ['b2b', 'ecommerce', 'b2c'] as const;
+export type SiteType = (typeof SITE_TYPES)[number];
+
+export function isSiteType(value: unknown): value is SiteType {
+ return typeof value === 'string' && (SITE_TYPES as readonly string[]).includes(value);
+}
+
+/** The page types each kind of site writes, in the order the editor offers them. */
+export const SITE_PAGE_TYPES: Record<SiteType, readonly PageType[]> = {
+ b2b: [
+ 'feature_page',
+ 'solution_page',
+ 'comparison',
+ 'integration',
+ 'pricing',
+ 'guide',
+ 'blog_post',
+ 'docs_faq',
+ ],
+ ecommerce: ['product_page', 'category_page', 'buying_guide', 'best_of', 'policy', 'blog_post'],
+ b2c: ['destination_page', 'itinerary', 'guide', 'best_of', 'help_faq', 'blog_post'],
+};
+
+/**
+ * Industries that point away from B2B. B2C's page types are a travel site's
+ * (destinations, itineraries), so only travel guesses B2C; shops and makers
+ * of things sold online guess e-commerce; the rest (software, finance,
+ * education…) write feature, pricing and FAQ pages, and guess B2B.
+ */
+const INDUSTRY_SITE_TYPES: Partial<Record<Industry, SiteType>> = {
+ 'E-commerce & Retail': 'ecommerce',
+ 'Fashion & Apparel': 'ecommerce',
+ 'Consumer Goods': 'ecommerce',
+ 'Food & Beverage': 'ecommerce',
+ Automotive: 'ecommerce',
+ 'Travel & Hospitality': 'b2c',
+};
+
+interface BrandSite {
+ siteType?: string | null;
+ industry?: string | null;
+ shoppingModeEnabled?: boolean;
+}
+
+/**
+ * A brand's site type before anyone picks one: a shop when Shopping mode is
+ * on, else by industry, and B2B when nothing says otherwise.
+ */
+export function guessSiteType(brand: BrandSite): SiteType {
+ if (brand.shoppingModeEnabled) return 'ecommerce';
+ return INDUSTRY_SITE_TYPES[brand.industry as Industry] ?? 'b2b';
+}
+
+/** The site type the brand chose, or the guess. */
+export function siteTypeOf(brand: BrandSite): SiteType {
+ return isSiteType(brand.siteType) ? brand.siteType : guessSiteType(brand);
+}
+
+/** What a sign means on each kind of site; a site it leaves out skips the sign. */
+type BySite = Partial<Record<SiteType, PageType>>;
+
+const ANY_SITE = (type: PageType): BySite => ({ b2b: type, ecommerce: type, b2c: type });
+const COMPARISON: BySite = { b2b: 'comparison', ecommerce: 'best_of', b2c: 'best_of' };
+const HELP: BySite = { b2b: 'docs_faq', ecommerce: 'policy', b2c: 'help_faq' };
+const GUIDE: BySite = { b2b: 'guide', ecommerce: 'buying_guide', b2c: 'guide' };
+
+/**
+ * URL paths, the most specific first: /blog/hubspot-vs-salesforce is a
+ * comparison before it is a blog post. Matched on the lowercased path with
+ * no trailing slash or file extension.
+ */
+const PATH_SIGNS: [RegExp, BySite][] = [
+ [/\/(pricing|plans|plans-and-pricing)(\/|$)/, { b2b: 'pricing' }],
+ [
+ /(^|[/-])(vs|versus)([/-]|$)|\/(compare|comparisons?)(\/|$)|[/-]alternatives?([/-]|$)/,
+ COMPARISON,
+ ],
+ [
+ /\/(shipping|delivery|returns?|refunds?|exchanges?|warranty|polic(y|ies)|terms|privacy|legal)([/-]|$)/,
+ HELP,
+ ],
+ [/\/(docs|documentation|help|help-center|support|faqs?|knowledge-base|kb)(\/|$)/, HELP],
+ [/\/(integrations?|apps|marketplace|connectors?)\//, { b2b: 'integration' }],
+ [/\/(buying-guides?|buyers?-guides?|how-to-choose)([/-]|$)/, GUIDE],
+ [/\/(the-)?(best(?!-(practices?|time|ways?)([/-]|$))|top-?\d+)([/-]|$)/, COMPARISON],
+ [/\/(features?|capabilities|platform)(\/|$)/, { b2b: 'feature_page' }],
+ [
+ /\/(solutions?|industries|industry|use-cases?|teams)(\/|$)|\/for-[a-z]/,
+ { b2b: 'solution_page' },
+ ],
+ [/\/(products?|p|dp|items?)\/[^/]+/, { b2b: 'feature_page', ecommerce: 'product_page' }],
+ [
+ /\/(collections?|categor(y|ies)|c|shop|catalog|departments?)(\/|$)/,
+ { ecommerce: 'category_page' },
+ ],
+ [/\/(itinerar(y|ies)|trips?|tours?)(\/|$)|\/\d+-days?-/, { b2c: 'itinerary' }],
+ [
+ /\/(destinations?|places|cities|regions|countries|locations?|hotels?|resorts?)(\/|$)/,
+ { b2c: 'destination_page' },
+ ],
+ [/\/services?(\/|$)/, { b2b: 'solution_page', b2c: 'destination_page' }],
+ [/\/(guides?|how-to|learn|academy|resources|tutorials?)([/-]|$)/, GUIDE],
+ [/\/(blog|news|articles?|posts?|insights|stories|magazine|journal)(\/|$)/, ANY_SITE('blog_post')],
+];
+
+/** Schema.org types in the page's JSON-LD, the most telling first. */
+const SCHEMA_SIGNS: [readonly string[], BySite][] = [
+ [
+ ['Product', 'ProductGroup', 'IndividualProduct'],
+ { b2b: 'feature_page', ecommerce: 'product_page' },
+ ],
+ [['SoftwareApplication', 'WebApplication', 'MobileApplication'], { b2b: 'feature_page' }],
+ [['TouristTrip'], { b2c: 'itinerary' }],
+ [
+ [
+ 'TouristDestination',
+ 'TouristAttraction',
+ 'City',
+ 'Place',
+ 'LodgingBusiness',
+ 'Hotel',
+ 'Resort',
+ ],
+ { b2c: 'destination_page' },
+ ],
+ [['Service'], { b2b: 'solution_page', b2c: 'destination_page' }],
+ [['CollectionPage', 'OfferCatalog'], { ecommerce: 'category_page' }],
+ [['HowTo'], GUIDE],
+ [['BlogPosting', 'Article', 'NewsArticle', 'TechArticle'], ANY_SITE('blog_post')],
+ [['FAQPage'], HELP],
+ [['ItemList'], COMPARISON],
+];
+
+/** Words in the title, for a page with no telling URL or schema. */
+const TITLE_SIGNS: [RegExp, BySite][] = [
+ [/\b(vs\.?|versus)\s|\balternatives?\b/i, COMPARISON],
+ [/\bpricing\b/i, { b2b: 'pricing' }],
+ [/\bpolic(y|ies)\b|\bfaqs?\b|\bfrequently asked\b/i, HELP],
+ [/\bbuying guide\b|\bhow to choose\b/i, GUIDE],
+ [/^(the\s+)?(\d+\s+)?best\b(?!\s+(time|way|practices?)\b)|\btop\s+\d+\b/i, COMPARISON],
+ [/\b\d+[-\s]days?\b|\bitinerar(y|ies)\b/i, { b2c: 'itinerary' }],
+ [/\bintegrations?\b|\bintegrates? with\b/i, { b2b: 'integration' }],
+ [
+ /\bfor\s+(\S+\s+){0,3}(teams|companies|businesses|agencies|startups|enterprises?)\b/i,
+ { b2b: 'solution_page' },
+ ],
+ [/\bhow to\b|\bguide\b|\btutorial\b|\bstep[-\s]by[-\s]step\b/i, GUIDE],
+];
+
+export interface PageSigns {
+ /** The page's address, or its path on the brand's site. */
+ url?: string | null;
+ /** Its title or first heading. */
+ title?: string | null;
+ /** Its HTML, read for JSON-LD. */
+ html?: string | null;
+}
+
+/**
+ * A page's type on this kind of site, from its URL first, then the schema in
+ * its JSON-LD, then its title; null when nothing tells. Only types the site
+ * writes come back: a shop's /vs/ page is a best-of, a SaaS site's a
+ * comparison.
+ */
+export function detectPageType(page: PageSigns, siteType: SiteType): PageType | null {
+ const path = page.url ? urlPath(page.url) : null;
+ const types = page.html ? schemaTypes(page.html) : null;
+ const title = page.title?.trim();
+ return (
+ (path ? firstSign(PATH_SIGNS, siteType, (pattern) => pattern.test(path)) : null) ??
+ (types?.size
+ ? firstSign(SCHEMA_SIGNS, siteType, (names) => names.some((name) => types.has(name)))
+ : null) ??
+ (title ? firstSign(TITLE_SIGNS, siteType, (pattern) => pattern.test(title)) : null)
+ );
+}
+
+function firstSign<T>(
+ signs: [T, BySite][],
+ siteType: SiteType,
+ matches: (sign: T) => boolean,
+): PageType | null {
+ for (const [sign, bySite] of signs) {
+ const type = bySite[siteType];
+ if (type && matches(sign)) return type;
+ }
+ return null;
+}
+
+/** "/Blog/Post.html?x=1" → "/blog/post"; null when it isn't a URL or path. */
+function urlPath(url: string): string | null {
+ try {
+ const path = new URL(url.trim(), 'https://site.invalid').pathname
+ .toLowerCase()
+ .replace(/\.(html?|php|aspx?)$/, '')
+ .replace(/\/+$/, '');
+ return path || '/';
+ } catch {
+ return null;
+ }
+}
+
+/** The @types in a page's JSON-LD, including @graph items and main entities. */
+function schemaTypes(html: string): Set<string> {
+ const types = new Set<string>();
+ const visit = (value: unknown) => {
+ if (Array.isArray(value)) return value.forEach(visit);
+ if (!value || typeof value !== 'object') return;
+ const item = value as Record<string, unknown>;
+ const type = item['@type'];
+ for (const name of Array.isArray(type) ? type : [type]) {
+ if (typeof name === 'string') types.add(name.replace(/^https?:\/\/schema\.org\//, ''));
+ }
+ visit(item['@graph']);
+ visit(item.mainEntity);
+ };
+ for (const { text } of jsonLdScripts(html)) {
+ try {
+ visit(JSON.parse(text));
+ } catch {
+ // Not JSON: nothing to read.
+ }
+ }
+ return types;
+}
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index 59a3e8958..b803e9fc9 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -25,6 +25,8 @@ export interface Brand {
language?: string;
trackingCode?: string;
shoppingModeEnabled: boolean;
+ /** b2b, ecommerce or b2c (Content Editor page types); unset = guessed (siteTypeOf). */
+ siteType?: string;
isActive: boolean;
domains: BrandDomain[];
createdAt: string;
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index f8eeb42ec..8a0bdb226 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -624,6 +624,7 @@ export type Database = {
organization_id: string
region: string | null
shopping_mode_enabled: boolean
+ site_type: string | null
slug: string
state: string | null
tracking_code: string
@@ -647,6 +648,7 @@ export type Database = {
organization_id: string
region?: string | null
shopping_mode_enabled?: boolean
+ site_type?: string | null
slug: string
state?: string | null
tracking_code?: string
@@ -670,6 +672,7 @@ export type Database = {
organization_id?: string
region?: string | null
shopping_mode_enabled?: boolean
+ site_type?: string | null
slug?: string
state?: string | null
tracking_code?: string
@@ -832,6 +835,7 @@ export type Database = {
id: string
method: string
page_type: string | null
+ page_type_source: string
score_after: number | null
score_before: number | null
status: string
@@ -847,6 +851,7 @@ export type Database = {
id?: string
method?: string
page_type?: string | null
+ page_type_source?: string
score_after?: number | null
score_before?: number | null
status?: string
@@ -862,6 +867,7 @@ export type Database = {
id?: string
method?: string
page_type?: string | null
+ page_type_source?: string
score_after?: number | null
score_before?: number | null
status?: string